diff --git a/third-party/fmt/CMakeLists.txt b/third-party/fmt/CMakeLists.txt index 4b928ae35c..00c059086b 100644 --- a/third-party/fmt/CMakeLists.txt +++ b/third-party/fmt/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.8...3.26) +cmake_minimum_required(VERSION 3.8...3.28) # Fallback for using newer policies on CMake <3.12. if (${CMAKE_VERSION} VERSION_LESS 3.12) @@ -27,7 +27,13 @@ endfunction() # DEPRECATED! Should be merged into add_module_library. function(enable_module target) if (MSVC) - set(BMI ${CMAKE_CURRENT_BINARY_DIR}/${target}.ifc) + if(CMAKE_GENERATOR STREQUAL "Ninja") + # Ninja dyndep expects the .ifc output to be located in a specific relative path + file(RELATIVE_PATH BMI_DIR "${CMAKE_BINARY_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${target}.dir") + else() + set(BMI_DIR "${CMAKE_CURRENT_BINARY_DIR}") + endif() + file(TO_NATIVE_PATH "${BMI_DIR}/${target}.ifc" BMI) target_compile_options(${target} PRIVATE /interface /ifcOutput ${BMI} INTERFACE /reference fmt=${BMI}) @@ -36,6 +42,12 @@ function(enable_module target) endif () endfunction() +set(FMT_USE_CMAKE_MODULES FALSE) +if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.28 AND + CMAKE_GENERATOR STREQUAL "Ninja") + set(FMT_USE_CMAKE_MODULES TRUE) +endif () + # Adds a library compiled with C++20 module support. # `enabled` is a CMake variables that specifies if modules are enabled. # If modules are disabled `add_module_library` falls back to creating a @@ -53,6 +65,7 @@ function(add_module_library name) if (NOT ${${AML_IF}}) # Create a non-modular library. target_sources(${name} PRIVATE ${AML_FALLBACK}) + set_target_properties(${name} PROPERTIES CXX_SCAN_FOR_MODULES OFF) return() endif () @@ -62,48 +75,53 @@ function(add_module_library name) target_compile_options(${name} PUBLIC -fmodules-ts) endif () - # `std` is affected by CMake options and may be higher than C++20. - get_target_property(std ${name} CXX_STANDARD) + if (FMT_USE_CMAKE_MODULES) + target_sources(${name} PUBLIC FILE_SET fmt TYPE CXX_MODULES + FILES ${sources}) + else() + # `std` is affected by CMake options and may be higher than C++20. + get_target_property(std ${name} CXX_STANDARD) - if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(pcms) - foreach (src ${sources}) - get_filename_component(pcm ${src} NAME_WE) - set(pcm ${pcm}.pcm) + if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(pcms) + foreach (src ${sources}) + get_filename_component(pcm ${src} NAME_WE) + set(pcm ${pcm}.pcm) - # Propagate -fmodule-file=*.pcm to targets that link with this library. - target_compile_options( - ${name} PUBLIC -fmodule-file=${CMAKE_CURRENT_BINARY_DIR}/${pcm}) + # Propagate -fmodule-file=*.pcm to targets that link with this library. + target_compile_options( + ${name} PUBLIC -fmodule-file=${CMAKE_CURRENT_BINARY_DIR}/${pcm}) - # Use an absolute path to prevent target_link_libraries prepending -l - # to it. - set(pcms ${pcms} ${CMAKE_CURRENT_BINARY_DIR}/${pcm}) - add_custom_command( - OUTPUT ${pcm} - COMMAND ${CMAKE_CXX_COMPILER} - -std=c++${std} -x c++-module --precompile -c - -o ${pcm} ${CMAKE_CURRENT_SOURCE_DIR}/${src} - "-I$,;-I>" - # Required by the -I generator expression above. - COMMAND_EXPAND_LISTS - DEPENDS ${src}) - endforeach () + # Use an absolute path to prevent target_link_libraries prepending -l + # to it. + set(pcms ${pcms} ${CMAKE_CURRENT_BINARY_DIR}/${pcm}) + add_custom_command( + OUTPUT ${pcm} + COMMAND ${CMAKE_CXX_COMPILER} + -std=c++${std} -x c++-module --precompile -c + -o ${pcm} ${CMAKE_CURRENT_SOURCE_DIR}/${src} + "-I$,;-I>" + # Required by the -I generator expression above. + COMMAND_EXPAND_LISTS + DEPENDS ${src}) + endforeach () - # Add .pcm files as sources to make sure they are built before the library. - set(sources) - foreach (pcm ${pcms}) - get_filename_component(pcm_we ${pcm} NAME_WE) - set(obj ${pcm_we}.o) - # Use an absolute path to prevent target_link_libraries prepending -l. - set(sources ${sources} ${pcm} ${CMAKE_CURRENT_BINARY_DIR}/${obj}) - add_custom_command( - OUTPUT ${obj} - COMMAND ${CMAKE_CXX_COMPILER} $ - -c -o ${obj} ${pcm} - DEPENDS ${pcm}) - endforeach () - endif () - target_sources(${name} PRIVATE ${sources}) + # Add .pcm files as sources to make sure they are built before the library. + set(sources) + foreach (pcm ${pcms}) + get_filename_component(pcm_we ${pcm} NAME_WE) + set(obj ${pcm_we}.o) + # Use an absolute path to prevent target_link_libraries prepending -l. + set(sources ${sources} ${pcm} ${CMAKE_CURRENT_BINARY_DIR}/${obj}) + add_custom_command( + OUTPUT ${obj} + COMMAND ${CMAKE_CXX_COMPILER} $ + -c -o ${obj} ${pcm} + DEPENDS ${pcm}) + endforeach () + endif () + target_sources(${name} PRIVATE ${sources}) + endif() endfunction() include(CMakeParseArguments) @@ -150,9 +168,10 @@ option(FMT_INSTALL "Generate the install target." ON) option(FMT_TEST "Generate the test target." ${FMT_MASTER_PROJECT}) option(FMT_FUZZ "Generate the fuzz target." OFF) option(FMT_CUDA_TEST "Generate the cuda-test target." OFF) -option(FMT_OS "Include core requiring OS (Windows/Posix) " ON) +option(FMT_OS "Include OS-specific APIs." ON) option(FMT_MODULE "Build a module instead of a traditional library." OFF) option(FMT_SYSTEM_HEADERS "Expose headers with marking them as system." OFF) +option(FMT_UNICODE "Enable Unicode support." ON) if (FMT_TEST AND FMT_MODULE) # The tests require {fmt} to be compiled as traditional library @@ -167,10 +186,10 @@ if (CMAKE_SYSTEM_NAME STREQUAL "MSDOS") message(STATUS "MSDOS is incompatible with gtest") endif () -# Get version from core.h -file(READ include/fmt/core.h core_h) -if (NOT core_h MATCHES "FMT_VERSION ([0-9]+)([0-9][0-9])([0-9][0-9])") - message(FATAL_ERROR "Cannot get FMT_VERSION from core.h.") +# Get version from base.h +file(READ include/fmt/base.h base_h) +if (NOT base_h MATCHES "FMT_VERSION ([0-9]+)([0-9][0-9])([0-9][0-9])") + message(FATAL_ERROR "Cannot get FMT_VERSION from base.h.") endif () # Use math to skip leading zeros if any. math(EXPR CPACK_PACKAGE_VERSION_MAJOR ${CMAKE_MATCH_1}) @@ -178,7 +197,7 @@ math(EXPR CPACK_PACKAGE_VERSION_MINOR ${CMAKE_MATCH_2}) math(EXPR CPACK_PACKAGE_VERSION_PATCH ${CMAKE_MATCH_3}) join(FMT_VERSION ${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}. ${CPACK_PACKAGE_VERSION_PATCH}) -message(STATUS "Version: ${FMT_VERSION}") +message(STATUS "{fmt} version: ${FMT_VERSION}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") @@ -225,7 +244,13 @@ if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") endif () if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.0) set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wshift-overflow=2 - -Wnull-dereference -Wduplicated-cond) + -Wduplicated-cond) + # Workaround for GCC regression + # [12/13/14/15 regression] New (since gcc 12) false positive null-dereference in vector.resize + # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108860 + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.0) + set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wnull-dereference) + endif () endif () set(WERROR_FLAG -Werror) endif () @@ -274,13 +299,11 @@ function(add_headers VAR) endfunction() # Define the fmt library, its includes and the needed defines. -add_headers(FMT_HEADERS args.h chrono.h color.h compile.h core.h format.h +set(FMT_HEADERS) +add_headers(FMT_HEADERS args.h base.h chrono.h color.h compile.h core.h format.h format-inl.h os.h ostream.h printf.h ranges.h std.h xchar.h) set(FMT_SOURCES src/format.cc) -if (FMT_OS) - set(FMT_SOURCES ${FMT_SOURCES} src/os.cc) -endif () add_module_library(fmt src/fmt.cc FALLBACK ${FMT_SOURCES} ${FMT_HEADERS} README.md ChangeLog.md @@ -288,6 +311,10 @@ add_module_library(fmt src/fmt.cc FALLBACK add_library(fmt::fmt ALIAS fmt) if (FMT_MODULE) enable_module(fmt) +elseif (FMT_OS) + target_sources(fmt PRIVATE src/os.cc) +else() + target_compile_definitions(fmt PRIVATE FMT_OS=0) endif () if (FMT_WERROR) @@ -303,7 +330,7 @@ else () message(WARNING "Feature cxx_std_11 is unknown for the CXX compiler") endif () -target_include_directories(fmt ${FMT_SYSTEM_HEADERS_ATTRIBUTE} PUBLIC +target_include_directories(fmt ${FMT_SYSTEM_HEADERS_ATTRIBUTE} BEFORE PUBLIC $ $) @@ -339,11 +366,21 @@ endif () add_library(fmt-header-only INTERFACE) add_library(fmt::fmt-header-only ALIAS fmt-header-only) +if (NOT MSVC) + # Unicode is always supported on compilers other than MSVC. +elseif (FMT_UNICODE) + # Unicode support requires compiling with /utf-8. + target_compile_options(fmt PUBLIC $<$,$>:/utf-8>) + target_compile_options(fmt-header-only INTERFACE $<$,$>:/utf-8>) +else () + target_compile_definitions(fmt PUBLIC FMT_UNICODE=0) +endif () + target_compile_definitions(fmt-header-only INTERFACE FMT_HEADER_ONLY=1) target_compile_features(fmt-header-only INTERFACE cxx_std_11) target_include_directories(fmt-header-only - ${FMT_SYSTEM_HEADERS_ATTRIBUTE} INTERFACE + ${FMT_SYSTEM_HEADERS_ATTRIBUTE} BEFORE INTERFACE $ $) @@ -388,12 +425,20 @@ if (FMT_INSTALL) set(INSTALL_TARGETS fmt fmt-header-only) + set(INSTALL_FILE_SET) + if (FMT_USE_CMAKE_MODULES) + set(INSTALL_FILE_SET FILE_SET fmt DESTINATION "${FMT_INC_DIR}/fmt") + endif() + # Install the library and headers. - install(TARGETS ${INSTALL_TARGETS} EXPORT ${targets_export_name} + install(TARGETS ${INSTALL_TARGETS} + COMPONENT fmt-core + EXPORT ${targets_export_name} LIBRARY DESTINATION ${FMT_LIB_DIR} ARCHIVE DESTINATION ${FMT_LIB_DIR} PUBLIC_HEADER DESTINATION "${FMT_INC_DIR}/fmt" - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ${INSTALL_FILE_SET}) # Use a namespace because CMake provides better diagnostics for namespaced # imported targets. @@ -401,17 +446,56 @@ if (FMT_INSTALL) FILE ${PROJECT_BINARY_DIR}/${targets_export_name}.cmake) # Install version, config and target files. - install( - FILES ${project_config} ${version_config} - DESTINATION ${FMT_CMAKE_DIR}) + install(FILES ${project_config} ${version_config} + DESTINATION ${FMT_CMAKE_DIR} + COMPONENT fmt-core) install(EXPORT ${targets_export_name} DESTINATION ${FMT_CMAKE_DIR} - NAMESPACE fmt::) + NAMESPACE fmt:: + COMPONENT fmt-core) - install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}") + install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}" + COMPONENT fmt-core) endif () +function(add_doc_target) + find_program(DOXYGEN doxygen + PATHS "$ENV{ProgramFiles}/doxygen/bin" + "$ENV{ProgramFiles\(x86\)}/doxygen/bin") + if (NOT DOXYGEN) + message(STATUS "Target 'doc' disabled because doxygen not found") + return () + endif () + + find_program(MKDOCS mkdocs) + if (NOT MKDOCS) + message(STATUS "Target 'doc' disabled because mkdocs not found") + return () + endif () + + set(sources ) + foreach (source api.md index.md syntax.md get-started.md fmt.css fmt.js) + set(sources ${sources} doc/${source}) + endforeach() + + add_custom_target( + doc + COMMAND + ${CMAKE_COMMAND} + -E env PYTHONPATH=${CMAKE_CURRENT_SOURCE_DIR}/support/python + ${MKDOCS} build -f ${CMAKE_CURRENT_SOURCE_DIR}/support/mkdocs.yml + # MkDocs requires the site dir to be outside of the doc dir. + --site-dir ${CMAKE_CURRENT_BINARY_DIR}/doc-html + --no-directory-urls + SOURCES ${sources}) + + include(GNUInstallDirs) + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doc-html/ + DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/doc/fmt + COMPONENT fmt-doc OPTIONAL) +endfunction() + if (FMT_DOC) - add_subdirectory(doc) + add_doc_target() endif () if (FMT_TEST) @@ -441,8 +525,7 @@ if (FMT_MASTER_PROJECT AND EXISTS ${gitignore}) string(REPLACE "*" ".*" line "${line}") set(ignored_files ${ignored_files} "${line}$" "${line}/") endforeach () - set(ignored_files ${ignored_files} - /.git /breathe /format-benchmark sphinx/ .buildinfo .doctrees) + set(ignored_files ${ignored_files} /.git /build/doxyxml .vagrant) set(CPACK_SOURCE_GENERATOR ZIP) set(CPACK_SOURCE_IGNORE_FILES ${ignored_files}) diff --git a/third-party/fmt/ChangeLog.md b/third-party/fmt/ChangeLog.md index 515f9fdc1d..99877fa56b 100644 --- a/third-party/fmt/ChangeLog.md +++ b/third-party/fmt/ChangeLog.md @@ -1,5533 +1,2950 @@ -# 10.2.1 - 2024-01-03 +# 11.1.4 - 2025-02-26 -- Fixed ABI compatibility with earlier 10.x versions - (https://github.com/fmtlib/fmt/pull/3786). Thanks @saraedum. +- Fixed ABI compatibility with earlier 11.x versions on Windows + (https://github.com/fmtlib/fmt/issues/4359). + +- Improved the logic of switching between fixed and exponential format for + `float` (https://github.com/fmtlib/fmt/issues/3649). + +- Moved `is_compiled_string` to the public API + (https://github.com/fmtlib/fmt/issues/4342). Thanks @SwooshyCueb. + +- Simplified implementation of `operator""_cf` + (https://github.com/fmtlib/fmt/pull/4349). Thanks @LocalSpook. + +- Fixed `__builtin_strlen` detection (https://github.com/fmtlib/fmt/pull/4329). + Thanks @LocalSpook. + +- Fixed handling of BMI paths with the Ninja generator + (https://github.com/fmtlib/fmt/pull/4344). Thanks @tkhyn. + +- Fixed gcc 8.3 compile errors (https://github.com/fmtlib/fmt/issues/4331, + https://github.com/fmtlib/fmt/pull/4336). Thanks @sergiud. + +- Fixed a bogus MSVC warning (https://github.com/fmtlib/fmt/pull/4356). + Thanks @dinomight. + +# 11.1.3 - 2025-01-25 + +- Fixed compilation on GCC 9.4 (https://github.com/fmtlib/fmt/issues/4313). + +- Worked around an internal compiler error when using C++20 modules with GCC + 14.2 and earlier (https://github.com/fmtlib/fmt/issues/4295). + +- Worked around a bug in GCC 6 (https://github.com/fmtlib/fmt/issues/4318). + +- Fixed an issue caused by instantiating `formatter` + (https://github.com/fmtlib/fmt/issues/4303, + https://github.com/fmtlib/fmt/pull/4325). Thanks @timsong-cpp. + +- Fixed formatting into `std::ostreambuf_iterator` when using format string + compilation (https://github.com/fmtlib/fmt/issues/4309, + https://github.com/fmtlib/fmt/pull/4312). Thanks @phprus. + +- Restored a constraint on the map formatter so that it correctly reports as + unformattable when the element is (https://github.com/fmtlib/fmt/pull/4326). + Thanks @timsong-cpp. + +- Reduced the size of format specs (https://github.com/fmtlib/fmt/issues/4298). + +- Readded `args()` to `fmt::format_context` + (https://github.com/fmtlib/fmt/issues/4307, + https://github.com/fmtlib/fmt/pull/4310). Thanks @Erroneous1. + +- Fixed a bogus MSVC warning (https://github.com/fmtlib/fmt/issues/4314, + https://github.com/fmtlib/fmt/pull/4322). Thanks @ZehMatt. + +- Fixed a pedantic mode error in the CMake config + (https://github.com/fmtlib/fmt/pull/4327). Thanks @rlalik. + +# 11.1.2 - 2025-01-12 + +- Fixed ABI compatibility with earlier 11.x versions + (https://github.com/fmtlib/fmt/issues/4292). + +- Added `wchar_t` support to the `std::bitset` formatter + (https://github.com/fmtlib/fmt/issues/4285, + https://github.com/fmtlib/fmt/pull/4286, + https://github.com/fmtlib/fmt/issues/4289, + https://github.com/fmtlib/fmt/pull/4290). Thanks @phprus. + +- Prefixed CMake components with `fmt-` to simplify usage of {fmt} via + `add_subdirectory` (https://github.com/fmtlib/fmt/issues/4283). + +- Updated docs for meson (https://github.com/fmtlib/fmt/pull/4291). + Thanks @trim21. + +- Fixed a compilation error in chrono on nvcc + (https://github.com/fmtlib/fmt/issues/4297, + https://github.com/fmtlib/fmt/pull/4301). Thanks @breyerml. + +- Fixed various warnings + (https://github.com/fmtlib/fmt/pull/4288, + https://github.com/fmtlib/fmt/pull/4299). Thanks @GamesTrap and @edo9300. + +# 11.1.1 - 2024-12-27 + +- Fixed ABI compatibility with earlier 11.x versions + (https://github.com/fmtlib/fmt/issues/4278). + +- Defined CMake components (`core` and `doc`) to allow docs to be installed + separately (https://github.com/fmtlib/fmt/pull/4276). + Thanks @carlsmedstad. + +# 11.1.0 - 2024-12-25 + +- Improved C++20 module support + (https://github.com/fmtlib/fmt/issues/4081, + https://github.com/fmtlib/fmt/pull/4083, + https://github.com/fmtlib/fmt/pull/4084, + https://github.com/fmtlib/fmt/pull/4152, + https://github.com/fmtlib/fmt/issues/4153, + https://github.com/fmtlib/fmt/pull/4169, + https://github.com/fmtlib/fmt/issues/4190, + https://github.com/fmtlib/fmt/issues/4234, + https://github.com/fmtlib/fmt/pull/4239). + Thanks @kamrann and @Arghnews. + +- Reduced debug (unoptimized) binary code size and the number of template + instantiations when passing formatting arguments. For example, unoptimized + binary code size for `fmt::print("{}", 42)` was reduced by ~40% on GCC and + ~60% on clang (x86-64). + + GCC: + - Before: 161 instructions of which 105 are in reusable functions + ([godbolt](https://www.godbolt.org/z/s9bGoo4ze)). + - After: 116 instructions of which 60 are in reusable functions + ([godbolt](https://www.godbolt.org/z/r7GGGxMs6)). + + Clang: + - Before: 310 instructions of which 251 are in reusable functions + ([godbolt](https://www.godbolt.org/z/Ts88b7M9o)). + - After: 194 instructions of which 135 are in reusable functions + ([godbolt](https://www.godbolt.org/z/vcrjP8ceW)). + +- Added an experimental `fmt::writer` API that can be used for writing to + different destinations such as files or strings + (https://github.com/fmtlib/fmt/issues/2354). + For example ([godbolt](https://www.godbolt.org/z/rWoKfbP7e)): + + ```c++ + #include + + void write_text(fmt::writer w) { + w.print("The answer is {}.", 42); + } + + int main() { + // Write to FILE. + write_text(stdout); + + // Write to fmt::ostream. + auto f = fmt::output_file("myfile"); + write_text(f); + + // Write to std::string. + auto sb = fmt::string_buffer(); + write_text(sb); + std::string s = sb.str(); + } + ``` + +- Added width and alignment support to the formatter of `std::error_code`. + +- Made `std::expected` formattable + (https://github.com/fmtlib/fmt/issues/4145, + https://github.com/fmtlib/fmt/pull/4148). + For example ([godbolt](https://www.godbolt.org/z/hrj5c6G86)): + + ```c++ + fmt::print("{}", std::expected()); + ``` + + prints + + ``` + expected() + ``` + + Thanks @phprus. + +- Made `fmt::is_formattable` SFINAE-friendly + (https://github.com/fmtlib/fmt/issues/4147). + +- Added support for `_BitInt` formatting when using clang + (https://github.com/fmtlib/fmt/issues/4007, + https://github.com/fmtlib/fmt/pull/4072, + https://github.com/fmtlib/fmt/issues/4140, + https://github.com/fmtlib/fmt/issues/4173, + https://github.com/fmtlib/fmt/pull/4176). + For example ([godbolt](https://www.godbolt.org/z/KWjbWec5z)): + + ```c++ + using int42 = _BitInt(42); + fmt::print("{}", int42(100)); + ``` + + Thanks @Arghnews. + +- Added the `n` specifier for tuples and pairs + (https://github.com/fmtlib/fmt/pull/4107). Thanks @someonewithpc. + +- Added support for tuple-like types to `fmt::join` + (https://github.com/fmtlib/fmt/issues/4226, + https://github.com/fmtlib/fmt/pull/4230). Thanks @phprus. + +- Made more types formattable at compile time + (https://github.com/fmtlib/fmt/pull/4127). Thanks @AnthonyVH. + +- Implemented a more efficient compile-time `fmt::formatted_size` + (https://github.com/fmtlib/fmt/issues/4102, + https://github.com/fmtlib/fmt/pull/4103). Thanks @phprus. + +- Fixed compile-time formatting of some string types + (https://github.com/fmtlib/fmt/pull/4065). Thanks @torshepherd. + +- Made compiled version of `fmt::format_to` work with + `std::back_insert_iterator>` + (https://github.com/fmtlib/fmt/issues/4206, + https://github.com/fmtlib/fmt/pull/4211). Thanks @phprus. + +- Added a formatter for `std::reference_wrapper` + (https://github.com/fmtlib/fmt/pull/4163, + https://github.com/fmtlib/fmt/pull/4164). Thanks @yfeldblum and @phprus. + +- Added experimental padding support (glibc `strftime` extension) to `%m`, `%j` + and `%Y` (https://github.com/fmtlib/fmt/pull/4161). Thanks @KKhanhH. + +- Made microseconds formatted as `us` instead of `µs` if the Unicode support is + disabled (https://github.com/fmtlib/fmt/issues/4088). + +- Fixed an unreleased regression in transcoding of surrogate pairs + (https://github.com/fmtlib/fmt/issues/4094, + https://github.com/fmtlib/fmt/pull/4095). Thanks @phprus. + +- Made `fmt::appender` satisfy `std::output_iterator` concept + (https://github.com/fmtlib/fmt/issues/4092, + https://github.com/fmtlib/fmt/pull/4093). Thanks @phprus. + +- Made `std::iterator_traits` standard-conforming + (https://github.com/fmtlib/fmt/pull/4185). Thanks @CaseyCarter. + +- Made it easier to reuse `fmt::formatter` for types with + an implicit conversion to `std::string_view` + (https://github.com/fmtlib/fmt/issues/4036, + https://github.com/fmtlib/fmt/pull/4055). Thanks @Arghnews. + +- Made it possible to disable `` use via `FMT_CPP_LIB_FILESYSTEM` + for compatibility with some video game console SDKs, e.g. Nintendo Switch SDK + (https://github.com/fmtlib/fmt/issues/4257, + https://github.com/fmtlib/fmt/pull/4258, + https://github.com/fmtlib/fmt/pull/4259). Thanks @W4RH4WK and @phprus. + +- Fixed compatibility with platforms that use 80-bit `long double` + (https://github.com/fmtlib/fmt/issues/4245, + https://github.com/fmtlib/fmt/pull/4246). Thanks @jsirpoma. + +- Added support for UTF-32 code units greater than `0xFFFF` in fill + (https://github.com/fmtlib/fmt/issues/4201). + +- Fixed handling of legacy encodings on Windows with GCC + (https://github.com/fmtlib/fmt/issues/4162). + +- Made `fmt::to_string` take `fmt::basic_memory_buffer` by const reference + (https://github.com/fmtlib/fmt/issues/4261, + https://github.com/fmtlib/fmt/pull/4262). Thanks @sascha-devel. + +- Added `fmt::dynamic_format_arg_store::size` + (https://github.com/fmtlib/fmt/pull/4270). Thanks @hannes-harnisch. + +- Removed the ability to control locale usage via an undocumented + `FMT_STATIC_THOUSANDS_SEPARATOR` in favor of `FMT_USE_LOCALE`. + +- Renamed `FMT_EXCEPTIONS` to `FMT_USE_EXCEPTIONS` for consistency with other + similar macros. + +- Improved include directory ordering to reduce the chance of including + incorrect headers when using multiple versions of {fmt} + (https://github.com/fmtlib/fmt/pull/4116). Thanks @cdzhan. + +- Made it possible to compile a subset of {fmt} without the C++ runtime. + +- Improved documentation and README + (https://github.com/fmtlib/fmt/pull/4066, + https://github.com/fmtlib/fmt/issues/4117, + https://github.com/fmtlib/fmt/issues/4203, + https://github.com/fmtlib/fmt/pull/4235). Thanks @zyctree and @nikola-sh. + +- Improved the documentation generator (https://github.com/fmtlib/fmt/pull/4110, + https://github.com/fmtlib/fmt/pull/4115). Thanks @rturrado. + +- Improved CI (https://github.com/fmtlib/fmt/pull/4155, + https://github.com/fmtlib/fmt/pull/4151). Thanks @phprus. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/2708, + https://github.com/fmtlib/fmt/issues/4091, + https://github.com/fmtlib/fmt/issues/4109, + https://github.com/fmtlib/fmt/issues/4113, + https://github.com/fmtlib/fmt/issues/4125, + https://github.com/fmtlib/fmt/issues/4129, + https://github.com/fmtlib/fmt/pull/4130, + https://github.com/fmtlib/fmt/pull/4131, + https://github.com/fmtlib/fmt/pull/4132, + https://github.com/fmtlib/fmt/issues/4133, + https://github.com/fmtlib/fmt/issues/4144, + https://github.com/fmtlib/fmt/issues/4150, + https://github.com/fmtlib/fmt/issues/4158, + https://github.com/fmtlib/fmt/pull/4159, + https://github.com/fmtlib/fmt/issues/4160, + https://github.com/fmtlib/fmt/pull/4170, + https://github.com/fmtlib/fmt/issues/4177, + https://github.com/fmtlib/fmt/pull/4187, + https://github.com/fmtlib/fmt/pull/4188, + https://github.com/fmtlib/fmt/pull/4194, + https://github.com/fmtlib/fmt/pull/4200, + https://github.com/fmtlib/fmt/issues/4205, + https://github.com/fmtlib/fmt/issues/4207, + https://github.com/fmtlib/fmt/pull/4208, + https://github.com/fmtlib/fmt/pull/4210, + https://github.com/fmtlib/fmt/issues/4220, + https://github.com/fmtlib/fmt/issues/4231, + https://github.com/fmtlib/fmt/issues/4232, + https://github.com/fmtlib/fmt/pull/4233, + https://github.com/fmtlib/fmt/pull/4236, + https://github.com/fmtlib/fmt/pull/4267, + https://github.com/fmtlib/fmt/pull/4271). + Thanks @torsten48, @Arghnews, @tinfoilboy, @aminya, @Ottani, @zeroomega, + @c4v4, @kongy, @vinayyadav3016, @sergio-nsk, @phprus and @YexuanXiao. + +# 11.0.2 - 2024-07-20 + +- Fixed compatibility with non-POSIX systems + (https://github.com/fmtlib/fmt/issues/4054, + https://github.com/fmtlib/fmt/issues/4060). + +- Fixed performance regressions when using `std::back_insert_iterator` with + `fmt::format_to` (https://github.com/fmtlib/fmt/issues/4070). + +- Fixed handling of `std::generator` and move-only iterators + (https://github.com/fmtlib/fmt/issues/4053, + https://github.com/fmtlib/fmt/pull/4057). Thanks @Arghnews. + +- Made `formatter::parse` work with types convertible to + `std::string_view` (https://github.com/fmtlib/fmt/issues/4036, + https://github.com/fmtlib/fmt/pull/4055). Thanks @Arghnews. + +- Made `volatile void*` formattable + (https://github.com/fmtlib/fmt/issues/4049, + https://github.com/fmtlib/fmt/pull/4056). Thanks @Arghnews. + +- Made `Glib::ustring` not be confused with `std::string` + (https://github.com/fmtlib/fmt/issues/4052). + +- Made `fmt::context` iterator compatible with STL algorithms that rely on + iterator category (https://github.com/fmtlib/fmt/issues/4079). + +# 11.0.1 - 2024-07-05 + +- Fixed version number in the inline namespace + (https://github.com/fmtlib/fmt/issues/4047). + +- Fixed disabling Unicode support via CMake + (https://github.com/fmtlib/fmt/issues/4051). + +- Fixed deprecated `visit_format_arg` (https://github.com/fmtlib/fmt/pull/4043). + Thanks @nebkat. + +- Fixed handling of a sign and improved the `std::complex` formater + (https://github.com/fmtlib/fmt/pull/4034, + https://github.com/fmtlib/fmt/pull/4050). Thanks @tesch1 and @phprus. + +- Fixed ADL issues in `fmt::printf` when using C++20 + (https://github.com/fmtlib/fmt/pull/4042). Thanks @toge. + +- Removed a redundant check in the formatter for `std::expected` + (https://github.com/fmtlib/fmt/pull/4040). Thanks @phprus. + +# 11.0.0 - 2024-07-01 + +- Added `fmt/base.h` which provides a subset of the API with minimal include + dependencies and enough functionality to replace all uses of the `printf` + family of functions. This brings the compile time of code using {fmt} much + closer to the equivalent `printf` code as shown on the following benchmark + that compiles 100 source files: + + | Method | Compile Time (s) | + |--------------|------------------| + | printf | 1.6 | + | IOStreams | 25.9 | + | fmt 10.x | 19.0 | + | fmt 11.0 | 4.8 | + | tinyformat | 29.1 | + | Boost Format | 55.0 | + + This gives almost 4x improvement in build speed compared to version 10. + Note that the benchmark is purely formatting code and includes. In real + projects the difference from `printf` will be smaller partly because common + standard headers will be included in almost any translation unit (TU) anyway. + In particular, in every case except `printf` above ~1s is spent in total on + including `` in all TUs. + +- Optimized includes in other headers such as `fmt/format.h` which is now + roughly equivalent to the old `fmt/core.h` in terms of build speed. + +- Migrated the documentation at https://fmt.dev/ from Sphinx to MkDocs. + +- Improved C++20 module support + (https://github.com/fmtlib/fmt/issues/3990, + https://github.com/fmtlib/fmt/pull/3991, + https://github.com/fmtlib/fmt/issues/3993, + https://github.com/fmtlib/fmt/pull/3994, + https://github.com/fmtlib/fmt/pull/3997, + https://github.com/fmtlib/fmt/pull/3998, + https://github.com/fmtlib/fmt/pull/4004, + https://github.com/fmtlib/fmt/pull/4005, + https://github.com/fmtlib/fmt/pull/4006, + https://github.com/fmtlib/fmt/pull/4013, + https://github.com/fmtlib/fmt/pull/4027, + https://github.com/fmtlib/fmt/pull/4029). In particular, native CMake support + for modules is now used if available. Thanks @yujincheng08 and @matt77hias. + +- Added an option to replace standard includes with `import std` enabled via + the `FMT_IMPORT_STD` macro (https://github.com/fmtlib/fmt/issues/3921, + https://github.com/fmtlib/fmt/pull/3928). Thanks @matt77hias. + +- Exported `fmt::range_format`, `fmt::range_format_kind` and + `fmt::compiled_string` from the `fmt` module + (https://github.com/fmtlib/fmt/pull/3970, + https://github.com/fmtlib/fmt/pull/3999). + Thanks @matt77hias and @yujincheng08. + +- Improved integration with stdio in `fmt::print`, enabling direct writes + into a C stream buffer in common cases. This may give significant + performance improvements ranging from tens of percent to [2x]( + https://stackoverflow.com/a/78457454/471164) and eliminates dynamic memory + allocations on the buffer level. It is currently enabled for built-in and + string types with wider availability coming up in future releases. + + For example, it gives ~24% improvement on a [simple benchmark]( + https://isocpp.org/files/papers/P3107R5.html#perf) compiled with Apple clang + version 15.0.0 (clang-1500.1.0.2.5) and run on macOS 14.2.1: + + ``` + ------------------------------------------------------- + Benchmark Time CPU Iterations + ------------------------------------------------------- + printf 81.8 ns 81.5 ns 8496899 + fmt::print (10.x) 63.8 ns 61.9 ns 11524151 + fmt::print (11.0) 51.3 ns 51.0 ns 13846580 + ``` + +- Improved safety of `fmt::format_to` when writing to an array + (https://github.com/fmtlib/fmt/pull/3805). + For example ([godbolt](https://www.godbolt.org/z/cYrn8dWY8)): + + ```c++ + auto volkswagen = char[4]; + auto result = fmt::format_to(volkswagen, "elephant"); + ``` + + no longer results in a buffer overflow. Instead the output will be truncated + and you can get the end iterator and whether truncation occurred from the + `result` object. Thanks @ThePhD. + +- Enabled Unicode support by default in MSVC, bringing it on par with other + compilers and making it unnecessary for users to enable it explicitly. + Most of {fmt} is encoding-agnostic but this prevents mojibake in places + where encoding matters such as path formatting and terminal output. + You can control the Unicode support via the CMake `FMT_UNICODE` option. + Note that some {fmt} packages such as the one in vcpkg have already been + compiled with Unicode enabled. + +- Added a formatter for `std::expected` + (https://github.com/fmtlib/fmt/pull/3834). Thanks @dominicpoeschko. + +- Added a formatter for `std::complex` + (https://github.com/fmtlib/fmt/issues/1467, + https://github.com/fmtlib/fmt/issues/3886, + https://github.com/fmtlib/fmt/pull/3892, + https://github.com/fmtlib/fmt/pull/3900). Thanks @phprus. + +- Added a formatter for `std::type_info` + (https://github.com/fmtlib/fmt/pull/3978). Thanks @matt77hias. + +- Specialized `formatter` for `std::basic_string` types with custom traits + and allocators (https://github.com/fmtlib/fmt/issues/3938, + https://github.com/fmtlib/fmt/pull/3943). Thanks @dieram3. + +- Added formatters for `std::chrono::day`, `std::chrono::month`, + `std::chrono::year` and `std::chrono::year_month_day` + (https://github.com/fmtlib/fmt/issues/3758, + https://github.com/fmtlib/fmt/issues/3772, + https://github.com/fmtlib/fmt/pull/3906, + https://github.com/fmtlib/fmt/pull/3913). For example: + + ```c++ + #include + #include + + int main() { + fmt::print(fg(fmt::color::green), "{}\n", std::chrono::day(7)); + } + ``` + + prints a green day: + + image + + Thanks @zivshek. + +- Fixed handling of precision in `%S` (https://github.com/fmtlib/fmt/issues/3794, + https://github.com/fmtlib/fmt/pull/3814). Thanks @js324. + +- Added support for the `-` specifier (glibc `strftime` extension) to day of + the month (`%d`) and week of the year (`%W`, `%U`, `%V`) specifiers + (https://github.com/fmtlib/fmt/pull/3976). Thanks @ZaheenJ. + +- Fixed the scope of the `-` extension in chrono formatting so that it doesn't + apply to subsequent specifiers (https://github.com/fmtlib/fmt/issues/3811, + https://github.com/fmtlib/fmt/pull/3812). Thanks @phprus. + +- Improved handling of `time_point::min()` + (https://github.com/fmtlib/fmt/issues/3282). + +- Added support for character range formatting + (https://github.com/fmtlib/fmt/issues/3857, + https://github.com/fmtlib/fmt/pull/3863). Thanks @js324. + +- Added `string` and `debug_string` range formatters + (https://github.com/fmtlib/fmt/pull/3973, + https://github.com/fmtlib/fmt/pull/4024). Thanks @matt77hias. + +- Enabled ADL for `begin` and `end` in `fmt::join` + (https://github.com/fmtlib/fmt/issues/3813, + https://github.com/fmtlib/fmt/pull/3824). Thanks @bbolli. + +- Made contiguous iterator optimizations apply to `std::basic_string` iterators + (https://github.com/fmtlib/fmt/pull/3798). Thanks @phprus. + +- Added support for ranges with mutable `begin` and `end` + (https://github.com/fmtlib/fmt/issues/3752, + https://github.com/fmtlib/fmt/pull/3800, + https://github.com/fmtlib/fmt/pull/3955). Thanks @tcbrindle and @Arghnews. + +- Added support for move-only iterators to `fmt::join` + (https://github.com/fmtlib/fmt/issues/3802, + https://github.com/fmtlib/fmt/pull/3946). Thanks @Arghnews. + +- Moved range and iterator overloads of `fmt::join` to `fmt/ranges.h`, next + to other overloads. + +- Fixed handling of types with `begin` returning `void` such as Eigen matrices + (https://github.com/fmtlib/fmt/issues/3839, + https://github.com/fmtlib/fmt/pull/3964). Thanks @Arghnews. + +- Added an `fmt::formattable` concept (https://github.com/fmtlib/fmt/pull/3974). + Thanks @matt77hias. + +- Added support for `__float128` (https://github.com/fmtlib/fmt/issues/3494). + +- Fixed rounding issues when formatting `long double` with fixed precision + (https://github.com/fmtlib/fmt/issues/3539). + +- Made `fmt::isnan` not trigger floating-point exception for NaN values + (https://github.com/fmtlib/fmt/issues/3948, + https://github.com/fmtlib/fmt/pull/3951). Thanks @alexdewar. + +- Removed dependency on `` for `std::allocator_traits` when possible + (https://github.com/fmtlib/fmt/pull/3804). Thanks @phprus. + +- Enabled compile-time checks in formatting functions that take text colors and + styles. + +- Deprecated wide stream overloads of `fmt::print` that take text styles. + +- Made format string compilation work with clang 12 and later despite + only partial non-type template parameter support + (https://github.com/fmtlib/fmt/issues/4000, + https://github.com/fmtlib/fmt/pull/4001). Thanks @yujincheng08. + +- Made `fmt::iterator_buffer`'s move constructor `noexcept` + (https://github.com/fmtlib/fmt/pull/3808). Thanks @waywardmonkeys. + +- Started enforcing that `formatter::format` is const for compatibility + with `std::format` (https://github.com/fmtlib/fmt/issues/3447). + +- Added `fmt::basic_format_arg::visit` and deprecated `fmt::visit_format_arg`. + +- Made `fmt::basic_string_view` not constructible from `nullptr` for + consistency with `std::string_view` in C++23 + (https://github.com/fmtlib/fmt/pull/3846). Thanks @dalle. + +- Fixed `fmt::group_digits` for negative integers + (https://github.com/fmtlib/fmt/issues/3891, + https://github.com/fmtlib/fmt/pull/3901). Thanks @phprus. + +- Fixed handling of negative ids in `fmt::basic_format_args::get` + (https://github.com/fmtlib/fmt/pull/3945). Thanks @marlenecota. + +- Fixed handling of a buffer boundary on flush + (https://github.com/fmtlib/fmt/issues/4229). + +- Improved named argument validation + (https://github.com/fmtlib/fmt/issues/3817). + +- Disabled copy construction/assignment for `fmt::format_arg_store` and + fixed moved construction (https://github.com/fmtlib/fmt/pull/3833). + Thanks @ivafanas. + +- Worked around a locale issue in RHEL/devtoolset + (https://github.com/fmtlib/fmt/issues/3858, + https://github.com/fmtlib/fmt/pull/3859). Thanks @g199209. + +- Added RTTI detection for MSVC (https://github.com/fmtlib/fmt/pull/3821, + https://github.com/fmtlib/fmt/pull/3963). Thanks @edo9300. + +- Migrated the documentation from Sphinx to MkDocs. + +- Improved documentation and README + (https://github.com/fmtlib/fmt/issues/3775, + https://github.com/fmtlib/fmt/pull/3784, + https://github.com/fmtlib/fmt/issues/3788, + https://github.com/fmtlib/fmt/pull/3789, + https://github.com/fmtlib/fmt/pull/3793, + https://github.com/fmtlib/fmt/issues/3818, + https://github.com/fmtlib/fmt/pull/3820, + https://github.com/fmtlib/fmt/pull/3822, + https://github.com/fmtlib/fmt/pull/3843, + https://github.com/fmtlib/fmt/pull/3890, + https://github.com/fmtlib/fmt/issues/3894, + https://github.com/fmtlib/fmt/pull/3895, + https://github.com/fmtlib/fmt/pull/3905, + https://github.com/fmtlib/fmt/issues/3942, + https://github.com/fmtlib/fmt/pull/4008). + Thanks @zencatalyst, WolleTD, @tupaschoal, @Dobiasd, @frank-weinberg, @bbolli, + @phprus, @waywardmonkeys, @js324 and @tchaikov. + +- Improved CI and tests + (https://github.com/fmtlib/fmt/issues/3878, + https://github.com/fmtlib/fmt/pull/3883, + https://github.com/fmtlib/fmt/issues/3897, + https://github.com/fmtlib/fmt/pull/3979, + https://github.com/fmtlib/fmt/pull/3980, + https://github.com/fmtlib/fmt/pull/3988, + https://github.com/fmtlib/fmt/pull/4010, + https://github.com/fmtlib/fmt/pull/4012, + https://github.com/fmtlib/fmt/pull/4038). + Thanks @vgorrX, @waywardmonkeys, @tchaikov and @phprus. + +- Fixed buffer overflow when using format string compilation with debug format + and `std::back_insert_iterator` (https://github.com/fmtlib/fmt/issues/3795, + https://github.com/fmtlib/fmt/pull/3797). Thanks @phprus. + +- Improved Bazel support + (https://github.com/fmtlib/fmt/pull/3792, + https://github.com/fmtlib/fmt/pull/3801, + https://github.com/fmtlib/fmt/pull/3962, + https://github.com/fmtlib/fmt/pull/3965). Thanks @Vertexwahn. + +- Improved/fixed the CMake config + (https://github.com/fmtlib/fmt/issues/3777, + https://github.com/fmtlib/fmt/pull/3783, + https://github.com/fmtlib/fmt/issues/3847, + https://github.com/fmtlib/fmt/pull/3907). Thanks @phprus and @xTachyon. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/3685, + https://github.com/fmtlib/fmt/issues/3769, + https://github.com/fmtlib/fmt/issues/3796, + https://github.com/fmtlib/fmt/issues/3803, + https://github.com/fmtlib/fmt/pull/3806, + https://github.com/fmtlib/fmt/pull/3807, + https://github.com/fmtlib/fmt/issues/3809, + https://github.com/fmtlib/fmt/pull/3810, + https://github.com/fmtlib/fmt/issues/3830, + https://github.com/fmtlib/fmt/pull/3832, + https://github.com/fmtlib/fmt/issues/3835, + https://github.com/fmtlib/fmt/pull/3844, + https://github.com/fmtlib/fmt/issues/3854, + https://github.com/fmtlib/fmt/pull/3856, + https://github.com/fmtlib/fmt/pull/3865, + https://github.com/fmtlib/fmt/pull/3866, + https://github.com/fmtlib/fmt/pull/3880, + https://github.com/fmtlib/fmt/issues/3881, + https://github.com/fmtlib/fmt/issues/3884, + https://github.com/fmtlib/fmt/issues/3898, + https://github.com/fmtlib/fmt/pull/3899, + https://github.com/fmtlib/fmt/pull/3909, + https://github.com/fmtlib/fmt/pull/3917, + https://github.com/fmtlib/fmt/pull/3923, + https://github.com/fmtlib/fmt/pull/3924, + https://github.com/fmtlib/fmt/issues/3925, + https://github.com/fmtlib/fmt/pull/3930, + https://github.com/fmtlib/fmt/pull/3931, + https://github.com/fmtlib/fmt/pull/3933, + https://github.com/fmtlib/fmt/issues/3935, + https://github.com/fmtlib/fmt/pull/3937, + https://github.com/fmtlib/fmt/pull/3967, + https://github.com/fmtlib/fmt/pull/3968, + https://github.com/fmtlib/fmt/pull/3972, + https://github.com/fmtlib/fmt/pull/3983, + https://github.com/fmtlib/fmt/issues/3992, + https://github.com/fmtlib/fmt/pull/3995, + https://github.com/fmtlib/fmt/pull/4009, + https://github.com/fmtlib/fmt/pull/4023). + Thanks @hmbj, @phprus, @res2k, @Baardi, @matt77hias, @waywardmonkeys, @hmbj, + @yakra, @prlw1, @Arghnews, @mtillmann0, @ShifftC, @eepp, @jimmy-park and + @ChristianGebhardt. + +# 10.2.1 - 2024-01-04 + +- Fixed ABI compatibility with earlier 10.x versions + (https://github.com/fmtlib/fmt/issues/3785, + https://github.com/fmtlib/fmt/pull/3786). Thanks @saraedum. # 10.2.0 - 2024-01-01 -- Added support for the `%j` specifier (the number of days) for - `std::chrono::duration` (https://github.com/fmtlib/fmt/issues/3643, - https://github.com/fmtlib/fmt/pull/3732). Thanks @intelfx. +- Added support for the `%j` specifier (the number of days) for + `std::chrono::duration` (https://github.com/fmtlib/fmt/issues/3643, + https://github.com/fmtlib/fmt/pull/3732). Thanks @intelfx. -- Added support for the chrono suffix for days and changed - the suffix for minutes from "m" to the correct "min" - (https://github.com/fmtlib/fmt/issues/3662, - https://github.com/fmtlib/fmt/pull/3664). - For example ([godbolt](https://godbolt.org/z/9KhMnq9ba)): +- Added support for the chrono suffix for days and changed + the suffix for minutes from "m" to the correct "min" + (https://github.com/fmtlib/fmt/issues/3662, + https://github.com/fmtlib/fmt/pull/3664). + For example ([godbolt](https://godbolt.org/z/9KhMnq9ba)): - ```c++ - #include + ```c++ + #include - int main() { - fmt::print("{}\n", std::chrono::days(42)); // prints "42d" + int main() { + fmt::print("{}\n", std::chrono::days(42)); // prints "42d" + } + ``` + + Thanks @Richardk2n. + +- Fixed an overflow in `std::chrono::time_point` formatting with large dates + (https://github.com/fmtlib/fmt/issues/3725, + https://github.com/fmtlib/fmt/pull/3727). Thanks @cschreib. + +- Added a formatter for `std::source_location` + (https://github.com/fmtlib/fmt/pull/3730). + For example ([godbolt](https://godbolt.org/z/YajfKjhhr)): + + ```c++ + #include + #include + + int main() { + fmt::print("{}\n", std::source_location::current()); + } + ``` + + prints + + ``` + /app/example.cpp:5:51: int main() + ``` + + Thanks @felix642. + +- Added a formatter for `std::bitset` + (https://github.com/fmtlib/fmt/pull/3660). + For example ([godbolt](https://godbolt.org/z/bdEaGeYxe)): + + ```c++ + #include + #include + + int main() { + fmt::print("{}\n", std::bitset<6>(42)); // prints "101010" + } + ``` + + Thanks @muggenhor. + +- Added an experimental `nested_formatter` that provides an easy way of + applying a formatter to one or more subobjects while automatically handling + width, fill and alignment. For example: + + ```c++ + #include + + struct point { + double x, y; + }; + + template <> + struct fmt::formatter : nested_formatter { + auto format(point p, format_context& ctx) const { + return write_padded(ctx, [=](auto out) { + return format_to(out, "({}, {})", nested(p.x), nested(p.y)); + }); } - ``` + }; - Thanks @Richardk2n. + int main() { + fmt::print("[{:>20.2f}]", point{1, 2}); + } + ``` -- Fixed an overflow in `std::chrono::time_point` formatting with large dates - (https://github.com/fmtlib/fmt/issues/3725, - https://github.com/fmtlib/fmt/pull/3727). Thanks @cschreib. + prints -- Added a formatter for `std::source_location` - (https://github.com/fmtlib/fmt/pull/3730). - For example ([godbolt](https://godbolt.org/z/YajfKjhhr)): + ``` + [ (1.00, 2.00)] + ``` - ```c++ - #include - #include +- Added the generic representation (`g`) to `std::filesystem::path` + (https://github.com/fmtlib/fmt/issues/3715, + https://github.com/fmtlib/fmt/pull/3729). For example: - int main() { - fmt::print("{}\n", std::source_location::current()); - } - ``` + ```c++ + #include + #include - prints + int main() { + fmt::print("{:g}\n", std::filesystem::path("C:\\foo")); + } + ``` - ``` - /app/example.cpp:5:51: int main() - ``` + prints `"C:/foo"` on Windows. - Thanks @felix642. + Thanks @js324. -- Added a formatter for `std::bitset` - (https://github.com/fmtlib/fmt/pull/3660). - For example ([godbolt](https://godbolt.org/z/bdEaGeYxe)): +- Made `format_as` work with references + (https://github.com/fmtlib/fmt/pull/3739). Thanks @tchaikov. - ```c++ - #include - #include +- Fixed formatting of invalid UTF-8 with precision + (https://github.com/fmtlib/fmt/issues/3284). - int main() { - fmt::print("{}\n", std::bitset<6>(42)); // prints "101010" - } - ``` +- Fixed an inconsistency between `fmt::to_string` and `fmt::format` + (https://github.com/fmtlib/fmt/issues/3684). - Thanks @muggenhor. +- Disallowed unsafe uses of `fmt::styled` + (https://github.com/fmtlib/fmt/issues/3625): -- Added an experimental `nested_formatter` that provides an easy way of - applying a formatter to one or more subobjects while automatically handling - width, fill and alignment. For example: + ```c++ + auto s = fmt::styled(std::string("dangle"), fmt::emphasis::bold); + fmt::print("{}\n", s); // compile error + ``` - ```c++ - #include + Pass `fmt::styled(...)` as a parameter instead. - struct point { - double x, y; - }; +- Added a null check when formatting a C string with the `s` specifier + (https://github.com/fmtlib/fmt/issues/3706). - template <> - struct fmt::formatter : nested_formatter { - auto format(point p, format_context& ctx) const { - return write_padded(ctx, [=](auto out) { - return format_to(out, "({}, {})", nested(p.x), nested(p.y)); - }); - } - }; +- Disallowed the `c` specifier for `bool` + (https://github.com/fmtlib/fmt/issues/3726, + https://github.com/fmtlib/fmt/pull/3734). Thanks @js324. - int main() { - fmt::print("[{:>20.2f}]", point{1, 2}); - } - ``` +- Made the default formatting unlocalized in `fmt::ostream_formatter` for + consistency with the rest of the library + (https://github.com/fmtlib/fmt/issues/3460). - prints +- Fixed localized formatting in bases other than decimal + (https://github.com/fmtlib/fmt/issues/3693, + https://github.com/fmtlib/fmt/pull/3750). Thanks @js324. - ``` - [ (1.00, 2.00)] - ``` +- Fixed a performance regression in experimental `fmt::ostream::print` + (https://github.com/fmtlib/fmt/issues/3674). -- Added the generic representation (`g`) to `std::filesystem::path` - (https://github.com/fmtlib/fmt/issues/3715, - https://github.com/fmtlib/fmt/pull/3729). For example: +- Added synchronization with the underlying output stream when writing to + the Windows console + (https://github.com/fmtlib/fmt/pull/3668, + https://github.com/fmtlib/fmt/issues/3688, + https://github.com/fmtlib/fmt/pull/3689). + Thanks @Roman-Koshelev and @dimztimz. - ```c++ - #include - #include +- Changed to only export `format_error` when {fmt} is built as a shared + library (https://github.com/fmtlib/fmt/issues/3626, + https://github.com/fmtlib/fmt/pull/3627). Thanks @phprus. - int main() { - fmt::print("{:g}\n", std::filesystem::path("C:\\foo")); - } - ``` +- Made `fmt::streamed` `constexpr`. + (https://github.com/fmtlib/fmt/pull/3650). Thanks @muggenhor. - prints `"C:/foo"` on Windows. +- Made `fmt::format_int` `constexpr` + (https://github.com/fmtlib/fmt/issues/4031, + https://github.com/fmtlib/fmt/pull/4032). Thanks @dixlorenz. - Thanks @js324. +- Enabled `consteval` on older versions of MSVC + (https://github.com/fmtlib/fmt/pull/3757). Thanks @phprus. -- Made `format_as` work with references - (https://github.com/fmtlib/fmt/pull/3739). Thanks @tchaikov. +- Added an option to build without `wchar_t` support on Windows + (https://github.com/fmtlib/fmt/issues/3631, + https://github.com/fmtlib/fmt/pull/3636). Thanks @glebm. -- Fixed formatting of invalid UTF-8 with precision - (https://github.com/fmtlib/fmt/issues/3284). +- Improved build and CI configuration + (https://github.com/fmtlib/fmt/pull/3679, + https://github.com/fmtlib/fmt/issues/3701, + https://github.com/fmtlib/fmt/pull/3702, + https://github.com/fmtlib/fmt/pull/3749). + Thanks @jcar87, @pklima and @tchaikov. -- Fixed an inconsistency between `fmt::to_string` and `fmt::format` - (https://github.com/fmtlib/fmt/issues/3684). +- Fixed various warnings, compilation and test issues + (https://github.com/fmtlib/fmt/issues/3607, + https://github.com/fmtlib/fmt/pull/3610, + https://github.com/fmtlib/fmt/pull/3624, + https://github.com/fmtlib/fmt/pull/3630, + https://github.com/fmtlib/fmt/pull/3634, + https://github.com/fmtlib/fmt/pull/3638, + https://github.com/fmtlib/fmt/issues/3645, + https://github.com/fmtlib/fmt/issues/3646, + https://github.com/fmtlib/fmt/pull/3647, + https://github.com/fmtlib/fmt/pull/3652, + https://github.com/fmtlib/fmt/issues/3654, + https://github.com/fmtlib/fmt/pull/3663, + https://github.com/fmtlib/fmt/issues/3670, + https://github.com/fmtlib/fmt/pull/3680, + https://github.com/fmtlib/fmt/issues/3694, + https://github.com/fmtlib/fmt/pull/3695, + https://github.com/fmtlib/fmt/pull/3699, + https://github.com/fmtlib/fmt/issues/3705, + https://github.com/fmtlib/fmt/issues/3710, + https://github.com/fmtlib/fmt/issues/3712, + https://github.com/fmtlib/fmt/pull/3713, + https://github.com/fmtlib/fmt/issues/3714, + https://github.com/fmtlib/fmt/pull/3716, + https://github.com/fmtlib/fmt/pull/3723, + https://github.com/fmtlib/fmt/issues/3738, + https://github.com/fmtlib/fmt/issues/3740, + https://github.com/fmtlib/fmt/pull/3741, + https://github.com/fmtlib/fmt/pull/3743, + https://github.com/fmtlib/fmt/issues/3745, + https://github.com/fmtlib/fmt/pull/3747, + https://github.com/fmtlib/fmt/pull/3748, + https://github.com/fmtlib/fmt/pull/3751, + https://github.com/fmtlib/fmt/pull/3754, + https://github.com/fmtlib/fmt/pull/3755, + https://github.com/fmtlib/fmt/issues/3760, + https://github.com/fmtlib/fmt/pull/3762, + https://github.com/fmtlib/fmt/issues/3763, + https://github.com/fmtlib/fmt/pull/3764, + https://github.com/fmtlib/fmt/issues/3774, + https://github.com/fmtlib/fmt/pull/3779). + Thanks @danakj, @vinayyadav3016, @cyyever, @phprus, @qimiko, @saschasc, + @gsjaardema, @lazka, @Zhaojun-Liu, @carlsmedstad, @hotwatermorning, + @cptFracassa, @kuguma, @PeterJohnson, @H1X4Dev, @asantoni, @eltociear, + @msimberg, @tchaikov, @waywardmonkeys. -- Disallowed unsafe uses of `fmt::styled` - (https://github.com/fmtlib/fmt/issues/3625): +- Improved documentation and README + (https://github.com/fmtlib/fmt/issues/2086, + https://github.com/fmtlib/fmt/issues/3637, + https://github.com/fmtlib/fmt/pull/3642, + https://github.com/fmtlib/fmt/pull/3653, + https://github.com/fmtlib/fmt/pull/3655, + https://github.com/fmtlib/fmt/pull/3661, + https://github.com/fmtlib/fmt/issues/3673, + https://github.com/fmtlib/fmt/pull/3677, + https://github.com/fmtlib/fmt/pull/3737, + https://github.com/fmtlib/fmt/issues/3742, + https://github.com/fmtlib/fmt/pull/3744). + Thanks @idzm, @perlun, @joycebrum, @fennewald, @reinhardt1053, @GeorgeLS. - ```c++ - auto s = fmt::styled(std::string("dangle"), fmt::emphasis::bold); - fmt::print("{}\n", s); // compile error - ``` - - Pass `fmt::styled(...)` as a parameter instead. - -- Added a null check when formatting a C string with the `s` specifier - (https://github.com/fmtlib/fmt/issues/3706). - -- Disallowed the `c` specifier for `bool` - (https://github.com/fmtlib/fmt/issues/3726, - https://github.com/fmtlib/fmt/pull/3734). Thanks @js324. - -- Made the default formatting unlocalized in `fmt::ostream_formatter` for - consistency with the rest of the library - (https://github.com/fmtlib/fmt/issues/3460). - -- Fixed localized formatting in bases other than decimal - (https://github.com/fmtlib/fmt/issues/3693, - https://github.com/fmtlib/fmt/pull/3750). Thanks @js324. - -- Fixed a performance regression in experimental `fmt::ostream::print` - (https://github.com/fmtlib/fmt/issues/3674). - -- Added synchronization with the underlying output stream when writing to - the Windows console - (https://github.com/fmtlib/fmt/pull/3668, - https://github.com/fmtlib/fmt/issues/3688, - https://github.com/fmtlib/fmt/pull/3689). - Thanks @Roman-Koshelev and @dimztimz. - -- Changed to only export `format_error` when {fmt} is built as a shared - library (https://github.com/fmtlib/fmt/issues/3626, - https://github.com/fmtlib/fmt/pull/3627). Thanks @phprus. - -- Made `fmt::streamed` `constexpr`. - (https://github.com/fmtlib/fmt/pull/3650). Thanks @muggenhor. - -- Enabled `consteval` on older versions of MSVC - (https://github.com/fmtlib/fmt/pull/3757). Thanks @phprus. - -- Added an option to build without `wchar_t` support on Windows - (https://github.com/fmtlib/fmt/issues/3631, - https://github.com/fmtlib/fmt/pull/3636). Thanks @glebm. - -- Improved build and CI configuration - (https://github.com/fmtlib/fmt/pull/3679, - https://github.com/fmtlib/fmt/issues/3701, - https://github.com/fmtlib/fmt/pull/3702, - https://github.com/fmtlib/fmt/pull/3749). - Thanks @jcar87, @pklima and @tchaikov. - -- Fixed various warnings, compilation and test issues - (https://github.com/fmtlib/fmt/issues/3607, - https://github.com/fmtlib/fmt/pull/3610, - https://github.com/fmtlib/fmt/pull/3624, - https://github.com/fmtlib/fmt/pull/3630, - https://github.com/fmtlib/fmt/pull/3634, - https://github.com/fmtlib/fmt/pull/3638, - https://github.com/fmtlib/fmt/issues/3645, - https://github.com/fmtlib/fmt/issues/3646, - https://github.com/fmtlib/fmt/pull/3647, - https://github.com/fmtlib/fmt/pull/3652, - https://github.com/fmtlib/fmt/issues/3654, - https://github.com/fmtlib/fmt/pull/3663, - https://github.com/fmtlib/fmt/issues/3670, - https://github.com/fmtlib/fmt/pull/3680, - https://github.com/fmtlib/fmt/issues/3694, - https://github.com/fmtlib/fmt/pull/3695, - https://github.com/fmtlib/fmt/pull/3699, - https://github.com/fmtlib/fmt/issues/3705, - https://github.com/fmtlib/fmt/issues/3710, - https://github.com/fmtlib/fmt/issues/3712, - https://github.com/fmtlib/fmt/pull/3713, - https://github.com/fmtlib/fmt/issues/3714, - https://github.com/fmtlib/fmt/pull/3716, - https://github.com/fmtlib/fmt/pull/3723, - https://github.com/fmtlib/fmt/issues/3738, - https://github.com/fmtlib/fmt/issues/3740, - https://github.com/fmtlib/fmt/pull/3741, - https://github.com/fmtlib/fmt/pull/3743, - https://github.com/fmtlib/fmt/issues/3745, - https://github.com/fmtlib/fmt/pull/3747, - https://github.com/fmtlib/fmt/pull/3748, - https://github.com/fmtlib/fmt/pull/3751, - https://github.com/fmtlib/fmt/pull/3754, - https://github.com/fmtlib/fmt/pull/3755, - https://github.com/fmtlib/fmt/issues/3760, - https://github.com/fmtlib/fmt/pull/3762, - https://github.com/fmtlib/fmt/issues/3763, - https://github.com/fmtlib/fmt/pull/3764, - https://github.com/fmtlib/fmt/issues/3774, - https://github.com/fmtlib/fmt/pull/3779). - Thanks @danakj, @vinayyadav3016, @cyyever, @phprus, @qimiko, @saschasc, - @gsjaardema, @lazka, @Zhaojun-Liu, @carlsmedstad, @hotwatermorning, - @cptFracassa, @kuguma, @PeterJohnson, @H1X4Dev, @asantoni, @eltociear, - @msimberg, @tchaikov, @waywardmonkeys. - -- Improved documentation and README - (https://github.com/fmtlib/fmt/issues/2086, - https://github.com/fmtlib/fmt/issues/3637, - https://github.com/fmtlib/fmt/pull/3642, - https://github.com/fmtlib/fmt/pull/3653, - https://github.com/fmtlib/fmt/pull/3655, - https://github.com/fmtlib/fmt/pull/3661, - https://github.com/fmtlib/fmt/issues/3673, - https://github.com/fmtlib/fmt/pull/3677, - https://github.com/fmtlib/fmt/pull/3737, - https://github.com/fmtlib/fmt/issues/3742, - https://github.com/fmtlib/fmt/pull/3744). - Thanks @idzm, @perlun, @joycebrum, @fennewald, @reinhardt1053, @GeorgeLS. - -- Updated CI dependencies - (https://github.com/fmtlib/fmt/pull/3615, - https://github.com/fmtlib/fmt/pull/3622, - https://github.com/fmtlib/fmt/pull/3623, - https://github.com/fmtlib/fmt/pull/3666, - https://github.com/fmtlib/fmt/pull/3696, - https://github.com/fmtlib/fmt/pull/3697, - https://github.com/fmtlib/fmt/pull/3759, - https://github.com/fmtlib/fmt/pull/3782). +- Updated CI dependencies + (https://github.com/fmtlib/fmt/pull/3615, + https://github.com/fmtlib/fmt/pull/3622, + https://github.com/fmtlib/fmt/pull/3623, + https://github.com/fmtlib/fmt/pull/3666, + https://github.com/fmtlib/fmt/pull/3696, + https://github.com/fmtlib/fmt/pull/3697, + https://github.com/fmtlib/fmt/pull/3759, + https://github.com/fmtlib/fmt/pull/3782). # 10.1.1 - 2023-08-28 -- Added formatters for `std::atomic` and `atomic_flag` - (https://github.com/fmtlib/fmt/pull/3574, - https://github.com/fmtlib/fmt/pull/3594). - Thanks @wangzw and @AlexGuteniev. -- Fixed an error about partial specialization of `formatter` - after instantiation when compiled with gcc and C++20 - (https://github.com/fmtlib/fmt/issues/3584). -- Fixed compilation as a C++20 module with gcc and clang - (https://github.com/fmtlib/fmt/issues/3587, - https://github.com/fmtlib/fmt/pull/3597, - https://github.com/fmtlib/fmt/pull/3605). - Thanks @MathewBensonCode. -- Made `fmt::to_string` work with types that have `format_as` - overloads (https://github.com/fmtlib/fmt/pull/3575). Thanks @phprus. -- Made `formatted_size` work with integral format specifiers at - compile time (https://github.com/fmtlib/fmt/pull/3591). - Thanks @elbeno. -- Fixed a warning about the `no_unique_address` attribute on clang-cl - (https://github.com/fmtlib/fmt/pull/3599). Thanks @lukester1975. -- Improved compatibility with the legacy GBK encoding - (https://github.com/fmtlib/fmt/issues/3598, - https://github.com/fmtlib/fmt/pull/3599). Thanks @YuHuanTin. -- Added OpenSSF Scorecard analysis - (https://github.com/fmtlib/fmt/issues/3530, - https://github.com/fmtlib/fmt/pull/3571). Thanks @joycebrum. -- Updated CI dependencies - (https://github.com/fmtlib/fmt/pull/3591, - https://github.com/fmtlib/fmt/pull/3592, - https://github.com/fmtlib/fmt/pull/3593, - https://github.com/fmtlib/fmt/pull/3602). +- Added formatters for `std::atomic` and `atomic_flag` + (https://github.com/fmtlib/fmt/pull/3574, + https://github.com/fmtlib/fmt/pull/3594). + Thanks @wangzw and @AlexGuteniev. +- Fixed an error about partial specialization of `formatter` + after instantiation when compiled with gcc and C++20 + (https://github.com/fmtlib/fmt/issues/3584). +- Fixed compilation as a C++20 module with gcc and clang + (https://github.com/fmtlib/fmt/issues/3587, + https://github.com/fmtlib/fmt/pull/3597, + https://github.com/fmtlib/fmt/pull/3605). + Thanks @MathewBensonCode. +- Made `fmt::to_string` work with types that have `format_as` + overloads (https://github.com/fmtlib/fmt/pull/3575). Thanks @phprus. +- Made `formatted_size` work with integral format specifiers at + compile time (https://github.com/fmtlib/fmt/pull/3591). + Thanks @elbeno. +- Fixed a warning about the `no_unique_address` attribute on clang-cl + (https://github.com/fmtlib/fmt/pull/3599). Thanks @lukester1975. +- Improved compatibility with the legacy GBK encoding + (https://github.com/fmtlib/fmt/issues/3598, + https://github.com/fmtlib/fmt/pull/3599). Thanks @YuHuanTin. +- Added OpenSSF Scorecard analysis + (https://github.com/fmtlib/fmt/issues/3530, + https://github.com/fmtlib/fmt/pull/3571). Thanks @joycebrum. +- Updated CI dependencies + (https://github.com/fmtlib/fmt/pull/3591, + https://github.com/fmtlib/fmt/pull/3592, + https://github.com/fmtlib/fmt/pull/3593, + https://github.com/fmtlib/fmt/pull/3602). # 10.1.0 - 2023-08-12 -- Optimized format string compilation resulting in up to 40% speed up - in compiled `format_to` and \~4x speed up in compiled `format_to_n` - on a concatenation benchmark - (https://github.com/fmtlib/fmt/issues/3133, - https://github.com/fmtlib/fmt/issues/3484). +- Optimized format string compilation resulting in up to 40% speed up + in compiled `format_to` and \~4x speed up in compiled `format_to_n` + on a concatenation benchmark + (https://github.com/fmtlib/fmt/issues/3133, + https://github.com/fmtlib/fmt/issues/3484). - {fmt} 10.0: + {fmt} 10.0: - --------------------------------------------------------- - Benchmark Time CPU Iterations - --------------------------------------------------------- - BM_format_to 78.9 ns 78.9 ns 8881746 - BM_format_to_n 568 ns 568 ns 1232089 + --------------------------------------------------------- + Benchmark Time CPU Iterations + --------------------------------------------------------- + BM_format_to 78.9 ns 78.9 ns 8881746 + BM_format_to_n 568 ns 568 ns 1232089 - {fmt} 10.1: + {fmt} 10.1: - --------------------------------------------------------- - Benchmark Time CPU Iterations - --------------------------------------------------------- - BM_format_to 54.9 ns 54.9 ns 12727944 - BM_format_to_n 133 ns 133 ns 5257795 + --------------------------------------------------------- + Benchmark Time CPU Iterations + --------------------------------------------------------- + BM_format_to 54.9 ns 54.9 ns 12727944 + BM_format_to_n 133 ns 133 ns 5257795 -- Optimized storage of an empty allocator in `basic_memory_buffer` - (https://github.com/fmtlib/fmt/pull/3485). Thanks @Minty-Meeo. +- Optimized storage of an empty allocator in `basic_memory_buffer` + (https://github.com/fmtlib/fmt/pull/3485). Thanks @Minty-Meeo. -- Added formatters for proxy references to elements of - `std::vector` and `std::bitset` - (https://github.com/fmtlib/fmt/issues/3567, - https://github.com/fmtlib/fmt/pull/3570). For example - ([godbolt](https://godbolt.org/z/zYb79Pvn8)): +- Added formatters for proxy references to elements of + `std::vector` and `std::bitset` + (https://github.com/fmtlib/fmt/issues/3567, + https://github.com/fmtlib/fmt/pull/3570). For example + ([godbolt](https://godbolt.org/z/zYb79Pvn8)): - ```c++ - #include - #include + ```c++ + #include + #include - int main() { - auto v = std::vector{true}; - fmt::print("{}", v[0]); - } - ``` + int main() { + auto v = std::vector{true}; + fmt::print("{}", v[0]); + } + ``` - Thanks @phprus and @felix642. + Thanks @phprus and @felix642. -- Fixed an ambiguous formatter specialization for containers that look - like container adaptors such as `boost::flat_set` - (https://github.com/fmtlib/fmt/issues/3556, - https://github.com/fmtlib/fmt/pull/3561). Thanks @5chmidti. +- Fixed an ambiguous formatter specialization for containers that look + like container adaptors such as `boost::flat_set` + (https://github.com/fmtlib/fmt/issues/3556, + https://github.com/fmtlib/fmt/pull/3561). Thanks @5chmidti. -- Fixed compilation when formatting durations not convertible from - `std::chrono::seconds` - (https://github.com/fmtlib/fmt/pull/3430). Thanks @patlkli. +- Fixed compilation when formatting durations not convertible from + `std::chrono::seconds` + (https://github.com/fmtlib/fmt/pull/3430). Thanks @patlkli. -- Made the `formatter` specialization for `char*` const-correct - (https://github.com/fmtlib/fmt/pull/3432). Thanks @timsong-cpp. +- Made the `formatter` specialization for `char*` const-correct + (https://github.com/fmtlib/fmt/pull/3432). Thanks @timsong-cpp. -- Made `{}` and `{:}` handled consistently during compile-time checks - (https://github.com/fmtlib/fmt/issues/3526). +- Made `{}` and `{:}` handled consistently during compile-time checks + (https://github.com/fmtlib/fmt/issues/3526). -- Disallowed passing temporaries to `make_format_args` to improve API - safety by preventing dangling references. +- Disallowed passing temporaries to `make_format_args` to improve API + safety by preventing dangling references. -- Improved the compile-time error for unformattable types - (https://github.com/fmtlib/fmt/pull/3478). Thanks @BRevzin. +- Improved the compile-time error for unformattable types + (https://github.com/fmtlib/fmt/pull/3478). Thanks @BRevzin. -- Improved the floating-point formatter - (https://github.com/fmtlib/fmt/pull/3448, - https://github.com/fmtlib/fmt/pull/3450). - Thanks @florimond-collette. +- Improved the floating-point formatter + (https://github.com/fmtlib/fmt/pull/3448, + https://github.com/fmtlib/fmt/pull/3450). + Thanks @florimond-collette. -- Fixed handling of precision for `long double` larger than 64 bits. - (https://github.com/fmtlib/fmt/issues/3539, - https://github.com/fmtlib/fmt/issues/3564). +- Fixed handling of precision for `long double` larger than 64 bits. + (https://github.com/fmtlib/fmt/issues/3539, + https://github.com/fmtlib/fmt/issues/3564). -- Made floating-point and chrono tests less platform-dependent - (https://github.com/fmtlib/fmt/issues/3337, - https://github.com/fmtlib/fmt/issues/3433, - https://github.com/fmtlib/fmt/pull/3434). Thanks @phprus. +- Made floating-point and chrono tests less platform-dependent + (https://github.com/fmtlib/fmt/issues/3337, + https://github.com/fmtlib/fmt/issues/3433, + https://github.com/fmtlib/fmt/pull/3434). Thanks @phprus. -- Removed the remnants of the Grisu floating-point formatter that has - been replaced by Dragonbox in earlier versions. +- Removed the remnants of the Grisu floating-point formatter that has + been replaced by Dragonbox in earlier versions. -- Added `throw_format_error` to the public API - (https://github.com/fmtlib/fmt/pull/3551). Thanks @mjerabek. +- Added `throw_format_error` to the public API + (https://github.com/fmtlib/fmt/pull/3551). Thanks @mjerabek. -- Made `FMT_THROW` assert even if assertions are disabled when - compiling with exceptions disabled - (https://github.com/fmtlib/fmt/issues/3418, - https://github.com/fmtlib/fmt/pull/3439). Thanks @BRevzin. +- Made `FMT_THROW` assert even if assertions are disabled when + compiling with exceptions disabled + (https://github.com/fmtlib/fmt/issues/3418, + https://github.com/fmtlib/fmt/pull/3439). Thanks @BRevzin. -- Made `format_as` and `std::filesystem::path` formatter work with - exotic code unit types. - (https://github.com/fmtlib/fmt/pull/3457, - https://github.com/fmtlib/fmt/pull/3476). Thanks @gix and @hmbj. +- Made `format_as` and `std::filesystem::path` formatter work with + exotic code unit types. + (https://github.com/fmtlib/fmt/pull/3457, + https://github.com/fmtlib/fmt/pull/3476). Thanks @gix and @hmbj. -- Added support for the `?` format specifier to - `std::filesystem::path` and made the default unescaped for - consistency with strings. +- Added support for the `?` format specifier to + `std::filesystem::path` and made the default unescaped for + consistency with strings. -- Deprecated the wide stream overload of `printf`. +- Deprecated the wide stream overload of `printf`. -- Removed unused `basic_printf_parse_context`. +- Removed unused `basic_printf_parse_context`. -- Improved RTTI detection used when formatting exceptions - (https://github.com/fmtlib/fmt/pull/3468). Thanks @danakj. +- Improved RTTI detection used when formatting exceptions + (https://github.com/fmtlib/fmt/pull/3468). Thanks @danakj. -- Improved compatibility with VxWorks7 - (https://github.com/fmtlib/fmt/pull/3467). Thanks @wenshan1. +- Improved compatibility with VxWorks7 + (https://github.com/fmtlib/fmt/pull/3467). Thanks @wenshan1. -- Improved documentation - (https://github.com/fmtlib/fmt/issues/3174, - https://github.com/fmtlib/fmt/issues/3423, - https://github.com/fmtlib/fmt/pull/3454, - https://github.com/fmtlib/fmt/issues/3458, - https://github.com/fmtlib/fmt/pull/3461, - https://github.com/fmtlib/fmt/issues/3487, - https://github.com/fmtlib/fmt/pull/3515). - Thanks @zencatalyst, @rlalik and @mikecrowe. +- Improved documentation + (https://github.com/fmtlib/fmt/issues/3174, + https://github.com/fmtlib/fmt/issues/3423, + https://github.com/fmtlib/fmt/pull/3454, + https://github.com/fmtlib/fmt/issues/3458, + https://github.com/fmtlib/fmt/pull/3461, + https://github.com/fmtlib/fmt/issues/3487, + https://github.com/fmtlib/fmt/pull/3515). + Thanks @zencatalyst, @rlalik and @mikecrowe. -- Improved build and CI configurations - (https://github.com/fmtlib/fmt/issues/3449, - https://github.com/fmtlib/fmt/pull/3451, - https://github.com/fmtlib/fmt/pull/3452, - https://github.com/fmtlib/fmt/pull/3453, - https://github.com/fmtlib/fmt/pull/3459, - https://github.com/fmtlib/fmt/issues/3481, - https://github.com/fmtlib/fmt/pull/3486, - https://github.com/fmtlib/fmt/issues/3489, - https://github.com/fmtlib/fmt/pull/3496, - https://github.com/fmtlib/fmt/issues/3517, - https://github.com/fmtlib/fmt/pull/3523, - https://github.com/fmtlib/fmt/pull/3563). - Thanks @joycebrum, @glebm, @phprus, @petrmanek, @setoye and @abouvier. +- Improved build and CI configurations + (https://github.com/fmtlib/fmt/issues/3449, + https://github.com/fmtlib/fmt/pull/3451, + https://github.com/fmtlib/fmt/pull/3452, + https://github.com/fmtlib/fmt/pull/3453, + https://github.com/fmtlib/fmt/pull/3459, + https://github.com/fmtlib/fmt/issues/3481, + https://github.com/fmtlib/fmt/pull/3486, + https://github.com/fmtlib/fmt/issues/3489, + https://github.com/fmtlib/fmt/pull/3496, + https://github.com/fmtlib/fmt/issues/3517, + https://github.com/fmtlib/fmt/pull/3523, + https://github.com/fmtlib/fmt/pull/3563). + Thanks @joycebrum, @glebm, @phprus, @petrmanek, @setoye and @abouvier. -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/issues/3408, - https://github.com/fmtlib/fmt/issues/3424, - https://github.com/fmtlib/fmt/issues/3444, - https://github.com/fmtlib/fmt/pull/3446, - https://github.com/fmtlib/fmt/pull/3475, - https://github.com/fmtlib/fmt/pull/3482, - https://github.com/fmtlib/fmt/issues/3492, - https://github.com/fmtlib/fmt/pull/3493, - https://github.com/fmtlib/fmt/pull/3508, - https://github.com/fmtlib/fmt/issues/3509, - https://github.com/fmtlib/fmt/issues/3533, - https://github.com/fmtlib/fmt/pull/3542, - https://github.com/fmtlib/fmt/issues/3543, - https://github.com/fmtlib/fmt/issues/3540, - https://github.com/fmtlib/fmt/pull/3544, - https://github.com/fmtlib/fmt/issues/3548, - https://github.com/fmtlib/fmt/pull/3549, - https://github.com/fmtlib/fmt/pull/3550, - https://github.com/fmtlib/fmt/pull/3552). - Thanks @adesitter, @hmbj, @Minty-Meeo, @phprus, @TobiSchluter, - @kieranclancy, @alexeedm, @jurihock, @Ozomahtli and @razaqq. +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/3408, + https://github.com/fmtlib/fmt/issues/3424, + https://github.com/fmtlib/fmt/issues/3444, + https://github.com/fmtlib/fmt/pull/3446, + https://github.com/fmtlib/fmt/pull/3475, + https://github.com/fmtlib/fmt/pull/3482, + https://github.com/fmtlib/fmt/issues/3492, + https://github.com/fmtlib/fmt/pull/3493, + https://github.com/fmtlib/fmt/pull/3508, + https://github.com/fmtlib/fmt/issues/3509, + https://github.com/fmtlib/fmt/issues/3533, + https://github.com/fmtlib/fmt/pull/3542, + https://github.com/fmtlib/fmt/issues/3543, + https://github.com/fmtlib/fmt/issues/3540, + https://github.com/fmtlib/fmt/pull/3544, + https://github.com/fmtlib/fmt/issues/3548, + https://github.com/fmtlib/fmt/pull/3549, + https://github.com/fmtlib/fmt/pull/3550, + https://github.com/fmtlib/fmt/pull/3552). + Thanks @adesitter, @hmbj, @Minty-Meeo, @phprus, @TobiSchluter, + @kieranclancy, @alexeedm, @jurihock, @Ozomahtli and @razaqq. # 10.0.0 - 2023-05-09 -- Replaced Grisu with a new floating-point formatting algorithm for - given precision (https://github.com/fmtlib/fmt/issues/3262, - https://github.com/fmtlib/fmt/issues/2750, - https://github.com/fmtlib/fmt/pull/3269, - https://github.com/fmtlib/fmt/pull/3276). The new algorithm - is based on Dragonbox already used for the shortest representation - and gives substantial performance improvement: +- Replaced Grisu with a new floating-point formatting algorithm for + given precision (https://github.com/fmtlib/fmt/issues/3262, + https://github.com/fmtlib/fmt/issues/2750, + https://github.com/fmtlib/fmt/pull/3269, + https://github.com/fmtlib/fmt/pull/3276). The new algorithm + is based on Dragonbox already used for the shortest representation + and gives substantial performance improvement: - ![](https://user-images.githubusercontent.com/33922675/211956670-84891a09-6867-47d9-82fc-3230da7abe0f.png) + ![](https://user-images.githubusercontent.com/33922675/211956670-84891a09-6867-47d9-82fc-3230da7abe0f.png) - - Red: new algorithm - - Green: new algorithm with `FMT_USE_FULL_CACHE_DRAGONBOX` defined - to 1 - - Blue: old algorithm + - Red: new algorithm + - Green: new algorithm with `FMT_USE_FULL_CACHE_DRAGONBOX` defined + to 1 + - Blue: old algorithm - Thanks @jk-jeon. + Thanks @jk-jeon. -- Replaced `snprintf`-based hex float formatter with an internal - implementation (https://github.com/fmtlib/fmt/pull/3179, - https://github.com/fmtlib/fmt/pull/3203). This removes the - last usage of `s(n)printf` in {fmt}. Thanks @phprus. +- Replaced `snprintf`-based hex float formatter with an internal + implementation (https://github.com/fmtlib/fmt/pull/3179, + https://github.com/fmtlib/fmt/pull/3203). This removes the + last usage of `s(n)printf` in {fmt}. Thanks @phprus. -- Fixed alignment of floating-point numbers with localization - (https://github.com/fmtlib/fmt/issues/3263, - https://github.com/fmtlib/fmt/pull/3272). Thanks @ShawnZhong. +- Fixed alignment of floating-point numbers with localization + (https://github.com/fmtlib/fmt/issues/3263, + https://github.com/fmtlib/fmt/pull/3272). Thanks @ShawnZhong. -- Made handling of `#` consistent with `std::format`. +- Made handling of `#` consistent with `std::format`. -- Improved C++20 module support - (https://github.com/fmtlib/fmt/pull/3134, - https://github.com/fmtlib/fmt/pull/3254, - https://github.com/fmtlib/fmt/pull/3386, - https://github.com/fmtlib/fmt/pull/3387, - https://github.com/fmtlib/fmt/pull/3388, - https://github.com/fmtlib/fmt/pull/3392, - https://github.com/fmtlib/fmt/pull/3397, - https://github.com/fmtlib/fmt/pull/3399, - https://github.com/fmtlib/fmt/pull/3400). - Thanks @laitingsheng, @Orvid and @DanielaE. - -- Switched to the [modules CMake library](https://github.com/vitaut/modules) - which allows building {fmt} as a C++20 module with clang: +- Improved C++20 module support + (https://github.com/fmtlib/fmt/pull/3134, + https://github.com/fmtlib/fmt/pull/3254, + https://github.com/fmtlib/fmt/pull/3386, + https://github.com/fmtlib/fmt/pull/3387, + https://github.com/fmtlib/fmt/pull/3388, + https://github.com/fmtlib/fmt/pull/3392, + https://github.com/fmtlib/fmt/pull/3397, + https://github.com/fmtlib/fmt/pull/3399, + https://github.com/fmtlib/fmt/pull/3400). + Thanks @laitingsheng, @Orvid and @DanielaE. + +- Switched to the [modules CMake library](https://github.com/vitaut/modules) + which allows building {fmt} as a C++20 module with clang: - CXX=clang++ cmake -DFMT_MODULE=ON . - make + CXX=clang++ cmake -DFMT_MODULE=ON . + make -- Made `format_as` work with any user-defined type and not just enums. - For example ([godbolt](https://godbolt.org/z/b7rqhq5Kh)): +- Made `format_as` work with any user-defined type and not just enums. + For example ([godbolt](https://godbolt.org/z/b7rqhq5Kh)): - ```c++ - #include + ```c++ + #include - struct floaty_mc_floatface { - double value; - }; + struct floaty_mc_floatface { + double value; + }; - auto format_as(floaty_mc_floatface f) { return f.value; } + auto format_as(floaty_mc_floatface f) { return f.value; } - int main() { - fmt::print("{:8}\n", floaty_mc_floatface{0.42}); // prints " 0.42" + int main() { + fmt::print("{:8}\n", floaty_mc_floatface{0.42}); // prints " 0.42" + } + ``` + +- Removed deprecated implicit conversions for enums and conversions to + primitive types for compatibility with `std::format` and to prevent + potential ODR violations. Use `format_as` instead. + +- Added support for fill, align and width to the time point formatter + (https://github.com/fmtlib/fmt/issues/3237, + https://github.com/fmtlib/fmt/pull/3260, + https://github.com/fmtlib/fmt/pull/3275). For example + ([godbolt](https://godbolt.org/z/rKP6MGz6c)): + + ```c++ + #include + + int main() { + // prints " 2023" + fmt::print("{:>8%Y}\n", std::chrono::system_clock::now()); + } + ``` + + Thanks @ShawnZhong. + +- Implemented formatting of subseconds + (https://github.com/fmtlib/fmt/issues/2207, + https://github.com/fmtlib/fmt/issues/3117, + https://github.com/fmtlib/fmt/pull/3115, + https://github.com/fmtlib/fmt/pull/3143, + https://github.com/fmtlib/fmt/pull/3144, + https://github.com/fmtlib/fmt/pull/3349). For example + ([godbolt](https://godbolt.org/z/45738oGEo)): + + ```c++ + #include + + int main() { + // prints 01.234567 + fmt::print("{:%S}\n", std::chrono::microseconds(1234567)); + } + ``` + + Thanks @patrickroocks @phprus and @BRevzin. + +- Added precision support to `%S` + (https://github.com/fmtlib/fmt/pull/3148). Thanks @SappyJoy + +- Added support for `std::utc_time` + (https://github.com/fmtlib/fmt/issues/3098, + https://github.com/fmtlib/fmt/pull/3110). Thanks @patrickroocks. + +- Switched formatting of `std::chrono::system_clock` from local time + to UTC for compatibility with the standard + (https://github.com/fmtlib/fmt/issues/3199, + https://github.com/fmtlib/fmt/pull/3230). Thanks @ned14. + +- Added support for `%Ez` and `%Oz` to chrono formatters. + (https://github.com/fmtlib/fmt/issues/3220, + https://github.com/fmtlib/fmt/pull/3222). Thanks @phprus. + +- Improved validation of format specifiers for `std::chrono::duration` + (https://github.com/fmtlib/fmt/issues/3219, + https://github.com/fmtlib/fmt/pull/3232). Thanks @ShawnZhong. + +- Fixed formatting of time points before the epoch + (https://github.com/fmtlib/fmt/issues/3117, + https://github.com/fmtlib/fmt/pull/3261). For example + ([godbolt](https://godbolt.org/z/f7bcznb3W)): + + ```c++ + #include + + int main() { + auto t = std::chrono::system_clock::from_time_t(0) - + std::chrono::milliseconds(250); + fmt::print("{:%S}\n", t); // prints 59.750000000 + } + ``` + + Thanks @ShawnZhong. + +- Experimental: implemented glibc extension for padding seconds, + minutes and hours + (https://github.com/fmtlib/fmt/issues/2959, + https://github.com/fmtlib/fmt/pull/3271). Thanks @ShawnZhong. + +- Added a formatter for `std::exception` + (https://github.com/fmtlib/fmt/issues/2977, + https://github.com/fmtlib/fmt/issues/3012, + https://github.com/fmtlib/fmt/pull/3062, + https://github.com/fmtlib/fmt/pull/3076, + https://github.com/fmtlib/fmt/pull/3119). For example + ([godbolt](https://godbolt.org/z/8xoWGs9e4)): + + ```c++ + #include + #include + + int main() { + try { + std::vector().at(0); + } catch(const std::exception& e) { + fmt::print("{}", e); } - ``` + } + ``` -- Removed deprecated implicit conversions for enums and conversions to - primitive types for compatibility with `std::format` and to prevent - potential ODR violations. Use `format_as` instead. + prints: -- Added support for fill, align and width to the time point formatter - (https://github.com/fmtlib/fmt/issues/3237, - https://github.com/fmtlib/fmt/pull/3260, - https://github.com/fmtlib/fmt/pull/3275). For example - ([godbolt](https://godbolt.org/z/rKP6MGz6c)): + vector::_M_range_check: __n (which is 0) >= this->size() (which is 0) - ```c++ - #include + on libstdc++. Thanks @zach2good and @phprus. - int main() { - // prints " 2023" - fmt::print("{:>8%Y}\n", std::chrono::system_clock::now()); - } - ``` +- Moved `std::error_code` formatter from `fmt/os.h` to `fmt/std.h`. + (https://github.com/fmtlib/fmt/pull/3125). Thanks @phprus. - Thanks @ShawnZhong. +- Added formatters for standard container adapters: + `std::priority_queue`, `std::queue` and `std::stack` + (https://github.com/fmtlib/fmt/issues/3215, + https://github.com/fmtlib/fmt/pull/3279). For example + ([godbolt](https://godbolt.org/z/74h1xY9qK)): -- Implemented formatting of subseconds - (https://github.com/fmtlib/fmt/issues/2207, - https://github.com/fmtlib/fmt/issues/3117, - https://github.com/fmtlib/fmt/pull/3115, - https://github.com/fmtlib/fmt/pull/3143, - https://github.com/fmtlib/fmt/pull/3144, - https://github.com/fmtlib/fmt/pull/3349). For example - ([godbolt](https://godbolt.org/z/45738oGEo)): + ```c++ + #include + #include + #include - ```c++ - #include + int main() { + auto s = std::stack>(); + for (auto b: {true, false, true}) s.push(b); + fmt::print("{}\n", s); // prints [true, false, true] + } + ``` - int main() { - // prints 01.234567 - fmt::print("{:%S}\n", std::chrono::microseconds(1234567)); - } - ``` + Thanks @ShawnZhong. - Thanks @patrickroocks @phprus and @BRevzin. +- Added a formatter for `std::optional` to `fmt/std.h` + (https://github.com/fmtlib/fmt/issues/1367, + https://github.com/fmtlib/fmt/pull/3303). + Thanks @tom-huntington. -- Added precision support to `%S` - (https://github.com/fmtlib/fmt/pull/3148). Thanks @SappyJoy +- Fixed formatting of valueless by exception variants + (https://github.com/fmtlib/fmt/pull/3347). Thanks @TheOmegaCarrot. -- Added support for `std::utc_time` - (https://github.com/fmtlib/fmt/issues/3098, - https://github.com/fmtlib/fmt/pull/3110). Thanks @patrickroocks. +- Made `fmt::ptr` accept `unique_ptr` with a custom deleter + (https://github.com/fmtlib/fmt/pull/3177). Thanks @hmbj. -- Switched formatting of `std::chrono::system_clock` from local time - to UTC for compatibility with the standard - (https://github.com/fmtlib/fmt/issues/3199, - https://github.com/fmtlib/fmt/pull/3230). Thanks @ned14. +- Fixed formatting of noncopyable ranges and nested ranges of chars + (https://github.com/fmtlib/fmt/pull/3158 + https://github.com/fmtlib/fmt/issues/3286, + https://github.com/fmtlib/fmt/pull/3290). Thanks @BRevzin. -- Added support for `%Ez` and `%Oz` to chrono formatters. - (https://github.com/fmtlib/fmt/issues/3220, - https://github.com/fmtlib/fmt/pull/3222). Thanks @phprus. +- Fixed issues with formatting of paths and ranges of paths + (https://github.com/fmtlib/fmt/issues/3319, + https://github.com/fmtlib/fmt/pull/3321 + https://github.com/fmtlib/fmt/issues/3322). Thanks @phprus. -- Improved validation of format specifiers for `std::chrono::duration` - (https://github.com/fmtlib/fmt/issues/3219, - https://github.com/fmtlib/fmt/pull/3232). Thanks @ShawnZhong. +- Improved handling of invalid Unicode in paths. -- Fixed formatting of time points before the epoch - (https://github.com/fmtlib/fmt/issues/3117, - https://github.com/fmtlib/fmt/pull/3261). For example - ([godbolt](https://godbolt.org/z/f7bcznb3W)): +- Enabled compile-time checks on Apple clang 14 and later + (https://github.com/fmtlib/fmt/pull/3331). Thanks @cloyce. - ```c++ - #include +- Improved compile-time checks of named arguments + (https://github.com/fmtlib/fmt/issues/3105, + https://github.com/fmtlib/fmt/pull/3214). Thanks @rbrich. - int main() { - auto t = std::chrono::system_clock::from_time_t(0) - - std::chrono::milliseconds(250); - fmt::print("{:%S}\n", t); // prints 59.750000000 - } - ``` +- Fixed formatting when both alignment and `0` are given + (https://github.com/fmtlib/fmt/issues/3236, + https://github.com/fmtlib/fmt/pull/3248). Thanks @ShawnZhong. - Thanks @ShawnZhong. +- Improved Unicode support in the experimental file API on Windows + (https://github.com/fmtlib/fmt/issues/3234, + https://github.com/fmtlib/fmt/pull/3293). Thanks @Fros1er. -- Experimental: implemented glibc extension for padding seconds, - minutes and hours - (https://github.com/fmtlib/fmt/issues/2959, - https://github.com/fmtlib/fmt/pull/3271). Thanks @ShawnZhong. +- Unified UTF transcoding + (https://github.com/fmtlib/fmt/pull/3416). Thanks @phprus. -- Added a formatter for `std::exception` - (https://github.com/fmtlib/fmt/issues/2977, - https://github.com/fmtlib/fmt/issues/3012, - https://github.com/fmtlib/fmt/pull/3062, - https://github.com/fmtlib/fmt/pull/3076, - https://github.com/fmtlib/fmt/pull/3119). For example - ([godbolt](https://godbolt.org/z/8xoWGs9e4)): +- Added support for UTF-8 digit separators via an experimental locale + facet (https://github.com/fmtlib/fmt/issues/1861). For + example ([godbolt](https://godbolt.org/z/f7bcznb3W)): - ```c++ - #include - #include + ```c++ + auto loc = std::locale( + std::locale(), new fmt::format_facet("’")); + auto s = fmt::format(loc, "{:L}", 1000); + ``` - int main() { - try { - std::vector().at(0); - } catch(const std::exception& e) { - fmt::print("{}", e); - } - } - ``` + where `’` is U+2019 used as a digit separator in the de_CH locale. - prints: +- Added an overload of `formatted_size` that takes a locale + (https://github.com/fmtlib/fmt/issues/3084, + https://github.com/fmtlib/fmt/pull/3087). Thanks @gerboengels. - vector::_M_range_check: __n (which is 0) >= this->size() (which is 0) +- Removed the deprecated `FMT_DEPRECATED_OSTREAM`. - on libstdc++. Thanks @zach2good and @phprus. +- Fixed a UB when using a null `std::string_view` with + `fmt::to_string` or format string compilation + (https://github.com/fmtlib/fmt/issues/3241, + https://github.com/fmtlib/fmt/pull/3244). Thanks @phprus. -- Moved `std::error_code` formatter from `fmt/os.h` to `fmt/std.h`. - (https://github.com/fmtlib/fmt/pull/3125). Thanks @phprus. +- Added `starts_with` to the fallback `string_view` implementation + (https://github.com/fmtlib/fmt/pull/3080). Thanks @phprus. -- Added formatters for standard container adapters: - `std::priority_queue`, `std::queue` and `std::stack` - (https://github.com/fmtlib/fmt/issues/3215, - https://github.com/fmtlib/fmt/pull/3279). For example - ([godbolt](https://godbolt.org/z/74h1xY9qK)): +- Added `fmt::basic_format_string::get()` for compatibility with + `basic_format_string` + (https://github.com/fmtlib/fmt/pull/3111). Thanks @huangqinjin. - ```c++ - #include - #include - #include +- Added `println` for compatibility with C++23 + (https://github.com/fmtlib/fmt/pull/3267). Thanks @ShawnZhong. - int main() { - auto s = std::stack>(); - for (auto b: {true, false, true}) s.push(b); - fmt::print("{}\n", s); // prints [true, false, true] - } - ``` +- Renamed the `FMT_EXPORT` macro for shared library usage to + `FMT_LIB_EXPORT`. - Thanks @ShawnZhong. +- Improved documentation + (https://github.com/fmtlib/fmt/issues/3108, + https://github.com/fmtlib/fmt/issues/3169, + https://github.com/fmtlib/fmt/pull/3243). + https://github.com/fmtlib/fmt/pull/3404, + https://github.com/fmtlib/fmt/pull/4002). + Thanks @Cleroth, @Vertexwahn and @yujincheng08. -- Added a formatter for `std::optional` to `fmt/std.h` - (https://github.com/fmtlib/fmt/issues/1367, - https://github.com/fmtlib/fmt/pull/3303). - Thanks @tom-huntington. +- Improved build configuration and tests + (https://github.com/fmtlib/fmt/pull/3118, + https://github.com/fmtlib/fmt/pull/3120, + https://github.com/fmtlib/fmt/pull/3188, + https://github.com/fmtlib/fmt/issues/3189, + https://github.com/fmtlib/fmt/pull/3198, + https://github.com/fmtlib/fmt/pull/3205, + https://github.com/fmtlib/fmt/pull/3207, + https://github.com/fmtlib/fmt/pull/3210, + https://github.com/fmtlib/fmt/pull/3240, + https://github.com/fmtlib/fmt/pull/3256, + https://github.com/fmtlib/fmt/pull/3264, + https://github.com/fmtlib/fmt/issues/3299, + https://github.com/fmtlib/fmt/pull/3302, + https://github.com/fmtlib/fmt/pull/3312, + https://github.com/fmtlib/fmt/issues/3317, + https://github.com/fmtlib/fmt/pull/3328, + https://github.com/fmtlib/fmt/pull/3333, + https://github.com/fmtlib/fmt/pull/3369, + https://github.com/fmtlib/fmt/issues/3373, + https://github.com/fmtlib/fmt/pull/3395, + https://github.com/fmtlib/fmt/pull/3406, + https://github.com/fmtlib/fmt/pull/3411). + Thanks @dimztimz, @phprus, @DavidKorczynski, @ChrisThrasher, + @FrancoisCarouge, @kennyweiss, @luzpaz, @codeinred, @Mixaill, @joycebrum, + @kevinhwang and @Vertexwahn. -- Fixed formatting of valueless by exception variants - (https://github.com/fmtlib/fmt/pull/3347). Thanks @TheOmegaCarrot. +- Fixed a regression in handling empty format specifiers after a colon + (`{:}`) (https://github.com/fmtlib/fmt/pull/3086). Thanks @oxidase. -- Made `fmt::ptr` accept `unique_ptr` with a custom deleter - (https://github.com/fmtlib/fmt/pull/3177). Thanks @hmbj. +- Worked around a broken implementation of + `std::is_constant_evaluated` in some versions of libstdc++ on clang + (https://github.com/fmtlib/fmt/issues/3247, + https://github.com/fmtlib/fmt/pull/3281). Thanks @phprus. -- Fixed formatting of noncopyable ranges and nested ranges of chars - (https://github.com/fmtlib/fmt/pull/3158 - https://github.com/fmtlib/fmt/issues/3286, - https://github.com/fmtlib/fmt/pull/3290). Thanks @BRevzin. +- Fixed formatting of volatile variables + (https://github.com/fmtlib/fmt/pull/3068). -- Fixed issues with formatting of paths and ranges of paths - (https://github.com/fmtlib/fmt/issues/3319, - https://github.com/fmtlib/fmt/pull/3321 - https://github.com/fmtlib/fmt/issues/3322). Thanks @phprus. - -- Improved handling of invalid Unicode in paths. - -- Enabled compile-time checks on Apple clang 14 and later - (https://github.com/fmtlib/fmt/pull/3331). Thanks @cloyce. - -- Improved compile-time checks of named arguments - (https://github.com/fmtlib/fmt/issues/3105, - https://github.com/fmtlib/fmt/pull/3214). Thanks @rbrich. - -- Fixed formatting when both alignment and `0` are given - (https://github.com/fmtlib/fmt/issues/3236, - https://github.com/fmtlib/fmt/pull/3248). Thanks @ShawnZhong. - -- Improved Unicode support in the experimental file API on Windows - (https://github.com/fmtlib/fmt/issues/3234, - https://github.com/fmtlib/fmt/pull/3293). Thanks @Fros1er. - -- Unified UTF transcoding - (https://github.com/fmtlib/fmt/pull/3416). Thanks @phprus. - -- Added support for UTF-8 digit separators via an experimental locale - facet (https://github.com/fmtlib/fmt/issues/1861). For - example ([godbolt](https://godbolt.org/z/f7bcznb3W)): - - ```c++ - auto loc = std::locale( - std::locale(), new fmt::format_facet("’")); - auto s = fmt::format(loc, "{:L}", 1000); - ``` - - where `’` is U+2019 used as a digit separator in the de_CH locale. - -- Added an overload of `formatted_size` that takes a locale - (https://github.com/fmtlib/fmt/issues/3084, - https://github.com/fmtlib/fmt/pull/3087). Thanks @gerboengels. - -- Removed the deprecated `FMT_DEPRECATED_OSTREAM`. - -- Fixed a UB when using a null `std::string_view` with - `fmt::to_string` or format string compilation - (https://github.com/fmtlib/fmt/issues/3241, - https://github.com/fmtlib/fmt/pull/3244). Thanks @phprus. - -- Added `starts_with` to the fallback `string_view` implementation - (https://github.com/fmtlib/fmt/pull/3080). Thanks @phprus. - -- Added `fmt::basic_format_string::get()` for compatibility with - `basic_format_string` - (https://github.com/fmtlib/fmt/pull/3111). Thanks @huangqinjin. - -- Added `println` for compatibility with C++23 - (https://github.com/fmtlib/fmt/pull/3267). Thanks @ShawnZhong. - -- Renamed the `FMT_EXPORT` macro for shared library usage to - `FMT_LIB_EXPORT`. - -- Improved documentation - (https://github.com/fmtlib/fmt/issues/3108, - https://github.com/fmtlib/fmt/issues/3169, - https://github.com/fmtlib/fmt/pull/3243). - https://github.com/fmtlib/fmt/pull/3404). - Thanks @Cleroth and @Vertexwahn. - -- Improved build configuration and tests - (https://github.com/fmtlib/fmt/pull/3118, - https://github.com/fmtlib/fmt/pull/3120, - https://github.com/fmtlib/fmt/pull/3188, - https://github.com/fmtlib/fmt/issues/3189, - https://github.com/fmtlib/fmt/pull/3198, - https://github.com/fmtlib/fmt/pull/3205, - https://github.com/fmtlib/fmt/pull/3207, - https://github.com/fmtlib/fmt/pull/3210, - https://github.com/fmtlib/fmt/pull/3240, - https://github.com/fmtlib/fmt/pull/3256, - https://github.com/fmtlib/fmt/pull/3264, - https://github.com/fmtlib/fmt/issues/3299, - https://github.com/fmtlib/fmt/pull/3302, - https://github.com/fmtlib/fmt/pull/3312, - https://github.com/fmtlib/fmt/issues/3317, - https://github.com/fmtlib/fmt/pull/3328, - https://github.com/fmtlib/fmt/pull/3333, - https://github.com/fmtlib/fmt/pull/3369, - https://github.com/fmtlib/fmt/issues/3373, - https://github.com/fmtlib/fmt/pull/3395, - https://github.com/fmtlib/fmt/pull/3406, - https://github.com/fmtlib/fmt/pull/3411). - Thanks @dimztimz, @phprus, @DavidKorczynski, @ChrisThrasher, - @FrancoisCarouge, @kennyweiss, @luzpaz, @codeinred, @Mixaill, @joycebrum, - @kevinhwang and @Vertexwahn. - -- Fixed a regression in handling empty format specifiers after a colon - (`{:}`) (https://github.com/fmtlib/fmt/pull/3086). Thanks @oxidase. - -- Worked around a broken implementation of - `std::is_constant_evaluated` in some versions of libstdc++ on clang - (https://github.com/fmtlib/fmt/issues/3247, - https://github.com/fmtlib/fmt/pull/3281). Thanks @phprus. - -- Fixed formatting of volatile variables - (https://github.com/fmtlib/fmt/pull/3068). - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/pull/3057, - https://github.com/fmtlib/fmt/pull/3066, - https://github.com/fmtlib/fmt/pull/3072, - https://github.com/fmtlib/fmt/pull/3082, - https://github.com/fmtlib/fmt/pull/3091, - https://github.com/fmtlib/fmt/issues/3092, - https://github.com/fmtlib/fmt/pull/3093, - https://github.com/fmtlib/fmt/pull/3095, - https://github.com/fmtlib/fmt/issues/3096, - https://github.com/fmtlib/fmt/pull/3097, - https://github.com/fmtlib/fmt/issues/3128, - https://github.com/fmtlib/fmt/pull/3129, - https://github.com/fmtlib/fmt/pull/3137, - https://github.com/fmtlib/fmt/pull/3139, - https://github.com/fmtlib/fmt/issues/3140, - https://github.com/fmtlib/fmt/pull/3142, - https://github.com/fmtlib/fmt/issues/3149, - https://github.com/fmtlib/fmt/pull/3150, - https://github.com/fmtlib/fmt/issues/3154, - https://github.com/fmtlib/fmt/issues/3163, - https://github.com/fmtlib/fmt/issues/3178, - https://github.com/fmtlib/fmt/pull/3184, - https://github.com/fmtlib/fmt/pull/3196, - https://github.com/fmtlib/fmt/issues/3204, - https://github.com/fmtlib/fmt/pull/3206, - https://github.com/fmtlib/fmt/pull/3208, - https://github.com/fmtlib/fmt/issues/3213, - https://github.com/fmtlib/fmt/pull/3216, - https://github.com/fmtlib/fmt/issues/3224, - https://github.com/fmtlib/fmt/issues/3226, - https://github.com/fmtlib/fmt/issues/3228, - https://github.com/fmtlib/fmt/pull/3229, - https://github.com/fmtlib/fmt/pull/3259, - https://github.com/fmtlib/fmt/issues/3274, - https://github.com/fmtlib/fmt/issues/3287, - https://github.com/fmtlib/fmt/pull/3288, - https://github.com/fmtlib/fmt/issues/3292, - https://github.com/fmtlib/fmt/pull/3295, - https://github.com/fmtlib/fmt/pull/3296, - https://github.com/fmtlib/fmt/issues/3298, - https://github.com/fmtlib/fmt/issues/3325, - https://github.com/fmtlib/fmt/pull/3326, - https://github.com/fmtlib/fmt/issues/3334, - https://github.com/fmtlib/fmt/issues/3342, - https://github.com/fmtlib/fmt/pull/3343, - https://github.com/fmtlib/fmt/issues/3351, - https://github.com/fmtlib/fmt/pull/3352, - https://github.com/fmtlib/fmt/pull/3362, - https://github.com/fmtlib/fmt/issues/3365, - https://github.com/fmtlib/fmt/pull/3366, - https://github.com/fmtlib/fmt/pull/3374, - https://github.com/fmtlib/fmt/issues/3377, - https://github.com/fmtlib/fmt/pull/3378, - https://github.com/fmtlib/fmt/issues/3381, - https://github.com/fmtlib/fmt/pull/3398, - https://github.com/fmtlib/fmt/pull/3413, - https://github.com/fmtlib/fmt/issues/3415). - Thanks @phprus, @gsjaardema, @NewbieOrange, @EngineLessCC, @asmaloney, - @HazardyKnusperkeks, @sergiud, @Youw, @thesmurph, @czudziakm, - @Roman-Koshelev, @chronoxor, @ShawnZhong, @russelltg, @glebm, @tmartin-gh, - @Zhaojun-Liu, @louiswins and @mogemimi. +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/3057, + https://github.com/fmtlib/fmt/pull/3066, + https://github.com/fmtlib/fmt/pull/3072, + https://github.com/fmtlib/fmt/pull/3082, + https://github.com/fmtlib/fmt/pull/3091, + https://github.com/fmtlib/fmt/issues/3092, + https://github.com/fmtlib/fmt/pull/3093, + https://github.com/fmtlib/fmt/pull/3095, + https://github.com/fmtlib/fmt/issues/3096, + https://github.com/fmtlib/fmt/pull/3097, + https://github.com/fmtlib/fmt/issues/3128, + https://github.com/fmtlib/fmt/pull/3129, + https://github.com/fmtlib/fmt/pull/3137, + https://github.com/fmtlib/fmt/pull/3139, + https://github.com/fmtlib/fmt/issues/3140, + https://github.com/fmtlib/fmt/pull/3142, + https://github.com/fmtlib/fmt/issues/3149, + https://github.com/fmtlib/fmt/pull/3150, + https://github.com/fmtlib/fmt/issues/3154, + https://github.com/fmtlib/fmt/issues/3163, + https://github.com/fmtlib/fmt/issues/3178, + https://github.com/fmtlib/fmt/pull/3184, + https://github.com/fmtlib/fmt/pull/3196, + https://github.com/fmtlib/fmt/issues/3204, + https://github.com/fmtlib/fmt/pull/3206, + https://github.com/fmtlib/fmt/pull/3208, + https://github.com/fmtlib/fmt/issues/3213, + https://github.com/fmtlib/fmt/pull/3216, + https://github.com/fmtlib/fmt/issues/3224, + https://github.com/fmtlib/fmt/issues/3226, + https://github.com/fmtlib/fmt/issues/3228, + https://github.com/fmtlib/fmt/pull/3229, + https://github.com/fmtlib/fmt/pull/3259, + https://github.com/fmtlib/fmt/issues/3274, + https://github.com/fmtlib/fmt/issues/3287, + https://github.com/fmtlib/fmt/pull/3288, + https://github.com/fmtlib/fmt/issues/3292, + https://github.com/fmtlib/fmt/pull/3295, + https://github.com/fmtlib/fmt/pull/3296, + https://github.com/fmtlib/fmt/issues/3298, + https://github.com/fmtlib/fmt/issues/3325, + https://github.com/fmtlib/fmt/pull/3326, + https://github.com/fmtlib/fmt/issues/3334, + https://github.com/fmtlib/fmt/issues/3342, + https://github.com/fmtlib/fmt/pull/3343, + https://github.com/fmtlib/fmt/issues/3351, + https://github.com/fmtlib/fmt/pull/3352, + https://github.com/fmtlib/fmt/pull/3362, + https://github.com/fmtlib/fmt/issues/3365, + https://github.com/fmtlib/fmt/pull/3366, + https://github.com/fmtlib/fmt/pull/3374, + https://github.com/fmtlib/fmt/issues/3377, + https://github.com/fmtlib/fmt/pull/3378, + https://github.com/fmtlib/fmt/issues/3381, + https://github.com/fmtlib/fmt/pull/3398, + https://github.com/fmtlib/fmt/pull/3413, + https://github.com/fmtlib/fmt/issues/3415). + Thanks @phprus, @gsjaardema, @NewbieOrange, @EngineLessCC, @asmaloney, + @HazardyKnusperkeks, @sergiud, @Youw, @thesmurph, @czudziakm, + @Roman-Koshelev, @chronoxor, @ShawnZhong, @russelltg, @glebm, @tmartin-gh, + @Zhaojun-Liu, @louiswins and @mogemimi. # 9.1.0 - 2022-08-27 -- `fmt::formatted_size` now works at compile time - (https://github.com/fmtlib/fmt/pull/3026). For example - ([godbolt](https://godbolt.org/z/1MW5rMdf8)): +- `fmt::formatted_size` now works at compile time + (https://github.com/fmtlib/fmt/pull/3026). For example + ([godbolt](https://godbolt.org/z/1MW5rMdf8)): - ```c++ - #include + ```c++ + #include - int main() { - using namespace fmt::literals; - constexpr size_t n = fmt::formatted_size("{}"_cf, 42); - fmt::print("{}\n", n); // prints 2 - } - ``` + int main() { + using namespace fmt::literals; + constexpr size_t n = fmt::formatted_size("{}"_cf, 42); + fmt::print("{}\n", n); // prints 2 + } + ``` - Thanks @marksantaniello. + Thanks @marksantaniello. -- Fixed handling of invalid UTF-8 - (https://github.com/fmtlib/fmt/pull/3038, - https://github.com/fmtlib/fmt/pull/3044, - https://github.com/fmtlib/fmt/pull/3056). - Thanks @phprus and @skeeto. +- Fixed handling of invalid UTF-8 + (https://github.com/fmtlib/fmt/pull/3038, + https://github.com/fmtlib/fmt/pull/3044, + https://github.com/fmtlib/fmt/pull/3056). + Thanks @phprus and @skeeto. -- Improved Unicode support in `ostream` overloads of `print` - (https://github.com/fmtlib/fmt/pull/2994, - https://github.com/fmtlib/fmt/pull/3001, - https://github.com/fmtlib/fmt/pull/3025). Thanks @dimztimz. +- Improved Unicode support in `ostream` overloads of `print` + (https://github.com/fmtlib/fmt/pull/2994, + https://github.com/fmtlib/fmt/pull/3001, + https://github.com/fmtlib/fmt/pull/3025). Thanks @dimztimz. -- Fixed handling of the sign specifier in localized formatting on - systems with 32-bit `wchar_t` - (https://github.com/fmtlib/fmt/issues/3041). +- Fixed handling of the sign specifier in localized formatting on + systems with 32-bit `wchar_t` + (https://github.com/fmtlib/fmt/issues/3041). -- Added support for wide streams to `fmt::streamed` - (https://github.com/fmtlib/fmt/pull/2994). Thanks @phprus. +- Added support for wide streams to `fmt::streamed` + (https://github.com/fmtlib/fmt/pull/2994). Thanks @phprus. -- Added the `n` specifier that disables the output of delimiters when - formatting ranges (https://github.com/fmtlib/fmt/pull/2981, - https://github.com/fmtlib/fmt/pull/2983). For example - ([godbolt](https://godbolt.org/z/roKqGdj8c)): +- Added the `n` specifier that disables the output of delimiters when + formatting ranges (https://github.com/fmtlib/fmt/pull/2981, + https://github.com/fmtlib/fmt/pull/2983). For example + ([godbolt](https://godbolt.org/z/roKqGdj8c)): - ```c++ - #include - #include + ```c++ + #include + #include - int main() { - auto v = std::vector{1, 2, 3}; - fmt::print("{:n}\n", v); // prints 1, 2, 3 - } - ``` + int main() { + auto v = std::vector{1, 2, 3}; + fmt::print("{:n}\n", v); // prints 1, 2, 3 + } + ``` - Thanks @BRevzin. + Thanks @BRevzin. -- Worked around problematic `std::string_view` constructors introduced - in C++23 (https://github.com/fmtlib/fmt/issues/3030, - https://github.com/fmtlib/fmt/issues/3050). Thanks @strega-nil-ms. +- Worked around problematic `std::string_view` constructors introduced + in C++23 (https://github.com/fmtlib/fmt/issues/3030, + https://github.com/fmtlib/fmt/issues/3050). Thanks @strega-nil-ms. -- Improve handling (exclusion) of recursive ranges - (https://github.com/fmtlib/fmt/issues/2968, - https://github.com/fmtlib/fmt/pull/2974). Thanks @Dani-Hub. +- Improve handling (exclusion) of recursive ranges + (https://github.com/fmtlib/fmt/issues/2968, + https://github.com/fmtlib/fmt/pull/2974). Thanks @Dani-Hub. -- Improved error reporting in format string compilation - (https://github.com/fmtlib/fmt/issues/3055). +- Improved error reporting in format string compilation + (https://github.com/fmtlib/fmt/issues/3055). -- Improved the implementation of - [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm - used for the default floating-point formatting - (https://github.com/fmtlib/fmt/pull/2984). Thanks @jk-jeon. +- Improved the implementation of + [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm + used for the default floating-point formatting + (https://github.com/fmtlib/fmt/pull/2984). Thanks @jk-jeon. -- Fixed issues with floating-point formatting on exotic platforms. +- Fixed issues with floating-point formatting on exotic platforms. -- Improved the implementation of chrono formatting - (https://github.com/fmtlib/fmt/pull/3010). Thanks @phprus. +- Improved the implementation of chrono formatting + (https://github.com/fmtlib/fmt/pull/3010). Thanks @phprus. -- Improved documentation - (https://github.com/fmtlib/fmt/pull/2966, - https://github.com/fmtlib/fmt/pull/3009, - https://github.com/fmtlib/fmt/issues/3020, - https://github.com/fmtlib/fmt/pull/3037). - Thanks @mwinterb, @jcelerier and @remiburtin. +- Improved documentation + (https://github.com/fmtlib/fmt/pull/2966, + https://github.com/fmtlib/fmt/pull/3009, + https://github.com/fmtlib/fmt/issues/3020, + https://github.com/fmtlib/fmt/pull/3037). + Thanks @mwinterb, @jcelerier and @remiburtin. -- Improved build configuration - (https://github.com/fmtlib/fmt/pull/2991, - https://github.com/fmtlib/fmt/pull/2995, - https://github.com/fmtlib/fmt/issues/3004, - https://github.com/fmtlib/fmt/pull/3007, - https://github.com/fmtlib/fmt/pull/3040). - Thanks @dimztimz and @hwhsu1231. +- Improved build configuration + (https://github.com/fmtlib/fmt/pull/2991, + https://github.com/fmtlib/fmt/pull/2995, + https://github.com/fmtlib/fmt/issues/3004, + https://github.com/fmtlib/fmt/pull/3007, + https://github.com/fmtlib/fmt/pull/3040). + Thanks @dimztimz and @hwhsu1231. -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/issues/2969, - https://github.com/fmtlib/fmt/pull/2971, - https://github.com/fmtlib/fmt/issues/2975, - https://github.com/fmtlib/fmt/pull/2982, - https://github.com/fmtlib/fmt/pull/2985, - https://github.com/fmtlib/fmt/issues/2988, - https://github.com/fmtlib/fmt/issues/2989, - https://github.com/fmtlib/fmt/issues/3000, - https://github.com/fmtlib/fmt/issues/3006, - https://github.com/fmtlib/fmt/issues/3014, - https://github.com/fmtlib/fmt/issues/3015, - https://github.com/fmtlib/fmt/pull/3021, - https://github.com/fmtlib/fmt/issues/3023, - https://github.com/fmtlib/fmt/pull/3024, - https://github.com/fmtlib/fmt/pull/3029, - https://github.com/fmtlib/fmt/pull/3043, - https://github.com/fmtlib/fmt/issues/3052, - https://github.com/fmtlib/fmt/pull/3053, - https://github.com/fmtlib/fmt/pull/3054). - Thanks @h-friederich, @dimztimz, @olupton, @bernhardmgruber and @phprus. +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/2969, + https://github.com/fmtlib/fmt/pull/2971, + https://github.com/fmtlib/fmt/issues/2975, + https://github.com/fmtlib/fmt/pull/2982, + https://github.com/fmtlib/fmt/pull/2985, + https://github.com/fmtlib/fmt/issues/2988, + https://github.com/fmtlib/fmt/issues/2989, + https://github.com/fmtlib/fmt/issues/3000, + https://github.com/fmtlib/fmt/issues/3006, + https://github.com/fmtlib/fmt/issues/3014, + https://github.com/fmtlib/fmt/issues/3015, + https://github.com/fmtlib/fmt/pull/3021, + https://github.com/fmtlib/fmt/issues/3023, + https://github.com/fmtlib/fmt/pull/3024, + https://github.com/fmtlib/fmt/pull/3029, + https://github.com/fmtlib/fmt/pull/3043, + https://github.com/fmtlib/fmt/issues/3052, + https://github.com/fmtlib/fmt/pull/3053, + https://github.com/fmtlib/fmt/pull/3054). + Thanks @h-friederich, @dimztimz, @olupton, @bernhardmgruber and @phprus. # 9.0.0 - 2022-07-04 -- Switched to the internal floating point formatter for all decimal - presentation formats. In particular this results in consistent - rounding on all platforms and removing the `s[n]printf` fallback for - decimal FP formatting. +- Switched to the internal floating point formatter for all decimal + presentation formats. In particular this results in consistent + rounding on all platforms and removing the `s[n]printf` fallback for + decimal FP formatting. -- Compile-time floating point formatting no longer requires the - header-only mode. For example - ([godbolt](https://godbolt.org/z/G37PTeG3b)): +- Compile-time floating point formatting no longer requires the + header-only mode. For example + ([godbolt](https://godbolt.org/z/G37PTeG3b)): - ```c++ - #include - #include + ```c++ + #include + #include - consteval auto compile_time_dtoa(double value) -> std::array { - auto result = std::array(); - fmt::format_to(result.data(), FMT_COMPILE("{}"), value); - return result; + consteval auto compile_time_dtoa(double value) -> std::array { + auto result = std::array(); + fmt::format_to(result.data(), FMT_COMPILE("{}"), value); + return result; + } + + constexpr auto answer = compile_time_dtoa(0.42); + ``` + + works with the default settings. + +- Improved the implementation of + [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm + used for the default floating-point formatting + (https://github.com/fmtlib/fmt/pull/2713, + https://github.com/fmtlib/fmt/pull/2750). Thanks @jk-jeon. + +- Made `fmt::to_string` work with `__float128`. This uses the internal + FP formatter and works even on system without `__float128` support + in `[s]printf`. + +- Disabled automatic `std::ostream` insertion operator (`operator<<`) + discovery when `fmt/ostream.h` is included to prevent ODR + violations. You can get the old behavior by defining + `FMT_DEPRECATED_OSTREAM` but this will be removed in the next major + release. Use `fmt::streamed` or `fmt::ostream_formatter` to enable + formatting via `std::ostream` instead. + +- Added `fmt::ostream_formatter` that can be used to write `formatter` + specializations that perform formatting via `std::ostream`. For + example ([godbolt](https://godbolt.org/z/5sEc5qMsf)): + + ```c++ + #include + + struct date { + int year, month, day; + + friend std::ostream& operator<<(std::ostream& os, const date& d) { + return os << d.year << '-' << d.month << '-' << d.day; } + }; - constexpr auto answer = compile_time_dtoa(0.42); - ``` + template <> struct fmt::formatter : ostream_formatter {}; - works with the default settings. + std::string s = fmt::format("The date is {}", date{2012, 12, 9}); + // s == "The date is 2012-12-9" + ``` -- Improved the implementation of - [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm - used for the default floating-point formatting - (https://github.com/fmtlib/fmt/pull/2713, - https://github.com/fmtlib/fmt/pull/2750). Thanks @jk-jeon. +- Added the `fmt::streamed` function that takes an object and formats + it via `std::ostream`. For example + ([godbolt](https://godbolt.org/z/5G3346G1f)): -- Made `fmt::to_string` work with `__float128`. This uses the internal - FP formatter and works even on system without `__float128` support - in `[s]printf`. + ```c++ + #include + #include -- Disabled automatic `std::ostream` insertion operator (`operator<<`) - discovery when `fmt/ostream.h` is included to prevent ODR - violations. You can get the old behavior by defining - `FMT_DEPRECATED_OSTREAM` but this will be removed in the next major - release. Use `fmt::streamed` or `fmt::ostream_formatter` to enable - formatting via `std::ostream` instead. + int main() { + fmt::print("Current thread id: {}\n", + fmt::streamed(std::this_thread::get_id())); + } + ``` -- Added `fmt::ostream_formatter` that can be used to write `formatter` - specializations that perform formatting via `std::ostream`. For - example ([godbolt](https://godbolt.org/z/5sEc5qMsf)): + Note that `fmt/std.h` provides a `formatter` specialization for + `std::thread::id` so you don\'t need to format it via + `std::ostream`. - ```c++ - #include +- Deprecated implicit conversions of unscoped enums to integers for + consistency with scoped enums. - struct date { - int year, month, day; +- Added an argument-dependent lookup based `format_as` extension API + to simplify formatting of enums. - friend std::ostream& operator<<(std::ostream& os, const date& d) { - return os << d.year << '-' << d.month << '-' << d.day; - } - }; +- Added experimental `std::variant` formatting support + (https://github.com/fmtlib/fmt/pull/2941). For example + ([godbolt](https://godbolt.org/z/KG9z6cq68)): - template <> struct fmt::formatter : ostream_formatter {}; + ```c++ + #include + #include - std::string s = fmt::format("The date is {}", date{2012, 12, 9}); - // s == "The date is 2012-12-9" - ``` + int main() { + auto v = std::variant(42); + fmt::print("{}\n", v); + } + ``` -- Added the `fmt::streamed` function that takes an object and formats - it via `std::ostream`. For example - ([godbolt](https://godbolt.org/z/5G3346G1f)): + prints: - ```c++ - #include - #include + variant(42) - int main() { - fmt::print("Current thread id: {}\n", - fmt::streamed(std::this_thread::get_id())); - } - ``` + Thanks @jehelset. - Note that `fmt/std.h` provides a `formatter` specialization for - `std::thread::id` so you don\'t need to format it via - `std::ostream`. +- Added experimental `std::filesystem::path` formatting support + (https://github.com/fmtlib/fmt/issues/2865, + https://github.com/fmtlib/fmt/pull/2902, + https://github.com/fmtlib/fmt/issues/2917, + https://github.com/fmtlib/fmt/pull/2918). For example + ([godbolt](https://godbolt.org/z/o44dMexEb)): -- Deprecated implicit conversions of unscoped enums to integers for - consistency with scoped enums. + ```c++ + #include + #include -- Added an argument-dependent lookup based `format_as` extension API - to simplify formatting of enums. + int main() { + fmt::print("There is no place like {}.", std::filesystem::path("/home")); + } + ``` -- Added experimental `std::variant` formatting support - (https://github.com/fmtlib/fmt/pull/2941). For example - ([godbolt](https://godbolt.org/z/KG9z6cq68)): + prints: - ```c++ - #include - #include + There is no place like "/home". - int main() { - auto v = std::variant(42); - fmt::print("{}\n", v); - } - ``` + Thanks @phprus. - prints: +- Added a `std::thread::id` formatter to `fmt/std.h`. For example + ([godbolt](https://godbolt.org/z/j1azbYf3E)): - variant(42) + ```c++ + #include + #include - Thanks @jehelset. + int main() { + fmt::print("Current thread id: {}\n", std::this_thread::get_id()); + } + ``` -- Added experimental `std::filesystem::path` formatting support - (https://github.com/fmtlib/fmt/issues/2865, - https://github.com/fmtlib/fmt/pull/2902, - https://github.com/fmtlib/fmt/issues/2917, - https://github.com/fmtlib/fmt/pull/2918). For example - ([godbolt](https://godbolt.org/z/o44dMexEb)): +- Added `fmt::styled` that applies a text style to an individual + argument (https://github.com/fmtlib/fmt/pull/2793). For + example ([godbolt](https://godbolt.org/z/vWGW7v5M6)): - ```c++ - #include - #include + ```c++ + #include + #include - int main() { - fmt::print("There is no place like {}.", std::filesystem::path("/home")); - } - ``` + int main() { + auto now = std::chrono::system_clock::now(); + fmt::print( + "[{}] {}: {}\n", + fmt::styled(now, fmt::emphasis::bold), + fmt::styled("error", fg(fmt::color::red)), + "something went wrong"); + } + ``` - prints: + prints - There is no place like "/home". + ![](https://user-images.githubusercontent.com/576385/175071215-12809244-dab0-4005-96d8-7cd911c964d5.png) - Thanks @phprus. + Thanks @rbrugo. -- Added a `std::thread::id` formatter to `fmt/std.h`. For example - ([godbolt](https://godbolt.org/z/j1azbYf3E)): +- Made `fmt::print` overload for text styles correctly handle UTF-8 + (https://github.com/fmtlib/fmt/issues/2681, + https://github.com/fmtlib/fmt/pull/2701). Thanks @AlexGuteniev. - ```c++ - #include - #include +- Fixed Unicode handling when writing to an ostream. - int main() { - fmt::print("Current thread id: {}\n", std::this_thread::get_id()); - } - ``` +- Added support for nested specifiers to range formatting + (https://github.com/fmtlib/fmt/pull/2673). For example + ([godbolt](https://godbolt.org/z/xd3Gj38cf)): -- Added `fmt::styled` that applies a text style to an individual - argument (https://github.com/fmtlib/fmt/pull/2793). For - example ([godbolt](https://godbolt.org/z/vWGW7v5M6)): + ```c++ + #include + #include - ```c++ - #include - #include + int main() { + fmt::print("{::#x}\n", std::vector{10, 20, 30}); + } + ``` - int main() { - auto now = std::chrono::system_clock::now(); - fmt::print( - "[{}] {}: {}\n", - fmt::styled(now, fmt::emphasis::bold), - fmt::styled("error", fg(fmt::color::red)), - "something went wrong"); - } - ``` + prints `[0xa, 0x14, 0x1e]`. - prints - - ![](https://user-images.githubusercontent.com/576385/175071215-12809244-dab0-4005-96d8-7cd911c964d5.png) - - Thanks @rbrugo. - -- Made `fmt::print` overload for text styles correctly handle UTF-8 - (https://github.com/fmtlib/fmt/issues/2681, - https://github.com/fmtlib/fmt/pull/2701). Thanks @AlexGuteniev. - -- Fixed Unicode handling when writing to an ostream. - -- Added support for nested specifiers to range formatting - (https://github.com/fmtlib/fmt/pull/2673). For example - ([godbolt](https://godbolt.org/z/xd3Gj38cf)): - - ```c++ - #include - #include - - int main() { - fmt::print("{::#x}\n", std::vector{10, 20, 30}); - } - ``` - - prints `[0xa, 0x14, 0x1e]`. - - Thanks @BRevzin. - -- Implemented escaping of wide strings in ranges - (https://github.com/fmtlib/fmt/pull/2904). Thanks @phprus. - -- Added support for ranges with `begin` / `end` found via the - argument-dependent lookup - (https://github.com/fmtlib/fmt/pull/2807). Thanks @rbrugo. - -- Fixed formatting of certain kinds of ranges of ranges - (https://github.com/fmtlib/fmt/pull/2787). Thanks @BRevzin. - -- Fixed handling of maps with element types other than `std::pair` - (https://github.com/fmtlib/fmt/pull/2944). Thanks @BrukerJWD. - -- Made tuple formatter enabled only if elements are formattable - (https://github.com/fmtlib/fmt/issues/2939, - https://github.com/fmtlib/fmt/pull/2940). Thanks @jehelset. - -- Made `fmt::join` compatible with format string compilation - (https://github.com/fmtlib/fmt/issues/2719, - https://github.com/fmtlib/fmt/pull/2720). Thanks @phprus. - -- Made compile-time checks work with named arguments of custom types - and `std::ostream` `print` overloads - (https://github.com/fmtlib/fmt/issues/2816, - https://github.com/fmtlib/fmt/issues/2817, - https://github.com/fmtlib/fmt/pull/2819). Thanks @timsong-cpp. - -- Removed `make_args_checked` because it is no longer needed for - compile-time checks - (https://github.com/fmtlib/fmt/pull/2760). Thanks @phprus. - -- Removed the following deprecated APIs: `_format`, `arg_join`, the - `format_to` overload that takes a memory buffer, `[v]fprintf` that - takes an `ostream`. - -- Removed the deprecated implicit conversion of `[const] signed char*` - and `[const] unsigned char*` to C strings. - -- Removed the deprecated `fmt/locale.h`. - -- Replaced the deprecated `fileno()` with `descriptor()` in - `buffered_file`. - -- Moved `to_string_view` to the `detail` namespace since it\'s an - implementation detail. - -- Made access mode of a created file consistent with `fopen` by - setting `S_IWGRP` and `S_IWOTH` - (https://github.com/fmtlib/fmt/pull/2733). Thanks @arogge. - -- Removed a redundant buffer resize when formatting to `std::ostream` - (https://github.com/fmtlib/fmt/issues/2842, - https://github.com/fmtlib/fmt/pull/2843). Thanks @jcelerier. - -- Made precision computation for strings consistent with width - (https://github.com/fmtlib/fmt/issues/2888). - -- Fixed handling of locale separators in floating point formatting - (https://github.com/fmtlib/fmt/issues/2830). - -- Made sign specifiers work with `__int128_t` - (https://github.com/fmtlib/fmt/issues/2773). - -- Improved support for systems such as CHERI with extra data stored in - pointers (https://github.com/fmtlib/fmt/pull/2932). - Thanks @davidchisnall. - -- Improved documentation - (https://github.com/fmtlib/fmt/pull/2706, - https://github.com/fmtlib/fmt/pull/2712, - https://github.com/fmtlib/fmt/pull/2789, - https://github.com/fmtlib/fmt/pull/2803, - https://github.com/fmtlib/fmt/pull/2805, - https://github.com/fmtlib/fmt/pull/2815, - https://github.com/fmtlib/fmt/pull/2924). - Thanks @BRevzin, @Pokechu22, @setoye, @rtobar, @rbrugo, @anoonD and - @leha-bot. - -- Improved build configuration - (https://github.com/fmtlib/fmt/pull/2766, - https://github.com/fmtlib/fmt/pull/2772, - https://github.com/fmtlib/fmt/pull/2836, - https://github.com/fmtlib/fmt/pull/2852, - https://github.com/fmtlib/fmt/pull/2907, - https://github.com/fmtlib/fmt/pull/2913, - https://github.com/fmtlib/fmt/pull/2914). - Thanks @kambala-decapitator, @mattiasljungstrom, @kieselnb, @nathannaveen - and @Vertexwahn. - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/issues/2408, - https://github.com/fmtlib/fmt/issues/2507, - https://github.com/fmtlib/fmt/issues/2697, - https://github.com/fmtlib/fmt/issues/2715, - https://github.com/fmtlib/fmt/issues/2717, - https://github.com/fmtlib/fmt/pull/2722, - https://github.com/fmtlib/fmt/pull/2724, - https://github.com/fmtlib/fmt/pull/2725, - https://github.com/fmtlib/fmt/issues/2726, - https://github.com/fmtlib/fmt/pull/2728, - https://github.com/fmtlib/fmt/pull/2732, - https://github.com/fmtlib/fmt/issues/2738, - https://github.com/fmtlib/fmt/pull/2742, - https://github.com/fmtlib/fmt/issues/2744, - https://github.com/fmtlib/fmt/issues/2745, - https://github.com/fmtlib/fmt/issues/2746, - https://github.com/fmtlib/fmt/issues/2754, - https://github.com/fmtlib/fmt/pull/2755, - https://github.com/fmtlib/fmt/issues/2757, - https://github.com/fmtlib/fmt/pull/2758, - https://github.com/fmtlib/fmt/issues/2761, - https://github.com/fmtlib/fmt/pull/2762, - https://github.com/fmtlib/fmt/issues/2763, - https://github.com/fmtlib/fmt/pull/2765, - https://github.com/fmtlib/fmt/issues/2769, - https://github.com/fmtlib/fmt/pull/2770, - https://github.com/fmtlib/fmt/issues/2771, - https://github.com/fmtlib/fmt/issues/2777, - https://github.com/fmtlib/fmt/pull/2779, - https://github.com/fmtlib/fmt/pull/2782, - https://github.com/fmtlib/fmt/pull/2783, - https://github.com/fmtlib/fmt/issues/2794, - https://github.com/fmtlib/fmt/issues/2796, - https://github.com/fmtlib/fmt/pull/2797, - https://github.com/fmtlib/fmt/pull/2801, - https://github.com/fmtlib/fmt/pull/2802, - https://github.com/fmtlib/fmt/issues/2808, - https://github.com/fmtlib/fmt/issues/2818, - https://github.com/fmtlib/fmt/pull/2819, - https://github.com/fmtlib/fmt/issues/2829, - https://github.com/fmtlib/fmt/issues/2835, - https://github.com/fmtlib/fmt/issues/2848, - https://github.com/fmtlib/fmt/issues/2860, - https://github.com/fmtlib/fmt/pull/2861, - https://github.com/fmtlib/fmt/pull/2882, - https://github.com/fmtlib/fmt/issues/2886, - https://github.com/fmtlib/fmt/issues/2891, - https://github.com/fmtlib/fmt/pull/2892, - https://github.com/fmtlib/fmt/issues/2895, - https://github.com/fmtlib/fmt/issues/2896, - https://github.com/fmtlib/fmt/pull/2903, - https://github.com/fmtlib/fmt/issues/2906, - https://github.com/fmtlib/fmt/issues/2908, - https://github.com/fmtlib/fmt/pull/2909, - https://github.com/fmtlib/fmt/issues/2920, - https://github.com/fmtlib/fmt/pull/2922, - https://github.com/fmtlib/fmt/pull/2927, - https://github.com/fmtlib/fmt/pull/2929, - https://github.com/fmtlib/fmt/issues/2936, - https://github.com/fmtlib/fmt/pull/2937, - https://github.com/fmtlib/fmt/pull/2938, - https://github.com/fmtlib/fmt/pull/2951, - https://github.com/fmtlib/fmt/issues/2954, - https://github.com/fmtlib/fmt/pull/2957, - https://github.com/fmtlib/fmt/issues/2958, - https://github.com/fmtlib/fmt/pull/2960). - Thanks @matrackif @Tobi823, @ivan-volnov, @VasiliPupkin256, - @federico-busato, @barcharcraz, @jk-jeon, @HazardyKnusperkeks, @dalboris, - @seanm, @gsjaardema, @timsong-cpp, @seanm, @frithrah, @chronoxor, @Agga, - @madmaxoft, @JurajX, @phprus and @Dani-Hub. + Thanks @BRevzin. + +- Implemented escaping of wide strings in ranges + (https://github.com/fmtlib/fmt/pull/2904). Thanks @phprus. + +- Added support for ranges with `begin` / `end` found via the + argument-dependent lookup + (https://github.com/fmtlib/fmt/pull/2807). Thanks @rbrugo. + +- Fixed formatting of certain kinds of ranges of ranges + (https://github.com/fmtlib/fmt/pull/2787). Thanks @BRevzin. + +- Fixed handling of maps with element types other than `std::pair` + (https://github.com/fmtlib/fmt/pull/2944). Thanks @BrukerJWD. + +- Made tuple formatter enabled only if elements are formattable + (https://github.com/fmtlib/fmt/issues/2939, + https://github.com/fmtlib/fmt/pull/2940). Thanks @jehelset. + +- Made `fmt::join` compatible with format string compilation + (https://github.com/fmtlib/fmt/issues/2719, + https://github.com/fmtlib/fmt/pull/2720). Thanks @phprus. + +- Made compile-time checks work with named arguments of custom types + and `std::ostream` `print` overloads + (https://github.com/fmtlib/fmt/issues/2816, + https://github.com/fmtlib/fmt/issues/2817, + https://github.com/fmtlib/fmt/pull/2819). Thanks @timsong-cpp. + +- Removed `make_args_checked` because it is no longer needed for + compile-time checks + (https://github.com/fmtlib/fmt/pull/2760). Thanks @phprus. + +- Removed the following deprecated APIs: `_format`, `arg_join`, the + `format_to` overload that takes a memory buffer, `[v]fprintf` that + takes an `ostream`. + +- Removed the deprecated implicit conversion of `[const] signed char*` + and `[const] unsigned char*` to C strings. + +- Removed the deprecated `fmt/locale.h`. + +- Replaced the deprecated `fileno()` with `descriptor()` in + `buffered_file`. + +- Moved `to_string_view` to the `detail` namespace since it\'s an + implementation detail. + +- Made access mode of a created file consistent with `fopen` by + setting `S_IWGRP` and `S_IWOTH` + (https://github.com/fmtlib/fmt/pull/2733). Thanks @arogge. + +- Removed a redundant buffer resize when formatting to `std::ostream` + (https://github.com/fmtlib/fmt/issues/2842, + https://github.com/fmtlib/fmt/pull/2843). Thanks @jcelerier. + +- Made precision computation for strings consistent with width + (https://github.com/fmtlib/fmt/issues/2888). + +- Fixed handling of locale separators in floating point formatting + (https://github.com/fmtlib/fmt/issues/2830). + +- Made sign specifiers work with `__int128_t` + (https://github.com/fmtlib/fmt/issues/2773). + +- Improved support for systems such as CHERI with extra data stored in + pointers (https://github.com/fmtlib/fmt/pull/2932). + Thanks @davidchisnall. + +- Improved documentation + (https://github.com/fmtlib/fmt/pull/2706, + https://github.com/fmtlib/fmt/pull/2712, + https://github.com/fmtlib/fmt/pull/2789, + https://github.com/fmtlib/fmt/pull/2803, + https://github.com/fmtlib/fmt/pull/2805, + https://github.com/fmtlib/fmt/pull/2815, + https://github.com/fmtlib/fmt/pull/2924). + Thanks @BRevzin, @Pokechu22, @setoye, @rtobar, @rbrugo, @anoonD and + @leha-bot. + +- Improved build configuration + (https://github.com/fmtlib/fmt/pull/2766, + https://github.com/fmtlib/fmt/pull/2772, + https://github.com/fmtlib/fmt/pull/2836, + https://github.com/fmtlib/fmt/pull/2852, + https://github.com/fmtlib/fmt/pull/2907, + https://github.com/fmtlib/fmt/pull/2913, + https://github.com/fmtlib/fmt/pull/2914). + Thanks @kambala-decapitator, @mattiasljungstrom, @kieselnb, @nathannaveen + and @Vertexwahn. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/2408, + https://github.com/fmtlib/fmt/issues/2507, + https://github.com/fmtlib/fmt/issues/2697, + https://github.com/fmtlib/fmt/issues/2715, + https://github.com/fmtlib/fmt/issues/2717, + https://github.com/fmtlib/fmt/pull/2722, + https://github.com/fmtlib/fmt/pull/2724, + https://github.com/fmtlib/fmt/pull/2725, + https://github.com/fmtlib/fmt/issues/2726, + https://github.com/fmtlib/fmt/pull/2728, + https://github.com/fmtlib/fmt/pull/2732, + https://github.com/fmtlib/fmt/issues/2738, + https://github.com/fmtlib/fmt/pull/2742, + https://github.com/fmtlib/fmt/issues/2744, + https://github.com/fmtlib/fmt/issues/2745, + https://github.com/fmtlib/fmt/issues/2746, + https://github.com/fmtlib/fmt/issues/2754, + https://github.com/fmtlib/fmt/pull/2755, + https://github.com/fmtlib/fmt/issues/2757, + https://github.com/fmtlib/fmt/pull/2758, + https://github.com/fmtlib/fmt/issues/2761, + https://github.com/fmtlib/fmt/pull/2762, + https://github.com/fmtlib/fmt/issues/2763, + https://github.com/fmtlib/fmt/pull/2765, + https://github.com/fmtlib/fmt/issues/2769, + https://github.com/fmtlib/fmt/pull/2770, + https://github.com/fmtlib/fmt/issues/2771, + https://github.com/fmtlib/fmt/issues/2777, + https://github.com/fmtlib/fmt/pull/2779, + https://github.com/fmtlib/fmt/pull/2782, + https://github.com/fmtlib/fmt/pull/2783, + https://github.com/fmtlib/fmt/issues/2794, + https://github.com/fmtlib/fmt/issues/2796, + https://github.com/fmtlib/fmt/pull/2797, + https://github.com/fmtlib/fmt/pull/2801, + https://github.com/fmtlib/fmt/pull/2802, + https://github.com/fmtlib/fmt/issues/2808, + https://github.com/fmtlib/fmt/issues/2818, + https://github.com/fmtlib/fmt/pull/2819, + https://github.com/fmtlib/fmt/issues/2829, + https://github.com/fmtlib/fmt/issues/2835, + https://github.com/fmtlib/fmt/issues/2848, + https://github.com/fmtlib/fmt/issues/2860, + https://github.com/fmtlib/fmt/pull/2861, + https://github.com/fmtlib/fmt/pull/2882, + https://github.com/fmtlib/fmt/issues/2886, + https://github.com/fmtlib/fmt/issues/2891, + https://github.com/fmtlib/fmt/pull/2892, + https://github.com/fmtlib/fmt/issues/2895, + https://github.com/fmtlib/fmt/issues/2896, + https://github.com/fmtlib/fmt/pull/2903, + https://github.com/fmtlib/fmt/issues/2906, + https://github.com/fmtlib/fmt/issues/2908, + https://github.com/fmtlib/fmt/pull/2909, + https://github.com/fmtlib/fmt/issues/2920, + https://github.com/fmtlib/fmt/pull/2922, + https://github.com/fmtlib/fmt/pull/2927, + https://github.com/fmtlib/fmt/pull/2929, + https://github.com/fmtlib/fmt/issues/2936, + https://github.com/fmtlib/fmt/pull/2937, + https://github.com/fmtlib/fmt/pull/2938, + https://github.com/fmtlib/fmt/pull/2951, + https://github.com/fmtlib/fmt/issues/2954, + https://github.com/fmtlib/fmt/pull/2957, + https://github.com/fmtlib/fmt/issues/2958, + https://github.com/fmtlib/fmt/pull/2960). + Thanks @matrackif @Tobi823, @ivan-volnov, @VasiliPupkin256, + @federico-busato, @barcharcraz, @jk-jeon, @HazardyKnusperkeks, @dalboris, + @seanm, @gsjaardema, @timsong-cpp, @seanm, @frithrah, @chronoxor, @Agga, + @madmaxoft, @JurajX, @phprus and @Dani-Hub. # 8.1.1 - 2022-01-06 -- Restored ABI compatibility with version 8.0.x - (https://github.com/fmtlib/fmt/issues/2695, - https://github.com/fmtlib/fmt/pull/2696). Thanks @saraedum. -- Fixed chrono formatting on big endian systems - (https://github.com/fmtlib/fmt/issues/2698, - https://github.com/fmtlib/fmt/pull/2699). - Thanks @phprus and @xvitaly. -- Fixed a linkage error with mingw - (https://github.com/fmtlib/fmt/issues/2691, - https://github.com/fmtlib/fmt/pull/2692). Thanks @rbberger. +- Restored ABI compatibility with version 8.0.x + (https://github.com/fmtlib/fmt/issues/2695, + https://github.com/fmtlib/fmt/pull/2696). Thanks @saraedum. +- Fixed chrono formatting on big endian systems + (https://github.com/fmtlib/fmt/issues/2698, + https://github.com/fmtlib/fmt/pull/2699). + Thanks @phprus and @xvitaly. +- Fixed a linkage error with mingw + (https://github.com/fmtlib/fmt/issues/2691, + https://github.com/fmtlib/fmt/pull/2692). Thanks @rbberger. # 8.1.0 - 2022-01-02 -- Optimized chrono formatting - (https://github.com/fmtlib/fmt/pull/2500, - https://github.com/fmtlib/fmt/pull/2537, - https://github.com/fmtlib/fmt/issues/2541, - https://github.com/fmtlib/fmt/pull/2544, - https://github.com/fmtlib/fmt/pull/2550, - https://github.com/fmtlib/fmt/pull/2551, - https://github.com/fmtlib/fmt/pull/2576, - https://github.com/fmtlib/fmt/issues/2577, - https://github.com/fmtlib/fmt/pull/2586, - https://github.com/fmtlib/fmt/pull/2591, - https://github.com/fmtlib/fmt/pull/2594, - https://github.com/fmtlib/fmt/pull/2602, - https://github.com/fmtlib/fmt/pull/2617, - https://github.com/fmtlib/fmt/issues/2628, - https://github.com/fmtlib/fmt/pull/2633, - https://github.com/fmtlib/fmt/issues/2670, - https://github.com/fmtlib/fmt/pull/2671). +- Optimized chrono formatting + (https://github.com/fmtlib/fmt/pull/2500, + https://github.com/fmtlib/fmt/pull/2537, + https://github.com/fmtlib/fmt/issues/2541, + https://github.com/fmtlib/fmt/pull/2544, + https://github.com/fmtlib/fmt/pull/2550, + https://github.com/fmtlib/fmt/pull/2551, + https://github.com/fmtlib/fmt/pull/2576, + https://github.com/fmtlib/fmt/issues/2577, + https://github.com/fmtlib/fmt/pull/2586, + https://github.com/fmtlib/fmt/pull/2591, + https://github.com/fmtlib/fmt/pull/2594, + https://github.com/fmtlib/fmt/pull/2602, + https://github.com/fmtlib/fmt/pull/2617, + https://github.com/fmtlib/fmt/issues/2628, + https://github.com/fmtlib/fmt/pull/2633, + https://github.com/fmtlib/fmt/issues/2670, + https://github.com/fmtlib/fmt/pull/2671). - Processing of some specifiers such as `%z` and `%Y` is now up to - 10-20 times faster, for example on GCC 11 with libstdc++: + Processing of some specifiers such as `%z` and `%Y` is now up to + 10-20 times faster, for example on GCC 11 with libstdc++: - ---------------------------------------------------------------------------- - Benchmark Before After - ---------------------------------------------------------------------------- - FMTFormatter_z 261 ns 26.3 ns - FMTFormatterCompile_z 246 ns 11.6 ns - FMTFormatter_Y 263 ns 26.1 ns - FMTFormatterCompile_Y 244 ns 10.5 ns - ---------------------------------------------------------------------------- + ---------------------------------------------------------------------------- + Benchmark Before After + ---------------------------------------------------------------------------- + FMTFormatter_z 261 ns 26.3 ns + FMTFormatterCompile_z 246 ns 11.6 ns + FMTFormatter_Y 263 ns 26.1 ns + FMTFormatterCompile_Y 244 ns 10.5 ns + ---------------------------------------------------------------------------- - Thanks @phprus and @toughengineer. + Thanks @phprus and @toughengineer. -- Implemented subsecond formatting for chrono durations - (https://github.com/fmtlib/fmt/pull/2623). For example - ([godbolt](https://godbolt.org/z/es7vWTETe)): +- Implemented subsecond formatting for chrono durations + (https://github.com/fmtlib/fmt/pull/2623). For example + ([godbolt](https://godbolt.org/z/es7vWTETe)): - ```c++ - #include + ```c++ + #include - int main() { - fmt::print("{:%S}", std::chrono::milliseconds(1234)); - } - ``` + int main() { + fmt::print("{:%S}", std::chrono::milliseconds(1234)); + } + ``` - prints \"01.234\". + prints \"01.234\". - Thanks @matrackif. + Thanks @matrackif. -- Fixed handling of precision 0 when formatting chrono durations - (https://github.com/fmtlib/fmt/issues/2587, - https://github.com/fmtlib/fmt/pull/2588). Thanks @lukester1975. +- Fixed handling of precision 0 when formatting chrono durations + (https://github.com/fmtlib/fmt/issues/2587, + https://github.com/fmtlib/fmt/pull/2588). Thanks @lukester1975. -- Fixed an overflow on invalid inputs in the `tm` formatter - (https://github.com/fmtlib/fmt/pull/2564). Thanks @phprus. +- Fixed an overflow on invalid inputs in the `tm` formatter + (https://github.com/fmtlib/fmt/pull/2564). Thanks @phprus. -- Added `fmt::group_digits` that formats integers with a non-localized - digit separator (comma) for groups of three digits. For example - ([godbolt](https://godbolt.org/z/TxGxG9Poq)): +- Added `fmt::group_digits` that formats integers with a non-localized + digit separator (comma) for groups of three digits. For example + ([godbolt](https://godbolt.org/z/TxGxG9Poq)): - ```c++ - #include + ```c++ + #include - int main() { - fmt::print("{} dollars", fmt::group_digits(1000000)); - } - ``` + int main() { + fmt::print("{} dollars", fmt::group_digits(1000000)); + } + ``` - prints \"1,000,000 dollars\". + prints \"1,000,000 dollars\". -- Added support for faint, conceal, reverse and blink text styles - (https://github.com/fmtlib/fmt/pull/2394): +- Added support for faint, conceal, reverse and blink text styles + (https://github.com/fmtlib/fmt/pull/2394): - + - Thanks @benit8 and @data-man. + Thanks @benit8 and @data-man. -- Added experimental support for compile-time floating point - formatting (https://github.com/fmtlib/fmt/pull/2426, - https://github.com/fmtlib/fmt/pull/2470). It is currently - limited to the header-only mode. Thanks @alexezeder. +- Added experimental support for compile-time floating point + formatting (https://github.com/fmtlib/fmt/pull/2426, + https://github.com/fmtlib/fmt/pull/2470). It is currently + limited to the header-only mode. Thanks @alexezeder. -- Added UDL-based named argument support to compile-time format string - checks (https://github.com/fmtlib/fmt/issues/2640, - https://github.com/fmtlib/fmt/pull/2649). For example - ([godbolt](https://godbolt.org/z/ohGbbvonv)): +- Added UDL-based named argument support to compile-time format string + checks (https://github.com/fmtlib/fmt/issues/2640, + https://github.com/fmtlib/fmt/pull/2649). For example + ([godbolt](https://godbolt.org/z/ohGbbvonv)): - ```c++ - #include + ```c++ + #include - int main() { - using namespace fmt::literals; - fmt::print("{answer:s}", "answer"_a=42); - } - ``` + int main() { + using namespace fmt::literals; + fmt::print("{answer:s}", "answer"_a=42); + } + ``` - gives a compile-time error on compilers with C++20 `consteval` and - non-type template parameter support (gcc 10+) because `s` is not a - valid format specifier for an integer. + gives a compile-time error on compilers with C++20 `consteval` and + non-type template parameter support (gcc 10+) because `s` is not a + valid format specifier for an integer. - Thanks @alexezeder. + Thanks @alexezeder. -- Implemented escaping of string range elements. For example - ([godbolt](https://godbolt.org/z/rKvM1vKf3)): +- Implemented escaping of string range elements. For example + ([godbolt](https://godbolt.org/z/rKvM1vKf3)): - ```c++ - #include - #include + ```c++ + #include + #include - int main() { - fmt::print("{}", std::vector{"\naan"}); - } - ``` + int main() { + fmt::print("{}", std::vector{"\naan"}); + } + ``` - is now printed as: + is now printed as: - ["\naan"] + ["\naan"] - instead of: + instead of: - [" - aan"] + [" + aan"] -- Added an experimental `?` specifier for escaping strings. - (https://github.com/fmtlib/fmt/pull/2674). Thanks @BRevzin. +- Added an experimental `?` specifier for escaping strings. + (https://github.com/fmtlib/fmt/pull/2674). Thanks @BRevzin. -- Switched to JSON-like representation of maps and sets for - consistency with Python\'s `str.format`. For example - ([godbolt](https://godbolt.org/z/seKjoY9W5)): +- Switched to JSON-like representation of maps and sets for + consistency with Python\'s `str.format`. For example + ([godbolt](https://godbolt.org/z/seKjoY9W5)): - ```c++ - #include - #include + ```c++ + #include + #include - int main() { - fmt::print("{}", std::map{{"answer", 42}}); - } - ``` + int main() { + fmt::print("{}", std::map{{"answer", 42}}); + } + ``` - is now printed as: + is now printed as: - {"answer": 42} + {"answer": 42} -- Extended `fmt::join` to support C++20-only ranges - (https://github.com/fmtlib/fmt/pull/2549). Thanks @BRevzin. +- Extended `fmt::join` to support C++20-only ranges + (https://github.com/fmtlib/fmt/pull/2549). Thanks @BRevzin. -- Optimized handling of non-const-iterable ranges and implemented - initial support for non-const-formattable types. +- Optimized handling of non-const-iterable ranges and implemented + initial support for non-const-formattable types. -- Disabled implicit conversions of scoped enums to integers that was - accidentally introduced in earlier versions - (https://github.com/fmtlib/fmt/pull/1841). +- Disabled implicit conversions of scoped enums to integers that was + accidentally introduced in earlier versions + (https://github.com/fmtlib/fmt/pull/1841). -- Deprecated implicit conversion of `[const] signed char*` and - `[const] unsigned char*` to C strings. +- Deprecated implicit conversion of `[const] signed char*` and + `[const] unsigned char*` to C strings. -- Deprecated `_format`, a legacy UDL-based format API - (https://github.com/fmtlib/fmt/pull/2646). Thanks @alexezeder. +- Deprecated `_format`, a legacy UDL-based format API + (https://github.com/fmtlib/fmt/pull/2646). Thanks @alexezeder. -- Marked `format`, `formatted_size` and `to_string` as `[[nodiscard]]` - (https://github.com/fmtlib/fmt/pull/2612). @0x8000-0000. +- Marked `format`, `formatted_size` and `to_string` as `[[nodiscard]]` + (https://github.com/fmtlib/fmt/pull/2612). @0x8000-0000. -- Added missing diagnostic when trying to format function and member - pointers as well as objects convertible to pointers which is - explicitly disallowed - (https://github.com/fmtlib/fmt/issues/2598, - https://github.com/fmtlib/fmt/pull/2609, - https://github.com/fmtlib/fmt/pull/2610). Thanks @AlexGuteniev. +- Added missing diagnostic when trying to format function and member + pointers as well as objects convertible to pointers which is + explicitly disallowed + (https://github.com/fmtlib/fmt/issues/2598, + https://github.com/fmtlib/fmt/pull/2609, + https://github.com/fmtlib/fmt/pull/2610). Thanks @AlexGuteniev. -- Optimized writing to a contiguous buffer with `format_to_n` - (https://github.com/fmtlib/fmt/pull/2489). Thanks @Roman-Koshelev. +- Optimized writing to a contiguous buffer with `format_to_n` + (https://github.com/fmtlib/fmt/pull/2489). Thanks @Roman-Koshelev. -- Optimized writing to non-`char` buffers - (https://github.com/fmtlib/fmt/pull/2477). Thanks @Roman-Koshelev. +- Optimized writing to non-`char` buffers + (https://github.com/fmtlib/fmt/pull/2477). Thanks @Roman-Koshelev. -- Decimal point is now localized when using the `L` specifier. +- Decimal point is now localized when using the `L` specifier. -- Improved floating point formatter implementation - (https://github.com/fmtlib/fmt/pull/2498, - https://github.com/fmtlib/fmt/pull/2499). Thanks @Roman-Koshelev. +- Improved floating point formatter implementation + (https://github.com/fmtlib/fmt/pull/2498, + https://github.com/fmtlib/fmt/pull/2499). Thanks @Roman-Koshelev. -- Fixed handling of very large precision in fixed format - (https://github.com/fmtlib/fmt/pull/2616). +- Fixed handling of very large precision in fixed format + (https://github.com/fmtlib/fmt/pull/2616). -- Made a table of cached powers used in FP formatting static - (https://github.com/fmtlib/fmt/pull/2509). Thanks @jk-jeon. +- Made a table of cached powers used in FP formatting static + (https://github.com/fmtlib/fmt/pull/2509). Thanks @jk-jeon. -- Resolved a lookup ambiguity with C++20 format-related functions due - to ADL (https://github.com/fmtlib/fmt/issues/2639, - https://github.com/fmtlib/fmt/pull/2641). Thanks @mkurdej. +- Resolved a lookup ambiguity with C++20 format-related functions due + to ADL (https://github.com/fmtlib/fmt/issues/2639, + https://github.com/fmtlib/fmt/pull/2641). Thanks @mkurdej. -- Removed unnecessary inline namespace qualification - (https://github.com/fmtlib/fmt/issues/2642, - https://github.com/fmtlib/fmt/pull/2643). Thanks @mkurdej. +- Removed unnecessary inline namespace qualification + (https://github.com/fmtlib/fmt/issues/2642, + https://github.com/fmtlib/fmt/pull/2643). Thanks @mkurdej. -- Implemented argument forwarding in `format_to_n` - (https://github.com/fmtlib/fmt/issues/2462, - https://github.com/fmtlib/fmt/pull/2463). Thanks @owent. +- Implemented argument forwarding in `format_to_n` + (https://github.com/fmtlib/fmt/issues/2462, + https://github.com/fmtlib/fmt/pull/2463). Thanks @owent. -- Fixed handling of implicit conversions in `fmt::to_string` and - format string compilation - (https://github.com/fmtlib/fmt/issues/2565). +- Fixed handling of implicit conversions in `fmt::to_string` and + format string compilation + (https://github.com/fmtlib/fmt/issues/2565). -- Changed the default access mode of files created by - `fmt::output_file` to `-rw-r--r--` for consistency with `fopen` - (https://github.com/fmtlib/fmt/issues/2530). +- Changed the default access mode of files created by + `fmt::output_file` to `-rw-r--r--` for consistency with `fopen` + (https://github.com/fmtlib/fmt/issues/2530). -- Make `fmt::ostream::flush` public - (https://github.com/fmtlib/fmt/issues/2435). +- Make `fmt::ostream::flush` public + (https://github.com/fmtlib/fmt/issues/2435). -- Improved C++14/17 attribute detection - (https://github.com/fmtlib/fmt/pull/2615). Thanks @AlexGuteniev. +- Improved C++14/17 attribute detection + (https://github.com/fmtlib/fmt/pull/2615). Thanks @AlexGuteniev. -- Improved `consteval` detection for MSVC - (https://github.com/fmtlib/fmt/pull/2559). Thanks @DanielaE. +- Improved `consteval` detection for MSVC + (https://github.com/fmtlib/fmt/pull/2559). Thanks @DanielaE. -- Improved documentation - (https://github.com/fmtlib/fmt/issues/2406, - https://github.com/fmtlib/fmt/pull/2446, - https://github.com/fmtlib/fmt/issues/2493, - https://github.com/fmtlib/fmt/issues/2513, - https://github.com/fmtlib/fmt/pull/2515, - https://github.com/fmtlib/fmt/issues/2522, - https://github.com/fmtlib/fmt/pull/2562, - https://github.com/fmtlib/fmt/pull/2575, - https://github.com/fmtlib/fmt/pull/2606, - https://github.com/fmtlib/fmt/pull/2620, - https://github.com/fmtlib/fmt/issues/2676). - Thanks @sobolevn, @UnePierre, @zhsj, @phprus, @ericcurtin and @Lounarok. +- Improved documentation + (https://github.com/fmtlib/fmt/issues/2406, + https://github.com/fmtlib/fmt/pull/2446, + https://github.com/fmtlib/fmt/issues/2493, + https://github.com/fmtlib/fmt/issues/2513, + https://github.com/fmtlib/fmt/pull/2515, + https://github.com/fmtlib/fmt/issues/2522, + https://github.com/fmtlib/fmt/pull/2562, + https://github.com/fmtlib/fmt/pull/2575, + https://github.com/fmtlib/fmt/pull/2606, + https://github.com/fmtlib/fmt/pull/2620, + https://github.com/fmtlib/fmt/issues/2676). + Thanks @sobolevn, @UnePierre, @zhsj, @phprus, @ericcurtin and @Lounarok. -- Improved fuzzers and added a fuzzer for chrono timepoint formatting - (https://github.com/fmtlib/fmt/pull/2461, - https://github.com/fmtlib/fmt/pull/2469). @pauldreik, +- Improved fuzzers and added a fuzzer for chrono timepoint formatting + (https://github.com/fmtlib/fmt/pull/2461, + https://github.com/fmtlib/fmt/pull/2469). @pauldreik, -- Added the `FMT_SYSTEM_HEADERS` CMake option setting which marks - {fmt}\'s headers as system. It can be used to suppress warnings - (https://github.com/fmtlib/fmt/issues/2644, - https://github.com/fmtlib/fmt/pull/2651). Thanks @alexezeder. +- Added the `FMT_SYSTEM_HEADERS` CMake option setting which marks + {fmt}\'s headers as system. It can be used to suppress warnings + (https://github.com/fmtlib/fmt/issues/2644, + https://github.com/fmtlib/fmt/pull/2651). Thanks @alexezeder. -- Added the Bazel build system support - (https://github.com/fmtlib/fmt/pull/2505, - https://github.com/fmtlib/fmt/pull/2516). Thanks @Vertexwahn. +- Added the Bazel build system support + (https://github.com/fmtlib/fmt/pull/2505, + https://github.com/fmtlib/fmt/pull/2516). Thanks @Vertexwahn. -- Improved build configuration and tests - (https://github.com/fmtlib/fmt/issues/2437, - https://github.com/fmtlib/fmt/pull/2558, - https://github.com/fmtlib/fmt/pull/2648, - https://github.com/fmtlib/fmt/pull/2650, - https://github.com/fmtlib/fmt/pull/2663, - https://github.com/fmtlib/fmt/pull/2677). - Thanks @DanielaE, @alexezeder and @phprus. +- Improved build configuration and tests + (https://github.com/fmtlib/fmt/issues/2437, + https://github.com/fmtlib/fmt/pull/2558, + https://github.com/fmtlib/fmt/pull/2648, + https://github.com/fmtlib/fmt/pull/2650, + https://github.com/fmtlib/fmt/pull/2663, + https://github.com/fmtlib/fmt/pull/2677). + Thanks @DanielaE, @alexezeder and @phprus. -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/pull/2353, - https://github.com/fmtlib/fmt/pull/2356, - https://github.com/fmtlib/fmt/pull/2399, - https://github.com/fmtlib/fmt/issues/2408, - https://github.com/fmtlib/fmt/pull/2414, - https://github.com/fmtlib/fmt/pull/2427, - https://github.com/fmtlib/fmt/pull/2432, - https://github.com/fmtlib/fmt/pull/2442, - https://github.com/fmtlib/fmt/pull/2434, - https://github.com/fmtlib/fmt/issues/2439, - https://github.com/fmtlib/fmt/pull/2447, - https://github.com/fmtlib/fmt/pull/2450, - https://github.com/fmtlib/fmt/issues/2455, - https://github.com/fmtlib/fmt/issues/2465, - https://github.com/fmtlib/fmt/issues/2472, - https://github.com/fmtlib/fmt/issues/2474, - https://github.com/fmtlib/fmt/pull/2476, - https://github.com/fmtlib/fmt/issues/2478, - https://github.com/fmtlib/fmt/issues/2479, - https://github.com/fmtlib/fmt/issues/2481, - https://github.com/fmtlib/fmt/pull/2482, - https://github.com/fmtlib/fmt/pull/2483, - https://github.com/fmtlib/fmt/issues/2490, - https://github.com/fmtlib/fmt/pull/2491, - https://github.com/fmtlib/fmt/pull/2510, - https://github.com/fmtlib/fmt/pull/2518, - https://github.com/fmtlib/fmt/issues/2528, - https://github.com/fmtlib/fmt/pull/2529, - https://github.com/fmtlib/fmt/pull/2539, - https://github.com/fmtlib/fmt/issues/2540, - https://github.com/fmtlib/fmt/pull/2545, - https://github.com/fmtlib/fmt/pull/2555, - https://github.com/fmtlib/fmt/issues/2557, - https://github.com/fmtlib/fmt/issues/2570, - https://github.com/fmtlib/fmt/pull/2573, - https://github.com/fmtlib/fmt/pull/2582, - https://github.com/fmtlib/fmt/issues/2605, - https://github.com/fmtlib/fmt/pull/2611, - https://github.com/fmtlib/fmt/pull/2647, - https://github.com/fmtlib/fmt/issues/2627, - https://github.com/fmtlib/fmt/pull/2630, - https://github.com/fmtlib/fmt/issues/2635, - https://github.com/fmtlib/fmt/issues/2638, - https://github.com/fmtlib/fmt/issues/2653, - https://github.com/fmtlib/fmt/issues/2654, - https://github.com/fmtlib/fmt/issues/2661, - https://github.com/fmtlib/fmt/pull/2664, - https://github.com/fmtlib/fmt/pull/2684). - Thanks @DanielaE, @mwinterb, @cdacamar, @TrebledJ, @bodomartin, @cquammen, - @white238, @mmarkeloff, @palacaze, @jcelerier, @mborn-adi, @BrukerJWD, - @spyridon97, @phprus, @oliverlee, @joshessman-llnl, @akohlmey, @timkalu, - @olupton, @Acretock, @alexezeder, @andrewcorrigan, @lucpelletier and - @HazardyKnusperkeks. +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/pull/2353, + https://github.com/fmtlib/fmt/pull/2356, + https://github.com/fmtlib/fmt/pull/2399, + https://github.com/fmtlib/fmt/issues/2408, + https://github.com/fmtlib/fmt/pull/2414, + https://github.com/fmtlib/fmt/pull/2427, + https://github.com/fmtlib/fmt/pull/2432, + https://github.com/fmtlib/fmt/pull/2442, + https://github.com/fmtlib/fmt/pull/2434, + https://github.com/fmtlib/fmt/issues/2439, + https://github.com/fmtlib/fmt/pull/2447, + https://github.com/fmtlib/fmt/pull/2450, + https://github.com/fmtlib/fmt/issues/2455, + https://github.com/fmtlib/fmt/issues/2465, + https://github.com/fmtlib/fmt/issues/2472, + https://github.com/fmtlib/fmt/issues/2474, + https://github.com/fmtlib/fmt/pull/2476, + https://github.com/fmtlib/fmt/issues/2478, + https://github.com/fmtlib/fmt/issues/2479, + https://github.com/fmtlib/fmt/issues/2481, + https://github.com/fmtlib/fmt/pull/2482, + https://github.com/fmtlib/fmt/pull/2483, + https://github.com/fmtlib/fmt/issues/2490, + https://github.com/fmtlib/fmt/pull/2491, + https://github.com/fmtlib/fmt/pull/2510, + https://github.com/fmtlib/fmt/pull/2518, + https://github.com/fmtlib/fmt/issues/2528, + https://github.com/fmtlib/fmt/pull/2529, + https://github.com/fmtlib/fmt/pull/2539, + https://github.com/fmtlib/fmt/issues/2540, + https://github.com/fmtlib/fmt/pull/2545, + https://github.com/fmtlib/fmt/pull/2555, + https://github.com/fmtlib/fmt/issues/2557, + https://github.com/fmtlib/fmt/issues/2570, + https://github.com/fmtlib/fmt/pull/2573, + https://github.com/fmtlib/fmt/pull/2582, + https://github.com/fmtlib/fmt/issues/2605, + https://github.com/fmtlib/fmt/pull/2611, + https://github.com/fmtlib/fmt/pull/2647, + https://github.com/fmtlib/fmt/issues/2627, + https://github.com/fmtlib/fmt/pull/2630, + https://github.com/fmtlib/fmt/issues/2635, + https://github.com/fmtlib/fmt/issues/2638, + https://github.com/fmtlib/fmt/issues/2653, + https://github.com/fmtlib/fmt/issues/2654, + https://github.com/fmtlib/fmt/issues/2661, + https://github.com/fmtlib/fmt/pull/2664, + https://github.com/fmtlib/fmt/pull/2684). + Thanks @DanielaE, @mwinterb, @cdacamar, @TrebledJ, @bodomartin, @cquammen, + @white238, @mmarkeloff, @palacaze, @jcelerier, @mborn-adi, @BrukerJWD, + @spyridon97, @phprus, @oliverlee, @joshessman-llnl, @akohlmey, @timkalu, + @olupton, @Acretock, @alexezeder, @andrewcorrigan, @lucpelletier and + @HazardyKnusperkeks. # 8.0.1 - 2021-07-02 -- Fixed the version number in the inline namespace - (https://github.com/fmtlib/fmt/issues/2374). -- Added a missing presentation type check for `std::string` - (https://github.com/fmtlib/fmt/issues/2402). -- Fixed a linkage error when mixing code built with clang and gcc - (https://github.com/fmtlib/fmt/issues/2377). -- Fixed documentation issues - (https://github.com/fmtlib/fmt/pull/2396, - https://github.com/fmtlib/fmt/issues/2403, - https://github.com/fmtlib/fmt/issues/2406). Thanks @mkurdej. -- Removed dead code in FP formatter ( - https://github.com/fmtlib/fmt/pull/2398). Thanks @javierhonduco. -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/issues/2351, - https://github.com/fmtlib/fmt/issues/2359, - https://github.com/fmtlib/fmt/pull/2365, - https://github.com/fmtlib/fmt/issues/2368, - https://github.com/fmtlib/fmt/pull/2370, - https://github.com/fmtlib/fmt/pull/2376, - https://github.com/fmtlib/fmt/pull/2381, - https://github.com/fmtlib/fmt/pull/2382, - https://github.com/fmtlib/fmt/issues/2386, - https://github.com/fmtlib/fmt/pull/2389, - https://github.com/fmtlib/fmt/pull/2395, - https://github.com/fmtlib/fmt/pull/2397, - https://github.com/fmtlib/fmt/issues/2400, - https://github.com/fmtlib/fmt/issues/2401, - https://github.com/fmtlib/fmt/pull/2407). - Thanks @zx2c4, @AidanSun05, @mattiasljungstrom, @joemmett, @erengy, - @patlkli, @gsjaardema and @phprus. +- Fixed the version number in the inline namespace + (https://github.com/fmtlib/fmt/issues/2374). +- Added a missing presentation type check for `std::string` + (https://github.com/fmtlib/fmt/issues/2402). +- Fixed a linkage error when mixing code built with clang and gcc + (https://github.com/fmtlib/fmt/issues/2377). +- Fixed documentation issues + (https://github.com/fmtlib/fmt/pull/2396, + https://github.com/fmtlib/fmt/issues/2403, + https://github.com/fmtlib/fmt/issues/2406). Thanks @mkurdej. +- Removed dead code in FP formatter ( + https://github.com/fmtlib/fmt/pull/2398). Thanks @javierhonduco. +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/2351, + https://github.com/fmtlib/fmt/issues/2359, + https://github.com/fmtlib/fmt/pull/2365, + https://github.com/fmtlib/fmt/issues/2368, + https://github.com/fmtlib/fmt/pull/2370, + https://github.com/fmtlib/fmt/pull/2376, + https://github.com/fmtlib/fmt/pull/2381, + https://github.com/fmtlib/fmt/pull/2382, + https://github.com/fmtlib/fmt/issues/2386, + https://github.com/fmtlib/fmt/pull/2389, + https://github.com/fmtlib/fmt/pull/2395, + https://github.com/fmtlib/fmt/pull/2397, + https://github.com/fmtlib/fmt/issues/2400, + https://github.com/fmtlib/fmt/issues/2401, + https://github.com/fmtlib/fmt/pull/2407). + Thanks @zx2c4, @AidanSun05, @mattiasljungstrom, @joemmett, @erengy, + @patlkli, @gsjaardema and @phprus. # 8.0.0 - 2021-06-21 -- Enabled compile-time format string checks by default. For example - ([godbolt](https://godbolt.org/z/sMxcohGjz)): +- Enabled compile-time format string checks by default. For example + ([godbolt](https://godbolt.org/z/sMxcohGjz)): - ```c++ - #include + ```c++ + #include - int main() { - fmt::print("{:d}", "I am not a number"); + int main() { + fmt::print("{:d}", "I am not a number"); + } + ``` + + gives a compile-time error on compilers with C++20 `consteval` + support (gcc 10+, clang 11+) because `d` is not a valid format + specifier for a string. + + To pass a runtime string wrap it in `fmt::runtime`: + + ```c++ + fmt::print(fmt::runtime("{:d}"), "I am not a number"); + ``` + +- Added compile-time formatting + (https://github.com/fmtlib/fmt/pull/2019, + https://github.com/fmtlib/fmt/pull/2044, + https://github.com/fmtlib/fmt/pull/2056, + https://github.com/fmtlib/fmt/pull/2072, + https://github.com/fmtlib/fmt/pull/2075, + https://github.com/fmtlib/fmt/issues/2078, + https://github.com/fmtlib/fmt/pull/2129, + https://github.com/fmtlib/fmt/pull/2326). For example + ([godbolt](https://godbolt.org/z/Mxx9d89jM)): + + ```c++ + #include + + consteval auto compile_time_itoa(int value) -> std::array { + auto result = std::array(); + fmt::format_to(result.data(), FMT_COMPILE("{}"), value); + return result; + } + + constexpr auto answer = compile_time_itoa(42); + ``` + + Most of the formatting functionality is available at compile time + with a notable exception of floating-point numbers and pointers. + Thanks @alexezeder. + +- Optimized handling of format specifiers during format string + compilation. For example, hexadecimal formatting (`"{:x}"`) is now + 3-7x faster than before when using `format_to` with format string + compilation and a stack-allocated buffer + (https://github.com/fmtlib/fmt/issues/1944). + + Before (7.1.3): + + ---------------------------------------------------------------------------- + Benchmark Time CPU Iterations + ---------------------------------------------------------------------------- + FMTCompileOld/0 15.5 ns 15.5 ns 43302898 + FMTCompileOld/42 16.6 ns 16.6 ns 43278267 + FMTCompileOld/273123 18.7 ns 18.6 ns 37035861 + FMTCompileOld/9223372036854775807 19.4 ns 19.4 ns 35243000 + ---------------------------------------------------------------------------- + + After (8.x): + + ---------------------------------------------------------------------------- + Benchmark Time CPU Iterations + ---------------------------------------------------------------------------- + FMTCompileNew/0 1.99 ns 1.99 ns 360523686 + FMTCompileNew/42 2.33 ns 2.33 ns 279865664 + FMTCompileNew/273123 3.72 ns 3.71 ns 190230315 + FMTCompileNew/9223372036854775807 5.28 ns 5.26 ns 130711631 + ---------------------------------------------------------------------------- + + It is even faster than `std::to_chars` from libc++ compiled with + clang on macOS: + + ---------------------------------------------------------------------------- + Benchmark Time CPU Iterations + ---------------------------------------------------------------------------- + ToChars/0 4.42 ns 4.41 ns 160196630 + ToChars/42 5.00 ns 4.98 ns 140735201 + ToChars/273123 7.26 ns 7.24 ns 95784130 + ToChars/9223372036854775807 8.77 ns 8.75 ns 75872534 + ---------------------------------------------------------------------------- + + In other cases, especially involving `std::string` construction, the + speed up is usually lower because handling format specifiers takes a + smaller fraction of the total time. + +- Added the `_cf` user-defined literal to represent a compiled format + string. It can be used instead of the `FMT_COMPILE` macro + (https://github.com/fmtlib/fmt/pull/2043, + https://github.com/fmtlib/fmt/pull/2242): + + ```c++ + #include + + using namespace fmt::literals; + auto s = fmt::format(FMT_COMPILE("{}"), 42); // 🙁 not modern + auto s = fmt::format("{}"_cf, 42); // 🙂 modern as hell + ``` + + It requires compiler support for class types in non-type template + parameters (a C++20 feature) which is available in GCC 9.3+. + Thanks @alexezeder. + +- Format string compilation now requires `format` functions of + `formatter` specializations for user-defined types to be `const`: + + ```c++ + template <> struct fmt::formatter: formatter { + template + auto format(my_type obj, FormatContext& ctx) const { // Note const here. + // ... } - ``` - - gives a compile-time error on compilers with C++20 `consteval` - support (gcc 10+, clang 11+) because `d` is not a valid format - specifier for a string. - - To pass a runtime string wrap it in `fmt::runtime`: - - ```c++ - fmt::print(fmt::runtime("{:d}"), "I am not a number"); - ``` - -- Added compile-time formatting - (https://github.com/fmtlib/fmt/pull/2019, - https://github.com/fmtlib/fmt/pull/2044, - https://github.com/fmtlib/fmt/pull/2056, - https://github.com/fmtlib/fmt/pull/2072, - https://github.com/fmtlib/fmt/pull/2075, - https://github.com/fmtlib/fmt/issues/2078, - https://github.com/fmtlib/fmt/pull/2129, - https://github.com/fmtlib/fmt/pull/2326). For example - ([godbolt](https://godbolt.org/z/Mxx9d89jM)): - - ```c++ - #include - - consteval auto compile_time_itoa(int value) -> std::array { - auto result = std::array(); - fmt::format_to(result.data(), FMT_COMPILE("{}"), value); - return result; - } - - constexpr auto answer = compile_time_itoa(42); - ``` - - Most of the formatting functionality is available at compile time - with a notable exception of floating-point numbers and pointers. - Thanks @alexezeder. - -- Optimized handling of format specifiers during format string - compilation. For example, hexadecimal formatting (`"{:x}"`) is now - 3-7x faster than before when using `format_to` with format string - compilation and a stack-allocated buffer - (https://github.com/fmtlib/fmt/issues/1944). - - Before (7.1.3): - - ---------------------------------------------------------------------------- - Benchmark Time CPU Iterations - ---------------------------------------------------------------------------- - FMTCompileOld/0 15.5 ns 15.5 ns 43302898 - FMTCompileOld/42 16.6 ns 16.6 ns 43278267 - FMTCompileOld/273123 18.7 ns 18.6 ns 37035861 - FMTCompileOld/9223372036854775807 19.4 ns 19.4 ns 35243000 - ---------------------------------------------------------------------------- - - After (8.x): - - ---------------------------------------------------------------------------- - Benchmark Time CPU Iterations - ---------------------------------------------------------------------------- - FMTCompileNew/0 1.99 ns 1.99 ns 360523686 - FMTCompileNew/42 2.33 ns 2.33 ns 279865664 - FMTCompileNew/273123 3.72 ns 3.71 ns 190230315 - FMTCompileNew/9223372036854775807 5.28 ns 5.26 ns 130711631 - ---------------------------------------------------------------------------- - - It is even faster than `std::to_chars` from libc++ compiled with - clang on macOS: - - ---------------------------------------------------------------------------- - Benchmark Time CPU Iterations - ---------------------------------------------------------------------------- - ToChars/0 4.42 ns 4.41 ns 160196630 - ToChars/42 5.00 ns 4.98 ns 140735201 - ToChars/273123 7.26 ns 7.24 ns 95784130 - ToChars/9223372036854775807 8.77 ns 8.75 ns 75872534 - ---------------------------------------------------------------------------- - - In other cases, especially involving `std::string` construction, the - speed up is usually lower because handling format specifiers takes a - smaller fraction of the total time. - -- Added the `_cf` user-defined literal to represent a compiled format - string. It can be used instead of the `FMT_COMPILE` macro - (https://github.com/fmtlib/fmt/pull/2043, - https://github.com/fmtlib/fmt/pull/2242): - - ```c++ - #include - - using namespace fmt::literals; - auto s = fmt::format(FMT_COMPILE("{}"), 42); // 🙁 not modern - auto s = fmt::format("{}"_cf, 42); // 🙂 modern as hell - ``` - - It requires compiler support for class types in non-type template - parameters (a C++20 feature) which is available in GCC 9.3+. - Thanks @alexezeder. - -- Format string compilation now requires `format` functions of - `formatter` specializations for user-defined types to be `const`: - - ```c++ - template <> struct fmt::formatter: formatter { - template - auto format(my_type obj, FormatContext& ctx) const { // Note const here. - // ... - } - }; - ``` - -- Added UDL-based named argument support to format string compilation - (https://github.com/fmtlib/fmt/pull/2243, - https://github.com/fmtlib/fmt/pull/2281). For example: - - ```c++ - #include - - using namespace fmt::literals; - auto s = fmt::format(FMT_COMPILE("{answer}"), "answer"_a = 42); - ``` - - Here the argument named \"answer\" is resolved at compile time with - no runtime overhead. Thanks @alexezeder. - -- Added format string compilation support to `fmt::print` - (https://github.com/fmtlib/fmt/issues/2280, - https://github.com/fmtlib/fmt/pull/2304). Thanks @alexezeder. - -- Added initial support for compiling {fmt} as a C++20 module - (https://github.com/fmtlib/fmt/pull/2235, - https://github.com/fmtlib/fmt/pull/2240, - https://github.com/fmtlib/fmt/pull/2260, - https://github.com/fmtlib/fmt/pull/2282, - https://github.com/fmtlib/fmt/pull/2283, - https://github.com/fmtlib/fmt/pull/2288, - https://github.com/fmtlib/fmt/pull/2298, - https://github.com/fmtlib/fmt/pull/2306, - https://github.com/fmtlib/fmt/pull/2307, - https://github.com/fmtlib/fmt/pull/2309, - https://github.com/fmtlib/fmt/pull/2318, - https://github.com/fmtlib/fmt/pull/2324, - https://github.com/fmtlib/fmt/pull/2332, - https://github.com/fmtlib/fmt/pull/2340). Thanks @DanielaE. - -- Made symbols private by default reducing shared library size - (https://github.com/fmtlib/fmt/pull/2301). For example - there was a \~15% reported reduction on one platform. Thanks @sergiud. - -- Optimized includes making the result of preprocessing `fmt/format.h` - \~20% smaller with libstdc++/C++20 and slightly improving build - times (https://github.com/fmtlib/fmt/issues/1998). - -- Added support of ranges with non-const `begin` / `end` - (https://github.com/fmtlib/fmt/pull/1953). Thanks @kitegi. - -- Added support of `std::byte` and other formattable types to - `fmt::join` (https://github.com/fmtlib/fmt/issues/1981, - https://github.com/fmtlib/fmt/issues/2040, - https://github.com/fmtlib/fmt/pull/2050, - https://github.com/fmtlib/fmt/issues/2262). For example: - - ```c++ - #include - #include - #include - - int main() { - auto bytes = std::vector{std::byte(4), std::byte(2)}; - fmt::print("{}", fmt::join(bytes, "")); - } - ``` - - prints \"42\". - - Thanks @kamibo. - -- Implemented the default format for `std::chrono::system_clock` - (https://github.com/fmtlib/fmt/issues/2319, - https://github.com/fmtlib/fmt/pull/2345). For example: - - ```c++ - #include - - int main() { - fmt::print("{}", std::chrono::system_clock::now()); - } - ``` - - prints \"2021-06-18 15:22:00\" (the output depends on the current - date and time). Thanks @sunmy2019. - -- Made more chrono specifiers locale independent by default. Use the - `'L'` specifier to get localized formatting. For example: - - ```c++ - #include - - int main() { - std::locale::global(std::locale("ru_RU.UTF-8")); - auto monday = std::chrono::weekday(1); - fmt::print("{}\n", monday); // prints "Mon" - fmt::print("{:L}\n", monday); // prints "пн" - } - ``` - -- Improved locale handling in chrono formatting - (https://github.com/fmtlib/fmt/issues/2337, - https://github.com/fmtlib/fmt/pull/2349, - https://github.com/fmtlib/fmt/pull/2350). Thanks @phprus. - -- Deprecated `fmt/locale.h` moving the formatting functions that take - a locale to `fmt/format.h` (`char`) and `fmt/xchar` (other - overloads). This doesn\'t introduce a dependency on `` so - there is virtually no compile time effect. - -- Deprecated an undocumented `format_to` overload that takes - `basic_memory_buffer`. - -- Made parameter order in `vformat_to` consistent with `format_to` - (https://github.com/fmtlib/fmt/issues/2327). - -- Added support for time points with arbitrary durations - (https://github.com/fmtlib/fmt/issues/2208). For example: - - ```c++ - #include - - int main() { - using tp = std::chrono::time_point< - std::chrono::system_clock, std::chrono::seconds>; - fmt::print("{:%S}", tp(std::chrono::seconds(42))); - } - ``` - - prints \"42\". - -- Formatting floating-point numbers no longer produces trailing zeros - by default for consistency with `std::format`. For example: - - ```c++ - #include - - int main() { - fmt::print("{0:.3}", 1.1); - } - ``` - - prints \"1.1\". Use the `'#'` specifier to keep trailing zeros. - -- Dropped a limit on the number of elements in a range and replaced - `{}` with `[]` as range delimiters for consistency with Python\'s - `str.format`. - -- The `'L'` specifier for locale-specific numeric formatting can now - be combined with presentation specifiers as in `std::format`. For - example: - - ```c++ - #include - #include - - int main() { - std::locale::global(std::locale("fr_FR.UTF-8")); - fmt::print("{0:.2Lf}", 0.42); - } - ``` - - prints \"0,42\". The deprecated `'n'` specifier has been removed. - -- Made the `0` specifier ignored for infinity and NaN - (https://github.com/fmtlib/fmt/issues/2305, - https://github.com/fmtlib/fmt/pull/2310). Thanks @Liedtke. - -- Made the hexfloat formatting use the right alignment by default - (https://github.com/fmtlib/fmt/issues/2308, - https://github.com/fmtlib/fmt/pull/2317). Thanks @Liedtke. - -- Removed the deprecated numeric alignment (`'='`). Use the `'0'` - specifier instead. - -- Removed the deprecated `fmt/posix.h` header that has been replaced - with `fmt/os.h`. - -- Removed the deprecated `format_to_n_context`, `format_to_n_args` and - `make_format_to_n_args`. They have been replaced with - `format_context`, `` format_args` and ``make_format_args\`\` - respectively. - -- Moved `wchar_t`-specific functions and types to `fmt/xchar.h`. You - can define `FMT_DEPRECATED_INCLUDE_XCHAR` to automatically include - `fmt/xchar.h` from `fmt/format.h` but this will be disabled in the - next major release. - -- Fixed handling of the `'+'` specifier in localized formatting - (https://github.com/fmtlib/fmt/issues/2133). - -- Added support for the `'s'` format specifier that gives textual - representation of `bool` - (https://github.com/fmtlib/fmt/issues/2094, - https://github.com/fmtlib/fmt/pull/2109). For example: - - ```c++ - #include - - int main() { - fmt::print("{:s}", true); - } - ``` - - prints \"true\". Thanks @powercoderlol. - -- Made `fmt::ptr` work with function pointers - (https://github.com/fmtlib/fmt/pull/2131). For example: - - ```c++ - #include - - int main() { - fmt::print("My main: {}\n", fmt::ptr(main)); - } - ``` - - Thanks @mikecrowe. - -- The undocumented support for specializing `formatter` for pointer - types has been removed. - -- Fixed `fmt::formatted_size` with format string compilation - (https://github.com/fmtlib/fmt/pull/2141, - https://github.com/fmtlib/fmt/pull/2161). Thanks @alexezeder. - -- Fixed handling of empty format strings during format string - compilation (https://github.com/fmtlib/fmt/issues/2042): - - ```c++ - auto s = fmt::format(FMT_COMPILE("")); - ``` - - Thanks @alexezeder. - -- Fixed handling of enums in `fmt::to_string` - (https://github.com/fmtlib/fmt/issues/2036). - -- Improved width computation - (https://github.com/fmtlib/fmt/issues/2033, - https://github.com/fmtlib/fmt/issues/2091). For example: - - ```c++ - #include - - int main() { - fmt::print("{:-<10}{}\n", "你好", "世界"); - fmt::print("{:-<10}{}\n", "hello", "world"); - } - ``` - - prints - - ![](https://user-images.githubusercontent.com/576385/119840373-cea3ca80-beb9-11eb-91e0-54266c48e181.png) - - on a modern terminal. - -- The experimental fast output stream (`fmt::ostream`) is now - truncated by default for consistency with `fopen` - (https://github.com/fmtlib/fmt/issues/2018). For example: - - ```c++ - #include - - int main() { - fmt::ostream out1 = fmt::output_file("guide"); - out1.print("Zaphod"); - out1.close(); - fmt::ostream out2 = fmt::output_file("guide"); - out2.print("Ford"); - } - ``` - - writes \"Ford\" to the file \"guide\". To preserve the old file - content if any pass `fmt::file::WRONLY | fmt::file::CREATE` flags to - `fmt::output_file`. - -- Fixed moving of `fmt::ostream` that holds buffered data - (https://github.com/fmtlib/fmt/issues/2197, - https://github.com/fmtlib/fmt/pull/2198). Thanks @vtta. - -- Replaced the `fmt::system_error` exception with a function of the - same name that constructs `std::system_error` - (https://github.com/fmtlib/fmt/issues/2266). - -- Replaced the `fmt::windows_error` exception with a function of the - same name that constructs `std::system_error` with the category - returned by `fmt::system_category()` - (https://github.com/fmtlib/fmt/issues/2274, - https://github.com/fmtlib/fmt/pull/2275). The latter is - similar to `std::sytem_category` but correctly handles UTF-8. - Thanks @phprus. - -- Replaced `fmt::error_code` with `std::error_code` and made it - formattable (https://github.com/fmtlib/fmt/issues/2269, - https://github.com/fmtlib/fmt/pull/2270, - https://github.com/fmtlib/fmt/pull/2273). Thanks @phprus. - -- Added speech synthesis support - (https://github.com/fmtlib/fmt/pull/2206). - -- Made `format_to` work with a memory buffer that has a custom - allocator (https://github.com/fmtlib/fmt/pull/2300). - Thanks @voxmea. - -- Added `Allocator::max_size` support to `basic_memory_buffer`. - (https://github.com/fmtlib/fmt/pull/1960). Thanks @phprus. - -- Added wide string support to `fmt::join` - (https://github.com/fmtlib/fmt/pull/2236). Thanks @crbrz. - -- Made iterators passed to `formatter` specializations via a format - context satisfy C++20 `std::output_iterator` requirements - (https://github.com/fmtlib/fmt/issues/2156, - https://github.com/fmtlib/fmt/pull/2158, - https://github.com/fmtlib/fmt/issues/2195, - https://github.com/fmtlib/fmt/pull/2204). Thanks @randomnetcat. - -- Optimized the `printf` implementation - (https://github.com/fmtlib/fmt/pull/1982, - https://github.com/fmtlib/fmt/pull/1984, - https://github.com/fmtlib/fmt/pull/2016, - https://github.com/fmtlib/fmt/pull/2164). - Thanks @rimathia and @moiwi. - -- Improved detection of `constexpr` `char_traits` - (https://github.com/fmtlib/fmt/pull/2246, - https://github.com/fmtlib/fmt/pull/2257). Thanks @phprus. - -- Fixed writing to `stdout` when it is redirected to `NUL` on Windows - (https://github.com/fmtlib/fmt/issues/2080). - -- Fixed exception propagation from iterators - (https://github.com/fmtlib/fmt/issues/2097). - -- Improved `strftime` error handling - (https://github.com/fmtlib/fmt/issues/2238, - https://github.com/fmtlib/fmt/pull/2244). Thanks @yumeyao. - -- Stopped using deprecated GCC UDL template extension. - -- Added `fmt/args.h` to the install target - (https://github.com/fmtlib/fmt/issues/2096). - -- Error messages are now passed to assert when exceptions are disabled - (https://github.com/fmtlib/fmt/pull/2145). Thanks @NobodyXu. - -- Added the `FMT_MASTER_PROJECT` CMake option to control build and - install targets when {fmt} is included via `add_subdirectory` - (https://github.com/fmtlib/fmt/issues/2098, - https://github.com/fmtlib/fmt/pull/2100). - Thanks @randomizedthinking. - -- Improved build configuration - (https://github.com/fmtlib/fmt/pull/2026, - https://github.com/fmtlib/fmt/pull/2122). - Thanks @luncliff and @ibaned. - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/issues/1947, - https://github.com/fmtlib/fmt/pull/1959, - https://github.com/fmtlib/fmt/pull/1963, - https://github.com/fmtlib/fmt/pull/1965, - https://github.com/fmtlib/fmt/issues/1966, - https://github.com/fmtlib/fmt/pull/1974, - https://github.com/fmtlib/fmt/pull/1975, - https://github.com/fmtlib/fmt/pull/1990, - https://github.com/fmtlib/fmt/issues/2000, - https://github.com/fmtlib/fmt/pull/2001, - https://github.com/fmtlib/fmt/issues/2002, - https://github.com/fmtlib/fmt/issues/2004, - https://github.com/fmtlib/fmt/pull/2006, - https://github.com/fmtlib/fmt/pull/2009, - https://github.com/fmtlib/fmt/pull/2010, - https://github.com/fmtlib/fmt/issues/2038, - https://github.com/fmtlib/fmt/issues/2039, - https://github.com/fmtlib/fmt/issues/2047, - https://github.com/fmtlib/fmt/pull/2053, - https://github.com/fmtlib/fmt/issues/2059, - https://github.com/fmtlib/fmt/pull/2065, - https://github.com/fmtlib/fmt/pull/2067, - https://github.com/fmtlib/fmt/pull/2068, - https://github.com/fmtlib/fmt/pull/2073, - https://github.com/fmtlib/fmt/issues/2103, - https://github.com/fmtlib/fmt/issues/2105, - https://github.com/fmtlib/fmt/pull/2106, - https://github.com/fmtlib/fmt/pull/2107, - https://github.com/fmtlib/fmt/issues/2116, - https://github.com/fmtlib/fmt/pull/2117, - https://github.com/fmtlib/fmt/issues/2118, - https://github.com/fmtlib/fmt/pull/2119, - https://github.com/fmtlib/fmt/issues/2127, - https://github.com/fmtlib/fmt/pull/2128, - https://github.com/fmtlib/fmt/issues/2140, - https://github.com/fmtlib/fmt/issues/2142, - https://github.com/fmtlib/fmt/pull/2143, - https://github.com/fmtlib/fmt/pull/2144, - https://github.com/fmtlib/fmt/issues/2147, - https://github.com/fmtlib/fmt/issues/2148, - https://github.com/fmtlib/fmt/issues/2149, - https://github.com/fmtlib/fmt/pull/2152, - https://github.com/fmtlib/fmt/pull/2160, - https://github.com/fmtlib/fmt/issues/2170, - https://github.com/fmtlib/fmt/issues/2175, - https://github.com/fmtlib/fmt/issues/2176, - https://github.com/fmtlib/fmt/pull/2177, - https://github.com/fmtlib/fmt/issues/2178, - https://github.com/fmtlib/fmt/pull/2179, - https://github.com/fmtlib/fmt/issues/2180, - https://github.com/fmtlib/fmt/issues/2181, - https://github.com/fmtlib/fmt/pull/2183, - https://github.com/fmtlib/fmt/issues/2184, - https://github.com/fmtlib/fmt/issues/2185, - https://github.com/fmtlib/fmt/pull/2186, - https://github.com/fmtlib/fmt/pull/2187, - https://github.com/fmtlib/fmt/pull/2190, - https://github.com/fmtlib/fmt/pull/2192, - https://github.com/fmtlib/fmt/pull/2194, - https://github.com/fmtlib/fmt/pull/2205, - https://github.com/fmtlib/fmt/issues/2210, - https://github.com/fmtlib/fmt/pull/2211, - https://github.com/fmtlib/fmt/pull/2215, - https://github.com/fmtlib/fmt/pull/2216, - https://github.com/fmtlib/fmt/pull/2218, - https://github.com/fmtlib/fmt/pull/2220, - https://github.com/fmtlib/fmt/issues/2228, - https://github.com/fmtlib/fmt/pull/2229, - https://github.com/fmtlib/fmt/pull/2230, - https://github.com/fmtlib/fmt/issues/2233, - https://github.com/fmtlib/fmt/pull/2239, - https://github.com/fmtlib/fmt/issues/2248, - https://github.com/fmtlib/fmt/issues/2252, - https://github.com/fmtlib/fmt/pull/2253, - https://github.com/fmtlib/fmt/pull/2255, - https://github.com/fmtlib/fmt/issues/2261, - https://github.com/fmtlib/fmt/issues/2278, - https://github.com/fmtlib/fmt/issues/2284, - https://github.com/fmtlib/fmt/pull/2287, - https://github.com/fmtlib/fmt/pull/2289, - https://github.com/fmtlib/fmt/pull/2290, - https://github.com/fmtlib/fmt/pull/2293, - https://github.com/fmtlib/fmt/issues/2295, - https://github.com/fmtlib/fmt/pull/2296, - https://github.com/fmtlib/fmt/pull/2297, - https://github.com/fmtlib/fmt/issues/2311, - https://github.com/fmtlib/fmt/pull/2313, - https://github.com/fmtlib/fmt/pull/2315, - https://github.com/fmtlib/fmt/issues/2320, - https://github.com/fmtlib/fmt/pull/2321, - https://github.com/fmtlib/fmt/pull/2323, - https://github.com/fmtlib/fmt/issues/2328, - https://github.com/fmtlib/fmt/pull/2329, - https://github.com/fmtlib/fmt/pull/2333, - https://github.com/fmtlib/fmt/pull/2338, - https://github.com/fmtlib/fmt/pull/2341). - Thanks @darklukee, @fagg, @killerbot242, @jgopel, @yeswalrus, @Finkman, - @HazardyKnusperkeks, @dkavolis, @concatime, @chronoxor, @summivox, @yNeo, - @Apache-HB, @alexezeder, @toojays, @Brainy0207, @vadz, @imsherlock, @phprus, - @white238, @yafshar, @BillyDonahue, @jstaahl, @denchat, @DanielaE, - @ilyakurdyukov, @ilmai, @JessyDL, @sergiud, @mwinterb, @sven-herrmann, - @jmelas, @twoixter, @crbrz and @upsj. - -- Improved documentation - (https://github.com/fmtlib/fmt/issues/1986, - https://github.com/fmtlib/fmt/pull/2051, - https://github.com/fmtlib/fmt/issues/2057, - https://github.com/fmtlib/fmt/pull/2081, - https://github.com/fmtlib/fmt/issues/2084, - https://github.com/fmtlib/fmt/pull/2312). - Thanks @imba-tjd, @0x416c69 and @mordante. - -- Continuous integration and test improvements - (https://github.com/fmtlib/fmt/issues/1969, - https://github.com/fmtlib/fmt/pull/1991, - https://github.com/fmtlib/fmt/pull/2020, - https://github.com/fmtlib/fmt/pull/2110, - https://github.com/fmtlib/fmt/pull/2114, - https://github.com/fmtlib/fmt/issues/2196, - https://github.com/fmtlib/fmt/pull/2217, - https://github.com/fmtlib/fmt/pull/2247, - https://github.com/fmtlib/fmt/pull/2256, - https://github.com/fmtlib/fmt/pull/2336, - https://github.com/fmtlib/fmt/pull/2346). - Thanks @jgopel, @alexezeder and @DanielaE. - -# 7.1.3 - 2020-11-24 - -- Fixed handling of buffer boundaries in `format_to_n` - (https://github.com/fmtlib/fmt/issues/1996, - https://github.com/fmtlib/fmt/issues/2029). -- Fixed linkage errors when linking with a shared library - (https://github.com/fmtlib/fmt/issues/2011). -- Reintroduced ostream support to range formatters - (https://github.com/fmtlib/fmt/issues/2014). -- Worked around an issue with mixing std versions in gcc - (https://github.com/fmtlib/fmt/issues/2017). - -# 7.1.2 - 2020-11-04 - -- Fixed floating point formatting with large precision - (https://github.com/fmtlib/fmt/issues/1976). - -# 7.1.1 - 2020-11-01 - -- Fixed ABI compatibility with 7.0.x - (https://github.com/fmtlib/fmt/issues/1961). -- Added the `FMT_ARM_ABI_COMPATIBILITY` macro to work around ABI - incompatibility between GCC and Clang on ARM - (https://github.com/fmtlib/fmt/issues/1919). -- Worked around a SFINAE bug in GCC 8 - (https://github.com/fmtlib/fmt/issues/1957). -- Fixed linkage errors when building with GCC\'s LTO - (https://github.com/fmtlib/fmt/issues/1955). -- Fixed a compilation error when building without `__builtin_clz` or - equivalent (https://github.com/fmtlib/fmt/pull/1968). - Thanks @tohammer. -- Fixed a sign conversion warning - (https://github.com/fmtlib/fmt/pull/1964). Thanks @OptoCloud. - -# 7.1.0 - 2020-10-25 - -- Switched from - [Grisu3](https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf) - to [Dragonbox](https://github.com/jk-jeon/dragonbox) for the default - floating-point formatting which gives the shortest decimal - representation with round-trip guarantee and correct rounding - (https://github.com/fmtlib/fmt/pull/1882, - https://github.com/fmtlib/fmt/pull/1887, - https://github.com/fmtlib/fmt/pull/1894). This makes {fmt} - up to 20-30x faster than common implementations of - `std::ostringstream` and `sprintf` on - [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark) and - faster than double-conversion and Ryū: - - ![](https://user-images.githubusercontent.com/576385/95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png) - - It is possible to get even better performance at the cost of larger - binary size by compiling with the `FMT_USE_FULL_CACHE_DRAGONBOX` - macro set to 1. - - Thanks @jk-jeon. - -- Added an experimental unsynchronized file output API which, together - with [format string - compilation](https://fmt.dev/latest/api.html#compile-api), can give - [5-9 times speed up compared to - fprintf](https://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html) - on common platforms ([godbolt](https://godbolt.org/z/nsTcG8)): - - ```c++ - #include - - int main() { - auto f = fmt::output_file("guide"); - f.print("The answer is {}.", 42); - } - ``` - -- Added a formatter for `std::chrono::time_point` - (https://github.com/fmtlib/fmt/issues/1819, - https://github.com/fmtlib/fmt/pull/1837). For example - ([godbolt](https://godbolt.org/z/c4M6fh)): - - ```c++ - #include - - int main() { - auto now = std::chrono::system_clock::now(); - fmt::print("The time is {:%H:%M:%S}.\n", now); - } - ``` - - Thanks @adamburgess. - -- Added support for ranges with non-const `begin`/`end` to `fmt::join` - (https://github.com/fmtlib/fmt/issues/1784, - https://github.com/fmtlib/fmt/pull/1786). For example - ([godbolt](https://godbolt.org/z/jP63Tv)): - - ```c++ - #include - #include - - int main() { - using std::literals::string_literals::operator""s; - auto strs = std::array{"a"s, "bb"s, "ccc"s}; - auto range = strs | ranges::views::filter( - [] (const std::string &x) { return x.size() != 2; } - ); - fmt::print("{}\n", fmt::join(range, "")); - } - ``` - - prints \"accc\". - - Thanks @tonyelewis. - -- Added a `memory_buffer::append` overload that takes a range - (https://github.com/fmtlib/fmt/pull/1806). Thanks @BRevzin. - -- Improved handling of single code units in `FMT_COMPILE`. For - example: - - ```c++ - #include - - char* f(char* buf) { - return fmt::format_to(buf, FMT_COMPILE("x{}"), 42); - } - ``` - - compiles to just ([godbolt](https://godbolt.org/z/5vncz3)): - - ```asm - _Z1fPc: - movb $120, (%rdi) - xorl %edx, %edx - cmpl $42, _ZN3fmt2v76detail10basic_dataIvE23zero_or_powers_of_10_32E+8(%rip) - movl $3, %eax - seta %dl - subl %edx, %eax - movzwl _ZN3fmt2v76detail10basic_dataIvE6digitsE+84(%rip), %edx - cltq - addq %rdi, %rax - movw %dx, -2(%rax) - ret - ``` - - Here a single `mov` instruction writes `'x'` (`$120`) to the output - buffer. - -- Added dynamic width support to format string compilation - (https://github.com/fmtlib/fmt/issues/1809). - -- Improved error reporting for unformattable types: now you\'ll get - the type name directly in the error message instead of the note: - - ```c++ - #include - - struct how_about_no {}; - - int main() { - fmt::print("{}", how_about_no()); - } - ``` - - Error ([godbolt](https://godbolt.org/z/GoxM4e)): - - `fmt/core.h:1438:3: error: static_assert failed due to requirement 'fmt::v7::formattable()' "Cannot format an argument. To make type T formattable provide a formatter specialization: https://fmt.dev/latest/api.html#udt" ...` - -- Added the - [make_args_checked](https://fmt.dev/7.1.0/api.html#argument-lists) - function template that allows you to write formatting functions with - compile-time format string checks and avoid binary code bloat - ([godbolt](https://godbolt.org/z/PEf9qr)): - - ```c++ - void vlog(const char* file, int line, fmt::string_view format, - fmt::format_args args) { - fmt::print("{}: {}: ", file, line); - fmt::vprint(format, args); - } - - template - void log(const char* file, int line, const S& format, Args&&... args) { - vlog(file, line, format, - fmt::make_args_checked(format, args...)); - } - - #define MY_LOG(format, ...) \ - log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__) - - MY_LOG("invalid squishiness: {}", 42); - ``` - -- Replaced `snprintf` fallback with a faster internal IEEE 754 `float` - and `double` formatter for arbitrary precision. For example - ([godbolt](https://godbolt.org/z/dPhWvj)): - - ```c++ - #include - - int main() { - fmt::print("{:.500}\n", 4.9406564584124654E-324); - } - ``` - - prints - - `4.9406564584124654417656879286822137236505980261432476442558568250067550727020875186529983636163599237979656469544571773092665671035593979639877479601078187812630071319031140452784581716784898210368871863605699873072305000638740915356498438731247339727316961514003171538539807412623856559117102665855668676818703956031062493194527159149245532930545654440112748012970999954193198940908041656332452475714786901472678015935523861155013480352649347201937902681071074917033322268447533357208324319360923829e-324`. - -- Made `format_to_n` and `formatted_size` part of the [core - API](https://fmt.dev/latest/api.html#core-api) - ([godbolt](https://godbolt.org/z/sPjY1K)): - - ```c++ - #include - - int main() { - char buffer[10]; - auto result = fmt::format_to_n(buffer, sizeof(buffer), "{}", 42); - } - ``` - -- Added `fmt::format_to_n` overload with format string compilation - (https://github.com/fmtlib/fmt/issues/1764, - https://github.com/fmtlib/fmt/pull/1767, - https://github.com/fmtlib/fmt/pull/1869). For example - ([godbolt](https://godbolt.org/z/93h86q)): - - ```c++ - #include - - int main() { - char buffer[8]; - fmt::format_to_n(buffer, sizeof(buffer), FMT_COMPILE("{}"), 42); - } - ``` - - Thanks @Kurkin and @alexezeder. - -- Added `fmt::format_to` overload that take `text_style` - (https://github.com/fmtlib/fmt/issues/1593, - https://github.com/fmtlib/fmt/issues/1842, - https://github.com/fmtlib/fmt/pull/1843). For example - ([godbolt](https://godbolt.org/z/91153r)): - - ```c++ - #include - - int main() { - std::string out; - fmt::format_to(std::back_inserter(out), - fmt::emphasis::bold | fg(fmt::color::red), - "The answer is {}.", 42); - } - ``` - - Thanks @Naios. - -- Made the `'#'` specifier emit trailing zeros in addition to the - decimal point (https://github.com/fmtlib/fmt/issues/1797). - For example ([godbolt](https://godbolt.org/z/bhdcW9)): - - ```c++ - #include - - int main() { - fmt::print("{:#.2g}", 0.5); - } - ``` - - prints `0.50`. - -- Changed the default floating point format to not include `.0` for - consistency with `std::format` and `std::to_chars` - (https://github.com/fmtlib/fmt/issues/1893, - https://github.com/fmtlib/fmt/issues/1943). It is possible - to get the decimal point and trailing zero with the `#` specifier. - -- Fixed an issue with floating-point formatting that could result in - addition of a non-significant trailing zero in rare cases e.g. - `1.00e-34` instead of `1.0e-34` - (https://github.com/fmtlib/fmt/issues/1873, - https://github.com/fmtlib/fmt/issues/1917). - -- Made `fmt::to_string` fallback on `ostream` insertion operator if - the `formatter` specialization is not provided - (https://github.com/fmtlib/fmt/issues/1815, - https://github.com/fmtlib/fmt/pull/1829). Thanks @alexezeder. - -- Added support for the append mode to the experimental file API and - improved `fcntl.h` detection. - (https://github.com/fmtlib/fmt/pull/1847, - https://github.com/fmtlib/fmt/pull/1848). Thanks @t-wiser. - -- Fixed handling of types that have both an implicit conversion - operator and an overloaded `ostream` insertion operator - (https://github.com/fmtlib/fmt/issues/1766). - -- Fixed a slicing issue in an internal iterator type - (https://github.com/fmtlib/fmt/pull/1822). Thanks @BRevzin. - -- Fixed an issue in locale-specific integer formatting - (https://github.com/fmtlib/fmt/issues/1927). - -- Fixed handling of exotic code unit types - (https://github.com/fmtlib/fmt/issues/1870, - https://github.com/fmtlib/fmt/issues/1932). - -- Improved `FMT_ALWAYS_INLINE` - (https://github.com/fmtlib/fmt/pull/1878). Thanks @jk-jeon. - -- Removed dependency on `windows.h` - (https://github.com/fmtlib/fmt/pull/1900). Thanks @bernd5. - -- Optimized counting of decimal digits on MSVC - (https://github.com/fmtlib/fmt/pull/1890). Thanks @mwinterb. - -- Improved documentation - (https://github.com/fmtlib/fmt/issues/1772, - https://github.com/fmtlib/fmt/pull/1775, - https://github.com/fmtlib/fmt/pull/1792, - https://github.com/fmtlib/fmt/pull/1838, - https://github.com/fmtlib/fmt/pull/1888, - https://github.com/fmtlib/fmt/pull/1918, - https://github.com/fmtlib/fmt/pull/1939). - Thanks @leolchat, @pepsiman, @Klaim, @ravijanjam, @francesco-st and @udnaan. - -- Added the `FMT_REDUCE_INT_INSTANTIATIONS` CMake option that reduces - the binary code size at the cost of some integer formatting - performance. This can be useful for extremely memory-constrained - embedded systems - (https://github.com/fmtlib/fmt/issues/1778, - https://github.com/fmtlib/fmt/pull/1781). Thanks @kammce. - -- Added the `FMT_USE_INLINE_NAMESPACES` macro to control usage of - inline namespaces - (https://github.com/fmtlib/fmt/pull/1945). Thanks @darklukee. - -- Improved build configuration - (https://github.com/fmtlib/fmt/pull/1760, - https://github.com/fmtlib/fmt/pull/1770, - https://github.com/fmtlib/fmt/issues/1779, - https://github.com/fmtlib/fmt/pull/1783, - https://github.com/fmtlib/fmt/pull/1823). - Thanks @dvetutnev, @xvitaly, @tambry, @medithe and @martinwuehrer. - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/pull/1790, - https://github.com/fmtlib/fmt/pull/1802, - https://github.com/fmtlib/fmt/pull/1808, - https://github.com/fmtlib/fmt/issues/1810, - https://github.com/fmtlib/fmt/issues/1811, - https://github.com/fmtlib/fmt/pull/1812, - https://github.com/fmtlib/fmt/pull/1814, - https://github.com/fmtlib/fmt/pull/1816, - https://github.com/fmtlib/fmt/pull/1817, - https://github.com/fmtlib/fmt/pull/1818, - https://github.com/fmtlib/fmt/issues/1825, - https://github.com/fmtlib/fmt/pull/1836, - https://github.com/fmtlib/fmt/pull/1855, - https://github.com/fmtlib/fmt/pull/1856, - https://github.com/fmtlib/fmt/pull/1860, - https://github.com/fmtlib/fmt/pull/1877, - https://github.com/fmtlib/fmt/pull/1879, - https://github.com/fmtlib/fmt/pull/1880, - https://github.com/fmtlib/fmt/issues/1896, - https://github.com/fmtlib/fmt/pull/1897, - https://github.com/fmtlib/fmt/pull/1898, - https://github.com/fmtlib/fmt/issues/1904, - https://github.com/fmtlib/fmt/pull/1908, - https://github.com/fmtlib/fmt/issues/1911, - https://github.com/fmtlib/fmt/issues/1912, - https://github.com/fmtlib/fmt/issues/1928, - https://github.com/fmtlib/fmt/pull/1929, - https://github.com/fmtlib/fmt/issues/1935, - https://github.com/fmtlib/fmt/pull/1937, - https://github.com/fmtlib/fmt/pull/1942, - https://github.com/fmtlib/fmt/issues/1949). - Thanks @TheQwertiest, @medithe, @martinwuehrer, @n16h7hunt3r, @Othereum, - @gsjaardema, @AlexanderLanin, @gcerretani, @chronoxor, @noizefloor, - @akohlmey, @jk-jeon, @rimathia, @rglarix, @moiwi, @heckad, @MarcDirven. - @BartSiwek and @darklukee. - -# 7.0.3 - 2020-08-06 - -- Worked around broken `numeric_limits` for 128-bit integers - (https://github.com/fmtlib/fmt/issues/1787). -- Added error reporting on missing named arguments - (https://github.com/fmtlib/fmt/issues/1796). -- Stopped using 128-bit integers with clang-cl - (https://github.com/fmtlib/fmt/pull/1800). Thanks @Kingcom. -- Fixed issues in locale-specific integer formatting - (https://github.com/fmtlib/fmt/issues/1782, - https://github.com/fmtlib/fmt/issues/1801). - -# 7.0.2 - 2020-07-29 - -- Worked around broken `numeric_limits` for 128-bit integers - (https://github.com/fmtlib/fmt/issues/1725). -- Fixed compatibility with CMake 3.4 - (https://github.com/fmtlib/fmt/issues/1779). -- Fixed handling of digit separators in locale-specific formatting - (https://github.com/fmtlib/fmt/issues/1782). - -# 7.0.1 - 2020-07-07 - -- Updated the inline version namespace name. -- Worked around a gcc bug in mangling of alias templates - (https://github.com/fmtlib/fmt/issues/1753). -- Fixed a linkage error on Windows - (https://github.com/fmtlib/fmt/issues/1757). Thanks @Kurkin. -- Fixed minor issues with the documentation. - -# 7.0.0 - 2020-07-05 - -- Reduced the library size. For example, on macOS a stripped test - binary statically linked with {fmt} [shrank from \~368k to less than - 100k](http://www.zverovich.net/2020/05/21/reducing-library-size.html). - -- Added a simpler and more efficient [format string compilation - API](https://fmt.dev/7.0.0/api.html#compile-api): - - ```c++ - #include - - // Converts 42 into std::string using the most efficient method and no - // runtime format string processing. - std::string s = fmt::format(FMT_COMPILE("{}"), 42); - ``` - - The old `fmt::compile` API is now deprecated. - -- Optimized integer formatting: `format_to` with format string - compilation and a stack-allocated buffer is now [faster than - to_chars on both libc++ and - libstdc++](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html). - -- Optimized handling of small format strings. For example, - - ```c++ - fmt::format("Result: {}: ({},{},{},{})", str1, str2, str3, str4, str5) - ``` - - is now \~40% faster - (https://github.com/fmtlib/fmt/issues/1685). - -- Applied extern templates to improve compile times when using the - core API and `fmt/format.h` - (https://github.com/fmtlib/fmt/issues/1452). For example, - on macOS with clang the compile time of a test translation unit - dropped from 2.3s to 0.3s with `-O2` and from 0.6s to 0.3s with the - default settings (`-O0`). - - Before (`-O2`): - - % time c++ -c test.cc -I include -std=c++17 -O2 - c++ -c test.cc -I include -std=c++17 -O2 2.22s user 0.08s system 99% cpu 2.311 total - - After (`-O2`): - - % time c++ -c test.cc -I include -std=c++17 -O2 - c++ -c test.cc -I include -std=c++17 -O2 0.26s user 0.04s system 98% cpu 0.303 total - - Before (default): - - % time c++ -c test.cc -I include -std=c++17 - c++ -c test.cc -I include -std=c++17 0.53s user 0.06s system 98% cpu 0.601 total - - After (default): - - % time c++ -c test.cc -I include -std=c++17 - c++ -c test.cc -I include -std=c++17 0.24s user 0.06s system 98% cpu 0.301 total - - It is still recommended to use `fmt/core.h` instead of - `fmt/format.h` but the compile time difference is now smaller. - Thanks @alex3d for the suggestion. - -- Named arguments are now stored on stack (no dynamic memory - allocations) and the compiled code is more compact and efficient. - For example - - ```c++ - #include - - int main() { - fmt::print("The answer is {answer}\n", fmt::arg("answer", 42)); - } - ``` - - compiles to just ([godbolt](https://godbolt.org/z/NcfEp_)) - - ```asm - .LC0: - .string "answer" - .LC1: - .string "The answer is {answer}\n" - main: - sub rsp, 56 - mov edi, OFFSET FLAT:.LC1 - mov esi, 23 - movabs rdx, 4611686018427387905 - lea rax, [rsp+32] - lea rcx, [rsp+16] - mov QWORD PTR [rsp+8], 1 - mov QWORD PTR [rsp], rax - mov DWORD PTR [rsp+16], 42 - mov QWORD PTR [rsp+32], OFFSET FLAT:.LC0 - mov DWORD PTR [rsp+40], 0 - call fmt::v6::vprint(fmt::v6::basic_string_view, - fmt::v6::format_args) - xor eax, eax - add rsp, 56 - ret - - .L.str.1: - .asciz "answer" - ``` - -- Implemented compile-time checks for dynamic width and precision - (https://github.com/fmtlib/fmt/issues/1614): - - ```c++ - #include - - int main() { - fmt::print(FMT_STRING("{0:{1}}"), 42); - } - ``` - - now gives a compilation error because argument 1 doesn\'t exist: - - In file included from test.cc:1: - include/fmt/format.h:2726:27: error: constexpr variable 'invalid_format' must be - initialized by a constant expression - FMT_CONSTEXPR_DECL bool invalid_format = - ^ - ... - include/fmt/core.h:569:26: note: in call to - '&checker(s, {}).context_->on_error(&"argument not found"[0])' - if (id >= num_args_) on_error("argument not found"); - ^ - -- Added sentinel support to `fmt::join` - (https://github.com/fmtlib/fmt/pull/1689) - - ```c++ - struct zstring_sentinel {}; - bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; } - bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; } - - struct zstring { - const char* p; - const char* begin() const { return p; } - zstring_sentinel end() const { return {}; } - }; - - auto s = fmt::format("{}", fmt::join(zstring{"hello"}, "_")); - // s == "h_e_l_l_o" - ``` - - Thanks @BRevzin. - -- Added support for named arguments, `clear` and `reserve` to - `dynamic_format_arg_store` - (https://github.com/fmtlib/fmt/issues/1655, - https://github.com/fmtlib/fmt/pull/1663, - https://github.com/fmtlib/fmt/pull/1674, - https://github.com/fmtlib/fmt/pull/1677). Thanks @vsolontsov-ll. - -- Added support for the `'c'` format specifier to integral types for - compatibility with `std::format` - (https://github.com/fmtlib/fmt/issues/1652). - -- Replaced the `'n'` format specifier with `'L'` for compatibility - with `std::format` - (https://github.com/fmtlib/fmt/issues/1624). The `'n'` - specifier can be enabled via the `FMT_DEPRECATED_N_SPECIFIER` macro. - -- The `'='` format specifier is now disabled by default for - compatibility with `std::format`. It can be enabled via the - `FMT_DEPRECATED_NUMERIC_ALIGN` macro. - -- Removed the following deprecated APIs: - - - `FMT_STRING_ALIAS` and `fmt` macros - replaced by `FMT_STRING` - - `fmt::basic_string_view::char_type` - replaced by - `fmt::basic_string_view::value_type` - - `convert_to_int` - - `format_arg_store::types` - - `*parse_context` - replaced by `*format_parse_context` - - `FMT_DEPRECATED_INCLUDE_OS` - - `FMT_DEPRECATED_PERCENT` - incompatible with `std::format` - - `*writer` - replaced by compiled format API - -- Renamed the `internal` namespace to `detail` - (https://github.com/fmtlib/fmt/issues/1538). The former is - still provided as an alias if the `FMT_USE_INTERNAL` macro is - defined. - -- Improved compatibility between `fmt::printf` with the standard specs - (https://github.com/fmtlib/fmt/issues/1595, - https://github.com/fmtlib/fmt/pull/1682, - https://github.com/fmtlib/fmt/pull/1683, - https://github.com/fmtlib/fmt/pull/1687, - https://github.com/fmtlib/fmt/pull/1699). Thanks @rimathia. - -- Fixed handling of `operator<<` overloads that use `copyfmt` - (https://github.com/fmtlib/fmt/issues/1666). - -- Added the `FMT_OS` CMake option to control inclusion of OS-specific - APIs in the fmt target. This can be useful for embedded platforms - (https://github.com/fmtlib/fmt/issues/1654, - https://github.com/fmtlib/fmt/pull/1656). Thanks @kwesolowski. - -- Replaced `FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION` with the - `FMT_FUZZ` macro to prevent interfering with fuzzing of projects - using {fmt} (https://github.com/fmtlib/fmt/pull/1650). - Thanks @asraa. - -- Fixed compatibility with emscripten - (https://github.com/fmtlib/fmt/issues/1636, - https://github.com/fmtlib/fmt/pull/1637). Thanks @ArthurSonzogni. - -- Improved documentation - (https://github.com/fmtlib/fmt/issues/704, - https://github.com/fmtlib/fmt/pull/1643, - https://github.com/fmtlib/fmt/pull/1660, - https://github.com/fmtlib/fmt/pull/1681, - https://github.com/fmtlib/fmt/pull/1691, - https://github.com/fmtlib/fmt/pull/1706, - https://github.com/fmtlib/fmt/pull/1714, - https://github.com/fmtlib/fmt/pull/1721, - https://github.com/fmtlib/fmt/pull/1739, - https://github.com/fmtlib/fmt/pull/1740, - https://github.com/fmtlib/fmt/pull/1741, - https://github.com/fmtlib/fmt/pull/1751). - Thanks @senior7515, @lsr0, @puetzk, @fpelliccioni, Alexey Kuzmenko, @jelly, - @claremacrae, @jiapengwen, @gsjaardema and @alexey-milovidov. - -- Implemented various build configuration fixes and improvements - (https://github.com/fmtlib/fmt/pull/1603, - https://github.com/fmtlib/fmt/pull/1657, - https://github.com/fmtlib/fmt/pull/1702, - https://github.com/fmtlib/fmt/pull/1728). - Thanks @scramsby, @jtojnar, @orivej and @flagarde. - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/pull/1616, - https://github.com/fmtlib/fmt/issues/1620, - https://github.com/fmtlib/fmt/issues/1622, - https://github.com/fmtlib/fmt/issues/1625, - https://github.com/fmtlib/fmt/pull/1627, - https://github.com/fmtlib/fmt/issues/1628, - https://github.com/fmtlib/fmt/pull/1629, - https://github.com/fmtlib/fmt/issues/1631, - https://github.com/fmtlib/fmt/pull/1633, - https://github.com/fmtlib/fmt/pull/1649, - https://github.com/fmtlib/fmt/issues/1658, - https://github.com/fmtlib/fmt/pull/1661, - https://github.com/fmtlib/fmt/pull/1667, - https://github.com/fmtlib/fmt/issues/1668, - https://github.com/fmtlib/fmt/pull/1669, - https://github.com/fmtlib/fmt/issues/1692, - https://github.com/fmtlib/fmt/pull/1696, - https://github.com/fmtlib/fmt/pull/1697, - https://github.com/fmtlib/fmt/issues/1707, - https://github.com/fmtlib/fmt/pull/1712, - https://github.com/fmtlib/fmt/pull/1716, - https://github.com/fmtlib/fmt/pull/1722, - https://github.com/fmtlib/fmt/issues/1724, - https://github.com/fmtlib/fmt/pull/1729, - https://github.com/fmtlib/fmt/pull/1738, - https://github.com/fmtlib/fmt/issues/1742, - https://github.com/fmtlib/fmt/issues/1743, - https://github.com/fmtlib/fmt/pull/1744, - https://github.com/fmtlib/fmt/issues/1747, - https://github.com/fmtlib/fmt/pull/1750). - Thanks @gsjaardema, @gabime, @johnor, @Kurkin, @invexed, @peterbell10, - @daixtrose, @petrutlucian94, @Neargye, @ambitslix, @gabime, @erthink, - @tohammer and @0x8000-0000. - -# 6.2.1 - 2020-05-09 - -- Fixed ostream support in `sprintf` - (https://github.com/fmtlib/fmt/issues/1631). -- Fixed type detection when using implicit conversion to `string_view` - and ostream `operator<<` inconsistently - (https://github.com/fmtlib/fmt/issues/1662). - -# 6.2.0 - 2020-04-05 - -- Improved error reporting when trying to format an object of a - non-formattable type: - - ```c++ - fmt::format("{}", S()); - ``` - - now gives: - - include/fmt/core.h:1015:5: error: static_assert failed due to requirement - 'formattable' "Cannot format argument. To make type T formattable provide a - formatter specialization: - https://fmt.dev/latest/api.html#formatting-user-defined-types" - static_assert( - ^ - ... - note: in instantiation of function template specialization - 'fmt::v6::format' requested here - fmt::format("{}", S()); - ^ - - if `S` is not formattable. - -- Reduced the library size by \~10%. - -- Always print decimal point if `#` is specified - (https://github.com/fmtlib/fmt/issues/1476, - https://github.com/fmtlib/fmt/issues/1498): - - ```c++ - fmt::print("{:#.0f}", 42.0); - ``` - - now prints `42.` - -- Implemented the `'L'` specifier for locale-specific numeric - formatting to improve compatibility with `std::format`. The `'n'` - specifier is now deprecated and will be removed in the next major - release. - -- Moved OS-specific APIs such as `windows_error` from `fmt/format.h` - to `fmt/os.h`. You can define `FMT_DEPRECATED_INCLUDE_OS` to - automatically include `fmt/os.h` from `fmt/format.h` for - compatibility but this will be disabled in the next major release. - -- Added precision overflow detection in floating-point formatting. - -- Implemented detection of invalid use of `fmt::arg`. - -- Used `type_identity` to block unnecessary template argument - deduction. Thanks Tim Song. - -- Improved UTF-8 handling - (https://github.com/fmtlib/fmt/issues/1109): - - ```c++ - fmt::print("┌{0:─^{2}}┐\n" - "│{1: ^{2}}│\n" - "└{0:─^{2}}┘\n", "", "Привет, мир!", 20); - ``` - - now prints: - - ┌────────────────────┐ - │ Привет, мир! │ - └────────────────────┘ - - on systems that support Unicode. - -- Added experimental dynamic argument storage - (https://github.com/fmtlib/fmt/issues/1170, - https://github.com/fmtlib/fmt/pull/1584): - - ```c++ - fmt::dynamic_format_arg_store store; - store.push_back("answer"); - store.push_back(42); - fmt::vprint("The {} is {}.\n", store); - ``` - - prints: - - The answer is 42. - - Thanks @vsolontsov-ll. - -- Made `fmt::join` accept `initializer_list` - (https://github.com/fmtlib/fmt/pull/1591). Thanks @Rapotkinnik. - -- Fixed handling of empty tuples - (https://github.com/fmtlib/fmt/issues/1588). - -- Fixed handling of output iterators in `format_to_n` - (https://github.com/fmtlib/fmt/issues/1506). - -- Fixed formatting of `std::chrono::duration` types to wide output - (https://github.com/fmtlib/fmt/pull/1533). Thanks @zeffy. - -- Added const `begin` and `end` overload to buffers - (https://github.com/fmtlib/fmt/pull/1553). Thanks @dominicpoeschko. - -- Added the ability to disable floating-point formatting via - `FMT_USE_FLOAT`, `FMT_USE_DOUBLE` and `FMT_USE_LONG_DOUBLE` macros - for extremely memory-constrained embedded system - (https://github.com/fmtlib/fmt/pull/1590). Thanks @albaguirre. - -- Made `FMT_STRING` work with `constexpr` `string_view` - (https://github.com/fmtlib/fmt/pull/1589). Thanks @scramsby. - -- Implemented a minor optimization in the format string parser - (https://github.com/fmtlib/fmt/pull/1560). Thanks @IkarusDeveloper. - -- Improved attribute detection - (https://github.com/fmtlib/fmt/pull/1469, - https://github.com/fmtlib/fmt/pull/1475, - https://github.com/fmtlib/fmt/pull/1576). - Thanks @federico-busato, @chronoxor and @refnum. - -- Improved documentation - (https://github.com/fmtlib/fmt/pull/1481, - https://github.com/fmtlib/fmt/pull/1523). - Thanks @JackBoosY and @imba-tjd. - -- Fixed symbol visibility on Linux when compiling with - `-fvisibility=hidden` - (https://github.com/fmtlib/fmt/pull/1535). Thanks @milianw. - -- Implemented various build configuration fixes and improvements - (https://github.com/fmtlib/fmt/issues/1264, - https://github.com/fmtlib/fmt/issues/1460, - https://github.com/fmtlib/fmt/pull/1534, - https://github.com/fmtlib/fmt/issues/1536, - https://github.com/fmtlib/fmt/issues/1545, - https://github.com/fmtlib/fmt/pull/1546, - https://github.com/fmtlib/fmt/issues/1566, - https://github.com/fmtlib/fmt/pull/1582, - https://github.com/fmtlib/fmt/issues/1597, - https://github.com/fmtlib/fmt/pull/1598). - Thanks @ambitslix, @jwillikers and @stac47. - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/pull/1433, - https://github.com/fmtlib/fmt/issues/1461, - https://github.com/fmtlib/fmt/pull/1470, - https://github.com/fmtlib/fmt/pull/1480, - https://github.com/fmtlib/fmt/pull/1485, - https://github.com/fmtlib/fmt/pull/1492, - https://github.com/fmtlib/fmt/issues/1493, - https://github.com/fmtlib/fmt/issues/1504, - https://github.com/fmtlib/fmt/pull/1505, - https://github.com/fmtlib/fmt/pull/1512, - https://github.com/fmtlib/fmt/issues/1515, - https://github.com/fmtlib/fmt/pull/1516, - https://github.com/fmtlib/fmt/pull/1518, - https://github.com/fmtlib/fmt/pull/1519, - https://github.com/fmtlib/fmt/pull/1520, - https://github.com/fmtlib/fmt/pull/1521, - https://github.com/fmtlib/fmt/pull/1522, - https://github.com/fmtlib/fmt/issues/1524, - https://github.com/fmtlib/fmt/pull/1530, - https://github.com/fmtlib/fmt/issues/1531, - https://github.com/fmtlib/fmt/pull/1532, - https://github.com/fmtlib/fmt/issues/1539, - https://github.com/fmtlib/fmt/issues/1547, - https://github.com/fmtlib/fmt/issues/1548, - https://github.com/fmtlib/fmt/pull/1554, - https://github.com/fmtlib/fmt/issues/1567, - https://github.com/fmtlib/fmt/pull/1568, - https://github.com/fmtlib/fmt/pull/1569, - https://github.com/fmtlib/fmt/pull/1571, - https://github.com/fmtlib/fmt/pull/1573, - https://github.com/fmtlib/fmt/pull/1575, - https://github.com/fmtlib/fmt/pull/1581, - https://github.com/fmtlib/fmt/issues/1583, - https://github.com/fmtlib/fmt/issues/1586, - https://github.com/fmtlib/fmt/issues/1587, - https://github.com/fmtlib/fmt/issues/1594, - https://github.com/fmtlib/fmt/pull/1596, - https://github.com/fmtlib/fmt/issues/1604, - https://github.com/fmtlib/fmt/pull/1606, - https://github.com/fmtlib/fmt/issues/1607, - https://github.com/fmtlib/fmt/issues/1609). - Thanks @marti4d, @iPherian, @parkertomatoes, @gsjaardema, @chronoxor, - @DanielaE, @torsten48, @tohammer, @lefticus, @ryusakki, @adnsv, @fghzxm, - @refnum, @pramodk, @Spirrwell and @scramsby. - -# 6.1.2 - 2019-12-11 - -- Fixed ABI compatibility with `libfmt.so.6.0.0` - (https://github.com/fmtlib/fmt/issues/1471). -- Fixed handling types convertible to `std::string_view` - (https://github.com/fmtlib/fmt/pull/1451). Thanks @denizevrenci. -- Made CUDA test an opt-in enabled via the `FMT_CUDA_TEST` CMake - option. -- Fixed sign conversion warnings - (https://github.com/fmtlib/fmt/pull/1440). Thanks @0x8000-0000. - -# 6.1.1 - 2019-12-04 - -- Fixed shared library build on Windows - (https://github.com/fmtlib/fmt/pull/1443, - https://github.com/fmtlib/fmt/issues/1445, - https://github.com/fmtlib/fmt/pull/1446, - https://github.com/fmtlib/fmt/issues/1450). - Thanks @egorpugin and @bbolli. -- Added a missing decimal point in exponent notation with trailing - zeros. -- Removed deprecated `format_arg_store::TYPES`. - -# 6.1.0 - 2019-12-01 - -- {fmt} now formats IEEE 754 `float` and `double` using the shortest - decimal representation with correct rounding by default: - - ```c++ - #include - #include - - int main() { - fmt::print("{}", M_PI); - } - ``` - - prints `3.141592653589793`. - -- Made the fast binary to decimal floating-point formatter the - default, simplified it and improved performance. {fmt} is now 15 - times faster than libc++\'s `std::ostringstream`, 11 times faster - than `printf` and 10% faster than double-conversion on - [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark): - - | Function | Time (ns) | Speedup | - | ------------- | --------: | ------: | - | ostringstream | 1,346.30 | 1.00x | - | ostrstream | 1,195.74 | 1.13x | - | sprintf | 995.08 | 1.35x | - | doubleconv | 99.10 | 13.59x | - | fmt | 88.34 | 15.24x | - - ![](https://user-images.githubusercontent.com/576385/69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png) - -- {fmt} no longer converts `float` arguments to `double`. In - particular this improves the default (shortest) representation of - floats and makes `fmt::format` consistent with `std::format` specs - (https://github.com/fmtlib/fmt/issues/1336, - https://github.com/fmtlib/fmt/issues/1353, - https://github.com/fmtlib/fmt/pull/1360, - https://github.com/fmtlib/fmt/pull/1361): - - ```c++ - fmt::print("{}", 0.1f); - ``` - - prints `0.1` instead of `0.10000000149011612`. - - Thanks @orivej. - -- Made floating-point formatting output consistent with - `printf`/iostreams - (https://github.com/fmtlib/fmt/issues/1376, - https://github.com/fmtlib/fmt/issues/1417). - -- Added support for 128-bit integers - (https://github.com/fmtlib/fmt/pull/1287): - - ```c++ - fmt::print("{}", std::numeric_limits<__int128_t>::max()); - ``` - - prints `170141183460469231731687303715884105727`. - - Thanks @denizevrenci. - -- The overload of `print` that takes `text_style` is now atomic, i.e. - the output from different threads doesn\'t interleave - (https://github.com/fmtlib/fmt/pull/1351). Thanks @tankiJong. - -- Made compile time in the header-only mode \~20% faster by reducing - the number of template instantiations. `wchar_t` overload of - `vprint` was moved from `fmt/core.h` to `fmt/format.h`. - -- Added an overload of `fmt::join` that works with tuples - (https://github.com/fmtlib/fmt/issues/1322, - https://github.com/fmtlib/fmt/pull/1330): - - ```c++ - #include - #include - - int main() { - std::tuple t{'a', 1, 2.0f}; - fmt::print("{}", t); - } - ``` - - prints `('a', 1, 2.0)`. - - Thanks @jeremyong. - -- Changed formatting of octal zero with prefix from \"00\" to \"0\": - - ```c++ - fmt::print("{:#o}", 0); - ``` - - prints `0`. - -- The locale is now passed to ostream insertion (`<<`) operators - (https://github.com/fmtlib/fmt/pull/1406): - - ```c++ - #include - #include - - struct S { - double value; - }; - - std::ostream& operator<<(std::ostream& os, S s) { - return os << s.value; - } - - int main() { - auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42}); - // s == "0,42" - } - ``` - - Thanks @dlaugt. - -- Locale-specific number formatting now uses grouping - (https://github.com/fmtlib/fmt/issues/1393, - https://github.com/fmtlib/fmt/pull/1394). Thanks @skrdaniel. - -- Fixed handling of types with deleted implicit rvalue conversion to - `const char**` (https://github.com/fmtlib/fmt/issues/1421): - - ```c++ - struct mystring { - operator const char*() const&; - operator const char*() &; - operator const char*() const&& = delete; - operator const char*() && = delete; - }; - mystring str; - fmt::print("{}", str); // now compiles - ``` - -- Enums are now mapped to correct underlying types instead of `int` - (https://github.com/fmtlib/fmt/pull/1286). Thanks @agmt. - -- Enum classes are no longer implicitly converted to `int` - (https://github.com/fmtlib/fmt/issues/1424). - -- Added `basic_format_parse_context` for consistency with C++20 - `std::format` and deprecated `basic_parse_context`. - -- Fixed handling of UTF-8 in precision - (https://github.com/fmtlib/fmt/issues/1389, - https://github.com/fmtlib/fmt/pull/1390). Thanks @tajtiattila. - -- {fmt} can now be installed on Linux, macOS and Windows with - [Conda](https://docs.conda.io/en/latest/) using its - [conda-forge](https://conda-forge.org) - [package](https://github.com/conda-forge/fmt-feedstock) - (https://github.com/fmtlib/fmt/pull/1410): - - conda install -c conda-forge fmt - - Thanks @tdegeus. - -- Added a CUDA test (https://github.com/fmtlib/fmt/pull/1285, - https://github.com/fmtlib/fmt/pull/1317). - Thanks @luncliff and @risa2000. - -- Improved documentation - (https://github.com/fmtlib/fmt/pull/1276, - https://github.com/fmtlib/fmt/issues/1291, - https://github.com/fmtlib/fmt/issues/1296, - https://github.com/fmtlib/fmt/pull/1315, - https://github.com/fmtlib/fmt/pull/1332, - https://github.com/fmtlib/fmt/pull/1337, - https://github.com/fmtlib/fmt/issues/1395 - https://github.com/fmtlib/fmt/pull/1418). - Thanks @waywardmonkeys, @pauldreik and @jackoalan. - -- Various code improvements - (https://github.com/fmtlib/fmt/pull/1358, - https://github.com/fmtlib/fmt/pull/1407). - Thanks @orivej and @dpacbach. - -- Fixed compile-time format string checks for user-defined types - (https://github.com/fmtlib/fmt/issues/1292). - -- Worked around a false positive in `unsigned-integer-overflow` sanitizer - (https://github.com/fmtlib/fmt/issues/1377). - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/issues/1273, - https://github.com/fmtlib/fmt/pull/1278, - https://github.com/fmtlib/fmt/pull/1280, - https://github.com/fmtlib/fmt/issues/1281, - https://github.com/fmtlib/fmt/issues/1288, - https://github.com/fmtlib/fmt/pull/1290, - https://github.com/fmtlib/fmt/pull/1301, - https://github.com/fmtlib/fmt/issues/1305, - https://github.com/fmtlib/fmt/issues/1306, - https://github.com/fmtlib/fmt/issues/1309, - https://github.com/fmtlib/fmt/pull/1312, - https://github.com/fmtlib/fmt/issues/1313, - https://github.com/fmtlib/fmt/issues/1316, - https://github.com/fmtlib/fmt/issues/1319, - https://github.com/fmtlib/fmt/pull/1320, - https://github.com/fmtlib/fmt/pull/1326, - https://github.com/fmtlib/fmt/pull/1328, - https://github.com/fmtlib/fmt/issues/1344, - https://github.com/fmtlib/fmt/pull/1345, - https://github.com/fmtlib/fmt/pull/1347, - https://github.com/fmtlib/fmt/pull/1349, - https://github.com/fmtlib/fmt/issues/1354, - https://github.com/fmtlib/fmt/issues/1362, - https://github.com/fmtlib/fmt/issues/1366, - https://github.com/fmtlib/fmt/pull/1364, - https://github.com/fmtlib/fmt/pull/1370, - https://github.com/fmtlib/fmt/pull/1371, - https://github.com/fmtlib/fmt/issues/1385, - https://github.com/fmtlib/fmt/issues/1388, - https://github.com/fmtlib/fmt/pull/1397, - https://github.com/fmtlib/fmt/pull/1414, - https://github.com/fmtlib/fmt/pull/1416, - https://github.com/fmtlib/fmt/issues/1422 - https://github.com/fmtlib/fmt/pull/1427, - https://github.com/fmtlib/fmt/issues/1431, - https://github.com/fmtlib/fmt/pull/1433). - Thanks @hhb, @gsjaardema, @gabime, @neheb, @vedranmiletic, @dkavolis, - @mwinterb, @orivej, @denizevrenci, @leonklingele, @chronoxor, @kent-tri, - @0x8000-0000 and @marti4d. - -# 6.0.0 - 2019-08-26 - -- Switched to the [MIT license]( - https://github.com/fmtlib/fmt/blob/5a4b24613ba16cc689977c3b5bd8274a3ba1dd1f/LICENSE.rst) - with an optional exception that allows distributing binary code - without attribution. - -- Floating-point formatting is now locale-independent by default: - - ```c++ - #include - #include - - 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: - - ```c++ + }; + ``` + +- Added UDL-based named argument support to format string compilation + (https://github.com/fmtlib/fmt/pull/2243, + https://github.com/fmtlib/fmt/pull/2281). For example: + + ```c++ + #include + + using namespace fmt::literals; + auto s = fmt::format(FMT_COMPILE("{answer}"), "answer"_a = 42); + ``` + + Here the argument named \"answer\" is resolved at compile time with + no runtime overhead. Thanks @alexezeder. + +- Added format string compilation support to `fmt::print` + (https://github.com/fmtlib/fmt/issues/2280, + https://github.com/fmtlib/fmt/pull/2304). Thanks @alexezeder. + +- Added initial support for compiling {fmt} as a C++20 module + (https://github.com/fmtlib/fmt/pull/2235, + https://github.com/fmtlib/fmt/pull/2240, + https://github.com/fmtlib/fmt/pull/2260, + https://github.com/fmtlib/fmt/pull/2282, + https://github.com/fmtlib/fmt/pull/2283, + https://github.com/fmtlib/fmt/pull/2288, + https://github.com/fmtlib/fmt/pull/2298, + https://github.com/fmtlib/fmt/pull/2306, + https://github.com/fmtlib/fmt/pull/2307, + https://github.com/fmtlib/fmt/pull/2309, + https://github.com/fmtlib/fmt/pull/2318, + https://github.com/fmtlib/fmt/pull/2324, + https://github.com/fmtlib/fmt/pull/2332, + https://github.com/fmtlib/fmt/pull/2340). Thanks @DanielaE. + +- Made symbols private by default reducing shared library size + (https://github.com/fmtlib/fmt/pull/2301). For example + there was a \~15% reported reduction on one platform. Thanks @sergiud. + +- Optimized includes making the result of preprocessing `fmt/format.h` + \~20% smaller with libstdc++/C++20 and slightly improving build + times (https://github.com/fmtlib/fmt/issues/1998). + +- Added support of ranges with non-const `begin` / `end` + (https://github.com/fmtlib/fmt/pull/1953). Thanks @kitegi. + +- Added support of `std::byte` and other formattable types to + `fmt::join` (https://github.com/fmtlib/fmt/issues/1981, + https://github.com/fmtlib/fmt/issues/2040, + https://github.com/fmtlib/fmt/pull/2050, + https://github.com/fmtlib/fmt/issues/2262). For example: + + ```c++ + #include + #include + #include + + int main() { + auto bytes = std::vector{std::byte(4), std::byte(2)}; + fmt::print("{}", fmt::join(bytes, "")); + } + ``` + + prints \"42\". + + Thanks @kamibo. + +- Implemented the default format for `std::chrono::system_clock` + (https://github.com/fmtlib/fmt/issues/2319, + https://github.com/fmtlib/fmt/pull/2345). For example: + + ```c++ + #include + + int main() { + fmt::print("{}", std::chrono::system_clock::now()); + } + ``` + + prints \"2021-06-18 15:22:00\" (the output depends on the current + date and time). Thanks @sunmy2019. + +- Made more chrono specifiers locale independent by default. Use the + `'L'` specifier to get localized formatting. For example: + + ```c++ + #include + + int main() { std::locale::global(std::locale("ru_RU.UTF-8")); - fmt::print("value = {:n}", 4.2); - ``` + auto monday = std::chrono::weekday(1); + fmt::print("{}\n", monday); // prints "Mon" + fmt::print("{:L}\n", monday); // prints "пн" + } + ``` - prints \"value = 4,2\". +- Improved locale handling in chrono formatting + (https://github.com/fmtlib/fmt/issues/2337, + https://github.com/fmtlib/fmt/pull/2349, + https://github.com/fmtlib/fmt/pull/2350). Thanks @phprus. -- 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: +- Deprecated `fmt/locale.h` moving the formatting functions that take + a locale to `fmt/format.h` (`char`) and `fmt/xchar` (other + overloads). This doesn\'t introduce a dependency on `` so + there is virtually no compile time effect. - ```c++ - #define FMT_USE_GRISU 1 - #include +- Deprecated an undocumented `format_to` overload that takes + `basic_memory_buffer`. - auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu - ``` +- Made parameter order in `vformat_to` consistent with `format_to` + (https://github.com/fmtlib/fmt/issues/2327). - 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)): +- Added support for time points with arbitrary durations + (https://github.com/fmtlib/fmt/issues/2208). For example: - ![](https://user-images.githubusercontent.com/576385/54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg) + ```c++ + #include -- 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. + int main() { + using tp = std::chrono::time_point< + std::chrono::system_clock, std::chrono::seconds>; + fmt::print("{:%S}", tp(std::chrono::seconds(42))); + } + ``` -- Added [oss-fuzz](https://github.com/google/oss-fuzz) support - (https://github.com/fmtlib/fmt/pull/1199). Thanks @pauldreik. + prints \"42\". -- `formatter` specializations now always take precedence over - `operator<<` (https://github.com/fmtlib/fmt/issues/952): +- Formatting floating-point numbers no longer produces trailing zeros + by default for consistency with `std::format`. For example: - ```c++ - #include - #include + ```c++ + #include - struct S {}; + int main() { + fmt::print("{0:.3}", 1.1); + } + ``` - std::ostream& operator<<(std::ostream& os, S) { - return os << 1; - } + prints \"1.1\". Use the `'#'` specifier to keep trailing zeros. - template <> - struct fmt::formatter : fmt::formatter { - auto format(S, format_context& ctx) { - return formatter::format(2, ctx); - } - }; +- Dropped a limit on the number of elements in a range and replaced + `{}` with `[]` as range delimiters for consistency with Python\'s + `str.format`. - int main() { - std::cout << S() << "\n"; // prints 1 using operator<< - fmt::print("{}\n", S()); // prints 2 using formatter - } - ``` +- The `'L'` specifier for locale-specific numeric formatting can now + be combined with presentation specifiers as in `std::format`. For + example: -- Introduced the experimental `fmt::compile` function that does format - string compilation - (https://github.com/fmtlib/fmt/issues/618, - https://github.com/fmtlib/fmt/issues/1169, - https://github.com/fmtlib/fmt/pull/1171): + ```c++ + #include + #include - ```c++ - #include + int main() { + std::locale::global(std::locale("fr_FR.UTF-8")); + fmt::print("{0:.2Lf}", 0.42); + } + ``` - auto f = fmt::compile("{}"); - std::string s = fmt::format(f, 42); // can be called multiple times to - // format different values - // s == "42" - ``` + prints \"0,42\". The deprecated `'n'` specifier has been removed. - 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. +- Made the `0` specifier ignored for infinity and NaN + (https://github.com/fmtlib/fmt/issues/2305, + https://github.com/fmtlib/fmt/pull/2310). Thanks @Liedtke. -- Added experimental `%` format specifier that formats floating-point - values as percentages - (https://github.com/fmtlib/fmt/pull/1060, - https://github.com/fmtlib/fmt/pull/1069, - https://github.com/fmtlib/fmt/pull/1071): +- Made the hexfloat formatting use the right alignment by default + (https://github.com/fmtlib/fmt/issues/2308, + https://github.com/fmtlib/fmt/pull/2317). Thanks @Liedtke. - ```c++ - auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%" - ``` +- Removed the deprecated numeric alignment (`'='`). Use the `'0'` + specifier instead. - Thanks @gawain-bolton. +- Removed the deprecated `fmt/posix.h` header that has been replaced + with `fmt/os.h`. -- Implemented precision for floating-point durations - (https://github.com/fmtlib/fmt/issues/1004, - https://github.com/fmtlib/fmt/pull/1012): +- Removed the deprecated `format_to_n_context`, `format_to_n_args` and + `make_format_to_n_args`. They have been replaced with + `format_context`, `` format_args` and ``make_format_args\`\` + respectively. - ```c++ - auto s = fmt::format("{:.1}", std::chrono::duration(1.234)); - // s == 1.2s - ``` +- Moved `wchar_t`-specific functions and types to `fmt/xchar.h`. You + can define `FMT_DEPRECATED_INCLUDE_XCHAR` to automatically include + `fmt/xchar.h` from `fmt/format.h` but this will be disabled in the + next major release. - Thanks @DanielaE. +- Fixed handling of the `'+'` specifier in localized formatting + (https://github.com/fmtlib/fmt/issues/2133). -- Implemented `chrono` format specifiers `%Q` and `%q` that give the - value and the unit respectively - (https://github.com/fmtlib/fmt/pull/1019): +- Added support for the `'s'` format specifier that gives textual + representation of `bool` + (https://github.com/fmtlib/fmt/issues/2094, + https://github.com/fmtlib/fmt/pull/2109). For example: - ```c++ - auto value = fmt::format("{:%Q}", 42s); // value == "42" - auto unit = fmt::format("{:%q}", 42s); // unit == "s" - ``` + ```c++ + #include - Thanks @DanielaE. + int main() { + fmt::print("{:s}", true); + } + ``` -- Fixed handling of dynamic width in chrono formatter: + prints \"true\". Thanks @powercoderlol. - ```c++ - auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); - // ^ width argument index ^ width - // s == "03:25:45 " - ``` +- Made `fmt::ptr` work with function pointers + (https://github.com/fmtlib/fmt/pull/2131). For example: - Thanks Howard Hinnant. + ```c++ + #include -- Removed deprecated `fmt/time.h`. Use `fmt/chrono.h` instead. + int main() { + fmt::print("My main: {}\n", fmt::ptr(main)); + } + ``` -- Added `fmt::format` and `fmt::vformat` overloads that take - `text_style` (https://github.com/fmtlib/fmt/issues/993, - https://github.com/fmtlib/fmt/pull/994): + Thanks @mikecrowe. - ```c++ - #include +- The undocumented support for specializing `formatter` for pointer + types has been removed. - std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), - "The answer is {}.", 42); - ``` +- Fixed `fmt::formatted_size` with format string compilation + (https://github.com/fmtlib/fmt/pull/2141, + https://github.com/fmtlib/fmt/pull/2161). Thanks @alexezeder. - Thanks @Naios. +- Fixed handling of empty format strings during format string + compilation (https://github.com/fmtlib/fmt/issues/2042): -- Removed the deprecated color API (`print_colored`). Use the new API, - namely `print` overloads that take `text_style` instead. + ```c++ + auto s = fmt::format(FMT_COMPILE("")); + ``` -- Made `std::unique_ptr` and `std::shared_ptr` formattable as pointers - via `fmt::ptr` (https://github.com/fmtlib/fmt/pull/1121): + Thanks @alexezeder. - ```c++ - std::unique_ptr p = ...; - fmt::print("{}", fmt::ptr(p)); // prints p as a pointer - ``` +- Fixed handling of enums in `fmt::to_string` + (https://github.com/fmtlib/fmt/issues/2036). - Thanks @sighingnow. +- Improved width computation + (https://github.com/fmtlib/fmt/issues/2033, + https://github.com/fmtlib/fmt/issues/2091). For example: -- Made `print` and `vprint` report I/O errors - (https://github.com/fmtlib/fmt/issues/1098, - https://github.com/fmtlib/fmt/pull/1099). Thanks @BillyDonahue. + ```c++ + #include -- Marked deprecated APIs with the `[[deprecated]]` attribute and - removed internal uses of deprecated APIs - (https://github.com/fmtlib/fmt/pull/1022). Thanks @eliaskosunen. + int main() { + fmt::print("{:-<10}{}\n", "你好", "世界"); + fmt::print("{:-<10}{}\n", "hello", "world"); + } + ``` -- Modernized the codebase using more C++11 features and removing - workarounds. Most importantly, `buffer_context` is now an alias - template, so use `buffer_context` instead of - `buffer_context::type`. These features require GCC 4.8 or later. + prints -- `formatter` specializations now always take precedence over implicit - conversions to `int` and the undocumented `convert_to_int` trait is - now deprecated. + ![](https://user-images.githubusercontent.com/576385/119840373-cea3ca80-beb9-11eb-91e0-54266c48e181.png) -- Moved the undocumented `basic_writer`, `writer`, and `wwriter` types - to the `internal` namespace. + on a modern terminal. -- Removed deprecated `basic_format_context::begin()`. Use `out()` - instead. +- The experimental fast output stream (`fmt::ostream`) is now + truncated by default for consistency with `fopen` + (https://github.com/fmtlib/fmt/issues/2018). For example: -- Disallowed passing the result of `join` as an lvalue to prevent - misuse. + ```c++ + #include -- 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 - (https://github.com/fmtlib/fmt/issues/1229, - https://github.com/fmtlib/fmt/pull/1243). Thanks @jackoalan. - -- Improved literal-based API - (https://github.com/fmtlib/fmt/pull/1254). Thanks @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 - (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) - (https://github.com/fmtlib/fmt/issues/1037). Thanks @Kronuz. - -- Added the `FMT_ENFORCE_COMPILE_STRING` macro to enforce the use of - compile-time format strings - (https://github.com/fmtlib/fmt/pull/1231). Thanks @jackoalan. - -- Stopped setting `CMAKE_BUILD_TYPE` if {fmt} is a subproject - (https://github.com/fmtlib/fmt/issues/1081). - -- Various build improvements - (https://github.com/fmtlib/fmt/pull/1039, - https://github.com/fmtlib/fmt/pull/1078, - https://github.com/fmtlib/fmt/pull/1091, - https://github.com/fmtlib/fmt/pull/1103, - https://github.com/fmtlib/fmt/pull/1177). - Thanks @luncliff, @jasonszang, @olafhering, @Lecetem and @pauldreik. - -- Improved documentation - (https://github.com/fmtlib/fmt/issues/1049, - https://github.com/fmtlib/fmt/pull/1051, - https://github.com/fmtlib/fmt/pull/1083, - https://github.com/fmtlib/fmt/pull/1113, - https://github.com/fmtlib/fmt/pull/1114, - https://github.com/fmtlib/fmt/issues/1146, - https://github.com/fmtlib/fmt/issues/1180, - https://github.com/fmtlib/fmt/pull/1250, - https://github.com/fmtlib/fmt/pull/1252, - https://github.com/fmtlib/fmt/pull/1265). - Thanks @mikelui, @foonathan, @BillyDonahue, @jwakely, @kaisbe and - @sdebionne. - -- Fixed ambiguous formatter specialization in `fmt/ranges.h` - (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 - (https://github.com/fmtlib/fmt/issues/1268). - -- Fixed handling of general output iterators when formatting - characters (https://github.com/fmtlib/fmt/issues/1056, - https://github.com/fmtlib/fmt/pull/1058). Thanks @abolz. - -- Fixed handling of output iterators in `formatter` specialization for - ranges (https://github.com/fmtlib/fmt/issues/1064). - -- Fixed handling of exotic character types - (https://github.com/fmtlib/fmt/issues/1188). - -- Made chrono formatting work with exceptions disabled - (https://github.com/fmtlib/fmt/issues/1062). - -- Fixed DLL visibility issues - (https://github.com/fmtlib/fmt/pull/1134, - https://github.com/fmtlib/fmt/pull/1147). Thanks @denchat. - -- Disabled the use of UDL template extension on GCC 9 - (https://github.com/fmtlib/fmt/issues/1148). - -- Removed misplaced `format` compile-time checks from `printf` - (https://github.com/fmtlib/fmt/issues/1173). - -- Fixed issues in the experimental floating-point formatter - (https://github.com/fmtlib/fmt/issues/1072, - https://github.com/fmtlib/fmt/issues/1129, - https://github.com/fmtlib/fmt/issues/1153, - https://github.com/fmtlib/fmt/pull/1155, - https://github.com/fmtlib/fmt/issues/1210, - https://github.com/fmtlib/fmt/issues/1222). Thanks @alabuzhev. - -- Fixed bugs discovered by fuzzing or during fuzzing integration - (https://github.com/fmtlib/fmt/issues/1124, - https://github.com/fmtlib/fmt/issues/1127, - https://github.com/fmtlib/fmt/issues/1132, - https://github.com/fmtlib/fmt/pull/1135, - https://github.com/fmtlib/fmt/issues/1136, - https://github.com/fmtlib/fmt/issues/1141, - https://github.com/fmtlib/fmt/issues/1142, - https://github.com/fmtlib/fmt/issues/1178, - https://github.com/fmtlib/fmt/issues/1179, - https://github.com/fmtlib/fmt/issues/1194). Thanks @pauldreik. - -- Fixed building tests on FreeBSD and Hurd - (https://github.com/fmtlib/fmt/issues/1043). Thanks @jackyf. - -- Fixed various warnings and compilation issues - (https://github.com/fmtlib/fmt/pull/998, - https://github.com/fmtlib/fmt/pull/1006, - https://github.com/fmtlib/fmt/issues/1008, - https://github.com/fmtlib/fmt/issues/1011, - https://github.com/fmtlib/fmt/issues/1025, - https://github.com/fmtlib/fmt/pull/1027, - https://github.com/fmtlib/fmt/pull/1028, - https://github.com/fmtlib/fmt/pull/1029, - https://github.com/fmtlib/fmt/pull/1030, - https://github.com/fmtlib/fmt/pull/1031, - https://github.com/fmtlib/fmt/pull/1054, - https://github.com/fmtlib/fmt/issues/1063, - https://github.com/fmtlib/fmt/pull/1068, - https://github.com/fmtlib/fmt/pull/1074, - https://github.com/fmtlib/fmt/pull/1075, - https://github.com/fmtlib/fmt/pull/1079, - https://github.com/fmtlib/fmt/pull/1086, - https://github.com/fmtlib/fmt/issues/1088, - https://github.com/fmtlib/fmt/pull/1089, - https://github.com/fmtlib/fmt/pull/1094, - https://github.com/fmtlib/fmt/issues/1101, - https://github.com/fmtlib/fmt/pull/1102, - https://github.com/fmtlib/fmt/issues/1105, - https://github.com/fmtlib/fmt/pull/1107, - https://github.com/fmtlib/fmt/issues/1115, - https://github.com/fmtlib/fmt/issues/1117, - https://github.com/fmtlib/fmt/issues/1118, - https://github.com/fmtlib/fmt/issues/1120, - https://github.com/fmtlib/fmt/issues/1123, - https://github.com/fmtlib/fmt/pull/1139, - https://github.com/fmtlib/fmt/issues/1140, - https://github.com/fmtlib/fmt/issues/1143, - https://github.com/fmtlib/fmt/pull/1144, - https://github.com/fmtlib/fmt/pull/1150, - https://github.com/fmtlib/fmt/pull/1151, - https://github.com/fmtlib/fmt/issues/1152, - https://github.com/fmtlib/fmt/issues/1154, - https://github.com/fmtlib/fmt/issues/1156, - https://github.com/fmtlib/fmt/pull/1159, - https://github.com/fmtlib/fmt/issues/1175, - https://github.com/fmtlib/fmt/issues/1181, - https://github.com/fmtlib/fmt/issues/1186, - https://github.com/fmtlib/fmt/pull/1187, - https://github.com/fmtlib/fmt/pull/1191, - https://github.com/fmtlib/fmt/issues/1197, - https://github.com/fmtlib/fmt/issues/1200, - https://github.com/fmtlib/fmt/issues/1203, - https://github.com/fmtlib/fmt/issues/1205, - https://github.com/fmtlib/fmt/pull/1206, - https://github.com/fmtlib/fmt/issues/1213, - https://github.com/fmtlib/fmt/issues/1214, - https://github.com/fmtlib/fmt/pull/1217, - https://github.com/fmtlib/fmt/issues/1228, - https://github.com/fmtlib/fmt/pull/1230, - https://github.com/fmtlib/fmt/issues/1232, - https://github.com/fmtlib/fmt/pull/1235, - https://github.com/fmtlib/fmt/pull/1236, - https://github.com/fmtlib/fmt/issues/1240). - Thanks @DanielaE, @mwinterb, @eliaskosunen, @morinmorin, @ricco19, - @waywardmonkeys, @chronoxor, @remyabel, @pauldreik, @gsjaardema, @rcane, - @mocabe, @denchat, @cjdb, @HazardyKnusperkeks, @vedranmiletic, @jackoalan, - @DaanDeMeyer and @starkmapper. - -# 5.3.0 - 2018-12-28 - -- Introduced experimental chrono formatting support: - - ```c++ - #include - - int main() { - using namespace std::literals::chrono_literals; - fmt::print("Default format: {} {}\n", 42s, 100ms); - fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); - } - ``` - - prints: - - Default format: 42s 100ms - strftime-like format: 03:15:30 - -- Added experimental support for emphasis (bold, italic, underline, - strikethrough), colored output to a file stream, and improved - colored formatting API - (https://github.com/fmtlib/fmt/pull/961, - https://github.com/fmtlib/fmt/pull/967, - https://github.com/fmtlib/fmt/pull/973): - - ```c++ - #include - - int main() { - print(fg(fmt::color::crimson) | fmt::emphasis::bold, - "Hello, {}!\n", "world"); - print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | - fmt::emphasis::underline, "Hello, {}!\n", "мир"); - print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, - "Hello, {}!\n", "世界"); - } - ``` - - prints the following on modern terminals with RGB color support: - - ![](https://user-images.githubusercontent.com/576385/50405788-b66e7500-076e-11e9-9592-7324d1f951d8.png) - - Thanks @Rakete1111. - -- Added support for 4-bit terminal colors - (https://github.com/fmtlib/fmt/issues/968, - https://github.com/fmtlib/fmt/pull/974) - - ```c++ - #include - - int main() { - print(fg(fmt::terminal_color::red), "stop\n"); - } - ``` - - Note that these colors vary by terminal: - - ![](https://user-images.githubusercontent.com/576385/50405925-dbfc7e00-0770-11e9-9b85-333fab0af9ac.png) - - Thanks @Rakete1111. - -- Parameterized formatting functions on the type of the format string - (https://github.com/fmtlib/fmt/issues/880, - https://github.com/fmtlib/fmt/pull/881, - https://github.com/fmtlib/fmt/pull/883, - https://github.com/fmtlib/fmt/pull/885, - https://github.com/fmtlib/fmt/pull/897, - https://github.com/fmtlib/fmt/issues/920). Any object of - type `S` that has an overloaded `to_string_view(const S&)` returning - `fmt::string_view` can be used as a format string: - - ```c++ - namespace my_ns { - inline string_view to_string_view(const my_string& s) { - return {s.data(), s.length()}; - } - } - - std::string message = fmt::format(my_string("The answer is {}."), 42); - ``` - - Thanks @DanielaE. - -- Made `std::string_view` work as a format string - (https://github.com/fmtlib/fmt/pull/898): - - ```c++ - auto message = fmt::format(std::string_view("The answer is {}."), 42); - ``` - - Thanks @DanielaE. - -- Added wide string support to compile-time format string checks - (https://github.com/fmtlib/fmt/pull/924): - - ```c++ - print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier - ``` - - Thanks @XZiar. - -- Made colored print functions work with wide strings - (https://github.com/fmtlib/fmt/pull/867): - - ```c++ - #include - - int main() { - print(fg(fmt::color::red), L"{}\n", 42); - } - ``` - - Thanks @DanielaE. - -- Introduced experimental Unicode support - (https://github.com/fmtlib/fmt/issues/628, - https://github.com/fmtlib/fmt/pull/891): - - ```c++ - using namespace fmt::literals; - auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u - ``` - -- Improved locale support: - - ```c++ - #include - - struct numpunct : std::numpunct { - protected: - char do_thousands_sep() const override { return '~'; } - }; - - std::locale loc; - auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567); - // s == "1~234~567" - ``` - -- Constrained formatting functions on proper iterator types - (https://github.com/fmtlib/fmt/pull/921). Thanks @DanielaE. - -- Added `make_printf_args` and `make_wprintf_args` functions - (https://github.com/fmtlib/fmt/pull/934). Thanks @tnovotny. - -- Deprecated `fmt::visit`, `parse_context`, and `wparse_context`. Use - `fmt::visit_format_arg`, `format_parse_context`, and - `wformat_parse_context` instead. - -- Removed undocumented `basic_fixed_buffer` which has been superseded - by the iterator-based API - (https://github.com/fmtlib/fmt/issues/873, - https://github.com/fmtlib/fmt/pull/902). Thanks @superfunc. - -- Disallowed repeated leading zeros in an argument ID: - - ```c++ - fmt::print("{000}", 42); // error - ``` - -- Reintroduced support for gcc 4.4. - -- Fixed compilation on platforms with exotic `double` - (https://github.com/fmtlib/fmt/issues/878). - -- Improved documentation - (https://github.com/fmtlib/fmt/issues/164, - https://github.com/fmtlib/fmt/issues/877, - https://github.com/fmtlib/fmt/pull/901, - https://github.com/fmtlib/fmt/pull/906, - https://github.com/fmtlib/fmt/pull/979). - Thanks @kookjr, @DarkDimius and @HecticSerenity. - -- Added pkgconfig support which makes it easier to consume the library - from meson and other build systems - (https://github.com/fmtlib/fmt/pull/916). Thanks @colemickens. - -- Various build improvements - (https://github.com/fmtlib/fmt/pull/909, - https://github.com/fmtlib/fmt/pull/926, - https://github.com/fmtlib/fmt/pull/937, - https://github.com/fmtlib/fmt/pull/953, - https://github.com/fmtlib/fmt/pull/959). - Thanks @tchaikov, @luncliff, @AndreasSchoenle, @hotwatermorning and @Zefz. - -- Improved `string_view` construction performance - (https://github.com/fmtlib/fmt/pull/914). Thanks @gabime. - -- Fixed non-matching char types - (https://github.com/fmtlib/fmt/pull/895). Thanks @DanielaE. - -- Fixed `format_to_n` with `std::back_insert_iterator` - (https://github.com/fmtlib/fmt/pull/913). Thanks @DanielaE. - -- Fixed locale-dependent formatting - (https://github.com/fmtlib/fmt/issues/905). - -- Fixed various compiler warnings and errors - (https://github.com/fmtlib/fmt/pull/882, - https://github.com/fmtlib/fmt/pull/886, - https://github.com/fmtlib/fmt/pull/933, - https://github.com/fmtlib/fmt/pull/941, - https://github.com/fmtlib/fmt/issues/931, - https://github.com/fmtlib/fmt/pull/943, - https://github.com/fmtlib/fmt/pull/954, - https://github.com/fmtlib/fmt/pull/956, - https://github.com/fmtlib/fmt/pull/962, - https://github.com/fmtlib/fmt/issues/965, - https://github.com/fmtlib/fmt/issues/977, - https://github.com/fmtlib/fmt/pull/983, - https://github.com/fmtlib/fmt/pull/989). - Thanks @Luthaf, @stevenhoving, @christinaa, @lgritz, @DanielaE, - @0x8000-0000 and @liuping1997. - -# 5.2.1 - 2018-09-21 - -- Fixed `visit` lookup issues on gcc 7 & 8 - (https://github.com/fmtlib/fmt/pull/870). Thanks @medithe. -- Fixed linkage errors on older gcc. -- Prevented `fmt/range.h` from specializing `fmt::basic_string_view` - (https://github.com/fmtlib/fmt/issues/865, - https://github.com/fmtlib/fmt/pull/868). Thanks @hhggit. -- Improved error message when formatting unknown types - (https://github.com/fmtlib/fmt/pull/872). Thanks @foonathan. -- Disabled templated user-defined literals when compiled under nvcc - (https://github.com/fmtlib/fmt/pull/875). Thanks @CandyGumdrop. -- Fixed `format_to` formatting to `wmemory_buffer` - (https://github.com/fmtlib/fmt/issues/874). - -# 5.2.0 - 2018-09-13 - -- Optimized format string parsing and argument processing which - resulted in up to 5x speed up on long format strings and significant - performance boost on various benchmarks. For example, version 5.2 is - 2.22x faster than 5.1 on decimal integer formatting with `format_to` - (macOS, clang-902.0.39.2): - - | Method | Time, s | Speedup | - | -------------------------- | --------------: | ------: | - | fmt::format 5.1 | 0.58 | | - | fmt::format 5.2 | 0.35 | 1.66x | - | fmt::format_to 5.1 | 0.51 | | - | fmt::format_to 5.2 | 0.23 | 2.22x | - | sprintf | 0.71 | | - | std::to_string | 1.01 | | - | std::stringstream | 1.73 | | - -- Changed the `fmt` macro from opt-out to opt-in to prevent name - collisions. To enable it define the `FMT_STRING_ALIAS` macro to 1 - before including `fmt/format.h`: - - ```c++ - #define FMT_STRING_ALIAS 1 - #include - std::string answer = format(fmt("{}"), 42); - ``` - -- Added compile-time format string checks to `format_to` overload that - takes `fmt::memory_buffer` - (https://github.com/fmtlib/fmt/issues/783): - - ```c++ - fmt::memory_buffer buf; - // Compile-time error: invalid type specifier. - fmt::format_to(buf, fmt("{:d}"), "foo"); - ``` - -- Moved experimental color support to `fmt/color.h` and enabled the - new API by default. The old API can be enabled by defining the - `FMT_DEPRECATED_COLORS` macro. - -- Added formatting support for types explicitly convertible to - `fmt::string_view`: - - ```c++ - struct foo { - explicit operator fmt::string_view() const { return "foo"; } - }; - auto s = format("{}", foo()); - ``` - - In particular, this makes formatting function work with - `folly::StringPiece`. - -- Implemented preliminary support for `char*_t` by replacing the - `format` function overloads with a single function template - parameterized on the string type. - -- Added support for dynamic argument lists - (https://github.com/fmtlib/fmt/issues/814, - https://github.com/fmtlib/fmt/pull/819). Thanks @MikePopoloski. - -- Reduced executable size overhead for embedded targets using newlib - nano by making locale dependency optional - (https://github.com/fmtlib/fmt/pull/839). Thanks @teajay-fr. - -- Keep `noexcept` specifier when exceptions are disabled - (https://github.com/fmtlib/fmt/issues/801, - https://github.com/fmtlib/fmt/pull/810). Thanks @qis. - -- Fixed formatting of user-defined types providing `operator<<` with - `format_to_n` (https://github.com/fmtlib/fmt/pull/806). - Thanks @mkurdej. - -- Fixed dynamic linkage of new symbols - (https://github.com/fmtlib/fmt/issues/808). - -- Fixed global initialization issue - (https://github.com/fmtlib/fmt/issues/807): - - ```c++ - // This works on compilers with constexpr support. - static const std::string answer = fmt::format("{}", 42); - ``` - -- Fixed various compiler warnings and errors - (https://github.com/fmtlib/fmt/pull/804, - https://github.com/fmtlib/fmt/issues/809, - https://github.com/fmtlib/fmt/pull/811, - https://github.com/fmtlib/fmt/issues/822, - https://github.com/fmtlib/fmt/pull/827, - https://github.com/fmtlib/fmt/issues/830, - https://github.com/fmtlib/fmt/pull/838, - https://github.com/fmtlib/fmt/issues/843, - https://github.com/fmtlib/fmt/pull/844, - https://github.com/fmtlib/fmt/issues/851, - https://github.com/fmtlib/fmt/pull/852, - https://github.com/fmtlib/fmt/pull/854). - Thanks @henryiii, @medithe, and @eliasdaler. - -# 5.1.0 - 2018-07-05 - -- Added experimental support for RGB color output enabled with the - `FMT_EXTENDED_COLORS` macro: - - ```c++ - #define FMT_EXTENDED_COLORS - #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined - #include - - fmt::print(fmt::color::steel_blue, "Some beautiful text"); - ``` - - The old API (the `print_colored` and `vprint_colored` functions and - the `color` enum) is now deprecated. - (https://github.com/fmtlib/fmt/issues/762 - https://github.com/fmtlib/fmt/pull/767). thanks @Remotion. - -- Added quotes to strings in ranges and tuples - (https://github.com/fmtlib/fmt/pull/766). Thanks @Remotion. - -- Made `format_to` work with `basic_memory_buffer` - (https://github.com/fmtlib/fmt/issues/776). - -- Added `vformat_to_n` and `wchar_t` overload of `format_to_n` - (https://github.com/fmtlib/fmt/issues/764, - https://github.com/fmtlib/fmt/issues/769). - -- Made `is_range` and `is_tuple_like` part of public (experimental) - API to allow specialization for user-defined types - (https://github.com/fmtlib/fmt/issues/751, - https://github.com/fmtlib/fmt/pull/759). Thanks @drrlvn. - -- Added more compilers to continuous integration and increased - `FMT_PEDANTIC` warning levels - (https://github.com/fmtlib/fmt/pull/736). Thanks @eliaskosunen. - -- Fixed compilation with MSVC 2013. - -- Fixed handling of user-defined types in `format_to` - (https://github.com/fmtlib/fmt/issues/793). - -- Forced linking of inline `vformat` functions into the library - (https://github.com/fmtlib/fmt/issues/795). - -- Fixed incorrect call to on_align in `'{:}='` - (https://github.com/fmtlib/fmt/issues/750). - -- Fixed floating-point formatting to a non-back_insert_iterator with - sign & numeric alignment specified - (https://github.com/fmtlib/fmt/issues/756). - -- Fixed formatting to an array with `format_to_n` - (https://github.com/fmtlib/fmt/issues/778). - -- Fixed formatting of more than 15 named arguments - (https://github.com/fmtlib/fmt/issues/754). - -- Fixed handling of compile-time strings when including - `fmt/ostream.h`. (https://github.com/fmtlib/fmt/issues/768). - -- Fixed various compiler warnings and errors - (https://github.com/fmtlib/fmt/issues/742, - https://github.com/fmtlib/fmt/issues/748, - https://github.com/fmtlib/fmt/issues/752, - https://github.com/fmtlib/fmt/issues/770, - https://github.com/fmtlib/fmt/pull/775, - https://github.com/fmtlib/fmt/issues/779, - https://github.com/fmtlib/fmt/pull/780, - https://github.com/fmtlib/fmt/pull/790, - https://github.com/fmtlib/fmt/pull/792, - https://github.com/fmtlib/fmt/pull/800). - Thanks @Remotion, @gabime, @foonathan, @Dark-Passenger and @0x8000-0000. - -# 5.0.0 - 2018-05-21 - -- Added a requirement for partial C++11 support, most importantly - variadic templates and type traits, and dropped `FMT_VARIADIC_*` - emulation macros. Variadic templates are available since GCC 4.4, - Clang 2.9 and MSVC 18.0 (2013). For older compilers use {fmt} - [version 4.x](https://github.com/fmtlib/fmt/releases/tag/4.1.0) - which continues to be maintained and works with C++98 compilers. - -- Renamed symbols to follow standard C++ naming conventions and - proposed a subset of the library for standardization in [P0645R2 - Text Formatting](https://wg21.link/P0645). - -- Implemented `constexpr` parsing of format strings and [compile-time - format string - checks](https://fmt.dev/latest/api.html#compile-time-format-string-checks). - For example - - ```c++ - #include - - std::string s = format(fmt("{:d}"), "foo"); - ``` - - gives a compile-time error because `d` is an invalid specifier for - strings ([godbolt](https://godbolt.org/g/rnCy9Q)): - - ... - :4:19: note: in instantiation of function template specialization 'fmt::v5::format' requested here - std::string s = format(fmt("{:d}"), "foo"); - ^ - format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression - handler.on_error("invalid type specifier"); - - Compile-time checks require relaxed `constexpr` (C++14 feature) - support. If the latter is not available, checks will be performed at - runtime. - -- Separated format string parsing and formatting in the extension API - to enable compile-time format string processing. For example - - ```c++ - struct Answer {}; - - namespace fmt { - template <> - struct formatter { - constexpr auto parse(parse_context& ctx) { - auto it = ctx.begin(); - spec = *it; - if (spec != 'd' && spec != 's') - throw format_error("invalid specifier"); - return ++it; - } - - template - auto format(Answer, FormatContext& ctx) { - return spec == 's' ? - format_to(ctx.begin(), "{}", "fourty-two") : - format_to(ctx.begin(), "{}", 42); - } - - char spec = 0; - }; - } - - std::string s = format(fmt("{:x}"), Answer()); - ``` - - gives a compile-time error due to invalid format specifier - ([godbolt](https://godbolt.org/g/2jQ1Dv)): - - ... - :12:45: error: expression '' is not a constant expression - throw format_error("invalid specifier"); - -- Added [iterator - support](https://fmt.dev/latest/api.html#output-iterator-support): - - ```c++ - #include - #include - - std::vector out; - fmt::format_to(std::back_inserter(out), "{}", 42); - ``` - -- Added the - [format_to_n](https://fmt.dev/latest/api.html#_CPPv2N3fmt11format_to_nE8OutputItNSt6size_tE11string_viewDpRK4Args) - function that restricts the output to the specified number of - characters (https://github.com/fmtlib/fmt/issues/298): - - ```c++ - char out[4]; - fmt::format_to_n(out, sizeof(out), "{}", 12345); - // out == "1234" (without terminating '\0') - ``` - -- Added the [formatted_size]( - https://fmt.dev/latest/api.html#_CPPv2N3fmt14formatted_sizeE11string_viewDpRK4Args) - function for computing the output size: - - ```c++ - #include - - auto size = fmt::formatted_size("{}", 12345); // size == 5 - ``` - -- Improved compile times by reducing dependencies on standard headers - and providing a lightweight [core - API](https://fmt.dev/latest/api.html#core-api): - - ```c++ - #include - - fmt::print("The answer is {}.", 42); - ``` - - See [Compile time and code - bloat](https://github.com/fmtlib/fmt#compile-time-and-code-bloat). - -- Added the [make_format_args]( - https://fmt.dev/latest/api.html#_CPPv2N3fmt16make_format_argsEDpRK4Args) - function for capturing formatting arguments: - - ```c++ - // Prints formatted error message. - void vreport_error(const char *format, fmt::format_args args) { - fmt::print("Error: "); - fmt::vprint(format, args); - } - template - void report_error(const char *format, const Args & ... args) { - vreport_error(format, fmt::make_format_args(args...)); - } - ``` - -- Added the `make_printf_args` function for capturing `printf` - arguments (https://github.com/fmtlib/fmt/issues/687, - https://github.com/fmtlib/fmt/pull/694). Thanks @Kronuz. - -- Added prefix `v` to non-variadic functions taking `format_args` to - distinguish them from variadic ones: - - ```c++ - std::string vformat(string_view format_str, format_args args); - - template - std::string format(string_view format_str, const Args & ... args); - ``` - -- Added experimental support for formatting ranges, containers and - tuple-like types in `fmt/ranges.h` - (https://github.com/fmtlib/fmt/pull/735): - - ```c++ - #include - - std::vector v = {1, 2, 3}; - fmt::print("{}", v); // prints {1, 2, 3} - ``` - - Thanks @Remotion. - -- Implemented `wchar_t` date and time formatting - (https://github.com/fmtlib/fmt/pull/712): - - ```c++ - #include - - std::time_t t = std::time(nullptr); - auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t)); - ``` - - Thanks @DanielaE. - -- Provided more wide string overloads - (https://github.com/fmtlib/fmt/pull/724). Thanks @DanielaE. - -- Switched from a custom null-terminated string view class to - `string_view` in the format API and provided `fmt::string_view` - which implements a subset of `std::string_view` API for pre-C++17 - systems. - -- Added support for `std::experimental::string_view` - (https://github.com/fmtlib/fmt/pull/607): - - ```c++ - #include - #include - - fmt::print("{}", std::experimental::string_view("foo")); - ``` - - Thanks @virgiliofornazin. - -- Allowed mixing named and automatic arguments: - - ```c++ - fmt::format("{} {two}", 1, fmt::arg("two", 2)); - ``` - -- Removed the write API in favor of the [format - API](https://fmt.dev/latest/api.html#format-api) with compile-time - handling of format strings. - -- Disallowed formatting of multibyte strings into a wide character - target (https://github.com/fmtlib/fmt/pull/606). - -- Improved documentation - (https://github.com/fmtlib/fmt/pull/515, - https://github.com/fmtlib/fmt/issues/614, - https://github.com/fmtlib/fmt/pull/617, - https://github.com/fmtlib/fmt/pull/661, - https://github.com/fmtlib/fmt/pull/680). - Thanks @ibell, @mihaitodor and @johnthagen. - -- Implemented more efficient handling of large number of format - arguments. - -- Introduced an inline namespace for symbol versioning. - -- Added debug postfix `d` to the `fmt` library name - (https://github.com/fmtlib/fmt/issues/636). - -- Removed unnecessary `fmt/` prefix in includes - (https://github.com/fmtlib/fmt/pull/397). Thanks @chronoxor. - -- Moved `fmt/*.h` to `include/fmt/*.h` to prevent irrelevant files and - directories appearing on the include search paths when fmt is used - as a subproject and moved source files to the `src` directory. - -- Added qmake project file `support/fmt.pro` - (https://github.com/fmtlib/fmt/pull/641). Thanks @cowo78. - -- Added Gradle build file `support/build.gradle` - (https://github.com/fmtlib/fmt/pull/649). Thanks @luncliff. - -- Removed `FMT_CPPFORMAT` CMake option. - -- Fixed a name conflict with the macro `CHAR_WIDTH` in glibc - (https://github.com/fmtlib/fmt/pull/616). Thanks @aroig. - -- Fixed handling of nested braces in `fmt::join` - (https://github.com/fmtlib/fmt/issues/638). - -- Added `SOURCELINK_SUFFIX` for compatibility with Sphinx 1.5 - (https://github.com/fmtlib/fmt/pull/497). Thanks @ginggs. - -- Added a missing `inline` in the header-only mode - (https://github.com/fmtlib/fmt/pull/626). Thanks @aroig. - -- Fixed various compiler warnings - (https://github.com/fmtlib/fmt/pull/640, - https://github.com/fmtlib/fmt/pull/656, - https://github.com/fmtlib/fmt/pull/679, - https://github.com/fmtlib/fmt/pull/681, - https://github.com/fmtlib/fmt/pull/705, - https://github.com/fmtlib/fmt/issues/715, - https://github.com/fmtlib/fmt/pull/717, - https://github.com/fmtlib/fmt/pull/720, - https://github.com/fmtlib/fmt/pull/723, - https://github.com/fmtlib/fmt/pull/726, - https://github.com/fmtlib/fmt/pull/730, - https://github.com/fmtlib/fmt/pull/739). - Thanks @peterbell10, @LarsGullik, @foonathan, @eliaskosunen, - @christianparpart, @DanielaE and @mwinterb. - -- Worked around an MSVC bug and fixed several warnings - (https://github.com/fmtlib/fmt/pull/653). Thanks @alabuzhev. - -- Worked around GCC bug 67371 - (https://github.com/fmtlib/fmt/issues/682). - -- Fixed compilation with `-fno-exceptions` - (https://github.com/fmtlib/fmt/pull/655). Thanks @chenxiaolong. - -- Made `constexpr remove_prefix` gcc version check tighter - (https://github.com/fmtlib/fmt/issues/648). - -- Renamed internal type enum constants to prevent collision with - poorly written C libraries - (https://github.com/fmtlib/fmt/issues/644). - -- Added detection of `wostream operator<<` - (https://github.com/fmtlib/fmt/issues/650). - -- Fixed compilation on OpenBSD - (https://github.com/fmtlib/fmt/pull/660). Thanks @hubslave. - -- Fixed compilation on FreeBSD 12 - (https://github.com/fmtlib/fmt/pull/732). Thanks @dankm. - -- Fixed compilation when there is a mismatch between `-std` options - between the library and user code - (https://github.com/fmtlib/fmt/issues/664). - -- Fixed compilation with GCC 7 and `-std=c++11` - (https://github.com/fmtlib/fmt/issues/734). - -- Improved generated binary code on GCC 7 and older - (https://github.com/fmtlib/fmt/issues/668). - -- Fixed handling of numeric alignment with no width - (https://github.com/fmtlib/fmt/issues/675). - -- Fixed handling of empty strings in UTF8/16 converters - (https://github.com/fmtlib/fmt/pull/676). Thanks @vgalka-sl. - -- Fixed formatting of an empty `string_view` - (https://github.com/fmtlib/fmt/issues/689). - -- Fixed detection of `string_view` on libc++ - (https://github.com/fmtlib/fmt/issues/686). - -- Fixed DLL issues (https://github.com/fmtlib/fmt/pull/696). - Thanks @sebkoenig. - -- Fixed compile checks for mixing narrow and wide strings - (https://github.com/fmtlib/fmt/issues/690). - -- Disabled unsafe implicit conversion to `std::string` - (https://github.com/fmtlib/fmt/issues/729). - -- Fixed handling of reused format specs (as in `fmt::join`) for - pointers (https://github.com/fmtlib/fmt/pull/725). Thanks @mwinterb. - -- Fixed installation of `fmt/ranges.h` - (https://github.com/fmtlib/fmt/pull/738). Thanks @sv1990. - -# 4.1.0 - 2017-12-20 - -- Added `fmt::to_wstring()` in addition to `fmt::to_string()` - (https://github.com/fmtlib/fmt/pull/559). Thanks @alabuzhev. -- Added support for C++17 `std::string_view` - (https://github.com/fmtlib/fmt/pull/571 and - https://github.com/fmtlib/fmt/pull/578). - Thanks @thelostt and @mwinterb. -- Enabled stream exceptions to catch errors - (https://github.com/fmtlib/fmt/issues/581). Thanks @crusader-mike. -- Allowed formatting of class hierarchies with `fmt::format_arg()` - (https://github.com/fmtlib/fmt/pull/547). Thanks @rollbear. -- Removed limitations on character types - (https://github.com/fmtlib/fmt/pull/563). Thanks @Yelnats321. -- Conditionally enabled use of `std::allocator_traits` - (https://github.com/fmtlib/fmt/pull/583). Thanks @mwinterb. -- Added support for `const` variadic member function emulation with - `FMT_VARIADIC_CONST` - (https://github.com/fmtlib/fmt/pull/591). Thanks @ludekvodicka. -- Various bugfixes: bad overflow check, unsupported implicit type - conversion when determining formatting function, test segfaults - (https://github.com/fmtlib/fmt/issues/551), ill-formed - macros (https://github.com/fmtlib/fmt/pull/542) and - ambiguous overloads - (https://github.com/fmtlib/fmt/issues/580). Thanks @xylosper. -- Prevented warnings on MSVC - (https://github.com/fmtlib/fmt/pull/605, - https://github.com/fmtlib/fmt/pull/602, and - https://github.com/fmtlib/fmt/pull/545), clang - (https://github.com/fmtlib/fmt/pull/582), GCC - (https://github.com/fmtlib/fmt/issues/573), various - conversion warnings (https://github.com/fmtlib/fmt/pull/609, - https://github.com/fmtlib/fmt/pull/567, - https://github.com/fmtlib/fmt/pull/553 and - https://github.com/fmtlib/fmt/pull/553), and added - `override` and `[[noreturn]]` - (https://github.com/fmtlib/fmt/pull/549 and - https://github.com/fmtlib/fmt/issues/555). - Thanks @alabuzhev, @virgiliofornazin, @alexanderbock, @yumetodo, @VaderY, - @jpcima, @thelostt and @Manu343726. -- Improved CMake: Used `GNUInstallDirs` to set installation location - (https://github.com/fmtlib/fmt/pull/610) and fixed warnings - (https://github.com/fmtlib/fmt/pull/536 and - https://github.com/fmtlib/fmt/pull/556). - Thanks @mikecrowe, @evgen231 and @henryiii. - -# 4.0.0 - 2017-06-27 - -- Removed old compatibility headers `cppformat/*.h` and CMake options - (https://github.com/fmtlib/fmt/pull/527). Thanks @maddinat0r. - -- Added `string.h` containing `fmt::to_string()` as alternative to - `std::to_string()` as well as other string writer functionality - (https://github.com/fmtlib/fmt/issues/326 and - https://github.com/fmtlib/fmt/pull/441): - - ```c++ - #include "fmt/string.h" - - std::string answer = fmt::to_string(42); - ``` - - Thanks @glebov-andrey. - -- Moved `fmt::printf()` to new `printf.h` header and allowed `%s` as - generic specifier (https://github.com/fmtlib/fmt/pull/453), - made `%.f` more conformant to regular `printf()` - (https://github.com/fmtlib/fmt/pull/490), added custom - writer support (https://github.com/fmtlib/fmt/issues/476) - and implemented missing custom argument formatting - (https://github.com/fmtlib/fmt/pull/339 and - https://github.com/fmtlib/fmt/pull/340): - - ```c++ - #include "fmt/printf.h" - - // %s format specifier can be used with any argument type. - fmt::printf("%s", 42); - ``` - - Thanks @mojoBrendan, @manylegged and @spacemoose. - See also https://github.com/fmtlib/fmt/issues/360, - https://github.com/fmtlib/fmt/issues/335 and - https://github.com/fmtlib/fmt/issues/331. - -- Added `container.h` containing a `BasicContainerWriter` to write to - containers like `std::vector` - (https://github.com/fmtlib/fmt/pull/450). Thanks @polyvertex. - -- Added `fmt::join()` function that takes a range and formats its - elements separated by a given string - (https://github.com/fmtlib/fmt/pull/466): - - ```c++ - #include "fmt/format.h" - - std::vector v = {1.2, 3.4, 5.6}; - // Prints "(+01.20, +03.40, +05.60)". - fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", ")); - ``` - - Thanks @olivier80. - -- Added support for custom formatting specifications to simplify - customization of built-in formatting - (https://github.com/fmtlib/fmt/pull/444). Thanks @polyvertex. - See also https://github.com/fmtlib/fmt/issues/439. - -- Added `fmt::format_system_error()` for error code formatting - (https://github.com/fmtlib/fmt/issues/323 and - https://github.com/fmtlib/fmt/pull/526). Thanks @maddinat0r. - -- Added thread-safe `fmt::localtime()` and `fmt::gmtime()` as - replacement for the standard version to `time.h` - (https://github.com/fmtlib/fmt/pull/396). Thanks @codicodi. - -- Internal improvements to `NamedArg` and `ArgLists` - (https://github.com/fmtlib/fmt/pull/389 and - https://github.com/fmtlib/fmt/pull/390). Thanks @chronoxor. - -- Fixed crash due to bug in `FormatBuf` - (https://github.com/fmtlib/fmt/pull/493). Thanks @effzeh. See also - https://github.com/fmtlib/fmt/issues/480 and - https://github.com/fmtlib/fmt/issues/491. - -- Fixed handling of wide strings in `fmt::StringWriter`. - -- Improved compiler error messages - (https://github.com/fmtlib/fmt/issues/357). - -- Fixed various warnings and issues with various compilers - (https://github.com/fmtlib/fmt/pull/494, - https://github.com/fmtlib/fmt/pull/499, - https://github.com/fmtlib/fmt/pull/483, - https://github.com/fmtlib/fmt/pull/485, - https://github.com/fmtlib/fmt/pull/482, - https://github.com/fmtlib/fmt/pull/475, - https://github.com/fmtlib/fmt/pull/473 and - https://github.com/fmtlib/fmt/pull/414). - Thanks @chronoxor, @zhaohuaxishi, @pkestene, @dschmidt and @0x414c. - -- Improved CMake: targets are now namespaced - (https://github.com/fmtlib/fmt/pull/511 and - https://github.com/fmtlib/fmt/pull/513), supported - header-only `printf.h` - (https://github.com/fmtlib/fmt/pull/354), fixed issue with - minimal supported library subset - (https://github.com/fmtlib/fmt/issues/418, - https://github.com/fmtlib/fmt/pull/419 and - https://github.com/fmtlib/fmt/pull/420). - Thanks @bjoernthiel, @niosHD, @LogicalKnight and @alabuzhev. - -- Improved documentation (https://github.com/fmtlib/fmt/pull/393). - Thanks @pwm1234. - -# 3.0.2 - 2017-06-14 - -- Added `FMT_VERSION` macro - (https://github.com/fmtlib/fmt/issues/411). -- Used `FMT_NULL` instead of literal `0` - (https://github.com/fmtlib/fmt/pull/409). Thanks @alabuzhev. -- Added extern templates for `format_float` - (https://github.com/fmtlib/fmt/issues/413). -- Fixed implicit conversion issue - (https://github.com/fmtlib/fmt/issues/507). -- Fixed signbit detection - (https://github.com/fmtlib/fmt/issues/423). -- Fixed naming collision - (https://github.com/fmtlib/fmt/issues/425). -- Fixed missing intrinsic for C++/CLI - (https://github.com/fmtlib/fmt/pull/457). Thanks @calumr. -- Fixed Android detection - (https://github.com/fmtlib/fmt/pull/458). Thanks @Gachapen. -- Use lean `windows.h` if not in header-only mode - (https://github.com/fmtlib/fmt/pull/503). Thanks @Quentin01. -- Fixed issue with CMake exporting C++11 flag - (https://github.com/fmtlib/fmt/pull/455). Thanks @EricWF. -- Fixed issue with nvcc and MSVC compiler bug and MinGW - (https://github.com/fmtlib/fmt/issues/505). -- Fixed DLL issues (https://github.com/fmtlib/fmt/pull/469 and - https://github.com/fmtlib/fmt/pull/502). - Thanks @richardeakin and @AndreasSchoenle. -- Fixed test compilation under FreeBSD - (https://github.com/fmtlib/fmt/issues/433). -- Fixed various warnings - (https://github.com/fmtlib/fmt/pull/403, - https://github.com/fmtlib/fmt/pull/410 and - https://github.com/fmtlib/fmt/pull/510). - Thanks @Lecetem, @chenhayat and @trozen. -- Worked around a broken `__builtin_clz` in clang with MS codegen - (https://github.com/fmtlib/fmt/issues/519). -- Removed redundant include - (https://github.com/fmtlib/fmt/issues/479). -- Fixed documentation issues. - -# 3.0.1 - 2016-11-01 - -- Fixed handling of thousands separator - (https://github.com/fmtlib/fmt/issues/353). -- Fixed handling of `unsigned char` strings - (https://github.com/fmtlib/fmt/issues/373). -- Corrected buffer growth when formatting time - (https://github.com/fmtlib/fmt/issues/367). -- Removed warnings under MSVC and clang - (https://github.com/fmtlib/fmt/issues/318, - https://github.com/fmtlib/fmt/issues/250, also merged - https://github.com/fmtlib/fmt/pull/385 and - https://github.com/fmtlib/fmt/pull/361). - Thanks @jcelerier and @nmoehrle. -- Fixed compilation issues under Android - (https://github.com/fmtlib/fmt/pull/327, - https://github.com/fmtlib/fmt/issues/345 and - https://github.com/fmtlib/fmt/pull/381), FreeBSD - (https://github.com/fmtlib/fmt/pull/358), Cygwin - (https://github.com/fmtlib/fmt/issues/388), MinGW - (https://github.com/fmtlib/fmt/issues/355) as well as other - issues (https://github.com/fmtlib/fmt/issues/350, - https://github.com/fmtlib/fmt/issues/355, - https://github.com/fmtlib/fmt/pull/348, - https://github.com/fmtlib/fmt/pull/402, - https://github.com/fmtlib/fmt/pull/405). - Thanks @dpantele, @hghwng, @arvedarved, @LogicalKnight and @JanHellwig. -- Fixed some documentation issues and extended specification - (https://github.com/fmtlib/fmt/issues/320, - https://github.com/fmtlib/fmt/pull/333, - https://github.com/fmtlib/fmt/issues/347, - https://github.com/fmtlib/fmt/pull/362). Thanks @smellman. - -# 3.0.0 - 2016-05-07 - -- The project has been renamed from C++ Format (cppformat) to fmt for - consistency with the used namespace and macro prefix - (https://github.com/fmtlib/fmt/issues/307). Library headers - are now located in the `fmt` directory: - - ```c++ - #include "fmt/format.h" - ``` - - Including `format.h` from the `cppformat` directory is deprecated - but works via a proxy header which will be removed in the next major - version. - - The documentation is now available at . - -- Added support for - [strftime](http://en.cppreference.com/w/cpp/chrono/c/strftime)-like - [date and time - formatting](https://fmt.dev/3.0.0/api.html#date-and-time-formatting) - (https://github.com/fmtlib/fmt/issues/283): - - ```c++ - #include "fmt/time.h" - - std::time_t t = std::time(nullptr); - // Prints "The date is 2016-04-29." (with the current date) - fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t)); - ``` - -- `std::ostream` support including formatting of user-defined types - that provide overloaded `operator<<` has been moved to - `fmt/ostream.h`: - - ```c++ - #include "fmt/ostream.h" - - class Date { - int year_, month_, day_; - public: - Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} - - friend std::ostream &operator<<(std::ostream &os, const Date &d) { - return os << d.year_ << '-' << d.month_ << '-' << d.day_; - } - }; - - std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); - // s == "The date is 2012-12-9" - ``` - -- Added support for [custom argument - formatters](https://fmt.dev/3.0.0/api.html#argument-formatters) - (https://github.com/fmtlib/fmt/issues/235). - -- Added support for locale-specific integer formatting with the `n` - specifier (https://github.com/fmtlib/fmt/issues/305): - - ```c++ - std::setlocale(LC_ALL, "en_US.utf8"); - fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567 - ``` - -- Sign is now preserved when formatting an integer with an incorrect - `printf` format specifier - (https://github.com/fmtlib/fmt/issues/265): - - ```c++ - fmt::printf("%lld", -42); // prints -42 - ``` - - Note that it would be an undefined behavior in `std::printf`. - -- Length modifiers such as `ll` are now optional in printf formatting - functions and the correct type is determined automatically - (https://github.com/fmtlib/fmt/issues/255): - - ```c++ - fmt::printf("%d", std::numeric_limits::max()); - ``` - - Note that it would be an undefined behavior in `std::printf`. - -- Added initial support for custom formatters - (https://github.com/fmtlib/fmt/issues/231). - -- Fixed detection of user-defined literal support on Intel C++ - compiler (https://github.com/fmtlib/fmt/issues/311, - https://github.com/fmtlib/fmt/pull/312). - Thanks @dean0x7d and @speth. - -- Reduced compile time - (https://github.com/fmtlib/fmt/pull/243, - https://github.com/fmtlib/fmt/pull/249, - https://github.com/fmtlib/fmt/issues/317): - - ![](https://cloud.githubusercontent.com/assets/4831417/11614060/b9e826d2-9c36-11e5-8666-d4131bf503ef.png) - - ![](https://cloud.githubusercontent.com/assets/4831417/11614080/6ac903cc-9c37-11e5-8165-26df6efae364.png) - - Thanks @dean0x7d. - -- Compile test fixes (https://github.com/fmtlib/fmt/pull/313). - Thanks @dean0x7d. - -- Documentation fixes (https://github.com/fmtlib/fmt/pull/239, - https://github.com/fmtlib/fmt/issues/248, - https://github.com/fmtlib/fmt/issues/252, - https://github.com/fmtlib/fmt/pull/258, - https://github.com/fmtlib/fmt/issues/260, - https://github.com/fmtlib/fmt/issues/301, - https://github.com/fmtlib/fmt/pull/309). - Thanks @ReadmeCritic @Gachapen and @jwilk. - -- Fixed compiler and sanitizer warnings - (https://github.com/fmtlib/fmt/issues/244, - https://github.com/fmtlib/fmt/pull/256, - https://github.com/fmtlib/fmt/pull/259, - https://github.com/fmtlib/fmt/issues/263, - https://github.com/fmtlib/fmt/issues/274, - https://github.com/fmtlib/fmt/pull/277, - https://github.com/fmtlib/fmt/pull/286, - https://github.com/fmtlib/fmt/issues/291, - https://github.com/fmtlib/fmt/issues/296, - https://github.com/fmtlib/fmt/issues/308). - Thanks @mwinterb, @pweiskircher and @Naios. - -- Improved compatibility with Windows Store apps - (https://github.com/fmtlib/fmt/issues/280, - https://github.com/fmtlib/fmt/pull/285) Thanks @mwinterb. - -- Added tests of compatibility with older C++ standards - (https://github.com/fmtlib/fmt/pull/273). Thanks @niosHD. - -- Fixed Android build - (https://github.com/fmtlib/fmt/pull/271). Thanks @newnon. - -- Changed `ArgMap` to be backed by a vector instead of a map. - (https://github.com/fmtlib/fmt/issues/261, - https://github.com/fmtlib/fmt/pull/262). Thanks @mwinterb. - -- Added `fprintf` overload that writes to a `std::ostream` - (https://github.com/fmtlib/fmt/pull/251). - Thanks @nickhutchinson. - -- Export symbols when building a Windows DLL - (https://github.com/fmtlib/fmt/pull/245). - Thanks @macdems. - -- Fixed compilation on Cygwin - (https://github.com/fmtlib/fmt/issues/304). - -- Implemented a workaround for a bug in Apple LLVM version 4.2 of - clang (https://github.com/fmtlib/fmt/issues/276). - -- Implemented a workaround for Google Test bug - https://github.com/google/googletest/issues/705 on gcc 6 - (https://github.com/fmtlib/fmt/issues/268). Thanks @octoploid. - -- Removed Biicode support because the latter has been discontinued. - -# 2.1.1 - 2016-04-11 - -- The install location for generated CMake files is now configurable - via the `FMT_CMAKE_DIR` CMake variable - (https://github.com/fmtlib/fmt/pull/299). Thanks @niosHD. -- Documentation fixes - (https://github.com/fmtlib/fmt/issues/252). - -# 2.1.0 - 2016-03-21 - -- Project layout and build system improvements - (https://github.com/fmtlib/fmt/pull/267): - - - The code have been moved to the `cppformat` directory. Including - `format.h` from the top-level directory is deprecated but works - via a proxy header which will be removed in the next major - version. - - C++ Format CMake targets now have proper interface definitions. - - Installed version of the library now supports the header-only - configuration. - - Targets `doc`, `install`, and `test` are now disabled if C++ - Format is included as a CMake subproject. They can be enabled by - setting `FMT_DOC`, `FMT_INSTALL`, and `FMT_TEST` in the parent - project. - - Thanks @niosHD. - -# 2.0.1 - 2016-03-13 - -- Improved CMake find and package support - (https://github.com/fmtlib/fmt/issues/264). Thanks @niosHD. -- Fix compile error with Android NDK and mingw32 - (https://github.com/fmtlib/fmt/issues/241). Thanks @Gachapen. -- Documentation fixes - (https://github.com/fmtlib/fmt/issues/248, - https://github.com/fmtlib/fmt/issues/260). - -# 2.0.0 - 2015-12-01 - -## General - -- \[Breaking\] Named arguments - (https://github.com/fmtlib/fmt/pull/169, - https://github.com/fmtlib/fmt/pull/173, - https://github.com/fmtlib/fmt/pull/174): - - ```c++ - fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); - ``` - - Thanks @jamboree. - -- \[Experimental\] User-defined literals for format and named - arguments (https://github.com/fmtlib/fmt/pull/204, - https://github.com/fmtlib/fmt/pull/206, - https://github.com/fmtlib/fmt/pull/207): - - ```c++ - using namespace fmt::literals; - fmt::print("The answer is {answer}.", "answer"_a=42); - ``` - - Thanks @dean0x7d. - -- \[Breaking\] Formatting of more than 16 arguments is now supported - when using variadic templates - (https://github.com/fmtlib/fmt/issues/141). Thanks @Shauren. - -- Runtime width specification - (https://github.com/fmtlib/fmt/pull/168): - - ```c++ - fmt::format("{0:{1}}", 42, 5); // gives " 42" - ``` - - Thanks @jamboree. - -- \[Breaking\] Enums are now formatted with an overloaded - `std::ostream` insertion operator (`operator<<`) if available - (https://github.com/fmtlib/fmt/issues/232). - -- \[Breaking\] Changed default `bool` format to textual, \"true\" or - \"false\" (https://github.com/fmtlib/fmt/issues/170): - - ```c++ - fmt::print("{}", true); // prints "true" - ``` - - To print `bool` as a number use numeric format specifier such as - `d`: - - ```c++ - fmt::print("{:d}", true); // prints "1" - ``` - -- `fmt::printf` and `fmt::sprintf` now support formatting of `bool` - with the `%s` specifier giving textual output, \"true\" or \"false\" - (https://github.com/fmtlib/fmt/pull/223): - - ```c++ - fmt::printf("%s", true); // prints "true" - ``` - - Thanks @LarsGullik. - -- \[Breaking\] `signed char` and `unsigned char` are now formatted as - integers by default - (https://github.com/fmtlib/fmt/pull/217). - -- \[Breaking\] Pointers to C strings can now be formatted with the `p` - specifier (https://github.com/fmtlib/fmt/pull/223): - - ```c++ - fmt::print("{:p}", "test"); // prints pointer value - ``` - - Thanks @LarsGullik. - -- \[Breaking\] `fmt::printf` and `fmt::sprintf` now print null - pointers as `(nil)` and null strings as `(null)` for consistency - with glibc (https://github.com/fmtlib/fmt/pull/226). - Thanks @LarsGullik. - -- \[Breaking\] `fmt::(s)printf` now supports formatting of objects of - user-defined types that provide an overloaded `std::ostream` - insertion operator (`operator<<`) - (https://github.com/fmtlib/fmt/issues/201): - - ```c++ - fmt::printf("The date is %s", Date(2012, 12, 9)); - ``` - -- \[Breaking\] The `Buffer` template is now part of the public API and - can be used to implement custom memory buffers - (https://github.com/fmtlib/fmt/issues/140). Thanks @polyvertex. - -- \[Breaking\] Improved compatibility between `BasicStringRef` and - [std::experimental::basic_string_view]( - http://en.cppreference.com/w/cpp/experimental/basic_string_view) - (https://github.com/fmtlib/fmt/issues/100, - https://github.com/fmtlib/fmt/issues/159, - https://github.com/fmtlib/fmt/issues/183): - - - Comparison operators now compare string content, not pointers - - `BasicStringRef::c_str` replaced by `BasicStringRef::data` - - `BasicStringRef` is no longer assumed to be null-terminated - - References to null-terminated strings are now represented by a new - class, `BasicCStringRef`. - -- Dependency on pthreads introduced by Google Test is now optional - (https://github.com/fmtlib/fmt/issues/185). - -- New CMake options `FMT_DOC`, `FMT_INSTALL` and `FMT_TEST` to control - generation of `doc`, `install` and `test` targets respectively, on - by default (https://github.com/fmtlib/fmt/issues/197, - https://github.com/fmtlib/fmt/issues/198, - https://github.com/fmtlib/fmt/issues/200). Thanks @maddinat0r. - -- `noexcept` is now used when compiling with MSVC2015 - (https://github.com/fmtlib/fmt/pull/215). Thanks @dmkrepo. - -- Added an option to disable use of `windows.h` when - `FMT_USE_WINDOWS_H` is defined as 0 before including `format.h` - (https://github.com/fmtlib/fmt/issues/171). Thanks @alfps. - -- \[Breaking\] `windows.h` is now included with `NOMINMAX` unless - `FMT_WIN_MINMAX` is defined. This is done to prevent breaking code - using `std::min` and `std::max` and only affects the header-only - configuration (https://github.com/fmtlib/fmt/issues/152, - https://github.com/fmtlib/fmt/pull/153, - https://github.com/fmtlib/fmt/pull/154). Thanks @DevO2012. - -- Improved support for custom character types - (https://github.com/fmtlib/fmt/issues/171). Thanks @alfps. - -- Added an option to disable use of IOStreams when `FMT_USE_IOSTREAMS` - is defined as 0 before including `format.h` - (https://github.com/fmtlib/fmt/issues/205, - https://github.com/fmtlib/fmt/pull/208). Thanks @JodiTheTigger. - -- Improved detection of `isnan`, `isinf` and `signbit`. - -## Optimization - -- Made formatting of user-defined types more efficient with a custom - stream buffer (https://github.com/fmtlib/fmt/issues/92, - https://github.com/fmtlib/fmt/pull/230). Thanks @NotImplemented. -- Further improved performance of `fmt::Writer` on integer formatting - and fixed a minor regression. Now it is \~7% faster than - `karma::generate` on Karma\'s benchmark - (https://github.com/fmtlib/fmt/issues/186). -- \[Breaking\] Reduced [compiled code - size](https://github.com/fmtlib/fmt#compile-time-and-code-bloat) - (https://github.com/fmtlib/fmt/issues/143, - https://github.com/fmtlib/fmt/pull/149). - -## Distribution - -- \[Breaking\] Headers are now installed in - `${CMAKE_INSTALL_PREFIX}/include/cppformat` - (https://github.com/fmtlib/fmt/issues/178). Thanks @jackyf. - -- \[Breaking\] Changed the library name from `format` to `cppformat` - for consistency with the project name and to avoid potential - conflicts (https://github.com/fmtlib/fmt/issues/178). - Thanks @jackyf. - -- C++ Format is now available in [Debian](https://www.debian.org/) - GNU/Linux - ([stretch](https://packages.debian.org/source/stretch/cppformat), - [sid](https://packages.debian.org/source/sid/cppformat)) and derived - distributions such as - [Ubuntu](https://launchpad.net/ubuntu/+source/cppformat) 15.10 and - later (https://github.com/fmtlib/fmt/issues/155): - - $ sudo apt-get install libcppformat1-dev - - Thanks @jackyf. - -- [Packages for Fedora and - RHEL](https://admin.fedoraproject.org/pkgdb/package/cppformat/) are - now available. Thanks Dave Johansen. - -- C++ Format can now be installed via [Homebrew](http://brew.sh/) on - OS X (https://github.com/fmtlib/fmt/issues/157): - - $ brew install cppformat - - Thanks @ortho and Anatoliy Bulukin. - -## Documentation - -- Migrated from ReadTheDocs to GitHub Pages for better responsiveness - and reliability (https://github.com/fmtlib/fmt/issues/128). - New documentation address is . -- Added [Building thedocumentation]( - 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. (https://github.com/fmtlib/fmt/pull/189, - https://github.com/fmtlib/fmt/issues/209). - Thanks @JodiTheTigger and @xentec. -- Documentation fixes and improvements - (https://github.com/fmtlib/fmt/issues/36, - https://github.com/fmtlib/fmt/issues/75, - https://github.com/fmtlib/fmt/issues/125, - https://github.com/fmtlib/fmt/pull/160, - https://github.com/fmtlib/fmt/pull/161, - https://github.com/fmtlib/fmt/issues/162, - https://github.com/fmtlib/fmt/issues/165, - https://github.com/fmtlib/fmt/issues/210). - Thanks @syohex. -- Fixed out-of-tree documentation build - (https://github.com/fmtlib/fmt/issues/177). Thanks @jackyf. - -## Fixes - -- Fixed `initializer_list` detection - (https://github.com/fmtlib/fmt/issues/136). Thanks @Gachapen. - -- \[Breaking\] Fixed formatting of enums with numeric format - specifiers in `fmt::(s)printf` - (https://github.com/fmtlib/fmt/issues/131, - https://github.com/fmtlib/fmt/issues/139): - - ```c++ - enum { ANSWER = 42 }; - fmt::printf("%d", ANSWER); - ``` - - Thanks @Naios. - -- Improved compatibility with old versions of MinGW - (https://github.com/fmtlib/fmt/issues/129, - https://github.com/fmtlib/fmt/pull/130, - https://github.com/fmtlib/fmt/issues/132). Thanks @cstamford. - -- Fixed a compile error on MSVC with disabled exceptions - (https://github.com/fmtlib/fmt/issues/144). - -- Added a workaround for broken implementation of variadic templates - in MSVC2012 (https://github.com/fmtlib/fmt/issues/148). - -- Placed the anonymous namespace within `fmt` namespace for the - header-only configuration (https://github.com/fmtlib/fmt/issues/171). - Thanks @alfps. - -- Fixed issues reported by Coverity Scan - (https://github.com/fmtlib/fmt/issues/187, - https://github.com/fmtlib/fmt/issues/192). - -- Implemented a workaround for a name lookup bug in MSVC2010 - (https://github.com/fmtlib/fmt/issues/188). - -- Fixed compiler warnings - (https://github.com/fmtlib/fmt/issues/95, - https://github.com/fmtlib/fmt/issues/96, - https://github.com/fmtlib/fmt/pull/114, - https://github.com/fmtlib/fmt/issues/135, - https://github.com/fmtlib/fmt/issues/142, - https://github.com/fmtlib/fmt/issues/145, - https://github.com/fmtlib/fmt/issues/146, - https://github.com/fmtlib/fmt/issues/158, - https://github.com/fmtlib/fmt/issues/163, - https://github.com/fmtlib/fmt/issues/175, - https://github.com/fmtlib/fmt/issues/190, - https://github.com/fmtlib/fmt/pull/191, - https://github.com/fmtlib/fmt/issues/194, - https://github.com/fmtlib/fmt/pull/196, - https://github.com/fmtlib/fmt/issues/216, - https://github.com/fmtlib/fmt/pull/218, - https://github.com/fmtlib/fmt/pull/220, - https://github.com/fmtlib/fmt/pull/229, - https://github.com/fmtlib/fmt/issues/233, - https://github.com/fmtlib/fmt/issues/234, - https://github.com/fmtlib/fmt/pull/236, - https://github.com/fmtlib/fmt/issues/281, - https://github.com/fmtlib/fmt/issues/289). - Thanks @seanmiddleditch, @dixlorenz, @CarterLi, @Naios, @fmatthew5876, - @LevskiWeng, @rpopescu, @gabime, @cubicool, @jkflying, @LogicalKnight, - @inguin and @Jopie64. - -- Fixed portability issues (mostly causing test failures) on ARM, - ppc64, ppc64le, s390x and SunOS 5.11 i386 - (https://github.com/fmtlib/fmt/issues/138, - https://github.com/fmtlib/fmt/issues/179, - https://github.com/fmtlib/fmt/issues/180, - https://github.com/fmtlib/fmt/issues/202, - https://github.com/fmtlib/fmt/issues/225, [Red Hat Bugzilla - Bug 1260297](https://bugzilla.redhat.com/show_bug.cgi?id=1260297)). - Thanks @Naios, @jackyf and Dave Johansen. - -- Fixed a name conflict with macro `free` defined in `crtdbg.h` when - `_CRTDBG_MAP_ALLOC` is set (https://github.com/fmtlib/fmt/issues/211). - -- Fixed shared library build on OS X - (https://github.com/fmtlib/fmt/pull/212). Thanks @dean0x7d. - -- Fixed an overload conflict on MSVC when `/Zc:wchar_t-` option is - specified (https://github.com/fmtlib/fmt/pull/214). - Thanks @slavanap. - -- Improved compatibility with MSVC 2008 - (https://github.com/fmtlib/fmt/pull/236). Thanks @Jopie64. - -- Improved compatibility with bcc32 - (https://github.com/fmtlib/fmt/issues/227). - -- Fixed `static_assert` detection on Clang - (https://github.com/fmtlib/fmt/pull/228). Thanks @dean0x7d. - -# 1.1.0 - 2015-03-06 - -- Added `BasicArrayWriter`, a class template that provides operations - for formatting and writing data into a fixed-size array - (https://github.com/fmtlib/fmt/issues/105 and - https://github.com/fmtlib/fmt/issues/122): - - ```c++ - char buffer[100]; - fmt::ArrayWriter w(buffer); - w.write("The answer is {}", 42); - ``` - -- Added [0 A.D.](http://play0ad.com/) and [PenUltima Online - (POL)](http://www.polserver.com/) to the list of notable projects - using C++ Format. - -- C++ Format now uses MSVC intrinsics for better formatting performance - (https://github.com/fmtlib/fmt/pull/115, - https://github.com/fmtlib/fmt/pull/116, - https://github.com/fmtlib/fmt/pull/118 and - https://github.com/fmtlib/fmt/pull/121). Previously these - optimizations where only used on GCC and Clang. - Thanks @CarterLi and @objectx. - -- CMake install target - (https://github.com/fmtlib/fmt/pull/119). Thanks @TrentHouliston. - - You can now install C++ Format with `make install` command. - -- Improved [Biicode](http://www.biicode.com/) support - (https://github.com/fmtlib/fmt/pull/98 and - https://github.com/fmtlib/fmt/pull/104). - Thanks @MariadeAnton and @franramirez688. - -- Improved support for building with [Android NDK]( - https://developer.android.com/tools/sdk/ndk/index.html) - (https://github.com/fmtlib/fmt/pull/107). Thanks @newnon. - - The [android-ndk-example](https://github.com/fmtlib/android-ndk-example) - repository provides and example of using C++ Format with Android NDK: - - ![](https://raw.githubusercontent.com/fmtlib/android-ndk-example/master/screenshot.png) - -- Improved documentation of `SystemError` and `WindowsError` - (https://github.com/fmtlib/fmt/issues/54). - -- Various code improvements - (https://github.com/fmtlib/fmt/pull/110, - https://github.com/fmtlib/fmt/pull/111 - https://github.com/fmtlib/fmt/pull/112). Thanks @CarterLi. - -- Improved compile-time errors when formatting wide into narrow - strings (https://github.com/fmtlib/fmt/issues/117). - -- Fixed `BasicWriter::write` without formatting arguments when C++11 - support is disabled - (https://github.com/fmtlib/fmt/issues/109). - -- Fixed header-only build on OS X with GCC 4.9 - (https://github.com/fmtlib/fmt/issues/124). - -- Fixed packaging issues (https://github.com/fmtlib/fmt/issues/94). - -- Added [changelog](https://github.com/fmtlib/fmt/blob/master/ChangeLog.md) - (https://github.com/fmtlib/fmt/issues/103). - -# 1.0.0 - 2015-02-05 - -- Add support for a header-only configuration when `FMT_HEADER_ONLY` - is defined before including `format.h`: - - ```c++ - #define FMT_HEADER_ONLY - #include "format.h" - ``` - -- Compute string length in the constructor of `BasicStringRef` instead - of the `size` method - (https://github.com/fmtlib/fmt/issues/79). This eliminates - size computation for string literals on reasonable optimizing - compilers. - -- Fix formatting of types with overloaded `operator <<` for - `std::wostream` (https://github.com/fmtlib/fmt/issues/86): - - ```c++ - fmt::format(L"The date is {0}", Date(2012, 12, 9)); - ``` - -- Fix linkage of tests on Arch Linux - (https://github.com/fmtlib/fmt/issues/89). - -- Allow precision specifier for non-float arguments - (https://github.com/fmtlib/fmt/issues/90): - - ```c++ - fmt::print("{:.3}\n", "Carpet"); // prints "Car" - ``` - -- Fix build on Android NDK (https://github.com/fmtlib/fmt/issues/93). - -- Improvements to documentation build procedure. - -- Remove `FMT_SHARED` CMake variable in favor of standard [BUILD_SHARED_LIBS]( - http://www.cmake.org/cmake/help/v3.0/variable/BUILD_SHARED_LIBS.html). - -- Fix error handling in `fmt::fprintf`. - -- Fix a number of warnings. - -# 0.12.0 - 2014-10-25 - -- \[Breaking\] Improved separation between formatting and buffer - management. `Writer` is now a base class that cannot be instantiated - directly. The new `MemoryWriter` class implements the default buffer - management with small allocations done on stack. So `fmt::Writer` - should be replaced with `fmt::MemoryWriter` in variable - declarations. - - Old code: - - ```c++ - fmt::Writer w; - ``` - - New code: - - ```c++ - fmt::MemoryWriter w; - ``` - - If you pass `fmt::Writer` by reference, you can continue to do so: - - ```c++ - void f(fmt::Writer &w); - ``` - - This doesn\'t affect the formatting API. - -- Support for custom memory allocators - (https://github.com/fmtlib/fmt/issues/69) - -- Formatting functions now accept [signed char]{.title-ref} and - [unsigned char]{.title-ref} strings as arguments - (https://github.com/fmtlib/fmt/issues/73): - - ```c++ - auto s = format("GLSL version: {}", glGetString(GL_VERSION)); - ``` - -- Reduced code bloat. According to the new [benchmark - results](https://github.com/fmtlib/fmt#compile-time-and-code-bloat), - cppformat is close to `printf` and by the order of magnitude better - than Boost Format in terms of compiled code size. - -- Improved appearance of the documentation on mobile by using the - [Sphinx Bootstrap - theme](http://ryan-roemer.github.io/sphinx-bootstrap-theme/): - - | Old | New | - | --- | --- | - | ![](https://cloud.githubusercontent.com/assets/576385/4792130/cd256436-5de3-11e4-9a62-c077d0c2b003.png) | ![](https://cloud.githubusercontent.com/assets/576385/4792131/cd29896c-5de3-11e4-8f59-cac952942bf0.png) | - -# 0.11.0 - 2014-08-21 - -- Safe printf implementation with a POSIX extension for positional - arguments: - - ```c++ - fmt::printf("Elapsed time: %.2f seconds", 1.23); - fmt::printf("%1$s, %3$d %2$s", weekday, month, day); - ``` - -- Arguments of `char` type can now be formatted as integers (Issue - https://github.com/fmtlib/fmt/issues/55): - - ```c++ - fmt::format("0x{0:02X}", 'a'); - ``` - -- Deprecated parts of the API removed. - -- The library is now built and tested on MinGW with Appveyor in - addition to existing test platforms Linux/GCC, OS X/Clang, - Windows/MSVC. - -# 0.10.0 - 2014-07-01 - -**Improved API** - -- All formatting methods are now implemented as variadic functions - instead of using `operator<<` for feeding arbitrary arguments into a - temporary formatter object. This works both with C++11 where - variadic templates are used and with older standards where variadic - functions are emulated by providing lightweight wrapper functions - defined with the `FMT_VARIADIC` macro. You can use this macro for - defining your own portable variadic functions: - - ```c++ - void report_error(const char *format, const fmt::ArgList &args) { - fmt::print("Error: {}"); - fmt::print(format, args); - } - FMT_VARIADIC(void, report_error, const char *) - - report_error("file not found: {}", path); - ``` - - Apart from a more natural syntax, this also improves performance as - there is no need to construct temporary formatter objects and - control arguments\' lifetimes. Because the wrapper functions are - very lightweight, this doesn\'t cause code bloat even in pre-C++11 - mode. - -- Simplified common case of formatting an `std::string`. Now it - requires a single function call: - - ```c++ - std::string s = format("The answer is {}.", 42); - ``` - - Previously it required 2 function calls: - - ```c++ - std::string s = str(Format("The answer is {}.") << 42); - ``` - - Instead of unsafe `c_str` function, `fmt::Writer` should be used - directly to bypass creation of `std::string`: - - ```c++ - fmt::Writer w; - w.write("The answer is {}.", 42); - w.c_str(); // returns a C string - ``` - - This doesn\'t do dynamic memory allocation for small strings and is - less error prone as the lifetime of the string is the same as for - `std::string::c_str` which is well understood (hopefully). - -- Improved consistency in naming functions that are a part of the - public API. Now all public functions are lowercase following the - standard library conventions. Previously it was a combination of - lowercase and CapitalizedWords. Issue - https://github.com/fmtlib/fmt/issues/50. - -- Old functions are marked as deprecated and will be removed in the - next release. - -**Other Changes** - -- Experimental support for printf format specifications (work in - progress): - - ```c++ - fmt::printf("The answer is %d.", 42); - std::string s = fmt::sprintf("Look, a %s!", "string"); - ``` - -- Support for hexadecimal floating point format specifiers `a` and - `A`: - - ```c++ - print("{:a}", -42.0); // Prints -0x1.5p+5 - print("{:A}", -42.0); // Prints -0X1.5P+5 - ``` - -- CMake option `FMT_SHARED` that specifies whether to build format as - a shared library (off by default). - -# 0.9.0 - 2014-05-13 - -- More efficient implementation of variadic formatting functions. - -- `Writer::Format` now has a variadic overload: - - ```c++ - Writer out; - out.Format("Look, I'm {}!", "variadic"); - ``` - -- For efficiency and consistency with other overloads, variadic - overload of the `Format` function now returns `Writer` instead of - `std::string`. Use the `str` function to convert it to - `std::string`: - - ```c++ - std::string s = str(Format("Look, I'm {}!", "variadic")); - ``` - -- Replaced formatter actions with output sinks: `NoAction` -\> - `NullSink`, `Write` -\> `FileSink`, `ColorWriter` -\> - `ANSITerminalSink`. This improves naming consistency and shouldn\'t - affect client code unless these classes are used directly which - should be rarely needed. - -- Added `ThrowSystemError` function that formats a message and throws - `SystemError` containing the formatted message and system-specific - error description. For example, the following code - - ```c++ - FILE *f = fopen(filename, "r"); - if (!f) - ThrowSystemError(errno, "Failed to open file '{}'") << filename; - ``` - - will throw `SystemError` exception with description \"Failed to open - file \'\\': No such file or directory\" if file doesn\'t - exist. - -- Support for AppVeyor continuous integration platform. - -- `Format` now throws `SystemError` in case of I/O errors. - -- Improve test infrastructure. Print functions are now tested by - redirecting the output to a pipe. - -# 0.8.0 - 2014-04-14 - -- Initial release + int main() { + fmt::ostream out1 = fmt::output_file("guide"); + out1.print("Zaphod"); + out1.close(); + fmt::ostream out2 = fmt::output_file("guide"); + out2.print("Ford"); + } + ``` + + writes \"Ford\" to the file \"guide\". To preserve the old file + content if any pass `fmt::file::WRONLY | fmt::file::CREATE` flags to + `fmt::output_file`. + +- Fixed moving of `fmt::ostream` that holds buffered data + (https://github.com/fmtlib/fmt/issues/2197, + https://github.com/fmtlib/fmt/pull/2198). Thanks @vtta. + +- Replaced the `fmt::system_error` exception with a function of the + same name that constructs `std::system_error` + (https://github.com/fmtlib/fmt/issues/2266). + +- Replaced the `fmt::windows_error` exception with a function of the + same name that constructs `std::system_error` with the category + returned by `fmt::system_category()` + (https://github.com/fmtlib/fmt/issues/2274, + https://github.com/fmtlib/fmt/pull/2275). The latter is + similar to `std::system_category` but correctly handles UTF-8. + Thanks @phprus. + +- Replaced `fmt::error_code` with `std::error_code` and made it + formattable (https://github.com/fmtlib/fmt/issues/2269, + https://github.com/fmtlib/fmt/pull/2270, + https://github.com/fmtlib/fmt/pull/2273). Thanks @phprus. + +- Added speech synthesis support + (https://github.com/fmtlib/fmt/pull/2206). + +- Made `format_to` work with a memory buffer that has a custom + allocator (https://github.com/fmtlib/fmt/pull/2300). + Thanks @voxmea. + +- Added `Allocator::max_size` support to `basic_memory_buffer`. + (https://github.com/fmtlib/fmt/pull/1960). Thanks @phprus. + +- Added wide string support to `fmt::join` + (https://github.com/fmtlib/fmt/pull/2236). Thanks @crbrz. + +- Made iterators passed to `formatter` specializations via a format + context satisfy C++20 `std::output_iterator` requirements + (https://github.com/fmtlib/fmt/issues/2156, + https://github.com/fmtlib/fmt/pull/2158, + https://github.com/fmtlib/fmt/issues/2195, + https://github.com/fmtlib/fmt/pull/2204). Thanks @randomnetcat. + +- Optimized the `printf` implementation + (https://github.com/fmtlib/fmt/pull/1982, + https://github.com/fmtlib/fmt/pull/1984, + https://github.com/fmtlib/fmt/pull/2016, + https://github.com/fmtlib/fmt/pull/2164). + Thanks @rimathia and @moiwi. + +- Improved detection of `constexpr` `char_traits` + (https://github.com/fmtlib/fmt/pull/2246, + https://github.com/fmtlib/fmt/pull/2257). Thanks @phprus. + +- Fixed writing to `stdout` when it is redirected to `NUL` on Windows + (https://github.com/fmtlib/fmt/issues/2080). + +- Fixed exception propagation from iterators + (https://github.com/fmtlib/fmt/issues/2097). + +- Improved `strftime` error handling + (https://github.com/fmtlib/fmt/issues/2238, + https://github.com/fmtlib/fmt/pull/2244). Thanks @yumeyao. + +- Stopped using deprecated GCC UDL template extension. + +- Added `fmt/args.h` to the install target + (https://github.com/fmtlib/fmt/issues/2096). + +- Error messages are now passed to assert when exceptions are disabled + (https://github.com/fmtlib/fmt/pull/2145). Thanks @NobodyXu. + +- Added the `FMT_MASTER_PROJECT` CMake option to control build and + install targets when {fmt} is included via `add_subdirectory` + (https://github.com/fmtlib/fmt/issues/2098, + https://github.com/fmtlib/fmt/pull/2100). + Thanks @randomizedthinking. + +- Improved build configuration + (https://github.com/fmtlib/fmt/pull/2026, + https://github.com/fmtlib/fmt/pull/2122). + Thanks @luncliff and @ibaned. + +- Fixed various warnings and compilation issues + (https://github.com/fmtlib/fmt/issues/1947, + https://github.com/fmtlib/fmt/pull/1959, + https://github.com/fmtlib/fmt/pull/1963, + https://github.com/fmtlib/fmt/pull/1965, + https://github.com/fmtlib/fmt/issues/1966, + https://github.com/fmtlib/fmt/pull/1974, + https://github.com/fmtlib/fmt/pull/1975, + https://github.com/fmtlib/fmt/pull/1990, + https://github.com/fmtlib/fmt/issues/2000, + https://github.com/fmtlib/fmt/pull/2001, + https://github.com/fmtlib/fmt/issues/2002, + https://github.com/fmtlib/fmt/issues/2004, + https://github.com/fmtlib/fmt/pull/2006, + https://github.com/fmtlib/fmt/pull/2009, + https://github.com/fmtlib/fmt/pull/2010, + https://github.com/fmtlib/fmt/issues/2038, + https://github.com/fmtlib/fmt/issues/2039, + https://github.com/fmtlib/fmt/issues/2047, + https://github.com/fmtlib/fmt/pull/2053, + https://github.com/fmtlib/fmt/issues/2059, + https://github.com/fmtlib/fmt/pull/2065, + https://github.com/fmtlib/fmt/pull/2067, + https://github.com/fmtlib/fmt/pull/2068, + https://github.com/fmtlib/fmt/pull/2073, + https://github.com/fmtlib/fmt/issues/2103, + https://github.com/fmtlib/fmt/issues/2105, + https://github.com/fmtlib/fmt/pull/2106, + https://github.com/fmtlib/fmt/pull/2107, + https://github.com/fmtlib/fmt/issues/2116, + https://github.com/fmtlib/fmt/pull/2117, + https://github.com/fmtlib/fmt/issues/2118, + https://github.com/fmtlib/fmt/pull/2119, + https://github.com/fmtlib/fmt/issues/2127, + https://github.com/fmtlib/fmt/pull/2128, + https://github.com/fmtlib/fmt/issues/2140, + https://github.com/fmtlib/fmt/issues/2142, + https://github.com/fmtlib/fmt/pull/2143, + https://github.com/fmtlib/fmt/pull/2144, + https://github.com/fmtlib/fmt/issues/2147, + https://github.com/fmtlib/fmt/issues/2148, + https://github.com/fmtlib/fmt/issues/2149, + https://github.com/fmtlib/fmt/pull/2152, + https://github.com/fmtlib/fmt/pull/2160, + https://github.com/fmtlib/fmt/issues/2170, + https://github.com/fmtlib/fmt/issues/2175, + https://github.com/fmtlib/fmt/issues/2176, + https://github.com/fmtlib/fmt/pull/2177, + https://github.com/fmtlib/fmt/issues/2178, + https://github.com/fmtlib/fmt/pull/2179, + https://github.com/fmtlib/fmt/issues/2180, + https://github.com/fmtlib/fmt/issues/2181, + https://github.com/fmtlib/fmt/pull/2183, + https://github.com/fmtlib/fmt/issues/2184, + https://github.com/fmtlib/fmt/issues/2185, + https://github.com/fmtlib/fmt/pull/2186, + https://github.com/fmtlib/fmt/pull/2187, + https://github.com/fmtlib/fmt/pull/2190, + https://github.com/fmtlib/fmt/pull/2192, + https://github.com/fmtlib/fmt/pull/2194, + https://github.com/fmtlib/fmt/pull/2205, + https://github.com/fmtlib/fmt/issues/2210, + https://github.com/fmtlib/fmt/pull/2211, + https://github.com/fmtlib/fmt/pull/2215, + https://github.com/fmtlib/fmt/pull/2216, + https://github.com/fmtlib/fmt/pull/2218, + https://github.com/fmtlib/fmt/pull/2220, + https://github.com/fmtlib/fmt/issues/2228, + https://github.com/fmtlib/fmt/pull/2229, + https://github.com/fmtlib/fmt/pull/2230, + https://github.com/fmtlib/fmt/issues/2233, + https://github.com/fmtlib/fmt/pull/2239, + https://github.com/fmtlib/fmt/issues/2248, + https://github.com/fmtlib/fmt/issues/2252, + https://github.com/fmtlib/fmt/pull/2253, + https://github.com/fmtlib/fmt/pull/2255, + https://github.com/fmtlib/fmt/issues/2261, + https://github.com/fmtlib/fmt/issues/2278, + https://github.com/fmtlib/fmt/issues/2284, + https://github.com/fmtlib/fmt/pull/2287, + https://github.com/fmtlib/fmt/pull/2289, + https://github.com/fmtlib/fmt/pull/2290, + https://github.com/fmtlib/fmt/pull/2293, + https://github.com/fmtlib/fmt/issues/2295, + https://github.com/fmtlib/fmt/pull/2296, + https://github.com/fmtlib/fmt/pull/2297, + https://github.com/fmtlib/fmt/issues/2311, + https://github.com/fmtlib/fmt/pull/2313, + https://github.com/fmtlib/fmt/pull/2315, + https://github.com/fmtlib/fmt/issues/2320, + https://github.com/fmtlib/fmt/pull/2321, + https://github.com/fmtlib/fmt/pull/2323, + https://github.com/fmtlib/fmt/issues/2328, + https://github.com/fmtlib/fmt/pull/2329, + https://github.com/fmtlib/fmt/pull/2333, + https://github.com/fmtlib/fmt/pull/2338, + https://github.com/fmtlib/fmt/pull/2341). + Thanks @darklukee, @fagg, @killerbot242, @jgopel, @yeswalrus, @Finkman, + @HazardyKnusperkeks, @dkavolis, @concatime, @chronoxor, @summivox, @yNeo, + @Apache-HB, @alexezeder, @toojays, @Brainy0207, @vadz, @imsherlock, @phprus, + @white238, @yafshar, @BillyDonahue, @jstaahl, @denchat, @DanielaE, + @ilyakurdyukov, @ilmai, @JessyDL, @sergiud, @mwinterb, @sven-herrmann, + @jmelas, @twoixter, @crbrz and @upsj. + +- Improved documentation + (https://github.com/fmtlib/fmt/issues/1986, + https://github.com/fmtlib/fmt/pull/2051, + https://github.com/fmtlib/fmt/issues/2057, + https://github.com/fmtlib/fmt/pull/2081, + https://github.com/fmtlib/fmt/issues/2084, + https://github.com/fmtlib/fmt/pull/2312). + Thanks @imba-tjd, @0x416c69 and @mordante. + +- Continuous integration and test improvements + (https://github.com/fmtlib/fmt/issues/1969, + https://github.com/fmtlib/fmt/pull/1991, + https://github.com/fmtlib/fmt/pull/2020, + https://github.com/fmtlib/fmt/pull/2110, + https://github.com/fmtlib/fmt/pull/2114, + https://github.com/fmtlib/fmt/issues/2196, + https://github.com/fmtlib/fmt/pull/2217, + https://github.com/fmtlib/fmt/pull/2247, + https://github.com/fmtlib/fmt/pull/2256, + https://github.com/fmtlib/fmt/pull/2336, + https://github.com/fmtlib/fmt/pull/2346). + Thanks @jgopel, @alexezeder and @DanielaE. + +The change log for versions 0.8.0 - 7.1.3 is available [here]( +doc/ChangeLog-old.md). diff --git a/third-party/fmt/README.md b/third-party/fmt/README.md index dcfb16ec22..fd845db20c 100644 --- a/third-party/fmt/README.md +++ b/third-party/fmt/README.md @@ -20,16 +20,16 @@ that help victims of the war in Ukraine: . Q&A: ask questions on [StackOverflow with the tag fmt](https://stackoverflow.com/questions/tagged/fmt). -Try {fmt} in [Compiler Explorer](https://godbolt.org/z/Eq5763). +Try {fmt} in [Compiler Explorer](https://godbolt.org/z/8Mx1EW73v). # Features -- Simple [format API](https://fmt.dev/latest/api.html) with positional +- Simple [format API](https://fmt.dev/latest/api/) with positional arguments for localization - Implementation of [C++20 std::format](https://en.cppreference.com/w/cpp/utility/format) and [C++23 std::print](https://en.cppreference.com/w/cpp/io/print) -- [Format string syntax](https://fmt.dev/latest/syntax.html) similar +- [Format string syntax](https://fmt.dev/latest/syntax/) similar to Python\'s [format](https://docs.python.org/3/library/stdtypes.html#str.format) - Fast IEEE 754 floating-point formatter with correct rounding, @@ -37,10 +37,10 @@ Try {fmt} in [Compiler Explorer](https://godbolt.org/z/Eq5763). [Dragonbox](https://github.com/jk-jeon/dragonbox) algorithm - Portable Unicode support - Safe [printf - implementation](https://fmt.dev/latest/api.html#printf-formatting) + implementation](https://fmt.dev/latest/api/#printf-formatting) including the POSIX extension for positional arguments - Extensibility: [support for user-defined - types](https://fmt.dev/latest/api.html#formatting-user-defined-types) + types](https://fmt.dev/latest/api/#formatting-user-defined-types) - High performance: faster than common standard library implementations of `(s)printf`, iostreams, `to_string` and `to_chars`, see [Speed tests](#speed-tests) and [Converting a @@ -58,8 +58,8 @@ Try {fmt} in [Compiler Explorer](https://godbolt.org/z/Eq5763). buffer overflow errors - Ease of use: small self-contained code base, no external dependencies, permissive MIT - [license](https://github.com/fmtlib/fmt/blob/master/LICENSE.rst) -- [Portability](https://fmt.dev/latest/index.html#portability) with + [license](https://github.com/fmtlib/fmt/blob/master/LICENSE) +- [Portability](https://fmt.dev/latest/#portability) with consistent output across platforms and support for older compilers - Clean warning-free codebase even on high warning levels such as `-Wall -Wextra -pedantic` @@ -203,43 +203,38 @@ and [ryu](https://github.com/ulfjack/ryu): ## 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. +The script [bloat-test.py][test] from [format-benchmark][bench] 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 +clang version 15.0.0 (clang-1500.1.0.2.5), macOS Sonoma, best of three) is shown +in the following tables. + +[test]: https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py +[bench]: https://github.com/fmtlib/format-benchmark **Optimized build (-O3)** | Method | Compile Time, s | Executable size, KiB | Stripped size, KiB | |---------------|-----------------|----------------------|--------------------| -| printf | 2.6 | 29 | 26 | -| printf+string | 16.4 | 29 | 26 | -| iostreams | 31.1 | 59 | 55 | -| {fmt} | 19.0 | 37 | 34 | -| Boost Format | 91.9 | 226 | 203 | -| Folly Format | 115.7 | 101 | 88 | +| printf | 1.6 | 54 | 50 | +| IOStreams | 25.9 | 98 | 84 | +| fmt 83652df | 4.8 | 54 | 50 | +| tinyformat | 29.1 | 161 | 136 | +| Boost Format | 55.0 | 530 | 317 | -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 an extra `` -include to measure the overhead of the latter. +{fmt} is fast to compile and is comparable to `printf` in terms of per-call +binary size (within a rounding error on this system). **Non-optimized build** | Method | Compile Time, s | Executable size, KiB | Stripped size, KiB | |---------------|-----------------|----------------------|--------------------| -| printf | 2.2 | 33 | 30 | -| printf+string | 16.0 | 33 | 30 | -| iostreams | 28.3 | 56 | 52 | -| {fmt} | 18.2 | 59 | 50 | -| Boost Format | 54.1 | 365 | 303 | -| Folly Format | 79.9 | 445 | 430 | +| printf | 1.4 | 54 | 50 | +| IOStreams | 23.4 | 92 | 68 | +| {fmt} 83652df | 4.4 | 89 | 85 | +| tinyformat | 24.5 | 204 | 161 | +| Boost Format | 36.4 | 831 | 462 | `libc`, `lib(std)c++`, and `libfmt` are all linked as shared libraries to compare formatting function overhead only. Boost Format is a @@ -248,7 +243,7 @@ header-only library so it doesn\'t provide any linkage options. ## Running the tests Please refer to [Building the -library](https://fmt.dev/latest/usage.html#building-the-library) for +library](https://fmt.dev/latest/get-started/#building-from-source) for instructions on how to build the library and run the unit tests. Benchmarks reside in a separate repository, @@ -270,8 +265,7 @@ or the bloat test: # Migrating code -[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) v17 (not yet -released) provides the +[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) v18 provides the [modernize-use-std-print](https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-std-print.html) check that is capable of converting occurrences of `printf` and `fprintf` to `fmt::print` if configured to do so. (By default it @@ -297,13 +291,14 @@ converts to `std::print`.) - [ccache](https://ccache.dev/): a compiler cache - [ClickHouse](https://github.com/ClickHouse/ClickHouse): an analytical database management system +- [ContextVision](https://www.contextvision.com/): medical imaging software - [Contour](https://github.com/contour-terminal/contour/): a modern terminal emulator - [CUAUV](https://cuauv.org/): Cornell University\'s autonomous underwater vehicle - [Drake](https://drake.mit.edu/): a planning, control, and analysis toolbox for nonlinear dynamical systems (MIT) -- [Envoy](https://lyft.github.io/envoy/): C++ L7 proxy and +- [Envoy](https://github.com/envoyproxy/envoy): C++ L7 proxy and communication bus (Lyft) - [FiveM](https://fivem.net/): a modification framework for GTA V - [fmtlog](https://github.com/MengRao/fmtlog): a performant @@ -343,7 +338,7 @@ converts to `std::print`.) - [Quill](https://github.com/odygrd/quill): asynchronous low-latency logging library - [QKW](https://github.com/ravijanjam/qkw): generalizing aliasing to - simplify navigation, and executing complex multi-line terminal + simplify navigation, and execute complex multi-line terminal command sequences - [redis-cerberus](https://github.com/HunanTV/redis-cerberus): a Redis cluster proxy @@ -432,7 +427,7 @@ code bloat issues (see [Benchmarks](#benchmarks)). ## FastFormat -This is an interesting library that is fast, safe, and has positional +This is an interesting library that is fast, safe and has positional arguments. However, it has significant limitations, citing its author: > Three features that have no hope of being accommodated within the @@ -442,8 +437,8 @@ arguments. However, it has significant limitations, citing its author: > - Octal/hexadecimal encoding > - Runtime width/alignment specification -It is also quite big and has a heavy dependency, STLSoft, which might be -too restrictive for using it in some projects. +It is also quite big and has a heavy dependency, on STLSoft, which might be +too restrictive for use in some projects. ## Boost Spirit.Karma @@ -462,7 +457,7 @@ second](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html). # Documentation License -The [Format String Syntax](https://fmt.dev/latest/syntax.html) section +The [Format String Syntax](https://fmt.dev/latest/syntax/) section in the documentation is based on the one from Python [string module documentation](https://docs.python.org/3/library/string.html#module-string). For this reason, the documentation is distributed under the Python @@ -486,5 +481,5 @@ To report a security issue, please disclose it at [security advisory](https://github.com/fmtlib/fmt/security/advisories/new). This project is maintained by a team of volunteers on a -reasonable-effort basis. As such, please give us at least 90 days to +reasonable-effort basis. As such, please give us at least *90* days to work on a fix before public exposure. diff --git a/third-party/fmt/doc-html/404.html b/third-party/fmt/doc-html/404.html new file mode 100644 index 0000000000..994f85e51b --- /dev/null +++ b/third-party/fmt/doc-html/404.html @@ -0,0 +1,430 @@ + + + + + + + + + + + + + + + + + + + {fmt} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ + + + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + + + + +
+
+
+ + + + +
+
+ +

404 - Not found

+ +
+
+ + + +
+ + + +
+ +
+ + +
+ +
+
+
+
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/fmt/doc-html/api.html b/third-party/fmt/doc-html/api.html new file mode 100644 index 0000000000..b403d09d21 --- /dev/null +++ b/third-party/fmt/doc-html/api.html @@ -0,0 +1,1974 @@ + + + + + + + + + + + + + + + + + + + + + + + API - {fmt} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + + + + + + +
+
+ + + + + + + +

API Reference

+

The {fmt} library API consists of the following components:

+ +

All functions and types provided by the library reside in namespace fmt +and macros have prefix FMT_.

+

Base API

+

fmt/base.h defines the base API which provides main formatting functions +for char/UTF-8 with C++20 compile-time checks. It has minimal include +dependencies for better compile times. This header is only beneficial when +using {fmt} as a library (the default) and not in the header-only mode. +It also provides formatter specializations for the following types:

+
    +
  • int, long long,
  • +
  • unsigned, unsigned long long
  • +
  • float, double, long double
  • +
  • bool
  • +
  • char
  • +
  • const char*, fmt::string_view
  • +
  • const void*
  • +
+

The following functions use format string syntax similar to that +of str.format +in Python. They take fmt and args as arguments.

+

fmt is a format string that contains literal text and replacement fields +surrounded by braces {}. The fields are replaced with formatted arguments +in the resulting string. fmt::format_string is a format +string which can be implicitly constructed from a string literal or a +constexpr string and is checked at compile time in C++20. To pass a runtime +format string wrap it in fmt::runtime.

+

args is an argument list representing objects to be formatted.

+

I/O errors are reported as std::system_error exceptions unless +specified otherwise.

+
+ +
template <typename... T> +
void print(format_string<T...> fmt, T&&... args);
+
+
+

Formats args according to specifications in fmt and writes the output to stdout.

+

Example:

fmt::print("The answer is {}.", 42);
+

+
+
+
+ +
template <typename... T> +
void print(FILE* f, format_string<T...> fmt, T&&... args);
+
+
+

Formats args according to specifications in fmt and writes the output to the file f.

+

Example:

fmt::print(stderr, "Don't {}!", "panic");
+

+
+
+
+ +
template <typename... T> +
void println(format_string<T...> fmt, T&&... args);
+
+
+

Formats args according to specifications in fmt and writes the output to stdout followed by a newline.

+
+
+
+ +
template <typename... T> +
void println(FILE* f, format_string<T...> fmt, T&&... args);
+
+
+

Formats args according to specifications in fmt and writes the output to the file f followed by a newline.

+
+
+
+ +
template <typename OutputIt, typename... T> +
auto format_to(OutputIt&& out, format_string<T...> fmt, T&&... args) -⁠> remove_cvref_t<OutputIt>;
+
+
+

Formats args according to specifications in fmt, writes the result to the output iterator out and returns the iterator past the end of the output range. format_to does not append a terminating null character.

+

Example:

auto out = std::vector<char>();
+fmt::format_to(std::back_inserter(out), "{}", 42);
+

+
+
+
+ +
template <typename OutputIt, typename... T> +
auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt, T&&... args) -⁠> format_to_n_result<OutputIt>;
+
+
+

Formats args according to specifications in fmt, writes up to n characters of the result to the output iterator out and returns the total (not truncated) output size and the iterator past the end of the output range. format_to_n does not append a terminating null character.

+
+
+
+ +
template <typename OutputIt> +
struct format_to_n_result;
+
+
+
+
OutputIt out;
+
+

Iterator past the end of the output range.

+
+
+
+
size_t size;
+
+

Total (not truncated) output size.

+
+
+
+
+
+ +
template <typename... T> +
auto formatted_size(format_string<T...> fmt, T&&... args) -⁠> size_t;
+
+
+

Returns the number of chars in the output of format(fmt, args...).

+
+
+

+

Formatting User-Defined Types

+

The {fmt} library provides formatters for many standard C++ types. +See fmt/ranges.h for ranges and tuples including standard +containers such as std::vector, fmt/chrono.h for date and +time formatting and fmt/std.h for other standard library types.

+

There are two ways to make a user-defined type formattable: providing a +format_as function or specializing the formatter struct template.

+

Use format_as if you want to make your type formattable as some other +type with the same format specifiers. The format_as function should +take an object of your type and return an object of a formattable type. +It should be defined in the same namespace as your type.

+

Example (run):

+
#include <fmt/format.h>
+
+namespace kevin_namespacy {
+
+enum class film {
+  house_of_cards, american_beauty, se7en = 7
+};
+
+auto format_as(film f) { return fmt::underlying(f); }
+
+}
+
+int main() {
+  fmt::print("{}\n", kevin_namespacy::film::se7en); // Output: 7
+}
+

Using specialization is more complex but gives you full control over +parsing and formatting. To use this method specialize the formatter +struct template for your type and implement parse and format +methods.

+

The recommended way of defining a formatter is by reusing an existing +one via inheritance or composition. This way you can support standard +format specifiers without implementing them yourself. For example:

+
// color.h:
+#include <fmt/base.h>
+
+enum class color {red, green, blue};
+
+template <> struct fmt::formatter<color>: formatter<string_view> {
+  // parse is inherited from formatter<string_view>.
+
+  auto format(color c, format_context& ctx) const
+    -> format_context::iterator;
+};
+
+
// color.cc:
+#include "color.h"
+#include <fmt/format.h>
+
+auto fmt::formatter<color>::format(color c, format_context& ctx) const
+    -> format_context::iterator {
+  string_view name = "unknown";
+  switch (c) {
+  case color::red:   name = "red"; break;
+  case color::green: name = "green"; break;
+  case color::blue:  name = "blue"; break;
+  }
+  return formatter<string_view>::format(name, ctx);
+}
+
+

Note that formatter<string_view>::format is defined in fmt/format.h +so it has to be included in the source file. Since parse is inherited +from formatter<string_view> it will recognize all string format +specifications, for example

+
fmt::format("{:>10}", color::blue)
+
+

will return " blue".

+ + +

In general the formatter has the following form:

+
template <> struct fmt::formatter<T> {
+  // Parses format specifiers and stores them in the formatter.
+  //
+  // [ctx.begin(), ctx.end()) is a, possibly empty, character range that
+  // contains a part of the format string starting from the format
+  // specifications to be parsed, e.g. in
+  //
+  //   fmt::format("{:f} continued", ...);
+  //
+  // the range will contain "f} continued". The formatter should parse
+  // specifiers until '}' or the end of the range. In this example the
+  // formatter should parse the 'f' specifier and return an iterator
+  // pointing to '}'.
+  constexpr auto parse(format_parse_context& ctx)
+    -> format_parse_context::iterator;
+
+  // Formats value using the parsed format specification stored in this
+  // formatter and writes the output to ctx.out().
+  auto format(const T& value, format_context& ctx) const
+    -> format_context::iterator;
+};
+

It is recommended to at least support fill, align and width that apply +to the whole object and have the same semantics as in standard +formatters.

+

You can also write a formatter for a hierarchy of classes:

+
// demo.h:
+#include <type_traits>
+#include <fmt/core.h>
+
+struct A {
+  virtual ~A() {}
+  virtual std::string name() const { return "A"; }
+};
+
+struct B : A {
+  virtual std::string name() const { return "B"; }
+};
+
+template <typename T>
+struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<A, T>, char>> :
+    fmt::formatter<std::string> {
+  auto format(const A& a, format_context& ctx) const {
+    return formatter<std::string>::format(a.name(), ctx);
+  }
+};
+
+
// demo.cc:
+#include "demo.h"
+#include <fmt/format.h>
+
+int main() {
+  B b;
+  A& a = b;
+  fmt::print("{}", a); // Output: B
+}
+
+

Providing both a formatter specialization and a format_as overload is +disallowed.

+ +
+ +
class context;
+
+
+
+
context(iterator out, format_args args, detail::locale_ref loc);
+
+

Constructs a context object. References to the arguments are stored in the object so make sure they have appropriate lifetimes.

+
+
+
+
+ +

Compile-Time Checks

+

Compile-time format string checks are enabled by default on compilers +that support C++20 consteval. On older compilers you can use the +FMT_STRING macro defined in fmt/format.h instead.

+

Unused arguments are allowed as in Python's str.format and ordinary functions.

+

See Type Erasure for an example of how to enable compile-time +checks in your own functions with fmt::format_string while avoiding template +bloat.

+
+ +
template <typename... T> +
struct fstring;
+
+
+

A compile-time format string. Use format_string in the public API to prevent type deduction.

+
+
+ +
+ +
auto runtime(string_view s) -⁠> runtime_format_string<>;
+
+
+

Creates a runtime format string.

+

Example:

// Check format string at runtime instead of compile-time.
+fmt::print(fmt::runtime("{:d}"), "I am not a number");
+

+
+
+

Type Erasure

+

You can create your own formatting function with compile-time checks and +small binary footprint, for example (run):

+
#include <fmt/format.h>
+
+void vlog(const char* file, int line,
+          fmt::string_view fmt, fmt::format_args args) {
+  fmt::print("{}: {}: {}", file, line, fmt::vformat(fmt, args));
+}
+
+template <typename... T>
+void log(const char* file, int line,
+         fmt::format_string<T...> fmt, T&&... args) {
+  vlog(file, line, fmt, fmt::make_format_args(args...));
+}
+
+#define MY_LOG(fmt, ...) log(__FILE__, __LINE__, fmt, __VA_ARGS__)
+
+MY_LOG("invalid squishiness: {}", 42);
+
+

Note that vlog is not parameterized on argument types which improves +compile times and reduces binary code size compared to a fully +parameterized version.

+
+ +
template <typename Context, typename... T, int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC> +
constexpr auto make_format_args(T&... args) -⁠> detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>;
+
+
+

Constructs an object that stores references to arguments and can be implicitly converted to format_args. Context can be omitted in which case it defaults to context. See arg for lifetime considerations.

+
+
+
+ +
template <typename Context> +
class basic_format_args;
+
+
+

A view of a collection of formatting arguments. To avoid lifetime issues it should only be used as a parameter type in type-erased functions such as vformat:

void vlog(fmt::string_view fmt, fmt::format_args args);  // OK
+fmt::format_args args = fmt::make_format_args();  // Dangling reference
+

+
+
constexpr basic_format_args(const store<NUM_ARGS, NUM_NAMED_ARGS, DESC>& s);
+
+

Constructs a basic_format_args object from format_arg_store.

+
+
+
+
constexpr basic_format_args(const format_arg* args, int count, bool has_named);
+
+

Constructs a basic_format_args object from a dynamic list of arguments.

+
+
+
+
auto get(int id) -⁠> format_arg;
+
+

Returns the argument with the specified id.

+
+
+
+
+ +
+ +
template <typename Context> +
class basic_format_arg;
+
+
+
+
auto visit(Visitor&& vis) -⁠> decltype(vis(0));
+
+

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.

+
+
+
+
+

Named Arguments

+
+ +
template <typename Char, typename T> +
auto arg(const Char* name, const T& arg) -⁠> detail::named_arg<Char, T>;
+
+
+

Returns a named argument to be used in a formatting function. It should only be used in a call to a formatting function.

+

Example:

fmt::print("The answer is {answer}.", fmt::arg("answer", 42));
+

+
+
+

Named arguments are not supported in compile-time checks at the moment.

+

Compatibility

+
+ +
template <typename Char> +
class basic_string_view;
+
+
+

An implementation of std::basic_string_view for pre-C++17. It provides a subset of the API. fmt::basic_string_view is used for format strings even if std::basic_string_view is available to prevent issues when a library is compiled with a different -std option than the client code (which is not recommended).

+
+
constexpr basic_string_view(const Char* s, size_t count);
+
+

Constructs a string reference object from a C string and a size.

+
+
+
+
basic_string_view(const Char* s);
+
+

Constructs a string reference object from a C string.

+
+
+
+
basic_string_view(const S& s);
+
+

Constructs a string reference from a std::basic_string or a std::basic_string_view object.

+
+
+
+
constexpr auto data() -⁠> const Char*;
+
+

Returns a pointer to the string data.

+
+
+
+
constexpr auto size() -⁠> size_t;
+
+

Returns the string size.

+
+
+
+
+ +

Format API

+

fmt/format.h defines the full format API providing additional +formatting functions and locale support.

+

+

+
+ +
template <typename... T> +
auto format(format_string<T...> fmt, T&&... args) -⁠> std::string;
+
+
+

Formats args according to specifications in fmt and returns the result as a string.

+

Example:

#include <fmt/format.h>
+std::string message = fmt::format("The answer is {}.", 42);
+

+
+
+ + +

Utilities

+
+ +
template <typename T> +
auto ptr(T p) -⁠> const void*;
+
+
+

Converts p to const void* for pointer formatting.

+

Example:

auto s = fmt::format("{}", fmt::ptr(p));
+

+
+
+
+ +
template <typename Enum> +
constexpr auto underlying(Enum e) -⁠> underlying_t<Enum>;
+
+
+

Converts e to the underlying type.

+

Example:

enum class color { red, green, blue };
+auto s = fmt::format("{}", fmt::underlying(color::red));  // s == "0"
+

+
+
+ +
+ +
template <typename T> +
auto group_digits(T value) -⁠> group_digits_view<T>;
+
+
+

Returns a view that formats an integer value using ',' as a locale-independent thousands separator.

+

Example:

fmt::print("{}", fmt::group_digits(12345));
+// Output: "12,345"
+

+
+
+
+ +
template <typename T> +
class detail::buffer;
+
+
+

A contiguous memory buffer with an optional growing ability. It is an internal class and shouldn't be used directly, only via memory_buffer.

+
+
constexpr auto size() -⁠> size_t;
+
+

Returns the size of this buffer.

+
+
+
+
constexpr auto capacity() -⁠> size_t;
+
+

Returns the capacity of this buffer.

+
+
+
+
auto data() -⁠> T*;
+
+

Returns a pointer to the buffer data (not null-terminated).

+
+
+
+
void clear();
+
+

Clears this buffer.

+
+
+
+
void append(const U* begin, const U* end);
+
+

Appends data to the end of the buffer.

+
+
+
+
+
+ +
template <typename T, size_t SIZE, typename Allocator> +
class basic_memory_buffer;
+
+
+

A dynamically growing memory buffer for trivially copyable/constructible types with the first SIZE elements stored in the object itself. Most commonly used via the memory_buffer alias for char.

+

Example:

auto out = fmt::memory_buffer();
+fmt::format_to(std::back_inserter(out), "The answer is {}.", 42);
+
This will append "The answer is 42." to out. The buffer content can be converted to std::string with to_string(out).

+
+
basic_memory_buffer(basic_memory_buffer&& other);
+
+

Constructs a basic_memory_buffer object moving the content of the other object to it.

+
+
+
+
auto operator=(basic_memory_buffer&& other) -⁠> basic_memory_buffer&;
+
+

Moves the content of the other basic_memory_buffer object to this one.

+
+
+
+
void resize(size_t count);
+
+

Resizes the buffer to contain count elements. If T is a POD type new elements may not be initialized.

+
+
+
+
void reserve(size_t new_capacity);
+
+

Increases the buffer capacity to new_capacity.

+
+
+
+
+

System Errors

+

{fmt} does not use errno to communicate errors to the user, but it may +call system functions which set errno. Users should not make any +assumptions about the value of errno being preserved by library +functions.

+
+ +
template <typename... T> +
auto system_error(int error_code, format_string<T...> fmt, T&&... args) -⁠> std::system_error;
+
+
+

Constructs std::system_error with a message formatted with fmt::format(fmt, args...). error_code is a system error code as given by errno.

+

Example:

// This throws std::system_error with the description
+//   cannot open file 'madeup': No such file or directory
+// or similar (system message may vary).
+const char* filename = "madeup";
+FILE* file = fopen(filename, "r");
+if (!file)
+  throw fmt::system_error(errno, "cannot open file '{}'", filename);
+

+
+
+
+ +
void format_system_error(detail::buffer<char>& out, int error_code, const char* message);
+
+
+

Formats an error message for an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out. The format is the same as the one used by std::system_error(ec, message) where ec is std::error_code(error_code, std::generic_category()). It is implementation-defined but normally looks like:

<message>: <system-message>
+
where <message> is the passed message and <system-message> is the system message corresponding to the error code. error_code is a system error code as given by errno.

+
+
+

Custom Allocators

+

The {fmt} library supports custom dynamic memory allocators. A custom +allocator class can be specified as a template argument to +fmt::basic_memory_buffer:

+
using custom_memory_buffer = 
+  fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
+

It is also possible to write a formatting function that uses a custom +allocator:

+
using custom_string =
+  std::basic_string<char, std::char_traits<char>, custom_allocator>;
+
+auto vformat(custom_allocator alloc, fmt::string_view fmt,
+             fmt::format_args args) -> custom_string {
+  auto buf = custom_memory_buffer(alloc);
+  fmt::vformat_to(std::back_inserter(buf), fmt, args);
+  return custom_string(buf.data(), buf.size(), alloc);
+}
+
+template <typename ...Args>
+auto format(custom_allocator alloc, fmt::string_view fmt,
+            const Args& ... args) -> custom_string {
+  return vformat(alloc, fmt, fmt::make_format_args(args...));
+}
+

The allocator will be used for the output container only. Formatting +functions normally don't do any allocations for built-in and string +types except for non-default floating-point formatting that occasionally +falls back on sprintf.

+

Locale

+

All formatting is locale-independent by default. Use the 'L' format +specifier to insert the appropriate number separator characters from the +locale:

+
#include <fmt/core.h>
+#include <locale>
+
+std::locale::global(std::locale("en_US.UTF-8"));
+auto s = fmt::format("{:L}", 1000000);  // s == "1,000,000"
+

fmt/format.h provides the following overloads of formatting functions +that take std::locale as a parameter. The locale type is a template +parameter to avoid the expensive <locale> include.

+ + + +

+

Legacy Compile-Time Checks

+

FMT_STRING enables compile-time checks on older compilers. It requires +C++14 or later and is a no-op in C++11.

+
+ +
FMT_STRING(s)
+
+
+

Constructs a legacy compile-time format string from a string literal s.

+

Example:

// A compile-time error because 'd' is an invalid specifier for strings.
+std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
+

+
+
+

To force the use of legacy compile-time checks, define the preprocessor +variable FMT_ENFORCE_COMPILE_STRING. When set, functions accepting +FMT_STRING will fail to compile with regular strings.

+

+

Range and Tuple Formatting

+

fmt/ranges.h provides formatting support for ranges and tuples:

+
#include <fmt/ranges.h>
+
+fmt::print("{}", std::tuple<char, int>{'a', 42});
+// Output: ('a', 42)
+

Using fmt::join, you can separate tuple elements with a custom separator:

+
#include <fmt/ranges.h>
+
+auto t = std::tuple<int, char>{1, 'a'};
+fmt::print("{}", fmt::join(t, ", "));
+// Output: 1, a
+
+ +
template <typename Range> +
auto join(Range&& r, string_view sep) -⁠> join_view<decltype(detail::range_begin(r)), decltype(detail::range_end(r))>;
+
+
+

Returns a view that formats range with elements separated by sep.

+

Example:

auto v = std::vector<int>{1, 2, 3};
+fmt::print("{}", fmt::join(v, ", "));
+// Output: 1, 2, 3
+
fmt::join applies passed format specifiers to the range elements:
fmt::print("{:02}", fmt::join(v, ", "));
+// Output: 01, 02, 03
+

+
+
+
+ +
template <typename It, typename Sentinel> +
auto join(It begin, Sentinel end, string_view sep) -⁠> join_view<It, Sentinel>;
+
+
+

Returns a view that formats the iterator range [begin, end) with elements separated by sep.

+
+
+
+ +
template <typename T> +
auto join(std::initializer_list<T> list, string_view sep) -⁠> join_view<const T*, const T*>;
+
+
+

Returns an object that formats std::initializer_list with elements separated by sep.

+

Example:

fmt::print("{}", fmt::join({1, 2, 3}, ", "));
+// Output: "1, 2, 3"
+

+
+
+

+

Date and Time Formatting

+

fmt/chrono.h provides formatters for

+ +

The format syntax is described in Chrono Format Specifications.

+

Example:

+
#include <fmt/chrono.h>
+
+int main() {
+  std::time_t t = std::time(nullptr);
+
+  fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
+  // Output: The date is 2020-11-07.
+  // (with 2020-11-07 replaced by the current date)
+
+  using namespace std::literals::chrono_literals;
+
+  fmt::print("Default format: {} {}\n", 42s, 100ms);
+  // Output: Default format: 42s 100ms
+
+  fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
+  // Output: strftime-like format: 03:15:30
+}
+
+ +
auto localtime(std::time_t time) -⁠> std::tm;
+
+
+

Converts given time since epoch as std::time_t value into calendar time, expressed in local time. Unlike std::localtime, this function is thread-safe on most platforms.

+
+
+
+ +
auto gmtime(std::time_t time) -⁠> std::tm;
+
+
+

Converts given time since epoch as std::time_t value into calendar time, expressed in Coordinated Universal Time (UTC). Unlike std::gmtime, this function is thread-safe on most platforms.

+
+
+

+

Standard Library Types Formatting

+

fmt/std.h provides formatters for:

+ + + +

Variants

+

A std::variant is only formattable if every variant alternative is +formattable, and requires the __cpp_lib_variant library +feature.

+

Example:

+
#include <fmt/std.h>
+
+fmt::print("{}", std::variant<char, float>('x'));
+// Output: variant('x')
+
+fmt::print("{}", std::variant<std::monostate, char>());
+// Output: variant(monostate)
+

Bit-Fields and Packed Structs

+

To format a bit-field or a field of a struct with __attribute__((packed)) +applied to it, you need to convert it to the underlying or compatible type via +a cast or a unary + (godbolt):

+
struct smol {
+  int bit : 1;
+};
+
+auto s = smol();
+fmt::print("{}", +s.bit);
+
+

This is a known limitation of "perfect" forwarding in C++.

+

+

Format String Compilation

+

fmt/compile.h provides format string compilation and compile-time +(constexpr) formatting enabled via the FMT_COMPILE macro or the _cf +user-defined literal defined in namespace fmt::literals. Format strings +marked with FMT_COMPILE or _cf are parsed, checked and converted into +efficient formatting code at compile-time. This supports arguments of built-in +and string types as well as user-defined types with format functions taking +the format context type as a template parameter in their formatter +specializations. For example:

+
template <> struct fmt::formatter<point> {
+  constexpr auto parse(format_parse_context& ctx);
+
+  template <typename FormatContext>
+  auto format(const point& p, FormatContext& ctx) const;
+};
+

Format string compilation can generate more binary code compared to the +default API and is only recommended in places where formatting is a +performance bottleneck.

+
+ +
FMT_COMPILE(s)
+
+
+

Converts a string literal s into a format string that will be parsed at compile time and converted into efficient formatting code. Requires C++17 constexpr if compiler support.

+

Example:

// Converts 42 into std::string using the most efficient method and no
+// runtime format string processing.
+std::string s = fmt::format(FMT_COMPILE("{}"), 42);
+

+
+
+ +

+

Terminal Colors and Text Styles

+

fmt/color.h provides support for terminal color and text style output.

+
+ +
template <typename... T> +
void print(const text_style& ts, format_string<T...> fmt, T&&... args);
+
+
+

Formats a string and prints it to stdout using ANSI escape sequences to specify text formatting.

+

Example:

fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
+           "Elapsed time: {0:.2f} seconds", 1.23);
+

+
+
+
+ +
auto fg(detail::color_type foreground) -⁠> text_style;
+
+
+

Creates a text style from the foreground (text) color.

+
+
+
+ +
auto bg(detail::color_type background) -⁠> text_style;
+
+
+

Creates a text style from the background color.

+
+
+
+ +
template <typename T> +
auto styled(const T& value, text_style ts) -⁠> detail::styled_arg<remove_cvref_t<T>>;
+
+
+

Returns an argument that will be formatted using ANSI escape sequences, to be used in a formatting function.

+

Example:

fmt::print("Elapsed time: {0:.2f} seconds",
+           fmt::styled(1.23, fmt::fg(fmt::color::green) |
+                             fmt::bg(fmt::color::blue)));
+

+
+
+

+

System APIs

+
+ +
class ostream;
+
+
+

A fast buffered output stream for writing from a single thread. Writing from multiple threads without external synchronization may result in a data race.

+
+
void print(format_string<T...> fmt, T&&... args);
+
+

Formats args according to specifications in fmt and writes the output to the file.

+
+
+
+
+
+ +
template <typename... T> +
auto windows_error(int error_code, string_view message, const T&... args) -⁠> std::system_error;
+
+
+

Constructs a std::system_error object with the description of the form

<message>: <system-message>
+
where <message> is the formatted message and <system-message> is the system message corresponding to the error code. error_code is a Windows error code as given by GetLastError. If error_code is not a valid error code such as -1, the system message will look like "error -1".

+

Example:

// This throws a system_error with the description
+//   cannot open file 'madeup': The system cannot find the file
+
specified. // or similar (system message may vary). const char *filename = "madeup"; LPOFSTRUCT of = LPOFSTRUCT(); HFILE file = OpenFile(filename, &of, OF_READ); if (file == HFILE_ERROR) { throw fmt::windows_error(GetLastError(), "cannot open file '{}'", filename); }

+
+
+

+

std::ostream Support

+

fmt/ostream.h provides std::ostream support including formatting of +user-defined types that have an overloaded insertion operator +(operator<<). In order to make a type formattable via std::ostream +you should provide a formatter specialization inherited from +ostream_formatter:

+
#include <fmt/ostream.h>
+
+struct date {
+  int year, month, day;
+
+  friend std::ostream& operator<<(std::ostream& os, const date& d) {
+    return os << d.year << '-' << d.month << '-' << d.day;
+  }
+};
+
+template <> struct fmt::formatter<date> : ostream_formatter {};
+
+std::string s = fmt::format("The date is {}", date{2012, 12, 9});
+// s == "The date is 2012-12-9"
+
+ +
template <typename T> +
constexpr auto streamed(const T& value) -⁠> detail::streamed_view<T>;
+
+
+

Returns a view that formats value via an ostream operator<<.

+

Example:

fmt::print("Current thread id: {}\n",
+           fmt::streamed(std::this_thread::get_id()));
+

+
+
+
+ +
template <typename... T> +
void print(std::ostream& os, format_string<T...> fmt, T&&... args);
+
+
+

Prints formatted data to the stream os.

+

Example:

fmt::print(cerr, "Don't {}!", "panic");
+

+
+
+

+

Dynamic Argument Lists

+

The header fmt/args.h provides dynamic_format_arg_store, a builder-like API +that can be used to construct format argument lists dynamically.

+
+ +
template <typename Context> +
class dynamic_format_arg_store;
+
+
+

A dynamic list of formatting arguments with storage.

+

It can be implicitly converted into fmt::basic_format_args for passing into type-erased formatting functions such as fmt::vformat.

+
+
void push_back(const T& arg);
+
+

Adds an argument into the dynamic store for later passing to a formatting function.

+

Note that custom types and string types (but not string views) are copied into the store dynamically allocating memory if necessary.

+

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
+store.push_back(42);
+store.push_back("abc");
+store.push_back(1.5f);
+std::string result = fmt::vformat("{} and {} and {}", store);
+

+
+
+
+
void push_back(std::reference_wrapper<T> arg);
+
+

Adds a reference to the argument into the dynamic store for later passing to a formatting function.

+

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
+char band[] = "Rolling Stones";
+store.push_back(std::cref(band));
+band[9] = 'c'; // Changing str affects the output.
+std::string result = fmt::vformat("{}", store);
+// result == "Rolling Scones"
+

+
+
+
+
void push_back(const detail::named_arg<char_type, T>& arg);
+
+

Adds named argument into the dynamic store for later passing to a formatting function. std::reference_wrapper is supported to avoid copying of the argument. The name is always copied into the store.

+
+
+
+
void clear();
+
+

Erase all elements from the store.

+
+
+
+
void reserve(size_t new_cap, size_t new_cap_named);
+
+

Reserves space to store at least new_cap arguments including new_cap_named named arguments.

+
+
+
+
size_t size();
+
+

Returns the number of elements in the store.

+
+
+
+
+

+

Safe printf

+

The header fmt/printf.h provides printf-like formatting +functionality. The following functions use printf format string +syntax +with the POSIX extension for positional arguments. Unlike their standard +counterparts, the fmt functions are type-safe and throw an exception +if an argument type doesn't match its format specification.

+
+ +
template <typename... T> +
auto printf(string_view fmt, const T&... args) -⁠> int;
+
+
+

Formats args according to specifications in fmt and writes the output to stdout.

+

Example:

+

fmt::printf("Elapsed time: %.2f seconds", 1.23);

+
+
+
+ +
template <typename S, typename... T, typename Char> +
auto fprintf(std::FILE* f, const S& fmt, const T&... args) -⁠> int;
+
+
+

Formats args according to specifications in fmt and writes the output to f.

+

Example:

fmt::fprintf(stderr, "Don't %s!", "panic");
+

+
+
+
+ +
template <typename S, typename... T, typename Char> +
auto sprintf(const S& fmt, const T&... args) -⁠> std::basic_string<Char>;
+
+
+

Formats args according to specifications in fmt and returns the result as as string.

+

Example:

std::string message = fmt::sprintf("The answer is %d", 42);
+

+
+
+

+

Wide Strings

+

The optional header fmt/xchar.h provides support for wchar_t and +exotic character types.

+ + + +
+ +
template <typename T> +
auto to_wstring(const T& value) -⁠> std::wstring;
+
+
+

Converts value to std::wstring using the default format for type T.

+
+
+

Compatibility with C++20 std::format

+

{fmt} implements nearly all of the C++20 formatting +library with the +following differences:

+
    +
  • +

    Names are defined in the fmt namespace instead of std to avoid + collisions with standard library implementations.

    +
  • +
  • +

    Width calculation doesn't use grapheme clusterization. The latter has + been implemented in a separate branch but hasn't been integrated yet.

    +
  • +
  • +

    The default floating-point representation in {fmt} uses the smallest + precision that provides round-trip guarantees similarly to other languages + like Java and Python. std::format is currently specified in terms of + std::to_chars which tries to generate the smallest number of characters + (ignoring redundant digits and sign in exponent) and may procude more + decimal digits than necessary.

    +
  • +
+ + + + + + + + + + + + + +
+
+ + + +
+ + + +
+ +
+ + +
+ +
+
+
+
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/fmt/doc-html/assets/_mkdocstrings.css b/third-party/fmt/doc-html/assets/_mkdocstrings.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/third-party/fmt/doc-html/assets/images/favicon.png b/third-party/fmt/doc-html/assets/images/favicon.png new file mode 100644 index 0000000000..1cf13b9f9d Binary files /dev/null and b/third-party/fmt/doc-html/assets/images/favicon.png differ diff --git a/third-party/fmt/doc-html/assets/javascripts/bundle.081f42fc.min.js b/third-party/fmt/doc-html/assets/javascripts/bundle.081f42fc.min.js new file mode 100644 index 0000000000..32734cd370 --- /dev/null +++ b/third-party/fmt/doc-html/assets/javascripts/bundle.081f42fc.min.js @@ -0,0 +1,29 @@ +"use strict";(()=>{var Fi=Object.create;var gr=Object.defineProperty;var ji=Object.getOwnPropertyDescriptor;var Wi=Object.getOwnPropertyNames,Dt=Object.getOwnPropertySymbols,Ui=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty,no=Object.prototype.propertyIsEnumerable;var oo=(e,t,r)=>t in e?gr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R=(e,t)=>{for(var r in t||(t={}))xr.call(t,r)&&oo(e,r,t[r]);if(Dt)for(var r of Dt(t))no.call(t,r)&&oo(e,r,t[r]);return e};var io=(e,t)=>{var r={};for(var o in e)xr.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(e!=null&&Dt)for(var o of Dt(e))t.indexOf(o)<0&&no.call(e,o)&&(r[o]=e[o]);return r};var yr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Di=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Wi(t))!xr.call(e,n)&&n!==r&&gr(e,n,{get:()=>t[n],enumerable:!(o=ji(t,n))||o.enumerable});return e};var Vt=(e,t,r)=>(r=e!=null?Fi(Ui(e)):{},Di(t||!e||!e.__esModule?gr(r,"default",{value:e,enumerable:!0}):r,e));var ao=(e,t,r)=>new Promise((o,n)=>{var i=p=>{try{s(r.next(p))}catch(c){n(c)}},a=p=>{try{s(r.throw(p))}catch(c){n(c)}},s=p=>p.done?o(p.value):Promise.resolve(p.value).then(i,a);s((r=r.apply(e,t)).next())});var co=yr((Er,so)=>{(function(e,t){typeof Er=="object"&&typeof so!="undefined"?t():typeof define=="function"&&define.amd?define(t):t()})(Er,function(){"use strict";function e(r){var o=!0,n=!1,i=null,a={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function s(H){return!!(H&&H!==document&&H.nodeName!=="HTML"&&H.nodeName!=="BODY"&&"classList"in H&&"contains"in H.classList)}function p(H){var mt=H.type,ze=H.tagName;return!!(ze==="INPUT"&&a[mt]&&!H.readOnly||ze==="TEXTAREA"&&!H.readOnly||H.isContentEditable)}function c(H){H.classList.contains("focus-visible")||(H.classList.add("focus-visible"),H.setAttribute("data-focus-visible-added",""))}function l(H){H.hasAttribute("data-focus-visible-added")&&(H.classList.remove("focus-visible"),H.removeAttribute("data-focus-visible-added"))}function f(H){H.metaKey||H.altKey||H.ctrlKey||(s(r.activeElement)&&c(r.activeElement),o=!0)}function u(H){o=!1}function h(H){s(H.target)&&(o||p(H.target))&&c(H.target)}function w(H){s(H.target)&&(H.target.classList.contains("focus-visible")||H.target.hasAttribute("data-focus-visible-added"))&&(n=!0,window.clearTimeout(i),i=window.setTimeout(function(){n=!1},100),l(H.target))}function A(H){document.visibilityState==="hidden"&&(n&&(o=!0),te())}function te(){document.addEventListener("mousemove",J),document.addEventListener("mousedown",J),document.addEventListener("mouseup",J),document.addEventListener("pointermove",J),document.addEventListener("pointerdown",J),document.addEventListener("pointerup",J),document.addEventListener("touchmove",J),document.addEventListener("touchstart",J),document.addEventListener("touchend",J)}function ie(){document.removeEventListener("mousemove",J),document.removeEventListener("mousedown",J),document.removeEventListener("mouseup",J),document.removeEventListener("pointermove",J),document.removeEventListener("pointerdown",J),document.removeEventListener("pointerup",J),document.removeEventListener("touchmove",J),document.removeEventListener("touchstart",J),document.removeEventListener("touchend",J)}function J(H){H.target.nodeName&&H.target.nodeName.toLowerCase()==="html"||(o=!1,ie())}document.addEventListener("keydown",f,!0),document.addEventListener("mousedown",u,!0),document.addEventListener("pointerdown",u,!0),document.addEventListener("touchstart",u,!0),document.addEventListener("visibilitychange",A,!0),te(),r.addEventListener("focus",h,!0),r.addEventListener("blur",w,!0),r.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&r.host?r.host.setAttribute("data-js-focus-visible",""):r.nodeType===Node.DOCUMENT_NODE&&(document.documentElement.classList.add("js-focus-visible"),document.documentElement.setAttribute("data-js-focus-visible",""))}if(typeof window!="undefined"&&typeof document!="undefined"){window.applyFocusVisiblePolyfill=e;var t;try{t=new CustomEvent("focus-visible-polyfill-ready")}catch(r){t=document.createEvent("CustomEvent"),t.initCustomEvent("focus-visible-polyfill-ready",!1,!1,{})}window.dispatchEvent(t)}typeof document!="undefined"&&e(document)})});var Yr=yr((Rt,Kr)=>{/*! + * clipboard.js v2.0.11 + * https://clipboardjs.com/ + * + * Licensed MIT © Zeno Rocha + */(function(t,r){typeof Rt=="object"&&typeof Kr=="object"?Kr.exports=r():typeof define=="function"&&define.amd?define([],r):typeof Rt=="object"?Rt.ClipboardJS=r():t.ClipboardJS=r()})(Rt,function(){return function(){var e={686:function(o,n,i){"use strict";i.d(n,{default:function(){return Ii}});var a=i(279),s=i.n(a),p=i(370),c=i.n(p),l=i(817),f=i.n(l);function u(V){try{return document.execCommand(V)}catch(_){return!1}}var h=function(_){var O=f()(_);return u("cut"),O},w=h;function A(V){var _=document.documentElement.getAttribute("dir")==="rtl",O=document.createElement("textarea");O.style.fontSize="12pt",O.style.border="0",O.style.padding="0",O.style.margin="0",O.style.position="absolute",O.style[_?"right":"left"]="-9999px";var j=window.pageYOffset||document.documentElement.scrollTop;return O.style.top="".concat(j,"px"),O.setAttribute("readonly",""),O.value=V,O}var te=function(_,O){var j=A(_);O.container.appendChild(j);var D=f()(j);return u("copy"),j.remove(),D},ie=function(_){var O=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body},j="";return typeof _=="string"?j=te(_,O):_ instanceof HTMLInputElement&&!["text","search","url","tel","password"].includes(_==null?void 0:_.type)?j=te(_.value,O):(j=f()(_),u("copy")),j},J=ie;function H(V){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?H=function(O){return typeof O}:H=function(O){return O&&typeof Symbol=="function"&&O.constructor===Symbol&&O!==Symbol.prototype?"symbol":typeof O},H(V)}var mt=function(){var _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=_.action,j=O===void 0?"copy":O,D=_.container,Y=_.target,ke=_.text;if(j!=="copy"&&j!=="cut")throw new Error('Invalid "action" value, use either "copy" or "cut"');if(Y!==void 0)if(Y&&H(Y)==="object"&&Y.nodeType===1){if(j==="copy"&&Y.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if(j==="cut"&&(Y.hasAttribute("readonly")||Y.hasAttribute("disabled")))throw new Error(`Invalid "target" attribute. You can't cut text from elements with "readonly" or "disabled" attributes`)}else throw new Error('Invalid "target" value, use a valid Element');if(ke)return J(ke,{container:D});if(Y)return j==="cut"?w(Y):J(Y,{container:D})},ze=mt;function Ie(V){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ie=function(O){return typeof O}:Ie=function(O){return O&&typeof Symbol=="function"&&O.constructor===Symbol&&O!==Symbol.prototype?"symbol":typeof O},Ie(V)}function _i(V,_){if(!(V instanceof _))throw new TypeError("Cannot call a class as a function")}function ro(V,_){for(var O=0;O<_.length;O++){var j=_[O];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty(V,j.key,j)}}function Ai(V,_,O){return _&&ro(V.prototype,_),O&&ro(V,O),V}function Ci(V,_){if(typeof _!="function"&&_!==null)throw new TypeError("Super expression must either be null or a function");V.prototype=Object.create(_&&_.prototype,{constructor:{value:V,writable:!0,configurable:!0}}),_&&br(V,_)}function br(V,_){return br=Object.setPrototypeOf||function(j,D){return j.__proto__=D,j},br(V,_)}function Hi(V){var _=Pi();return function(){var j=Wt(V),D;if(_){var Y=Wt(this).constructor;D=Reflect.construct(j,arguments,Y)}else D=j.apply(this,arguments);return ki(this,D)}}function ki(V,_){return _&&(Ie(_)==="object"||typeof _=="function")?_:$i(V)}function $i(V){if(V===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return V}function Pi(){if(typeof Reflect=="undefined"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(V){return!1}}function Wt(V){return Wt=Object.setPrototypeOf?Object.getPrototypeOf:function(O){return O.__proto__||Object.getPrototypeOf(O)},Wt(V)}function vr(V,_){var O="data-clipboard-".concat(V);if(_.hasAttribute(O))return _.getAttribute(O)}var Ri=function(V){Ci(O,V);var _=Hi(O);function O(j,D){var Y;return _i(this,O),Y=_.call(this),Y.resolveOptions(D),Y.listenClick(j),Y}return Ai(O,[{key:"resolveOptions",value:function(){var D=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.action=typeof D.action=="function"?D.action:this.defaultAction,this.target=typeof D.target=="function"?D.target:this.defaultTarget,this.text=typeof D.text=="function"?D.text:this.defaultText,this.container=Ie(D.container)==="object"?D.container:document.body}},{key:"listenClick",value:function(D){var Y=this;this.listener=c()(D,"click",function(ke){return Y.onClick(ke)})}},{key:"onClick",value:function(D){var Y=D.delegateTarget||D.currentTarget,ke=this.action(Y)||"copy",Ut=ze({action:ke,container:this.container,target:this.target(Y),text:this.text(Y)});this.emit(Ut?"success":"error",{action:ke,text:Ut,trigger:Y,clearSelection:function(){Y&&Y.focus(),window.getSelection().removeAllRanges()}})}},{key:"defaultAction",value:function(D){return vr("action",D)}},{key:"defaultTarget",value:function(D){var Y=vr("target",D);if(Y)return document.querySelector(Y)}},{key:"defaultText",value:function(D){return vr("text",D)}},{key:"destroy",value:function(){this.listener.destroy()}}],[{key:"copy",value:function(D){var Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body};return J(D,Y)}},{key:"cut",value:function(D){return w(D)}},{key:"isSupported",value:function(){var D=arguments.length>0&&arguments[0]!==void 0?arguments[0]:["copy","cut"],Y=typeof D=="string"?[D]:D,ke=!!document.queryCommandSupported;return Y.forEach(function(Ut){ke=ke&&!!document.queryCommandSupported(Ut)}),ke}}]),O}(s()),Ii=Ri},828:function(o){var n=9;if(typeof Element!="undefined"&&!Element.prototype.matches){var i=Element.prototype;i.matches=i.matchesSelector||i.mozMatchesSelector||i.msMatchesSelector||i.oMatchesSelector||i.webkitMatchesSelector}function a(s,p){for(;s&&s.nodeType!==n;){if(typeof s.matches=="function"&&s.matches(p))return s;s=s.parentNode}}o.exports=a},438:function(o,n,i){var a=i(828);function s(l,f,u,h,w){var A=c.apply(this,arguments);return l.addEventListener(u,A,w),{destroy:function(){l.removeEventListener(u,A,w)}}}function p(l,f,u,h,w){return typeof l.addEventListener=="function"?s.apply(null,arguments):typeof u=="function"?s.bind(null,document).apply(null,arguments):(typeof l=="string"&&(l=document.querySelectorAll(l)),Array.prototype.map.call(l,function(A){return s(A,f,u,h,w)}))}function c(l,f,u,h){return function(w){w.delegateTarget=a(w.target,f),w.delegateTarget&&h.call(l,w)}}o.exports=p},879:function(o,n){n.node=function(i){return i!==void 0&&i instanceof HTMLElement&&i.nodeType===1},n.nodeList=function(i){var a=Object.prototype.toString.call(i);return i!==void 0&&(a==="[object NodeList]"||a==="[object HTMLCollection]")&&"length"in i&&(i.length===0||n.node(i[0]))},n.string=function(i){return typeof i=="string"||i instanceof String},n.fn=function(i){var a=Object.prototype.toString.call(i);return a==="[object Function]"}},370:function(o,n,i){var a=i(879),s=i(438);function p(u,h,w){if(!u&&!h&&!w)throw new Error("Missing required arguments");if(!a.string(h))throw new TypeError("Second argument must be a String");if(!a.fn(w))throw new TypeError("Third argument must be a Function");if(a.node(u))return c(u,h,w);if(a.nodeList(u))return l(u,h,w);if(a.string(u))return f(u,h,w);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function c(u,h,w){return u.addEventListener(h,w),{destroy:function(){u.removeEventListener(h,w)}}}function l(u,h,w){return Array.prototype.forEach.call(u,function(A){A.addEventListener(h,w)}),{destroy:function(){Array.prototype.forEach.call(u,function(A){A.removeEventListener(h,w)})}}}function f(u,h,w){return s(document.body,u,h,w)}o.exports=p},817:function(o){function n(i){var a;if(i.nodeName==="SELECT")i.focus(),a=i.value;else if(i.nodeName==="INPUT"||i.nodeName==="TEXTAREA"){var s=i.hasAttribute("readonly");s||i.setAttribute("readonly",""),i.select(),i.setSelectionRange(0,i.value.length),s||i.removeAttribute("readonly"),a=i.value}else{i.hasAttribute("contenteditable")&&i.focus();var p=window.getSelection(),c=document.createRange();c.selectNodeContents(i),p.removeAllRanges(),p.addRange(c),a=p.toString()}return a}o.exports=n},279:function(o){function n(){}n.prototype={on:function(i,a,s){var p=this.e||(this.e={});return(p[i]||(p[i]=[])).push({fn:a,ctx:s}),this},once:function(i,a,s){var p=this;function c(){p.off(i,c),a.apply(s,arguments)}return c._=a,this.on(i,c,s)},emit:function(i){var a=[].slice.call(arguments,1),s=((this.e||(this.e={}))[i]||[]).slice(),p=0,c=s.length;for(p;p{"use strict";/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */var ts=/["'&<>]/;ei.exports=rs;function rs(e){var t=""+e,r=ts.exec(t);if(!r)return t;var o,n="",i=0,a=0;for(i=r.index;i0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,i=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)i.push(n.value)}catch(s){a={error:s}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return i}function q(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o1||s(u,h)})})}function s(u,h){try{p(o[u](h))}catch(w){f(i[0][3],w)}}function p(u){u.value instanceof nt?Promise.resolve(u.value.v).then(c,l):f(i[0][2],u)}function c(u){s("next",u)}function l(u){s("throw",u)}function f(u,h){u(h),i.shift(),i.length&&s(i[0][0],i[0][1])}}function mo(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof de=="function"?de(e):e[Symbol.iterator](),r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r);function o(i){r[i]=e[i]&&function(a){return new Promise(function(s,p){a=e[i](a),n(s,p,a.done,a.value)})}}function n(i,a,s,p){Promise.resolve(p).then(function(c){i({value:c,done:s})},a)}}function k(e){return typeof e=="function"}function ft(e){var t=function(o){Error.call(o),o.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var zt=ft(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription: +`+r.map(function(o,n){return n+1+") "+o.toString()}).join(` + `):"",this.name="UnsubscriptionError",this.errors=r}});function qe(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Fe=function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,o,n,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var s=de(a),p=s.next();!p.done;p=s.next()){var c=p.value;c.remove(this)}}catch(A){t={error:A}}finally{try{p&&!p.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}else a.remove(this);var l=this.initialTeardown;if(k(l))try{l()}catch(A){i=A instanceof zt?A.errors:[A]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var u=de(f),h=u.next();!h.done;h=u.next()){var w=h.value;try{fo(w)}catch(A){i=i!=null?i:[],A instanceof zt?i=q(q([],N(i)),N(A.errors)):i.push(A)}}}catch(A){o={error:A}}finally{try{h&&!h.done&&(n=u.return)&&n.call(u)}finally{if(o)throw o.error}}}if(i)throw new zt(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)fo(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&qe(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&qe(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}();var Tr=Fe.EMPTY;function qt(e){return e instanceof Fe||e&&"closed"in e&&k(e.remove)&&k(e.add)&&k(e.unsubscribe)}function fo(e){k(e)?e():e.unsubscribe()}var $e={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var ut={setTimeout:function(e,t){for(var r=[],o=2;o0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var o=this,n=this,i=n.hasError,a=n.isStopped,s=n.observers;return i||a?Tr:(this.currentObservers=null,s.push(r),new Fe(function(){o.currentObservers=null,qe(s,r)}))},t.prototype._checkFinalizedStatuses=function(r){var o=this,n=o.hasError,i=o.thrownError,a=o.isStopped;n?r.error(i):a&&r.complete()},t.prototype.asObservable=function(){var r=new F;return r.source=this,r},t.create=function(r,o){return new Eo(r,o)},t}(F);var Eo=function(e){re(t,e);function t(r,o){var n=e.call(this)||this;return n.destination=r,n.source=o,n}return t.prototype.next=function(r){var o,n;(n=(o=this.destination)===null||o===void 0?void 0:o.next)===null||n===void 0||n.call(o,r)},t.prototype.error=function(r){var o,n;(n=(o=this.destination)===null||o===void 0?void 0:o.error)===null||n===void 0||n.call(o,r)},t.prototype.complete=function(){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||o===void 0||o.call(r)},t.prototype._subscribe=function(r){var o,n;return(n=(o=this.source)===null||o===void 0?void 0:o.subscribe(r))!==null&&n!==void 0?n:Tr},t}(g);var _r=function(e){re(t,e);function t(r){var o=e.call(this)||this;return o._value=r,o}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(r){var o=e.prototype._subscribe.call(this,r);return!o.closed&&r.next(this._value),o},t.prototype.getValue=function(){var r=this,o=r.hasError,n=r.thrownError,i=r._value;if(o)throw n;return this._throwIfClosed(),i},t.prototype.next=function(r){e.prototype.next.call(this,this._value=r)},t}(g);var Lt={now:function(){return(Lt.delegate||Date).now()},delegate:void 0};var _t=function(e){re(t,e);function t(r,o,n){r===void 0&&(r=1/0),o===void 0&&(o=1/0),n===void 0&&(n=Lt);var i=e.call(this)||this;return i._bufferSize=r,i._windowTime=o,i._timestampProvider=n,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=o===1/0,i._bufferSize=Math.max(1,r),i._windowTime=Math.max(1,o),i}return t.prototype.next=function(r){var o=this,n=o.isStopped,i=o._buffer,a=o._infiniteTimeWindow,s=o._timestampProvider,p=o._windowTime;n||(i.push(r),!a&&i.push(s.now()+p)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var o=this._innerSubscribe(r),n=this,i=n._infiniteTimeWindow,a=n._buffer,s=a.slice(),p=0;p0?e.prototype.schedule.call(this,r,o):(this.delay=o,this.state=r,this.scheduler.flush(this),this)},t.prototype.execute=function(r,o){return o>0||this.closed?e.prototype.execute.call(this,r,o):this._execute(r,o)},t.prototype.requestAsyncId=function(r,o,n){return n===void 0&&(n=0),n!=null&&n>0||n==null&&this.delay>0?e.prototype.requestAsyncId.call(this,r,o,n):(r.flush(this),0)},t}(vt);var So=function(e){re(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(gt);var Hr=new So(To);var Oo=function(e){re(t,e);function t(r,o){var n=e.call(this,r,o)||this;return n.scheduler=r,n.work=o,n}return t.prototype.requestAsyncId=function(r,o,n){return n===void 0&&(n=0),n!==null&&n>0?e.prototype.requestAsyncId.call(this,r,o,n):(r.actions.push(this),r._scheduled||(r._scheduled=bt.requestAnimationFrame(function(){return r.flush(void 0)})))},t.prototype.recycleAsyncId=function(r,o,n){var i;if(n===void 0&&(n=0),n!=null?n>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,r,o,n);var a=r.actions;o!=null&&((i=a[a.length-1])===null||i===void 0?void 0:i.id)!==o&&(bt.cancelAnimationFrame(o),r._scheduled=void 0)},t}(vt);var Mo=function(e){re(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(r){this._active=!0;var o=this._scheduled;this._scheduled=void 0;var n=this.actions,i;r=r||n.shift();do if(i=r.execute(r.state,r.delay))break;while((r=n[0])&&r.id===o&&n.shift());if(this._active=!1,i){for(;(r=n[0])&&r.id===o&&n.shift();)r.unsubscribe();throw i}},t}(gt);var me=new Mo(Oo);var M=new F(function(e){return e.complete()});function Yt(e){return e&&k(e.schedule)}function kr(e){return e[e.length-1]}function Xe(e){return k(kr(e))?e.pop():void 0}function He(e){return Yt(kr(e))?e.pop():void 0}function Bt(e,t){return typeof kr(e)=="number"?e.pop():t}var xt=function(e){return e&&typeof e.length=="number"&&typeof e!="function"};function Gt(e){return k(e==null?void 0:e.then)}function Jt(e){return k(e[ht])}function Xt(e){return Symbol.asyncIterator&&k(e==null?void 0:e[Symbol.asyncIterator])}function Zt(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Gi(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var er=Gi();function tr(e){return k(e==null?void 0:e[er])}function rr(e){return lo(this,arguments,function(){var r,o,n,i;return Nt(this,function(a){switch(a.label){case 0:r=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,nt(r.read())];case 3:return o=a.sent(),n=o.value,i=o.done,i?[4,nt(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,nt(n)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function or(e){return k(e==null?void 0:e.getReader)}function W(e){if(e instanceof F)return e;if(e!=null){if(Jt(e))return Ji(e);if(xt(e))return Xi(e);if(Gt(e))return Zi(e);if(Xt(e))return Lo(e);if(tr(e))return ea(e);if(or(e))return ta(e)}throw Zt(e)}function Ji(e){return new F(function(t){var r=e[ht]();if(k(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Xi(e){return new F(function(t){for(var r=0;r=2;return function(o){return o.pipe(e?v(function(n,i){return e(n,i,o)}):le,Te(1),r?Be(t):zo(function(){return new ir}))}}function Fr(e){return e<=0?function(){return M}:y(function(t,r){var o=[];t.subscribe(T(r,function(n){o.push(n),e=2,!0))}function pe(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new g}:t,o=e.resetOnError,n=o===void 0?!0:o,i=e.resetOnComplete,a=i===void 0?!0:i,s=e.resetOnRefCountZero,p=s===void 0?!0:s;return function(c){var l,f,u,h=0,w=!1,A=!1,te=function(){f==null||f.unsubscribe(),f=void 0},ie=function(){te(),l=u=void 0,w=A=!1},J=function(){var H=l;ie(),H==null||H.unsubscribe()};return y(function(H,mt){h++,!A&&!w&&te();var ze=u=u!=null?u:r();mt.add(function(){h--,h===0&&!A&&!w&&(f=Wr(J,p))}),ze.subscribe(mt),!l&&h>0&&(l=new at({next:function(Ie){return ze.next(Ie)},error:function(Ie){A=!0,te(),f=Wr(ie,n,Ie),ze.error(Ie)},complete:function(){w=!0,te(),f=Wr(ie,a),ze.complete()}}),W(H).subscribe(l))})(c)}}function Wr(e,t){for(var r=[],o=2;oe.next(document)),e}function $(e,t=document){return Array.from(t.querySelectorAll(e))}function P(e,t=document){let r=fe(e,t);if(typeof r=="undefined")throw new ReferenceError(`Missing element: expected "${e}" to be present`);return r}function fe(e,t=document){return t.querySelector(e)||void 0}function Re(){var e,t,r,o;return(o=(r=(t=(e=document.activeElement)==null?void 0:e.shadowRoot)==null?void 0:t.activeElement)!=null?r:document.activeElement)!=null?o:void 0}var xa=S(d(document.body,"focusin"),d(document.body,"focusout")).pipe(_e(1),Q(void 0),m(()=>Re()||document.body),B(1));function et(e){return xa.pipe(m(t=>e.contains(t)),K())}function kt(e,t){return C(()=>S(d(e,"mouseenter").pipe(m(()=>!0)),d(e,"mouseleave").pipe(m(()=>!1))).pipe(t?Ht(r=>Me(+!r*t)):le,Q(e.matches(":hover"))))}function Bo(e,t){if(typeof t=="string"||typeof t=="number")e.innerHTML+=t.toString();else if(t instanceof Node)e.appendChild(t);else if(Array.isArray(t))for(let r of t)Bo(e,r)}function x(e,t,...r){let o=document.createElement(e);if(t)for(let n of Object.keys(t))typeof t[n]!="undefined"&&(typeof t[n]!="boolean"?o.setAttribute(n,t[n]):o.setAttribute(n,""));for(let n of r)Bo(o,n);return o}function sr(e){if(e>999){let t=+((e-950)%1e3>99);return`${((e+1e-6)/1e3).toFixed(t)}k`}else return e.toString()}function wt(e){let t=x("script",{src:e});return C(()=>(document.head.appendChild(t),S(d(t,"load"),d(t,"error").pipe(b(()=>$r(()=>new ReferenceError(`Invalid script: ${e}`))))).pipe(m(()=>{}),L(()=>document.head.removeChild(t)),Te(1))))}var Go=new g,ya=C(()=>typeof ResizeObserver=="undefined"?wt("https://unpkg.com/resize-observer-polyfill"):I(void 0)).pipe(m(()=>new ResizeObserver(e=>e.forEach(t=>Go.next(t)))),b(e=>S(Ke,I(e)).pipe(L(()=>e.disconnect()))),B(1));function ce(e){return{width:e.offsetWidth,height:e.offsetHeight}}function ge(e){let t=e;for(;t.clientWidth===0&&t.parentElement;)t=t.parentElement;return ya.pipe(E(r=>r.observe(t)),b(r=>Go.pipe(v(o=>o.target===t),L(()=>r.unobserve(t)))),m(()=>ce(e)),Q(ce(e)))}function Tt(e){return{width:e.scrollWidth,height:e.scrollHeight}}function cr(e){let t=e.parentElement;for(;t&&(e.scrollWidth<=t.scrollWidth&&e.scrollHeight<=t.scrollHeight);)t=(e=t).parentElement;return t?e:void 0}function Jo(e){let t=[],r=e.parentElement;for(;r;)(e.clientWidth>r.clientWidth||e.clientHeight>r.clientHeight)&&t.push(r),r=(e=r).parentElement;return t.length===0&&t.push(document.documentElement),t}function Ue(e){return{x:e.offsetLeft,y:e.offsetTop}}function Xo(e){let t=e.getBoundingClientRect();return{x:t.x+window.scrollX,y:t.y+window.scrollY}}function Zo(e){return S(d(window,"load"),d(window,"resize")).pipe(Le(0,me),m(()=>Ue(e)),Q(Ue(e)))}function pr(e){return{x:e.scrollLeft,y:e.scrollTop}}function De(e){return S(d(e,"scroll"),d(window,"scroll"),d(window,"resize")).pipe(Le(0,me),m(()=>pr(e)),Q(pr(e)))}var en=new g,Ea=C(()=>I(new IntersectionObserver(e=>{for(let t of e)en.next(t)},{threshold:0}))).pipe(b(e=>S(Ke,I(e)).pipe(L(()=>e.disconnect()))),B(1));function tt(e){return Ea.pipe(E(t=>t.observe(e)),b(t=>en.pipe(v(({target:r})=>r===e),L(()=>t.unobserve(e)),m(({isIntersecting:r})=>r))))}function tn(e,t=16){return De(e).pipe(m(({y:r})=>{let o=ce(e),n=Tt(e);return r>=n.height-o.height-t}),K())}var lr={drawer:P("[data-md-toggle=drawer]"),search:P("[data-md-toggle=search]")};function rn(e){return lr[e].checked}function Je(e,t){lr[e].checked!==t&&lr[e].click()}function Ve(e){let t=lr[e];return d(t,"change").pipe(m(()=>t.checked),Q(t.checked))}function wa(e,t){switch(e.constructor){case HTMLInputElement:return e.type==="radio"?/^Arrow/.test(t):!0;case HTMLSelectElement:case HTMLTextAreaElement:return!0;default:return e.isContentEditable}}function Ta(){return S(d(window,"compositionstart").pipe(m(()=>!0)),d(window,"compositionend").pipe(m(()=>!1))).pipe(Q(!1))}function on(){let e=d(window,"keydown").pipe(v(t=>!(t.metaKey||t.ctrlKey)),m(t=>({mode:rn("search")?"search":"global",type:t.key,claim(){t.preventDefault(),t.stopPropagation()}})),v(({mode:t,type:r})=>{if(t==="global"){let o=Re();if(typeof o!="undefined")return!wa(o,r)}return!0}),pe());return Ta().pipe(b(t=>t?M:e))}function xe(){return new URL(location.href)}function pt(e,t=!1){if(G("navigation.instant")&&!t){let r=x("a",{href:e.href});document.body.appendChild(r),r.click(),r.remove()}else location.href=e.href}function nn(){return new g}function an(){return location.hash.slice(1)}function sn(e){let t=x("a",{href:e});t.addEventListener("click",r=>r.stopPropagation()),t.click()}function Sa(e){return S(d(window,"hashchange"),e).pipe(m(an),Q(an()),v(t=>t.length>0),B(1))}function cn(e){return Sa(e).pipe(m(t=>fe(`[id="${t}"]`)),v(t=>typeof t!="undefined"))}function $t(e){let t=matchMedia(e);return ar(r=>t.addListener(()=>r(t.matches))).pipe(Q(t.matches))}function pn(){let e=matchMedia("print");return S(d(window,"beforeprint").pipe(m(()=>!0)),d(window,"afterprint").pipe(m(()=>!1))).pipe(Q(e.matches))}function Nr(e,t){return e.pipe(b(r=>r?t():M))}function zr(e,t){return new F(r=>{let o=new XMLHttpRequest;return o.open("GET",`${e}`),o.responseType="blob",o.addEventListener("load",()=>{o.status>=200&&o.status<300?(r.next(o.response),r.complete()):r.error(new Error(o.statusText))}),o.addEventListener("error",()=>{r.error(new Error("Network error"))}),o.addEventListener("abort",()=>{r.complete()}),typeof(t==null?void 0:t.progress$)!="undefined"&&(o.addEventListener("progress",n=>{var i;if(n.lengthComputable)t.progress$.next(n.loaded/n.total*100);else{let a=(i=o.getResponseHeader("Content-Length"))!=null?i:0;t.progress$.next(n.loaded/+a*100)}}),t.progress$.next(5)),o.send(),()=>o.abort()})}function Ne(e,t){return zr(e,t).pipe(b(r=>r.text()),m(r=>JSON.parse(r)),B(1))}function ln(e,t){let r=new DOMParser;return zr(e,t).pipe(b(o=>o.text()),m(o=>r.parseFromString(o,"text/html")),B(1))}function mn(e,t){let r=new DOMParser;return zr(e,t).pipe(b(o=>o.text()),m(o=>r.parseFromString(o,"text/xml")),B(1))}function fn(){return{x:Math.max(0,scrollX),y:Math.max(0,scrollY)}}function un(){return S(d(window,"scroll",{passive:!0}),d(window,"resize",{passive:!0})).pipe(m(fn),Q(fn()))}function dn(){return{width:innerWidth,height:innerHeight}}function hn(){return d(window,"resize",{passive:!0}).pipe(m(dn),Q(dn()))}function bn(){return z([un(),hn()]).pipe(m(([e,t])=>({offset:e,size:t})),B(1))}function mr(e,{viewport$:t,header$:r}){let o=t.pipe(Z("size")),n=z([o,r]).pipe(m(()=>Ue(e)));return z([r,t,n]).pipe(m(([{height:i},{offset:a,size:s},{x:p,y:c}])=>({offset:{x:a.x-p,y:a.y-c+i},size:s})))}function Oa(e){return d(e,"message",t=>t.data)}function Ma(e){let t=new g;return t.subscribe(r=>e.postMessage(r)),t}function vn(e,t=new Worker(e)){let r=Oa(t),o=Ma(t),n=new g;n.subscribe(o);let i=o.pipe(X(),ne(!0));return n.pipe(X(),Pe(r.pipe(U(i))),pe())}var La=P("#__config"),St=JSON.parse(La.textContent);St.base=`${new URL(St.base,xe())}`;function ye(){return St}function G(e){return St.features.includes(e)}function Ee(e,t){return typeof t!="undefined"?St.translations[e].replace("#",t.toString()):St.translations[e]}function Se(e,t=document){return P(`[data-md-component=${e}]`,t)}function ae(e,t=document){return $(`[data-md-component=${e}]`,t)}function _a(e){let t=P(".md-typeset > :first-child",e);return d(t,"click",{once:!0}).pipe(m(()=>P(".md-typeset",e)),m(r=>({hash:__md_hash(r.innerHTML)})))}function gn(e){if(!G("announce.dismiss")||!e.childElementCount)return M;if(!e.hidden){let t=P(".md-typeset",e);__md_hash(t.innerHTML)===__md_get("__announce")&&(e.hidden=!0)}return C(()=>{let t=new g;return t.subscribe(({hash:r})=>{e.hidden=!0,__md_set("__announce",r)}),_a(e).pipe(E(r=>t.next(r)),L(()=>t.complete()),m(r=>R({ref:e},r)))})}function Aa(e,{target$:t}){return t.pipe(m(r=>({hidden:r!==e})))}function xn(e,t){let r=new g;return r.subscribe(({hidden:o})=>{e.hidden=o}),Aa(e,t).pipe(E(o=>r.next(o)),L(()=>r.complete()),m(o=>R({ref:e},o)))}function Pt(e,t){return t==="inline"?x("div",{class:"md-tooltip md-tooltip--inline",id:e,role:"tooltip"},x("div",{class:"md-tooltip__inner md-typeset"})):x("div",{class:"md-tooltip",id:e,role:"tooltip"},x("div",{class:"md-tooltip__inner md-typeset"}))}function yn(...e){return x("div",{class:"md-tooltip2",role:"tooltip"},x("div",{class:"md-tooltip2__inner md-typeset"},e))}function En(e,t){if(t=t?`${t}_annotation_${e}`:void 0,t){let r=t?`#${t}`:void 0;return x("aside",{class:"md-annotation",tabIndex:0},Pt(t),x("a",{href:r,class:"md-annotation__index",tabIndex:-1},x("span",{"data-md-annotation-id":e})))}else return x("aside",{class:"md-annotation",tabIndex:0},Pt(t),x("span",{class:"md-annotation__index",tabIndex:-1},x("span",{"data-md-annotation-id":e})))}function wn(e){return x("button",{class:"md-clipboard md-icon",title:Ee("clipboard.copy"),"data-clipboard-target":`#${e} > code`})}function qr(e,t){let r=t&2,o=t&1,n=Object.keys(e.terms).filter(p=>!e.terms[p]).reduce((p,c)=>[...p,x("del",null,c)," "],[]).slice(0,-1),i=ye(),a=new URL(e.location,i.base);G("search.highlight")&&a.searchParams.set("h",Object.entries(e.terms).filter(([,p])=>p).reduce((p,[c])=>`${p} ${c}`.trim(),""));let{tags:s}=ye();return x("a",{href:`${a}`,class:"md-search-result__link",tabIndex:-1},x("article",{class:"md-search-result__article md-typeset","data-md-score":e.score.toFixed(2)},r>0&&x("div",{class:"md-search-result__icon md-icon"}),r>0&&x("h1",null,e.title),r<=0&&x("h2",null,e.title),o>0&&e.text.length>0&&e.text,e.tags&&e.tags.map(p=>{let c=s?p in s?`md-tag-icon md-tag--${s[p]}`:"md-tag-icon":"";return x("span",{class:`md-tag ${c}`},p)}),o>0&&n.length>0&&x("p",{class:"md-search-result__terms"},Ee("search.result.term.missing"),": ",...n)))}function Tn(e){let t=e[0].score,r=[...e],o=ye(),n=r.findIndex(l=>!`${new URL(l.location,o.base)}`.includes("#")),[i]=r.splice(n,1),a=r.findIndex(l=>l.scoreqr(l,1)),...p.length?[x("details",{class:"md-search-result__more"},x("summary",{tabIndex:-1},x("div",null,p.length>0&&p.length===1?Ee("search.result.more.one"):Ee("search.result.more.other",p.length))),...p.map(l=>qr(l,1)))]:[]];return x("li",{class:"md-search-result__item"},c)}function Sn(e){return x("ul",{class:"md-source__facts"},Object.entries(e).map(([t,r])=>x("li",{class:`md-source__fact md-source__fact--${t}`},typeof r=="number"?sr(r):r)))}function Qr(e){let t=`tabbed-control tabbed-control--${e}`;return x("div",{class:t,hidden:!0},x("button",{class:"tabbed-button",tabIndex:-1,"aria-hidden":"true"}))}function On(e){return x("div",{class:"md-typeset__scrollwrap"},x("div",{class:"md-typeset__table"},e))}function Ca(e){var o;let t=ye(),r=new URL(`../${e.version}/`,t.base);return x("li",{class:"md-version__item"},x("a",{href:`${r}`,class:"md-version__link"},e.title,((o=t.version)==null?void 0:o.alias)&&e.aliases.length>0&&x("span",{class:"md-version__alias"},e.aliases[0])))}function Mn(e,t){var o;let r=ye();return e=e.filter(n=>{var i;return!((i=n.properties)!=null&&i.hidden)}),x("div",{class:"md-version"},x("button",{class:"md-version__current","aria-label":Ee("select.version")},t.title,((o=r.version)==null?void 0:o.alias)&&t.aliases.length>0&&x("span",{class:"md-version__alias"},t.aliases[0])),x("ul",{class:"md-version__list"},e.map(Ca)))}var Ha=0;function ka(e){let t=z([et(e),kt(e)]).pipe(m(([o,n])=>o||n),K()),r=C(()=>Jo(e)).pipe(oe(De),ct(1),m(()=>Xo(e)));return t.pipe(Ae(o=>o),b(()=>z([t,r])),m(([o,n])=>({active:o,offset:n})),pe())}function $a(e,t){let{content$:r,viewport$:o}=t,n=`__tooltip2_${Ha++}`;return C(()=>{let i=new g,a=new _r(!1);i.pipe(X(),ne(!1)).subscribe(a);let s=a.pipe(Ht(c=>Me(+!c*250,Hr)),K(),b(c=>c?r:M),E(c=>c.id=n),pe());z([i.pipe(m(({active:c})=>c)),s.pipe(b(c=>kt(c,250)),Q(!1))]).pipe(m(c=>c.some(l=>l))).subscribe(a);let p=a.pipe(v(c=>c),ee(s,o),m(([c,l,{size:f}])=>{let u=e.getBoundingClientRect(),h=u.width/2;if(l.role==="tooltip")return{x:h,y:8+u.height};if(u.y>=f.height/2){let{height:w}=ce(l);return{x:h,y:-16-w}}else return{x:h,y:16+u.height}}));return z([s,i,p]).subscribe(([c,{offset:l},f])=>{c.style.setProperty("--md-tooltip-host-x",`${l.x}px`),c.style.setProperty("--md-tooltip-host-y",`${l.y}px`),c.style.setProperty("--md-tooltip-x",`${f.x}px`),c.style.setProperty("--md-tooltip-y",`${f.y}px`),c.classList.toggle("md-tooltip2--top",f.y<0),c.classList.toggle("md-tooltip2--bottom",f.y>=0)}),a.pipe(v(c=>c),ee(s,(c,l)=>l),v(c=>c.role==="tooltip")).subscribe(c=>{let l=ce(P(":scope > *",c));c.style.setProperty("--md-tooltip-width",`${l.width}px`),c.style.setProperty("--md-tooltip-tail","0px")}),a.pipe(K(),be(me),ee(s)).subscribe(([c,l])=>{l.classList.toggle("md-tooltip2--active",c)}),z([a.pipe(v(c=>c)),s]).subscribe(([c,l])=>{l.role==="dialog"?(e.setAttribute("aria-controls",n),e.setAttribute("aria-haspopup","dialog")):e.setAttribute("aria-describedby",n)}),a.pipe(v(c=>!c)).subscribe(()=>{e.removeAttribute("aria-controls"),e.removeAttribute("aria-describedby"),e.removeAttribute("aria-haspopup")}),ka(e).pipe(E(c=>i.next(c)),L(()=>i.complete()),m(c=>R({ref:e},c)))})}function lt(e,{viewport$:t},r=document.body){return $a(e,{content$:new F(o=>{let n=e.title,i=yn(n);return o.next(i),e.removeAttribute("title"),r.append(i),()=>{i.remove(),e.setAttribute("title",n)}}),viewport$:t})}function Pa(e,t){let r=C(()=>z([Zo(e),De(t)])).pipe(m(([{x:o,y:n},i])=>{let{width:a,height:s}=ce(e);return{x:o-i.x+a/2,y:n-i.y+s/2}}));return et(e).pipe(b(o=>r.pipe(m(n=>({active:o,offset:n})),Te(+!o||1/0))))}function Ln(e,t,{target$:r}){let[o,n]=Array.from(e.children);return C(()=>{let i=new g,a=i.pipe(X(),ne(!0));return i.subscribe({next({offset:s}){e.style.setProperty("--md-tooltip-x",`${s.x}px`),e.style.setProperty("--md-tooltip-y",`${s.y}px`)},complete(){e.style.removeProperty("--md-tooltip-x"),e.style.removeProperty("--md-tooltip-y")}}),tt(e).pipe(U(a)).subscribe(s=>{e.toggleAttribute("data-md-visible",s)}),S(i.pipe(v(({active:s})=>s)),i.pipe(_e(250),v(({active:s})=>!s))).subscribe({next({active:s}){s?e.prepend(o):o.remove()},complete(){e.prepend(o)}}),i.pipe(Le(16,me)).subscribe(({active:s})=>{o.classList.toggle("md-tooltip--active",s)}),i.pipe(ct(125,me),v(()=>!!e.offsetParent),m(()=>e.offsetParent.getBoundingClientRect()),m(({x:s})=>s)).subscribe({next(s){s?e.style.setProperty("--md-tooltip-0",`${-s}px`):e.style.removeProperty("--md-tooltip-0")},complete(){e.style.removeProperty("--md-tooltip-0")}}),d(n,"click").pipe(U(a),v(s=>!(s.metaKey||s.ctrlKey))).subscribe(s=>{s.stopPropagation(),s.preventDefault()}),d(n,"mousedown").pipe(U(a),ee(i)).subscribe(([s,{active:p}])=>{var c;if(s.button!==0||s.metaKey||s.ctrlKey)s.preventDefault();else if(p){s.preventDefault();let l=e.parentElement.closest(".md-annotation");l instanceof HTMLElement?l.focus():(c=Re())==null||c.blur()}}),r.pipe(U(a),v(s=>s===o),Ge(125)).subscribe(()=>e.focus()),Pa(e,t).pipe(E(s=>i.next(s)),L(()=>i.complete()),m(s=>R({ref:e},s)))})}function Ra(e){return e.tagName==="CODE"?$(".c, .c1, .cm",e):[e]}function Ia(e){let t=[];for(let r of Ra(e)){let o=[],n=document.createNodeIterator(r,NodeFilter.SHOW_TEXT);for(let i=n.nextNode();i;i=n.nextNode())o.push(i);for(let i of o){let a;for(;a=/(\(\d+\))(!)?/.exec(i.textContent);){let[,s,p]=a;if(typeof p=="undefined"){let c=i.splitText(a.index);i=c.splitText(s.length),t.push(c)}else{i.textContent=s,t.push(i);break}}}}return t}function _n(e,t){t.append(...Array.from(e.childNodes))}function fr(e,t,{target$:r,print$:o}){let n=t.closest("[id]"),i=n==null?void 0:n.id,a=new Map;for(let s of Ia(t)){let[,p]=s.textContent.match(/\((\d+)\)/);fe(`:scope > li:nth-child(${p})`,e)&&(a.set(p,En(p,i)),s.replaceWith(a.get(p)))}return a.size===0?M:C(()=>{let s=new g,p=s.pipe(X(),ne(!0)),c=[];for(let[l,f]of a)c.push([P(".md-typeset",f),P(`:scope > li:nth-child(${l})`,e)]);return o.pipe(U(p)).subscribe(l=>{e.hidden=!l,e.classList.toggle("md-annotation-list",l);for(let[f,u]of c)l?_n(f,u):_n(u,f)}),S(...[...a].map(([,l])=>Ln(l,t,{target$:r}))).pipe(L(()=>s.complete()),pe())})}function An(e){if(e.nextElementSibling){let t=e.nextElementSibling;if(t.tagName==="OL")return t;if(t.tagName==="P"&&!t.children.length)return An(t)}}function Cn(e,t){return C(()=>{let r=An(e);return typeof r!="undefined"?fr(r,e,t):M})}var Hn=Vt(Yr());var Fa=0;function kn(e){if(e.nextElementSibling){let t=e.nextElementSibling;if(t.tagName==="OL")return t;if(t.tagName==="P"&&!t.children.length)return kn(t)}}function ja(e){return ge(e).pipe(m(({width:t})=>({scrollable:Tt(e).width>t})),Z("scrollable"))}function $n(e,t){let{matches:r}=matchMedia("(hover)"),o=C(()=>{let n=new g,i=n.pipe(Fr(1));n.subscribe(({scrollable:c})=>{c&&r?e.setAttribute("tabindex","0"):e.removeAttribute("tabindex")});let a=[];if(Hn.default.isSupported()&&(e.closest(".copy")||G("content.code.copy")&&!e.closest(".no-copy"))){let c=e.closest("pre");c.id=`__code_${Fa++}`;let l=wn(c.id);c.insertBefore(l,e),G("content.tooltips")&&a.push(lt(l,{viewport$}))}let s=e.closest(".highlight");if(s instanceof HTMLElement){let c=kn(s);if(typeof c!="undefined"&&(s.classList.contains("annotate")||G("content.code.annotate"))){let l=fr(c,e,t);a.push(ge(s).pipe(U(i),m(({width:f,height:u})=>f&&u),K(),b(f=>f?l:M)))}}return $(":scope > span[id]",e).length&&e.classList.add("md-code__content"),ja(e).pipe(E(c=>n.next(c)),L(()=>n.complete()),m(c=>R({ref:e},c)),Pe(...a))});return G("content.lazy")?tt(e).pipe(v(n=>n),Te(1),b(()=>o)):o}function Wa(e,{target$:t,print$:r}){let o=!0;return S(t.pipe(m(n=>n.closest("details:not([open])")),v(n=>e===n),m(()=>({action:"open",reveal:!0}))),r.pipe(v(n=>n||!o),E(()=>o=e.open),m(n=>({action:n?"open":"close"}))))}function Pn(e,t){return C(()=>{let r=new g;return r.subscribe(({action:o,reveal:n})=>{e.toggleAttribute("open",o==="open"),n&&e.scrollIntoView()}),Wa(e,t).pipe(E(o=>r.next(o)),L(()=>r.complete()),m(o=>R({ref:e},o)))})}var Rn=".node circle,.node ellipse,.node path,.node polygon,.node rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}marker{fill:var(--md-mermaid-edge-color)!important}.edgeLabel .label rect{fill:#0000}.label{color:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}.label foreignObject{line-height:normal;overflow:visible}.label div .edgeLabel{color:var(--md-mermaid-label-fg-color)}.edgeLabel,.edgeLabel rect,.label div .edgeLabel{background-color:var(--md-mermaid-label-bg-color)}.edgeLabel,.edgeLabel rect{fill:var(--md-mermaid-label-bg-color);color:var(--md-mermaid-edge-color)}.edgePath .path,.flowchart-link{stroke:var(--md-mermaid-edge-color);stroke-width:.05rem}.edgePath .arrowheadPath{fill:var(--md-mermaid-edge-color);stroke:none}.cluster rect{fill:var(--md-default-fg-color--lightest);stroke:var(--md-default-fg-color--lighter)}.cluster span{color:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}g #flowchart-circleEnd,g #flowchart-circleStart,g #flowchart-crossEnd,g #flowchart-crossStart,g #flowchart-pointEnd,g #flowchart-pointStart{stroke:none}g.classGroup line,g.classGroup rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}g.classGroup text{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}.classLabel .box{fill:var(--md-mermaid-label-bg-color);background-color:var(--md-mermaid-label-bg-color);opacity:1}.classLabel .label{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}.node .divider{stroke:var(--md-mermaid-node-fg-color)}.relation{stroke:var(--md-mermaid-edge-color)}.cardinality{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}.cardinality text{fill:inherit!important}defs #classDiagram-compositionEnd,defs #classDiagram-compositionStart,defs #classDiagram-dependencyEnd,defs #classDiagram-dependencyStart,defs #classDiagram-extensionEnd,defs #classDiagram-extensionStart{fill:var(--md-mermaid-edge-color)!important;stroke:var(--md-mermaid-edge-color)!important}defs #classDiagram-aggregationEnd,defs #classDiagram-aggregationStart{fill:var(--md-mermaid-label-bg-color)!important;stroke:var(--md-mermaid-edge-color)!important}g.stateGroup rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}g.stateGroup .state-title{fill:var(--md-mermaid-label-fg-color)!important;font-family:var(--md-mermaid-font-family)}g.stateGroup .composit{fill:var(--md-mermaid-label-bg-color)}.nodeLabel,.nodeLabel p{color:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}a .nodeLabel{text-decoration:underline}.node circle.state-end,.node circle.state-start,.start-state{fill:var(--md-mermaid-edge-color);stroke:none}.end-state-inner,.end-state-outer{fill:var(--md-mermaid-edge-color)}.end-state-inner,.node circle.state-end{stroke:var(--md-mermaid-label-bg-color)}.transition{stroke:var(--md-mermaid-edge-color)}[id^=state-fork] rect,[id^=state-join] rect{fill:var(--md-mermaid-edge-color)!important;stroke:none!important}.statediagram-cluster.statediagram-cluster .inner{fill:var(--md-default-bg-color)}.statediagram-cluster rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}.statediagram-state rect.divider{fill:var(--md-default-fg-color--lightest);stroke:var(--md-default-fg-color--lighter)}defs #statediagram-barbEnd{stroke:var(--md-mermaid-edge-color)}.attributeBoxEven,.attributeBoxOdd{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}.entityBox{fill:var(--md-mermaid-label-bg-color);stroke:var(--md-mermaid-node-fg-color)}.entityLabel{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}.relationshipLabelBox{fill:var(--md-mermaid-label-bg-color);fill-opacity:1;background-color:var(--md-mermaid-label-bg-color);opacity:1}.relationshipLabel{fill:var(--md-mermaid-label-fg-color)}.relationshipLine{stroke:var(--md-mermaid-edge-color)}defs #ONE_OR_MORE_END *,defs #ONE_OR_MORE_START *,defs #ONLY_ONE_END *,defs #ONLY_ONE_START *,defs #ZERO_OR_MORE_END *,defs #ZERO_OR_MORE_START *,defs #ZERO_OR_ONE_END *,defs #ZERO_OR_ONE_START *{stroke:var(--md-mermaid-edge-color)!important}defs #ZERO_OR_MORE_END circle,defs #ZERO_OR_MORE_START circle{fill:var(--md-mermaid-label-bg-color)}.actor{fill:var(--md-mermaid-sequence-actor-bg-color);stroke:var(--md-mermaid-sequence-actor-border-color)}text.actor>tspan{fill:var(--md-mermaid-sequence-actor-fg-color);font-family:var(--md-mermaid-font-family)}line{stroke:var(--md-mermaid-sequence-actor-line-color)}.actor-man circle,.actor-man line{fill:var(--md-mermaid-sequence-actorman-bg-color);stroke:var(--md-mermaid-sequence-actorman-line-color)}.messageLine0,.messageLine1{stroke:var(--md-mermaid-sequence-message-line-color)}.note{fill:var(--md-mermaid-sequence-note-bg-color);stroke:var(--md-mermaid-sequence-note-border-color)}.loopText,.loopText>tspan,.messageText,.noteText>tspan{stroke:none;font-family:var(--md-mermaid-font-family)!important}.messageText{fill:var(--md-mermaid-sequence-message-fg-color)}.loopText,.loopText>tspan{fill:var(--md-mermaid-sequence-loop-fg-color)}.noteText>tspan{fill:var(--md-mermaid-sequence-note-fg-color)}#arrowhead path{fill:var(--md-mermaid-sequence-message-line-color);stroke:none}.loopLine{fill:var(--md-mermaid-sequence-loop-bg-color);stroke:var(--md-mermaid-sequence-loop-border-color)}.labelBox{fill:var(--md-mermaid-sequence-label-bg-color);stroke:none}.labelText,.labelText>span{fill:var(--md-mermaid-sequence-label-fg-color);font-family:var(--md-mermaid-font-family)}.sequenceNumber{fill:var(--md-mermaid-sequence-number-fg-color)}rect.rect{fill:var(--md-mermaid-sequence-box-bg-color);stroke:none}rect.rect+text.text{fill:var(--md-mermaid-sequence-box-fg-color)}defs #sequencenumber{fill:var(--md-mermaid-sequence-number-bg-color)!important}";var Br,Da=0;function Va(){return typeof mermaid=="undefined"||mermaid instanceof Element?wt("https://unpkg.com/mermaid@10/dist/mermaid.min.js"):I(void 0)}function In(e){return e.classList.remove("mermaid"),Br||(Br=Va().pipe(E(()=>mermaid.initialize({startOnLoad:!1,themeCSS:Rn,sequence:{actorFontSize:"16px",messageFontSize:"16px",noteFontSize:"16px"}})),m(()=>{}),B(1))),Br.subscribe(()=>ao(this,null,function*(){e.classList.add("mermaid");let t=`__mermaid_${Da++}`,r=x("div",{class:"mermaid"}),o=e.textContent,{svg:n,fn:i}=yield mermaid.render(t,o),a=r.attachShadow({mode:"closed"});a.innerHTML=n,e.replaceWith(r),i==null||i(a)})),Br.pipe(m(()=>({ref:e})))}var Fn=x("table");function jn(e){return e.replaceWith(Fn),Fn.replaceWith(On(e)),I({ref:e})}function Na(e){let t=e.find(r=>r.checked)||e[0];return S(...e.map(r=>d(r,"change").pipe(m(()=>P(`label[for="${r.id}"]`))))).pipe(Q(P(`label[for="${t.id}"]`)),m(r=>({active:r})))}function Wn(e,{viewport$:t,target$:r}){let o=P(".tabbed-labels",e),n=$(":scope > input",e),i=Qr("prev");e.append(i);let a=Qr("next");return e.append(a),C(()=>{let s=new g,p=s.pipe(X(),ne(!0));z([s,ge(e)]).pipe(U(p),Le(1,me)).subscribe({next([{active:c},l]){let f=Ue(c),{width:u}=ce(c);e.style.setProperty("--md-indicator-x",`${f.x}px`),e.style.setProperty("--md-indicator-width",`${u}px`);let h=pr(o);(f.xh.x+l.width)&&o.scrollTo({left:Math.max(0,f.x-16),behavior:"smooth"})},complete(){e.style.removeProperty("--md-indicator-x"),e.style.removeProperty("--md-indicator-width")}}),z([De(o),ge(o)]).pipe(U(p)).subscribe(([c,l])=>{let f=Tt(o);i.hidden=c.x<16,a.hidden=c.x>f.width-l.width-16}),S(d(i,"click").pipe(m(()=>-1)),d(a,"click").pipe(m(()=>1))).pipe(U(p)).subscribe(c=>{let{width:l}=ce(o);o.scrollBy({left:l*c,behavior:"smooth"})}),r.pipe(U(p),v(c=>n.includes(c))).subscribe(c=>c.click()),o.classList.add("tabbed-labels--linked");for(let c of n){let l=P(`label[for="${c.id}"]`);l.replaceChildren(x("a",{href:`#${l.htmlFor}`,tabIndex:-1},...Array.from(l.childNodes))),d(l.firstElementChild,"click").pipe(U(p),v(f=>!(f.metaKey||f.ctrlKey)),E(f=>{f.preventDefault(),f.stopPropagation()})).subscribe(()=>{history.replaceState({},"",`#${l.htmlFor}`),l.click()})}return G("content.tabs.link")&&s.pipe(Ce(1),ee(t)).subscribe(([{active:c},{offset:l}])=>{let f=c.innerText.trim();if(c.hasAttribute("data-md-switching"))c.removeAttribute("data-md-switching");else{let u=e.offsetTop-l.y;for(let w of $("[data-tabs]"))for(let A of $(":scope > input",w)){let te=P(`label[for="${A.id}"]`);if(te!==c&&te.innerText.trim()===f){te.setAttribute("data-md-switching",""),A.click();break}}window.scrollTo({top:e.offsetTop-u});let h=__md_get("__tabs")||[];__md_set("__tabs",[...new Set([f,...h])])}}),s.pipe(U(p)).subscribe(()=>{for(let c of $("audio, video",e))c.pause()}),tt(e).pipe(b(()=>Na(n)),E(c=>s.next(c)),L(()=>s.complete()),m(c=>R({ref:e},c)))}).pipe(Qe(se))}function Un(e,{viewport$:t,target$:r,print$:o}){return S(...$(".annotate:not(.highlight)",e).map(n=>Cn(n,{target$:r,print$:o})),...$("pre:not(.mermaid) > code",e).map(n=>$n(n,{target$:r,print$:o})),...$("pre.mermaid",e).map(n=>In(n)),...$("table:not([class])",e).map(n=>jn(n)),...$("details",e).map(n=>Pn(n,{target$:r,print$:o})),...$("[data-tabs]",e).map(n=>Wn(n,{viewport$:t,target$:r})),...$("[title]",e).filter(()=>G("content.tooltips")).map(n=>lt(n,{viewport$:t})))}function za(e,{alert$:t}){return t.pipe(b(r=>S(I(!0),I(!1).pipe(Ge(2e3))).pipe(m(o=>({message:r,active:o})))))}function Dn(e,t){let r=P(".md-typeset",e);return C(()=>{let o=new g;return o.subscribe(({message:n,active:i})=>{e.classList.toggle("md-dialog--active",i),r.textContent=n}),za(e,t).pipe(E(n=>o.next(n)),L(()=>o.complete()),m(n=>R({ref:e},n)))})}var qa=0;function Qa(e,t){document.body.append(e);let{width:r}=ce(e);e.style.setProperty("--md-tooltip-width",`${r}px`),e.remove();let o=cr(t),n=typeof o!="undefined"?De(o):I({x:0,y:0}),i=S(et(t),kt(t)).pipe(K());return z([i,n]).pipe(m(([a,s])=>{let{x:p,y:c}=Ue(t),l=ce(t),f=t.closest("table");return f&&t.parentElement&&(p+=f.offsetLeft+t.parentElement.offsetLeft,c+=f.offsetTop+t.parentElement.offsetTop),{active:a,offset:{x:p-s.x+l.width/2-r/2,y:c-s.y+l.height+8}}}))}function Vn(e){let t=e.title;if(!t.length)return M;let r=`__tooltip_${qa++}`,o=Pt(r,"inline"),n=P(".md-typeset",o);return n.innerHTML=t,C(()=>{let i=new g;return i.subscribe({next({offset:a}){o.style.setProperty("--md-tooltip-x",`${a.x}px`),o.style.setProperty("--md-tooltip-y",`${a.y}px`)},complete(){o.style.removeProperty("--md-tooltip-x"),o.style.removeProperty("--md-tooltip-y")}}),S(i.pipe(v(({active:a})=>a)),i.pipe(_e(250),v(({active:a})=>!a))).subscribe({next({active:a}){a?(e.insertAdjacentElement("afterend",o),e.setAttribute("aria-describedby",r),e.removeAttribute("title")):(o.remove(),e.removeAttribute("aria-describedby"),e.setAttribute("title",t))},complete(){o.remove(),e.removeAttribute("aria-describedby"),e.setAttribute("title",t)}}),i.pipe(Le(16,me)).subscribe(({active:a})=>{o.classList.toggle("md-tooltip--active",a)}),i.pipe(ct(125,me),v(()=>!!e.offsetParent),m(()=>e.offsetParent.getBoundingClientRect()),m(({x:a})=>a)).subscribe({next(a){a?o.style.setProperty("--md-tooltip-0",`${-a}px`):o.style.removeProperty("--md-tooltip-0")},complete(){o.style.removeProperty("--md-tooltip-0")}}),Qa(o,e).pipe(E(a=>i.next(a)),L(()=>i.complete()),m(a=>R({ref:e},a)))}).pipe(Qe(se))}function Ka({viewport$:e}){if(!G("header.autohide"))return I(!1);let t=e.pipe(m(({offset:{y:n}})=>n),Ye(2,1),m(([n,i])=>[nMath.abs(i-n.y)>100),m(([,[n]])=>n),K()),o=Ve("search");return z([e,o]).pipe(m(([{offset:n},i])=>n.y>400&&!i),K(),b(n=>n?r:I(!1)),Q(!1))}function Nn(e,t){return C(()=>z([ge(e),Ka(t)])).pipe(m(([{height:r},o])=>({height:r,hidden:o})),K((r,o)=>r.height===o.height&&r.hidden===o.hidden),B(1))}function zn(e,{header$:t,main$:r}){return C(()=>{let o=new g,n=o.pipe(X(),ne(!0));o.pipe(Z("active"),We(t)).subscribe(([{active:a},{hidden:s}])=>{e.classList.toggle("md-header--shadow",a&&!s),e.hidden=s});let i=ue($("[title]",e)).pipe(v(()=>G("content.tooltips")),oe(a=>Vn(a)));return r.subscribe(o),t.pipe(U(n),m(a=>R({ref:e},a)),Pe(i.pipe(U(n))))})}function Ya(e,{viewport$:t,header$:r}){return mr(e,{viewport$:t,header$:r}).pipe(m(({offset:{y:o}})=>{let{height:n}=ce(e);return{active:o>=n}}),Z("active"))}function qn(e,t){return C(()=>{let r=new g;r.subscribe({next({active:n}){e.classList.toggle("md-header__title--active",n)},complete(){e.classList.remove("md-header__title--active")}});let o=fe(".md-content h1");return typeof o=="undefined"?M:Ya(o,t).pipe(E(n=>r.next(n)),L(()=>r.complete()),m(n=>R({ref:e},n)))})}function Qn(e,{viewport$:t,header$:r}){let o=r.pipe(m(({height:i})=>i),K()),n=o.pipe(b(()=>ge(e).pipe(m(({height:i})=>({top:e.offsetTop,bottom:e.offsetTop+i})),Z("bottom"))));return z([o,n,t]).pipe(m(([i,{top:a,bottom:s},{offset:{y:p},size:{height:c}}])=>(c=Math.max(0,c-Math.max(0,a-p,i)-Math.max(0,c+p-s)),{offset:a-i,height:c,active:a-i<=p})),K((i,a)=>i.offset===a.offset&&i.height===a.height&&i.active===a.active))}function Ba(e){let t=__md_get("__palette")||{index:e.findIndex(o=>matchMedia(o.getAttribute("data-md-color-media")).matches)},r=Math.max(0,Math.min(t.index,e.length-1));return I(...e).pipe(oe(o=>d(o,"change").pipe(m(()=>o))),Q(e[r]),m(o=>({index:e.indexOf(o),color:{media:o.getAttribute("data-md-color-media"),scheme:o.getAttribute("data-md-color-scheme"),primary:o.getAttribute("data-md-color-primary"),accent:o.getAttribute("data-md-color-accent")}})),B(1))}function Kn(e){let t=$("input",e),r=x("meta",{name:"theme-color"});document.head.appendChild(r);let o=x("meta",{name:"color-scheme"});document.head.appendChild(o);let n=$t("(prefers-color-scheme: light)");return C(()=>{let i=new g;return i.subscribe(a=>{if(document.body.setAttribute("data-md-color-switching",""),a.color.media==="(prefers-color-scheme)"){let s=matchMedia("(prefers-color-scheme: light)"),p=document.querySelector(s.matches?"[data-md-color-media='(prefers-color-scheme: light)']":"[data-md-color-media='(prefers-color-scheme: dark)']");a.color.scheme=p.getAttribute("data-md-color-scheme"),a.color.primary=p.getAttribute("data-md-color-primary"),a.color.accent=p.getAttribute("data-md-color-accent")}for(let[s,p]of Object.entries(a.color))document.body.setAttribute(`data-md-color-${s}`,p);for(let s=0;sa.key==="Enter"),ee(i,(a,s)=>s)).subscribe(({index:a})=>{a=(a+1)%t.length,t[a].click(),t[a].focus()}),i.pipe(m(()=>{let a=Se("header"),s=window.getComputedStyle(a);return o.content=s.colorScheme,s.backgroundColor.match(/\d+/g).map(p=>(+p).toString(16).padStart(2,"0")).join("")})).subscribe(a=>r.content=`#${a}`),i.pipe(be(se)).subscribe(()=>{document.body.removeAttribute("data-md-color-switching")}),Ba(t).pipe(U(n.pipe(Ce(1))),st(),E(a=>i.next(a)),L(()=>i.complete()),m(a=>R({ref:e},a)))})}function Yn(e,{progress$:t}){return C(()=>{let r=new g;return r.subscribe(({value:o})=>{e.style.setProperty("--md-progress-value",`${o}`)}),t.pipe(E(o=>r.next({value:o})),L(()=>r.complete()),m(o=>({ref:e,value:o})))})}var Gr=Vt(Yr());function Ga(e){e.setAttribute("data-md-copying","");let t=e.closest("[data-copy]"),r=t?t.getAttribute("data-copy"):e.innerText;return e.removeAttribute("data-md-copying"),r.trimEnd()}function Bn({alert$:e}){Gr.default.isSupported()&&new F(t=>{new Gr.default("[data-clipboard-target], [data-clipboard-text]",{text:r=>r.getAttribute("data-clipboard-text")||Ga(P(r.getAttribute("data-clipboard-target")))}).on("success",r=>t.next(r))}).pipe(E(t=>{t.trigger.focus()}),m(()=>Ee("clipboard.copied"))).subscribe(e)}function Gn(e,t){return e.protocol=t.protocol,e.hostname=t.hostname,e}function Ja(e,t){let r=new Map;for(let o of $("url",e)){let n=P("loc",o),i=[Gn(new URL(n.textContent),t)];r.set(`${i[0]}`,i);for(let a of $("[rel=alternate]",o)){let s=a.getAttribute("href");s!=null&&i.push(Gn(new URL(s),t))}}return r}function ur(e){return mn(new URL("sitemap.xml",e)).pipe(m(t=>Ja(t,new URL(e))),ve(()=>I(new Map)))}function Xa(e,t){if(!(e.target instanceof Element))return M;let r=e.target.closest("a");if(r===null)return M;if(r.target||e.metaKey||e.ctrlKey)return M;let o=new URL(r.href);return o.search=o.hash="",t.has(`${o}`)?(e.preventDefault(),I(new URL(r.href))):M}function Jn(e){let t=new Map;for(let r of $(":scope > *",e.head))t.set(r.outerHTML,r);return t}function Xn(e){for(let t of $("[href], [src]",e))for(let r of["href","src"]){let o=t.getAttribute(r);if(o&&!/^(?:[a-z]+:)?\/\//i.test(o)){t[r]=t[r];break}}return I(e)}function Za(e){for(let o of["[data-md-component=announce]","[data-md-component=container]","[data-md-component=header-topic]","[data-md-component=outdated]","[data-md-component=logo]","[data-md-component=skip]",...G("navigation.tabs.sticky")?["[data-md-component=tabs]"]:[]]){let n=fe(o),i=fe(o,e);typeof n!="undefined"&&typeof i!="undefined"&&n.replaceWith(i)}let t=Jn(document);for(let[o,n]of Jn(e))t.has(o)?t.delete(o):document.head.appendChild(n);for(let o of t.values()){let n=o.getAttribute("name");n!=="theme-color"&&n!=="color-scheme"&&o.remove()}let r=Se("container");return je($("script",r)).pipe(b(o=>{let n=e.createElement("script");if(o.src){for(let i of o.getAttributeNames())n.setAttribute(i,o.getAttribute(i));return o.replaceWith(n),new F(i=>{n.onload=()=>i.complete()})}else return n.textContent=o.textContent,o.replaceWith(n),M}),X(),ne(document))}function Zn({location$:e,viewport$:t,progress$:r}){let o=ye();if(location.protocol==="file:")return M;let n=ur(o.base);I(document).subscribe(Xn);let i=d(document.body,"click").pipe(We(n),b(([p,c])=>Xa(p,c)),pe()),a=d(window,"popstate").pipe(m(xe),pe());i.pipe(ee(t)).subscribe(([p,{offset:c}])=>{history.replaceState(c,""),history.pushState(null,"",p)}),S(i,a).subscribe(e);let s=e.pipe(Z("pathname"),b(p=>ln(p,{progress$:r}).pipe(ve(()=>(pt(p,!0),M)))),b(Xn),b(Za),pe());return S(s.pipe(ee(e,(p,c)=>c)),s.pipe(b(()=>e),Z("pathname"),b(()=>e),Z("hash")),e.pipe(K((p,c)=>p.pathname===c.pathname&&p.hash===c.hash),b(()=>i),E(()=>history.back()))).subscribe(p=>{var c,l;history.state!==null||!p.hash?window.scrollTo(0,(l=(c=history.state)==null?void 0:c.y)!=null?l:0):(history.scrollRestoration="auto",sn(p.hash),history.scrollRestoration="manual")}),e.subscribe(()=>{history.scrollRestoration="manual"}),d(window,"beforeunload").subscribe(()=>{history.scrollRestoration="auto"}),t.pipe(Z("offset"),_e(100)).subscribe(({offset:p})=>{history.replaceState(p,"")}),s}var ri=Vt(ti());function oi(e){let t=e.separator.split("|").map(n=>n.replace(/(\(\?[!=<][^)]+\))/g,"").length===0?"\uFFFD":n).join("|"),r=new RegExp(t,"img"),o=(n,i,a)=>`${i}${a}`;return n=>{n=n.replace(/[\s*+\-:~^]+/g," ").trim();let i=new RegExp(`(^|${e.separator}|)(${n.replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&").replace(r,"|")})`,"img");return a=>(0,ri.default)(a).replace(i,o).replace(/<\/mark>(\s+)]*>/img,"$1")}}function It(e){return e.type===1}function dr(e){return e.type===3}function ni(e,t){let r=vn(e);return S(I(location.protocol!=="file:"),Ve("search")).pipe(Ae(o=>o),b(()=>t)).subscribe(({config:o,docs:n})=>r.next({type:0,data:{config:o,docs:n,options:{suggest:G("search.suggest")}}})),r}function ii({document$:e}){let t=ye(),r=Ne(new URL("../versions.json",t.base)).pipe(ve(()=>M)),o=r.pipe(m(n=>{let[,i]=t.base.match(/([^/]+)\/?$/);return n.find(({version:a,aliases:s})=>a===i||s.includes(i))||n[0]}));r.pipe(m(n=>new Map(n.map(i=>[`${new URL(`../${i.version}/`,t.base)}`,i]))),b(n=>d(document.body,"click").pipe(v(i=>!i.metaKey&&!i.ctrlKey),ee(o),b(([i,a])=>{if(i.target instanceof Element){let s=i.target.closest("a");if(s&&!s.target&&n.has(s.href)){let p=s.href;return!i.target.closest(".md-version")&&n.get(p)===a?M:(i.preventDefault(),I(p))}}return M}),b(i=>ur(new URL(i)).pipe(m(a=>{let p=xe().href.replace(t.base,i);return a.has(p.split("#")[0])?new URL(p):new URL(i)})))))).subscribe(n=>pt(n,!0)),z([r,o]).subscribe(([n,i])=>{P(".md-header__topic").appendChild(Mn(n,i))}),e.pipe(b(()=>o)).subscribe(n=>{var a;let i=__md_get("__outdated",sessionStorage);if(i===null){i=!0;let s=((a=t.version)==null?void 0:a.default)||"latest";Array.isArray(s)||(s=[s]);e:for(let p of s)for(let c of n.aliases.concat(n.version))if(new RegExp(p,"i").test(c)){i=!1;break e}__md_set("__outdated",i,sessionStorage)}if(i)for(let s of ae("outdated"))s.hidden=!1})}function ns(e,{worker$:t}){let{searchParams:r}=xe();r.has("q")&&(Je("search",!0),e.value=r.get("q"),e.focus(),Ve("search").pipe(Ae(i=>!i)).subscribe(()=>{let i=xe();i.searchParams.delete("q"),history.replaceState({},"",`${i}`)}));let o=et(e),n=S(t.pipe(Ae(It)),d(e,"keyup"),o).pipe(m(()=>e.value),K());return z([n,o]).pipe(m(([i,a])=>({value:i,focus:a})),B(1))}function ai(e,{worker$:t}){let r=new g,o=r.pipe(X(),ne(!0));z([t.pipe(Ae(It)),r],(i,a)=>a).pipe(Z("value")).subscribe(({value:i})=>t.next({type:2,data:i})),r.pipe(Z("focus")).subscribe(({focus:i})=>{i&&Je("search",i)}),d(e.form,"reset").pipe(U(o)).subscribe(()=>e.focus());let n=P("header [for=__search]");return d(n,"click").subscribe(()=>e.focus()),ns(e,{worker$:t}).pipe(E(i=>r.next(i)),L(()=>r.complete()),m(i=>R({ref:e},i)),B(1))}function si(e,{worker$:t,query$:r}){let o=new g,n=tn(e.parentElement).pipe(v(Boolean)),i=e.parentElement,a=P(":scope > :first-child",e),s=P(":scope > :last-child",e);Ve("search").subscribe(l=>s.setAttribute("role",l?"list":"presentation")),o.pipe(ee(r),Ur(t.pipe(Ae(It)))).subscribe(([{items:l},{value:f}])=>{switch(l.length){case 0:a.textContent=f.length?Ee("search.result.none"):Ee("search.result.placeholder");break;case 1:a.textContent=Ee("search.result.one");break;default:let u=sr(l.length);a.textContent=Ee("search.result.other",u)}});let p=o.pipe(E(()=>s.innerHTML=""),b(({items:l})=>S(I(...l.slice(0,10)),I(...l.slice(10)).pipe(Ye(4),Vr(n),b(([f])=>f)))),m(Tn),pe());return p.subscribe(l=>s.appendChild(l)),p.pipe(oe(l=>{let f=fe("details",l);return typeof f=="undefined"?M:d(f,"toggle").pipe(U(o),m(()=>f))})).subscribe(l=>{l.open===!1&&l.offsetTop<=i.scrollTop&&i.scrollTo({top:l.offsetTop})}),t.pipe(v(dr),m(({data:l})=>l)).pipe(E(l=>o.next(l)),L(()=>o.complete()),m(l=>R({ref:e},l)))}function is(e,{query$:t}){return t.pipe(m(({value:r})=>{let o=xe();return o.hash="",r=r.replace(/\s+/g,"+").replace(/&/g,"%26").replace(/=/g,"%3D"),o.search=`q=${r}`,{url:o}}))}function ci(e,t){let r=new g,o=r.pipe(X(),ne(!0));return r.subscribe(({url:n})=>{e.setAttribute("data-clipboard-text",e.href),e.href=`${n}`}),d(e,"click").pipe(U(o)).subscribe(n=>n.preventDefault()),is(e,t).pipe(E(n=>r.next(n)),L(()=>r.complete()),m(n=>R({ref:e},n)))}function pi(e,{worker$:t,keyboard$:r}){let o=new g,n=Se("search-query"),i=S(d(n,"keydown"),d(n,"focus")).pipe(be(se),m(()=>n.value),K());return o.pipe(We(i),m(([{suggest:s},p])=>{let c=p.split(/([\s-]+)/);if(s!=null&&s.length&&c[c.length-1]){let l=s[s.length-1];l.startsWith(c[c.length-1])&&(c[c.length-1]=l)}else c.length=0;return c})).subscribe(s=>e.innerHTML=s.join("").replace(/\s/g," ")),r.pipe(v(({mode:s})=>s==="search")).subscribe(s=>{switch(s.type){case"ArrowRight":e.innerText.length&&n.selectionStart===n.value.length&&(n.value=e.innerText);break}}),t.pipe(v(dr),m(({data:s})=>s)).pipe(E(s=>o.next(s)),L(()=>o.complete()),m(()=>({ref:e})))}function li(e,{index$:t,keyboard$:r}){let o=ye();try{let n=ni(o.search,t),i=Se("search-query",e),a=Se("search-result",e);d(e,"click").pipe(v(({target:p})=>p instanceof Element&&!!p.closest("a"))).subscribe(()=>Je("search",!1)),r.pipe(v(({mode:p})=>p==="search")).subscribe(p=>{let c=Re();switch(p.type){case"Enter":if(c===i){let l=new Map;for(let f of $(":first-child [href]",a)){let u=f.firstElementChild;l.set(f,parseFloat(u.getAttribute("data-md-score")))}if(l.size){let[[f]]=[...l].sort(([,u],[,h])=>h-u);f.click()}p.claim()}break;case"Escape":case"Tab":Je("search",!1),i.blur();break;case"ArrowUp":case"ArrowDown":if(typeof c=="undefined")i.focus();else{let l=[i,...$(":not(details) > [href], summary, details[open] [href]",a)],f=Math.max(0,(Math.max(0,l.indexOf(c))+l.length+(p.type==="ArrowUp"?-1:1))%l.length);l[f].focus()}p.claim();break;default:i!==Re()&&i.focus()}}),r.pipe(v(({mode:p})=>p==="global")).subscribe(p=>{switch(p.type){case"f":case"s":case"/":i.focus(),i.select(),p.claim();break}});let s=ai(i,{worker$:n});return S(s,si(a,{worker$:n,query$:s})).pipe(Pe(...ae("search-share",e).map(p=>ci(p,{query$:s})),...ae("search-suggest",e).map(p=>pi(p,{worker$:n,keyboard$:r}))))}catch(n){return e.hidden=!0,Ke}}function mi(e,{index$:t,location$:r}){return z([t,r.pipe(Q(xe()),v(o=>!!o.searchParams.get("h")))]).pipe(m(([o,n])=>oi(o.config)(n.searchParams.get("h"))),m(o=>{var a;let n=new Map,i=document.createNodeIterator(e,NodeFilter.SHOW_TEXT);for(let s=i.nextNode();s;s=i.nextNode())if((a=s.parentElement)!=null&&a.offsetHeight){let p=s.textContent,c=o(p);c.length>p.length&&n.set(s,c)}for(let[s,p]of n){let{childNodes:c}=x("span",null,p);s.replaceWith(...Array.from(c))}return{ref:e,nodes:n}}))}function as(e,{viewport$:t,main$:r}){let o=e.closest(".md-grid"),n=o.offsetTop-o.parentElement.offsetTop;return z([r,t]).pipe(m(([{offset:i,height:a},{offset:{y:s}}])=>(a=a+Math.min(n,Math.max(0,s-i))-n,{height:a,locked:s>=i+n})),K((i,a)=>i.height===a.height&&i.locked===a.locked))}function Jr(e,o){var n=o,{header$:t}=n,r=io(n,["header$"]);let i=P(".md-sidebar__scrollwrap",e),{y:a}=Ue(i);return C(()=>{let s=new g,p=s.pipe(X(),ne(!0)),c=s.pipe(Le(0,me));return c.pipe(ee(t)).subscribe({next([{height:l},{height:f}]){i.style.height=`${l-2*a}px`,e.style.top=`${f}px`},complete(){i.style.height="",e.style.top=""}}),c.pipe(Ae()).subscribe(()=>{for(let l of $(".md-nav__link--active[href]",e)){if(!l.clientHeight)continue;let f=l.closest(".md-sidebar__scrollwrap");if(typeof f!="undefined"){let u=l.offsetTop-f.offsetTop,{height:h}=ce(f);f.scrollTo({top:u-h/2})}}}),ue($("label[tabindex]",e)).pipe(oe(l=>d(l,"click").pipe(be(se),m(()=>l),U(p)))).subscribe(l=>{let f=P(`[id="${l.htmlFor}"]`);P(`[aria-labelledby="${l.id}"]`).setAttribute("aria-expanded",`${f.checked}`)}),as(e,r).pipe(E(l=>s.next(l)),L(()=>s.complete()),m(l=>R({ref:e},l)))})}function fi(e,t){if(typeof t!="undefined"){let r=`https://api.github.com/repos/${e}/${t}`;return Ct(Ne(`${r}/releases/latest`).pipe(ve(()=>M),m(o=>({version:o.tag_name})),Be({})),Ne(r).pipe(ve(()=>M),m(o=>({stars:o.stargazers_count,forks:o.forks_count})),Be({}))).pipe(m(([o,n])=>R(R({},o),n)))}else{let r=`https://api.github.com/users/${e}`;return Ne(r).pipe(m(o=>({repositories:o.public_repos})),Be({}))}}function ui(e,t){let r=`https://${e}/api/v4/projects/${encodeURIComponent(t)}`;return Ne(r).pipe(ve(()=>M),m(({star_count:o,forks_count:n})=>({stars:o,forks:n})),Be({}))}function di(e){let t=e.match(/^.+github\.com\/([^/]+)\/?([^/]+)?/i);if(t){let[,r,o]=t;return fi(r,o)}if(t=e.match(/^.+?([^/]*gitlab[^/]+)\/(.+?)\/?$/i),t){let[,r,o]=t;return ui(r,o)}return M}var ss;function cs(e){return ss||(ss=C(()=>{let t=__md_get("__source",sessionStorage);if(t)return I(t);if(ae("consent").length){let o=__md_get("__consent");if(!(o&&o.github))return M}return di(e.href).pipe(E(o=>__md_set("__source",o,sessionStorage)))}).pipe(ve(()=>M),v(t=>Object.keys(t).length>0),m(t=>({facts:t})),B(1)))}function hi(e){let t=P(":scope > :last-child",e);return C(()=>{let r=new g;return r.subscribe(({facts:o})=>{t.appendChild(Sn(o)),t.classList.add("md-source__repository--active")}),cs(e).pipe(E(o=>r.next(o)),L(()=>r.complete()),m(o=>R({ref:e},o)))})}function ps(e,{viewport$:t,header$:r}){return ge(document.body).pipe(b(()=>mr(e,{header$:r,viewport$:t})),m(({offset:{y:o}})=>({hidden:o>=10})),Z("hidden"))}function bi(e,t){return C(()=>{let r=new g;return r.subscribe({next({hidden:o}){e.hidden=o},complete(){e.hidden=!1}}),(G("navigation.tabs.sticky")?I({hidden:!1}):ps(e,t)).pipe(E(o=>r.next(o)),L(()=>r.complete()),m(o=>R({ref:e},o)))})}function ls(e,{viewport$:t,header$:r}){let o=new Map,n=$(".md-nav__link",e);for(let s of n){let p=decodeURIComponent(s.hash.substring(1)),c=fe(`[id="${p}"]`);typeof c!="undefined"&&o.set(s,c)}let i=r.pipe(Z("height"),m(({height:s})=>{let p=Se("main"),c=P(":scope > :first-child",p);return s+.8*(c.offsetTop-p.offsetTop)}),pe());return ge(document.body).pipe(Z("height"),b(s=>C(()=>{let p=[];return I([...o].reduce((c,[l,f])=>{for(;p.length&&o.get(p[p.length-1]).tagName>=f.tagName;)p.pop();let u=f.offsetTop;for(;!u&&f.parentElement;)f=f.parentElement,u=f.offsetTop;let h=f.offsetParent;for(;h;h=h.offsetParent)u+=h.offsetTop;return c.set([...p=[...p,l]].reverse(),u)},new Map))}).pipe(m(p=>new Map([...p].sort(([,c],[,l])=>c-l))),We(i),b(([p,c])=>t.pipe(jr(([l,f],{offset:{y:u},size:h})=>{let w=u+h.height>=Math.floor(s.height);for(;f.length;){let[,A]=f[0];if(A-c=u&&!w)f=[l.pop(),...f];else break}return[l,f]},[[],[...p]]),K((l,f)=>l[0]===f[0]&&l[1]===f[1])))))).pipe(m(([s,p])=>({prev:s.map(([c])=>c),next:p.map(([c])=>c)})),Q({prev:[],next:[]}),Ye(2,1),m(([s,p])=>s.prev.length{let i=new g,a=i.pipe(X(),ne(!0));if(i.subscribe(({prev:s,next:p})=>{for(let[c]of p)c.classList.remove("md-nav__link--passed"),c.classList.remove("md-nav__link--active");for(let[c,[l]]of s.entries())l.classList.add("md-nav__link--passed"),l.classList.toggle("md-nav__link--active",c===s.length-1)}),G("toc.follow")){let s=S(t.pipe(_e(1),m(()=>{})),t.pipe(_e(250),m(()=>"smooth")));i.pipe(v(({prev:p})=>p.length>0),We(o.pipe(be(se))),ee(s)).subscribe(([[{prev:p}],c])=>{let[l]=p[p.length-1];if(l.offsetHeight){let f=cr(l);if(typeof f!="undefined"){let u=l.offsetTop-f.offsetTop,{height:h}=ce(f);f.scrollTo({top:u-h/2,behavior:c})}}})}return G("navigation.tracking")&&t.pipe(U(a),Z("offset"),_e(250),Ce(1),U(n.pipe(Ce(1))),st({delay:250}),ee(i)).subscribe(([,{prev:s}])=>{let p=xe(),c=s[s.length-1];if(c&&c.length){let[l]=c,{hash:f}=new URL(l.href);p.hash!==f&&(p.hash=f,history.replaceState({},"",`${p}`))}else p.hash="",history.replaceState({},"",`${p}`)}),ls(e,{viewport$:t,header$:r}).pipe(E(s=>i.next(s)),L(()=>i.complete()),m(s=>R({ref:e},s)))})}function ms(e,{viewport$:t,main$:r,target$:o}){let n=t.pipe(m(({offset:{y:a}})=>a),Ye(2,1),m(([a,s])=>a>s&&s>0),K()),i=r.pipe(m(({active:a})=>a));return z([i,n]).pipe(m(([a,s])=>!(a&&s)),K(),U(o.pipe(Ce(1))),ne(!0),st({delay:250}),m(a=>({hidden:a})))}function gi(e,{viewport$:t,header$:r,main$:o,target$:n}){let i=new g,a=i.pipe(X(),ne(!0));return i.subscribe({next({hidden:s}){e.hidden=s,s?(e.setAttribute("tabindex","-1"),e.blur()):e.removeAttribute("tabindex")},complete(){e.style.top="",e.hidden=!0,e.removeAttribute("tabindex")}}),r.pipe(U(a),Z("height")).subscribe(({height:s})=>{e.style.top=`${s+16}px`}),d(e,"click").subscribe(s=>{s.preventDefault(),window.scrollTo({top:0})}),ms(e,{viewport$:t,main$:o,target$:n}).pipe(E(s=>i.next(s)),L(()=>i.complete()),m(s=>R({ref:e},s)))}function xi({document$:e,viewport$:t}){e.pipe(b(()=>$(".md-ellipsis")),oe(r=>tt(r).pipe(U(e.pipe(Ce(1))),v(o=>o),m(()=>r),Te(1))),v(r=>r.offsetWidth{let o=r.innerText,n=r.closest("a")||r;return n.title=o,lt(n,{viewport$:t}).pipe(U(e.pipe(Ce(1))),L(()=>n.removeAttribute("title")))})).subscribe(),e.pipe(b(()=>$(".md-status")),oe(r=>lt(r,{viewport$:t}))).subscribe()}function yi({document$:e,tablet$:t}){e.pipe(b(()=>$(".md-toggle--indeterminate")),E(r=>{r.indeterminate=!0,r.checked=!1}),oe(r=>d(r,"change").pipe(Dr(()=>r.classList.contains("md-toggle--indeterminate")),m(()=>r))),ee(t)).subscribe(([r,o])=>{r.classList.remove("md-toggle--indeterminate"),o&&(r.checked=!1)})}function fs(){return/(iPad|iPhone|iPod)/.test(navigator.userAgent)}function Ei({document$:e}){e.pipe(b(()=>$("[data-md-scrollfix]")),E(t=>t.removeAttribute("data-md-scrollfix")),v(fs),oe(t=>d(t,"touchstart").pipe(m(()=>t)))).subscribe(t=>{let r=t.scrollTop;r===0?t.scrollTop=1:r+t.offsetHeight===t.scrollHeight&&(t.scrollTop=r-1)})}function wi({viewport$:e,tablet$:t}){z([Ve("search"),t]).pipe(m(([r,o])=>r&&!o),b(r=>I(r).pipe(Ge(r?400:100))),ee(e)).subscribe(([r,{offset:{y:o}}])=>{if(r)document.body.setAttribute("data-md-scrolllock",""),document.body.style.top=`-${o}px`;else{let n=-1*parseInt(document.body.style.top,10);document.body.removeAttribute("data-md-scrolllock"),document.body.style.top="",n&&window.scrollTo(0,n)}})}Object.entries||(Object.entries=function(e){let t=[];for(let r of Object.keys(e))t.push([r,e[r]]);return t});Object.values||(Object.values=function(e){let t=[];for(let r of Object.keys(e))t.push(e[r]);return t});typeof Element!="undefined"&&(Element.prototype.scrollTo||(Element.prototype.scrollTo=function(e,t){typeof e=="object"?(this.scrollLeft=e.left,this.scrollTop=e.top):(this.scrollLeft=e,this.scrollTop=t)}),Element.prototype.replaceWith||(Element.prototype.replaceWith=function(...e){let t=this.parentNode;if(t){e.length===0&&t.removeChild(this);for(let r=e.length-1;r>=0;r--){let o=e[r];typeof o=="string"?o=document.createTextNode(o):o.parentNode&&o.parentNode.removeChild(o),r?t.insertBefore(this.previousSibling,o):t.replaceChild(o,this)}}}));function us(){return location.protocol==="file:"?wt(`${new URL("search/search_index.js",Xr.base)}`).pipe(m(()=>__index),B(1)):Ne(new URL("search/search_index.json",Xr.base))}document.documentElement.classList.remove("no-js");document.documentElement.classList.add("js");var ot=Yo(),jt=nn(),Ot=cn(jt),Zr=on(),Oe=bn(),hr=$t("(min-width: 960px)"),Si=$t("(min-width: 1220px)"),Oi=pn(),Xr=ye(),Mi=document.forms.namedItem("search")?us():Ke,eo=new g;Bn({alert$:eo});var to=new g;G("navigation.instant")&&Zn({location$:jt,viewport$:Oe,progress$:to}).subscribe(ot);var Ti;((Ti=Xr.version)==null?void 0:Ti.provider)==="mike"&&ii({document$:ot});S(jt,Ot).pipe(Ge(125)).subscribe(()=>{Je("drawer",!1),Je("search",!1)});Zr.pipe(v(({mode:e})=>e==="global")).subscribe(e=>{switch(e.type){case"p":case",":let t=fe("link[rel=prev]");typeof t!="undefined"&&pt(t);break;case"n":case".":let r=fe("link[rel=next]");typeof r!="undefined"&&pt(r);break;case"Enter":let o=Re();o instanceof HTMLLabelElement&&o.click()}});xi({viewport$:Oe,document$:ot});yi({document$:ot,tablet$:hr});Ei({document$:ot});wi({viewport$:Oe,tablet$:hr});var rt=Nn(Se("header"),{viewport$:Oe}),Ft=ot.pipe(m(()=>Se("main")),b(e=>Qn(e,{viewport$:Oe,header$:rt})),B(1)),ds=S(...ae("consent").map(e=>xn(e,{target$:Ot})),...ae("dialog").map(e=>Dn(e,{alert$:eo})),...ae("header").map(e=>zn(e,{viewport$:Oe,header$:rt,main$:Ft})),...ae("palette").map(e=>Kn(e)),...ae("progress").map(e=>Yn(e,{progress$:to})),...ae("search").map(e=>li(e,{index$:Mi,keyboard$:Zr})),...ae("source").map(e=>hi(e))),hs=C(()=>S(...ae("announce").map(e=>gn(e)),...ae("content").map(e=>Un(e,{viewport$:Oe,target$:Ot,print$:Oi})),...ae("content").map(e=>G("search.highlight")?mi(e,{index$:Mi,location$:jt}):M),...ae("header-title").map(e=>qn(e,{viewport$:Oe,header$:rt})),...ae("sidebar").map(e=>e.getAttribute("data-md-type")==="navigation"?Nr(Si,()=>Jr(e,{viewport$:Oe,header$:rt,main$:Ft})):Nr(hr,()=>Jr(e,{viewport$:Oe,header$:rt,main$:Ft}))),...ae("tabs").map(e=>bi(e,{viewport$:Oe,header$:rt})),...ae("toc").map(e=>vi(e,{viewport$:Oe,header$:rt,main$:Ft,target$:Ot})),...ae("top").map(e=>gi(e,{viewport$:Oe,header$:rt,main$:Ft,target$:Ot})))),Li=ot.pipe(b(()=>hs),Pe(ds),B(1));Li.subscribe();window.document$=ot;window.location$=jt;window.target$=Ot;window.keyboard$=Zr;window.viewport$=Oe;window.tablet$=hr;window.screen$=Si;window.print$=Oi;window.alert$=eo;window.progress$=to;window.component$=Li;})(); +//# sourceMappingURL=bundle.081f42fc.min.js.map + diff --git a/third-party/fmt/doc-html/assets/javascripts/bundle.081f42fc.min.js.map b/third-party/fmt/doc-html/assets/javascripts/bundle.081f42fc.min.js.map new file mode 100644 index 0000000000..e055db5acc --- /dev/null +++ b/third-party/fmt/doc-html/assets/javascripts/bundle.081f42fc.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["node_modules/focus-visible/dist/focus-visible.js", "node_modules/clipboard/dist/clipboard.js", "node_modules/escape-html/index.js", "src/templates/assets/javascripts/bundle.ts", "node_modules/rxjs/node_modules/tslib/tslib.es6.js", "node_modules/rxjs/src/internal/util/isFunction.ts", "node_modules/rxjs/src/internal/util/createErrorClass.ts", "node_modules/rxjs/src/internal/util/UnsubscriptionError.ts", "node_modules/rxjs/src/internal/util/arrRemove.ts", "node_modules/rxjs/src/internal/Subscription.ts", "node_modules/rxjs/src/internal/config.ts", "node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts", "node_modules/rxjs/src/internal/util/reportUnhandledError.ts", "node_modules/rxjs/src/internal/util/noop.ts", "node_modules/rxjs/src/internal/NotificationFactories.ts", "node_modules/rxjs/src/internal/util/errorContext.ts", "node_modules/rxjs/src/internal/Subscriber.ts", "node_modules/rxjs/src/internal/symbol/observable.ts", "node_modules/rxjs/src/internal/util/identity.ts", "node_modules/rxjs/src/internal/util/pipe.ts", "node_modules/rxjs/src/internal/Observable.ts", "node_modules/rxjs/src/internal/util/lift.ts", "node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts", "node_modules/rxjs/src/internal/scheduler/animationFrameProvider.ts", "node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts", "node_modules/rxjs/src/internal/Subject.ts", "node_modules/rxjs/src/internal/BehaviorSubject.ts", "node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts", "node_modules/rxjs/src/internal/ReplaySubject.ts", "node_modules/rxjs/src/internal/scheduler/Action.ts", "node_modules/rxjs/src/internal/scheduler/intervalProvider.ts", "node_modules/rxjs/src/internal/scheduler/AsyncAction.ts", "node_modules/rxjs/src/internal/Scheduler.ts", "node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts", "node_modules/rxjs/src/internal/scheduler/async.ts", "node_modules/rxjs/src/internal/scheduler/QueueAction.ts", "node_modules/rxjs/src/internal/scheduler/QueueScheduler.ts", "node_modules/rxjs/src/internal/scheduler/queue.ts", "node_modules/rxjs/src/internal/scheduler/AnimationFrameAction.ts", "node_modules/rxjs/src/internal/scheduler/AnimationFrameScheduler.ts", "node_modules/rxjs/src/internal/scheduler/animationFrame.ts", "node_modules/rxjs/src/internal/observable/empty.ts", "node_modules/rxjs/src/internal/util/isScheduler.ts", "node_modules/rxjs/src/internal/util/args.ts", "node_modules/rxjs/src/internal/util/isArrayLike.ts", "node_modules/rxjs/src/internal/util/isPromise.ts", "node_modules/rxjs/src/internal/util/isInteropObservable.ts", "node_modules/rxjs/src/internal/util/isAsyncIterable.ts", "node_modules/rxjs/src/internal/util/throwUnobservableError.ts", "node_modules/rxjs/src/internal/symbol/iterator.ts", "node_modules/rxjs/src/internal/util/isIterable.ts", "node_modules/rxjs/src/internal/util/isReadableStreamLike.ts", "node_modules/rxjs/src/internal/observable/innerFrom.ts", "node_modules/rxjs/src/internal/util/executeSchedule.ts", "node_modules/rxjs/src/internal/operators/observeOn.ts", "node_modules/rxjs/src/internal/operators/subscribeOn.ts", "node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts", "node_modules/rxjs/src/internal/scheduled/schedulePromise.ts", "node_modules/rxjs/src/internal/scheduled/scheduleArray.ts", "node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts", "node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts", "node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts", "node_modules/rxjs/src/internal/scheduled/scheduled.ts", "node_modules/rxjs/src/internal/observable/from.ts", "node_modules/rxjs/src/internal/observable/of.ts", "node_modules/rxjs/src/internal/observable/throwError.ts", "node_modules/rxjs/src/internal/util/EmptyError.ts", "node_modules/rxjs/src/internal/util/isDate.ts", "node_modules/rxjs/src/internal/operators/map.ts", "node_modules/rxjs/src/internal/util/mapOneOrManyArgs.ts", "node_modules/rxjs/src/internal/util/argsArgArrayOrObject.ts", "node_modules/rxjs/src/internal/util/createObject.ts", "node_modules/rxjs/src/internal/observable/combineLatest.ts", "node_modules/rxjs/src/internal/operators/mergeInternals.ts", "node_modules/rxjs/src/internal/operators/mergeMap.ts", "node_modules/rxjs/src/internal/operators/mergeAll.ts", "node_modules/rxjs/src/internal/operators/concatAll.ts", "node_modules/rxjs/src/internal/observable/concat.ts", "node_modules/rxjs/src/internal/observable/defer.ts", "node_modules/rxjs/src/internal/observable/fromEvent.ts", "node_modules/rxjs/src/internal/observable/fromEventPattern.ts", "node_modules/rxjs/src/internal/observable/timer.ts", "node_modules/rxjs/src/internal/observable/merge.ts", "node_modules/rxjs/src/internal/observable/never.ts", "node_modules/rxjs/src/internal/util/argsOrArgArray.ts", "node_modules/rxjs/src/internal/operators/filter.ts", "node_modules/rxjs/src/internal/observable/zip.ts", "node_modules/rxjs/src/internal/operators/audit.ts", "node_modules/rxjs/src/internal/operators/auditTime.ts", "node_modules/rxjs/src/internal/operators/bufferCount.ts", "node_modules/rxjs/src/internal/operators/catchError.ts", "node_modules/rxjs/src/internal/operators/scanInternals.ts", "node_modules/rxjs/src/internal/operators/combineLatest.ts", "node_modules/rxjs/src/internal/operators/combineLatestWith.ts", "node_modules/rxjs/src/internal/operators/debounce.ts", "node_modules/rxjs/src/internal/operators/debounceTime.ts", "node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts", "node_modules/rxjs/src/internal/operators/take.ts", "node_modules/rxjs/src/internal/operators/ignoreElements.ts", "node_modules/rxjs/src/internal/operators/mapTo.ts", "node_modules/rxjs/src/internal/operators/delayWhen.ts", "node_modules/rxjs/src/internal/operators/delay.ts", "node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts", "node_modules/rxjs/src/internal/operators/distinctUntilKeyChanged.ts", "node_modules/rxjs/src/internal/operators/throwIfEmpty.ts", "node_modules/rxjs/src/internal/operators/endWith.ts", "node_modules/rxjs/src/internal/operators/finalize.ts", "node_modules/rxjs/src/internal/operators/first.ts", "node_modules/rxjs/src/internal/operators/takeLast.ts", "node_modules/rxjs/src/internal/operators/merge.ts", "node_modules/rxjs/src/internal/operators/mergeWith.ts", "node_modules/rxjs/src/internal/operators/repeat.ts", "node_modules/rxjs/src/internal/operators/scan.ts", "node_modules/rxjs/src/internal/operators/share.ts", "node_modules/rxjs/src/internal/operators/shareReplay.ts", "node_modules/rxjs/src/internal/operators/skip.ts", "node_modules/rxjs/src/internal/operators/skipUntil.ts", "node_modules/rxjs/src/internal/operators/startWith.ts", "node_modules/rxjs/src/internal/operators/switchMap.ts", "node_modules/rxjs/src/internal/operators/takeUntil.ts", "node_modules/rxjs/src/internal/operators/takeWhile.ts", "node_modules/rxjs/src/internal/operators/tap.ts", "node_modules/rxjs/src/internal/operators/throttle.ts", "node_modules/rxjs/src/internal/operators/throttleTime.ts", "node_modules/rxjs/src/internal/operators/withLatestFrom.ts", "node_modules/rxjs/src/internal/operators/zip.ts", "node_modules/rxjs/src/internal/operators/zipWith.ts", "src/templates/assets/javascripts/browser/document/index.ts", "src/templates/assets/javascripts/browser/element/_/index.ts", "src/templates/assets/javascripts/browser/element/focus/index.ts", "src/templates/assets/javascripts/browser/element/hover/index.ts", "src/templates/assets/javascripts/utilities/h/index.ts", "src/templates/assets/javascripts/utilities/round/index.ts", "src/templates/assets/javascripts/browser/script/index.ts", "src/templates/assets/javascripts/browser/element/size/_/index.ts", "src/templates/assets/javascripts/browser/element/size/content/index.ts", "src/templates/assets/javascripts/browser/element/offset/_/index.ts", "src/templates/assets/javascripts/browser/element/offset/content/index.ts", "src/templates/assets/javascripts/browser/element/visibility/index.ts", "src/templates/assets/javascripts/browser/toggle/index.ts", "src/templates/assets/javascripts/browser/keyboard/index.ts", "src/templates/assets/javascripts/browser/location/_/index.ts", "src/templates/assets/javascripts/browser/location/hash/index.ts", "src/templates/assets/javascripts/browser/media/index.ts", "src/templates/assets/javascripts/browser/request/index.ts", "src/templates/assets/javascripts/browser/viewport/offset/index.ts", "src/templates/assets/javascripts/browser/viewport/size/index.ts", "src/templates/assets/javascripts/browser/viewport/_/index.ts", "src/templates/assets/javascripts/browser/viewport/at/index.ts", "src/templates/assets/javascripts/browser/worker/index.ts", "src/templates/assets/javascripts/_/index.ts", "src/templates/assets/javascripts/components/_/index.ts", "src/templates/assets/javascripts/components/announce/index.ts", "src/templates/assets/javascripts/components/consent/index.ts", "src/templates/assets/javascripts/templates/tooltip/index.tsx", "src/templates/assets/javascripts/templates/annotation/index.tsx", "src/templates/assets/javascripts/templates/clipboard/index.tsx", "src/templates/assets/javascripts/templates/search/index.tsx", "src/templates/assets/javascripts/templates/source/index.tsx", "src/templates/assets/javascripts/templates/tabbed/index.tsx", "src/templates/assets/javascripts/templates/table/index.tsx", "src/templates/assets/javascripts/templates/version/index.tsx", "src/templates/assets/javascripts/components/tooltip2/index.ts", "src/templates/assets/javascripts/components/content/annotation/_/index.ts", "src/templates/assets/javascripts/components/content/annotation/list/index.ts", "src/templates/assets/javascripts/components/content/annotation/block/index.ts", "src/templates/assets/javascripts/components/content/code/_/index.ts", "src/templates/assets/javascripts/components/content/details/index.ts", "src/templates/assets/javascripts/components/content/mermaid/index.css", "src/templates/assets/javascripts/components/content/mermaid/index.ts", "src/templates/assets/javascripts/components/content/table/index.ts", "src/templates/assets/javascripts/components/content/tabs/index.ts", "src/templates/assets/javascripts/components/content/_/index.ts", "src/templates/assets/javascripts/components/dialog/index.ts", "src/templates/assets/javascripts/components/tooltip/index.ts", "src/templates/assets/javascripts/components/header/_/index.ts", "src/templates/assets/javascripts/components/header/title/index.ts", "src/templates/assets/javascripts/components/main/index.ts", "src/templates/assets/javascripts/components/palette/index.ts", "src/templates/assets/javascripts/components/progress/index.ts", "src/templates/assets/javascripts/integrations/clipboard/index.ts", "src/templates/assets/javascripts/integrations/sitemap/index.ts", "src/templates/assets/javascripts/integrations/instant/index.ts", "src/templates/assets/javascripts/integrations/search/highlighter/index.ts", "src/templates/assets/javascripts/integrations/search/worker/message/index.ts", "src/templates/assets/javascripts/integrations/search/worker/_/index.ts", "src/templates/assets/javascripts/integrations/version/index.ts", "src/templates/assets/javascripts/components/search/query/index.ts", "src/templates/assets/javascripts/components/search/result/index.ts", "src/templates/assets/javascripts/components/search/share/index.ts", "src/templates/assets/javascripts/components/search/suggest/index.ts", "src/templates/assets/javascripts/components/search/_/index.ts", "src/templates/assets/javascripts/components/search/highlight/index.ts", "src/templates/assets/javascripts/components/sidebar/index.ts", "src/templates/assets/javascripts/components/source/facts/github/index.ts", "src/templates/assets/javascripts/components/source/facts/gitlab/index.ts", "src/templates/assets/javascripts/components/source/facts/_/index.ts", "src/templates/assets/javascripts/components/source/_/index.ts", "src/templates/assets/javascripts/components/tabs/index.ts", "src/templates/assets/javascripts/components/toc/index.ts", "src/templates/assets/javascripts/components/top/index.ts", "src/templates/assets/javascripts/patches/ellipsis/index.ts", "src/templates/assets/javascripts/patches/indeterminate/index.ts", "src/templates/assets/javascripts/patches/scrollfix/index.ts", "src/templates/assets/javascripts/patches/scrolllock/index.ts", "src/templates/assets/javascripts/polyfills/index.ts"], + "sourcesContent": ["(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (factory());\n}(this, (function () { 'use strict';\n\n /**\n * Applies the :focus-visible polyfill at the given scope.\n * A scope in this case is either the top-level Document or a Shadow Root.\n *\n * @param {(Document|ShadowRoot)} scope\n * @see https://github.com/WICG/focus-visible\n */\n function applyFocusVisiblePolyfill(scope) {\n var hadKeyboardEvent = true;\n var hadFocusVisibleRecently = false;\n var hadFocusVisibleRecentlyTimeout = null;\n\n var inputTypesAllowlist = {\n text: true,\n search: true,\n url: true,\n tel: true,\n email: true,\n password: true,\n number: true,\n date: true,\n month: true,\n week: true,\n time: true,\n datetime: true,\n 'datetime-local': true\n };\n\n /**\n * Helper function for legacy browsers and iframes which sometimes focus\n * elements like document, body, and non-interactive SVG.\n * @param {Element} el\n */\n function isValidFocusTarget(el) {\n if (\n el &&\n el !== document &&\n el.nodeName !== 'HTML' &&\n el.nodeName !== 'BODY' &&\n 'classList' in el &&\n 'contains' in el.classList\n ) {\n return true;\n }\n return false;\n }\n\n /**\n * Computes whether the given element should automatically trigger the\n * `focus-visible` class being added, i.e. whether it should always match\n * `:focus-visible` when focused.\n * @param {Element} el\n * @return {boolean}\n */\n function focusTriggersKeyboardModality(el) {\n var type = el.type;\n var tagName = el.tagName;\n\n if (tagName === 'INPUT' && inputTypesAllowlist[type] && !el.readOnly) {\n return true;\n }\n\n if (tagName === 'TEXTAREA' && !el.readOnly) {\n return true;\n }\n\n if (el.isContentEditable) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Add the `focus-visible` class to the given element if it was not added by\n * the author.\n * @param {Element} el\n */\n function addFocusVisibleClass(el) {\n if (el.classList.contains('focus-visible')) {\n return;\n }\n el.classList.add('focus-visible');\n el.setAttribute('data-focus-visible-added', '');\n }\n\n /**\n * Remove the `focus-visible` class from the given element if it was not\n * originally added by the author.\n * @param {Element} el\n */\n function removeFocusVisibleClass(el) {\n if (!el.hasAttribute('data-focus-visible-added')) {\n return;\n }\n el.classList.remove('focus-visible');\n el.removeAttribute('data-focus-visible-added');\n }\n\n /**\n * If the most recent user interaction was via the keyboard;\n * and the key press did not include a meta, alt/option, or control key;\n * then the modality is keyboard. Otherwise, the modality is not keyboard.\n * Apply `focus-visible` to any current active element and keep track\n * of our keyboard modality state with `hadKeyboardEvent`.\n * @param {KeyboardEvent} e\n */\n function onKeyDown(e) {\n if (e.metaKey || e.altKey || e.ctrlKey) {\n return;\n }\n\n if (isValidFocusTarget(scope.activeElement)) {\n addFocusVisibleClass(scope.activeElement);\n }\n\n hadKeyboardEvent = true;\n }\n\n /**\n * If at any point a user clicks with a pointing device, ensure that we change\n * the modality away from keyboard.\n * This avoids the situation where a user presses a key on an already focused\n * element, and then clicks on a different element, focusing it with a\n * pointing device, while we still think we're in keyboard modality.\n * @param {Event} e\n */\n function onPointerDown(e) {\n hadKeyboardEvent = false;\n }\n\n /**\n * On `focus`, add the `focus-visible` class to the target if:\n * - the target received focus as a result of keyboard navigation, or\n * - the event target is an element that will likely require interaction\n * via the keyboard (e.g. a text box)\n * @param {Event} e\n */\n function onFocus(e) {\n // Prevent IE from focusing the document or HTML element.\n if (!isValidFocusTarget(e.target)) {\n return;\n }\n\n if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) {\n addFocusVisibleClass(e.target);\n }\n }\n\n /**\n * On `blur`, remove the `focus-visible` class from the target.\n * @param {Event} e\n */\n function onBlur(e) {\n if (!isValidFocusTarget(e.target)) {\n return;\n }\n\n if (\n e.target.classList.contains('focus-visible') ||\n e.target.hasAttribute('data-focus-visible-added')\n ) {\n // To detect a tab/window switch, we look for a blur event followed\n // rapidly by a visibility change.\n // If we don't see a visibility change within 100ms, it's probably a\n // regular focus change.\n hadFocusVisibleRecently = true;\n window.clearTimeout(hadFocusVisibleRecentlyTimeout);\n hadFocusVisibleRecentlyTimeout = window.setTimeout(function() {\n hadFocusVisibleRecently = false;\n }, 100);\n removeFocusVisibleClass(e.target);\n }\n }\n\n /**\n * If the user changes tabs, keep track of whether or not the previously\n * focused element had .focus-visible.\n * @param {Event} e\n */\n function onVisibilityChange(e) {\n if (document.visibilityState === 'hidden') {\n // If the tab becomes active again, the browser will handle calling focus\n // on the element (Safari actually calls it twice).\n // If this tab change caused a blur on an element with focus-visible,\n // re-apply the class when the user switches back to the tab.\n if (hadFocusVisibleRecently) {\n hadKeyboardEvent = true;\n }\n addInitialPointerMoveListeners();\n }\n }\n\n /**\n * Add a group of listeners to detect usage of any pointing devices.\n * These listeners will be added when the polyfill first loads, and anytime\n * the window is blurred, so that they are active when the window regains\n * focus.\n */\n function addInitialPointerMoveListeners() {\n document.addEventListener('mousemove', onInitialPointerMove);\n document.addEventListener('mousedown', onInitialPointerMove);\n document.addEventListener('mouseup', onInitialPointerMove);\n document.addEventListener('pointermove', onInitialPointerMove);\n document.addEventListener('pointerdown', onInitialPointerMove);\n document.addEventListener('pointerup', onInitialPointerMove);\n document.addEventListener('touchmove', onInitialPointerMove);\n document.addEventListener('touchstart', onInitialPointerMove);\n document.addEventListener('touchend', onInitialPointerMove);\n }\n\n function removeInitialPointerMoveListeners() {\n document.removeEventListener('mousemove', onInitialPointerMove);\n document.removeEventListener('mousedown', onInitialPointerMove);\n document.removeEventListener('mouseup', onInitialPointerMove);\n document.removeEventListener('pointermove', onInitialPointerMove);\n document.removeEventListener('pointerdown', onInitialPointerMove);\n document.removeEventListener('pointerup', onInitialPointerMove);\n document.removeEventListener('touchmove', onInitialPointerMove);\n document.removeEventListener('touchstart', onInitialPointerMove);\n document.removeEventListener('touchend', onInitialPointerMove);\n }\n\n /**\n * When the polfyill first loads, assume the user is in keyboard modality.\n * If any event is received from a pointing device (e.g. mouse, pointer,\n * touch), turn off keyboard modality.\n * This accounts for situations where focus enters the page from the URL bar.\n * @param {Event} e\n */\n function onInitialPointerMove(e) {\n // Work around a Safari quirk that fires a mousemove on whenever the\n // window blurs, even if you're tabbing out of the page. \u00AF\\_(\u30C4)_/\u00AF\n if (e.target.nodeName && e.target.nodeName.toLowerCase() === 'html') {\n return;\n }\n\n hadKeyboardEvent = false;\n removeInitialPointerMoveListeners();\n }\n\n // For some kinds of state, we are interested in changes at the global scope\n // only. For example, global pointer input, global key presses and global\n // visibility change should affect the state at every scope:\n document.addEventListener('keydown', onKeyDown, true);\n document.addEventListener('mousedown', onPointerDown, true);\n document.addEventListener('pointerdown', onPointerDown, true);\n document.addEventListener('touchstart', onPointerDown, true);\n document.addEventListener('visibilitychange', onVisibilityChange, true);\n\n addInitialPointerMoveListeners();\n\n // For focus and blur, we specifically care about state changes in the local\n // scope. This is because focus / blur events that originate from within a\n // shadow root are not re-dispatched from the host element if it was already\n // the active element in its own scope:\n scope.addEventListener('focus', onFocus, true);\n scope.addEventListener('blur', onBlur, true);\n\n // We detect that a node is a ShadowRoot by ensuring that it is a\n // DocumentFragment and also has a host property. This check covers native\n // implementation and polyfill implementation transparently. If we only cared\n // about the native implementation, we could just check if the scope was\n // an instance of a ShadowRoot.\n if (scope.nodeType === Node.DOCUMENT_FRAGMENT_NODE && scope.host) {\n // Since a ShadowRoot is a special kind of DocumentFragment, it does not\n // have a root element to add a class to. So, we add this attribute to the\n // host element instead:\n scope.host.setAttribute('data-js-focus-visible', '');\n } else if (scope.nodeType === Node.DOCUMENT_NODE) {\n document.documentElement.classList.add('js-focus-visible');\n document.documentElement.setAttribute('data-js-focus-visible', '');\n }\n }\n\n // It is important to wrap all references to global window and document in\n // these checks to support server-side rendering use cases\n // @see https://github.com/WICG/focus-visible/issues/199\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n // Make the polyfill helper globally available. This can be used as a signal\n // to interested libraries that wish to coordinate with the polyfill for e.g.,\n // applying the polyfill to a shadow root:\n window.applyFocusVisiblePolyfill = applyFocusVisiblePolyfill;\n\n // Notify interested libraries of the polyfill's presence, in case the\n // polyfill was loaded lazily:\n var event;\n\n try {\n event = new CustomEvent('focus-visible-polyfill-ready');\n } catch (error) {\n // IE11 does not support using CustomEvent as a constructor directly:\n event = document.createEvent('CustomEvent');\n event.initCustomEvent('focus-visible-polyfill-ready', false, false, {});\n }\n\n window.dispatchEvent(event);\n }\n\n if (typeof document !== 'undefined') {\n // Apply the polyfill to the global document, so that no JavaScript\n // coordination is required to use the polyfill in the top-level document:\n applyFocusVisiblePolyfill(document);\n }\n\n})));\n", "/*!\n * clipboard.js v2.0.11\n * https://clipboardjs.com/\n *\n * Licensed MIT \u00A9 Zeno Rocha\n */\n(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ClipboardJS\"] = factory();\n\telse\n\t\troot[\"ClipboardJS\"] = factory();\n})(this, function() {\nreturn /******/ (function() { // webpackBootstrap\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ 686:\n/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n\n// EXPORTS\n__webpack_require__.d(__webpack_exports__, {\n \"default\": function() { return /* binding */ clipboard; }\n});\n\n// EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js\nvar tiny_emitter = __webpack_require__(279);\nvar tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter);\n// EXTERNAL MODULE: ./node_modules/good-listener/src/listen.js\nvar listen = __webpack_require__(370);\nvar listen_default = /*#__PURE__*/__webpack_require__.n(listen);\n// EXTERNAL MODULE: ./node_modules/select/src/select.js\nvar src_select = __webpack_require__(817);\nvar select_default = /*#__PURE__*/__webpack_require__.n(src_select);\n;// CONCATENATED MODULE: ./src/common/command.js\n/**\n * Executes a given operation type.\n * @param {String} type\n * @return {Boolean}\n */\nfunction command(type) {\n try {\n return document.execCommand(type);\n } catch (err) {\n return false;\n }\n}\n;// CONCATENATED MODULE: ./src/actions/cut.js\n\n\n/**\n * Cut action wrapper.\n * @param {String|HTMLElement} target\n * @return {String}\n */\n\nvar ClipboardActionCut = function ClipboardActionCut(target) {\n var selectedText = select_default()(target);\n command('cut');\n return selectedText;\n};\n\n/* harmony default export */ var actions_cut = (ClipboardActionCut);\n;// CONCATENATED MODULE: ./src/common/create-fake-element.js\n/**\n * Creates a fake textarea element with a value.\n * @param {String} value\n * @return {HTMLElement}\n */\nfunction createFakeElement(value) {\n var isRTL = document.documentElement.getAttribute('dir') === 'rtl';\n var fakeElement = document.createElement('textarea'); // Prevent zooming on iOS\n\n fakeElement.style.fontSize = '12pt'; // Reset box model\n\n fakeElement.style.border = '0';\n fakeElement.style.padding = '0';\n fakeElement.style.margin = '0'; // Move element out of screen horizontally\n\n fakeElement.style.position = 'absolute';\n fakeElement.style[isRTL ? 'right' : 'left'] = '-9999px'; // Move element to the same position vertically\n\n var yPosition = window.pageYOffset || document.documentElement.scrollTop;\n fakeElement.style.top = \"\".concat(yPosition, \"px\");\n fakeElement.setAttribute('readonly', '');\n fakeElement.value = value;\n return fakeElement;\n}\n;// CONCATENATED MODULE: ./src/actions/copy.js\n\n\n\n/**\n * Create fake copy action wrapper using a fake element.\n * @param {String} target\n * @param {Object} options\n * @return {String}\n */\n\nvar fakeCopyAction = function fakeCopyAction(value, options) {\n var fakeElement = createFakeElement(value);\n options.container.appendChild(fakeElement);\n var selectedText = select_default()(fakeElement);\n command('copy');\n fakeElement.remove();\n return selectedText;\n};\n/**\n * Copy action wrapper.\n * @param {String|HTMLElement} target\n * @param {Object} options\n * @return {String}\n */\n\n\nvar ClipboardActionCopy = function ClipboardActionCopy(target) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n container: document.body\n };\n var selectedText = '';\n\n if (typeof target === 'string') {\n selectedText = fakeCopyAction(target, options);\n } else if (target instanceof HTMLInputElement && !['text', 'search', 'url', 'tel', 'password'].includes(target === null || target === void 0 ? void 0 : target.type)) {\n // If input type doesn't support `setSelectionRange`. Simulate it. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n selectedText = fakeCopyAction(target.value, options);\n } else {\n selectedText = select_default()(target);\n command('copy');\n }\n\n return selectedText;\n};\n\n/* harmony default export */ var actions_copy = (ClipboardActionCopy);\n;// CONCATENATED MODULE: ./src/actions/default.js\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n\n\n/**\n * Inner function which performs selection from either `text` or `target`\n * properties and then executes copy or cut operations.\n * @param {Object} options\n */\n\nvar ClipboardActionDefault = function ClipboardActionDefault() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // Defines base properties passed from constructor.\n var _options$action = options.action,\n action = _options$action === void 0 ? 'copy' : _options$action,\n container = options.container,\n target = options.target,\n text = options.text; // Sets the `action` to be performed which can be either 'copy' or 'cut'.\n\n if (action !== 'copy' && action !== 'cut') {\n throw new Error('Invalid \"action\" value, use either \"copy\" or \"cut\"');\n } // Sets the `target` property using an element that will be have its content copied.\n\n\n if (target !== undefined) {\n if (target && _typeof(target) === 'object' && target.nodeType === 1) {\n if (action === 'copy' && target.hasAttribute('disabled')) {\n throw new Error('Invalid \"target\" attribute. Please use \"readonly\" instead of \"disabled\" attribute');\n }\n\n if (action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) {\n throw new Error('Invalid \"target\" attribute. You can\\'t cut text from elements with \"readonly\" or \"disabled\" attributes');\n }\n } else {\n throw new Error('Invalid \"target\" value, use a valid Element');\n }\n } // Define selection strategy based on `text` property.\n\n\n if (text) {\n return actions_copy(text, {\n container: container\n });\n } // Defines which selection strategy based on `target` property.\n\n\n if (target) {\n return action === 'cut' ? actions_cut(target) : actions_copy(target, {\n container: container\n });\n }\n};\n\n/* harmony default export */ var actions_default = (ClipboardActionDefault);\n;// CONCATENATED MODULE: ./src/clipboard.js\nfunction clipboard_typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { clipboard_typeof = function _typeof(obj) { return typeof obj; }; } else { clipboard_typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return clipboard_typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (clipboard_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n/**\n * Helper function to retrieve attribute value.\n * @param {String} suffix\n * @param {Element} element\n */\n\nfunction getAttributeValue(suffix, element) {\n var attribute = \"data-clipboard-\".concat(suffix);\n\n if (!element.hasAttribute(attribute)) {\n return;\n }\n\n return element.getAttribute(attribute);\n}\n/**\n * Base class which takes one or more elements, adds event listeners to them,\n * and instantiates a new `ClipboardAction` on each click.\n */\n\n\nvar Clipboard = /*#__PURE__*/function (_Emitter) {\n _inherits(Clipboard, _Emitter);\n\n var _super = _createSuper(Clipboard);\n\n /**\n * @param {String|HTMLElement|HTMLCollection|NodeList} trigger\n * @param {Object} options\n */\n function Clipboard(trigger, options) {\n var _this;\n\n _classCallCheck(this, Clipboard);\n\n _this = _super.call(this);\n\n _this.resolveOptions(options);\n\n _this.listenClick(trigger);\n\n return _this;\n }\n /**\n * Defines if attributes would be resolved using internal setter functions\n * or custom functions that were passed in the constructor.\n * @param {Object} options\n */\n\n\n _createClass(Clipboard, [{\n key: \"resolveOptions\",\n value: function resolveOptions() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.action = typeof options.action === 'function' ? options.action : this.defaultAction;\n this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;\n this.text = typeof options.text === 'function' ? options.text : this.defaultText;\n this.container = clipboard_typeof(options.container) === 'object' ? options.container : document.body;\n }\n /**\n * Adds a click event listener to the passed trigger.\n * @param {String|HTMLElement|HTMLCollection|NodeList} trigger\n */\n\n }, {\n key: \"listenClick\",\n value: function listenClick(trigger) {\n var _this2 = this;\n\n this.listener = listen_default()(trigger, 'click', function (e) {\n return _this2.onClick(e);\n });\n }\n /**\n * Defines a new `ClipboardAction` on each click event.\n * @param {Event} e\n */\n\n }, {\n key: \"onClick\",\n value: function onClick(e) {\n var trigger = e.delegateTarget || e.currentTarget;\n var action = this.action(trigger) || 'copy';\n var text = actions_default({\n action: action,\n container: this.container,\n target: this.target(trigger),\n text: this.text(trigger)\n }); // Fires an event based on the copy operation result.\n\n this.emit(text ? 'success' : 'error', {\n action: action,\n text: text,\n trigger: trigger,\n clearSelection: function clearSelection() {\n if (trigger) {\n trigger.focus();\n }\n\n window.getSelection().removeAllRanges();\n }\n });\n }\n /**\n * Default `action` lookup function.\n * @param {Element} trigger\n */\n\n }, {\n key: \"defaultAction\",\n value: function defaultAction(trigger) {\n return getAttributeValue('action', trigger);\n }\n /**\n * Default `target` lookup function.\n * @param {Element} trigger\n */\n\n }, {\n key: \"defaultTarget\",\n value: function defaultTarget(trigger) {\n var selector = getAttributeValue('target', trigger);\n\n if (selector) {\n return document.querySelector(selector);\n }\n }\n /**\n * Allow fire programmatically a copy action\n * @param {String|HTMLElement} target\n * @param {Object} options\n * @returns Text copied.\n */\n\n }, {\n key: \"defaultText\",\n\n /**\n * Default `text` lookup function.\n * @param {Element} trigger\n */\n value: function defaultText(trigger) {\n return getAttributeValue('text', trigger);\n }\n /**\n * Destroy lifecycle.\n */\n\n }, {\n key: \"destroy\",\n value: function destroy() {\n this.listener.destroy();\n }\n }], [{\n key: \"copy\",\n value: function copy(target) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n container: document.body\n };\n return actions_copy(target, options);\n }\n /**\n * Allow fire programmatically a cut action\n * @param {String|HTMLElement} target\n * @returns Text cutted.\n */\n\n }, {\n key: \"cut\",\n value: function cut(target) {\n return actions_cut(target);\n }\n /**\n * Returns the support of the given action, or all actions if no action is\n * given.\n * @param {String} [action]\n */\n\n }, {\n key: \"isSupported\",\n value: function isSupported() {\n var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut'];\n var actions = typeof action === 'string' ? [action] : action;\n var support = !!document.queryCommandSupported;\n actions.forEach(function (action) {\n support = support && !!document.queryCommandSupported(action);\n });\n return support;\n }\n }]);\n\n return Clipboard;\n}((tiny_emitter_default()));\n\n/* harmony default export */ var clipboard = (Clipboard);\n\n/***/ }),\n\n/***/ 828:\n/***/ (function(module) {\n\nvar DOCUMENT_NODE_TYPE = 9;\n\n/**\n * A polyfill for Element.matches()\n */\nif (typeof Element !== 'undefined' && !Element.prototype.matches) {\n var proto = Element.prototype;\n\n proto.matches = proto.matchesSelector ||\n proto.mozMatchesSelector ||\n proto.msMatchesSelector ||\n proto.oMatchesSelector ||\n proto.webkitMatchesSelector;\n}\n\n/**\n * Finds the closest parent that matches a selector.\n *\n * @param {Element} element\n * @param {String} selector\n * @return {Function}\n */\nfunction closest (element, selector) {\n while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {\n if (typeof element.matches === 'function' &&\n element.matches(selector)) {\n return element;\n }\n element = element.parentNode;\n }\n}\n\nmodule.exports = closest;\n\n\n/***/ }),\n\n/***/ 438:\n/***/ (function(module, __unused_webpack_exports, __webpack_require__) {\n\nvar closest = __webpack_require__(828);\n\n/**\n * Delegates event to a selector.\n *\n * @param {Element} element\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @param {Boolean} useCapture\n * @return {Object}\n */\nfunction _delegate(element, selector, type, callback, useCapture) {\n var listenerFn = listener.apply(this, arguments);\n\n element.addEventListener(type, listenerFn, useCapture);\n\n return {\n destroy: function() {\n element.removeEventListener(type, listenerFn, useCapture);\n }\n }\n}\n\n/**\n * Delegates event to a selector.\n *\n * @param {Element|String|Array} [elements]\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @param {Boolean} useCapture\n * @return {Object}\n */\nfunction delegate(elements, selector, type, callback, useCapture) {\n // Handle the regular Element usage\n if (typeof elements.addEventListener === 'function') {\n return _delegate.apply(null, arguments);\n }\n\n // Handle Element-less usage, it defaults to global delegation\n if (typeof type === 'function') {\n // Use `document` as the first parameter, then apply arguments\n // This is a short way to .unshift `arguments` without running into deoptimizations\n return _delegate.bind(null, document).apply(null, arguments);\n }\n\n // Handle Selector-based usage\n if (typeof elements === 'string') {\n elements = document.querySelectorAll(elements);\n }\n\n // Handle Array-like based usage\n return Array.prototype.map.call(elements, function (element) {\n return _delegate(element, selector, type, callback, useCapture);\n });\n}\n\n/**\n * Finds closest match and invokes callback.\n *\n * @param {Element} element\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @return {Function}\n */\nfunction listener(element, selector, type, callback) {\n return function(e) {\n e.delegateTarget = closest(e.target, selector);\n\n if (e.delegateTarget) {\n callback.call(element, e);\n }\n }\n}\n\nmodule.exports = delegate;\n\n\n/***/ }),\n\n/***/ 879:\n/***/ (function(__unused_webpack_module, exports) {\n\n/**\n * Check if argument is a HTML element.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.node = function(value) {\n return value !== undefined\n && value instanceof HTMLElement\n && value.nodeType === 1;\n};\n\n/**\n * Check if argument is a list of HTML elements.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.nodeList = function(value) {\n var type = Object.prototype.toString.call(value);\n\n return value !== undefined\n && (type === '[object NodeList]' || type === '[object HTMLCollection]')\n && ('length' in value)\n && (value.length === 0 || exports.node(value[0]));\n};\n\n/**\n * Check if argument is a string.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.string = function(value) {\n return typeof value === 'string'\n || value instanceof String;\n};\n\n/**\n * Check if argument is a function.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.fn = function(value) {\n var type = Object.prototype.toString.call(value);\n\n return type === '[object Function]';\n};\n\n\n/***/ }),\n\n/***/ 370:\n/***/ (function(module, __unused_webpack_exports, __webpack_require__) {\n\nvar is = __webpack_require__(879);\nvar delegate = __webpack_require__(438);\n\n/**\n * Validates all params and calls the right\n * listener function based on its target type.\n *\n * @param {String|HTMLElement|HTMLCollection|NodeList} target\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listen(target, type, callback) {\n if (!target && !type && !callback) {\n throw new Error('Missing required arguments');\n }\n\n if (!is.string(type)) {\n throw new TypeError('Second argument must be a String');\n }\n\n if (!is.fn(callback)) {\n throw new TypeError('Third argument must be a Function');\n }\n\n if (is.node(target)) {\n return listenNode(target, type, callback);\n }\n else if (is.nodeList(target)) {\n return listenNodeList(target, type, callback);\n }\n else if (is.string(target)) {\n return listenSelector(target, type, callback);\n }\n else {\n throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');\n }\n}\n\n/**\n * Adds an event listener to a HTML element\n * and returns a remove listener function.\n *\n * @param {HTMLElement} node\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenNode(node, type, callback) {\n node.addEventListener(type, callback);\n\n return {\n destroy: function() {\n node.removeEventListener(type, callback);\n }\n }\n}\n\n/**\n * Add an event listener to a list of HTML elements\n * and returns a remove listener function.\n *\n * @param {NodeList|HTMLCollection} nodeList\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenNodeList(nodeList, type, callback) {\n Array.prototype.forEach.call(nodeList, function(node) {\n node.addEventListener(type, callback);\n });\n\n return {\n destroy: function() {\n Array.prototype.forEach.call(nodeList, function(node) {\n node.removeEventListener(type, callback);\n });\n }\n }\n}\n\n/**\n * Add an event listener to a selector\n * and returns a remove listener function.\n *\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenSelector(selector, type, callback) {\n return delegate(document.body, selector, type, callback);\n}\n\nmodule.exports = listen;\n\n\n/***/ }),\n\n/***/ 817:\n/***/ (function(module) {\n\nfunction select(element) {\n var selectedText;\n\n if (element.nodeName === 'SELECT') {\n element.focus();\n\n selectedText = element.value;\n }\n else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {\n var isReadOnly = element.hasAttribute('readonly');\n\n if (!isReadOnly) {\n element.setAttribute('readonly', '');\n }\n\n element.select();\n element.setSelectionRange(0, element.value.length);\n\n if (!isReadOnly) {\n element.removeAttribute('readonly');\n }\n\n selectedText = element.value;\n }\n else {\n if (element.hasAttribute('contenteditable')) {\n element.focus();\n }\n\n var selection = window.getSelection();\n var range = document.createRange();\n\n range.selectNodeContents(element);\n selection.removeAllRanges();\n selection.addRange(range);\n\n selectedText = selection.toString();\n }\n\n return selectedText;\n}\n\nmodule.exports = select;\n\n\n/***/ }),\n\n/***/ 279:\n/***/ (function(module) {\n\nfunction E () {\n // Keep this empty so it's easier to inherit from\n // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)\n}\n\nE.prototype = {\n on: function (name, callback, ctx) {\n var e = this.e || (this.e = {});\n\n (e[name] || (e[name] = [])).push({\n fn: callback,\n ctx: ctx\n });\n\n return this;\n },\n\n once: function (name, callback, ctx) {\n var self = this;\n function listener () {\n self.off(name, listener);\n callback.apply(ctx, arguments);\n };\n\n listener._ = callback\n return this.on(name, listener, ctx);\n },\n\n emit: function (name) {\n var data = [].slice.call(arguments, 1);\n var evtArr = ((this.e || (this.e = {}))[name] || []).slice();\n var i = 0;\n var len = evtArr.length;\n\n for (i; i < len; i++) {\n evtArr[i].fn.apply(evtArr[i].ctx, data);\n }\n\n return this;\n },\n\n off: function (name, callback) {\n var e = this.e || (this.e = {});\n var evts = e[name];\n var liveEvents = [];\n\n if (evts && callback) {\n for (var i = 0, len = evts.length; i < len; i++) {\n if (evts[i].fn !== callback && evts[i].fn._ !== callback)\n liveEvents.push(evts[i]);\n }\n }\n\n // Remove event from queue to prevent memory leak\n // Suggested by https://github.com/lazd\n // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910\n\n (liveEvents.length)\n ? e[name] = liveEvents\n : delete e[name];\n\n return this;\n }\n};\n\nmodule.exports = E;\nmodule.exports.TinyEmitter = E;\n\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(__webpack_module_cache__[moduleId]) {\n/******/ \t\t\treturn __webpack_module_cache__[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/compat get default export */\n/******/ \t!function() {\n/******/ \t\t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t\t__webpack_require__.n = function(module) {\n/******/ \t\t\tvar getter = module && module.__esModule ?\n/******/ \t\t\t\tfunction() { return module['default']; } :\n/******/ \t\t\t\tfunction() { return module; };\n/******/ \t\t\t__webpack_require__.d(getter, { a: getter });\n/******/ \t\t\treturn getter;\n/******/ \t\t};\n/******/ \t}();\n/******/ \t\n/******/ \t/* webpack/runtime/define property getters */\n/******/ \t!function() {\n/******/ \t\t// define getter functions for harmony exports\n/******/ \t\t__webpack_require__.d = function(exports, definition) {\n/******/ \t\t\tfor(var key in definition) {\n/******/ \t\t\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n/******/ \t\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n/******/ \t\t\t\t}\n/******/ \t\t\t}\n/******/ \t\t};\n/******/ \t}();\n/******/ \t\n/******/ \t/* webpack/runtime/hasOwnProperty shorthand */\n/******/ \t!function() {\n/******/ \t\t__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }\n/******/ \t}();\n/******/ \t\n/************************************************************************/\n/******/ \t// module exports must be returned from runtime so entry inlining is disabled\n/******/ \t// startup\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(686);\n/******/ })()\n.default;\n});", "/*!\n * escape-html\n * Copyright(c) 2012-2013 TJ Holowaychuk\n * Copyright(c) 2015 Andreas Lubbe\n * Copyright(c) 2015 Tiancheng \"Timothy\" Gu\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module variables.\n * @private\n */\n\nvar matchHtmlRegExp = /[\"'&<>]/;\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = escapeHtml;\n\n/**\n * Escape special characters in the given string of html.\n *\n * @param {string} string The string to escape for inserting into HTML\n * @return {string}\n * @public\n */\n\nfunction escapeHtml(string) {\n var str = '' + string;\n var match = matchHtmlRegExp.exec(str);\n\n if (!match) {\n return str;\n }\n\n var escape;\n var html = '';\n var index = 0;\n var lastIndex = 0;\n\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escape = '"';\n break;\n case 38: // &\n escape = '&';\n break;\n case 39: // '\n escape = ''';\n break;\n case 60: // <\n escape = '<';\n break;\n case 62: // >\n escape = '>';\n break;\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.substring(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escape;\n }\n\n return lastIndex !== index\n ? html + str.substring(lastIndex, index)\n : html;\n}\n", "/*\n * Copyright (c) 2016-2024 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport \"focus-visible\"\n\nimport {\n EMPTY,\n NEVER,\n Observable,\n Subject,\n defer,\n delay,\n filter,\n map,\n merge,\n mergeWith,\n shareReplay,\n switchMap\n} from \"rxjs\"\n\nimport { configuration, feature } from \"./_\"\nimport {\n at,\n getActiveElement,\n getOptionalElement,\n requestJSON,\n setLocation,\n setToggle,\n watchDocument,\n watchKeyboard,\n watchLocation,\n watchLocationTarget,\n watchMedia,\n watchPrint,\n watchScript,\n watchViewport\n} from \"./browser\"\nimport {\n getComponentElement,\n getComponentElements,\n mountAnnounce,\n mountBackToTop,\n mountConsent,\n mountContent,\n mountDialog,\n mountHeader,\n mountHeaderTitle,\n mountPalette,\n mountProgress,\n mountSearch,\n mountSearchHiglight,\n mountSidebar,\n mountSource,\n mountTableOfContents,\n mountTabs,\n watchHeader,\n watchMain\n} from \"./components\"\nimport {\n SearchIndex,\n setupClipboardJS,\n setupInstantNavigation,\n setupVersionSelector\n} from \"./integrations\"\nimport {\n patchEllipsis,\n patchIndeterminate,\n patchScrollfix,\n patchScrolllock\n} from \"./patches\"\nimport \"./polyfills\"\n\n/* ----------------------------------------------------------------------------\n * Functions - @todo refactor\n * ------------------------------------------------------------------------- */\n\n/**\n * Fetch search index\n *\n * @returns Search index observable\n */\nfunction fetchSearchIndex(): Observable {\n if (location.protocol === \"file:\") {\n return watchScript(\n `${new URL(\"search/search_index.js\", config.base)}`\n )\n .pipe(\n // @ts-ignore - @todo fix typings\n map(() => __index),\n shareReplay(1)\n )\n } else {\n return requestJSON(\n new URL(\"search/search_index.json\", config.base)\n )\n }\n}\n\n/* ----------------------------------------------------------------------------\n * Application\n * ------------------------------------------------------------------------- */\n\n/* Yay, JavaScript is available */\ndocument.documentElement.classList.remove(\"no-js\")\ndocument.documentElement.classList.add(\"js\")\n\n/* Set up navigation observables and subjects */\nconst document$ = watchDocument()\nconst location$ = watchLocation()\nconst target$ = watchLocationTarget(location$)\nconst keyboard$ = watchKeyboard()\n\n/* Set up media observables */\nconst viewport$ = watchViewport()\nconst tablet$ = watchMedia(\"(min-width: 960px)\")\nconst screen$ = watchMedia(\"(min-width: 1220px)\")\nconst print$ = watchPrint()\n\n/* Retrieve search index, if search is enabled */\nconst config = configuration()\nconst index$ = document.forms.namedItem(\"search\")\n ? fetchSearchIndex()\n : NEVER\n\n/* Set up Clipboard.js integration */\nconst alert$ = new Subject()\nsetupClipboardJS({ alert$ })\n\n/* Set up progress indicator */\nconst progress$ = new Subject()\n\n/* Set up instant navigation, if enabled */\nif (feature(\"navigation.instant\"))\n setupInstantNavigation({ location$, viewport$, progress$ })\n .subscribe(document$)\n\n/* Set up version selector */\nif (config.version?.provider === \"mike\")\n setupVersionSelector({ document$ })\n\n/* Always close drawer and search on navigation */\nmerge(location$, target$)\n .pipe(\n delay(125)\n )\n .subscribe(() => {\n setToggle(\"drawer\", false)\n setToggle(\"search\", false)\n })\n\n/* Set up global keyboard handlers */\nkeyboard$\n .pipe(\n filter(({ mode }) => mode === \"global\")\n )\n .subscribe(key => {\n switch (key.type) {\n\n /* Go to previous page */\n case \"p\":\n case \",\":\n const prev = getOptionalElement(\"link[rel=prev]\")\n if (typeof prev !== \"undefined\")\n setLocation(prev)\n break\n\n /* Go to next page */\n case \"n\":\n case \".\":\n const next = getOptionalElement(\"link[rel=next]\")\n if (typeof next !== \"undefined\")\n setLocation(next)\n break\n\n /* Expand navigation, see https://bit.ly/3ZjG5io */\n case \"Enter\":\n const active = getActiveElement()\n if (active instanceof HTMLLabelElement)\n active.click()\n }\n })\n\n/* Set up patches */\npatchEllipsis({ viewport$, document$ })\npatchIndeterminate({ document$, tablet$ })\npatchScrollfix({ document$ })\npatchScrolllock({ viewport$, tablet$ })\n\n/* Set up header and main area observable */\nconst header$ = watchHeader(getComponentElement(\"header\"), { viewport$ })\nconst main$ = document$\n .pipe(\n map(() => getComponentElement(\"main\")),\n switchMap(el => watchMain(el, { viewport$, header$ })),\n shareReplay(1)\n )\n\n/* Set up control component observables */\nconst control$ = merge(\n\n /* Consent */\n ...getComponentElements(\"consent\")\n .map(el => mountConsent(el, { target$ })),\n\n /* Dialog */\n ...getComponentElements(\"dialog\")\n .map(el => mountDialog(el, { alert$ })),\n\n /* Header */\n ...getComponentElements(\"header\")\n .map(el => mountHeader(el, { viewport$, header$, main$ })),\n\n /* Color palette */\n ...getComponentElements(\"palette\")\n .map(el => mountPalette(el)),\n\n /* Progress bar */\n ...getComponentElements(\"progress\")\n .map(el => mountProgress(el, { progress$ })),\n\n /* Search */\n ...getComponentElements(\"search\")\n .map(el => mountSearch(el, { index$, keyboard$ })),\n\n /* Repository information */\n ...getComponentElements(\"source\")\n .map(el => mountSource(el))\n)\n\n/* Set up content component observables */\nconst content$ = defer(() => merge(\n\n /* Announcement bar */\n ...getComponentElements(\"announce\")\n .map(el => mountAnnounce(el)),\n\n /* Content */\n ...getComponentElements(\"content\")\n .map(el => mountContent(el, { viewport$, target$, print$ })),\n\n /* Search highlighting */\n ...getComponentElements(\"content\")\n .map(el => feature(\"search.highlight\")\n ? mountSearchHiglight(el, { index$, location$ })\n : EMPTY\n ),\n\n /* Header title */\n ...getComponentElements(\"header-title\")\n .map(el => mountHeaderTitle(el, { viewport$, header$ })),\n\n /* Sidebar */\n ...getComponentElements(\"sidebar\")\n .map(el => el.getAttribute(\"data-md-type\") === \"navigation\"\n ? at(screen$, () => mountSidebar(el, { viewport$, header$, main$ }))\n : at(tablet$, () => mountSidebar(el, { viewport$, header$, main$ }))\n ),\n\n /* Navigation tabs */\n ...getComponentElements(\"tabs\")\n .map(el => mountTabs(el, { viewport$, header$ })),\n\n /* Table of contents */\n ...getComponentElements(\"toc\")\n .map(el => mountTableOfContents(el, {\n viewport$, header$, main$, target$\n })),\n\n /* Back-to-top button */\n ...getComponentElements(\"top\")\n .map(el => mountBackToTop(el, { viewport$, header$, main$, target$ }))\n))\n\n/* Set up component observables */\nconst component$ = document$\n .pipe(\n switchMap(() => content$),\n mergeWith(control$),\n shareReplay(1)\n )\n\n/* Subscribe to all components */\ncomponent$.subscribe()\n\n/* ----------------------------------------------------------------------------\n * Exports\n * ------------------------------------------------------------------------- */\n\nwindow.document$ = document$ /* Document observable */\nwindow.location$ = location$ /* Location subject */\nwindow.target$ = target$ /* Location target observable */\nwindow.keyboard$ = keyboard$ /* Keyboard observable */\nwindow.viewport$ = viewport$ /* Viewport observable */\nwindow.tablet$ = tablet$ /* Media tablet observable */\nwindow.screen$ = screen$ /* Media screen observable */\nwindow.print$ = print$ /* Media print observable */\nwindow.alert$ = alert$ /* Alert subject */\nwindow.progress$ = progress$ /* Progress indicator subject */\nwindow.component$ = component$ /* Component observable */\n", "/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n", "/**\n * Returns true if the object is a function.\n * @param value The value to check\n */\nexport function isFunction(value: any): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n", "/**\n * Used to create Error subclasses until the community moves away from ES5.\n *\n * This is because compiling from TypeScript down to ES5 has issues with subclassing Errors\n * as well as other built-in types: https://github.com/Microsoft/TypeScript/issues/12123\n *\n * @param createImpl A factory function to create the actual constructor implementation. The returned\n * function should be a named function that calls `_super` internally.\n */\nexport function createErrorClass(createImpl: (_super: any) => any): T {\n const _super = (instance: any) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (errors: any[]): UnsubscriptionError;\n}\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = createErrorClass(\n (_super) =>\n function UnsubscriptionErrorImpl(this: any, errors: (Error | string)[]) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n }\n);\n", "/**\n * Removes an item from an array, mutating it.\n * @param arr The array to remove the item from\n * @param item The item to remove\n */\nexport function arrRemove(arr: T[] | undefined | null, item: T) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';\nimport { arrRemove } from './util/arrRemove';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n /** @nocollapse */\n public static EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n */\n public closed = false;\n\n private _parentage: Subscription[] | Subscription | null = null;\n\n /**\n * The list of registered finalizers to execute upon unsubscription. Adding and removing from this\n * list occurs in the {@link #add} and {@link #remove} methods.\n */\n private _finalizers: Exclude[] | null = null;\n\n /**\n * @param initialTeardown A function executed first as part of the finalization\n * process that is kicked off when {@link #unsubscribe} is called.\n */\n constructor(private initialTeardown?: () => void) {}\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n * @return {void}\n */\n unsubscribe(): void {\n let errors: any[] | undefined;\n\n if (!this.closed) {\n this.closed = true;\n\n // Remove this from it's parents.\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n } else {\n _parentage.remove(this);\n }\n }\n\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n } catch (err) {\n errors = errors ?? [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n } else {\n errors.push(err);\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n\n /**\n * Adds a finalizer to this subscription, so that finalization will be unsubscribed/called\n * when this subscription is unsubscribed. If this subscription is already {@link #closed},\n * because it has already been unsubscribed, then whatever finalizer is passed to it\n * will automatically be executed (unless the finalizer itself is also a closed subscription).\n *\n * Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed\n * subscription to a any subscription will result in no operation. (A noop).\n *\n * Adding a subscription to itself, or adding `null` or `undefined` will not perform any\n * operation at all. (A noop).\n *\n * `Subscription` instances that are added to this instance will automatically remove themselves\n * if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove\n * will need to be removed manually with {@link #remove}\n *\n * @param teardown The finalization logic to add to this subscription.\n */\n add(teardown: TeardownLogic): void {\n // Only add the finalizer if it's not undefined\n // and don't add a subscription to itself.\n if (teardown && teardown !== this) {\n if (this.closed) {\n // If this subscription is already closed,\n // execute whatever finalizer is handed to it automatically.\n execFinalizer(teardown);\n } else {\n if (teardown instanceof Subscription) {\n // We don't add closed subscriptions, and we don't add the same subscription\n // twice. Subscription unsubscribe is idempotent.\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = this._finalizers ?? []).push(teardown);\n }\n }\n }\n\n /**\n * Checks to see if a this subscription already has a particular parent.\n * This will signal that this subscription has already been added to the parent in question.\n * @param parent the parent to check for\n */\n private _hasParent(parent: Subscription) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n\n /**\n * Adds a parent to this subscription so it can be removed from the parent if it\n * unsubscribes on it's own.\n *\n * NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.\n * @param parent The parent subscription to add\n */\n private _addParent(parent: Subscription) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n\n /**\n * Called on a child when it is removed via {@link #remove}.\n * @param parent The parent to remove\n */\n private _removeParent(parent: Subscription) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n } else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n\n /**\n * Removes a finalizer from this subscription that was previously added with the {@link #add} method.\n *\n * Note that `Subscription` instances, when unsubscribed, will automatically remove themselves\n * from every other `Subscription` they have been added to. This means that using the `remove` method\n * is not a common thing and should be used thoughtfully.\n *\n * If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance\n * more than once, you will need to call `remove` the same number of times to remove all instances.\n *\n * All finalizer instances are removed to free up memory upon unsubscription.\n *\n * @param teardown The finalizer to remove from this subscription\n */\n remove(teardown: Exclude): void {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\n\nexport const EMPTY_SUBSCRIPTION = Subscription.EMPTY;\n\nexport function isSubscription(value: any): value is Subscription {\n return (\n value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))\n );\n}\n\nfunction execFinalizer(finalizer: Unsubscribable | (() => void)) {\n if (isFunction(finalizer)) {\n finalizer();\n } else {\n finalizer.unsubscribe();\n }\n}\n", "import { Subscriber } from './Subscriber';\nimport { ObservableNotification } from './types';\n\n/**\n * The {@link GlobalConfig} object for RxJS. It is used to configure things\n * like how to react on unhandled errors.\n */\nexport const config: GlobalConfig = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like how to react on unhandled errors. Accessible via {@link config}\n * object.\n */\nexport interface GlobalConfig {\n /**\n * A registration point for unhandled errors from RxJS. These are errors that\n * cannot were not handled by consuming code in the usual subscription path. For\n * example, if you have this configured, and you subscribe to an observable without\n * providing an error handler, errors from that subscription will end up here. This\n * will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onUnhandledError: ((err: any) => void) | null;\n\n /**\n * A registration point for notifications that cannot be sent to subscribers because they\n * have completed, errored or have been explicitly unsubscribed. By default, next, complete\n * and error notifications sent to stopped subscribers are noops. However, sometimes callers\n * might want a different behavior. For example, with sources that attempt to report errors\n * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.\n * This will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onStoppedNotification: ((notification: ObservableNotification, subscriber: Subscriber) => void) | null;\n\n /**\n * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}\n * methods.\n *\n * @deprecated As of version 8, RxJS will no longer support this sort of injection of a\n * Promise constructor. If you need a Promise implementation other than native promises,\n * please polyfill/patch Promise as you see appropriate. Will be removed in v8.\n */\n Promise?: PromiseConstructorLike;\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME\n * FOR MIGRATION REASONS.\n *\n * @deprecated As of version 8, RxJS will no longer support synchronous throwing\n * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad\n * behaviors described above. Will be removed in v8.\n */\n useDeprecatedSynchronousErrorHandling: boolean;\n\n /**\n * If true, enables an as-of-yet undocumented feature from v5: The ability to access\n * `unsubscribe()` via `this` context in `next` functions created in observers passed\n * to `subscribe`.\n *\n * This is being removed because the performance was severely problematic, and it could also cause\n * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have\n * their `this` context overwritten.\n *\n * @deprecated As of version 8, RxJS will no longer support altering the\n * context of next functions provided as part of an observer to Subscribe. Instead,\n * you will have access to a subscription or a signal or token that will allow you to do things like\n * unsubscribe and test closed status. Will be removed in v8.\n */\n useDeprecatedNextContext: boolean;\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetTimeoutFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearTimeoutFunction = (handle: TimerHandle) => void;\n\ninterface TimeoutProvider {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n delegate:\n | {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n }\n | undefined;\n}\n\nexport const timeoutProvider: TimeoutProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setTimeout(handler: () => void, timeout?: number, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate?.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return (delegate?.clearTimeout || clearTimeout)(handle as any);\n },\n delegate: undefined,\n};\n", "import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\n\n/**\n * Handles an error on another job either with the user-configured {@link onUnhandledError},\n * or by throwing it on that new job so it can be picked up by `window.onerror`, `process.on('error')`, etc.\n *\n * This should be called whenever there is an error that is out-of-band with the subscription\n * or when an error hits a terminal boundary of the subscription and no error handler was provided.\n *\n * @param err the error to report\n */\nexport function reportUnhandledError(err: any) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n // Execute the user-configured error handler.\n onUnhandledError(err);\n } else {\n // Throw so it is picked up by the runtime's uncaught error mechanism.\n throw err;\n }\n });\n}\n", "/* tslint:disable:no-empty */\nexport function noop() { }\n", "import { CompleteNotification, NextNotification, ErrorNotification } from './types';\n\n/**\n * A completion object optimized for memory use and created to be the\n * same \"shape\" as other notifications in v8.\n * @internal\n */\nexport const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();\n\n/**\n * Internal use only. Creates an optimized error notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function errorNotification(error: any): ErrorNotification {\n return createNotification('E', undefined, error) as any;\n}\n\n/**\n * Internal use only. Creates an optimized next notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function nextNotification(value: T) {\n return createNotification('N', value, undefined) as NextNotification;\n}\n\n/**\n * Ensures that all notifications created internally have the same \"shape\" in v8.\n *\n * TODO: This is only exported to support a crazy legacy test in `groupBy`.\n * @internal\n */\nexport function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {\n return {\n kind,\n value,\n error,\n };\n}\n", "import { config } from '../config';\n\nlet context: { errorThrown: boolean; error: any } | null = null;\n\n/**\n * Handles dealing with errors for super-gross mode. Creates a context, in which\n * any synchronously thrown errors will be passed to {@link captureError}. Which\n * will record the error such that it will be rethrown after the call back is complete.\n * TODO: Remove in v8\n * @param cb An immediately executed function.\n */\nexport function errorContext(cb: () => void) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context!;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n } else {\n // This is the general non-deprecated path for everyone that\n // isn't crazy enough to use super-gross mode (useDeprecatedSynchronousErrorHandling)\n cb();\n }\n}\n\n/**\n * Captures errors only in super-gross mode.\n * @param err the error to capture\n */\nexport function captureError(err: any) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { Observer, ObservableNotification } from './types';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber\n */\nexport class Subscriber extends Subscription implements Observer {\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param next The `next` callback of an Observer.\n * @param error The `error` callback of an\n * Observer.\n * @param complete The `complete` callback of an\n * Observer.\n * @return A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @nocollapse\n * @deprecated Do not use. Will be removed in v8. There is no replacement for this\n * method, and there is no reason to be creating instances of `Subscriber` directly.\n * If you have a specific use case, please file an issue.\n */\n static create(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber {\n return new SafeSubscriber(next, error, complete);\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected isStopped: boolean = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected destination: Subscriber | Observer; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.\n */\n constructor(destination?: Subscriber | Observer) {\n super();\n if (destination) {\n this.destination = destination;\n // Automatically chain subscriptions together here.\n // if destination is a Subscription, then it is a Subscriber.\n if (isSubscription(destination)) {\n destination.add(this);\n }\n } else {\n this.destination = EMPTY_OBSERVER;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param {T} [value] The `next` value.\n * @return {void}\n */\n next(value?: T): void {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n } else {\n this._next(value!);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param {any} [err] The `error` exception.\n * @return {void}\n */\n error(err?: any): void {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n } else {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n * @return {void}\n */\n complete(): void {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n } else {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null!;\n }\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n try {\n this.destination.error(err);\n } finally {\n this.unsubscribe();\n }\n }\n\n protected _complete(): void {\n try {\n this.destination.complete();\n } finally {\n this.unsubscribe();\n }\n }\n}\n\n/**\n * This bind is captured here because we want to be able to have\n * compatibility with monoid libraries that tend to use a method named\n * `bind`. In particular, a library called Monio requires this.\n */\nconst _bind = Function.prototype.bind;\n\nfunction bind any>(fn: Fn, thisArg: any): Fn {\n return _bind.call(fn, thisArg);\n}\n\n/**\n * Internal optimization only, DO NOT EXPOSE.\n * @internal\n */\nclass ConsumerObserver implements Observer {\n constructor(private partialObserver: Partial>) {}\n\n next(value: T): void {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n\n error(err: any): void {\n const { partialObserver } = this;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n } catch (error) {\n handleUnhandledError(error);\n }\n } else {\n handleUnhandledError(err);\n }\n }\n\n complete(): void {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\n\nexport class SafeSubscriber extends Subscriber {\n constructor(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((e?: any) => void) | null,\n complete?: (() => void) | null\n ) {\n super();\n\n let partialObserver: Partial>;\n if (isFunction(observerOrNext) || !observerOrNext) {\n // The first argument is a function, not an observer. The next\n // two arguments *could* be observers, or they could be empty.\n partialObserver = {\n next: (observerOrNext ?? undefined) as (((value: T) => void) | undefined),\n error: error ?? undefined,\n complete: complete ?? undefined,\n };\n } else {\n // The first argument is a partial observer.\n let context: any;\n if (this && config.useDeprecatedNextContext) {\n // This is a deprecated path that made `this.unsubscribe()` available in\n // next handler functions passed to subscribe. This only exists behind a flag\n // now, as it is *very* slow.\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n } else {\n // The \"normal\" path. Just use the partial observer directly.\n partialObserver = observerOrNext;\n }\n }\n\n // Wrap the partial observer to ensure it's a full observer, and\n // make sure proper error handling is accounted for.\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\n\nfunction handleUnhandledError(error: any) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n } else {\n // Ideal path, we report this as an unhandled error,\n // which is thrown on a new call stack.\n reportUnhandledError(error);\n }\n}\n\n/**\n * An error handler used when no error handler was supplied\n * to the SafeSubscriber -- meaning no error handler was supplied\n * do the `subscribe` call on our observable.\n * @param err The error to handle\n */\nfunction defaultErrorHandler(err: any) {\n throw err;\n}\n\n/**\n * A handler for notifications that cannot be sent to a stopped subscriber.\n * @param notification The notification being sent\n * @param subscriber The stopped subscriber\n */\nfunction handleStoppedNotification(notification: ObservableNotification, subscriber: Subscriber) {\n const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\n\n/**\n * The observer used as a stub for subscriptions where the user did not\n * pass any arguments to `subscribe`. Comes with the default error handling\n * behavior.\n */\nexport const EMPTY_OBSERVER: Readonly> & { closed: true } = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n", "/**\n * Symbol.observable or a string \"@@observable\". Used for interop\n *\n * @deprecated We will no longer be exporting this symbol in upcoming versions of RxJS.\n * Instead polyfill and use Symbol.observable directly *or* use https://www.npmjs.com/package/symbol-observable\n */\nexport const observable: string | symbol = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n", "/**\n * This function takes one parameter and just returns it. Simply put,\n * this is like `(x: T): T => x`.\n *\n * ## Examples\n *\n * This is useful in some cases when using things like `mergeMap`\n *\n * ```ts\n * import { interval, take, map, range, mergeMap, identity } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(5));\n *\n * const result$ = source$.pipe(\n * map(i => range(i)),\n * mergeMap(identity) // same as mergeMap(x => x)\n * );\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * Or when you want to selectively apply an operator\n *\n * ```ts\n * import { interval, take, identity } from 'rxjs';\n *\n * const shouldLimit = () => Math.random() < 0.5;\n *\n * const source$ = interval(1000);\n *\n * const result$ = source$.pipe(shouldLimit() ? take(5) : identity);\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * @param x Any value that is returned by this function\n * @returns The value passed as the first parameter to this function\n */\nexport function identity(x: T): T {\n return x;\n}\n", "import { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\nexport function pipe(): typeof identity;\nexport function pipe(fn1: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction, fn3: UnaryFunction): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction,\n ...fns: UnaryFunction[]\n): UnaryFunction;\n\n/**\n * pipe() can be called on one or more functions, each of which can take one argument (\"UnaryFunction\")\n * and uses it to return a value.\n * It returns a function that takes one argument, passes it to the first UnaryFunction, and then\n * passes the result to the next one, passes that result to the next one, and so on. \n */\nexport function pipe(...fns: Array>): UnaryFunction {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray(fns: Array>): UnaryFunction {\n if (fns.length === 0) {\n return identity as UnaryFunction;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction) => fn(prev), input as any);\n };\n}\n", "import { Operator } from './Operator';\nimport { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription, Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable\n */\nexport class Observable implements Subscribable {\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n source: Observable | undefined;\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n operator: Operator | undefined;\n\n /**\n * @constructor\n * @param {Function} subscribe the function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable, subscriber: Subscriber) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new Observable by calling the Observable constructor\n * @owner Observable\n * @method create\n * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n * @return {Observable} a new observable\n * @nocollapse\n * @deprecated Use `new Observable()` instead. Will be removed in v8.\n */\n static create: (...args: any[]) => any = (subscribe?: (subscriber: Subscriber) => TeardownLogic) => {\n return new Observable(subscribe);\n };\n\n /**\n * Creates a new Observable, with this Observable instance as the source, and the passed\n * operator defined as the new observable's operator.\n * @method lift\n * @param operator the operator defining the operation to take on the observable\n * @return a new observable with the Operator applied\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * If you have implemented an operator using `lift`, it is recommended that you create an\n * operator by simply returning `new Observable()` directly. See \"Creating new operators from\n * scratch\" section here: https://rxjs.dev/guide/operators\n */\n lift(operator?: Operator): Observable {\n const observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observerOrNext?: Partial> | ((value: T) => void)): Subscription;\n /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\n subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * Use it when you have all these Observables, but still nothing is happening.\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,\n * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,\n * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or\n * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide\n * an `error` method to avoid missing thrown errors.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,\n * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.\n *\n * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events\n * and you also handled emissions internally by using operators (e.g. using `tap`).\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * #### Examples\n *\n * Subscribe with an {@link guide/observer Observer}\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})\n *\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Cancel a subscription\n *\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe({\n * next(num) {\n * console.log(num)\n * },\n * complete() {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * });\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 'unsubscribed!' after 2.5s\n * ```\n *\n * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n * or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n * Observable.\n * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown asynchronously as unhandled.\n * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n * @return {Subscription} a subscription reference to the registered handlers\n * @method subscribe\n */\n subscribe(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n ): Subscription {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n\n errorContext(() => {\n const { operator, source } = this;\n subscriber.add(\n operator\n ? // We're dealing with a subscription in the\n // operator chain to one of our lifted operators.\n operator.call(subscriber, source)\n : source\n ? // If `source` has a value, but `operator` does not, something that\n // had intimate knowledge of our API, like our `Subject`, must have\n // set it. We're going to just call `_subscribe` directly.\n this._subscribe(subscriber)\n : // In all other cases, we're likely wrapping a user-provided initializer\n // function, so we need to catch errors and handle them appropriately.\n this._trySubscribe(subscriber)\n );\n });\n\n return subscriber;\n }\n\n /** @internal */\n protected _trySubscribe(sink: Subscriber): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n // We don't need to return anything in this case,\n // because it's just going to try to `add()` to a subscription\n // above.\n sink.error(err);\n }\n }\n\n /**\n * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with\n * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * #### Example\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(4));\n *\n * async function getTotal() {\n * let total = 0;\n *\n * await source$.forEach(value => {\n * total += value;\n * console.log('observable -> ' + value);\n * });\n *\n * return total;\n * }\n *\n * getTotal().then(\n * total => console.log('Total: ' + total)\n * );\n *\n * // Expected:\n * // 'observable -> 0'\n * // 'observable -> 1'\n * // 'observable -> 2'\n * // 'observable -> 3'\n * // 'Total: 6'\n * ```\n *\n * @param next a handler for each value emitted by the observable\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n */\n forEach(next: (value: T) => void): Promise;\n\n /**\n * @param next a handler for each value emitted by the observable\n * @param promiseCtor a constructor function used to instantiate the Promise\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n * @deprecated Passing a Promise constructor will no longer be available\n * in upcoming versions of RxJS. This is because it adds weight to the library, for very\n * little benefit. If you need this functionality, it is recommended that you either\n * polyfill Promise, or you create an adapter to convert the returned native promise\n * to whatever promise implementation you wanted. Will be removed in v8.\n */\n forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise;\n\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n const subscriber = new SafeSubscriber({\n next: (value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n this.subscribe(subscriber);\n }) as Promise;\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): TeardownLogic {\n return this.source?.subscribe(subscriber);\n }\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @method Symbol.observable\n * @return {Observable} this instance of the observable\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable;\n pipe(op1: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction,\n ...operations: OperatorFunction[]\n ): Observable;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n * @method pipe\n * @return {Observable} the Observable result of all of the operators having\n * been called in the order they were passed in.\n *\n * ## Example\n *\n * ```ts\n * import { interval, filter, map, scan } from 'rxjs';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x));\n * ```\n */\n pipe(...operations: OperatorFunction[]): Observable {\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: typeof Promise): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: PromiseConstructorLike): Promise;\n /* tslint:enable:max-line-length */\n\n /**\n * Subscribe to this Observable and get a Promise resolving on\n * `complete` with the last emission (if any).\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * @method toPromise\n * @param [promiseCtor] a constructor function used to instantiate\n * the Promise\n * @return A Promise that resolves with the last value emit, or\n * rejects on an error. If there were no emissions, Promise\n * resolves with undefined.\n * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise\n */\n toPromise(promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: T | undefined;\n this.subscribe(\n (x: T) => (value = x),\n (err: any) => reject(err),\n () => resolve(value)\n );\n }) as Promise;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n return promiseCtor ?? config.Promise ?? Promise;\n}\n\nfunction isObserver(value: any): value is Observer {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\n\nfunction isSubscriber(value: any): value is Subscriber {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n", "import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\nimport { isFunction } from './isFunction';\n\n/**\n * Used to determine if an object is an Observable with a lift function.\n */\nexport function hasLift(source: any): source is { lift: InstanceType['lift'] } {\n return isFunction(source?.lift);\n}\n\n/**\n * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way.\n * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription.\n */\nexport function operate(\n init: (liftedSource: Observable, subscriber: Subscriber) => (() => void) | void\n): OperatorFunction {\n return (source: Observable) => {\n if (hasLift(source)) {\n return source.lift(function (this: Subscriber, liftedSource: Observable) {\n try {\n return init(liftedSource, this);\n } catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n", "import { Subscriber } from '../Subscriber';\n\n/**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional teardown logic here. This will only be called on teardown if the\n * subscriber itself is not already closed. This is called after all other teardown logic is executed.\n */\nexport function createOperatorSubscriber(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n onFinalize?: () => void\n): Subscriber {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\n\n/**\n * A generic helper for allowing operators to be created with a Subscriber and\n * use closures to capture necessary state from the operator function itself.\n */\nexport class OperatorSubscriber extends Subscriber {\n /**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional finalization logic here. This will only be called on finalization if the\n * subscriber itself is not already closed. This is called after all other finalization logic is executed.\n * @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.\n * NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription\n * to the resulting observable does not actually disconnect from the source if there are active subscriptions\n * to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)\n */\n constructor(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n private onFinalize?: () => void,\n private shouldUnsubscribe?: () => boolean\n ) {\n // It's important - for performance reasons - that all of this class's\n // members are initialized and that they are always initialized in the same\n // order. This will ensure that all OperatorSubscriber instances have the\n // same hidden class in V8. This, in turn, will help keep the number of\n // hidden classes involved in property accesses within the base class as\n // low as possible. If the number of hidden classes involved exceeds four,\n // the property accesses will become megamorphic and performance penalties\n // will be incurred - i.e. inline caches won't be used.\n //\n // The reasons for ensuring all instances have the same hidden class are\n // further discussed in this blog post from Benedikt Meurer:\n // https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/\n super(destination);\n this._next = onNext\n ? function (this: OperatorSubscriber, value: T) {\n try {\n onNext(value);\n } catch (err) {\n destination.error(err);\n }\n }\n : super._next;\n this._error = onError\n ? function (this: OperatorSubscriber, err: any) {\n try {\n onError(err);\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._error;\n this._complete = onComplete\n ? function (this: OperatorSubscriber) {\n try {\n onComplete();\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._complete;\n }\n\n unsubscribe() {\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n // Execute additional teardown if we have any and we didn't already do so.\n !closed && this.onFinalize?.();\n }\n }\n}\n", "import { Subscription } from '../Subscription';\n\ninterface AnimationFrameProvider {\n schedule(callback: FrameRequestCallback): Subscription;\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n delegate:\n | {\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n }\n | undefined;\n}\n\nexport const animationFrameProvider: AnimationFrameProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n schedule(callback) {\n let request = requestAnimationFrame;\n let cancel: typeof cancelAnimationFrame | undefined = cancelAnimationFrame;\n const { delegate } = animationFrameProvider;\n if (delegate) {\n request = delegate.requestAnimationFrame;\n cancel = delegate.cancelAnimationFrame;\n }\n const handle = request((timestamp) => {\n // Clear the cancel function. The request has been fulfilled, so\n // attempting to cancel the request upon unsubscription would be\n // pointless.\n cancel = undefined;\n callback(timestamp);\n });\n return new Subscription(() => cancel?.(handle));\n },\n requestAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.requestAnimationFrame || requestAnimationFrame)(...args);\n },\n cancelAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.cancelAnimationFrame || cancelAnimationFrame)(...args);\n },\n delegate: undefined,\n};\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface ObjectUnsubscribedError extends Error {}\n\nexport interface ObjectUnsubscribedErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ObjectUnsubscribedError;\n}\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = createErrorClass(\n (_super) =>\n function ObjectUnsubscribedErrorImpl(this: any) {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n }\n);\n", "import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n */\nexport class Subject extends Observable implements SubscriptionLike {\n closed = false;\n\n private currentObservers: Observer[] | null = null;\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n observers: Observer[] = [];\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n isStopped = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n hasError = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n thrownError: any = null;\n\n /**\n * Creates a \"subject\" by basically gluing an observer to an observable.\n *\n * @nocollapse\n * @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.\n */\n static create: (...args: any[]) => any = (destination: Observer, source: Observable): AnonymousSubject => {\n return new AnonymousSubject(destination, source);\n };\n\n constructor() {\n // NOTE: This must be here to obscure Observable's constructor.\n super();\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n lift(operator: Operator): Observable {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator as any;\n return subject as any;\n }\n\n /** @internal */\n protected _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n\n next(value: T) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n\n error(err: any) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.error(err);\n }\n }\n });\n }\n\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.complete();\n }\n }\n });\n }\n\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null!;\n }\n\n get observed() {\n return this.observers?.length > 0;\n }\n\n /** @internal */\n protected _trySubscribe(subscriber: Subscriber): TeardownLogic {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n\n /** @internal */\n protected _innerSubscribe(subscriber: Subscriber) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped) {\n subscriber.complete();\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create custom Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return {Observable} Observable that the Subject casts to\n */\n asObservable(): Observable {\n const observable: any = new Observable();\n observable.source = this;\n return observable;\n }\n}\n\n/**\n * @class AnonymousSubject\n */\nexport class AnonymousSubject extends Subject {\n constructor(\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n public destination?: Observer,\n source?: Observable\n ) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n this.destination?.next?.(value);\n }\n\n error(err: any) {\n this.destination?.error?.(err);\n }\n\n complete() {\n this.destination?.complete?.();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;\n }\n}\n", "import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\n\n/**\n * A variant of Subject that requires an initial value and emits its current\n * value whenever it is subscribed to.\n *\n * @class BehaviorSubject\n */\nexport class BehaviorSubject extends Subject {\n constructor(private _value: T) {\n super();\n }\n\n get value(): T {\n return this.getValue();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n const subscription = super._subscribe(subscriber);\n !subscription.closed && subscriber.next(this._value);\n return subscription;\n }\n\n getValue(): T {\n const { hasError, thrownError, _value } = this;\n if (hasError) {\n throw thrownError;\n }\n this._throwIfClosed();\n return _value;\n }\n\n next(value: T): void {\n super.next((this._value = value));\n }\n}\n", "import { TimestampProvider } from '../types';\n\ninterface DateTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const dateTimestampProvider: DateTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n", "import { Subject } from './Subject';\nimport { TimestampProvider } from './types';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * A variant of {@link Subject} that \"replays\" old values to new subscribers by emitting them when they first subscribe.\n *\n * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,\n * `ReplaySubject` \"observes\" values by having them passed to its `next` method. When it observes a value, it will store that\n * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.\n *\n * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in\n * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will\n * error if it has observed an error.\n *\n * There are two main configuration items to be concerned with:\n *\n * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.\n * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.\n *\n * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values\n * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.\n *\n * ### Differences with BehaviorSubject\n *\n * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:\n *\n * 1. `BehaviorSubject` comes \"primed\" with a single value upon construction.\n * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n * @see {@link shareReplay}\n */\nexport class ReplaySubject extends Subject {\n private _buffer: (T | number)[] = [];\n private _infiniteTimeWindow = true;\n\n /**\n * @param bufferSize The size of the buffer to replay on subscription\n * @param windowTime The amount of time the buffered items will stay buffered\n * @param timestampProvider An object with a `now()` method that provides the current timestamp. This is used to\n * calculate the amount of time something has been buffered.\n */\n constructor(\n private _bufferSize = Infinity,\n private _windowTime = Infinity,\n private _timestampProvider: TimestampProvider = dateTimestampProvider\n ) {\n super();\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n\n next(value: T): void {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._trimBuffer();\n\n const subscription = this._innerSubscribe(subscriber);\n\n const { _infiniteTimeWindow, _buffer } = this;\n // We use a copy here, so reentrant code does not mutate our array while we're\n // emitting it to a new subscriber.\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i] as T);\n }\n\n this._checkFinalizedStatuses(subscriber);\n\n return subscription;\n }\n\n private _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n // If we don't have an infinite buffer size, and we're over the length,\n // use splice to truncate the old buffer values off. Note that we have to\n // double the size for instances where we're not using an infinite time window\n // because we're storing the values and the timestamps in the same array.\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n\n // Now, if we're not in an infinite time window, remove all values where the time is\n // older than what is allowed.\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n // Search the array for the first timestamp that isn't expired and\n // truncate the buffer up to that point.\n for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n", "import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n *\n * @class Action\n */\nexport class Action extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler.\n * @return {void}\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetIntervalFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearIntervalFunction = (handle: TimerHandle) => void;\n\ninterface IntervalProvider {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n delegate:\n | {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n }\n | undefined;\n}\n\nexport const intervalProvider: IntervalProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setInterval(handler: () => void, timeout?: number, ...args) {\n const { delegate } = intervalProvider;\n if (delegate?.setInterval) {\n return delegate.setInterval(handler, timeout, ...args);\n }\n return setInterval(handler, timeout, ...args);\n },\n clearInterval(handle) {\n const { delegate } = intervalProvider;\n return (delegate?.clearInterval || clearInterval)(handle as any);\n },\n delegate: undefined,\n};\n", "import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { intervalProvider } from './intervalProvider';\nimport { arrRemove } from '../util/arrRemove';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncAction extends Action {\n public id: TimerHandle | undefined;\n public state?: T;\n // @ts-ignore: Property has no initializer and is not definitely assigned\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id ?? this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, _id?: TimerHandle, delay: number = 0): TimerHandle {\n return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(_scheduler: AsyncScheduler, id?: TimerHandle, delay: number | null = 0): TimerHandle | undefined {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay != null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n if (id != null) {\n intervalProvider.clearInterval(id);\n }\n\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n * @return {any}\n */\n public execute(state: T, delay: number): any {\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, _delay: number): any {\n let errored: boolean = false;\n let errorValue: any;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n // HACK: Since code elsewhere is relying on the \"truthiness\" of the\n // return here, we can't have it return \"\" or 0 or false.\n // TODO: Clean this up when we refactor schedulers mid-version-8 or so.\n errorValue = e ? e : new Error('Scheduled action threw falsy error');\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n unsubscribe() {\n if (!this.closed) {\n const { id, scheduler } = this;\n const { actions } = scheduler;\n\n this.work = this.state = this.scheduler = null!;\n this.pending = false;\n\n arrRemove(actions, this);\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null!;\n super.unsubscribe();\n }\n }\n}\n", "import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @class Scheduler\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}. Will be made internal in v8.\n */\nexport class Scheduler implements SchedulerLike {\n public static now: () => number = dateTimestampProvider.now;\n\n constructor(private schedulerActionCtor: typeof Action, now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return {number} A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param {function(state: ?T): ?Subscription} work A function representing a\n * task, or some unit of work to be executed by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler itself.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @return {Subscription} A subscription in order to be able to unsubscribe\n * the scheduled work.\n */\n public schedule(work: (this: SchedulerAction, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.schedulerActionCtor(this, work).schedule(state, delay);\n }\n}\n", "import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncScheduler extends Scheduler {\n public actions: Array> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @type {boolean}\n * @internal\n */\n public _active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @type {any}\n * @internal\n */\n public _scheduled: TimerHandle | undefined;\n\n constructor(SchedulerAction: typeof Action, now: () => number = Scheduler.now) {\n super(SchedulerAction, now);\n }\n\n public flush(action: AsyncAction): void {\n const { actions } = this;\n\n if (this._active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this._active = true;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions.shift()!)); // exhaust the scheduler queue\n\n this._active = false;\n\n if (error) {\n while ((action = actions.shift()!)) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * Schedule task as if you used setTimeout(task, duration)\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\n\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated Renamed to {@link asyncScheduler}. Will be removed in v8.\n */\nexport const async = asyncScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { QueueScheduler } from './QueueScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class QueueAction extends AsyncAction {\n constructor(protected scheduler: QueueScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n\n public execute(state: T, delay: number): any {\n return delay > 0 || this.closed ? super.execute(state, delay) : this._execute(state, delay);\n }\n\n protected requestAsyncId(scheduler: QueueScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n\n if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n\n // Otherwise flush the scheduler starting with this action.\n scheduler.flush(this);\n\n // HACK: In the past, this was returning `void`. However, `void` isn't a valid\n // `TimerHandle`, and generally the return value here isn't really used. So the\n // compromise is to return `0` which is both \"falsy\" and a valid `TimerHandle`,\n // as opposed to refactoring every other instanceo of `requestAsyncId`.\n return 0;\n }\n}\n", "import { AsyncScheduler } from './AsyncScheduler';\n\nexport class QueueScheduler extends AsyncScheduler {\n}\n", "import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\n\n/**\n *\n * Queue Scheduler\n *\n * Put every next task on a queue, instead of executing it immediately\n *\n * `queue` scheduler, when used with delay, behaves the same as {@link asyncScheduler} scheduler.\n *\n * When used without delay, it schedules given task synchronously - executes it right when\n * it is scheduled. However when called recursively, that is when inside the scheduled task,\n * another task is scheduled with queue scheduler, instead of executing immediately as well,\n * that task will be put on a queue and wait for current one to finish.\n *\n * This means that when you execute task with `queue` scheduler, you are sure it will end\n * before any other task scheduled with that scheduler will start.\n *\n * ## Examples\n * Schedule recursively first, then do something\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(() => {\n * queueScheduler.schedule(() => console.log('second')); // will not happen now, but will be put on a queue\n *\n * console.log('first');\n * });\n *\n * // Logs:\n * // \"first\"\n * // \"second\"\n * ```\n *\n * Reschedule itself recursively\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(function(state) {\n * if (state !== 0) {\n * console.log('before', state);\n * this.schedule(state - 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * console.log('after', state);\n * }\n * }, 0, 3);\n *\n * // In scheduler that runs recursively, you would expect:\n * // \"before\", 3\n * // \"before\", 2\n * // \"before\", 1\n * // \"after\", 1\n * // \"after\", 2\n * // \"after\", 3\n *\n * // But with queue it logs:\n * // \"before\", 3\n * // \"after\", 3\n * // \"before\", 2\n * // \"after\", 2\n * // \"before\", 1\n * // \"after\", 1\n * ```\n */\n\nexport const queueScheduler = new QueueScheduler(QueueAction);\n\n/**\n * @deprecated Renamed to {@link queueScheduler}. Will be removed in v8.\n */\nexport const queue = queueScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nimport { SchedulerAction } from '../types';\nimport { animationFrameProvider } from './animationFrameProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AnimationFrameAction extends AsyncAction {\n constructor(protected scheduler: AnimationFrameScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If an animation frame has already been requested, don't request another\n // one. If an animation frame hasn't been requested yet, request one. Return\n // the current animation frame request id.\n return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(() => scheduler.flush(undefined)));\n }\n\n protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested animation frame and set the scheduled flag to\n // undefined so the next AnimationFrameAction will request its own.\n const { actions } = scheduler;\n if (id != null && actions[actions.length - 1]?.id !== id) {\n animationFrameProvider.cancelAnimationFrame(id as number);\n scheduler._scheduled = undefined;\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AnimationFrameScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n const flushId = this._scheduled;\n this._scheduled = undefined;\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\n\n/**\n *\n * Animation Frame Scheduler\n *\n * Perform task when `window.requestAnimationFrame` would fire\n *\n * When `animationFrame` scheduler is used with delay, it will fall back to {@link asyncScheduler} scheduler\n * behaviour.\n *\n * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.\n * It makes sure scheduled task will happen just before next browser content repaint,\n * thus performing animations as efficiently as possible.\n *\n * ## Example\n * Schedule div height animation\n * ```ts\n * // html:
\n * import { animationFrameScheduler } from 'rxjs';\n *\n * const div = document.querySelector('div');\n *\n * animationFrameScheduler.schedule(function(height) {\n * div.style.height = height + \"px\";\n *\n * this.schedule(height + 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * }, 0, 0);\n *\n * // You will see a div element growing in height\n * ```\n */\n\nexport const animationFrameScheduler = new AnimationFrameScheduler(AnimationFrameAction);\n\n/**\n * @deprecated Renamed to {@link animationFrameScheduler}. Will be removed in v8.\n */\nexport const animationFrame = animationFrameScheduler;\n", "import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * A simple Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * Just emits 'complete', and nothing else.\n *\n * ![](empty.png)\n *\n * A simple Observable that only emits the complete notification. It can be used\n * for composing with other Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n *\n * Log complete notification\n *\n * ```ts\n * import { EMPTY } from 'rxjs';\n *\n * EMPTY.subscribe({\n * next: () => console.log('Next'),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Outputs\n * // Complete!\n * ```\n *\n * Emit the number 7, then complete\n *\n * ```ts\n * import { EMPTY, startWith } from 'rxjs';\n *\n * const result = EMPTY.pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // 7\n * ```\n *\n * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`\n *\n * ```ts\n * import { interval, mergeMap, of, EMPTY } from 'rxjs';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1, print a, b, c (each on its own)\n * // if x % 2 is not equal to 1, nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link NEVER}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const EMPTY = new Observable((subscriber) => subscriber.complete());\n\n/**\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && isFunction(value.schedule);\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\n\nfunction last(arr: T[]): T | undefined {\n return arr[arr.length - 1];\n}\n\nexport function popResultSelector(args: any[]): ((...args: unknown[]) => unknown) | undefined {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\n\nexport function popScheduler(args: any[]): SchedulerLike | undefined {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\n\nexport function popNumber(args: any[], defaultValue: number): number {\n return typeof last(args) === 'number' ? args.pop()! : defaultValue;\n}\n", "export const isArrayLike = ((x: any): x is ArrayLike => x && typeof x.length === 'number' && typeof x !== 'function');", "import { isFunction } from \"./isFunction\";\n\n/**\n * Tests to see if the object is \"thennable\".\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike {\n return isFunction(value?.then);\n}\n", "import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable {\n return isFunction(input[Symbol_observable]);\n}\n", "import { isFunction } from './isFunction';\n\nexport function isAsyncIterable(obj: any): obj is AsyncIterable {\n return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);\n}\n", "/**\n * Creates the TypeError to throw if an invalid object is passed to `from` or `scheduled`.\n * @param input The object that was passed.\n */\nexport function createInvalidObservableTypeError(input: any) {\n // TODO: We should create error codes that can be looked up, so this can be less verbose.\n return new TypeError(\n `You provided ${\n input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`\n } where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`\n );\n}\n", "export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n", "import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable {\n return isFunction(input?.[Symbol_iterator]);\n}\n", "import { ReadableStreamLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport async function* readableStreamLikeToAsyncGenerator(readableStream: ReadableStreamLike): AsyncGenerator {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n yield value!;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function isReadableStreamLike(obj: any): obj is ReadableStreamLike {\n // We don't want to use instanceof checks because they would return\n // false for instances from another Realm, like an - diff --git a/third-party/fmt/doc/perf.svg b/third-party/fmt/doc/perf.svg new file mode 100644 index 0000000000..7867a1544c --- /dev/null +++ b/third-party/fmt/doc/perf.svg @@ -0,0 +1 @@ +double to string02505007501,0001,2501,500ostringstreamostrstreamsprintfdoubleconvfmtTime (ns), smaller is better \ No newline at end of file diff --git a/third-party/fmt/doc/syntax.md b/third-party/fmt/doc/syntax.md new file mode 100644 index 0000000000..46d7d2fd2e --- /dev/null +++ b/third-party/fmt/doc/syntax.md @@ -0,0 +1,886 @@ +# Format String Syntax + +Formatting functions such as [`fmt::format`](api.md#format) and [`fmt::print`]( +api.md#print) use the same format string syntax described in this section. + +Format strings contain "replacement fields" surrounded by curly braces `{}`. +Anything that is not contained in braces is considered literal text, which is +copied unchanged to the output. If you need to include a brace character in +the literal text, it can be escaped by doubling: `{{` and `}}`. + +The grammar for a replacement field is as follows: + +
+
replacement_field ::= "{" [arg_id] [":" (format_spec | chrono_format_spec)] "}"
+arg_id            ::= integer | identifier
+integer           ::= digit+
+digit             ::= "0"..."9"
+identifier        ::= id_start id_continue*
+id_start          ::= "a"..."z" | "A"..."Z" | "_"
+id_continue       ::= id_start | digit
+
+ +In less formal terms, the replacement field can start with an *arg_id* that +specifies the argument whose value is to be formatted and inserted into the +output instead of the replacement field. The *arg_id* is optionally followed +by a *format_spec*, which is preceded by a colon `':'`. These specify a +non-default format for the replacement value. + +See also the [Format Specification +Mini-Language](#format-specification-mini-language) section. + +If the numerical arg_ids in a format string are 0, 1, 2, ... in sequence, +they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be +automatically inserted in that order. + +Named arguments can be referred to by their names or indices. + +Some simple format string examples: + +```c++ +"First, thou shalt count to {0}" // References the first argument +"Bring me a {}" // Implicitly references the first argument +"From {} to {}" // Same as "From {0} to {1}" +``` + +The *format_spec* field contains a specification of how the value should +be presented, including such details as field width, alignment, padding, +decimal precision and so on. Each value type can define its own +"formatting mini-language" or interpretation of the *format_spec*. + +Most built-in types support a common formatting mini-language, which is +described in the next section. + +A *format_spec* field can also include nested replacement fields in +certain positions within it. These nested replacement fields can contain +only an argument id; format specifications are not allowed. This allows +the formatting of a value to be dynamically specified. + +See the [Format Examples](#format-examples) section for some examples. + +## Format Specification Mini-Language + +"Format specifications" are used within replacement fields contained within a +format string to define how individual values are presented. Each formattable +type may define how the format specification is to be interpreted. + +Most built-in types implement the following options for format +specifications, although some of the formatting options are only +supported by the numeric types. + +The general form of a *standard format specifier* is: + + +
format_spec ::= [[fill]align][sign]["#"]["0"][width]["." precision]["L"][type]
+fill        ::= <a character other than '{' or '}'>
+align       ::= "<" | ">" | "^"
+sign        ::= "+" | "-" | " "
+width       ::= integer | "{" [arg_id] "}"
+precision   ::= integer | "{" [arg_id] "}"
+type        ::= "a" | "A" | "b" | "B" | "c" | "d" | "e" | "E" | "f" | "F" |
+                "g" | "G" | "o" | "p" | "s" | "x" | "X" | "?"
+
+ +The *fill* character can be any Unicode code point other than `'{'` or `'}'`. +The presence of a fill character is signaled by the character following it, +which must be one of the alignment options. If the second character of +*format_spec* is not a valid alignment option, then it is assumed that both +the fill character and the alignment option are absent. + +The meaning of the various alignment options is as follows: + + + + + + + + + + + + + + + + + + +
OptionMeaning
'<' + Forces the field to be left-aligned within the available space (this is the + default for most objects). +
'>' + Forces the field to be right-aligned within the available space (this is + the default for numbers). +
'^'Forces the field to be centered within the available space.
+ +Note that unless a minimum field width is defined, the field width will +always be the same size as the data to fill it, so that the alignment +option has no meaning in this case. + +The *sign* option is only valid for floating point and signed integer types, +and can be one of the following: + + + + + + + + + + + + + + + + + + +
OptionMeaning
'+' + Indicates that a sign should be used for both nonnegative as well as + negative numbers. +
'-' + Indicates that a sign should be used only for negative numbers (this is the + default behavior). +
space + Indicates that a leading space should be used on nonnegative numbers, and a + minus sign on negative numbers. +
+ +The `'#'` option causes the "alternate form" to be used for the +conversion. The alternate form is defined differently for different +types. This option is only valid for integer and floating-point types. +For integers, when binary, octal, or hexadecimal output is used, this +option adds the prefix respective `"0b"` (`"0B"`), `"0"`, or `"0x"` +(`"0X"`) to the output value. Whether the prefix is lower-case or +upper-case is determined by the case of the type specifier, for example, +the prefix `"0x"` is used for the type `'x'` and `"0X"` is used for +`'X'`. For floating-point numbers the alternate form causes the result +of the conversion to always contain a decimal-point character, even if +no digits follow it. Normally, a decimal-point character appears in the +result of these conversions only if a digit follows it. In addition, for +`'g'` and `'G'` conversions, trailing zeros are not removed from the +result. + +*width* is a decimal integer defining the minimum field width. If not +specified, then the field width will be determined by the content. + +Preceding the *width* field by a zero (`'0'`) character enables +sign-aware zero-padding for numeric types. It forces the padding to be +placed after the sign or base (if any) but before the digits. This is +used for printing fields in the form "+000000120". This option is only +valid for numeric types and it has no effect on formatting of infinity +and NaN. This option is ignored when any alignment specifier is present. + +The *precision* is a decimal number indicating how many digits should be +displayed after the decimal point for a floating-point value formatted +with `'f'` and `'F'`, or before and after the decimal point for a +floating-point value formatted with `'g'` or `'G'`. For non-number types +the field indicates the maximum field size - in other words, how many +characters will be used from the field content. The *precision* is not +allowed for integer, character, Boolean, and pointer values. Note that a +C string must be null-terminated even if precision is specified. + +The `'L'` option uses the current locale setting to insert the appropriate +number separator characters. This option is only valid for numeric types. + +Finally, the *type* determines how the data should be presented. + +The available string presentation types are: + + + + + + + + + + + + + + + + + + +
TypeMeaning
's' + String format. This is the default type for strings and may be omitted. +
'?'Debug format. The string is quoted and special characters escaped.
noneThe same as 's'.
+ +The available character presentation types are: + + + + + + + + + + + + + + + + + + +
TypeMeaning
'c' + Character format. This is the default type for characters and may be + omitted. +
'?'Debug format. The character is quoted and special characters escaped.
noneThe same as 'c'.
+ +The available integer presentation types are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeMeaning
'b' + Binary format. Outputs the number in base 2. Using the '#' + option with this type adds the prefix "0b" to the output value. +
'B' + Binary format. Outputs the number in base 2. Using the '#' + option with this type adds the prefix "0B" to the output value. +
'c'Character format. Outputs the number as a character.
'd'Decimal integer. Outputs the number in base 10.
'o'Octal format. Outputs the number in base 8.
'x' + Hex format. Outputs the number in base 16, using lower-case letters for the + digits above 9. Using the '#' option with this type adds the + prefix "0x" to the output value. +
'X' + Hex format. Outputs the number in base 16, using upper-case letters for the + digits above 9. Using the '#' option with this type adds the + prefix "0X" to the output value. +
noneThe same as 'd'.
+ +Integer presentation types can also be used with character and Boolean values +with the only exception that `'c'` cannot be used with `bool`. Boolean values +are formatted using textual representation, either `true` or `false`, if the +presentation type is not specified. + +The available presentation types for floating-point values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeMeaning
'a' + Hexadecimal floating point format. Prints the number in base 16 with + prefix "0x" and lower-case letters for digits above 9. + Uses 'p' to indicate the exponent. +
'A' + Same as 'a' except it uses upper-case letters for the + prefix, digits above 9 and to indicate the exponent. +
'e' + Exponent notation. Prints the number in scientific 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. +
'f'Fixed point. Displays the number as a fixed-point number.
'F' + Fixed point. Same as 'f', but converts nan + to NAN and inf to INF. +
'g' +

General format. For a given precision p >= 1, + this rounds the number to p significant digits and then + formats the result in either fixed-point format or in scientific + notation, depending on its magnitude.

+

A precision of 0 is treated as equivalent to a precision + of 1.

+
'G' + General format. Same as 'g' except switches to + 'E' if the number gets too large. The representations of + infinity and NaN are uppercased, too. +
none + Similar to 'g', except that the default precision is as + high as needed to represent the particular value. +
+ +The available presentation types for pointers are: + + + + + + + + + + + + + + +
TypeMeaning
'p' + Pointer format. This is the default type for pointers and may be omitted. +
noneThe same as 'p'.
+ +## Chrono Format Specifications + +Format specifications for chrono duration and time point types as well as +`std::tm` have the following syntax: + + +
chrono_format_spec ::= [[fill]align][width]["." precision][chrono_specs]
+chrono_specs       ::= conversion_spec |
+                       chrono_specs (conversion_spec | literal_char)
+conversion_spec    ::= "%" [padding_modifier] [locale_modifier] chrono_type
+literal_char       ::= <a character other than '{', '}' or '%'>
+padding_modifier   ::= "-" | "_"  | "0"
+locale_modifier    ::= "E" | "O"
+chrono_type        ::= "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" |
+                       "F" | "g" | "G" | "h" | "H" | "I" | "j" | "m" | "M" |
+                       "n" | "p" | "q" | "Q" | "r" | "R" | "S" | "t" | "T" |
+                       "u" | "U" | "V" | "w" | "W" | "x" | "X" | "y" | "Y" |
+                       "z" | "Z" | "%"
+
+ +Literal chars are copied unchanged to the output. Precision is valid only +for `std::chrono::duration` types with a floating-point representation type. + +The available presentation types (*chrono_type*) are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeMeaning
'a' + The abbreviated weekday name, e.g. "Sat". If the value does not contain a + valid weekday, an exception of type format_error is thrown. +
'A' + The full weekday name, e.g. "Saturday". If the value does not contain a + valid weekday, an exception of type format_error is thrown. +
'b' + The abbreviated month name, e.g. "Nov". If the value does not contain a + valid month, an exception of type format_error is thrown. +
'B' + The full month name, e.g. "November". If the value does not contain a valid + month, an exception of type format_error is thrown. +
'c' + The date and time representation, e.g. "Sat Nov 12 22:04:00 1955". The + modified command %Ec produces the locale's alternate date and + time representation. +
'C' + The year divided by 100 using floored division, e.g. "19". If the result + is a single decimal digit, it is prefixed with 0. The modified command + %EC produces the locale's alternative representation of the + century. +
'd' + The day of month as a decimal number. If the result is a single decimal + digit, it is prefixed with 0. The modified command %Od + produces the locale's alternative representation. +
'D'Equivalent to %m/%d/%y, e.g. "11/12/55".
'e' + The day of month as a decimal number. If the result is a single decimal + digit, it is prefixed with a space. The modified command %Oe + produces the locale's alternative representation. +
'F'Equivalent to %Y-%m-%d, e.g. "1955-11-12".
'g' + The last two decimal digits of the ISO week-based year. If the result is a + single digit it is prefixed by 0. +
'G' + The ISO week-based year as a decimal number. If the result is less than + four digits it is left-padded with 0 to four digits. +
'h'Equivalent to %b, e.g. "Nov".
'H' + The hour (24-hour clock) as a decimal number. If the result is a single + digit, it is prefixed with 0. The modified command %OH + produces the locale's alternative representation. +
'I' + The hour (12-hour clock) as a decimal number. If the result is a single + digit, it is prefixed with 0. The modified command %OI + produces the locale's alternative representation. +
'j' + If the type being formatted is a specialization of duration, the decimal + number of days without padding. Otherwise, the day of the year as a decimal + number. Jan 1 is 001. If the result is less than three digits, it is + left-padded with 0 to three digits. +
'm' + The month as a decimal number. Jan is 01. If the result is a single digit, + it is prefixed with 0. The modified command %Om produces the + locale's alternative representation. +
'M' + The minute as a decimal number. If the result is a single digit, it + is prefixed with 0. The modified command %OM produces the + locale's alternative representation. +
'n'A new-line character.
'p'The AM/PM designations associated with a 12-hour clock.
'q'The duration's unit suffix.
'Q' + The duration's numeric value (as if extracted via .count()). +
'r'The 12-hour clock time, e.g. "10:04:00 PM".
'R'Equivalent to %H:%M, e.g. "22:04".
'S' + Seconds as a decimal number. If the number of seconds is less than 10, the + result is prefixed with 0. If the precision of the input cannot be exactly + represented with seconds, then the format is a decimal floating-point number + with a fixed format and a precision matching that of the precision of the + input (or to a microseconds precision if the conversion to floating-point + decimal seconds cannot be made within 18 fractional digits). The modified + command %OS produces the locale's alternative representation. +
't'A horizontal-tab character.
'T'Equivalent to %H:%M:%S.
'u' + The ISO weekday as a decimal number (1-7), where Monday is 1. The modified + command %Ou produces the locale's alternative representation. +
'U' + The week number of the year as a decimal number. The first Sunday of the + year is the first day of week 01. Days of the same year prior to that are + in week 00. If the result is a single digit, it is prefixed with 0. + The modified command %OU produces the locale's alternative + representation. +
'V' + The ISO week-based week number as a decimal number. If the result is a + single digit, it is prefixed with 0. The modified command %OV + produces the locale's alternative representation. +
'w' + The weekday as a decimal number (0-6), where Sunday is 0. The modified + command %Ow produces the locale's alternative representation. +
'W' + The week number of the year as a decimal number. The first Monday of the + year is the first day of week 01. Days of the same year prior to that are + in week 00. If the result is a single digit, it is prefixed with 0. + The modified command %OW produces the locale's alternative + representation. +
'x' + The date representation, e.g. "11/12/55". The modified command + %Ex produces the locale's alternate date representation. +
'X' + The time representation, e.g. "10:04:00". The modified command + %EX produces the locale's alternate time representation. +
'y' + The last two decimal digits of the year. If the result is a single digit + it is prefixed by 0. The modified command %Oy produces the + locale's alternative representation. The modified command %Ey + produces the locale's alternative representation of offset from + %EC (year only). +
'Y' + The year as a decimal number. If the result is less than four digits it is + left-padded with 0 to four digits. The modified command %EY + produces the locale's alternative full year representation. +
'z' + The offset from UTC in the ISO 8601:2004 format. For example -0430 refers + to 4 hours 30 minutes behind UTC. If the offset is zero, +0000 is used. + The modified commands %Ez and %Oz insert a + : between the hours and minutes: -04:30. If the offset + information is not available, an exception of type + format_error is thrown. +
'Z' + The time zone abbreviation. If the time zone abbreviation is not available, + an exception of type format_error is thrown. +
'%'A % character.
+ +Specifiers that have a calendaric component such as `'d'` (the day of month) +are valid only for `std::tm` and time points but not durations. + +The available padding modifiers (*padding_modifier*) are: + +| Type | Meaning | +|-------|-----------------------------------------| +| `'_'` | Pad a numeric result with spaces. | +| `'-'` | Do not pad a numeric result string. | +| `'0'` | Pad a numeric result string with zeros. | + +These modifiers are only supported for the `'H'`, `'I'`, `'M'`, `'S'`, `'U'`, +`'V'`, `'W'`, `'Y'`, `'d'`, `'j'` and `'m'` presentation types. + +## Range Format Specifications + +Format specifications for range types have the following syntax: + +
range_format_spec ::= ["n"][range_type][range_underlying_spec]
+
+ +The `'n'` option formats the range without the opening and closing brackets. + +The available presentation types for `range_type` are: + +| Type | Meaning | +|--------|------------------------------------------------------------| +| none | Default format. | +| `'s'` | String format. The range is formatted as a string. | +| `'?⁠s'` | Debug format. The range is formatted as an escaped string. | + +If `range_type` is `'s'` or `'?s'`, the range element type must be a character +type. The `'n'` option and `range_underlying_spec` are mutually exclusive with +`'s'` and `'?s'`. + +The `range_underlying_spec` is parsed based on the formatter of the range's +element type. + +By default, a range of characters or strings is printed escaped and quoted. +But if any `range_underlying_spec` is provided (even if it is empty), then the +characters or strings are printed according to the provided specification. + +Examples: + +```c++ +fmt::print("{}", std::vector{10, 20, 30}); +// Output: [10, 20, 30] +fmt::print("{::#x}", std::vector{10, 20, 30}); +// Output: [0xa, 0x14, 0x1e] +fmt::print("{}", std::vector{'h', 'e', 'l', 'l', 'o'}); +// Output: ['h', 'e', 'l', 'l', 'o'] +fmt::print("{:n}", std::vector{'h', 'e', 'l', 'l', 'o'}); +// Output: 'h', 'e', 'l', 'l', 'o' +fmt::print("{:s}", std::vector{'h', 'e', 'l', 'l', 'o'}); +// Output: "hello" +fmt::print("{:?s}", std::vector{'h', 'e', 'l', 'l', 'o', '\n'}); +// Output: "hello\n" +fmt::print("{::}", std::vector{'h', 'e', 'l', 'l', 'o'}); +// Output: [h, e, l, l, o] +fmt::print("{::d}", std::vector{'h', 'e', 'l', 'l', 'o'}); +// Output: [104, 101, 108, 108, 111] +``` + +## Format Examples + +This section contains examples of the format syntax and comparison with +the printf formatting. + +In most of the cases the syntax is similar to the printf formatting, +with the addition of the `{}` and with `:` used instead of `%`. For +example, `"%03.2f"` can be translated to `"{:03.2f}"`. + +The new format syntax also supports new and different options, shown in +the following examples. + +Accessing arguments by position: + +```c++ +fmt::format("{0}, {1}, {2}", 'a', 'b', 'c'); +// Result: "a, b, c" +fmt::format("{}, {}, {}", 'a', 'b', 'c'); +// Result: "a, b, c" +fmt::format("{2}, {1}, {0}", 'a', 'b', 'c'); +// Result: "c, b, a" +fmt::format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated +// Result: "abracadabra" +``` + +Aligning the text and specifying a width: + +```c++ +fmt::format("{:<30}", "left aligned"); +// Result: "left aligned " +fmt::format("{:>30}", "right aligned"); +// Result: " right aligned" +fmt::format("{:^30}", "centered"); +// Result: " centered " +fmt::format("{:*^30}", "centered"); // use '*' as a fill char +// Result: "***********centered***********" +``` + +Dynamic width: + +```c++ +fmt::format("{:<{}}", "left aligned", 30); +// Result: "left aligned " +``` + +Dynamic precision: + +```c++ +fmt::format("{:.{}f}", 3.14, 1); +// Result: "3.1" +``` + +Replacing `%+f`, `%-f`, and `% f` and specifying a sign: + +```c++ +fmt::format("{:+f}; {:+f}", 3.14, -3.14); // show it always +// Result: "+3.140000; -3.140000" +fmt::format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers +// Result: " 3.140000; -3.140000" +fmt::format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}' +// Result: "3.140000; -3.140000" +``` + +Replacing `%x` and `%o` and converting the value to different bases: + +```c++ +fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); +// Result: "int: 42; hex: 2a; oct: 52; bin: 101010" +// with 0x or 0 or 0b as prefix: +fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42); +// Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010" +``` + +Padded hex byte with prefix and always prints both hex characters: + +```c++ +fmt::format("{:#04x}", 0); +// Result: "0x00" +``` + +Box drawing using Unicode fill: + +```c++ +fmt::print( + "┌{0:─^{2}}┐\n" + "│{1: ^{2}}│\n" + "└{0:─^{2}}┘\n", "", "Hello, world!", 20); +``` + +prints: + +``` +┌────────────────────┐ +│ Hello, world! │ +└────────────────────┘ +``` + +Using type-specific formatting: + +```c++ +#include + +auto t = tm(); +t.tm_year = 2010 - 1900; +t.tm_mon = 7; +t.tm_mday = 4; +t.tm_hour = 12; +t.tm_min = 15; +t.tm_sec = 58; +fmt::print("{:%Y-%m-%d %H:%M:%S}", t); +// Prints: 2010-08-04 12:15:58 +``` + +Using the comma as a thousands separator: + +```c++ +#include + +auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890); +// s == "1,234,567,890" +``` diff --git a/third-party/fmt/doc/syntax.rst b/third-party/fmt/doc/syntax.rst deleted file mode 100644 index 3c21902c78..0000000000 --- a/third-party/fmt/doc/syntax.rst +++ /dev/null @@ -1,647 +0,0 @@ -.. _syntax: - -******************** -Format String Syntax -******************** - -Formatting functions such as :ref:`fmt::format() ` and -:ref:`fmt::print() ` use the same format string syntax described in this -section. - -Format strings contain "replacement fields" surrounded by curly braces ``{}``. -Anything that is not contained in braces is considered literal text, which is -copied unchanged to the output. If you need to include a brace character in the -literal text, it can be escaped by doubling: ``{{`` and ``}}``. - -The grammar for a replacement field is as follows: - -.. productionlist:: sf - replacement_field: "{" [`arg_id`] [":" (`format_spec` | `chrono_format_spec`)] "}" - arg_id: `integer` | `identifier` - integer: `digit`+ - digit: "0"..."9" - identifier: `id_start` `id_continue`* - id_start: "a"..."z" | "A"..."Z" | "_" - id_continue: `id_start` | `digit` - -In less formal terms, the replacement field can start with an *arg_id* -that specifies the argument whose value is to be formatted and inserted into -the output instead of the replacement field. -The *arg_id* is optionally followed by a *format_spec*, which is preceded by a -colon ``':'``. These specify a non-default format for the replacement value. - -See also the :ref:`formatspec` section. - -If the numerical arg_ids in a format string are 0, 1, 2, ... in sequence, -they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be -automatically inserted in that order. - -Named arguments can be referred to by their names or indices. - -Some simple format string examples:: - - "First, thou shalt count to {0}" // References the first argument - "Bring me a {}" // Implicitly references the first argument - "From {} to {}" // Same as "From {0} to {1}" - -The *format_spec* field contains a specification of how the value should be -presented, including such details as field width, alignment, padding, decimal -precision and so on. Each value type can define its own "formatting -mini-language" or interpretation of the *format_spec*. - -Most built-in types support a common formatting mini-language, which is -described in the next section. - -A *format_spec* field can also include nested replacement fields in certain -positions within it. These nested replacement fields can contain only an -argument id; format specifications are not allowed. This allows the formatting -of a value to be dynamically specified. - -See the :ref:`formatexamples` section for some examples. - -.. _formatspec: - -Format Specification Mini-Language -================================== - -"Format specifications" are used within replacement fields contained within a -format string to define how individual values are presented (see -:ref:`syntax`). Each formattable type may define how the format -specification is to be interpreted. - -Most built-in types implement the following options for format specifications, -although some of the formatting options are only supported by the numeric types. - -The general form of a *standard format specifier* is: - -.. productionlist:: sf - format_spec: [[`fill`]`align`][`sign`]["#"]["0"][`width`]["." `precision`]["L"][`type`] - fill: - align: "<" | ">" | "^" - sign: "+" | "-" | " " - width: `integer` | "{" [`arg_id`] "}" - precision: `integer` | "{" [`arg_id`] "}" - type: "a" | "A" | "b" | "B" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | - : "o" | "p" | "s" | "x" | "X" | "?" - -The *fill* character can be any Unicode code point other than ``'{'`` or -``'}'``. The presence of a fill character is signaled by the character following -it, which must be one of the alignment options. If the second character of -*format_spec* is not a valid alignment option, then it is assumed that both the -fill character and the alignment option are absent. - -The meaning of the various alignment options is as follows: - -+---------+----------------------------------------------------------+ -| Option | Meaning | -+=========+==========================================================+ -| ``'<'`` | Forces the field to be left-aligned within the available | -| | space (this is the default for most objects). | -+---------+----------------------------------------------------------+ -| ``'>'`` | Forces the field to be right-aligned within the | -| | available space (this is the default for numbers). | -+---------+----------------------------------------------------------+ -| ``'^'`` | Forces the field to be centered within the available | -| | space. | -+---------+----------------------------------------------------------+ - -Note that unless a minimum field width is defined, the field width will always -be the same size as the data to fill it, so that the alignment option has no -meaning in this case. - -The *sign* option is only valid for floating point and signed integer types, -and can be one of the following: - -+---------+------------------------------------------------------------+ -| Option | Meaning | -+=========+============================================================+ -| ``'+'`` | indicates that a sign should be used for both | -| | nonnegative as well as negative numbers. | -+---------+------------------------------------------------------------+ -| ``'-'`` | indicates that a sign should be used only for negative | -| | numbers (this is the default behavior). | -+---------+------------------------------------------------------------+ -| space | indicates that a leading space should be used on | -| | nonnegative numbers, and a minus sign on negative numbers. | -+---------+------------------------------------------------------------+ - -The ``'#'`` option causes the "alternate form" to be used for the -conversion. The alternate form is defined differently for different -types. This option is only valid for integer and floating-point types. -For integers, when binary, octal, or hexadecimal output is used, this -option adds the prefix respective ``"0b"`` (``"0B"``), ``"0"``, or -``"0x"`` (``"0X"``) to the output value. Whether the prefix is -lower-case or upper-case is determined by the case of the type -specifier, for example, the prefix ``"0x"`` is used for the type ``'x'`` -and ``"0X"`` is used for ``'X'``. For floating-point numbers the -alternate form causes the result of the conversion to always contain a -decimal-point character, even if no digits follow it. Normally, a -decimal-point character appears in the result of these conversions -only if a digit follows it. In addition, for ``'g'`` and ``'G'`` -conversions, trailing zeros are not removed from the result. - -.. ifconfig:: False - - The ``','`` option signals the use of a comma for a thousands separator. - For a locale aware separator, use the ``'L'`` integer presentation type - instead. - -*width* is a decimal integer defining the minimum field width. If not -specified, then the field width will be determined by the content. - -Preceding the *width* field by a zero (``'0'``) character enables sign-aware -zero-padding for numeric types. It forces the padding to be placed after the -sign or base (if any) but before the digits. This is used for printing fields in -the form '+000000120'. This option is only valid for numeric types and it has no -effect on formatting of infinity and NaN. - -The *precision* is a decimal number indicating how many digits should be -displayed after the decimal point for a floating-point value formatted with -``'f'`` and ``'F'``, or before and after the decimal point for a floating-point -value formatted with ``'g'`` or ``'G'``. For non-number types the field -indicates the maximum field size - in other words, how many characters will be -used from the field content. The *precision* is not allowed for integer, -character, Boolean, and pointer values. Note that a C string must be -null-terminated even if precision is specified. - -The ``'L'`` option uses the current locale setting to insert the appropriate -number separator characters. This option is only valid for numeric types. - -Finally, the *type* determines how the data should be presented. - -The available string presentation types are: - -+---------+----------------------------------------------------------+ -| Type | Meaning | -+=========+==========================================================+ -| ``'s'`` | String format. This is the default type for strings and | -| | may be omitted. | -+---------+----------------------------------------------------------+ -| ``'?'`` | Debug format. The string is quoted and special | -| | characters escaped. | -+---------+----------------------------------------------------------+ -| none | The same as ``'s'``. | -+---------+----------------------------------------------------------+ - -The available character presentation types are: - -+---------+----------------------------------------------------------+ -| Type | Meaning | -+=========+==========================================================+ -| ``'c'`` | Character format. This is the default type for | -| | characters and may be omitted. | -+---------+----------------------------------------------------------+ -| ``'?'`` | Debug format. The character is quoted and special | -| | characters escaped. | -+---------+----------------------------------------------------------+ -| none | The same as ``'c'``. | -+---------+----------------------------------------------------------+ - -The available integer presentation types are: - -+---------+----------------------------------------------------------+ -| Type | Meaning | -+=========+==========================================================+ -| ``'b'`` | Binary format. Outputs the number in base 2. Using the | -| | ``'#'`` option with this type adds the prefix ``"0b"`` | -| | to the output value. | -+---------+----------------------------------------------------------+ -| ``'B'`` | Binary format. Outputs the number in base 2. Using the | -| | ``'#'`` option with this type adds the prefix ``"0B"`` | -| | to the output value. | -+---------+----------------------------------------------------------+ -| ``'c'`` | Character format. Outputs the number as a character. | -+---------+----------------------------------------------------------+ -| ``'d'`` | Decimal integer. Outputs the number in base 10. | -+---------+----------------------------------------------------------+ -| ``'o'`` | Octal format. Outputs the number in base 8. | -+---------+----------------------------------------------------------+ -| ``'x'`` | Hex format. Outputs the number in base 16, using | -| | lower-case letters for the digits above 9. Using the | -| | ``'#'`` option with this type adds the prefix ``"0x"`` | -| | to the output value. | -+---------+----------------------------------------------------------+ -| ``'X'`` | Hex format. Outputs the number in base 16, using | -| | upper-case letters for the digits above 9. Using the | -| | ``'#'`` option with this type adds the prefix ``"0X"`` | -| | to the output value. | -+---------+----------------------------------------------------------+ -| none | The same as ``'d'``. | -+---------+----------------------------------------------------------+ - -Integer presentation types can also be used with character and Boolean values -with the only exception that ``'c'`` cannot be used with `bool`. Boolean values -are formatted using textual representation, either ``true`` or ``false``, if the -presentation type is not specified. - -The available presentation types for floating-point values are: - -+---------+----------------------------------------------------------+ -| Type | Meaning | -+=========+==========================================================+ -| ``'a'`` | Hexadecimal floating point format. Prints the number in | -| | base 16 with prefix ``"0x"`` and lower-case letters for | -| | digits above 9. Uses ``'p'`` to indicate the exponent. | -+---------+----------------------------------------------------------+ -| ``'A'`` | Same as ``'a'`` except it uses upper-case letters for | -| | the prefix, digits above 9 and to indicate the exponent. | -+---------+----------------------------------------------------------+ -| ``'e'`` | Exponent notation. Prints the number in scientific | -| | 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. | -+---------+----------------------------------------------------------+ -| ``'f'`` | Fixed point. Displays the number as a fixed-point | -| | number. | -+---------+----------------------------------------------------------+ -| ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to | -| | ``NAN`` and ``inf`` to ``INF``. | -+---------+----------------------------------------------------------+ -| ``'g'`` | General format. For a given precision ``p >= 1``, | -| | this rounds the number to ``p`` significant digits and | -| | then formats the result in either fixed-point format | -| | or in scientific notation, depending on its magnitude. | -| | | -| | A precision of ``0`` is treated as equivalent to a | -| | precision of ``1``. | -+---------+----------------------------------------------------------+ -| ``'G'`` | General format. Same as ``'g'`` except switches to | -| | ``'E'`` if the number gets too large. The | -| | representations of infinity and NaN are uppercased, too. | -+---------+----------------------------------------------------------+ -| none | Similar to ``'g'``, except that the default precision is | -| | as high as needed to represent the particular value. | -+---------+----------------------------------------------------------+ - -.. ifconfig:: False - - +---------+----------------------------------------------------------+ - | | The precise rules are as follows: suppose that the | - | | result formatted with presentation type ``'e'`` and | - | | precision ``p-1`` would have exponent ``exp``. Then | - | | if ``-4 <= exp < p``, the number is formatted | - | | with presentation type ``'f'`` and precision | - | | ``p-1-exp``. Otherwise, the number is formatted | - | | with presentation type ``'e'`` and precision ``p-1``. | - | | In both cases insignificant trailing zeros are removed | - | | from the significand, and the decimal point is also | - | | removed if there are no remaining digits following it. | - | | | - | | Positive and negative infinity, positive and negative | - | | zero, and nans, are formatted as ``inf``, ``-inf``, | - | | ``0``, ``-0`` and ``nan`` respectively, regardless of | - | | the precision. | - | | | - +---------+----------------------------------------------------------+ - -The available presentation types for pointers are: - -+---------+----------------------------------------------------------+ -| Type | Meaning | -+=========+==========================================================+ -| ``'p'`` | Pointer format. This is the default type for | -| | pointers and may be omitted. | -+---------+----------------------------------------------------------+ -| none | The same as ``'p'``. | -+---------+----------------------------------------------------------+ - -.. _chrono-specs: - -Chrono Format Specifications -============================ - -Format specifications for chrono duration and time point types as well as -``std::tm`` have the following syntax: - -.. productionlist:: sf - chrono_format_spec: [[`fill`]`align`][`width`]["." `precision`][`chrono_specs`] - chrono_specs: [`chrono_specs`] `conversion_spec` | `chrono_specs` `literal_char` - conversion_spec: "%" [`modifier`] `chrono_type` - literal_char: - modifier: "E" | "O" - chrono_type: "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" | "F" | - : "g" | "G" | "h" | "H" | "I" | "j" | "m" | "M" | "n" | "p" | - : "q" | "Q" | "r" | "R" | "S" | "t" | "T" | "u" | "U" | "V" | - : "w" | "W" | "x" | "X" | "y" | "Y" | "z" | "Z" | "%" - -Literal chars are copied unchanged to the output. Precision is valid only for -``std::chrono::duration`` types with a floating-point representation type. - -The available presentation types (*chrono_type*) are: - -+---------+--------------------------------------------------------------------+ -| Type | Meaning | -+=========+====================================================================+ -| ``'a'`` | The abbreviated weekday name, e.g. "Sat". If the value does not | -| | contain a valid weekday, an exception of type ``format_error`` is | -| | thrown. | -+---------+--------------------------------------------------------------------+ -| ``'A'`` | The full weekday name, e.g. "Saturday". If the value does not | -| | contain a valid weekday, an exception of type ``format_error`` is | -| | thrown. | -+---------+--------------------------------------------------------------------+ -| ``'b'`` | The abbreviated month name, e.g. "Nov". If the value does not | -| | contain a valid month, an exception of type ``format_error`` is | -| | thrown. | -+---------+--------------------------------------------------------------------+ -| ``'B'`` | The full month name, e.g. "November". If the value does not | -| | contain a valid month, an exception of type ``format_error`` is | -| | thrown. | -+---------+--------------------------------------------------------------------+ -| ``'c'`` | The date and time representation, e.g. "Sat Nov 12 22:04:00 1955". | -| | The modified command ``%Ec`` produces the locale's alternate date | -| | and time representation. | -+---------+--------------------------------------------------------------------+ -| ``'C'`` | The year divided by 100 using floored division, e.g. "55". If the | -| | result is a single decimal digit, it is prefixed with 0. | -| | The modified command ``%EC`` produces the locale's alternative | -| | representation of the century. | -+---------+--------------------------------------------------------------------+ -| ``'d'`` | The day of month as a decimal number. If the result is a single | -| | decimal digit, it is prefixed with 0. The modified command ``%Od`` | -| | produces the locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'D'`` | Equivalent to ``%m/%d/%y``, e.g. "11/12/55". | -+---------+--------------------------------------------------------------------+ -| ``'e'`` | The day of month as a decimal number. If the result is a single | -| | decimal digit, it is prefixed with a space. The modified command | -| | ``%Oe`` produces the locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'F'`` | Equivalent to ``%Y-%m-%d``, e.g. "1955-11-12". | -+---------+--------------------------------------------------------------------+ -| ``'g'`` | The last two decimal digits of the ISO week-based year. If the | -| | result is a single digit it is prefixed by 0. | -+---------+--------------------------------------------------------------------+ -| ``'G'`` | The ISO week-based year as a decimal number. If the result is less | -| | than four digits it is left-padded with 0 to four digits. | -+---------+--------------------------------------------------------------------+ -| ``'h'`` | Equivalent to ``%b``, e.g. "Nov". | -+---------+--------------------------------------------------------------------+ -| ``'H'`` | The hour (24-hour clock) as a decimal number. If the result is a | -| | single digit, it is prefixed with 0. The modified command ``%OH`` | -| | produces the locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'I'`` | The hour (12-hour clock) as a decimal number. If the result is a | -| | single digit, it is prefixed with 0. The modified command ``%OI`` | -| | produces the locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'j'`` | If the type being formatted is a specialization of duration, the | -| | decimal number of days without padding. Otherwise, the day of the | -| | year as a decimal number. Jan 1 is 001. If the result is less than | -| | three digits, it is left-padded with 0 to three digits. | -+---------+--------------------------------------------------------------------+ -| ``'m'`` | The month as a decimal number. Jan is 01. If the result is a | -| | single digit, it is prefixed with 0. The modified command ``%Om`` | -| | produces the locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'M'`` | The minute as a decimal number. If the result is a single digit, | -| | it is prefixed with 0. The modified command ``%OM`` produces the | -| | locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'n'`` | A new-line character. | -+---------+--------------------------------------------------------------------+ -| ``'p'`` | The AM/PM designations associated with a 12-hour clock. | -+---------+--------------------------------------------------------------------+ -| ``'q'`` | The duration's unit suffix. | -+---------+--------------------------------------------------------------------+ -| ``'Q'`` | The duration's numeric value (as if extracted via ``.count()``). | -+---------+--------------------------------------------------------------------+ -| ``'r'`` | The 12-hour clock time, e.g. "10:04:00 PM". | -+---------+--------------------------------------------------------------------+ -| ``'R'`` | Equivalent to ``%H:%M``, e.g. "22:04". | -+---------+--------------------------------------------------------------------+ -| ``'S'`` | Seconds as a decimal number. If the number of seconds is less than | -| | 10, the result is prefixed with 0. If the precision of the input | -| | cannot be exactly represented with seconds, then the format is a | -| | decimal floating-point number with a fixed format and a precision | -| | matching that of the precision of the input (or to a microseconds | -| | precision if the conversion to floating-point decimal seconds | -| | cannot be made within 18 fractional digits). The character for the | -| | decimal point is localized according to the locale. The modified | -| | command ``%OS`` produces the locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'t'`` | A horizontal-tab character. | -+---------+--------------------------------------------------------------------+ -| ``'T'`` | Equivalent to ``%H:%M:%S``. | -+---------+--------------------------------------------------------------------+ -| ``'u'`` | The ISO weekday as a decimal number (1-7), where Monday is 1. The | -| | modified command ``%Ou`` produces the locale's alternative | -| | representation. | -+---------+--------------------------------------------------------------------+ -| ``'U'`` | The week number of the year as a decimal number. The first Sunday | -| | of the year is the first day of week 01. Days of the same year | -| | prior to that are in week 00. If the result is a single digit, it | -| | is prefixed with 0. The modified command ``%OU`` produces the | -| | locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'V'`` | The ISO week-based week number as a decimal number. If the result | -| | is a single digit, it is prefixed with 0. The modified command | -| | ``%OV`` produces the locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'w'`` | The weekday as a decimal number (0-6), where Sunday is 0. | -| | The modified command ``%Ow`` produces the locale's alternative | -| | representation. | -+---------+--------------------------------------------------------------------+ -| ``'W'`` | The week number of the year as a decimal number. The first Monday | -| | of the year is the first day of week 01. Days of the same year | -| | prior to that are in week 00. If the result is a single digit, it | -| | is prefixed with 0. The modified command ``%OW`` produces the | -| | locale's alternative representation. | -+---------+--------------------------------------------------------------------+ -| ``'x'`` | The date representation, e.g. "11/12/55". The modified command | -| | ``%Ex`` produces the locale's alternate date representation. | -+---------+--------------------------------------------------------------------+ -| ``'X'`` | The time representation, e.g. "10:04:00". The modified command | -| | ``%EX`` produces the locale's alternate time representation. | -+---------+--------------------------------------------------------------------+ -| ``'y'`` | The last two decimal digits of the year. If the result is a single | -| | digit it is prefixed by 0. The modified command ``%Oy`` produces | -| | the locale's alternative representation. The modified command | -| | ``%Ey`` produces the locale's alternative representation of offset | -| | from ``%EC`` (year only). | -+---------+--------------------------------------------------------------------+ -| ``'Y'`` | The year as a decimal number. If the result is less than four | -| | digits it is left-padded with 0 to four digits. The modified | -| | command ``%EY`` produces the locale's alternative full year | -| | representation. | -+---------+--------------------------------------------------------------------+ -| ``'z'`` | The offset from UTC in the ISO 8601:2004 format. For example -0430 | -| | refers to 4 hours 30 minutes behind UTC. If the offset is zero, | -| | +0000 is used. The modified commands ``%Ez`` and ``%Oz`` insert a | -| | ``:`` between the hours and minutes: -04:30. If the offset | -| | information is not available, an exception of type | -| | ``format_error`` is thrown. | -+---------+--------------------------------------------------------------------+ -| ``'Z'`` | The time zone abbreviation. If the time zone abbreviation is not | -| | available, an exception of type ``format_error`` is thrown. | -+---------+--------------------------------------------------------------------+ -| ``'%'`` | A % character. | -+---------+--------------------------------------------------------------------+ - -Specifiers that have a calendaric component such as ``'d'`` (the day of month) -are valid only for ``std::tm`` and time points but not durations. - -.. range-specs: - -Range Format Specifications -=========================== - -Format specifications for range types have the following syntax: - -.. productionlist:: sf - range_format_spec: [":" [`underlying_spec`]] - -The `underlying_spec` is parsed based on the formatter of the range's -reference type. - -By default, a range of characters or strings is printed escaped and quoted. But -if any `underlying_spec` is provided (even if it is empty), then the characters -or strings are printed according to the provided specification. - -Examples:: - - fmt::format("{}", std::vector{10, 20, 30}); - // Result: [10, 20, 30] - fmt::format("{::#x}", std::vector{10, 20, 30}); - // Result: [0xa, 0x14, 0x1e] - fmt::format("{}", vector{'h', 'e', 'l', 'l', 'o'}); - // Result: ['h', 'e', 'l', 'l', 'o'] - fmt::format("{::}", vector{'h', 'e', 'l', 'l', 'o'}); - // Result: [h, e, l, l, o] - fmt::format("{::d}", vector{'h', 'e', 'l', 'l', 'o'}); - // Result: [104, 101, 108, 108, 111] - -.. _formatexamples: - -Format Examples -=============== - -This section contains examples of the format syntax and comparison with -the printf formatting. - -In most of the cases the syntax is similar to the printf formatting, with the -addition of the ``{}`` and with ``:`` used instead of ``%``. -For example, ``"%03.2f"`` can be translated to ``"{:03.2f}"``. - -The new format syntax also supports new and different options, shown in the -following examples. - -Accessing arguments by position:: - - fmt::format("{0}, {1}, {2}", 'a', 'b', 'c'); - // Result: "a, b, c" - fmt::format("{}, {}, {}", 'a', 'b', 'c'); - // Result: "a, b, c" - fmt::format("{2}, {1}, {0}", 'a', 'b', 'c'); - // Result: "c, b, a" - fmt::format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated - // Result: "abracadabra" - -Aligning the text and specifying a width:: - - fmt::format("{:<30}", "left aligned"); - // Result: "left aligned " - fmt::format("{:>30}", "right aligned"); - // Result: " right aligned" - fmt::format("{:^30}", "centered"); - // Result: " centered " - fmt::format("{:*^30}", "centered"); // use '*' as a fill char - // Result: "***********centered***********" - -Dynamic width:: - - fmt::format("{:<{}}", "left aligned", 30); - // Result: "left aligned " - -Dynamic precision:: - - fmt::format("{:.{}f}", 3.14, 1); - // Result: "3.1" - -Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:: - - fmt::format("{:+f}; {:+f}", 3.14, -3.14); // show it always - // Result: "+3.140000; -3.140000" - fmt::format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers - // Result: " 3.140000; -3.140000" - fmt::format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}' - // Result: "3.140000; -3.140000" - -Replacing ``%x`` and ``%o`` and converting the value to different bases:: - - fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); - // Result: "int: 42; hex: 2a; oct: 52; bin: 101010" - // with 0x or 0 or 0b as prefix: - fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42); - // Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010" - -Padded hex byte with prefix and always prints both hex characters:: - - fmt::format("{:#04x}", 0); - // Result: "0x00" - -Box drawing using Unicode fill:: - - fmt::print( - "┌{0:─^{2}}┐\n" - "│{1: ^{2}}│\n" - "└{0:─^{2}}┘\n", "", "Hello, world!", 20); - -prints:: - - ┌────────────────────┐ - │ Hello, world! │ - └────────────────────┘ - -Using type-specific formatting:: - - #include - - auto t = tm(); - t.tm_year = 2010 - 1900; - t.tm_mon = 7; - t.tm_mday = 4; - t.tm_hour = 12; - t.tm_min = 15; - t.tm_sec = 58; - fmt::print("{:%Y-%m-%d %H:%M:%S}", t); - // Prints: 2010-08-04 12:15:58 - -Using the comma as a thousands separator:: - - #include - - auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890); - // s == "1,234,567,890" - -.. ifconfig:: False - - Nesting arguments and more complex examples:: - - >>> for align, text in zip('<^>', ['left', 'center', 'right']): - ... '{0:{fill}{align}16}") << text, fill=align, align=align) - ... - 'left<<<<<<<<<<<<' - '^^^^^center^^^^^' - '>>>>>>>>>>>right' - >>> - >>> octets = [192, 168, 0, 1] - Format("{:02X}{:02X}{:02X}{:02X}") << *octets) - 'C0A80001' - >>> int(_, 16) - 3232235521 - >>> - >>> width = 5 - >>> for num in range(5,12): - ... for base in 'dXob': - ... print('{0:{width}{base}}") << num, base=base, width=width), end=' ') - ... print() - ... - 5 5 5 101 - 6 6 6 110 - 7 7 7 111 - 8 8 10 1000 - 9 9 11 1001 - 10 A 12 1010 - 11 B 13 1011 diff --git a/third-party/fmt/doc/usage.rst b/third-party/fmt/doc/usage.rst deleted file mode 100644 index 717fd1cdf9..0000000000 --- a/third-party/fmt/doc/usage.rst +++ /dev/null @@ -1,250 +0,0 @@ -***** -Usage -***** - -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 `_ or -the `Git repository `_ to your project. -Alternatively, you can :ref:`build the library with CMake `. - -.. _building: - -Building the Library -==================== - -The included `CMake build script`__ can be used to build the fmt -library on a wide range of platforms. CMake is freely available for -download from https://www.cmake.org/download/. - -__ https://github.com/fmtlib/fmt/blob/master/CMakeLists.txt - -CMake works by generating native makefiles or project files that can -be used in the compiler environment of your choice. The typical -workflow starts with:: - - mkdir build # Create a directory to hold the build output. - cd build - cmake .. # Generate native build scripts. - -where :file:`{}` is a path to the ``fmt`` repository. - -If you are on a \*nix system, you should now see a Makefile in the -current directory. Now you can build the library by running :command:`make`. - -Once the library has been built you can invoke :command:`make test` to run -the tests. - -You can control generation of the make ``test`` target with the ``FMT_TEST`` -CMake option. This can be useful if you include fmt as a subdirectory in -your project but don't want to add fmt's tests to your ``test`` target. - -If you use Windows and have Visual Studio installed, a :file:`FMT.sln` -file and several :file:`.vcproj` files will be created. You can then build them -using Visual Studio or msbuild. - -On Mac OS X with Xcode installed, an :file:`.xcodeproj` file will be generated. - -To build a `shared library`__ set the ``BUILD_SHARED_LIBS`` CMake variable to -``TRUE``:: - - cmake -DBUILD_SHARED_LIBS=TRUE ... - -__ https://en.wikipedia.org/wiki/Library_%28computing%29#Shared_libraries - - -To build a `static library` with position independent code (required if the main -consumer of the fmt library is a shared library i.e. a Python extension) set the -``CMAKE_POSITION_INDEPENDENT_CODE`` CMake variable to ``TRUE``:: - - cmake -DCMAKE_POSITION_INDEPENDENT_CODE=TRUE ... - - -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:: - - add_subdirectory(fmt) - -or - -:: - - add_subdirectory(fmt EXCLUDE_FROM_ALL) - -to exclude it from ``make``, ``make all``, or ``cmake --build .``. - -You can detect and use an installed version of {fmt} as follows:: - - find_package(fmt) - target_link_libraries( fmt::fmt) - -Setting up your target to use a header-only version of ``fmt`` is equally easy:: - - target_link_libraries( PRIVATE fmt::fmt-header-only) - -Usage with build2 -================= - -You can use `build2 `_, a dependency manager and a -build-system combined, to use ``fmt``. - -Currently this package is available in these package repositories: - -- **https://cppget.org/fmt/** for released and published versions. -- `The git repository with the sources of the build2 package of fmt `_ - for unreleased or custom revisions of ``fmt``. - -**Usage:** - -- ``build2`` package name: ``fmt`` -- Library target name : ``lib{fmt}`` - -For example, to make your ``build2`` project depend on ``fmt``: - -- Add one of the repositories to your configurations, or in your - ``repositories.manifest``, if not already there:: - - : - role: prerequisite - location: https://pkg.cppget.org/1/stable - -- Add this package as a dependency to your ``./manifest`` file - (example for ``v7.0.x``):: - - depends: fmt ~7.0.0 - -- Import the target and use it as a prerequisite to your own target - using `fmt` in the appropriate ``buildfile``:: - - import fmt = fmt%lib{fmt} - lib{mylib} : cxx{**} ... $fmt - -Then build your project as usual with `b` or `bdep update`. - -For ``build2`` newcomers or to get more details and use cases, you can read the -``build2`` -`toolchain introduction `_. - -Usage with Meson -================ - -`Meson's WrapDB ` includes a ``fmt`` -package, which repackages fmt to be built by Meson as a subproject. - -**Usage:** - -- Install the ``fmt`` subproject from the WrapDB by running:: - - meson wrap install fmt - - from the root of your project. - -- In your project's ``meson.build`` file, add an entry for the new subproject:: - - fmt = subproject('fmt') - fmt_dep = fmt.get_variable('fmt_dep') - -- Include the new dependency object to link with fmt:: - - my_build_target = executable('name', 'src/main.cc', dependencies: [fmt_dep]) - -**Options:** - -If desired, ``fmt`` may be built as a static library, or as a header-only -library. - -For a static build, use the following subproject definition:: - - fmt = subproject('fmt', default_options: 'default_library=static') - fmt_dep = fmt.get_variable('fmt_dep') - -For the header-only version, use:: - - fmt = subproject('fmt') - fmt_dep = fmt.get_variable('fmt_header_only_dep') - -Building the Documentation -========================== - -To build the documentation you need the following software installed on your -system: - -* `Python `_ with pip and virtualenv -* `Doxygen `_ -* `Less `_ with ``less-plugin-clean-css``. - Ubuntu doesn't package the ``clean-css`` plugin so you should use ``npm`` - instead of ``apt`` to install both ``less`` and the plugin:: - - sudo npm install -g less less-plugin-clean-css. - -First generate makefiles or project files using CMake as described in -the previous section. Then compile the ``doc`` target/project, for example:: - - make doc - -This will generate the HTML documentation in ``doc/html``. - -Conda -===== - -fmt can be installed on Linux, macOS and Windows with -`Conda `__, using its -`conda-forge `__ -`package `__, as follows:: - - conda install -c conda-forge fmt - -Vcpkg -===== - -You can download and install fmt using the `vcpkg -`__ dependency manager:: - - git clone https://github.com/Microsoft/vcpkg.git - cd vcpkg - ./bootstrap-vcpkg.sh - ./vcpkg integrate install - ./vcpkg install fmt - -The fmt port in vcpkg is kept up to date by Microsoft team members and community -contributors. If the version is out of date, please `create an issue or pull -request `__ on the vcpkg repository. - -LHelper -======= - -You can download and install fmt using -`lhelper `__ dependency manager:: - - lhelper activate - lhelper install fmt - -All the recipes for lhelper are kept in the -`lhelper's recipe `__ repository. - -Android NDK -=========== - -fmt provides `Android.mk file`__ that can be used to build the library -with `Android NDK `_. -For an example of using fmt with Android NDK, see the -`android-ndk-example `_ -repository. - -__ https://github.com/fmtlib/fmt/blob/master/support/Android.mk - -Homebrew -======== - -fmt can be installed on OS X using `Homebrew `_:: - - brew install fmt diff --git a/third-party/fmt/include/fmt/args.h b/third-party/fmt/include/fmt/args.h index ad1654bbb6..3ff4788074 100644 --- a/third-party/fmt/include/fmt/args.h +++ b/third-party/fmt/include/fmt/args.h @@ -8,14 +8,15 @@ #ifndef FMT_ARGS_H_ #define FMT_ARGS_H_ -#include // std::reference_wrapper -#include // std::unique_ptr -#include +#ifndef FMT_MODULE +# include // std::reference_wrapper +# include // std::unique_ptr +# include +#endif -#include "core.h" +#include "format.h" // std_string_view FMT_BEGIN_NAMESPACE - namespace detail { template struct is_reference_wrapper : std::false_type {}; @@ -28,15 +29,18 @@ auto unwrap(const std::reference_wrapper& v) -> const T& { return static_cast(v); } -class dynamic_arg_list { - // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for - // templates it doesn't complain about inability to deduce single translation - // unit for placing vtable. So storage_node_base is made a fake template. - template struct node { - virtual ~node() = default; - std::unique_ptr> next; - }; +// node is defined outside dynamic_arg_list to workaround a C2504 bug in MSVC +// 2022 (v17.10.0). +// +// Workaround for clang's -Wweak-vtables. Unlike for regular classes, for +// templates it doesn't complain about inability to deduce single translation +// unit for placing vtable. So node is made a fake template. +template struct node { + virtual ~node() = default; + std::unique_ptr> next; +}; +class dynamic_arg_list { template struct typed_node : node<> { T value; @@ -62,28 +66,18 @@ class dynamic_arg_list { } // namespace detail /** - \rst - A dynamic version of `fmt::format_arg_store`. - It's equipped with a storage to potentially temporary objects which lifetimes - could be shorter than the format arguments object. - - It can be implicitly converted into `~fmt::basic_format_args` for passing - into type-erased formatting functions such as `~fmt::vformat`. - \endrst + * A dynamic list of formatting arguments with storage. + * + * It can be implicitly converted into `fmt::basic_format_args` for passing + * into type-erased formatting functions such as `fmt::vformat`. */ -template -class dynamic_format_arg_store -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 - // Workaround a GCC template argument substitution bug. - : public basic_format_args -#endif -{ +template class dynamic_format_arg_store { private: using char_type = typename Context::char_type; template struct need_copy { static constexpr detail::type mapped_type = - detail::mapped_type_constant::value; + detail::mapped_type_constant::value; enum { value = !(detail::is_reference_wrapper::value || @@ -96,7 +90,7 @@ class dynamic_format_arg_store }; template - using stored_type = conditional_t< + using stored_t = conditional_t< std::is_convertible>::value && !detail::is_reference_wrapper::value, std::basic_string, T>; @@ -111,80 +105,72 @@ class dynamic_format_arg_store friend class basic_format_args; - auto get_types() const -> unsigned long long { - return detail::is_unpacked_bit | data_.size() | - (named_info_.empty() - ? 0ULL - : static_cast(detail::has_named_args_bit)); - } - auto data() const -> const basic_format_arg* { return named_info_.empty() ? data_.data() : data_.data() + 1; } template void emplace_arg(const T& arg) { - data_.emplace_back(detail::make_arg(arg)); + data_.emplace_back(arg); } template void emplace_arg(const detail::named_arg& arg) { - if (named_info_.empty()) { - constexpr const detail::named_arg_info* zero_ptr{nullptr}; - data_.insert(data_.begin(), {zero_ptr, 0}); - } - data_.emplace_back(detail::make_arg(detail::unwrap(arg.value))); + if (named_info_.empty()) + data_.insert(data_.begin(), basic_format_arg(nullptr, 0)); + data_.emplace_back(detail::unwrap(arg.value)); auto pop_one = [](std::vector>* data) { data->pop_back(); }; std::unique_ptr>, decltype(pop_one)> guard{&data_, pop_one}; named_info_.push_back({arg.name, static_cast(data_.size() - 2u)}); - data_[0].value_.named_args = {named_info_.data(), named_info_.size()}; + data_[0] = {named_info_.data(), named_info_.size()}; guard.release(); } public: constexpr dynamic_format_arg_store() = default; + operator basic_format_args() const { + return basic_format_args(data(), static_cast(data_.size()), + !named_info_.empty()); + } + /** - \rst - Adds an argument into the dynamic store for later passing to a formatting - function. - - Note that custom types and string types (but not string views) are copied - into the store dynamically allocating memory if necessary. - - **Example**:: - - fmt::dynamic_format_arg_store store; - store.push_back(42); - store.push_back("abc"); - store.push_back(1.5f); - std::string result = fmt::vformat("{} and {} and {}", store); - \endrst - */ + * Adds an argument into the dynamic store for later passing to a formatting + * function. + * + * Note that custom types and string types (but not string views) are copied + * into the store dynamically allocating memory if necessary. + * + * **Example**: + * + * fmt::dynamic_format_arg_store store; + * store.push_back(42); + * store.push_back("abc"); + * store.push_back(1.5f); + * std::string result = fmt::vformat("{} and {} and {}", store); + */ template void push_back(const T& arg) { if (detail::const_check(need_copy::value)) - emplace_arg(dynamic_args_.push>(arg)); + emplace_arg(dynamic_args_.push>(arg)); else emplace_arg(detail::unwrap(arg)); } /** - \rst - Adds a reference to the argument into the dynamic store for later passing to - a formatting function. - - **Example**:: - - fmt::dynamic_format_arg_store store; - char band[] = "Rolling Stones"; - store.push_back(std::cref(band)); - band[9] = 'c'; // Changing str affects the output. - std::string result = fmt::vformat("{}", store); - // result == "Rolling Scones" - \endrst - */ + * Adds a reference to the argument into the dynamic store for later passing + * to a formatting function. + * + * **Example**: + * + * fmt::dynamic_format_arg_store store; + * char band[] = "Rolling Stones"; + * store.push_back(std::cref(band)); + * band[9] = 'c'; // Changing str affects the output. + * std::string result = fmt::vformat("{}", store); + * // result == "Rolling Scones" + */ template void push_back(std::reference_wrapper arg) { static_assert( need_copy::value, @@ -193,41 +179,40 @@ class dynamic_format_arg_store } /** - Adds named argument into the dynamic store for later passing to a formatting - function. ``std::reference_wrapper`` is supported to avoid copying of the - argument. The name is always copied into the store. - */ + * Adds named argument into the dynamic store for later passing to a + * formatting function. `std::reference_wrapper` is supported to avoid + * copying of the argument. The name is always copied into the store. + */ template void push_back(const detail::named_arg& arg) { const char_type* arg_name = dynamic_args_.push>(arg.name).c_str(); if (detail::const_check(need_copy::value)) { emplace_arg( - fmt::arg(arg_name, dynamic_args_.push>(arg.value))); + fmt::arg(arg_name, dynamic_args_.push>(arg.value))); } else { emplace_arg(fmt::arg(arg_name, arg.value)); } } - /** Erase all elements from the store */ + /// Erase all elements from the store. void clear() { data_.clear(); named_info_.clear(); - dynamic_args_ = detail::dynamic_arg_list(); + dynamic_args_ = {}; } - /** - \rst - Reserves space to store at least *new_cap* arguments including - *new_cap_named* named arguments. - \endrst - */ + /// Reserves space to store at least `new_cap` arguments including + /// `new_cap_named` named arguments. void reserve(size_t new_cap, size_t new_cap_named) { FMT_ASSERT(new_cap >= new_cap_named, - "Set of arguments includes set of named arguments"); + "set of arguments includes set of named arguments"); data_.reserve(new_cap); named_info_.reserve(new_cap_named); } + + /// Returns the number of elements in the store. + size_t size() const noexcept { return data_.size(); } }; FMT_END_NAMESPACE diff --git a/third-party/fmt/include/fmt/base.h b/third-party/fmt/include/fmt/base.h new file mode 100644 index 0000000000..b886317d6a --- /dev/null +++ b/third-party/fmt/include/fmt/base.h @@ -0,0 +1,2962 @@ +// Formatting library for C++ - the base API for char/UTF-8 +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_BASE_H_ +#define FMT_BASE_H_ + +#if defined(FMT_IMPORT_STD) && !defined(FMT_MODULE) +# define FMT_MODULE +#endif + +#ifndef FMT_MODULE +# include // CHAR_BIT +# include // FILE +# include // memcmp + +# include // std::enable_if +#endif + +// The fmt library version in the form major * 10000 + minor * 100 + patch. +#define FMT_VERSION 110104 + +// Detect compiler versions. +#if defined(__clang__) && !defined(__ibmxl__) +# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#else +# define FMT_CLANG_VERSION 0 +#endif +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define FMT_GCC_VERSION 0 +#endif +#if defined(__ICL) +# define FMT_ICC_VERSION __ICL +#elif defined(__INTEL_COMPILER) +# define FMT_ICC_VERSION __INTEL_COMPILER +#else +# define FMT_ICC_VERSION 0 +#endif +#if defined(_MSC_VER) +# define FMT_MSC_VERSION _MSC_VER +#else +# define FMT_MSC_VERSION 0 +#endif + +// Detect standard library versions. +#ifdef _GLIBCXX_RELEASE +# define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE +#else +# define FMT_GLIBCXX_RELEASE 0 +#endif +#ifdef _LIBCPP_VERSION +# define FMT_LIBCPP_VERSION _LIBCPP_VERSION +#else +# define FMT_LIBCPP_VERSION 0 +#endif + +#ifdef _MSVC_LANG +# define FMT_CPLUSPLUS _MSVC_LANG +#else +# define FMT_CPLUSPLUS __cplusplus +#endif + +// Detect __has_*. +#ifdef __has_feature +# define FMT_HAS_FEATURE(x) __has_feature(x) +#else +# define FMT_HAS_FEATURE(x) 0 +#endif +#ifdef __has_include +# define FMT_HAS_INCLUDE(x) __has_include(x) +#else +# define FMT_HAS_INCLUDE(x) 0 +#endif +#ifdef __has_builtin +# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#else +# define FMT_HAS_BUILTIN(x) 0 +#endif +#ifdef __has_cpp_attribute +# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#endif + +#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \ + (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \ + (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +// Detect C++14 relaxed constexpr. +#ifdef FMT_USE_CONSTEXPR +// Use the provided definition. +#elif FMT_GCC_VERSION >= 702 && FMT_CPLUSPLUS >= 201402L +// GCC only allows constexpr member functions in non-literal types since 7.2: +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66297. +# define FMT_USE_CONSTEXPR 1 +#elif FMT_ICC_VERSION +# define FMT_USE_CONSTEXPR 0 // https://github.com/fmtlib/fmt/issues/1628 +#elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 +# define FMT_USE_CONSTEXPR 1 +#else +# define FMT_USE_CONSTEXPR 0 +#endif +#if FMT_USE_CONSTEXPR +# define FMT_CONSTEXPR constexpr +#else +# define FMT_CONSTEXPR +#endif + +// Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated. +#if !defined(__cpp_lib_is_constant_evaluated) +# define FMT_USE_CONSTEVAL 0 +#elif FMT_CPLUSPLUS < 201709L +# define FMT_USE_CONSTEVAL 0 +#elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10 +# define FMT_USE_CONSTEVAL 0 +#elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000 +# define FMT_USE_CONSTEVAL 0 +#elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L +# define FMT_USE_CONSTEVAL 0 // consteval is broken in Apple clang < 14. +#elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929 +# define FMT_USE_CONSTEVAL 0 // consteval is broken in MSVC VS2019 < 16.10. +#elif defined(__cpp_consteval) +# define FMT_USE_CONSTEVAL 1 +#elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101 +# define FMT_USE_CONSTEVAL 1 +#else +# define FMT_USE_CONSTEVAL 0 +#endif +#if FMT_USE_CONSTEVAL +# define FMT_CONSTEVAL consteval +# define FMT_CONSTEXPR20 constexpr +#else +# define FMT_CONSTEVAL +# define FMT_CONSTEXPR20 +#endif + +// Check if exceptions are disabled. +#ifdef FMT_USE_EXCEPTIONS +// Use the provided definition. +#elif defined(__GNUC__) && !defined(__EXCEPTIONS) +# define FMT_USE_EXCEPTIONS 0 +#elif defined(__clang__) && !defined(__cpp_exceptions) +# define FMT_USE_EXCEPTIONS 0 +#elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS +# define FMT_USE_EXCEPTIONS 0 +#else +# define FMT_USE_EXCEPTIONS 1 +#endif +#if FMT_USE_EXCEPTIONS +# define FMT_TRY try +# define FMT_CATCH(x) catch (x) +#else +# define FMT_TRY if (true) +# define FMT_CATCH(x) if (false) +#endif + +#ifdef FMT_NO_UNIQUE_ADDRESS +// Use the provided definition. +#elif FMT_CPLUSPLUS < 202002L +// Not supported. +#elif FMT_HAS_CPP_ATTRIBUTE(no_unique_address) +# define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]] +// VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485). +#elif FMT_MSC_VERSION >= 1929 && !FMT_CLANG_VERSION +# define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]] +#endif +#ifndef FMT_NO_UNIQUE_ADDRESS +# define FMT_NO_UNIQUE_ADDRESS +#endif + +#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough) +# define FMT_FALLTHROUGH [[fallthrough]] +#elif defined(__clang__) +# define FMT_FALLTHROUGH [[clang::fallthrough]] +#elif FMT_GCC_VERSION >= 700 && \ + (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520) +# define FMT_FALLTHROUGH [[gnu::fallthrough]] +#else +# define FMT_FALLTHROUGH +#endif + +// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings. +#if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__) +# define FMT_NORETURN [[noreturn]] +#else +# define FMT_NORETURN +#endif + +#ifdef FMT_NODISCARD +// Use the provided definition. +#elif FMT_HAS_CPP17_ATTRIBUTE(nodiscard) +# define FMT_NODISCARD [[nodiscard]] +#else +# define FMT_NODISCARD +#endif + +#ifdef FMT_DEPRECATED +// Use the provided definition. +#elif FMT_HAS_CPP14_ATTRIBUTE(deprecated) +# define FMT_DEPRECATED [[deprecated]] +#else +# define FMT_DEPRECATED /* deprecated */ +#endif + +#ifdef FMT_ALWAYS_INLINE +// Use the provided definition. +#elif FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_ALWAYS_INLINE inline __attribute__((always_inline)) +#else +# define FMT_ALWAYS_INLINE inline +#endif +// A version of FMT_ALWAYS_INLINE to prevent code bloat in debug mode. +#ifdef NDEBUG +# define FMT_INLINE FMT_ALWAYS_INLINE +#else +# define FMT_INLINE inline +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_VISIBILITY(value) __attribute__((visibility(value))) +#else +# define FMT_VISIBILITY(value) +#endif + +// Detect pragmas. +#define FMT_PRAGMA_IMPL(x) _Pragma(#x) +#if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER) +// Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884 +// and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582. +# define FMT_PRAGMA_GCC(x) FMT_PRAGMA_IMPL(GCC x) +#else +# define FMT_PRAGMA_GCC(x) +#endif +#if FMT_CLANG_VERSION +# define FMT_PRAGMA_CLANG(x) FMT_PRAGMA_IMPL(clang x) +#else +# define FMT_PRAGMA_CLANG(x) +#endif +#if FMT_MSC_VERSION +# define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__)) +#else +# define FMT_MSC_WARNING(...) +#endif + +#ifndef FMT_BEGIN_NAMESPACE +# define FMT_BEGIN_NAMESPACE \ + namespace fmt { \ + inline namespace v11 { +# define FMT_END_NAMESPACE \ + } \ + } +#endif + +#ifndef FMT_EXPORT +# define FMT_EXPORT +# define FMT_BEGIN_EXPORT +# define FMT_END_EXPORT +#endif + +#ifdef _WIN32 +# define FMT_WIN32 1 +#else +# define FMT_WIN32 0 +#endif + +#if !defined(FMT_HEADER_ONLY) && FMT_WIN32 +# if defined(FMT_LIB_EXPORT) +# define FMT_API __declspec(dllexport) +# elif defined(FMT_SHARED) +# define FMT_API __declspec(dllimport) +# endif +#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) +# define FMT_API FMT_VISIBILITY("default") +#endif +#ifndef FMT_API +# define FMT_API +#endif + +#ifndef FMT_OPTIMIZE_SIZE +# define FMT_OPTIMIZE_SIZE 0 +#endif + +// FMT_BUILTIN_TYPE=0 may result in smaller library size at the cost of higher +// per-call binary size by passing built-in types through the extension API. +#ifndef FMT_BUILTIN_TYPES +# define FMT_BUILTIN_TYPES 1 +#endif + +#define FMT_APPLY_VARIADIC(expr) \ + using unused = int[]; \ + (void)unused { 0, (expr, 0)... } + +// Enable minimal optimizations for more compact code in debug mode. +FMT_PRAGMA_GCC(push_options) +#if !defined(__OPTIMIZE__) && !defined(__CUDACC__) && !defined(FMT_MODULE) +FMT_PRAGMA_GCC(optimize("Og")) +#endif +FMT_PRAGMA_CLANG(diagnostic push) + +FMT_BEGIN_NAMESPACE + +// Implementations of enable_if_t and other metafunctions for older systems. +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; +template using bool_constant = std::integral_constant; +template +using remove_reference_t = typename std::remove_reference::type; +template +using remove_const_t = typename std::remove_const::type; +template +using remove_cvref_t = typename std::remove_cv>::type; +template +using make_unsigned_t = typename std::make_unsigned::type; +template +using underlying_t = typename std::underlying_type::type; +template using decay_t = typename std::decay::type; +using nullptr_t = decltype(nullptr); + +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 500 +// A workaround for gcc 4.9 to make void_t work in a SFINAE context. +template struct void_t_impl { + using type = void; +}; +template using void_t = typename void_t_impl::type; +#else +template using void_t = void; +#endif + +struct monostate { + constexpr 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). +#ifdef FMT_DOC +# define FMT_ENABLE_IF(...) +#else +# define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0 +#endif + +template constexpr auto min_of(T a, T b) -> T { + return a < b ? a : b; +} +template constexpr auto max_of(T a, T b) -> T { + return a > b ? a : b; +} + +namespace detail { +// Suppresses "unused variable" warnings with the method described in +// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/. +// (void)var does not work on many Intel compilers. +template FMT_CONSTEXPR void ignore_unused(const T&...) {} + +constexpr auto is_constant_evaluated(bool default_value = false) noexcept + -> bool { +// Workaround for incompatibility between clang 14 and libstdc++ consteval-based +// std::is_constant_evaluated: https://github.com/fmtlib/fmt/issues/3247. +#if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \ + (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500) + ignore_unused(default_value); + return __builtin_is_constant_evaluated(); +#elif defined(__cpp_lib_is_constant_evaluated) + ignore_unused(default_value); + return std::is_constant_evaluated(); +#else + return default_value; +#endif +} + +// Suppresses "conditional expression is constant" warnings. +template FMT_ALWAYS_INLINE constexpr auto const_check(T val) -> T { + return val; +} + +FMT_NORETURN FMT_API void assert_fail(const char* file, int line, + const char* message); + +#if defined(FMT_ASSERT) +// Use the provided definition. +#elif defined(NDEBUG) +// FMT_ASSERT is not empty to avoid -Wempty-body. +# define FMT_ASSERT(condition, message) \ + fmt::detail::ignore_unused((condition), (message)) +#else +# define FMT_ASSERT(condition, message) \ + ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ + ? (void)0 \ + : fmt::detail::assert_fail(__FILE__, __LINE__, (message))) +#endif + +#ifdef FMT_USE_INT128 +// Use the provided definition. +#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \ + !(FMT_CLANG_VERSION && FMT_MSC_VERSION) +# define FMT_USE_INT128 1 +using int128_opt = __int128_t; // An optional native 128-bit integer. +using uint128_opt = __uint128_t; +inline auto map(int128_opt x) -> int128_opt { return x; } +inline auto map(uint128_opt x) -> uint128_opt { return x; } +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +enum class int128_opt {}; +enum class uint128_opt {}; +// Reduce template instantiations. +inline auto map(int128_opt) -> monostate { return {}; } +inline auto map(uint128_opt) -> monostate { return {}; } +#endif + +#ifndef FMT_USE_BITINT +# define FMT_USE_BITINT (FMT_CLANG_VERSION >= 1500) +#endif + +#if FMT_USE_BITINT +FMT_PRAGMA_CLANG(diagnostic ignored "-Wbit-int-extension") +template using bitint = _BitInt(N); +template using ubitint = unsigned _BitInt(N); +#else +template struct bitint {}; +template struct ubitint {}; +#endif // FMT_USE_BITINT + +// Casts a nonnegative integer to unsigned. +template +FMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t { + FMT_ASSERT(std::is_unsigned::value || value >= 0, "negative value"); + return static_cast>(value); +} + +template +using unsigned_char = conditional_t; + +// A heuristic to detect std::string and std::[experimental::]string_view. +// It is mainly used to avoid dependency on <[experimental/]string_view>. +template +struct is_std_string_like : std::false_type {}; +template +struct is_std_string_like().find_first_of( + typename T::value_type(), 0))>> + : std::is_convertible().data()), + const typename T::value_type*> {}; + +// Check if the literal encoding is UTF-8. +enum { is_utf8_enabled = "\u00A7"[1] == '\xA7' }; +enum { use_utf8 = !FMT_WIN32 || is_utf8_enabled }; + +#ifndef FMT_UNICODE +# define FMT_UNICODE 1 +#endif + +static_assert(!FMT_UNICODE || use_utf8, + "Unicode support requires compiling with /utf-8"); + +template constexpr const char* narrow(const T*) { return nullptr; } +constexpr FMT_ALWAYS_INLINE const char* narrow(const char* s) { return s; } + +template +FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, std::size_t n) + -> int { + if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n); + for (; n != 0; ++s1, ++s2, --n) { + if (*s1 < *s2) return -1; + if (*s1 > *s2) return 1; + } + return 0; +} + +namespace adl { +using namespace std; + +template +auto invoke_back_inserter() + -> decltype(back_inserter(std::declval())); +} // namespace adl + +template +struct is_back_insert_iterator : std::false_type {}; + +template +struct is_back_insert_iterator< + It, bool_constant()), + It>::value>> : std::true_type {}; + +// Extracts a reference to the container from *insert_iterator. +template +inline FMT_CONSTEXPR20 auto get_container(OutputIt it) -> + typename OutputIt::container_type& { + struct accessor : OutputIt { + FMT_CONSTEXPR20 accessor(OutputIt base) : OutputIt(base) {} + using OutputIt::container; + }; + return *accessor(it).container; +} +} // namespace detail + +// Parsing-related public API and forward declarations. +FMT_BEGIN_EXPORT + +/** + * An implementation of `std::basic_string_view` for pre-C++17. It provides a + * subset of the API. `fmt::basic_string_view` is used for format strings even + * if `std::basic_string_view` is available to prevent issues when a library is + * compiled with a different `-std` option than the client code (which is not + * recommended). + */ +template class basic_string_view { + private: + const Char* data_; + size_t size_; + + public: + using value_type = Char; + using iterator = const Char*; + + constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {} + + /// Constructs a string reference object from a C string and a size. + constexpr basic_string_view(const Char* s, size_t count) noexcept + : data_(s), size_(count) {} + + constexpr basic_string_view(nullptr_t) = delete; + + /// Constructs a string reference object from a C string. +#if FMT_GCC_VERSION + FMT_ALWAYS_INLINE +#endif + FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) { +#if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION + if (std::is_same::value) { + size_ = __builtin_strlen(detail::narrow(s)); + return; + } +#endif + size_t len = 0; + while (*s++) ++len; + size_ = len; + } + + /// Constructs a string reference from a `std::basic_string` or a + /// `std::basic_string_view` object. + template ::value&& std::is_same< + typename S::value_type, Char>::value)> + FMT_CONSTEXPR basic_string_view(const S& s) noexcept + : data_(s.data()), size_(s.size()) {} + + /// Returns a pointer to the string data. + constexpr auto data() const noexcept -> const Char* { return data_; } + + /// Returns the string size. + constexpr auto size() const noexcept -> size_t { return size_; } + + constexpr auto begin() const noexcept -> iterator { return data_; } + constexpr auto end() const noexcept -> iterator { return data_ + size_; } + + constexpr auto operator[](size_t pos) const noexcept -> const Char& { + return data_[pos]; + } + + FMT_CONSTEXPR void remove_prefix(size_t n) noexcept { + data_ += n; + size_ -= n; + } + + FMT_CONSTEXPR auto starts_with(basic_string_view sv) const noexcept + -> bool { + return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0; + } + FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool { + return size_ >= 1 && *data_ == c; + } + FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool { + return starts_with(basic_string_view(s)); + } + + // Lexicographically compare this string reference to other. + FMT_CONSTEXPR auto compare(basic_string_view other) const -> int { + int result = + detail::compare(data_, other.data_, min_of(size_, other.size_)); + if (result != 0) return result; + return size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + } + + FMT_CONSTEXPR friend auto operator==(basic_string_view lhs, + basic_string_view rhs) -> bool { + return lhs.compare(rhs) == 0; + } + friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) != 0; + } + friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) < 0; + } + friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) <= 0; + } + friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) > 0; + } + friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) >= 0; + } +}; + +using string_view = basic_string_view; + +/// Specifies if `T` is an extended character type. Can be specialized by users. +template struct is_xchar : std::false_type {}; +template <> struct is_xchar : std::true_type {}; +template <> struct is_xchar : std::true_type {}; +template <> struct is_xchar : std::true_type {}; +#ifdef __cpp_char8_t +template <> struct is_xchar : std::true_type {}; +#endif + +// DEPRECATED! Will be replaced with an alias to prevent specializations. +template struct is_char : is_xchar {}; +template <> struct is_char : std::true_type {}; + +template class basic_appender; +using appender = basic_appender; + +// Checks whether T is a container with contiguous storage. +template struct is_contiguous : std::false_type {}; + +class context; +template class generic_context; +template class parse_context; + +// Longer aliases for C++20 compatibility. +template using basic_format_parse_context = parse_context; +using format_parse_context = parse_context; +template +using basic_format_context = + conditional_t::value, context, + generic_context>; +using format_context = context; + +template +using buffered_context = + conditional_t::value, context, + generic_context, Char>>; + +template class basic_format_arg; +template class basic_format_args; + +// A separate type would result in shorter symbols but break ABI compatibility +// between clang and gcc on ARM (#1919). +using format_args = basic_format_args; + +// A formatter for objects of type T. +template +struct formatter { + // A deleted default constructor indicates a disabled formatter. + formatter() = delete; +}; + +/// Reports a format error at compile time or, via a `format_error` exception, +/// at runtime. +// This function is intentionally not constexpr to give a compile-time error. +FMT_NORETURN FMT_API void report_error(const char* message); + +enum class presentation_type : unsigned char { + // Common specifiers: + none = 0, + debug = 1, // '?' + string = 2, // 's' (string, bool) + + // Integral, bool and character specifiers: + dec = 3, // 'd' + hex, // 'x' or 'X' + oct, // 'o' + bin, // 'b' or 'B' + chr, // 'c' + + // String and pointer specifiers: + pointer = 3, // 'p' + + // Floating-point specifiers: + exp = 1, // 'e' or 'E' (1 since there is no FP debug presentation) + fixed, // 'f' or 'F' + general, // 'g' or 'G' + hexfloat // 'a' or 'A' +}; + +enum class align { none, left, right, center, numeric }; +enum class sign { none, minus, plus, space }; +enum class arg_id_kind { none, index, name }; + +// Basic format specifiers for built-in and string types. +class basic_specs { + private: + // Data is arranged as follows: + // + // 0 1 2 3 + // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + // |type |align| w | p | s |u|#|L| f | unused | + // +-----+-----+---+---+---+-+-+-+-----+---------------------------+ + // + // w - dynamic width info + // p - dynamic precision info + // s - sign + // u - uppercase (e.g. 'X' for 'x') + // # - alternate form ('#') + // L - localized + // f - fill size + // + // Bitfields are not used because of compiler bugs such as gcc bug 61414. + enum : unsigned { + type_mask = 0x00007, + align_mask = 0x00038, + width_mask = 0x000C0, + precision_mask = 0x00300, + sign_mask = 0x00C00, + uppercase_mask = 0x01000, + alternate_mask = 0x02000, + localized_mask = 0x04000, + fill_size_mask = 0x38000, + + align_shift = 3, + width_shift = 6, + precision_shift = 8, + sign_shift = 10, + fill_size_shift = 15, + + max_fill_size = 4 + }; + + unsigned data_ = 1 << fill_size_shift; + static_assert(sizeof(basic_specs::data_) * CHAR_BIT >= 18, ""); + + // Character (code unit) type is erased to prevent template bloat. + char fill_data_[max_fill_size] = {' '}; + + FMT_CONSTEXPR void set_fill_size(size_t size) { + data_ = (data_ & ~fill_size_mask) | + (static_cast(size) << fill_size_shift); + } + + public: + constexpr auto type() const -> presentation_type { + return static_cast(data_ & type_mask); + } + FMT_CONSTEXPR void set_type(presentation_type t) { + data_ = (data_ & ~type_mask) | static_cast(t); + } + + constexpr auto align() const -> align { + return static_cast((data_ & align_mask) >> align_shift); + } + FMT_CONSTEXPR void set_align(fmt::align a) { + data_ = (data_ & ~align_mask) | (static_cast(a) << align_shift); + } + + constexpr auto dynamic_width() const -> arg_id_kind { + return static_cast((data_ & width_mask) >> width_shift); + } + FMT_CONSTEXPR void set_dynamic_width(arg_id_kind w) { + data_ = (data_ & ~width_mask) | (static_cast(w) << width_shift); + } + + FMT_CONSTEXPR auto dynamic_precision() const -> arg_id_kind { + return static_cast((data_ & precision_mask) >> + precision_shift); + } + FMT_CONSTEXPR void set_dynamic_precision(arg_id_kind p) { + data_ = (data_ & ~precision_mask) | + (static_cast(p) << precision_shift); + } + + constexpr bool dynamic() const { + return (data_ & (width_mask | precision_mask)) != 0; + } + + constexpr auto sign() const -> sign { + return static_cast((data_ & sign_mask) >> sign_shift); + } + FMT_CONSTEXPR void set_sign(fmt::sign s) { + data_ = (data_ & ~sign_mask) | (static_cast(s) << sign_shift); + } + + constexpr auto upper() const -> bool { return (data_ & uppercase_mask) != 0; } + FMT_CONSTEXPR void set_upper() { data_ |= uppercase_mask; } + + constexpr auto alt() const -> bool { return (data_ & alternate_mask) != 0; } + FMT_CONSTEXPR void set_alt() { data_ |= alternate_mask; } + FMT_CONSTEXPR void clear_alt() { data_ &= ~alternate_mask; } + + constexpr auto localized() const -> bool { + return (data_ & localized_mask) != 0; + } + FMT_CONSTEXPR void set_localized() { data_ |= localized_mask; } + + constexpr auto fill_size() const -> size_t { + return (data_ & fill_size_mask) >> fill_size_shift; + } + + template ::value)> + constexpr auto fill() const -> const Char* { + return fill_data_; + } + template ::value)> + constexpr auto fill() const -> const Char* { + return nullptr; + } + + template constexpr auto fill_unit() const -> Char { + using uchar = unsigned char; + return static_cast(static_cast(fill_data_[0]) | + (static_cast(fill_data_[1]) << 8) | + (static_cast(fill_data_[2]) << 16)); + } + + FMT_CONSTEXPR void set_fill(char c) { + fill_data_[0] = c; + set_fill_size(1); + } + + template + FMT_CONSTEXPR void set_fill(basic_string_view s) { + auto size = s.size(); + set_fill_size(size); + if (size == 1) { + unsigned uchar = static_cast>(s[0]); + fill_data_[0] = static_cast(uchar); + fill_data_[1] = static_cast(uchar >> 8); + fill_data_[2] = static_cast(uchar >> 16); + return; + } + FMT_ASSERT(size <= max_fill_size, "invalid fill"); + for (size_t i = 0; i < size; ++i) + fill_data_[i & 3] = static_cast(s[i]); + } + + FMT_CONSTEXPR void copy_fill_from(const basic_specs& specs) { + set_fill_size(specs.fill_size()); + for (size_t i = 0; i < max_fill_size; ++i) + fill_data_[i] = specs.fill_data_[i]; + } +}; + +// Format specifiers for built-in and string types. +struct format_specs : basic_specs { + int width; + int precision; + + constexpr format_specs() : width(0), precision(-1) {} +}; + +/** + * Parsing context consisting of a format string range being parsed and an + * argument counter for automatic indexing. + */ +template class parse_context { + private: + basic_string_view fmt_; + int next_arg_id_; + + enum { use_constexpr_cast = !FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200 }; + + FMT_CONSTEXPR void do_check_arg_id(int arg_id); + + public: + using char_type = Char; + using iterator = const Char*; + + constexpr explicit parse_context(basic_string_view fmt, + int next_arg_id = 0) + : fmt_(fmt), next_arg_id_(next_arg_id) {} + + /// Returns an iterator to the beginning of the format string range being + /// parsed. + constexpr auto begin() const noexcept -> iterator { return fmt_.begin(); } + + /// Returns an iterator past the end of the format string range being parsed. + constexpr auto end() const noexcept -> iterator { return fmt_.end(); } + + /// Advances the begin iterator to `it`. + FMT_CONSTEXPR void advance_to(iterator it) { + fmt_.remove_prefix(detail::to_unsigned(it - begin())); + } + + /// Reports an error if using the manual argument indexing; otherwise returns + /// the next argument index and switches to the automatic indexing. + FMT_CONSTEXPR auto next_arg_id() -> int { + if (next_arg_id_ < 0) { + report_error("cannot switch from manual to automatic argument indexing"); + return 0; + } + int id = next_arg_id_++; + do_check_arg_id(id); + return id; + } + + /// Reports an error if using the automatic argument indexing; otherwise + /// switches to the manual indexing. + FMT_CONSTEXPR void check_arg_id(int id) { + if (next_arg_id_ > 0) { + report_error("cannot switch from automatic to manual argument indexing"); + return; + } + next_arg_id_ = -1; + do_check_arg_id(id); + } + FMT_CONSTEXPR void check_arg_id(basic_string_view) { + next_arg_id_ = -1; + } + FMT_CONSTEXPR void check_dynamic_spec(int arg_id); +}; + +FMT_END_EXPORT + +namespace detail { + +// Constructs fmt::basic_string_view from types implicitly convertible +// to it, deducing Char. Explicitly convertible types such as the ones returned +// from FMT_STRING are intentionally excluded. +template ::value)> +constexpr auto to_string_view(const Char* s) -> basic_string_view { + return s; +} +template ::value)> +constexpr auto to_string_view(const T& s) + -> basic_string_view { + return s; +} +template +constexpr auto to_string_view(basic_string_view s) + -> basic_string_view { + return s; +} + +template +struct has_to_string_view : std::false_type {}; +// detail:: is intentional since to_string_view is not an extension point. +template +struct has_to_string_view< + T, void_t()))>> + : std::true_type {}; + +/// String's character (code unit) type. detail:: is intentional to prevent ADL. +template ()))> +using char_t = typename V::value_type; + +enum class type { + none_type, + // Integer types should go first, + int_type, + uint_type, + long_long_type, + ulong_long_type, + int128_type, + uint128_type, + bool_type, + char_type, + last_integer_type = char_type, + // followed by floating-point types. + float_type, + double_type, + long_double_type, + last_numeric_type = long_double_type, + cstring_type, + string_type, + pointer_type, + custom_type +}; + +// Maps core type T to the corresponding type enum constant. +template +struct type_constant : std::integral_constant {}; + +#define FMT_TYPE_CONSTANT(Type, constant) \ + template \ + struct type_constant \ + : std::integral_constant {} + +FMT_TYPE_CONSTANT(int, int_type); +FMT_TYPE_CONSTANT(unsigned, uint_type); +FMT_TYPE_CONSTANT(long long, long_long_type); +FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); +FMT_TYPE_CONSTANT(int128_opt, int128_type); +FMT_TYPE_CONSTANT(uint128_opt, uint128_type); +FMT_TYPE_CONSTANT(bool, bool_type); +FMT_TYPE_CONSTANT(Char, char_type); +FMT_TYPE_CONSTANT(float, float_type); +FMT_TYPE_CONSTANT(double, double_type); +FMT_TYPE_CONSTANT(long double, long_double_type); +FMT_TYPE_CONSTANT(const Char*, cstring_type); +FMT_TYPE_CONSTANT(basic_string_view, string_type); +FMT_TYPE_CONSTANT(const void*, pointer_type); + +constexpr auto is_integral_type(type t) -> bool { + return t > type::none_type && t <= type::last_integer_type; +} +constexpr auto is_arithmetic_type(type t) -> bool { + return t > type::none_type && t <= type::last_numeric_type; +} + +constexpr auto set(type rhs) -> int { return 1 << static_cast(rhs); } +constexpr auto in(type t, int set) -> bool { + return ((set >> static_cast(t)) & 1) != 0; +} + +// Bitsets of types. +enum { + sint_set = + set(type::int_type) | set(type::long_long_type) | set(type::int128_type), + uint_set = set(type::uint_type) | set(type::ulong_long_type) | + set(type::uint128_type), + bool_set = set(type::bool_type), + char_set = set(type::char_type), + float_set = set(type::float_type) | set(type::double_type) | + set(type::long_double_type), + string_set = set(type::string_type), + cstring_set = set(type::cstring_type), + pointer_set = set(type::pointer_type) +}; + +struct view {}; + +template struct named_arg; +template struct is_named_arg : std::false_type {}; +template struct is_static_named_arg : std::false_type {}; + +template +struct is_named_arg> : std::true_type {}; + +template struct named_arg : view { + const Char* name; + const T& value; + + named_arg(const Char* n, const T& v) : name(n), value(v) {} + static_assert(!is_named_arg::value, "nested named arguments"); +}; + +template constexpr auto count() -> int { return B ? 1 : 0; } +template constexpr auto count() -> int { + return (B1 ? 1 : 0) + count(); +} + +template constexpr auto count_named_args() -> int { + return count::value...>(); +} +template constexpr auto count_static_named_args() -> int { + return count::value...>(); +} + +template struct named_arg_info { + const Char* name; + int id; +}; + +template ::value)> +void init_named_arg(named_arg_info*, int& arg_index, int&, const T&) { + ++arg_index; +} +template ::value)> +void init_named_arg(named_arg_info* named_args, int& arg_index, + int& named_arg_index, const T& arg) { + named_args[named_arg_index++] = {arg.name, arg_index++}; +} + +template ::value)> +FMT_CONSTEXPR void init_static_named_arg(named_arg_info*, int& arg_index, + int&) { + ++arg_index; +} +template ::value)> +FMT_CONSTEXPR void init_static_named_arg(named_arg_info* named_args, + int& arg_index, int& named_arg_index) { + named_args[named_arg_index++] = {T::name, arg_index++}; +} + +// 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; +using ulong_type = conditional_t; + +template +using format_as_result = + remove_cvref_t()))>; +template +using format_as_member_result = + remove_cvref_t::format_as(std::declval()))>; + +template +struct use_format_as : std::false_type {}; +// format_as member is only used to avoid injection into the std namespace. +template +struct use_format_as_member : std::false_type {}; + +// Only map owning types because mapping views can be unsafe. +template +struct use_format_as< + T, bool_constant>::value>> + : std::true_type {}; +template +struct use_format_as_member< + T, bool_constant>::value>> + : std::true_type {}; + +template > +using use_formatter = + bool_constant<(std::is_class::value || std::is_enum::value || + std::is_union::value || std::is_array::value) && + !has_to_string_view::value && !is_named_arg::value && + !use_format_as::value && !use_format_as_member::value>; + +template > +auto has_formatter_impl(T* p, buffered_context* ctx = nullptr) + -> decltype(formatter().format(*p, *ctx), std::true_type()); +template auto has_formatter_impl(...) -> std::false_type; + +// T can be const-qualified to check if it is const-formattable. +template constexpr auto has_formatter() -> bool { + return decltype(has_formatter_impl(static_cast(nullptr)))::value; +} + +// Maps formatting argument types to natively supported types or user-defined +// types with formatters. Returns void on errors to be SFINAE-friendly. +template struct type_mapper { + static auto map(signed char) -> int; + static auto map(unsigned char) -> unsigned; + static auto map(short) -> int; + static auto map(unsigned short) -> unsigned; + static auto map(int) -> int; + static auto map(unsigned) -> unsigned; + static auto map(long) -> long_type; + static auto map(unsigned long) -> ulong_type; + static auto map(long long) -> long long; + static auto map(unsigned long long) -> unsigned long long; + static auto map(int128_opt) -> int128_opt; + static auto map(uint128_opt) -> uint128_opt; + static auto map(bool) -> bool; + + template + static auto map(bitint) -> conditional_t; + template + static auto map(ubitint) + -> conditional_t; + + template ::value)> + static auto map(T) -> conditional_t< + std::is_same::value || std::is_same::value, Char, void>; + + static auto map(float) -> float; + static auto map(double) -> double; + static auto map(long double) -> long double; + + static auto map(Char*) -> const Char*; + static auto map(const Char*) -> const Char*; + template , + FMT_ENABLE_IF(!std::is_pointer::value)> + static auto map(const T&) -> conditional_t::value, + basic_string_view, void>; + + static auto map(void*) -> const void*; + static auto map(const void*) -> const void*; + static auto map(volatile void*) -> const void*; + static auto map(const volatile void*) -> const void*; + static auto map(nullptr_t) -> const void*; + template ::value || + std::is_member_pointer::value)> + static auto map(const T&) -> void; + + template ::value)> + static auto map(const T& x) -> decltype(map(format_as(x))); + template ::value)> + static auto map(const T& x) -> decltype(map(formatter::format_as(x))); + + template ::value)> + static auto map(T&) -> conditional_t(), T&, void>; + + template ::value)> + static auto map(const T& named_arg) -> decltype(map(named_arg.value)); +}; + +// detail:: is used to workaround a bug in MSVC 2017. +template +using mapped_t = decltype(detail::type_mapper::map(std::declval())); + +// A type constant after applying type_mapper. +template +using mapped_type_constant = type_constant, Char>; + +template ::value> +using stored_type_constant = std::integral_constant< + type, Context::builtin_types || TYPE == type::int_type ? TYPE + : type::custom_type>; +// A parse context with extra data used only in compile-time checks. +template +class compile_parse_context : public parse_context { + private: + int num_args_; + const type* types_; + using base = parse_context; + + public: + FMT_CONSTEXPR explicit compile_parse_context(basic_string_view fmt, + int num_args, const type* types, + int next_arg_id = 0) + : base(fmt, next_arg_id), num_args_(num_args), types_(types) {} + + constexpr auto num_args() const -> int { return num_args_; } + constexpr auto arg_type(int id) const -> type { return types_[id]; } + + FMT_CONSTEXPR auto next_arg_id() -> int { + int id = base::next_arg_id(); + if (id >= num_args_) report_error("argument not found"); + return id; + } + + FMT_CONSTEXPR void check_arg_id(int id) { + base::check_arg_id(id); + if (id >= num_args_) report_error("argument not found"); + } + using base::check_arg_id; + + FMT_CONSTEXPR void check_dynamic_spec(int arg_id) { + ignore_unused(arg_id); + if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id])) + report_error("width/precision is not integer"); + } +}; + +// An argument reference. +template union arg_ref { + FMT_CONSTEXPR arg_ref(int idx = 0) : index(idx) {} + FMT_CONSTEXPR arg_ref(basic_string_view n) : name(n) {} + + int index; + basic_string_view name; +}; + +// Format specifiers with width and precision resolved at formatting rather +// than parsing time to allow reusing the same parsed specifiers with +// different sets of arguments (precompilation of format strings). +template struct dynamic_format_specs : format_specs { + arg_ref width_ref; + arg_ref precision_ref; +}; + +// Converts a character to ASCII. Returns '\0' on conversion failure. +template ::value)> +constexpr auto to_ascii(Char c) -> char { + return c <= 0xff ? static_cast(c) : '\0'; +} + +// Returns the number of code units in a code point or 1 on error. +template +FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int { + if (const_check(sizeof(Char) != 1)) return 1; + auto c = static_cast(*begin); + return static_cast((0x3a55000000000000ull >> (2 * (c >> 3))) & 3) + 1; +} + +// Parses the range [begin, end) as an unsigned integer. This function assumes +// that the range is non-empty and the first character is a digit. +template +FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end, + int error_value) noexcept -> int { + FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); + unsigned value = 0, prev = 0; + auto p = begin; + do { + prev = value; + value = value * 10 + unsigned(*p - '0'); + ++p; + } while (p != end && '0' <= *p && *p <= '9'); + auto num_digits = p - begin; + begin = p; + int digits10 = static_cast(sizeof(int) * CHAR_BIT * 3 / 10); + if (num_digits <= digits10) return static_cast(value); + // Check for overflow. + unsigned max = INT_MAX; + return num_digits == digits10 + 1 && + prev * 10ull + unsigned(p[-1] - '0') <= max + ? static_cast(value) + : error_value; +} + +FMT_CONSTEXPR inline auto parse_align(char c) -> align { + switch (c) { + case '<': return align::left; + case '>': return align::right; + case '^': return align::center; + } + return align::none; +} + +template constexpr auto is_name_start(Char c) -> bool { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; +} + +template +FMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + Char c = *begin; + if (c >= '0' && c <= '9') { + int index = 0; + if (c != '0') + index = parse_nonnegative_int(begin, end, INT_MAX); + else + ++begin; + if (begin == end || (*begin != '}' && *begin != ':')) + report_error("invalid format string"); + else + handler.on_index(index); + return begin; + } + if (FMT_OPTIMIZE_SIZE > 1 || !is_name_start(c)) { + report_error("invalid format string"); + return begin; + } + auto it = begin; + do { + ++it; + } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9'))); + handler.on_name({begin, to_unsigned(it - begin)}); + return it; +} + +template struct dynamic_spec_handler { + parse_context& ctx; + arg_ref& ref; + arg_id_kind& kind; + + FMT_CONSTEXPR void on_index(int id) { + ref = id; + kind = arg_id_kind::index; + ctx.check_arg_id(id); + ctx.check_dynamic_spec(id); + } + FMT_CONSTEXPR void on_name(basic_string_view id) { + ref = id; + kind = arg_id_kind::name; + ctx.check_arg_id(id); + } +}; + +template struct parse_dynamic_spec_result { + const Char* end; + arg_id_kind kind; +}; + +// Parses integer | "{" [arg_id] "}". +template +FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end, + int& value, arg_ref& ref, + parse_context& ctx) + -> parse_dynamic_spec_result { + FMT_ASSERT(begin != end, ""); + auto kind = arg_id_kind::none; + if ('0' <= *begin && *begin <= '9') { + int val = parse_nonnegative_int(begin, end, -1); + if (val == -1) report_error("number is too big"); + value = val; + } else { + if (*begin == '{') { + ++begin; + if (begin != end) { + Char c = *begin; + if (c == '}' || c == ':') { + int id = ctx.next_arg_id(); + ref = id; + kind = arg_id_kind::index; + ctx.check_dynamic_spec(id); + } else { + begin = parse_arg_id(begin, end, + dynamic_spec_handler{ctx, ref, kind}); + } + } + if (begin != end && *begin == '}') return {++begin, kind}; + } + report_error("invalid format string"); + } + return {begin, kind}; +} + +template +FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end, + format_specs& specs, arg_ref& width_ref, + parse_context& ctx) -> const Char* { + auto result = parse_dynamic_spec(begin, end, specs.width, width_ref, ctx); + specs.set_dynamic_width(result.kind); + return result.end; +} + +template +FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end, + format_specs& specs, + arg_ref& precision_ref, + parse_context& ctx) -> const Char* { + ++begin; + if (begin == end) { + report_error("invalid precision"); + return begin; + } + auto result = + parse_dynamic_spec(begin, end, specs.precision, precision_ref, ctx); + specs.set_dynamic_precision(result.kind); + return result.end; +} + +enum class state { start, align, sign, hash, zero, width, precision, locale }; + +// Parses standard format specifiers. +template +FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end, + dynamic_format_specs& specs, + parse_context& ctx, type arg_type) + -> const Char* { + auto c = '\0'; + if (end - begin > 1) { + auto next = to_ascii(begin[1]); + c = parse_align(next) == align::none ? to_ascii(*begin) : '\0'; + } else { + if (begin == end) return begin; + c = to_ascii(*begin); + } + + struct { + state current_state = state::start; + FMT_CONSTEXPR void operator()(state s, bool valid = true) { + if (current_state >= s || !valid) + report_error("invalid format specifier"); + current_state = s; + } + } enter_state; + + using pres = presentation_type; + constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; + struct { + const Char*& begin; + format_specs& specs; + type arg_type; + + FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* { + if (!in(arg_type, set)) report_error("invalid format specifier"); + specs.set_type(pres_type); + return begin + 1; + } + } parse_presentation_type{begin, specs, arg_type}; + + for (;;) { + switch (c) { + case '<': + case '>': + case '^': + enter_state(state::align); + specs.set_align(parse_align(c)); + ++begin; + break; + case '+': + case ' ': + specs.set_sign(c == ' ' ? sign::space : sign::plus); + FMT_FALLTHROUGH; + case '-': + enter_state(state::sign, in(arg_type, sint_set | float_set)); + ++begin; + break; + case '#': + enter_state(state::hash, is_arithmetic_type(arg_type)); + specs.set_alt(); + ++begin; + break; + case '0': + enter_state(state::zero); + if (!is_arithmetic_type(arg_type)) + report_error("format specifier requires numeric argument"); + if (specs.align() == align::none) { + // Ignore 0 if align is specified for compatibility with std::format. + specs.set_align(align::numeric); + specs.set_fill('0'); + } + ++begin; + break; + // clang-format off + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': case '{': + // clang-format on + enter_state(state::width); + begin = parse_width(begin, end, specs, specs.width_ref, ctx); + break; + case '.': + enter_state(state::precision, + in(arg_type, float_set | string_set | cstring_set)); + begin = parse_precision(begin, end, specs, specs.precision_ref, ctx); + break; + case 'L': + enter_state(state::locale, is_arithmetic_type(arg_type)); + specs.set_localized(); + ++begin; + break; + case 'd': return parse_presentation_type(pres::dec, integral_set); + case 'X': specs.set_upper(); FMT_FALLTHROUGH; + case 'x': return parse_presentation_type(pres::hex, integral_set); + case 'o': return parse_presentation_type(pres::oct, integral_set); + case 'B': specs.set_upper(); FMT_FALLTHROUGH; + case 'b': return parse_presentation_type(pres::bin, integral_set); + case 'E': specs.set_upper(); FMT_FALLTHROUGH; + case 'e': return parse_presentation_type(pres::exp, float_set); + case 'F': specs.set_upper(); FMT_FALLTHROUGH; + case 'f': return parse_presentation_type(pres::fixed, float_set); + case 'G': specs.set_upper(); FMT_FALLTHROUGH; + case 'g': return parse_presentation_type(pres::general, float_set); + case 'A': specs.set_upper(); FMT_FALLTHROUGH; + case 'a': return parse_presentation_type(pres::hexfloat, float_set); + case 'c': + if (arg_type == type::bool_type) report_error("invalid format specifier"); + return parse_presentation_type(pres::chr, integral_set); + case 's': + return parse_presentation_type(pres::string, + bool_set | string_set | cstring_set); + case 'p': + return parse_presentation_type(pres::pointer, pointer_set | cstring_set); + case '?': + return parse_presentation_type(pres::debug, + char_set | string_set | cstring_set); + case '}': return begin; + default: { + if (*begin == '}') return begin; + // Parse fill and alignment. + auto fill_end = begin + code_point_length(begin); + if (end - fill_end <= 0) { + report_error("invalid format specifier"); + return begin; + } + if (*begin == '{') { + report_error("invalid fill character '{'"); + return begin; + } + auto alignment = parse_align(to_ascii(*fill_end)); + enter_state(state::align, alignment != align::none); + specs.set_fill( + basic_string_view(begin, to_unsigned(fill_end - begin))); + specs.set_align(alignment); + begin = fill_end + 1; + } + } + if (begin == end) return begin; + c = to_ascii(*begin); + } +} + +template +FMT_CONSTEXPR FMT_INLINE auto parse_replacement_field(const Char* begin, + const Char* end, + Handler&& handler) + -> const Char* { + ++begin; + if (begin == end) { + handler.on_error("invalid format string"); + return end; + } + int arg_id = 0; + switch (*begin) { + case '}': + handler.on_replacement_field(handler.on_arg_id(), begin); + return begin + 1; + case '{': handler.on_text(begin, begin + 1); return begin + 1; + case ':': arg_id = handler.on_arg_id(); break; + default: { + struct id_adapter { + Handler& handler; + int arg_id; + + FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); } + FMT_CONSTEXPR void on_name(basic_string_view id) { + arg_id = handler.on_arg_id(id); + } + } adapter = {handler, 0}; + begin = parse_arg_id(begin, end, adapter); + arg_id = adapter.arg_id; + Char c = begin != end ? *begin : Char(); + if (c == '}') { + handler.on_replacement_field(arg_id, begin); + return begin + 1; + } + if (c != ':') { + handler.on_error("missing '}' in format string"); + return end; + } + break; + } + } + begin = handler.on_format_specs(arg_id, begin + 1, end); + if (begin == end || *begin != '}') + return handler.on_error("unknown format specifier"), end; + return begin + 1; +} + +template +FMT_CONSTEXPR void parse_format_string(basic_string_view fmt, + Handler&& handler) { + auto begin = fmt.data(), end = begin + fmt.size(); + auto p = begin; + while (p != end) { + auto c = *p++; + if (c == '{') { + handler.on_text(begin, p - 1); + begin = p = parse_replacement_field(p - 1, end, handler); + } else if (c == '}') { + if (p == end || *p != '}') + return handler.on_error("unmatched '}' in format string"); + handler.on_text(begin, p); + begin = ++p; + } + } + handler.on_text(begin, end); +} + +// Checks char specs and returns true iff the presentation type is char-like. +FMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool { + auto type = specs.type(); + if (type != presentation_type::none && type != presentation_type::chr && + type != presentation_type::debug) { + return false; + } + if (specs.align() == align::numeric || specs.sign() != sign::none || + specs.alt()) { + report_error("invalid format specifier for char"); + } + return true; +} + +// A base class for compile-time strings. +struct compile_string {}; + +template +FMT_VISIBILITY("hidden") // Suppress an ld warning on macOS (#3769). +FMT_CONSTEXPR auto invoke_parse(parse_context& ctx) -> const Char* { + using mapped_type = remove_cvref_t>; + constexpr bool formattable = + std::is_constructible>::value; + if (!formattable) return ctx.begin(); // Error is reported in the value ctor. + using formatted_type = conditional_t; + return formatter().parse(ctx); +} + +template struct arg_pack {}; + +template +class format_string_checker { + private: + type types_[max_of(1, NUM_ARGS)]; + named_arg_info named_args_[max_of(1, NUM_NAMED_ARGS)]; + compile_parse_context context_; + + using parse_func = auto (*)(parse_context&) -> const Char*; + parse_func parse_funcs_[max_of(1, NUM_ARGS)]; + + public: + template + FMT_CONSTEXPR explicit format_string_checker(basic_string_view fmt, + arg_pack) + : types_{mapped_type_constant::value...}, + named_args_{}, + context_(fmt, NUM_ARGS, types_), + parse_funcs_{&invoke_parse...} { + int arg_index = 0, named_arg_index = 0; + FMT_APPLY_VARIADIC( + init_static_named_arg(named_args_, arg_index, named_arg_index)); + ignore_unused(arg_index, named_arg_index); + } + + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + + FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + context_.check_arg_id(id); + return id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { + for (int i = 0; i < NUM_NAMED_ARGS; ++i) { + if (named_args_[i].name == id) return named_args_[i].id; + } + if (!DYNAMIC_NAMES) on_error("argument not found"); + return -1; + } + + FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) { + on_format_specs(id, begin, begin); // Call parse() on empty specs. + } + + FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char* end) + -> const Char* { + context_.advance_to(begin); + if (id >= 0 && id < NUM_ARGS) return parse_funcs_[id](context_); + while (begin != end && *begin != '}') ++begin; + return begin; + } + + FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) { + report_error(message); + } +}; + +/// A contiguous memory buffer with an optional growing ability. It is an +/// internal class and shouldn't be used directly, only via `memory_buffer`. +template class buffer { + private: + T* ptr_; + size_t size_; + size_t capacity_; + + using grow_fun = void (*)(buffer& buf, size_t capacity); + grow_fun grow_; + + protected: + // Don't initialize ptr_ since it is not accessed to save a few cycles. + FMT_MSC_WARNING(suppress : 26495) + FMT_CONSTEXPR buffer(grow_fun grow, size_t sz) noexcept + : size_(sz), capacity_(sz), grow_(grow) {} + + constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0, + size_t cap = 0) noexcept + : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {} + + FMT_CONSTEXPR20 ~buffer() = default; + buffer(buffer&&) = default; + + /// Sets the buffer data and capacity. + FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept { + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + public: + using value_type = T; + using const_reference = const T&; + + buffer(const buffer&) = delete; + void operator=(const buffer&) = delete; + + auto begin() noexcept -> T* { return ptr_; } + auto end() noexcept -> T* { return ptr_ + size_; } + + auto begin() const noexcept -> const T* { return ptr_; } + auto end() const noexcept -> const T* { return ptr_ + size_; } + + /// Returns the size of this buffer. + constexpr auto size() const noexcept -> size_t { return size_; } + + /// Returns the capacity of this buffer. + constexpr auto capacity() const noexcept -> size_t { return capacity_; } + + /// Returns a pointer to the buffer data (not null-terminated). + FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; } + FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; } + + /// Clears this buffer. + FMT_CONSTEXPR void clear() { size_ = 0; } + + // Tries resizing the buffer to contain `count` elements. If T is a POD type + // the new elements may not be initialized. + FMT_CONSTEXPR void try_resize(size_t count) { + try_reserve(count); + size_ = min_of(count, capacity_); + } + + // Tries increasing the buffer capacity to `new_capacity`. It can increase the + // capacity by a smaller amount than requested but guarantees there is space + // for at least one additional element either by increasing the capacity or by + // flushing the buffer if it is full. + FMT_CONSTEXPR void try_reserve(size_t new_capacity) { + if (new_capacity > capacity_) grow_(*this, new_capacity); + } + + FMT_CONSTEXPR void push_back(const T& value) { + try_reserve(size_ + 1); + ptr_[size_++] = value; + } + + /// Appends data to the end of the buffer. + template +// Workaround for MSVC2019 to fix error C2893: Failed to specialize function +// template 'void fmt::v11::detail::buffer::append(const U *,const U *)'. +#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1940 + FMT_CONSTEXPR20 +#endif + void + append(const U* begin, const U* end) { + while (begin != end) { + auto count = to_unsigned(end - begin); + try_reserve(size_ + count); + auto free_cap = capacity_ - size_; + if (free_cap < count) count = free_cap; + // A loop is faster than memcpy on small sizes. + T* out = ptr_ + size_; + for (size_t i = 0; i < count; ++i) out[i] = begin[i]; + size_ += count; + begin += count; + } + } + + template FMT_CONSTEXPR auto operator[](Idx index) -> T& { + return ptr_[index]; + } + template + FMT_CONSTEXPR auto operator[](Idx index) const -> const T& { + return ptr_[index]; + } +}; + +struct buffer_traits { + constexpr explicit buffer_traits(size_t) {} + constexpr auto count() const -> size_t { return 0; } + constexpr auto limit(size_t size) const -> size_t { return size; } +}; + +class fixed_buffer_traits { + private: + size_t count_ = 0; + size_t limit_; + + public: + constexpr explicit fixed_buffer_traits(size_t limit) : limit_(limit) {} + constexpr auto count() const -> size_t { return count_; } + FMT_CONSTEXPR auto limit(size_t size) -> size_t { + size_t n = limit_ > count_ ? limit_ - count_ : 0; + count_ += size; + return min_of(size, n); + } +}; + +// A buffer that writes to an output iterator when flushed. +template +class iterator_buffer : public Traits, public buffer { + private: + OutputIt out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() == buffer_size) static_cast(buf).flush(); + } + + void flush() { + auto size = this->size(); + this->clear(); + const T* begin = data_; + const T* end = begin + this->limit(size); + while (begin != end) *out_++ = *begin++; + } + + public: + explicit iterator_buffer(OutputIt out, size_t n = buffer_size) + : Traits(n), buffer(grow, data_, 0, buffer_size), out_(out) {} + iterator_buffer(iterator_buffer&& other) noexcept + : Traits(other), + buffer(grow, data_, 0, buffer_size), + out_(other.out_) {} + ~iterator_buffer() { + // Don't crash if flush fails during unwinding. + FMT_TRY { flush(); } + FMT_CATCH(...) {} + } + + auto out() -> OutputIt { + flush(); + return out_; + } + auto count() const -> size_t { return Traits::count() + this->size(); } +}; + +template +class iterator_buffer : public fixed_buffer_traits, + public buffer { + private: + T* out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() == buf.capacity()) + static_cast(buf).flush(); + } + + void flush() { + size_t n = this->limit(this->size()); + if (this->data() == out_) { + out_ += n; + this->set(data_, buffer_size); + } + this->clear(); + } + + public: + explicit iterator_buffer(T* out, size_t n = buffer_size) + : fixed_buffer_traits(n), buffer(grow, out, 0, n), out_(out) {} + iterator_buffer(iterator_buffer&& other) noexcept + : fixed_buffer_traits(other), + buffer(static_cast(other)), + out_(other.out_) { + if (this->data() != out_) { + this->set(data_, buffer_size); + this->clear(); + } + } + ~iterator_buffer() { flush(); } + + auto out() -> T* { + flush(); + return out_; + } + auto count() const -> size_t { + return fixed_buffer_traits::count() + this->size(); + } +}; + +template class iterator_buffer : public buffer { + public: + explicit iterator_buffer(T* out, size_t = 0) + : buffer([](buffer&, size_t) {}, out, 0, ~size_t()) {} + + auto out() -> T* { return &*this->end(); } +}; + +template +class container_buffer : public buffer { + private: + using value_type = typename Container::value_type; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t capacity) { + auto& self = static_cast(buf); + self.container.resize(capacity); + self.set(&self.container[0], capacity); + } + + public: + Container& container; + + explicit container_buffer(Container& c) + : buffer(grow, c.size()), container(c) {} +}; + +// A buffer that writes to a container with the contiguous storage. +template +class iterator_buffer< + OutputIt, + enable_if_t::value && + is_contiguous::value, + typename OutputIt::container_type::value_type>> + : public container_buffer { + private: + using base = container_buffer; + + public: + explicit iterator_buffer(typename OutputIt::container_type& c) : base(c) {} + explicit iterator_buffer(OutputIt out, size_t = 0) + : base(get_container(out)) {} + + auto out() -> OutputIt { return OutputIt(this->container); } +}; + +// A buffer that counts the number of code units written discarding the output. +template class counting_buffer : public buffer { + private: + enum { buffer_size = 256 }; + T data_[buffer_size]; + size_t count_ = 0; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() != buffer_size) return; + static_cast(buf).count_ += buf.size(); + buf.clear(); + } + + public: + FMT_CONSTEXPR counting_buffer() : buffer(grow, data_, 0, buffer_size) {} + + constexpr auto count() const noexcept -> size_t { + return count_ + this->size(); + } +}; + +template +struct is_back_insert_iterator> : std::true_type {}; + +template +struct has_back_insert_iterator_container_append : std::false_type {}; +template +struct has_back_insert_iterator_container_append< + OutputIt, InputIt, + void_t()) + .append(std::declval(), + std::declval()))>> : std::true_type {}; + +// An optimized version of std::copy with the output value type (T). +template ::value&& + has_back_insert_iterator_container_append< + OutputIt, InputIt>::value)> +FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out) + -> OutputIt { + get_container(out).append(begin, end); + return out; +} + +template ::value && + !has_back_insert_iterator_container_append< + OutputIt, InputIt>::value)> +FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out) + -> OutputIt { + auto& c = get_container(out); + c.insert(c.end(), begin, end); + return out; +} + +template ::value)> +FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt { + while (begin != end) *out++ = static_cast(*begin++); + return out; +} + +template +FMT_CONSTEXPR auto copy(basic_string_view s, OutputIt out) -> OutputIt { + return copy(s.begin(), s.end(), out); +} + +template +struct is_buffer_appender : std::false_type {}; +template +struct is_buffer_appender< + It, bool_constant< + is_back_insert_iterator::value && + std::is_base_of, + typename It::container_type>::value>> + : std::true_type {}; + +// Maps an output iterator to a buffer. +template ::value)> +auto get_buffer(OutputIt out) -> iterator_buffer { + return iterator_buffer(out); +} +template ::value)> +auto get_buffer(OutputIt out) -> buffer& { + return get_container(out); +} + +template +auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) { + return buf.out(); +} +template +auto get_iterator(buffer&, OutputIt out) -> OutputIt { + return out; +} + +// This type is intentionally undefined, only used for errors. +template struct type_is_unformattable_for; + +template struct string_value { + const Char* data; + size_t size; + auto str() const -> basic_string_view { return {data, size}; } +}; + +template struct custom_value { + using char_type = typename Context::char_type; + void* value; + void (*format)(void* arg, parse_context& parse_ctx, Context& ctx); +}; + +template struct named_arg_value { + const named_arg_info* data; + size_t size; +}; + +struct custom_tag {}; + +#if !FMT_BUILTIN_TYPES +# define FMT_BUILTIN , monostate +#else +# define FMT_BUILTIN +#endif + +// A formatting argument value. +template class value { + public: + using char_type = typename Context::char_type; + + union { + monostate no_value; + int int_value; + unsigned uint_value; + long long long_long_value; + unsigned long long ulong_long_value; + int128_opt int128_value; + uint128_opt uint128_value; + bool bool_value; + char_type char_value; + float float_value; + double double_value; + long double long_double_value; + const void* pointer; + string_value string; + custom_value custom; + named_arg_value named_args; + }; + + constexpr FMT_INLINE value() : no_value() {} + constexpr FMT_INLINE value(signed char x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned char x FMT_BUILTIN) : uint_value(x) {} + constexpr FMT_INLINE value(signed short x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned short x FMT_BUILTIN) : uint_value(x) {} + constexpr FMT_INLINE value(int x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned x FMT_BUILTIN) : uint_value(x) {} + FMT_CONSTEXPR FMT_INLINE value(long x FMT_BUILTIN) : value(long_type(x)) {} + FMT_CONSTEXPR FMT_INLINE value(unsigned long x FMT_BUILTIN) + : value(ulong_type(x)) {} + constexpr FMT_INLINE value(long long x FMT_BUILTIN) : long_long_value(x) {} + constexpr FMT_INLINE value(unsigned long long x FMT_BUILTIN) + : ulong_long_value(x) {} + FMT_INLINE value(int128_opt x FMT_BUILTIN) : int128_value(x) {} + FMT_INLINE value(uint128_opt x FMT_BUILTIN) : uint128_value(x) {} + constexpr FMT_INLINE value(bool x FMT_BUILTIN) : bool_value(x) {} + + template + constexpr FMT_INLINE value(bitint x FMT_BUILTIN) : long_long_value(x) { + static_assert(N <= 64, "unsupported _BitInt"); + } + template + constexpr FMT_INLINE value(ubitint x FMT_BUILTIN) : ulong_long_value(x) { + static_assert(N <= 64, "unsupported _BitInt"); + } + + template ::value)> + constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) { + static_assert( + std::is_same::value || std::is_same::value, + "mixing character types is disallowed"); + } + + constexpr FMT_INLINE value(float x FMT_BUILTIN) : float_value(x) {} + constexpr FMT_INLINE value(double x FMT_BUILTIN) : double_value(x) {} + FMT_INLINE value(long double x FMT_BUILTIN) : long_double_value(x) {} + + FMT_CONSTEXPR FMT_INLINE value(char_type* x FMT_BUILTIN) { + string.data = x; + if (is_constant_evaluated()) string.size = 0; + } + FMT_CONSTEXPR FMT_INLINE value(const char_type* x FMT_BUILTIN) { + string.data = x; + if (is_constant_evaluated()) string.size = 0; + } + template , + FMT_ENABLE_IF(!std::is_pointer::value)> + FMT_CONSTEXPR value(const T& x FMT_BUILTIN) { + static_assert(std::is_same::value, + "mixing character types is disallowed"); + auto sv = to_string_view(x); + string.data = sv.data(); + string.size = sv.size(); + } + FMT_INLINE value(void* x FMT_BUILTIN) : pointer(x) {} + FMT_INLINE value(const void* x FMT_BUILTIN) : pointer(x) {} + FMT_INLINE value(volatile void* x FMT_BUILTIN) + : pointer(const_cast(x)) {} + FMT_INLINE value(const volatile void* x FMT_BUILTIN) + : pointer(const_cast(x)) {} + FMT_INLINE value(nullptr_t) : pointer(nullptr) {} + + template ::value || + std::is_member_pointer::value)> + value(const T&) { + // Formatting of arbitrary pointers is disallowed. If you want to format a + // pointer cast it to `void*` or `const void*`. In particular, this forbids + // formatting of `[const] volatile char*` printed as bool by iostreams. + static_assert(sizeof(T) == 0, + "formatting of non-void pointers is disallowed"); + } + + template ::value)> + value(const T& x) : value(format_as(x)) {} + template ::value)> + value(const T& x) : value(formatter::format_as(x)) {} + + template ::value)> + value(const T& named_arg) : value(named_arg.value) {} + + template ::value || !FMT_BUILTIN_TYPES)> + FMT_CONSTEXPR20 FMT_INLINE value(T& x) : value(x, custom_tag()) {} + + FMT_ALWAYS_INLINE value(const named_arg_info* args, size_t size) + : named_args{args, size} {} + + private: + template ())> + FMT_CONSTEXPR value(T& x, custom_tag) { + using value_type = remove_const_t; + // T may overload operator& e.g. std::vector::reference in libc++. + if (!is_constant_evaluated()) { + custom.value = + const_cast(&reinterpret_cast(x)); + } else { + custom.value = nullptr; +#if defined(__cpp_if_constexpr) + if constexpr (std::is_same*>::value) + custom.value = const_cast(&x); +#endif + } + custom.format = format_custom>; + } + + template ())> + FMT_CONSTEXPR value(const T&, custom_tag) { + // Cannot format an argument; to make type T formattable provide a + // formatter specialization: https://fmt.dev/latest/api.html#udt. + type_is_unformattable_for _; + } + + // Formats an argument of a custom type, such as a user-defined class. + template + static void format_custom(void* arg, parse_context& parse_ctx, + Context& ctx) { + auto f = Formatter(); + parse_ctx.advance_to(f.parse(parse_ctx)); + using qualified_type = + conditional_t(), const T, T>; + // format must be const for compatibility with std::format and compilation. + const auto& cf = f; + ctx.advance_to(cf.format(*static_cast(arg), ctx)); + } +}; + +enum { packed_arg_bits = 4 }; +// Maximum number of arguments with packed types. +enum { max_packed_args = 62 / packed_arg_bits }; +enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; +enum : unsigned long long { has_named_args_bit = 1ULL << 62 }; + +template +struct is_output_iterator : std::false_type {}; + +template <> struct is_output_iterator : std::true_type {}; + +template +struct is_output_iterator< + It, T, + enable_if_t&>()++), + T>::value>> : std::true_type {}; + +#ifndef FMT_USE_LOCALE +# define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1) +#endif + +// A type-erased reference to an std::locale to avoid a heavy include. +class locale_ref { +#if FMT_USE_LOCALE + private: + const void* locale_; // A type-erased pointer to std::locale. + + public: + constexpr locale_ref() : locale_(nullptr) {} + template locale_ref(const Locale& loc); + + inline explicit operator bool() const noexcept { return locale_ != nullptr; } +#endif // FMT_USE_LOCALE + + public: + template auto get() const -> Locale; +}; + +template constexpr auto encode_types() -> unsigned long long { + return 0; +} + +template +constexpr auto encode_types() -> unsigned long long { + return static_cast(stored_type_constant::value) | + (encode_types() << packed_arg_bits); +} + +template +constexpr auto make_descriptor() -> unsigned long long { + return NUM_ARGS <= max_packed_args ? encode_types() + : is_unpacked_bit | NUM_ARGS; +} + +template +using arg_t = conditional_t, + basic_format_arg>; + +template +struct named_arg_store { + // args_[0].named_args points to named_args to avoid bloating format_args. + arg_t args[1 + NUM_ARGS]; + named_arg_info named_args[NUM_NAMED_ARGS]; + + template + FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values) + : args{{named_args, NUM_NAMED_ARGS}, values...} { + int arg_index = 0, named_arg_index = 0; + FMT_APPLY_VARIADIC( + init_named_arg(named_args, arg_index, named_arg_index, values)); + } + + named_arg_store(named_arg_store&& rhs) { + args[0] = {named_args, NUM_NAMED_ARGS}; + for (size_t i = 1; i < sizeof(args) / sizeof(*args); ++i) + args[i] = rhs.args[i]; + for (size_t i = 0; i < NUM_NAMED_ARGS; ++i) + named_args[i] = rhs.named_args[i]; + } + + named_arg_store(const named_arg_store& rhs) = delete; + named_arg_store& operator=(const named_arg_store& rhs) = delete; + named_arg_store& operator=(named_arg_store&& rhs) = delete; + operator const arg_t*() const { return args + 1; } +}; + +// An array of references to arguments. It can be implicitly converted to +// `basic_format_args` for passing into type-erased formatting functions +// such as `vformat`. It is a plain struct to reduce binary size in debug mode. +template +struct format_arg_store { + // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. + using type = + conditional_t[max_of(1, NUM_ARGS)], + named_arg_store>; + type args; +}; + +// TYPE can be different from type_constant, e.g. for __float128. +template struct native_formatter { + private: + dynamic_format_specs specs_; + + public: + using nonlocking = void; + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin(); + auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE); + if (const_check(TYPE == type::char_type)) check_char_specs(specs_); + return end; + } + + template + FMT_CONSTEXPR void set_debug_format(bool set = true) { + specs_.set_type(set ? presentation_type::debug : presentation_type::none); + } + + FMT_PRAGMA_CLANG(diagnostic ignored "-Wundefined-inline") + template + FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const + -> decltype(ctx.out()); +}; + +template +struct locking + : bool_constant::value == type::custom_type> {}; +template +struct locking>::nonlocking>> + : std::false_type {}; + +template FMT_CONSTEXPR inline auto is_locking() -> bool { + return locking::value; +} +template +FMT_CONSTEXPR inline auto is_locking() -> bool { + return locking::value || is_locking(); +} + +FMT_API void vformat_to(buffer& buf, string_view fmt, format_args args, + locale_ref loc = {}); + +#if FMT_WIN32 +FMT_API void vprint_mojibake(FILE*, string_view, format_args, bool); +#else // format_args is passed by reference since it is defined later. +inline void vprint_mojibake(FILE*, string_view, const format_args&, bool) {} +#endif +} // namespace detail + +// The main public API. + +template +FMT_CONSTEXPR void parse_context::do_check_arg_id(int arg_id) { + // Argument id is only checked at compile time during parsing because + // formatting has its own validation. + if (detail::is_constant_evaluated() && use_constexpr_cast) { + auto ctx = static_cast*>(this); + if (arg_id >= ctx->num_args()) report_error("argument not found"); + } +} + +template +FMT_CONSTEXPR void parse_context::check_dynamic_spec(int arg_id) { + using detail::compile_parse_context; + if (detail::is_constant_evaluated() && use_constexpr_cast) + static_cast*>(this)->check_dynamic_spec(arg_id); +} + +FMT_BEGIN_EXPORT + +// An output iterator that appends to a buffer. It is used instead of +// back_insert_iterator to reduce symbol sizes and avoid dependency. +template class basic_appender { + protected: + detail::buffer* container; + + public: + using container_type = detail::buffer; + + FMT_CONSTEXPR basic_appender(detail::buffer& buf) : container(&buf) {} + + FMT_CONSTEXPR20 auto operator=(T c) -> basic_appender& { + container->push_back(c); + return *this; + } + FMT_CONSTEXPR20 auto operator*() -> basic_appender& { return *this; } + FMT_CONSTEXPR20 auto operator++() -> basic_appender& { return *this; } + FMT_CONSTEXPR20 auto operator++(int) -> basic_appender { return *this; } +}; + +// A formatting argument. Context is a template parameter for the compiled API +// where output can be unbuffered. +template class basic_format_arg { + private: + detail::value value_; + detail::type type_; + + friend class basic_format_args; + + using char_type = typename Context::char_type; + + public: + class handle { + private: + detail::custom_value custom_; + + public: + explicit handle(detail::custom_value custom) : custom_(custom) {} + + void format(parse_context& parse_ctx, Context& ctx) const { + custom_.format(custom_.value, parse_ctx, ctx); + } + }; + + constexpr basic_format_arg() : type_(detail::type::none_type) {} + basic_format_arg(const detail::named_arg_info* args, size_t size) + : value_(args, size) {} + template + basic_format_arg(T&& val) + : value_(val), type_(detail::stored_type_constant::value) {} + + constexpr explicit operator bool() const noexcept { + return type_ != detail::type::none_type; + } + auto type() const -> detail::type { return type_; } + + /** + * 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`. + */ + template + FMT_CONSTEXPR FMT_INLINE auto visit(Visitor&& vis) const -> decltype(vis(0)) { + using detail::map; + switch (type_) { + case detail::type::none_type: break; + case detail::type::int_type: return vis(value_.int_value); + case detail::type::uint_type: return vis(value_.uint_value); + case detail::type::long_long_type: return vis(value_.long_long_value); + case detail::type::ulong_long_type: return vis(value_.ulong_long_value); + case detail::type::int128_type: return vis(map(value_.int128_value)); + case detail::type::uint128_type: return vis(map(value_.uint128_value)); + case detail::type::bool_type: return vis(value_.bool_value); + case detail::type::char_type: return vis(value_.char_value); + case detail::type::float_type: return vis(value_.float_value); + case detail::type::double_type: return vis(value_.double_value); + case detail::type::long_double_type: return vis(value_.long_double_value); + case detail::type::cstring_type: return vis(value_.string.data); + case detail::type::string_type: return vis(value_.string.str()); + case detail::type::pointer_type: return vis(value_.pointer); + case detail::type::custom_type: return vis(handle(value_.custom)); + } + return vis(monostate()); + } + + auto format_custom(const char_type* parse_begin, + parse_context& parse_ctx, Context& ctx) + -> bool { + if (type_ != detail::type::custom_type) return false; + parse_ctx.advance_to(parse_begin); + value_.custom.format(value_.custom.value, parse_ctx, ctx); + return true; + } +}; + +/** + * A view of a collection of formatting arguments. To avoid lifetime issues it + * should only be used as a parameter type in type-erased functions such as + * `vformat`: + * + * void vlog(fmt::string_view fmt, fmt::format_args args); // OK + * fmt::format_args args = fmt::make_format_args(); // Dangling reference + */ +template class basic_format_args { + private: + // A descriptor that contains information about formatting arguments. + // If the number of arguments is less or equal to max_packed_args then + // argument types are passed in the descriptor. This reduces binary code size + // per formatting function call. + unsigned long long desc_; + union { + // If is_packed() returns true then argument values are stored in values_; + // otherwise they are stored in args_. This is done to improve cache + // locality and reduce compiled code size since storing larger objects + // may require more code (at least on x86-64) even if the same amount of + // data is actually copied to stack. It saves ~10% on the bloat test. + const detail::value* values_; + const basic_format_arg* args_; + }; + + constexpr auto is_packed() const -> bool { + return (desc_ & detail::is_unpacked_bit) == 0; + } + constexpr auto has_named_args() const -> bool { + return (desc_ & detail::has_named_args_bit) != 0; + } + + FMT_CONSTEXPR auto type(int index) const -> detail::type { + int shift = index * detail::packed_arg_bits; + unsigned mask = (1 << detail::packed_arg_bits) - 1; + return static_cast((desc_ >> shift) & mask); + } + + template + using store = + detail::format_arg_store; + + public: + using format_arg = basic_format_arg; + + constexpr basic_format_args() : desc_(0), args_(nullptr) {} + + /// Constructs a `basic_format_args` object from `format_arg_store`. + template + constexpr FMT_ALWAYS_INLINE basic_format_args( + const store& s) + : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)), + values_(s.args) {} + + template detail::max_packed_args)> + constexpr basic_format_args(const store& s) + : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)), + args_(s.args) {} + + /// Constructs a `basic_format_args` object from a dynamic list of arguments. + constexpr basic_format_args(const format_arg* args, int count, + bool has_named = false) + : desc_(detail::is_unpacked_bit | detail::to_unsigned(count) | + (has_named ? +detail::has_named_args_bit : 0)), + args_(args) {} + + /// Returns the argument with the specified id. + FMT_CONSTEXPR auto get(int id) const -> format_arg { + auto arg = format_arg(); + if (!is_packed()) { + if (id < max_size()) arg = args_[id]; + return arg; + } + if (static_cast(id) >= detail::max_packed_args) return arg; + arg.type_ = type(id); + if (arg.type_ != detail::type::none_type) arg.value_ = values_[id]; + return arg; + } + + template + auto get(basic_string_view name) const -> format_arg { + int id = get_id(name); + return id >= 0 ? get(id) : format_arg(); + } + + template + FMT_CONSTEXPR auto get_id(basic_string_view name) const -> int { + if (!has_named_args()) return -1; + const auto& named_args = + (is_packed() ? values_[-1] : args_[-1].value_).named_args; + for (size_t i = 0; i < named_args.size; ++i) { + if (named_args.data[i].name == name) return named_args.data[i].id; + } + return -1; + } + + auto max_size() const -> int { + unsigned long long max_packed = detail::max_packed_args; + return static_cast(is_packed() ? max_packed + : desc_ & ~detail::is_unpacked_bit); + } +}; + +// A formatting context. +class context { + private: + appender out_; + format_args args_; + FMT_NO_UNIQUE_ADDRESS detail::locale_ref loc_; + + public: + /// The character type for the output. + using char_type = char; + + using iterator = appender; + using format_arg = basic_format_arg; + using parse_context_type FMT_DEPRECATED = parse_context<>; + template using formatter_type FMT_DEPRECATED = formatter; + enum { builtin_types = FMT_BUILTIN_TYPES }; + + /// Constructs a `context` object. References to the arguments are stored + /// in the object so make sure they have appropriate lifetimes. + FMT_CONSTEXPR context(iterator out, format_args args, + detail::locale_ref loc = {}) + : out_(out), args_(args), loc_(loc) {} + context(context&&) = default; + context(const context&) = delete; + void operator=(const context&) = delete; + + FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); } + inline auto arg(string_view name) const -> format_arg { + return args_.get(name); + } + FMT_CONSTEXPR auto arg_id(string_view name) const -> int { + return args_.get_id(name); + } + auto args() const -> const format_args& { return args_; } + + // Returns an iterator to the beginning of the output range. + FMT_CONSTEXPR auto out() const -> iterator { return out_; } + + // Advances the begin iterator to `it`. + FMT_CONSTEXPR void advance_to(iterator) {} + + FMT_CONSTEXPR auto locale() const -> detail::locale_ref { return loc_; } +}; + +template struct runtime_format_string { + basic_string_view str; +}; + +/** + * Creates a runtime format string. + * + * **Example**: + * + * // Check format string at runtime instead of compile-time. + * fmt::print(fmt::runtime("{:d}"), "I am not a number"); + */ +inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; } + +/// A compile-time format string. Use `format_string` in the public API to +/// prevent type deduction. +template struct fstring { + private: + static constexpr int num_static_named_args = + detail::count_static_named_args(); + + using checker = detail::format_string_checker< + char, static_cast(sizeof...(T)), num_static_named_args, + num_static_named_args != detail::count_named_args()>; + + using arg_pack = detail::arg_pack; + + public: + string_view str; + using t = fstring; + + // Reports a compile-time error if S is not a valid format string for T. + template + FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const char (&s)[N]) : str(s, N - 1) { + using namespace detail; + static_assert(count<(std::is_base_of>::value && + std::is_reference::value)...>() == 0, + "passing views as lvalues is disallowed"); + if (FMT_USE_CONSTEVAL) parse_format_string(s, checker(s, arg_pack())); +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert( + FMT_USE_CONSTEVAL && sizeof(s) != 0, + "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING"); +#endif + } + template ::value)> + FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const S& s) : str(s) { + auto sv = string_view(str); + if (FMT_USE_CONSTEVAL) + detail::parse_format_string(sv, checker(sv, arg_pack())); +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert( + FMT_USE_CONSTEVAL && sizeof(s) != 0, + "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING"); +#endif + } + template ::value&& + std::is_same::value)> + FMT_ALWAYS_INLINE fstring(const S&) : str(S()) { + FMT_CONSTEXPR auto sv = string_view(S()); + FMT_CONSTEXPR int unused = + (parse_format_string(sv, checker(sv, arg_pack())), 0); + detail::ignore_unused(unused); + } + fstring(runtime_format_string<> fmt) : str(fmt.str) {} + + // Returning by reference generates better code in debug mode. + FMT_ALWAYS_INLINE operator const string_view&() const { return str; } + auto get() const -> string_view { return str; } +}; + +template using format_string = typename fstring::t; + +template +using is_formattable = bool_constant::value, int*, T>, Char>, + void>::value>; +#ifdef __cpp_concepts +template +concept formattable = is_formattable, Char>::value; +#endif + +template +using has_formatter FMT_DEPRECATED = std::is_constructible>; + +// A formatter specialization for natively supported types. +template +struct formatter::value != + detail::type::custom_type>> + : detail::native_formatter::value> { +}; + +/** + * Constructs an object that stores references to arguments and can be + * implicitly converted to `format_args`. `Context` can be omitted in which case + * it defaults to `context`. See `arg` for lifetime considerations. + */ +// Take arguments by lvalue references to avoid some lifetime issues, e.g. +// auto args = make_format_args(std::string()); +template (), + unsigned long long DESC = detail::make_descriptor()> +constexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args) + -> detail::format_arg_store { + // Suppress warnings for pathological types convertible to detail::value. + FMT_PRAGMA_GCC(diagnostic ignored "-Wconversion") + return {{args...}}; +} + +template +using vargs = + detail::format_arg_store(), + detail::make_descriptor()>; + +/** + * Returns a named argument to be used in a formatting function. + * It should only be used in a call to a formatting function. + * + * **Example**: + * + * fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); + */ +template +inline auto arg(const Char* name, const T& arg) -> detail::named_arg { + return {name, arg}; +} + +/// Formats a string and writes the output to `out`. +template , + char>::value)> +auto vformat_to(OutputIt&& out, string_view fmt, format_args args) + -> remove_cvref_t { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, fmt, args, {}); + return detail::get_iterator(buf, out); +} + +/** + * Formats `args` according to specifications in `fmt`, writes the result to + * the output iterator `out` and returns the iterator past the end of the output + * range. `format_to` does not append a terminating null character. + * + * **Example**: + * + * auto out = std::vector(); + * fmt::format_to(std::back_inserter(out), "{}", 42); + */ +template , + char>::value)> +FMT_INLINE auto format_to(OutputIt&& out, format_string fmt, T&&... args) + -> remove_cvref_t { + return vformat_to(out, fmt.str, vargs{{args...}}); +} + +template struct format_to_n_result { + /// Iterator past the end of the output range. + OutputIt out; + /// Total (not truncated) output size. + size_t size; +}; + +template ::value)> +auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + detail::vformat_to(buf, fmt, args, {}); + return {buf.out(), buf.count()}; +} + +/** + * Formats `args` according to specifications in `fmt`, writes up to `n` + * characters of the result to the output iterator `out` and returns the total + * (not truncated) output size and the iterator past the end of the output + * range. `format_to_n` does not append a terminating null character. + */ +template ::value)> +FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string fmt, + T&&... args) -> format_to_n_result { + return vformat_to_n(out, n, fmt.str, vargs{{args...}}); +} + +struct format_to_result { + /// Pointer to just after the last successful write in the array. + char* out; + /// Specifies if the output was truncated. + bool truncated; + + FMT_CONSTEXPR operator char*() const { + // Report truncation to prevent silent data loss. + if (truncated) report_error("output is truncated"); + return out; + } +}; + +template +auto vformat_to(char (&out)[N], string_view fmt, format_args args) + -> format_to_result { + auto result = vformat_to_n(out, N, fmt, args); + return {result.out, result.size > N}; +} + +template +FMT_INLINE auto format_to(char (&out)[N], format_string fmt, T&&... args) + -> format_to_result { + auto result = vformat_to_n(out, N, fmt.str, vargs{{args...}}); + return {result.out, result.size > N}; +} + +/// Returns the number of chars in the output of `format(fmt, args...)`. +template +FMT_NODISCARD FMT_INLINE auto formatted_size(format_string fmt, + T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + detail::vformat_to(buf, fmt.str, vargs{{args...}}, {}); + return buf.count(); +} + +FMT_API void vprint(string_view fmt, format_args args); +FMT_API void vprint(FILE* f, string_view fmt, format_args args); +FMT_API void vprintln(FILE* f, string_view fmt, format_args args); +FMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args); + +/** + * Formats `args` according to specifications in `fmt` and writes the output + * to `stdout`. + * + * **Example**: + * + * fmt::print("The answer is {}.", 42); + */ +template +FMT_INLINE void print(format_string fmt, T&&... args) { + vargs va = {{args...}}; + if (detail::const_check(!detail::use_utf8)) + return detail::vprint_mojibake(stdout, fmt.str, va, false); + return detail::is_locking() ? vprint_buffered(stdout, fmt.str, va) + : vprint(fmt.str, va); +} + +/** + * Formats `args` according to specifications in `fmt` and writes the + * output to the file `f`. + * + * **Example**: + * + * fmt::print(stderr, "Don't {}!", "panic"); + */ +template +FMT_INLINE void print(FILE* f, format_string fmt, T&&... args) { + vargs va = {{args...}}; + if (detail::const_check(!detail::use_utf8)) + return detail::vprint_mojibake(f, fmt.str, va, false); + return detail::is_locking() ? vprint_buffered(f, fmt.str, va) + : vprint(f, fmt.str, va); +} + +/// Formats `args` according to specifications in `fmt` and writes the output +/// to the file `f` followed by a newline. +template +FMT_INLINE void println(FILE* f, format_string fmt, T&&... args) { + vargs va = {{args...}}; + return detail::const_check(detail::use_utf8) + ? vprintln(f, fmt.str, va) + : detail::vprint_mojibake(f, fmt.str, va, true); +} + +/// Formats `args` according to specifications in `fmt` and writes the output +/// to `stdout` followed by a newline. +template +FMT_INLINE void println(format_string fmt, T&&... args) { + return fmt::println(stdout, fmt, static_cast(args)...); +} + +FMT_END_EXPORT +FMT_PRAGMA_CLANG(diagnostic pop) +FMT_PRAGMA_GCC(pop_options) +FMT_END_NAMESPACE + +#ifdef FMT_HEADER_ONLY +# include "format.h" +#endif +#endif // FMT_BASE_H_ diff --git a/third-party/fmt/include/fmt/chrono.h b/third-party/fmt/include/fmt/chrono.h index 9d54574e16..50c777c841 100644 --- a/third-party/fmt/include/fmt/chrono.h +++ b/third-party/fmt/include/fmt/chrono.h @@ -8,52 +8,37 @@ #ifndef FMT_CHRONO_H_ #define FMT_CHRONO_H_ -#include -#include -#include // std::isfinite -#include // std::memcpy -#include -#include -#include -#include -#include +#ifndef FMT_MODULE +# include +# include +# include // std::isfinite +# include // std::memcpy +# include +# include +# include +# include +# include +#endif -#include "ostream.h" // formatbuf +#include "format.h" + +namespace fmt_detail { +struct time_zone { + template + auto to_sys(T) + -> std::chrono::time_point { + return {}; + } +}; +template inline auto current_zone(T...) -> time_zone* { + return nullptr; +} + +template inline void _tzset(T...) {} +} // namespace fmt_detail FMT_BEGIN_NAMESPACE -// Check if std::chrono::local_t is available. -#ifndef FMT_USE_LOCAL_TIME -# ifdef __cpp_lib_chrono -# define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L) -# else -# define FMT_USE_LOCAL_TIME 0 -# endif -#endif - -// Check if std::chrono::utc_timestamp is available. -#ifndef FMT_USE_UTC_TIME -# ifdef __cpp_lib_chrono -# define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L) -# else -# define FMT_USE_UTC_TIME 0 -# endif -#endif - -// Enable tzset. -#ifndef FMT_USE_TZSET -// UWP doesn't provide _tzset. -# if FMT_HAS_INCLUDE("winapifamily.h") -# include -# endif -# if defined(_WIN32) && (!defined(WINAPI_FAMILY) || \ - (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) -# define FMT_USE_TZSET 1 -# else -# define FMT_USE_TZSET 0 -# endif -#endif - // Enable safe chrono durations, unless explicitly disabled. #ifndef FMT_SAFE_DURATION_CAST # define FMT_SAFE_DURATION_CAST 1 @@ -94,10 +79,8 @@ FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec) return static_cast(from); } -/** - * converts From to To, without loss. If the dynamic value of from - * can't be converted to To without loss, ec is set. - */ +/// Converts From to To, without loss. If the dynamic value of from +/// can't be converted to To without loss, ec is set. template ::value && std::numeric_limits::is_signed != @@ -185,61 +168,7 @@ FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To { return from; } -/** - * safe duration cast between integral durations - */ -template ::value), - FMT_ENABLE_IF(std::is_integral::value)> -auto safe_duration_cast(std::chrono::duration from, - int& ec) -> To { - using From = std::chrono::duration; - ec = 0; - // the basic idea is that we need to convert from count() in the from type - // to count() in the To type, by multiplying it with this: - struct Factor - : std::ratio_divide {}; - - 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::type; - - // safe conversion to IntermediateRep - IntermediateRep count = - lossless_integral_conversion(from.count(), ec); - if (ec) return {}; - // multiply with Factor::num without overflow or underflow - if (detail::const_check(Factor::num != 1)) { - const auto max1 = detail::max_value() / Factor::num; - if (count > max1) { - ec = 1; - return {}; - } - const auto min1 = - (std::numeric_limits::min)() / Factor::num; - if (detail::const_check(!std::is_unsigned::value) && - count < min1) { - ec = 1; - return {}; - } - count *= Factor::num; - } - - if (detail::const_check(Factor::den != 1)) count /= Factor::den; - auto tocount = lossless_integral_conversion(count, ec); - return ec ? To() : To(tocount); -} - -/** - * safe duration_cast between floating point durations - */ +/// Safe duration_cast between floating point durations template ::value), FMT_ENABLE_IF(std::is_floating_point::value)> @@ -318,17 +247,94 @@ auto safe_duration_cast(std::chrono::duration from, } // namespace safe_duration_cast #endif +namespace detail { + +// Check if std::chrono::utc_time is available. +#ifdef FMT_USE_UTC_TIME +// Use the provided definition. +#elif defined(__cpp_lib_chrono) +# define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L) +#else +# define FMT_USE_UTC_TIME 0 +#endif +#if FMT_USE_UTC_TIME +using utc_clock = std::chrono::utc_clock; +#else +struct utc_clock { + template void to_sys(T); +}; +#endif + +// Check if std::chrono::local_time is available. +#ifdef FMT_USE_LOCAL_TIME +// Use the provided definition. +#elif defined(__cpp_lib_chrono) +# define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L) +#else +# define FMT_USE_LOCAL_TIME 0 +#endif +#if FMT_USE_LOCAL_TIME +using local_t = std::chrono::local_t; +#else +struct local_t {}; +#endif + +} // namespace detail + +template +using sys_time = std::chrono::time_point; + +template +using utc_time = std::chrono::time_point; + +template +using local_time = std::chrono::time_point; + +namespace detail { + // Prevents expansion of a preceding token as a function-style macro. // Usage: f FMT_NOMACRO() #define FMT_NOMACRO -namespace detail { template struct null {}; inline auto localtime_r FMT_NOMACRO(...) -> null<> { return null<>(); } inline auto localtime_s(...) -> null<> { return null<>(); } inline auto gmtime_r(...) -> null<> { return null<>(); } inline auto gmtime_s(...) -> null<> { return null<>(); } +// It is defined here and not in ostream.h because the latter has expensive +// includes. +template class formatbuf : public StreamBuf { + private: + using char_type = typename StreamBuf::char_type; + using streamsize = decltype(std::declval().sputn(nullptr, 0)); + using int_type = typename StreamBuf::int_type; + using traits_type = typename StreamBuf::traits_type; + + buffer& buffer_; + + public: + explicit formatbuf(buffer& buf) : buffer_(buf) {} + + protected: + // The put area is always empty. This makes the implementation simpler and has + // the advantage that the streambuf and the buffer are always in sync and + // sputc never writes into uninitialized memory. A disadvantage is that each + // call to sputc always results in a (virtual) call to overflow. There is no + // disadvantage here for sputn since this always results in a call to xsputn. + + auto overflow(int_type ch) -> int_type override { + if (!traits_type::eq_int_type(ch, traits_type::eof())) + buffer_.push_back(static_cast(ch)); + return ch; + } + + auto xsputn(const char_type* s, streamsize count) -> streamsize override { + buffer_.append(s, s + count); + return count; + } +}; + inline auto get_classic_locale() -> const std::locale& { static const auto& locale = std::locale::classic(); return locale; @@ -341,20 +347,16 @@ template struct codecvt_result { }; template -void write_codecvt(codecvt_result& out, string_view in_buf, +void write_codecvt(codecvt_result& out, string_view in, const std::locale& loc) { -#if FMT_CLANG_VERSION -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated" + FMT_PRAGMA_CLANG(diagnostic push) + FMT_PRAGMA_CLANG(diagnostic ignored "-Wdeprecated") auto& f = std::use_facet>(loc); -# pragma clang diagnostic pop -#else - auto& f = std::use_facet>(loc); -#endif + FMT_PRAGMA_CLANG(diagnostic pop) auto mb = std::mbstate_t(); const char* from_next = nullptr; - auto result = f.in(mb, in_buf.begin(), in_buf.end(), from_next, - std::begin(out.buf), std::end(out.buf), out.end); + auto result = f.in(mb, in.begin(), in.end(), from_next, std::begin(out.buf), + std::end(out.buf), out.end); if (result != std::codecvt_base::ok) FMT_THROW(format_error("failed to format time")); } @@ -362,11 +364,12 @@ void write_codecvt(codecvt_result& out, string_view in_buf, template auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc) -> OutputIt { - if (detail::is_utf8() && loc != get_classic_locale()) { + if (const_check(detail::use_utf8) && loc != get_classic_locale()) { // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and // gcc-4. -#if FMT_MSC_VERSION != 0 || \ - (defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI)) +#if FMT_MSC_VERSION != 0 || \ + (defined(__GLIBCXX__) && \ + (!defined(_GLIBCXX_USE_DUAL_ABI) || _GLIBCXX_USE_DUAL_ABI == 0)) // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5 // and newer. using code_unit = wchar_t; @@ -382,9 +385,9 @@ auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc) to_utf8>(); if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)})) FMT_THROW(format_error("failed to format time")); - return copy_str(u.c_str(), u.c_str() + u.size(), out); + return copy(u.c_str(), u.c_str() + u.size(), out); } - return copy_str(in.data(), in.data() + in.size(), out); + return copy(in.data(), in.data() + in.size(), out); } template OutputIt { codecvt_result unit; write_codecvt(unit, sv, loc); - return copy_str(unit.buf, unit.end, out); + return copy(unit.buf, unit.end, out); } template ::value)> { }; -template < - typename To, typename FromRep, typename FromPeriod, - FMT_ENABLE_IF(is_same_arithmetic_type::value)> -auto fmt_duration_cast(std::chrono::duration from) -> To { +FMT_NORETURN inline void throw_duration_error() { + FMT_THROW(format_error("cannot format duration")); +} + +// Cast one integral duration to another with an overflow check. +template ::value&& + std::is_integral::value)> +auto duration_cast(std::chrono::duration from) -> To { +#if !FMT_SAFE_DURATION_CAST + return std::chrono::duration_cast(from); +#else + // The conversion factor: to.count() == factor * from.count(). + using factor = std::ratio_divide; + + using common_rep = typename std::common_type::type; + + int ec = 0; + auto count = safe_duration_cast::lossless_integral_conversion( + from.count(), ec); + if (ec) throw_duration_error(); + + // Multiply from.count() by factor and check for overflow. + if (const_check(factor::num != 1)) { + if (count > max_value() / factor::num) throw_duration_error(); + const auto min = (std::numeric_limits::min)() / factor::num; + if (const_check(!std::is_unsigned::value) && count < min) + throw_duration_error(); + count *= factor::num; + } + if (const_check(factor::den != 1)) count /= factor::den; + auto to = + To(safe_duration_cast::lossless_integral_conversion( + count, ec)); + if (ec) throw_duration_error(); + return to; +#endif +} + +template ::value&& + std::is_floating_point::value)> +auto duration_cast(std::chrono::duration from) -> To { #if FMT_SAFE_DURATION_CAST // Throwing version of safe_duration_cast is only available for // integer to integer or float to float casts. int ec; To to = safe_duration_cast::safe_duration_cast(from, ec); - if (ec) FMT_THROW(format_error("cannot format duration")); + if (ec) throw_duration_error(); return to; #else // Standard duration cast, may overflow. @@ -461,54 +504,60 @@ auto fmt_duration_cast(std::chrono::duration from) -> To { template < typename To, typename FromRep, typename FromPeriod, FMT_ENABLE_IF(!is_same_arithmetic_type::value)> -auto fmt_duration_cast(std::chrono::duration from) -> To { +auto duration_cast(std::chrono::duration from) -> To { // Mixed integer <-> float cast is not supported by safe_duration_cast. return std::chrono::duration_cast(from); } template -auto to_time_t( - std::chrono::time_point time_point) - -> std::time_t { +auto to_time_t(sys_time time_point) -> std::time_t { // Cannot use std::chrono::system_clock::to_time_t since this would first // require a cast to std::chrono::system_clock::time_point, which could // overflow. - return fmt_duration_cast>( + return detail::duration_cast>( time_point.time_since_epoch()) .count(); } + +// Workaround a bug in libstdc++ which sets __cpp_lib_chrono to 201907 without +// providing current_zone(): https://github.com/fmtlib/fmt/issues/4160. +template FMT_CONSTEXPR auto has_current_zone() -> bool { + using namespace std::chrono; + using namespace fmt_detail; + return !std::is_same::value; +} } // namespace detail FMT_BEGIN_EXPORT /** - Converts given time since epoch as ``std::time_t`` value into calendar time, - expressed in local time. Unlike ``std::localtime``, this function is - thread-safe on most platforms. + * Converts given time since epoch as `std::time_t` value into calendar time, + * expressed in local time. Unlike `std::localtime`, this function is + * thread-safe on most platforms. */ inline auto localtime(std::time_t time) -> std::tm { struct dispatcher { std::time_t time_; std::tm tm_; - dispatcher(std::time_t t) : time_(t) {} + inline dispatcher(std::time_t t) : time_(t) {} - auto run() -> bool { + inline auto run() -> bool { using namespace fmt::detail; return handle(localtime_r(&time_, &tm_)); } - auto handle(std::tm* tm) -> bool { return tm != nullptr; } + inline auto handle(std::tm* tm) -> bool { return tm != nullptr; } - auto handle(detail::null<>) -> bool { + inline auto handle(detail::null<>) -> bool { using namespace fmt::detail; return fallback(localtime_s(&tm_, &time_)); } - auto fallback(int res) -> bool { return res == 0; } + inline auto fallback(int res) -> bool { return res == 0; } #if !FMT_MSC_VERSION - auto fallback(detail::null<>) -> bool { + inline auto fallback(detail::null<>) -> bool { using namespace fmt::detail; std::tm* tm = std::localtime(&time_); if (tm) tm_ = *tm; @@ -523,41 +572,43 @@ inline auto localtime(std::time_t time) -> std::tm { } #if FMT_USE_LOCAL_TIME -template +template ())> inline auto localtime(std::chrono::local_time time) -> std::tm { - return localtime( - detail::to_time_t(std::chrono::current_zone()->to_sys(time))); + using namespace std::chrono; + using namespace fmt_detail; + return localtime(detail::to_time_t(current_zone()->to_sys(time))); } #endif /** - Converts given time since epoch as ``std::time_t`` value into calendar time, - expressed in Coordinated Universal Time (UTC). Unlike ``std::gmtime``, this - function is thread-safe on most platforms. + * Converts given time since epoch as `std::time_t` value into calendar time, + * expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this + * function is thread-safe on most platforms. */ inline auto gmtime(std::time_t time) -> std::tm { struct dispatcher { std::time_t time_; std::tm tm_; - dispatcher(std::time_t t) : time_(t) {} + inline dispatcher(std::time_t t) : time_(t) {} - auto run() -> bool { + inline auto run() -> bool { using namespace fmt::detail; return handle(gmtime_r(&time_, &tm_)); } - auto handle(std::tm* tm) -> bool { return tm != nullptr; } + inline auto handle(std::tm* tm) -> bool { return tm != nullptr; } - auto handle(detail::null<>) -> bool { + inline auto handle(detail::null<>) -> bool { using namespace fmt::detail; return fallback(gmtime_s(&tm_, &time_)); } - auto fallback(int res) -> bool { return res == 0; } + inline auto fallback(int res) -> bool { return res == 0; } #if !FMT_MSC_VERSION - auto fallback(detail::null<>) -> bool { + inline auto fallback(detail::null<>) -> bool { std::tm* tm = std::gmtime(&time_); if (tm) tm_ = *tm; return tm != nullptr; @@ -571,9 +622,7 @@ inline auto gmtime(std::time_t time) -> std::tm { } template -inline auto gmtime( - std::chrono::time_point time_point) - -> std::tm { +inline auto gmtime(sys_time time_point) -> std::tm { return gmtime(detail::to_time_t(time_point)); } @@ -619,7 +668,8 @@ FMT_CONSTEXPR inline auto get_units() -> const char* { if (std::is_same::value) return "fs"; if (std::is_same::value) return "ps"; if (std::is_same::value) return "ns"; - if (std::is_same::value) return "µs"; + if (std::is_same::value) + return detail::use_utf8 ? "µs" : "us"; if (std::is_same::value) return "ms"; if (std::is_same::value) return "cs"; if (std::is_same::value) return "ds"; @@ -646,12 +696,10 @@ enum class numeric_system { // Glibc extensions for formatting numeric values. enum class pad_type { - unspecified, + // Pad a numeric result string with zeros (the default). + zero, // Do not pad a numeric result string. none, - // Pad a numeric result string with zeros even if the conversion specifier - // character uses space-padding by default. - zero, // Pad a numeric result string with spaces. space, }; @@ -659,7 +707,7 @@ enum class pad_type { template auto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt { if (pad == pad_type::none) return out; - return std::fill_n(out, width, pad == pad_type::space ? ' ' : '0'); + return detail::fill_n(out, width, pad == pad_type::space ? ' ' : '0'); } template @@ -675,8 +723,8 @@ FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end, if (begin == end || *begin == '}') return begin; if (*begin != '%') FMT_THROW(format_error("invalid format")); auto ptr = begin; - pad_type pad = pad_type::unspecified; while (ptr != end) { + pad_type pad = pad_type::zero; auto c = *ptr; if (c == '}') break; if (c != '%') { @@ -696,17 +744,11 @@ FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end, pad = pad_type::none; ++ptr; break; - case '0': - pad = pad_type::zero; - ++ptr; - break; } if (ptr == end) FMT_THROW(format_error("invalid format")); c = *ptr++; switch (c) { - case '%': - handler.on_text(ptr - 1, ptr); - break; + case '%': handler.on_text(ptr - 1, ptr); break; case 'n': { const Char newline[] = {'\n'}; handler.on_text(newline, newline + 1); @@ -718,145 +760,66 @@ FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end, break; } // Year: - case 'Y': - handler.on_year(numeric_system::standard); - break; - case 'y': - handler.on_short_year(numeric_system::standard); - break; - case 'C': - handler.on_century(numeric_system::standard); - break; - case 'G': - handler.on_iso_week_based_year(); - break; - case 'g': - handler.on_iso_week_based_short_year(); - break; + case 'Y': handler.on_year(numeric_system::standard, pad); break; + case 'y': handler.on_short_year(numeric_system::standard); break; + case 'C': handler.on_century(numeric_system::standard); break; + case 'G': handler.on_iso_week_based_year(); break; + case 'g': handler.on_iso_week_based_short_year(); break; // Day of the week: - case 'a': - handler.on_abbr_weekday(); - break; - case 'A': - handler.on_full_weekday(); - break; - case 'w': - handler.on_dec0_weekday(numeric_system::standard); - break; - case 'u': - handler.on_dec1_weekday(numeric_system::standard); - break; + case 'a': handler.on_abbr_weekday(); break; + case 'A': handler.on_full_weekday(); break; + case 'w': handler.on_dec0_weekday(numeric_system::standard); break; + case 'u': handler.on_dec1_weekday(numeric_system::standard); break; // Month: case 'b': - case 'h': - handler.on_abbr_month(); - break; - case 'B': - handler.on_full_month(); - break; - case 'm': - handler.on_dec_month(numeric_system::standard); - break; + case 'h': handler.on_abbr_month(); break; + case 'B': handler.on_full_month(); break; + case 'm': handler.on_dec_month(numeric_system::standard, pad); break; // Day of the year/month: case 'U': - handler.on_dec0_week_of_year(numeric_system::standard); + handler.on_dec0_week_of_year(numeric_system::standard, pad); break; case 'W': - handler.on_dec1_week_of_year(numeric_system::standard); - break; - case 'V': - handler.on_iso_week_of_year(numeric_system::standard); - break; - case 'j': - handler.on_day_of_year(); - break; - case 'd': - handler.on_day_of_month(numeric_system::standard); + handler.on_dec1_week_of_year(numeric_system::standard, pad); break; + case 'V': handler.on_iso_week_of_year(numeric_system::standard, pad); break; + case 'j': handler.on_day_of_year(pad); break; + case 'd': handler.on_day_of_month(numeric_system::standard, pad); break; case 'e': - handler.on_day_of_month_space(numeric_system::standard); + handler.on_day_of_month(numeric_system::standard, pad_type::space); break; // Hour, minute, second: - case 'H': - handler.on_24_hour(numeric_system::standard, pad); - break; - case 'I': - handler.on_12_hour(numeric_system::standard, pad); - break; - case 'M': - handler.on_minute(numeric_system::standard, pad); - break; - case 'S': - handler.on_second(numeric_system::standard, pad); - break; + case 'H': handler.on_24_hour(numeric_system::standard, pad); break; + case 'I': handler.on_12_hour(numeric_system::standard, pad); break; + case 'M': handler.on_minute(numeric_system::standard, pad); break; + case 'S': handler.on_second(numeric_system::standard, pad); break; // Other: - case 'c': - handler.on_datetime(numeric_system::standard); - break; - case 'x': - handler.on_loc_date(numeric_system::standard); - break; - case 'X': - handler.on_loc_time(numeric_system::standard); - break; - case 'D': - handler.on_us_date(); - break; - case 'F': - handler.on_iso_date(); - break; - case 'r': - handler.on_12_hour_time(); - break; - case 'R': - handler.on_24_hour_time(); - break; - case 'T': - handler.on_iso_time(); - break; - case 'p': - handler.on_am_pm(); - break; - case 'Q': - handler.on_duration_value(); - break; - case 'q': - handler.on_duration_unit(); - break; - case 'z': - handler.on_utc_offset(numeric_system::standard); - break; - case 'Z': - handler.on_tz_name(); - break; + case 'c': handler.on_datetime(numeric_system::standard); break; + case 'x': handler.on_loc_date(numeric_system::standard); break; + case 'X': handler.on_loc_time(numeric_system::standard); break; + case 'D': handler.on_us_date(); break; + case 'F': handler.on_iso_date(); break; + case 'r': handler.on_12_hour_time(); break; + case 'R': handler.on_24_hour_time(); break; + case 'T': handler.on_iso_time(); break; + case 'p': handler.on_am_pm(); break; + case 'Q': handler.on_duration_value(); break; + case 'q': handler.on_duration_unit(); break; + case 'z': handler.on_utc_offset(numeric_system::standard); break; + case 'Z': handler.on_tz_name(); break; // Alternative representation: case 'E': { if (ptr == end) FMT_THROW(format_error("invalid format")); c = *ptr++; switch (c) { - case 'Y': - handler.on_year(numeric_system::alternative); - break; - case 'y': - handler.on_offset_year(); - break; - case 'C': - handler.on_century(numeric_system::alternative); - break; - case 'c': - handler.on_datetime(numeric_system::alternative); - break; - case 'x': - handler.on_loc_date(numeric_system::alternative); - break; - case 'X': - handler.on_loc_time(numeric_system::alternative); - break; - case 'z': - handler.on_utc_offset(numeric_system::alternative); - break; - default: - FMT_THROW(format_error("invalid format")); + case 'Y': handler.on_year(numeric_system::alternative, pad); break; + case 'y': handler.on_offset_year(); break; + case 'C': handler.on_century(numeric_system::alternative); break; + case 'c': handler.on_datetime(numeric_system::alternative); break; + case 'x': handler.on_loc_date(numeric_system::alternative); break; + case 'X': handler.on_loc_time(numeric_system::alternative); break; + case 'z': handler.on_utc_offset(numeric_system::alternative); break; + default: FMT_THROW(format_error("invalid format")); } break; } @@ -864,54 +827,34 @@ FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end, if (ptr == end) FMT_THROW(format_error("invalid format")); c = *ptr++; switch (c) { - case 'y': - handler.on_short_year(numeric_system::alternative); - break; - case 'm': - handler.on_dec_month(numeric_system::alternative); - break; + case 'y': handler.on_short_year(numeric_system::alternative); break; + case 'm': handler.on_dec_month(numeric_system::alternative, pad); break; case 'U': - handler.on_dec0_week_of_year(numeric_system::alternative); + handler.on_dec0_week_of_year(numeric_system::alternative, pad); break; case 'W': - handler.on_dec1_week_of_year(numeric_system::alternative); + handler.on_dec1_week_of_year(numeric_system::alternative, pad); break; case 'V': - handler.on_iso_week_of_year(numeric_system::alternative); + handler.on_iso_week_of_year(numeric_system::alternative, pad); break; case 'd': - handler.on_day_of_month(numeric_system::alternative); + handler.on_day_of_month(numeric_system::alternative, pad); break; case 'e': - handler.on_day_of_month_space(numeric_system::alternative); + handler.on_day_of_month(numeric_system::alternative, pad_type::space); break; - case 'w': - handler.on_dec0_weekday(numeric_system::alternative); - break; - case 'u': - handler.on_dec1_weekday(numeric_system::alternative); - break; - case 'H': - handler.on_24_hour(numeric_system::alternative, pad); - break; - case 'I': - handler.on_12_hour(numeric_system::alternative, pad); - break; - case 'M': - handler.on_minute(numeric_system::alternative, pad); - break; - case 'S': - handler.on_second(numeric_system::alternative, pad); - break; - case 'z': - handler.on_utc_offset(numeric_system::alternative); - break; - default: - FMT_THROW(format_error("invalid format")); + case 'w': handler.on_dec0_weekday(numeric_system::alternative); break; + case 'u': handler.on_dec1_weekday(numeric_system::alternative); break; + case 'H': handler.on_24_hour(numeric_system::alternative, pad); break; + case 'I': handler.on_12_hour(numeric_system::alternative, pad); break; + case 'M': handler.on_minute(numeric_system::alternative, pad); break; + case 'S': handler.on_second(numeric_system::alternative, pad); break; + case 'z': handler.on_utc_offset(numeric_system::alternative); break; + default: FMT_THROW(format_error("invalid format")); } break; - default: - FMT_THROW(format_error("invalid format")); + default: FMT_THROW(format_error("invalid format")); } begin = ptr; } @@ -923,7 +866,7 @@ template struct null_chrono_spec_handler { FMT_CONSTEXPR void unsupported() { static_cast(this)->unsupported(); } - FMT_CONSTEXPR void on_year(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_year(numeric_system, pad_type) { unsupported(); } FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); } FMT_CONSTEXPR void on_offset_year() { unsupported(); } FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); } @@ -935,13 +878,20 @@ template struct null_chrono_spec_handler { FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); } FMT_CONSTEXPR void on_abbr_month() { unsupported(); } FMT_CONSTEXPR void on_full_month() { unsupported(); } - FMT_CONSTEXPR void on_dec_month(numeric_system) { unsupported(); } - FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) { unsupported(); } - FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) { unsupported(); } - FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) { unsupported(); } - FMT_CONSTEXPR void on_day_of_year() { unsupported(); } - FMT_CONSTEXPR void on_day_of_month(numeric_system) { unsupported(); } - FMT_CONSTEXPR void on_day_of_month_space(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) { unsupported(); } + FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) { + unsupported(); + } + FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) { + unsupported(); + } + FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) { + unsupported(); + } + FMT_CONSTEXPR void on_day_of_year(pad_type) { unsupported(); } + FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) { + unsupported(); + } FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); } FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); } FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); } @@ -962,11 +912,13 @@ template struct null_chrono_spec_handler { }; struct tm_format_checker : null_chrono_spec_handler { - FMT_NORETURN void unsupported() { FMT_THROW(format_error("no format")); } + FMT_NORETURN inline void unsupported() { + FMT_THROW(format_error("no format")); + } template FMT_CONSTEXPR void on_text(const Char*, const Char*) {} - FMT_CONSTEXPR void on_year(numeric_system) {} + FMT_CONSTEXPR void on_year(numeric_system, pad_type) {} FMT_CONSTEXPR void on_short_year(numeric_system) {} FMT_CONSTEXPR void on_offset_year() {} FMT_CONSTEXPR void on_century(numeric_system) {} @@ -978,13 +930,12 @@ struct tm_format_checker : null_chrono_spec_handler { FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {} FMT_CONSTEXPR void on_abbr_month() {} FMT_CONSTEXPR void on_full_month() {} - FMT_CONSTEXPR void on_dec_month(numeric_system) {} - FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) {} - FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) {} - FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) {} - FMT_CONSTEXPR void on_day_of_year() {} - FMT_CONSTEXPR void on_day_of_month(numeric_system) {} - FMT_CONSTEXPR void on_day_of_month_space(numeric_system) {} + FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_day_of_year(pad_type) {} + FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {} FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {} FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {} FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {} @@ -1040,15 +991,14 @@ template struct has_member_data_tm_zone> : std::true_type {}; -#if FMT_USE_TZSET inline void tzset_once() { - static bool init = []() -> bool { + static bool init = []() { + using namespace fmt_detail; _tzset(); - return true; + return false; }(); ignore_unused(init); } -#endif // Converts value to Int and checks that it's in the range [0, upper). template ::value)> @@ -1061,9 +1011,10 @@ inline auto to_nonnegative_int(T value, Int upper) -> Int { } template ::value)> inline auto to_nonnegative_int(T value, Int upper) -> Int { - if (value < 0 || value > static_cast(upper)) + auto int_value = static_cast(value); + if (int_value < 0 || value > static_cast(upper)) FMT_THROW(format_error("invalid value")); - return static_cast(value); + return int_value; } constexpr auto pow10(std::uint32_t n) -> long long { @@ -1098,16 +1049,16 @@ void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) { using subsecond_precision = std::chrono::duration< typename std::common_type::type, - std::ratio<1, detail::pow10(num_fractional_digits)>>; + std::ratio<1, pow10(num_fractional_digits)>>; - const auto fractional = d - fmt_duration_cast(d); + const auto fractional = d - detail::duration_cast(d); const auto subseconds = std::chrono::treat_as_floating_point< typename subsecond_precision::rep>::value ? fractional.count() - : fmt_duration_cast(fractional).count(); + : detail::duration_cast(fractional).count(); auto n = static_cast>(subseconds); - const int num_digits = detail::count_digits(n); + const int num_digits = count_digits(n); int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits); if (precision < 0) { @@ -1115,22 +1066,25 @@ void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) { if (std::ratio_less::value) { *out++ = '.'; - out = std::fill_n(out, leading_zeroes, '0'); - out = format_decimal(out, n, num_digits).end; + out = detail::fill_n(out, leading_zeroes, '0'); + out = format_decimal(out, n, num_digits); } - } else { + } else if (precision > 0) { *out++ = '.'; - leading_zeroes = (std::min)(leading_zeroes, precision); - out = std::fill_n(out, leading_zeroes, '0'); + leading_zeroes = min_of(leading_zeroes, precision); int remaining = precision - leading_zeroes; - if (remaining != 0 && remaining < num_digits) { - n /= to_unsigned(detail::pow10(to_unsigned(num_digits - remaining))); - out = format_decimal(out, n, remaining).end; + out = detail::fill_n(out, leading_zeroes, '0'); + if (remaining < num_digits) { + int num_truncated_digits = num_digits - remaining; + n /= to_unsigned(pow10(to_unsigned(num_truncated_digits))); + if (n != 0) out = format_decimal(out, n, remaining); return; } - out = format_decimal(out, n, num_digits).end; - remaining -= num_digits; - out = std::fill_n(out, remaining, '0'); + if (n != 0) { + out = format_decimal(out, n, num_digits); + remaining -= num_digits; + } + out = detail::fill_n(out, remaining, '0'); } } @@ -1271,29 +1225,28 @@ class tm_writer { } } - void write_year_extended(long long year) { + void write_year_extended(long long year, pad_type pad) { // At least 4 characters. int width = 4; - if (year < 0) { - *out_++ = '-'; + bool negative = year < 0; + if (negative) { year = 0 - year; --width; } uint32_or_64_or_128_t n = to_unsigned(year); const int num_digits = count_digits(n); - if (width > num_digits) out_ = std::fill_n(out_, width - num_digits, '0'); - out_ = format_decimal(out_, n, num_digits).end; - } - void write_year(long long year) { - if (year >= 0 && year < 10000) { - write2(static_cast(year / 100)); - write2(static_cast(year % 100)); - } else { - write_year_extended(year); + if (negative && pad == pad_type::zero) *out_++ = '-'; + if (width > num_digits) { + out_ = detail::write_padding(out_, pad, width - num_digits); } + if (negative && pad != pad_type::zero) *out_++ = '-'; + out_ = format_decimal(out_, n, num_digits); + } + void write_year(long long year, pad_type pad) { + write_year_extended(year, pad); } - void write_utc_offset(long offset, numeric_system ns) { + void write_utc_offset(long long offset, numeric_system ns) { if (offset < 0) { *out_++ = '-'; offset = -offset; @@ -1305,6 +1258,7 @@ class tm_writer { if (ns != numeric_system::standard) *out_++ = ':'; write2(static_cast(offset % 60)); } + template ::value)> void format_utc_offset_impl(const T& tm, numeric_system ns) { write_utc_offset(tm.tm_gmtoff, ns); @@ -1312,9 +1266,7 @@ class tm_writer { template ::value)> void format_utc_offset_impl(const T& tm, numeric_system ns) { #if defined(_WIN32) && defined(_UCRT) -# if FMT_USE_TZSET tzset_once(); -# endif long offset = 0; _get_timezone(&offset); if (tm.tm_isdst) { @@ -1331,7 +1283,7 @@ class tm_writer { std::time_t gt = std::mktime(>m); std::tm ltm = gmtime(gt); std::time_t lt = std::mktime(<m); - long offset = gt - lt; + long long offset = gt - lt; write_utc_offset(offset, ns); #endif } @@ -1364,7 +1316,7 @@ class tm_writer { auto out() const -> OutputIt { return out_; } FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { - out_ = copy_str(begin, end, out_); + out_ = copy(begin, end, out_); } void on_abbr_weekday() { @@ -1411,11 +1363,11 @@ class tm_writer { *out_++ = ' '; on_abbr_month(); *out_++ = ' '; - on_day_of_month_space(numeric_system::standard); + on_day_of_month(numeric_system::standard, pad_type::space); *out_++ = ' '; on_iso_time(); *out_++ = ' '; - on_year(numeric_system::standard); + on_year(numeric_system::standard, pad_type::space); } else { format_localized('c', ns == numeric_system::standard ? '\0' : 'E'); } @@ -1437,31 +1389,31 @@ class tm_writer { write_digit2_separated(buf, to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()), to_unsigned(split_year_lower(tm_year())), '/'); - out_ = copy_str(std::begin(buf), std::end(buf), out_); + out_ = copy(std::begin(buf), std::end(buf), out_); } void on_iso_date() { auto year = tm_year(); char buf[10]; size_t offset = 0; if (year >= 0 && year < 10000) { - copy2(buf, digits2(static_cast(year / 100))); + write2digits(buf, static_cast(year / 100)); } else { offset = 4; - write_year_extended(year); + write_year_extended(year, pad_type::zero); year = 0; } write_digit2_separated(buf + 2, static_cast(year % 100), to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()), '-'); - out_ = copy_str(std::begin(buf) + offset, std::end(buf), out_); + out_ = copy(std::begin(buf) + offset, std::end(buf), out_); } void on_utc_offset(numeric_system ns) { format_utc_offset_impl(tm_, ns); } void on_tz_name() { format_tz_name_impl(tm_); } - void on_year(numeric_system ns) { + void on_year(numeric_system ns, pad_type pad) { if (is_classic_ || ns == numeric_system::standard) - return write_year(tm_year()); + return write_year(tm_year(), pad); format_localized('Y', 'E'); } void on_short_year(numeric_system ns) { @@ -1492,56 +1444,57 @@ class tm_writer { } } - void on_dec_month(numeric_system ns) { + void on_dec_month(numeric_system ns, pad_type pad) { if (is_classic_ || ns == numeric_system::standard) - return write2(tm_mon() + 1); + return write2(tm_mon() + 1, pad); format_localized('m', 'O'); } - void on_dec0_week_of_year(numeric_system ns) { + void on_dec0_week_of_year(numeric_system ns, pad_type pad) { if (is_classic_ || ns == numeric_system::standard) - return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week); + return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week, + pad); format_localized('U', 'O'); } - void on_dec1_week_of_year(numeric_system ns) { + void on_dec1_week_of_year(numeric_system ns, pad_type pad) { if (is_classic_ || ns == numeric_system::standard) { auto wday = tm_wday(); write2((tm_yday() + days_per_week - (wday == 0 ? (days_per_week - 1) : (wday - 1))) / - days_per_week); + days_per_week, + pad); } else { format_localized('W', 'O'); } } - void on_iso_week_of_year(numeric_system ns) { + void on_iso_week_of_year(numeric_system ns, pad_type pad) { if (is_classic_ || ns == numeric_system::standard) - return write2(tm_iso_week_of_year()); + return write2(tm_iso_week_of_year(), pad); format_localized('V', 'O'); } - void on_iso_week_based_year() { write_year(tm_iso_week_year()); } + void on_iso_week_based_year() { + write_year(tm_iso_week_year(), pad_type::zero); + } void on_iso_week_based_short_year() { write2(split_year_lower(tm_iso_week_year())); } - void on_day_of_year() { + void on_day_of_year(pad_type pad) { auto yday = tm_yday() + 1; - write1(yday / 100); - write2(yday % 100); - } - void on_day_of_month(numeric_system ns) { - if (is_classic_ || ns == numeric_system::standard) return write2(tm_mday()); - format_localized('d', 'O'); - } - void on_day_of_month_space(numeric_system ns) { - if (is_classic_ || ns == numeric_system::standard) { - auto mday = to_unsigned(tm_mday()) % 100; - const char* d2 = digits2(mday); - *out_++ = mday < 10 ? ' ' : d2[0]; - *out_++ = d2[1]; + auto digit1 = yday / 100; + if (digit1 != 0) { + write1(digit1); } else { - format_localized('e', 'O'); + out_ = detail::write_padding(out_, pad); } + write2(yday % 100, pad); + } + + void on_day_of_month(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_mday(), pad); + format_localized('d', 'O'); } void on_24_hour(numeric_system ns, pad_type pad) { @@ -1569,7 +1522,7 @@ class tm_writer { write_floating_seconds(buf, *subsecs_); if (buf.size() > 1) { // Remove the leading "0", write something like ".123". - out_ = std::copy(buf.begin() + 1, buf.end(), out_); + out_ = copy(buf.begin() + 1, buf.end(), out_); } } else { write_fractional_seconds(out_, *subsecs_); @@ -1586,7 +1539,7 @@ class tm_writer { char buf[8]; write_digit2_separated(buf, to_unsigned(tm_hour12()), to_unsigned(tm_min()), to_unsigned(tm_sec()), ':'); - out_ = copy_str(std::begin(buf), std::end(buf), out_); + out_ = copy(std::begin(buf), std::end(buf), out_); *out_++ = ' '; on_am_pm(); } else { @@ -1601,7 +1554,7 @@ class tm_writer { void on_iso_time() { on_24_hour_time(); *out_++ = ':'; - on_second(numeric_system::standard, pad_type::unspecified); + on_second(numeric_system::standard, pad_type::zero); } void on_am_pm() { @@ -1621,11 +1574,11 @@ class tm_writer { struct chrono_format_checker : null_chrono_spec_handler { bool has_precision_integral = false; - FMT_NORETURN void unsupported() { FMT_THROW(format_error("no date")); } + FMT_NORETURN inline void unsupported() { FMT_THROW(format_error("no date")); } template FMT_CONSTEXPR void on_text(const Char*, const Char*) {} - FMT_CONSTEXPR void on_day_of_year() {} + FMT_CONSTEXPR void on_day_of_year(pad_type) {} FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {} FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {} FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {} @@ -1635,9 +1588,8 @@ struct chrono_format_checker : null_chrono_spec_handler { FMT_CONSTEXPR void on_iso_time() {} FMT_CONSTEXPR void on_am_pm() {} FMT_CONSTEXPR void on_duration_value() const { - if (has_precision_integral) { + if (has_precision_integral) FMT_THROW(format_error("precision not allowed for this argument type")); - } } FMT_CONSTEXPR void on_duration_unit() {} }; @@ -1677,17 +1629,17 @@ inline auto get_milliseconds(std::chrono::duration d) #if FMT_SAFE_DURATION_CAST using CommonSecondsType = typename std::common_type::type; - const auto d_as_common = fmt_duration_cast(d); + const auto d_as_common = detail::duration_cast(d); const auto d_as_whole_seconds = - fmt_duration_cast(d_as_common); + detail::duration_cast(d_as_common); // this conversion should be nonproblematic const auto diff = d_as_common - d_as_whole_seconds; const auto ms = - fmt_duration_cast>(diff); + detail::duration_cast>(diff); return ms; #else - auto s = fmt_duration_cast(d); - return fmt_duration_cast(d - s); + auto s = detail::duration_cast(d); + return detail::duration_cast(d - s); #endif } @@ -1700,16 +1652,16 @@ auto format_duration_value(OutputIt out, Rep val, int) -> OutputIt { template ::value)> auto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt { - auto specs = format_specs(); + auto specs = format_specs(); specs.precision = precision; - specs.type = precision >= 0 ? presentation_type::fixed_lower - : presentation_type::general_lower; + specs.set_type(precision >= 0 ? presentation_type::fixed + : presentation_type::general); return write(out, val, specs); } template auto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt { - return std::copy(unit.begin(), unit.end(), out); + return copy(unit.begin(), unit.end(), out); } template @@ -1717,7 +1669,7 @@ auto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt { // This works when wchar_t is UTF-32 because units only contain characters // that have the same representation in UTF-16 and UTF-32. utf8_to_utf16 u(unit); - return std::copy(u.c_str(), u.c_str() + u.size(), out); + return copy(u.c_str(), u.c_str() + u.size(), out); } template @@ -1743,14 +1695,14 @@ class get_locale { bool has_locale_ = false; public: - get_locale(bool localized, locale_ref loc) : has_locale_(localized) { + inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) { if (localized) ::new (&locale_) std::locale(loc.template get()); } - ~get_locale() { + inline ~get_locale() { if (has_locale_) locale_.~locale(); } - operator const std::locale&() const { + inline operator const std::locale&() const { return has_locale_ ? locale_ : get_classic_locale(); } }; @@ -1789,7 +1741,7 @@ struct chrono_formatter { // this may overflow and/or the result may not fit in the // target type. // might need checked conversion (rep!=Rep) - s = fmt_duration_cast(std::chrono::duration(val)); + s = detail::duration_cast(std::chrono::duration(val)); } // returns true if nan or inf, writes to out. @@ -1840,7 +1792,7 @@ struct chrono_formatter { } } - void write(Rep value, int width, pad_type pad = pad_type::unspecified) { + void write(Rep value, int width, pad_type pad = pad_type::zero) { write_sign(); if (isnan(value)) return write_nan(); uint32_or_64_or_128_t n = @@ -1849,7 +1801,7 @@ struct chrono_formatter { if (width > num_digits) { out = detail::write_padding(out, pad, width - num_digits); } - out = format_decimal(out, n, num_digits).end; + out = format_decimal(out, n, num_digits); } void write_nan() { std::copy_n("nan", 3, out); } @@ -1866,7 +1818,7 @@ struct chrono_formatter { } void on_text(const char_type* begin, const char_type* end) { - std::copy(begin, end, out); + copy(begin, end, out); } // These are not implemented because durations don't have date information. @@ -1883,20 +1835,19 @@ struct chrono_formatter { void on_iso_date() {} void on_utc_offset(numeric_system) {} void on_tz_name() {} - void on_year(numeric_system) {} + void on_year(numeric_system, pad_type) {} void on_short_year(numeric_system) {} void on_offset_year() {} void on_century(numeric_system) {} void on_iso_week_based_year() {} void on_iso_week_based_short_year() {} - void on_dec_month(numeric_system) {} - void on_dec0_week_of_year(numeric_system) {} - void on_dec1_week_of_year(numeric_system) {} - void on_iso_week_of_year(numeric_system) {} - void on_day_of_month(numeric_system) {} - void on_day_of_month_space(numeric_system) {} + void on_dec_month(numeric_system, pad_type) {} + void on_dec0_week_of_year(numeric_system, pad_type) {} + void on_dec1_week_of_year(numeric_system, pad_type) {} + void on_iso_week_of_year(numeric_system, pad_type) {} + void on_day_of_month(numeric_system, pad_type) {} - void on_day_of_year() { + void on_day_of_year(pad_type) { if (handle_nan_inf()) return; write(days(), 0); } @@ -1940,7 +1891,7 @@ struct chrono_formatter { if (buf.size() < 2 || buf[1] == '.') { out = detail::write_padding(out, pad); } - out = std::copy(buf.begin(), buf.end(), out); + out = copy(buf.begin(), buf.end(), out); } else { write(second(), 2, pad); write_fractional_seconds( @@ -1974,7 +1925,7 @@ struct chrono_formatter { on_24_hour_time(); *out++ = ':'; if (handle_nan_inf()) return; - on_second(numeric_system::standard, pad_type::unspecified); + on_second(numeric_system::standard, pad_type::zero); } void on_am_pm() { @@ -1997,82 +1948,240 @@ struct chrono_formatter { #if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907 using weekday = std::chrono::weekday; +using day = std::chrono::day; +using month = std::chrono::month; +using year = std::chrono::year; +using year_month_day = std::chrono::year_month_day; #else // A fallback version of weekday. class weekday { private: - unsigned char value; + unsigned char value_; public: weekday() = default; - explicit constexpr weekday(unsigned wd) noexcept - : value(static_cast(wd != 7 ? wd : 0)) {} - constexpr auto c_encoding() const noexcept -> unsigned { return value; } + constexpr explicit weekday(unsigned wd) noexcept + : value_(static_cast(wd != 7 ? wd : 0)) {} + constexpr auto c_encoding() const noexcept -> unsigned { return value_; } }; -class year_month_day {}; -#endif - -// A rudimentary weekday formatter. -template struct formatter { +class day { private: - bool localized = false; + unsigned char value_; public: - FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) - -> decltype(ctx.begin()) { - auto begin = ctx.begin(), end = ctx.end(); - if (begin != end && *begin == 'L') { - ++begin; - localized = true; + day() = default; + constexpr explicit day(unsigned d) noexcept + : value_(static_cast(d)) {} + constexpr explicit operator unsigned() const noexcept { return value_; } +}; + +class month { + private: + unsigned char value_; + + public: + month() = default; + constexpr explicit month(unsigned m) noexcept + : value_(static_cast(m)) {} + constexpr explicit operator unsigned() const noexcept { return value_; } +}; + +class year { + private: + int value_; + + public: + year() = default; + constexpr explicit year(int y) noexcept : value_(y) {} + constexpr explicit operator int() const noexcept { return value_; } +}; + +class year_month_day { + private: + fmt::year year_; + fmt::month month_; + fmt::day day_; + + public: + year_month_day() = default; + constexpr year_month_day(const year& y, const month& m, const day& d) noexcept + : year_(y), month_(m), day_(d) {} + constexpr auto year() const noexcept -> fmt::year { return year_; } + constexpr auto month() const noexcept -> fmt::month { return month_; } + constexpr auto day() const noexcept -> fmt::day { return day_; } +}; +#endif + +template +struct formatter : private formatter { + private: + bool localized_ = false; + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it != end && *it == 'L') { + ++it; + localized_ = true; + return it; } - return begin; + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; } template auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) { auto time = std::tm(); time.tm_wday = static_cast(wd.c_encoding()); - detail::get_locale loc(localized, ctx.locale()); + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(localized_, ctx.locale()); auto w = detail::tm_writer(loc, ctx.out(), time); w.on_abbr_weekday(); return w.out(); } }; +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(day d, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_mday = static_cast(static_cast(d)); + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(false, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_day_of_month(detail::numeric_system::standard, detail::pad_type::zero); + return w.out(); + } +}; + +template +struct formatter : private formatter { + private: + bool localized_ = false; + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it != end && *it == 'L') { + ++it; + localized_ = true; + return it; + } + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(month m, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_mon = static_cast(static_cast(m)) - 1; + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(localized_, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_abbr_month(); + return w.out(); + } +}; + +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(year y, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_year = static_cast(y) - 1900; + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(false, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_year(detail::numeric_system::standard, detail::pad_type::zero); + return w.out(); + } +}; + +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(year_month_day val, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_year = static_cast(val.year()) - 1900; + time.tm_mon = static_cast(static_cast(val.month())) - 1; + time.tm_mday = static_cast(static_cast(val.day())); + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(true, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_iso_date(); + return w.out(); + } +}; + template struct formatter, Char> { private: - format_specs specs_; + format_specs specs_; detail::arg_ref width_ref_; detail::arg_ref precision_ref_; bool localized_ = false; - basic_string_view format_str_; + basic_string_view fmt_; public: - FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) - -> decltype(ctx.begin()) { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { auto it = ctx.begin(), end = ctx.end(); if (it == end || *it == '}') return it; it = detail::parse_align(it, end, specs_); if (it == end) return it; - it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx); - if (it == end) return it; + Char c = *it; + if ((c >= '0' && c <= '9') || c == '{') { + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + if (it == end) return it; + } auto checker = detail::chrono_format_checker(); if (*it == '.') { checker.has_precision_integral = !std::is_floating_point::value; - it = detail::parse_precision(it, end, specs_.precision, precision_ref_, - ctx); + it = detail::parse_precision(it, end, specs_, precision_ref_, ctx); } if (it != end && *it == 'L') { localized_ = true; ++it; } end = detail::parse_chrono_format(it, end, checker); - format_str_ = {it, detail::to_unsigned(end - it)}; + fmt_ = {it, detail::to_unsigned(end - it)}; return end; } @@ -2082,15 +2191,15 @@ struct formatter, Char> { auto specs = specs_; auto precision = specs.precision; specs.precision = -1; - auto begin = format_str_.begin(), end = format_str_.end(); + auto begin = fmt_.begin(), end = fmt_.end(); // As a possible future optimization, we could avoid extra copying if width // is not specified. auto buf = basic_memory_buffer(); - auto out = std::back_inserter(buf); - detail::handle_dynamic_spec(specs.width, width_ref_, - ctx); - detail::handle_dynamic_spec(precision, - precision_ref_, ctx); + auto out = basic_appender(buf); + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), precision, + precision_ref_, ctx); if (begin == end || *begin == '}') { out = detail::format_duration_value(out, d.count(), precision); detail::format_duration_unit(out); @@ -2107,130 +2216,119 @@ struct formatter, Char> { } }; -template -struct formatter, - Char> : formatter { - FMT_CONSTEXPR formatter() { - this->format_str_ = detail::string_literal{}; - } - - template - auto format(std::chrono::time_point val, - FormatContext& ctx) const -> decltype(ctx.out()) { - using period = typename Duration::period; - if (detail::const_check( - period::num != 1 || period::den != 1 || - std::is_floating_point::value)) { - const auto epoch = val.time_since_epoch(); - auto subsecs = detail::fmt_duration_cast( - epoch - detail::fmt_duration_cast(epoch)); - - if (subsecs.count() < 0) { - auto second = - detail::fmt_duration_cast(std::chrono::seconds(1)); - if (epoch.count() < ((Duration::min)() + second).count()) - FMT_THROW(format_error("duration is too small")); - subsecs += second; - val -= second; - } - - return formatter::do_format(gmtime(val), ctx, &subsecs); - } - - return formatter::format(gmtime(val), ctx); - } -}; - -#if FMT_USE_LOCAL_TIME -template -struct formatter, Char> - : formatter { - FMT_CONSTEXPR formatter() { - this->format_str_ = detail::string_literal{}; - } - - template - auto format(std::chrono::local_time val, FormatContext& ctx) const - -> decltype(ctx.out()) { - using period = typename Duration::period; - if (period::num != 1 || period::den != 1 || - std::is_floating_point::value) { - const auto epoch = val.time_since_epoch(); - const auto subsecs = detail::fmt_duration_cast( - epoch - detail::fmt_duration_cast(epoch)); - - return formatter::do_format(localtime(val), ctx, &subsecs); - } - - return formatter::format(localtime(val), ctx); - } -}; -#endif - -#if FMT_USE_UTC_TIME -template -struct formatter, - Char> - : formatter, - Char> { - template - auto format(std::chrono::time_point val, - FormatContext& ctx) const -> decltype(ctx.out()) { - return formatter< - std::chrono::time_point, - Char>::format(std::chrono::utc_clock::to_sys(val), ctx); - } -}; -#endif - template struct formatter { private: - format_specs specs_; + format_specs specs_; detail::arg_ref width_ref_; protected: - basic_string_view format_str_; + basic_string_view fmt_; - template + template auto do_format(const std::tm& tm, FormatContext& ctx, const Duration* subsecs) const -> decltype(ctx.out()) { auto specs = specs_; auto buf = basic_memory_buffer(); - auto out = std::back_inserter(buf); - detail::handle_dynamic_spec(specs.width, width_ref_, - ctx); + auto out = basic_appender(buf); + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); auto loc_ref = ctx.locale(); detail::get_locale loc(static_cast(loc_ref), loc_ref); auto w = detail::tm_writer(loc, out, tm, subsecs); - detail::parse_chrono_format(format_str_.begin(), format_str_.end(), w); + detail::parse_chrono_format(fmt_.begin(), fmt_.end(), w); return detail::write( ctx.out(), basic_string_view(buf.data(), buf.size()), specs); } public: - FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) - -> decltype(ctx.begin()) { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { auto it = ctx.begin(), end = ctx.end(); if (it == end || *it == '}') return it; it = detail::parse_align(it, end, specs_); if (it == end) return it; - it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx); - if (it == end) return it; + Char c = *it; + if ((c >= '0' && c <= '9') || c == '{') { + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + if (it == end) return it; + } end = detail::parse_chrono_format(it, end, detail::tm_format_checker()); - // Replace the default format_str only if the new spec is not empty. - if (end != it) format_str_ = {it, detail::to_unsigned(end - it)}; + // Replace the default format string only if the new spec is not empty. + if (end != it) fmt_ = {it, detail::to_unsigned(end - it)}; return end; } template auto format(const std::tm& tm, FormatContext& ctx) const -> decltype(ctx.out()) { - return do_format(tm, ctx, nullptr); + return do_format(tm, ctx, nullptr); + } +}; + +template +struct formatter, Char> : formatter { + FMT_CONSTEXPR formatter() { + this->fmt_ = detail::string_literal(); + } + + template + auto format(sys_time val, FormatContext& ctx) const + -> decltype(ctx.out()) { + std::tm tm = gmtime(val); + using period = typename Duration::period; + if (detail::const_check( + period::num == 1 && period::den == 1 && + !std::is_floating_point::value)) { + return formatter::format(tm, ctx); + } + Duration epoch = val.time_since_epoch(); + Duration subsecs = detail::duration_cast( + epoch - detail::duration_cast(epoch)); + if (subsecs.count() < 0) { + auto second = detail::duration_cast(std::chrono::seconds(1)); + if (tm.tm_sec != 0) + --tm.tm_sec; + else + tm = gmtime(val - second); + subsecs += detail::duration_cast(std::chrono::seconds(1)); + } + return formatter::do_format(tm, ctx, &subsecs); + } +}; + +template +struct formatter, Char> + : formatter, Char> { + template + auto format(utc_time val, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter, Char>::format( + detail::utc_clock::to_sys(val), ctx); + } +}; + +template +struct formatter, Char> : formatter { + FMT_CONSTEXPR formatter() { + this->fmt_ = detail::string_literal(); + } + + template + auto format(local_time val, FormatContext& ctx) const + -> decltype(ctx.out()) { + using period = typename Duration::period; + if (period::num == 1 && period::den == 1 && + !std::is_floating_point::value) { + return formatter::format(localtime(val), ctx); + } + auto epoch = val.time_since_epoch(); + auto subsecs = detail::duration_cast( + epoch - detail::duration_cast(epoch)); + return formatter::do_format(localtime(val), ctx, &subsecs); } }; diff --git a/third-party/fmt/include/fmt/color.h b/third-party/fmt/include/fmt/color.h index 367849a86a..2faaf3a067 100644 --- a/third-party/fmt/include/fmt/color.h +++ b/third-party/fmt/include/fmt/color.h @@ -227,7 +227,7 @@ struct color_type { }; } // namespace detail -/** A text style consisting of foreground and background colors and emphasis. */ +/// A text style consisting of foreground and background colors and emphasis. class text_style { public: FMT_CONSTEXPR text_style(emphasis em = emphasis()) noexcept @@ -239,7 +239,7 @@ class text_style { foreground_color = rhs.foreground_color; } else if (rhs.set_foreground_color) { if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) - FMT_THROW(format_error("can't OR a terminal color")); + report_error("can't OR a terminal color"); foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color; } @@ -248,7 +248,7 @@ class text_style { background_color = rhs.background_color; } else if (rhs.set_background_color) { if (!background_color.is_rgb || !rhs.background_color.is_rgb) - FMT_THROW(format_error("can't OR a terminal color")); + report_error("can't OR a terminal color"); background_color.value.rgb_color |= rhs.background_color.value.rgb_color; } @@ -310,13 +310,13 @@ class text_style { emphasis ems; }; -/** Creates a text style from the foreground (text) color. */ +/// Creates a text style from the foreground (text) color. FMT_CONSTEXPR inline auto fg(detail::color_type foreground) noexcept -> text_style { return text_style(true, foreground); } -/** Creates a text style from the background color. */ +/// Creates a text style from the background color. FMT_CONSTEXPR inline auto bg(detail::color_type background) noexcept -> text_style { return text_style(false, background); @@ -330,7 +330,7 @@ FMT_CONSTEXPR inline auto operator|(emphasis lhs, emphasis rhs) noexcept namespace detail { template struct ansi_color_escape { - FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color, + FMT_CONSTEXPR ansi_color_escape(color_type text_color, const char* esc) noexcept { // If we have a terminal color, we need to output another escape code // sequence. @@ -390,8 +390,8 @@ template struct ansi_color_escape { FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; } FMT_CONSTEXPR auto begin() const noexcept -> const Char* { return buffer; } - FMT_CONSTEXPR_CHAR_TRAITS auto end() const noexcept -> const Char* { - return buffer + std::char_traits::length(buffer); + FMT_CONSTEXPR20 auto end() const noexcept -> const Char* { + return buffer + basic_string_view(buffer).size(); } private: @@ -412,13 +412,13 @@ template struct ansi_color_escape { }; template -FMT_CONSTEXPR auto make_foreground_color(detail::color_type foreground) noexcept +FMT_CONSTEXPR auto make_foreground_color(color_type foreground) noexcept -> ansi_color_escape { return ansi_color_escape(foreground, "\x1b[38;2;"); } template -FMT_CONSTEXPR auto make_background_color(detail::color_type background) noexcept +FMT_CONSTEXPR auto make_background_color(color_type background) noexcept -> ansi_color_escape { return ansi_color_escape(background, "\x1b[48;2;"); } @@ -434,7 +434,7 @@ template inline void reset_color(buffer& buffer) { buffer.append(reset_color.begin(), reset_color.end()); } -template struct styled_arg : detail::view { +template struct styled_arg : view { const T& value; text_style style; styled_arg(const T& v, text_style s) : value(v), style(s) {} @@ -442,145 +442,115 @@ template struct styled_arg : detail::view { template void vformat_to(buffer& buf, const text_style& ts, - basic_string_view format_str, - basic_format_args>> args) { + basic_string_view fmt, + basic_format_args> args) { bool has_style = false; if (ts.has_emphasis()) { has_style = true; - auto emphasis = detail::make_emphasis(ts.get_emphasis()); + auto emphasis = make_emphasis(ts.get_emphasis()); buf.append(emphasis.begin(), emphasis.end()); } if (ts.has_foreground()) { has_style = true; - auto foreground = detail::make_foreground_color(ts.get_foreground()); + auto foreground = make_foreground_color(ts.get_foreground()); buf.append(foreground.begin(), foreground.end()); } if (ts.has_background()) { has_style = true; - auto background = detail::make_background_color(ts.get_background()); + auto background = make_background_color(ts.get_background()); buf.append(background.begin(), background.end()); } - detail::vformat_to(buf, format_str, args, {}); - if (has_style) detail::reset_color(buf); + vformat_to(buf, fmt, args); + if (has_style) reset_color(buf); } - } // namespace detail -inline void vprint(std::FILE* f, const text_style& ts, string_view fmt, +inline void vprint(FILE* f, const text_style& ts, string_view fmt, format_args args) { - // Legacy wide streams are not supported. auto buf = memory_buffer(); detail::vformat_to(buf, ts, fmt, args); - if (detail::is_utf8()) { - detail::print(f, string_view(buf.begin(), buf.size())); - return; - } - buf.push_back('\0'); - int result = std::fputs(buf.data(), f); - if (result < 0) - FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); + print(f, FMT_STRING("{}"), string_view(buf.begin(), buf.size())); } /** - \rst - Formats a string and prints it to the specified file stream using ANSI - escape sequences to specify text formatting. - - **Example**:: - - fmt::print(fmt::emphasis::bold | fg(fmt::color::red), - "Elapsed time: {0:.2f} seconds", 1.23); - \endrst + * Formats a string and prints it to the specified file stream using ANSI + * escape sequences to specify text formatting. + * + * **Example**: + * + * fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + * "Elapsed time: {0:.2f} seconds", 1.23); */ -template ::value)> -void print(std::FILE* f, const text_style& ts, const S& format_str, - const Args&... args) { - vprint(f, ts, format_str, - fmt::make_format_args>>(args...)); +template +void print(FILE* f, const text_style& ts, format_string fmt, + T&&... args) { + vprint(f, ts, fmt.str, vargs{{args...}}); } /** - \rst - Formats a string and prints it to stdout using ANSI escape sequences to - specify text formatting. - - **Example**:: - - fmt::print(fmt::emphasis::bold | fg(fmt::color::red), - "Elapsed time: {0:.2f} seconds", 1.23); - \endrst + * Formats a string and prints it to stdout using ANSI escape sequences to + * specify text formatting. + * + * **Example**: + * + * fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + * "Elapsed time: {0:.2f} seconds", 1.23); */ -template ::value)> -void print(const text_style& ts, const S& format_str, const Args&... args) { - return print(stdout, ts, format_str, args...); +template +void print(const text_style& ts, format_string fmt, T&&... args) { + return print(stdout, ts, fmt, std::forward(args)...); } -template > -inline auto vformat( - const text_style& ts, const S& format_str, - basic_format_args>> args) - -> std::basic_string { - basic_memory_buffer buf; - detail::vformat_to(buf, ts, detail::to_string_view(format_str), args); +inline auto vformat(const text_style& ts, string_view fmt, format_args args) + -> std::string { + auto buf = memory_buffer(); + detail::vformat_to(buf, ts, fmt, args); return fmt::to_string(buf); } /** - \rst - Formats arguments and returns the result as a string using ANSI - escape sequences to specify text formatting. - - **Example**:: - - #include - std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), - "The answer is {}", 42); - \endrst -*/ -template > -inline auto format(const text_style& ts, const S& format_str, - const Args&... args) -> std::basic_string { - return fmt::vformat(ts, detail::to_string_view(format_str), - fmt::make_format_args>(args...)); + * Formats arguments and returns the result as a string using ANSI escape + * sequences to specify text formatting. + * + * **Example**: + * + * ``` + * #include + * std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + * "The answer is {}", 42); + * ``` + */ +template +inline auto format(const text_style& ts, format_string fmt, T&&... args) + -> std::string { + return fmt::vformat(ts, fmt.str, vargs{{args...}}); } -/** - Formats a string with the given text_style and writes the output to ``out``. - */ -template ::value)> -auto vformat_to(OutputIt out, const text_style& ts, - basic_string_view format_str, - basic_format_args>> args) - -> OutputIt { - auto&& buf = detail::get_buffer(out); - detail::vformat_to(buf, ts, format_str, args); +/// Formats a string with the given text_style and writes the output to `out`. +template ::value)> +auto vformat_to(OutputIt out, const text_style& ts, string_view fmt, + format_args args) -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, ts, fmt, args); return detail::get_iterator(buf, out); } /** - \rst - Formats arguments with the given text_style, writes the result to the output - iterator ``out`` and returns the iterator past the end of the output range. - - **Example**:: - - std::vector out; - fmt::format_to(std::back_inserter(out), - fmt::emphasis::bold | fg(fmt::color::red), "{}", 42); - \endrst -*/ -template < - typename OutputIt, typename S, typename... Args, - bool enable = detail::is_output_iterator>::value && - detail::is_string::value> -inline auto format_to(OutputIt out, const text_style& ts, const S& format_str, - Args&&... args) -> - typename std::enable_if::type { - return vformat_to(out, ts, detail::to_string_view(format_str), - fmt::make_format_args>>(args...)); + * Formats arguments with the given text style, writes the result to the output + * iterator `out` and returns the iterator past the end of the output range. + * + * **Example**: + * + * std::vector out; + * fmt::format_to(std::back_inserter(out), + * fmt::emphasis::bold | fg(fmt::color::red), "{}", 42); + */ +template ::value)> +inline auto format_to(OutputIt out, const text_style& ts, + format_string fmt, T&&... args) -> OutputIt { + return vformat_to(out, ts, fmt.str, vargs{{args...}}); } template @@ -589,47 +559,44 @@ struct formatter, Char> : formatter { auto format(const detail::styled_arg& arg, FormatContext& ctx) const -> decltype(ctx.out()) { const auto& ts = arg.style; - const auto& value = arg.value; auto out = ctx.out(); bool has_style = false; if (ts.has_emphasis()) { has_style = true; auto emphasis = detail::make_emphasis(ts.get_emphasis()); - out = std::copy(emphasis.begin(), emphasis.end(), out); + out = detail::copy(emphasis.begin(), emphasis.end(), out); } if (ts.has_foreground()) { has_style = true; auto foreground = detail::make_foreground_color(ts.get_foreground()); - out = std::copy(foreground.begin(), foreground.end(), out); + out = detail::copy(foreground.begin(), foreground.end(), out); } if (ts.has_background()) { has_style = true; auto background = detail::make_background_color(ts.get_background()); - out = std::copy(background.begin(), background.end(), out); + out = detail::copy(background.begin(), background.end(), out); } - out = formatter::format(value, ctx); + out = formatter::format(arg.value, ctx); if (has_style) { auto reset_color = string_view("\x1b[0m"); - out = std::copy(reset_color.begin(), reset_color.end(), out); + out = detail::copy(reset_color.begin(), reset_color.end(), out); } return out; } }; /** - \rst - Returns an argument that will be formatted using ANSI escape sequences, - to be used in a formatting function. - - **Example**:: - - fmt::print("Elapsed time: {0:.2f} seconds", - fmt::styled(1.23, fmt::fg(fmt::color::green) | - fmt::bg(fmt::color::blue))); - \endrst + * Returns an argument that will be formatted using ANSI escape sequences, + * to be used in a formatting function. + * + * **Example**: + * + * fmt::print("Elapsed time: {0:.2f} seconds", + * fmt::styled(1.23, fmt::fg(fmt::color::green) | + * fmt::bg(fmt::color::blue))); */ template FMT_CONSTEXPR auto styled(const T& value, text_style ts) diff --git a/third-party/fmt/include/fmt/compile.h b/third-party/fmt/include/fmt/compile.h index 3b3f166e0c..08d9427ff2 100644 --- a/third-party/fmt/include/fmt/compile.h +++ b/third-party/fmt/include/fmt/compile.h @@ -8,54 +8,39 @@ #ifndef FMT_COMPILE_H_ #define FMT_COMPILE_H_ +#ifndef FMT_MODULE +# include // std::back_inserter +#endif + #include "format.h" FMT_BEGIN_NAMESPACE -namespace detail { - -template -FMT_CONSTEXPR inline auto copy_str(InputIt begin, InputIt end, - counting_iterator it) -> counting_iterator { - return it + (end - begin); -} // A compile-time string which is compiled into fast formatting code. -class compiled_string {}; +FMT_EXPORT class compiled_string {}; template struct is_compiled_string : std::is_base_of {}; +namespace detail { + /** - \rst - Converts a string literal *s* into a format string that will be parsed at - compile time and converted into efficient formatting code. Requires C++17 - ``constexpr if`` compiler support. - - **Example**:: - - // Converts 42 into std::string using the most efficient method and no - // runtime format string processing. - std::string s = fmt::format(FMT_COMPILE("{}"), 42); - \endrst + * Converts a string literal `s` into a format string that will be parsed at + * compile time and converted into efficient formatting code. Requires C++17 + * `constexpr if` compiler support. + * + * **Example**: + * + * // Converts 42 into std::string using the most efficient method and no + * // runtime format string processing. + * std::string s = fmt::format(FMT_COMPILE("{}"), 42); */ #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) -# define FMT_COMPILE(s) \ - FMT_STRING_IMPL(s, fmt::detail::compiled_string, explicit) +# define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::compiled_string) #else # define FMT_COMPILE(s) FMT_STRING(s) #endif -#if FMT_USE_NONTYPE_TEMPLATE_ARGS -template Str> -struct udl_compiled_string : compiled_string { - using char_type = Char; - explicit constexpr operator basic_string_view() const { - return {Str.data, N - 1}; - } -}; -#endif - template auto first(const T& value, const Tail&...) -> const T& { return value; @@ -75,6 +60,29 @@ constexpr const auto& get([[maybe_unused]] const T& first, return detail::get(rest...); } +# if FMT_USE_NONTYPE_TEMPLATE_ARGS +template +constexpr auto get_arg_index_by_name(basic_string_view name) -> int { + if constexpr (is_static_named_arg()) { + if (name == T::name) return N; + } + if constexpr (sizeof...(Args) > 0) + return get_arg_index_by_name(name); + (void)name; // Workaround an MSVC bug about "unused" parameter. + return -1; +} +# endif + +template +FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view name) -> int { +# if FMT_USE_NONTYPE_TEMPLATE_ARGS + if constexpr (sizeof...(Args) > 0) + return get_arg_index_by_name<0, Args...>(name); +# endif + (void)name; + return -1; +} + template constexpr int get_arg_index_by_name(basic_string_view name, type_list) { @@ -144,11 +152,12 @@ template struct field { template constexpr OutputIt format(OutputIt out, const Args&... args) const { const T& arg = get_arg_checked(args...); - if constexpr (std::is_convertible_v>) { + if constexpr (std::is_convertible>::value) { auto s = basic_string_view(arg); - return copy_str(s.begin(), s.end(), out); + return copy(s.begin(), s.end(), out); + } else { + return write(out, arg); } - return write(out, arg); } }; @@ -236,13 +245,12 @@ constexpr size_t parse_text(basic_string_view str, size_t pos) { } template -constexpr auto compile_format_string(S format_str); +constexpr auto compile_format_string(S fmt); template -constexpr auto parse_tail(T head, S format_str) { - if constexpr (POS != - basic_string_view(format_str).size()) { - constexpr auto tail = compile_format_string(format_str); +constexpr auto parse_tail(T head, S fmt) { + if constexpr (POS != basic_string_view(fmt).size()) { + constexpr auto tail = compile_format_string(fmt); if constexpr (std::is_same, unknown_format>()) return tail; @@ -274,6 +282,7 @@ constexpr parse_specs_result parse_specs(basic_string_view str, } template struct arg_id_handler { + arg_id_kind kind; arg_ref arg_id; constexpr int on_auto() { @@ -281,25 +290,28 @@ template struct arg_id_handler { return 0; } constexpr int on_index(int id) { + kind = arg_id_kind::index; arg_id = arg_ref(id); return 0; } constexpr int on_name(basic_string_view id) { + kind = arg_id_kind::name; arg_id = arg_ref(id); return 0; } }; template struct parse_arg_id_result { + arg_id_kind kind; arg_ref arg_id; const Char* arg_id_end; }; template constexpr auto parse_arg_id(const Char* begin, const Char* end) { - auto handler = arg_id_handler{arg_ref{}}; + auto handler = arg_id_handler{arg_id_kind::none, arg_ref{}}; auto arg_id_end = parse_arg_id(begin, end, handler); - return parse_arg_id_result{handler.arg_id, arg_id_end}; + return parse_arg_id_result{handler.kind, handler.arg_id, arg_id_end}; } template struct field_type { @@ -313,14 +325,13 @@ struct field_type::value>> { template -constexpr auto parse_replacement_field_then_tail(S format_str) { +constexpr auto parse_replacement_field_then_tail(S fmt) { using char_type = typename S::char_type; - constexpr auto str = basic_string_view(format_str); + constexpr auto str = basic_string_view(fmt); constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type(); if constexpr (c == '}') { return parse_tail( - field::type, ARG_INDEX>(), - format_str); + field::type, ARG_INDEX>(), fmt); } else if constexpr (c != ':') { FMT_THROW(format_error("expected ':'")); } else { @@ -333,7 +344,7 @@ constexpr auto parse_replacement_field_then_tail(S format_str) { return parse_tail( spec_field::type, ARG_INDEX>{ result.fmt}, - format_str); + fmt); } } } @@ -341,22 +352,21 @@ constexpr auto parse_replacement_field_then_tail(S format_str) { // Compiles a non-empty format string and returns the compiled representation // or unknown_format() on unrecognized input. template -constexpr auto compile_format_string(S format_str) { +constexpr auto compile_format_string(S fmt) { using char_type = typename S::char_type; - constexpr auto str = basic_string_view(format_str); + constexpr auto str = basic_string_view(fmt); if constexpr (str[POS] == '{') { if constexpr (POS + 1 == str.size()) FMT_THROW(format_error("unmatched '{' in format string")); if constexpr (str[POS + 1] == '{') { - return parse_tail(make_text(str, POS, 1), format_str); + return parse_tail(make_text(str, POS, 1), fmt); } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') { static_assert(ID != manual_indexing_id, "cannot switch from manual to automatic argument indexing"); constexpr auto next_id = ID != manual_indexing_id ? ID + 1 : manual_indexing_id; return parse_replacement_field_then_tail, Args, - POS + 1, ID, next_id>( - format_str); + POS + 1, ID, next_id>(fmt); } else { constexpr auto arg_id_result = parse_arg_id(str.data() + POS + 1, str.data() + str.size()); @@ -364,28 +374,27 @@ constexpr auto compile_format_string(S format_str) { constexpr char_type c = arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type(); static_assert(c == '}' || c == ':', "missing '}' in format string"); - if constexpr (arg_id_result.arg_id.kind == arg_id_kind::index) { + if constexpr (arg_id_result.kind == arg_id_kind::index) { static_assert( ID == manual_indexing_id || ID == 0, "cannot switch from automatic to manual argument indexing"); - constexpr auto arg_index = arg_id_result.arg_id.val.index; + constexpr auto arg_index = arg_id_result.arg_id.index; return parse_replacement_field_then_tail, Args, arg_id_end_pos, arg_index, manual_indexing_id>( - format_str); - } else if constexpr (arg_id_result.arg_id.kind == arg_id_kind::name) { + fmt); + } else if constexpr (arg_id_result.kind == arg_id_kind::name) { constexpr auto arg_index = - get_arg_index_by_name(arg_id_result.arg_id.val.name, Args{}); + get_arg_index_by_name(arg_id_result.arg_id.name, Args{}); if constexpr (arg_index >= 0) { constexpr auto next_id = ID != manual_indexing_id ? ID + 1 : manual_indexing_id; return parse_replacement_field_then_tail< decltype(get_type::value), Args, arg_id_end_pos, - arg_index, next_id>(format_str); + arg_index, next_id>(fmt); } else if constexpr (c == '}') { return parse_tail( - runtime_named_field{arg_id_result.arg_id.val.name}, - format_str); + runtime_named_field{arg_id_result.arg_id.name}, fmt); } else if constexpr (c == ':') { return unknown_format(); // no type info for specs parsing } @@ -394,29 +403,26 @@ constexpr auto compile_format_string(S format_str) { } else if constexpr (str[POS] == '}') { if constexpr (POS + 1 == str.size()) FMT_THROW(format_error("unmatched '}' in format string")); - return parse_tail(make_text(str, POS, 1), format_str); + return parse_tail(make_text(str, POS, 1), fmt); } else { constexpr auto end = parse_text(str, POS + 1); if constexpr (end - POS > 1) { - return parse_tail(make_text(str, POS, end - POS), - format_str); + return parse_tail(make_text(str, POS, end - POS), fmt); } else { - return parse_tail(code_unit{str[POS]}, - format_str); + return parse_tail(code_unit{str[POS]}, fmt); } } } template ::value)> -constexpr auto compile(S format_str) { - constexpr auto str = basic_string_view(format_str); + FMT_ENABLE_IF(is_compiled_string::value)> +constexpr auto compile(S fmt) { + constexpr auto str = basic_string_view(fmt); if constexpr (str.size() == 0) { return detail::make_text(str, 0, 0); } else { constexpr auto result = - detail::compile_format_string, 0, 0>( - format_str); + detail::compile_format_string, 0, 0>(fmt); return result; } } @@ -445,7 +451,7 @@ constexpr FMT_INLINE OutputIt format_to(OutputIt out, const CompiledFormat& cf, } template ::value)> + FMT_ENABLE_IF(is_compiled_string::value)> FMT_INLINE std::basic_string format(const S&, Args&&... args) { if constexpr (std::is_same::value) { @@ -472,7 +478,7 @@ FMT_INLINE std::basic_string format(const S&, } template ::value)> + FMT_ENABLE_IF(is_compiled_string::value)> FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) { constexpr auto compiled = detail::compile(S()); if constexpr (std::is_same, @@ -487,44 +493,42 @@ FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) { #endif template ::value)> -auto format_to_n(OutputIt out, size_t n, const S& format_str, Args&&... args) + FMT_ENABLE_IF(is_compiled_string::value)> +auto format_to_n(OutputIt out, size_t n, const S& fmt, Args&&... args) -> format_to_n_result { using traits = detail::fixed_buffer_traits; auto buf = detail::iterator_buffer(out, n); - fmt::format_to(std::back_inserter(buf), format_str, - std::forward(args)...); + fmt::format_to(std::back_inserter(buf), fmt, std::forward(args)...); return {buf.out(), buf.count()}; } template ::value)> -FMT_CONSTEXPR20 auto formatted_size(const S& format_str, const Args&... args) + FMT_ENABLE_IF(is_compiled_string::value)> +FMT_CONSTEXPR20 auto formatted_size(const S& fmt, const Args&... args) -> size_t { - return fmt::format_to(detail::counting_iterator(), format_str, args...) - .count(); + auto buf = detail::counting_buffer<>(); + fmt::format_to(appender(buf), fmt, args...); + return buf.count(); } template ::value)> -void print(std::FILE* f, const S& format_str, const Args&... args) { - memory_buffer buffer; - fmt::format_to(std::back_inserter(buffer), format_str, args...); - detail::print(f, {buffer.data(), buffer.size()}); + FMT_ENABLE_IF(is_compiled_string::value)> +void print(std::FILE* f, const S& fmt, const Args&... args) { + auto buf = memory_buffer(); + fmt::format_to(appender(buf), fmt, args...); + detail::print(f, {buf.data(), buf.size()}); } template ::value)> -void print(const S& format_str, const Args&... args) { - print(stdout, format_str, args...); + FMT_ENABLE_IF(is_compiled_string::value)> +void print(const S& fmt, const Args&... args) { + print(stdout, fmt, args...); } #if FMT_USE_NONTYPE_TEMPLATE_ARGS inline namespace literals { -template constexpr auto operator""_cf() { - using char_t = remove_cvref_t; - return detail::udl_compiled_string(); +template constexpr auto operator""_cf() { + return FMT_COMPILE(Str.data); } } // namespace literals #endif diff --git a/third-party/fmt/include/fmt/core.h b/third-party/fmt/include/fmt/core.h index b51c1406a9..8ca735f0c0 100644 --- a/third-party/fmt/include/fmt/core.h +++ b/third-party/fmt/include/fmt/core.h @@ -1,2969 +1,5 @@ -// Formatting library for C++ - the core API for char/UTF-8 -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. +// This file is only provided for compatibility and may be removed in future +// versions. Use fmt/base.h if you don't need fmt::format and fmt/format.h +// otherwise. -#ifndef FMT_CORE_H_ -#define FMT_CORE_H_ - -#include // std::byte -#include // std::FILE -#include // std::strlen -#include -#include -#include // std::addressof -#include -#include - -// The fmt library version in the form major * 10000 + minor * 100 + patch. -#define FMT_VERSION 100201 - -#if defined(__clang__) && !defined(__ibmxl__) -# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) -#else -# define FMT_CLANG_VERSION 0 -#endif - -#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && \ - !defined(__NVCOMPILER) -# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -#else -# define FMT_GCC_VERSION 0 -#endif - -#ifndef FMT_GCC_PRAGMA -// Workaround _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884. -# if FMT_GCC_VERSION >= 504 -# define FMT_GCC_PRAGMA(arg) _Pragma(arg) -# else -# define FMT_GCC_PRAGMA(arg) -# endif -#endif - -#ifdef __ICL -# define FMT_ICC_VERSION __ICL -#elif defined(__INTEL_COMPILER) -# define FMT_ICC_VERSION __INTEL_COMPILER -#else -# define FMT_ICC_VERSION 0 -#endif - -#ifdef _MSC_VER -# define FMT_MSC_VERSION _MSC_VER -# define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__)) -#else -# define FMT_MSC_VERSION 0 -# define FMT_MSC_WARNING(...) -#endif - -#ifdef _MSVC_LANG -# define FMT_CPLUSPLUS _MSVC_LANG -#else -# define FMT_CPLUSPLUS __cplusplus -#endif - -#ifdef __has_feature -# define FMT_HAS_FEATURE(x) __has_feature(x) -#else -# define FMT_HAS_FEATURE(x) 0 -#endif - -#if defined(__has_include) || FMT_ICC_VERSION >= 1600 || FMT_MSC_VERSION > 1900 -# define FMT_HAS_INCLUDE(x) __has_include(x) -#else -# define FMT_HAS_INCLUDE(x) 0 -#endif - -#ifdef __has_cpp_attribute -# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) -#else -# define FMT_HAS_CPP_ATTRIBUTE(x) 0 -#endif - -#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \ - (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute)) - -#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \ - (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute)) - -// Check if relaxed C++14 constexpr is supported. -// GCC doesn't allow throw in constexpr until version 6 (bug 67371). -#ifndef FMT_USE_CONSTEXPR -# if (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 || \ - (FMT_GCC_VERSION >= 600 && FMT_CPLUSPLUS >= 201402L)) && \ - !FMT_ICC_VERSION && (!defined(__NVCC__) || FMT_CPLUSPLUS >= 202002L) -# define FMT_USE_CONSTEXPR 1 -# else -# define FMT_USE_CONSTEXPR 0 -# endif -#endif -#if FMT_USE_CONSTEXPR -# define FMT_CONSTEXPR constexpr -#else -# define FMT_CONSTEXPR -#endif - -#if (FMT_CPLUSPLUS >= 202002L || \ - (FMT_CPLUSPLUS >= 201709L && FMT_GCC_VERSION >= 1002)) && \ - ((!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE >= 10) && \ - (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION >= 10000) && \ - (!FMT_MSC_VERSION || FMT_MSC_VERSION >= 1928)) && \ - defined(__cpp_lib_is_constant_evaluated) -# define FMT_CONSTEXPR20 constexpr -#else -# define FMT_CONSTEXPR20 -#endif - -// Check if constexpr std::char_traits<>::{compare,length} are supported. -#if defined(__GLIBCXX__) -# if FMT_CPLUSPLUS >= 201703L && defined(_GLIBCXX_RELEASE) && \ - _GLIBCXX_RELEASE >= 7 // GCC 7+ libstdc++ has _GLIBCXX_RELEASE. -# define FMT_CONSTEXPR_CHAR_TRAITS constexpr -# endif -#elif defined(_LIBCPP_VERSION) && FMT_CPLUSPLUS >= 201703L && \ - _LIBCPP_VERSION >= 4000 -# define FMT_CONSTEXPR_CHAR_TRAITS constexpr -#elif FMT_MSC_VERSION >= 1914 && FMT_CPLUSPLUS >= 201703L -# define FMT_CONSTEXPR_CHAR_TRAITS constexpr -#endif -#ifndef FMT_CONSTEXPR_CHAR_TRAITS -# define FMT_CONSTEXPR_CHAR_TRAITS -#endif - -// Check if exceptions are disabled. -#ifndef FMT_EXCEPTIONS -# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ - (FMT_MSC_VERSION && !_HAS_EXCEPTIONS) -# define FMT_EXCEPTIONS 0 -# else -# define FMT_EXCEPTIONS 1 -# endif -#endif - -// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings. -#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && \ - !defined(__NVCC__) -# define FMT_NORETURN [[noreturn]] -#else -# define FMT_NORETURN -#endif - -#ifndef FMT_NODISCARD -# if FMT_HAS_CPP17_ATTRIBUTE(nodiscard) -# define FMT_NODISCARD [[nodiscard]] -# else -# define FMT_NODISCARD -# endif -#endif - -#ifndef FMT_INLINE -# if FMT_GCC_VERSION || FMT_CLANG_VERSION -# define FMT_INLINE inline __attribute__((always_inline)) -# else -# define FMT_INLINE inline -# endif -#endif - -#ifdef _MSC_VER -# define FMT_UNCHECKED_ITERATOR(It) \ - using _Unchecked_type = It // Mark iterator as checked. -#else -# define FMT_UNCHECKED_ITERATOR(It) using unchecked_type = It -#endif - -#ifndef FMT_BEGIN_NAMESPACE -# define FMT_BEGIN_NAMESPACE \ - namespace fmt { \ - inline namespace v10 { -# define FMT_END_NAMESPACE \ - } \ - } -#endif - -#ifndef FMT_EXPORT -# define FMT_EXPORT -# define FMT_BEGIN_EXPORT -# define FMT_END_EXPORT -#endif - -#if FMT_GCC_VERSION || FMT_CLANG_VERSION -# define FMT_VISIBILITY(value) __attribute__((visibility(value))) -#else -# define FMT_VISIBILITY(value) -#endif - -#if !defined(FMT_HEADER_ONLY) && defined(_WIN32) -# if defined(FMT_LIB_EXPORT) -# define FMT_API __declspec(dllexport) -# elif defined(FMT_SHARED) -# define FMT_API __declspec(dllimport) -# endif -#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) -# define FMT_API FMT_VISIBILITY("default") -#endif -#ifndef FMT_API -# define FMT_API -#endif - -// libc++ supports string_view in pre-c++17. -#if FMT_HAS_INCLUDE() && \ - (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION)) -# include -# define FMT_USE_STRING_VIEW -#elif FMT_HAS_INCLUDE("experimental/string_view") && FMT_CPLUSPLUS >= 201402L -# include -# define FMT_USE_EXPERIMENTAL_STRING_VIEW -#endif - -#ifndef FMT_UNICODE -# define FMT_UNICODE !FMT_MSC_VERSION -#endif - -#ifndef FMT_CONSTEVAL -# if ((FMT_GCC_VERSION >= 1000 || FMT_CLANG_VERSION >= 1101) && \ - (!defined(__apple_build_version__) || \ - __apple_build_version__ >= 14000029L) && \ - FMT_CPLUSPLUS >= 202002L) || \ - (defined(__cpp_consteval) && \ - (!FMT_MSC_VERSION || FMT_MSC_VERSION >= 1929)) -// consteval is broken in MSVC before VS2019 version 16.10 and Apple clang -// before 14. -# define FMT_CONSTEVAL consteval -# define FMT_HAS_CONSTEVAL -# else -# define FMT_CONSTEVAL -# endif -#endif - -#ifndef FMT_USE_NONTYPE_TEMPLATE_ARGS -# if defined(__cpp_nontype_template_args) && \ - ((FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L) || \ - __cpp_nontype_template_args >= 201911L) && \ - !defined(__NVCOMPILER) && !defined(__LCC__) -# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 -# else -# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 -# endif -#endif - -// GCC < 5 requires this-> in decltype -#ifndef FMT_DECLTYPE_THIS -# if FMT_GCC_VERSION && FMT_GCC_VERSION < 500 -# define FMT_DECLTYPE_THIS this-> -# else -# define FMT_DECLTYPE_THIS -# endif -#endif - -// Enable minimal optimizations for more compact code in debug mode. -FMT_GCC_PRAGMA("GCC push_options") -#if !defined(__OPTIMIZE__) && !defined(__NVCOMPILER) && !defined(__LCC__) && \ - !defined(__CUDACC__) -FMT_GCC_PRAGMA("GCC optimize(\"Og\")") -#endif - -FMT_BEGIN_NAMESPACE - -// Implementations of enable_if_t and other metafunctions for older systems. -template -using enable_if_t = typename std::enable_if::type; -template -using conditional_t = typename std::conditional::type; -template using bool_constant = std::integral_constant; -template -using remove_reference_t = typename std::remove_reference::type; -template -using remove_const_t = typename std::remove_const::type; -template -using remove_cvref_t = typename std::remove_cv>::type; -template struct type_identity { - using type = T; -}; -template using type_identity_t = typename type_identity::type; -template -using underlying_t = typename std::underlying_type::type; - -// Checks whether T is a container with contiguous storage. -template struct is_contiguous : std::false_type {}; -template -struct is_contiguous> : std::true_type {}; - -struct monostate { - constexpr 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). -#ifdef FMT_DOC -# define FMT_ENABLE_IF(...) -#else -# define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0 -#endif - -// This is defined in core.h instead of format.h to avoid injecting in std. -// It is a template to avoid undesirable implicit conversions to std::byte. -#ifdef __cpp_lib_byte -template ::value)> -inline auto format_as(T b) -> unsigned char { - return static_cast(b); -} -#endif - -namespace detail { -// Suppresses "unused variable" warnings with the method described in -// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/. -// (void)var does not work on many Intel compilers. -template FMT_CONSTEXPR void ignore_unused(const T&...) {} - -constexpr FMT_INLINE auto is_constant_evaluated( - bool default_value = false) noexcept -> bool { -// Workaround for incompatibility between libstdc++ consteval-based -// std::is_constant_evaluated() implementation and clang-14. -// https://github.com/fmtlib/fmt/issues/3247 -#if FMT_CPLUSPLUS >= 202002L && defined(_GLIBCXX_RELEASE) && \ - _GLIBCXX_RELEASE >= 12 && \ - (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500) - ignore_unused(default_value); - return __builtin_is_constant_evaluated(); -#elif defined(__cpp_lib_is_constant_evaluated) - ignore_unused(default_value); - return std::is_constant_evaluated(); -#else - return default_value; -#endif -} - -// Suppresses "conditional expression is constant" warnings. -template constexpr FMT_INLINE auto const_check(T value) -> T { - return value; -} - -FMT_NORETURN FMT_API void assert_fail(const char* file, int line, - const char* message); - -#ifndef FMT_ASSERT -# ifdef NDEBUG -// FMT_ASSERT is not empty to avoid -Wempty-body. -# define FMT_ASSERT(condition, message) \ - fmt::detail::ignore_unused((condition), (message)) -# else -# define FMT_ASSERT(condition, message) \ - ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ - ? (void)0 \ - : fmt::detail::assert_fail(__FILE__, __LINE__, (message))) -# endif -#endif - -#if defined(FMT_USE_STRING_VIEW) -template using std_string_view = std::basic_string_view; -#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) -template -using std_string_view = std::experimental::basic_string_view; -#else -template struct std_string_view {}; -#endif - -#ifdef FMT_USE_INT128 -// Do nothing. -#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \ - !(FMT_CLANG_VERSION && FMT_MSC_VERSION) -# define FMT_USE_INT128 1 -using int128_opt = __int128_t; // An optional native 128-bit integer. -using uint128_opt = __uint128_t; -template inline auto convert_for_visit(T value) -> T { - return value; -} -#else -# define FMT_USE_INT128 0 -#endif -#if !FMT_USE_INT128 -enum class int128_opt {}; -enum class uint128_opt {}; -// Reduce template instantiations. -template auto convert_for_visit(T) -> monostate { return {}; } -#endif - -// Casts a nonnegative integer to unsigned. -template -FMT_CONSTEXPR auto to_unsigned(Int value) -> - typename std::make_unsigned::type { - FMT_ASSERT(std::is_unsigned::value || value >= 0, "negative value"); - return static_cast::type>(value); -} - -FMT_CONSTEXPR inline auto is_utf8() -> bool { - FMT_MSC_WARNING(suppress : 4566) constexpr unsigned char section[] = "\u00A7"; - - // Avoid buggy sign extensions in MSVC's constant evaluation mode (#2297). - using uchar = unsigned char; - return FMT_UNICODE || (sizeof(section) == 3 && uchar(section[0]) == 0xC2 && - uchar(section[1]) == 0xA7); -} -} // namespace detail - -/** - An implementation of ``std::basic_string_view`` for pre-C++17. It provides a - subset of the API. ``fmt::basic_string_view`` is used for format strings even - if ``std::string_view`` is available to prevent issues when a library is - compiled with a different ``-std`` option than the client code (which is not - recommended). - */ -FMT_EXPORT -template class basic_string_view { - private: - const Char* data_; - size_t size_; - - public: - using value_type = Char; - using iterator = const Char*; - - constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {} - - /** Constructs a string reference object from a C string and a size. */ - constexpr basic_string_view(const Char* s, size_t count) noexcept - : data_(s), size_(count) {} - - /** - \rst - Constructs a string reference object from a C string computing - the size with ``std::char_traits::length``. - \endrst - */ - FMT_CONSTEXPR_CHAR_TRAITS - FMT_INLINE - basic_string_view(const Char* s) - : data_(s), - size_(detail::const_check(std::is_same::value && - !detail::is_constant_evaluated(true)) - ? std::strlen(reinterpret_cast(s)) - : std::char_traits::length(s)) {} - - /** Constructs a string reference from a ``std::basic_string`` object. */ - template - FMT_CONSTEXPR basic_string_view( - const std::basic_string& s) noexcept - : data_(s.data()), size_(s.size()) {} - - template >::value)> - FMT_CONSTEXPR basic_string_view(S s) noexcept - : data_(s.data()), size_(s.size()) {} - - /** Returns a pointer to the string data. */ - constexpr auto data() const noexcept -> const Char* { return data_; } - - /** Returns the string size. */ - constexpr auto size() const noexcept -> size_t { return size_; } - - constexpr auto begin() const noexcept -> iterator { return data_; } - constexpr auto end() const noexcept -> iterator { return data_ + size_; } - - constexpr auto operator[](size_t pos) const noexcept -> const Char& { - return data_[pos]; - } - - FMT_CONSTEXPR void remove_prefix(size_t n) noexcept { - data_ += n; - size_ -= n; - } - - FMT_CONSTEXPR_CHAR_TRAITS auto starts_with( - basic_string_view sv) const noexcept -> bool { - return size_ >= sv.size_ && - std::char_traits::compare(data_, sv.data_, sv.size_) == 0; - } - FMT_CONSTEXPR_CHAR_TRAITS auto starts_with(Char c) const noexcept -> bool { - return size_ >= 1 && std::char_traits::eq(*data_, c); - } - FMT_CONSTEXPR_CHAR_TRAITS auto starts_with(const Char* s) const -> bool { - return starts_with(basic_string_view(s)); - } - - // Lexicographically compare this string reference to other. - FMT_CONSTEXPR_CHAR_TRAITS auto compare(basic_string_view other) const -> int { - size_t str_size = size_ < other.size_ ? size_ : other.size_; - int result = std::char_traits::compare(data_, other.data_, str_size); - if (result == 0) - result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); - return result; - } - - FMT_CONSTEXPR_CHAR_TRAITS friend auto operator==(basic_string_view lhs, - basic_string_view rhs) - -> bool { - return lhs.compare(rhs) == 0; - } - friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool { - return lhs.compare(rhs) != 0; - } - friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool { - return lhs.compare(rhs) < 0; - } - friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool { - return lhs.compare(rhs) <= 0; - } - friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool { - return lhs.compare(rhs) > 0; - } - friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool { - return lhs.compare(rhs) >= 0; - } -}; - -FMT_EXPORT -using string_view = basic_string_view; - -/** Specifies if ``T`` is a character type. Can be specialized by users. */ -FMT_EXPORT -template struct is_char : std::false_type {}; -template <> struct is_char : std::true_type {}; - -namespace detail { - -// A base class for compile-time strings. -struct compile_string {}; - -template -struct is_compile_string : std::is_base_of {}; - -template ::value)> -FMT_INLINE auto to_string_view(const Char* s) -> basic_string_view { - return s; -} -template -inline auto to_string_view(const std::basic_string& s) - -> basic_string_view { - return s; -} -template -constexpr auto to_string_view(basic_string_view s) - -> basic_string_view { - return s; -} -template >::value)> -inline auto to_string_view(std_string_view s) -> basic_string_view { - return s; -} -template ::value)> -constexpr auto to_string_view(const S& s) - -> basic_string_view { - return basic_string_view(s); -} -void 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. -// ADL is intentionally disabled as to_string_view is not an extension point. -template -struct is_string - : std::is_class()))> {}; - -template struct char_t_impl {}; -template struct char_t_impl::value>> { - using result = decltype(to_string_view(std::declval())); - using type = typename result::value_type; -}; - -enum class type { - none_type, - // Integer types should go first, - int_type, - uint_type, - long_long_type, - ulong_long_type, - int128_type, - uint128_type, - bool_type, - char_type, - last_integer_type = char_type, - // followed by floating-point types. - float_type, - double_type, - long_double_type, - last_numeric_type = long_double_type, - cstring_type, - string_type, - pointer_type, - custom_type -}; - -// Maps core type T to the corresponding type enum constant. -template -struct type_constant : std::integral_constant {}; - -#define FMT_TYPE_CONSTANT(Type, constant) \ - template \ - struct type_constant \ - : std::integral_constant {} - -FMT_TYPE_CONSTANT(int, int_type); -FMT_TYPE_CONSTANT(unsigned, uint_type); -FMT_TYPE_CONSTANT(long long, long_long_type); -FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); -FMT_TYPE_CONSTANT(int128_opt, int128_type); -FMT_TYPE_CONSTANT(uint128_opt, uint128_type); -FMT_TYPE_CONSTANT(bool, bool_type); -FMT_TYPE_CONSTANT(Char, char_type); -FMT_TYPE_CONSTANT(float, float_type); -FMT_TYPE_CONSTANT(double, double_type); -FMT_TYPE_CONSTANT(long double, long_double_type); -FMT_TYPE_CONSTANT(const Char*, cstring_type); -FMT_TYPE_CONSTANT(basic_string_view, string_type); -FMT_TYPE_CONSTANT(const void*, pointer_type); - -constexpr auto is_integral_type(type t) -> bool { - return t > type::none_type && t <= type::last_integer_type; -} -constexpr auto is_arithmetic_type(type t) -> bool { - return t > type::none_type && t <= type::last_numeric_type; -} - -constexpr auto set(type rhs) -> int { return 1 << static_cast(rhs); } -constexpr auto in(type t, int set) -> bool { - return ((set >> static_cast(t)) & 1) != 0; -} - -// Bitsets of types. -enum { - sint_set = - set(type::int_type) | set(type::long_long_type) | set(type::int128_type), - uint_set = set(type::uint_type) | set(type::ulong_long_type) | - set(type::uint128_type), - bool_set = set(type::bool_type), - char_set = set(type::char_type), - float_set = set(type::float_type) | set(type::double_type) | - set(type::long_double_type), - string_set = set(type::string_type), - cstring_set = set(type::cstring_type), - pointer_set = set(type::pointer_type) -}; - -// DEPRECATED! -FMT_NORETURN FMT_API void throw_format_error(const char* message); - -struct error_handler { - constexpr error_handler() = default; - - // This function is intentionally not constexpr to give a compile-time error. - FMT_NORETURN void on_error(const char* message) { - throw_format_error(message); - } -}; -} // namespace detail - -/** Throws ``format_error`` with a given message. */ -using detail::throw_format_error; - -/** String's character type. */ -template using char_t = typename detail::char_t_impl::type; - -/** - \rst - Parsing context consisting of a format string range being parsed and an - argument counter for automatic indexing. - You can use the ``format_parse_context`` type alias for ``char`` instead. - \endrst - */ -FMT_EXPORT -template class basic_format_parse_context { - private: - basic_string_view format_str_; - int next_arg_id_; - - FMT_CONSTEXPR void do_check_arg_id(int id); - - public: - using char_type = Char; - using iterator = const Char*; - - explicit constexpr basic_format_parse_context( - basic_string_view format_str, int next_arg_id = 0) - : format_str_(format_str), next_arg_id_(next_arg_id) {} - - /** - Returns an iterator to the beginning of the format string range being - parsed. - */ - constexpr auto begin() const noexcept -> iterator { - return format_str_.begin(); - } - - /** - Returns an iterator past the end of the format string range being parsed. - */ - constexpr auto end() const noexcept -> iterator { return format_str_.end(); } - - /** Advances the begin iterator to ``it``. */ - FMT_CONSTEXPR void advance_to(iterator it) { - format_str_.remove_prefix(detail::to_unsigned(it - begin())); - } - - /** - Reports an error if using the manual argument indexing; otherwise returns - the next argument index and switches to the automatic indexing. - */ - FMT_CONSTEXPR auto next_arg_id() -> int { - if (next_arg_id_ < 0) { - detail::throw_format_error( - "cannot switch from manual to automatic argument indexing"); - return 0; - } - int id = next_arg_id_++; - do_check_arg_id(id); - return id; - } - - /** - Reports an error if using the automatic argument indexing; otherwise - switches to the manual indexing. - */ - FMT_CONSTEXPR void check_arg_id(int id) { - if (next_arg_id_ > 0) { - detail::throw_format_error( - "cannot switch from automatic to manual argument indexing"); - return; - } - next_arg_id_ = -1; - do_check_arg_id(id); - } - FMT_CONSTEXPR void check_arg_id(basic_string_view) {} - FMT_CONSTEXPR void check_dynamic_spec(int arg_id); -}; - -FMT_EXPORT -using format_parse_context = basic_format_parse_context; - -namespace detail { -// A parse context with extra data used only in compile-time checks. -template -class compile_parse_context : public basic_format_parse_context { - private: - int num_args_; - const type* types_; - using base = basic_format_parse_context; - - public: - explicit FMT_CONSTEXPR compile_parse_context( - basic_string_view format_str, int num_args, const type* types, - int next_arg_id = 0) - : base(format_str, next_arg_id), num_args_(num_args), types_(types) {} - - constexpr auto num_args() const -> int { return num_args_; } - constexpr auto arg_type(int id) const -> type { return types_[id]; } - - FMT_CONSTEXPR auto next_arg_id() -> int { - int id = base::next_arg_id(); - if (id >= num_args_) throw_format_error("argument not found"); - return id; - } - - FMT_CONSTEXPR void check_arg_id(int id) { - base::check_arg_id(id); - if (id >= num_args_) throw_format_error("argument not found"); - } - using base::check_arg_id; - - FMT_CONSTEXPR void check_dynamic_spec(int arg_id) { - detail::ignore_unused(arg_id); -#if !defined(__LCC__) - if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id])) - throw_format_error("width/precision is not integer"); -#endif - } -}; - -// Extracts a reference to the container from back_insert_iterator. -template -inline auto get_container(std::back_insert_iterator it) - -> Container& { - using base = std::back_insert_iterator; - struct accessor : base { - accessor(base b) : base(b) {} - using base::container; - }; - return *accessor(it).container; -} - -template -FMT_CONSTEXPR auto copy_str(InputIt begin, InputIt end, OutputIt out) - -> OutputIt { - while (begin != end) *out++ = static_cast(*begin++); - return out; -} - -template , U>::value&& is_char::value)> -FMT_CONSTEXPR auto copy_str(T* begin, T* end, U* out) -> U* { - if (is_constant_evaluated()) return copy_str(begin, end, out); - auto size = to_unsigned(end - begin); - if (size > 0) memcpy(out, begin, size * sizeof(U)); - return out + size; -} - -/** - \rst - A contiguous memory buffer with an optional growing ability. It is an internal - class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`. - \endrst - */ -template class buffer { - private: - T* ptr_; - size_t size_; - size_t capacity_; - - protected: - // Don't initialize ptr_ since it is not accessed to save a few cycles. - FMT_MSC_WARNING(suppress : 26495) - FMT_CONSTEXPR buffer(size_t sz) noexcept : size_(sz), capacity_(sz) {} - - FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) noexcept - : ptr_(p), size_(sz), capacity_(cap) {} - - FMT_CONSTEXPR20 ~buffer() = default; - buffer(buffer&&) = default; - - /** Sets the buffer data and capacity. */ - FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept { - ptr_ = buf_data; - capacity_ = buf_capacity; - } - - /** Increases the buffer capacity to hold at least *capacity* elements. */ - // DEPRECATED! - virtual FMT_CONSTEXPR20 void grow(size_t capacity) = 0; - - public: - using value_type = T; - using const_reference = const T&; - - buffer(const buffer&) = delete; - void operator=(const buffer&) = delete; - - FMT_INLINE auto begin() noexcept -> T* { return ptr_; } - FMT_INLINE auto end() noexcept -> T* { return ptr_ + size_; } - - FMT_INLINE auto begin() const noexcept -> const T* { return ptr_; } - FMT_INLINE auto end() const noexcept -> const T* { return ptr_ + size_; } - - /** Returns the size of this buffer. */ - constexpr auto size() const noexcept -> size_t { return size_; } - - /** Returns the capacity of this buffer. */ - constexpr auto capacity() const noexcept -> size_t { return capacity_; } - - /** Returns a pointer to the buffer data (not null-terminated). */ - FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; } - FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; } - - /** Clears this buffer. */ - void clear() { size_ = 0; } - - // Tries resizing the buffer to contain *count* elements. If T is a POD type - // the new elements may not be initialized. - FMT_CONSTEXPR20 void try_resize(size_t count) { - try_reserve(count); - size_ = count <= capacity_ ? count : capacity_; - } - - // Tries increasing the buffer capacity to *new_capacity*. It can increase the - // capacity by a smaller amount than requested but guarantees there is space - // for at least one additional element either by increasing the capacity or by - // flushing the buffer if it is full. - FMT_CONSTEXPR20 void try_reserve(size_t new_capacity) { - if (new_capacity > capacity_) grow(new_capacity); - } - - FMT_CONSTEXPR20 void push_back(const T& value) { - try_reserve(size_ + 1); - ptr_[size_++] = value; - } - - /** Appends data to the end of the buffer. */ - template void append(const U* begin, const U* end); - - template FMT_CONSTEXPR auto operator[](Idx index) -> T& { - return ptr_[index]; - } - template - FMT_CONSTEXPR auto operator[](Idx index) const -> const T& { - return ptr_[index]; - } -}; - -struct buffer_traits { - explicit buffer_traits(size_t) {} - auto count() const -> size_t { return 0; } - auto limit(size_t size) -> size_t { return size; } -}; - -class fixed_buffer_traits { - private: - size_t count_ = 0; - size_t limit_; - - public: - explicit fixed_buffer_traits(size_t limit) : limit_(limit) {} - auto count() const -> size_t { return count_; } - auto limit(size_t size) -> size_t { - size_t n = limit_ > count_ ? limit_ - count_ : 0; - count_ += size; - return size < n ? size : n; - } -}; - -// A buffer that writes to an output iterator when flushed. -template -class iterator_buffer final : public Traits, public buffer { - private: - OutputIt out_; - enum { buffer_size = 256 }; - T data_[buffer_size]; - - protected: - FMT_CONSTEXPR20 void grow(size_t) override { - if (this->size() == buffer_size) flush(); - } - - void flush() { - auto size = this->size(); - this->clear(); - out_ = copy_str(data_, data_ + this->limit(size), out_); - } - - public: - explicit iterator_buffer(OutputIt out, size_t n = buffer_size) - : Traits(n), buffer(data_, 0, buffer_size), out_(out) {} - iterator_buffer(iterator_buffer&& other) - : Traits(other), buffer(data_, 0, buffer_size), out_(other.out_) {} - ~iterator_buffer() { flush(); } - - auto out() -> OutputIt { - flush(); - return out_; - } - auto count() const -> size_t { return Traits::count() + this->size(); } -}; - -template -class iterator_buffer final - : public fixed_buffer_traits, - public buffer { - private: - T* out_; - enum { buffer_size = 256 }; - T data_[buffer_size]; - - protected: - FMT_CONSTEXPR20 void grow(size_t) override { - if (this->size() == this->capacity()) flush(); - } - - void flush() { - size_t n = this->limit(this->size()); - if (this->data() == out_) { - out_ += n; - this->set(data_, buffer_size); - } - this->clear(); - } - - public: - explicit iterator_buffer(T* out, size_t n = buffer_size) - : fixed_buffer_traits(n), buffer(out, 0, n), out_(out) {} - iterator_buffer(iterator_buffer&& other) - : fixed_buffer_traits(other), - buffer(std::move(other)), - out_(other.out_) { - if (this->data() != out_) { - this->set(data_, buffer_size); - this->clear(); - } - } - ~iterator_buffer() { flush(); } - - auto out() -> T* { - flush(); - return out_; - } - auto count() const -> size_t { - return fixed_buffer_traits::count() + this->size(); - } -}; - -template class iterator_buffer final : public buffer { - protected: - FMT_CONSTEXPR20 void grow(size_t) override {} - - public: - explicit iterator_buffer(T* out, size_t = 0) : buffer(out, 0, ~size_t()) {} - - auto out() -> T* { return &*this->end(); } -}; - -// A buffer that writes to a container with the contiguous storage. -template -class iterator_buffer, - enable_if_t::value, - typename Container::value_type>> - final : public buffer { - private: - Container& container_; - - protected: - FMT_CONSTEXPR20 void grow(size_t capacity) override { - container_.resize(capacity); - this->set(&container_[0], capacity); - } - - public: - explicit iterator_buffer(Container& c) - : buffer(c.size()), container_(c) {} - explicit iterator_buffer(std::back_insert_iterator out, size_t = 0) - : iterator_buffer(get_container(out)) {} - - auto out() -> std::back_insert_iterator { - return std::back_inserter(container_); - } -}; - -// A buffer that counts the number of code units written discarding the output. -template class counting_buffer final : public buffer { - private: - enum { buffer_size = 256 }; - T data_[buffer_size]; - size_t count_ = 0; - - protected: - FMT_CONSTEXPR20 void grow(size_t) override { - if (this->size() != buffer_size) return; - count_ += this->size(); - this->clear(); - } - - public: - counting_buffer() : buffer(data_, 0, buffer_size) {} - - auto count() -> size_t { return count_ + this->size(); } -}; -} // namespace detail - -template -FMT_CONSTEXPR void basic_format_parse_context::do_check_arg_id(int id) { - // Argument id is only checked at compile-time during parsing because - // formatting has its own validation. - if (detail::is_constant_evaluated() && - (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) { - using context = detail::compile_parse_context; - if (id >= static_cast(this)->num_args()) - detail::throw_format_error("argument not found"); - } -} - -template -FMT_CONSTEXPR void basic_format_parse_context::check_dynamic_spec( - int arg_id) { - if (detail::is_constant_evaluated() && - (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) { - using context = detail::compile_parse_context; - static_cast(this)->check_dynamic_spec(arg_id); - } -} - -FMT_EXPORT template class basic_format_arg; -FMT_EXPORT template class basic_format_args; -FMT_EXPORT template class dynamic_format_arg_store; - -// A formatter for objects of type T. -FMT_EXPORT -template -struct formatter { - // A deleted default constructor indicates a disabled formatter. - formatter() = delete; -}; - -// Specifies if T has an enabled formatter specialization. A type can be -// formattable even if it doesn't have a formatter e.g. via a conversion. -template -using has_formatter = - std::is_constructible>; - -// An output iterator that appends to a buffer. -// It is used to reduce symbol sizes for the common case. -class appender : public std::back_insert_iterator> { - using base = std::back_insert_iterator>; - - public: - using std::back_insert_iterator>::back_insert_iterator; - appender(base it) noexcept : base(it) {} - FMT_UNCHECKED_ITERATOR(appender); - - auto operator++() noexcept -> appender& { return *this; } - auto operator++(int) noexcept -> appender { return *this; } -}; - -namespace detail { - -template -constexpr auto has_const_formatter_impl(T*) - -> decltype(typename Context::template formatter_type().format( - std::declval(), std::declval()), - true) { - return true; -} -template -constexpr auto has_const_formatter_impl(...) -> bool { - return false; -} -template -constexpr auto has_const_formatter() -> bool { - return has_const_formatter_impl(static_cast(nullptr)); -} - -template -using buffer_appender = conditional_t::value, appender, - std::back_insert_iterator>>; - -// Maps an output iterator to a buffer. -template -auto get_buffer(OutputIt out) -> iterator_buffer { - return iterator_buffer(out); -} -template , Buf>::value)> -auto get_buffer(std::back_insert_iterator out) -> buffer& { - return get_container(out); -} - -template -FMT_INLINE auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) { - return buf.out(); -} -template -auto get_iterator(buffer&, OutputIt out) -> OutputIt { - return out; -} - -struct view {}; - -template struct named_arg : view { - const Char* name; - const T& value; - named_arg(const Char* n, const T& v) : name(n), value(v) {} -}; - -template struct named_arg_info { - const Char* name; - int id; -}; - -template -struct arg_data { - // args_[0].named_args points to named_args_ to avoid bloating format_args. - // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. - T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)]; - named_arg_info named_args_[NUM_NAMED_ARGS]; - - template - arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {} - arg_data(const arg_data& other) = delete; - auto args() const -> const T* { return args_ + 1; } - auto named_args() -> named_arg_info* { return named_args_; } -}; - -template -struct arg_data { - // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. - T args_[NUM_ARGS != 0 ? NUM_ARGS : +1]; - - template - FMT_CONSTEXPR FMT_INLINE arg_data(const U&... init) : args_{init...} {} - FMT_CONSTEXPR FMT_INLINE auto args() const -> const T* { return args_; } - FMT_CONSTEXPR FMT_INLINE auto named_args() -> std::nullptr_t { - return nullptr; - } -}; - -template -inline void init_named_args(named_arg_info*, int, int) {} - -template struct is_named_arg : std::false_type {}; -template struct is_statically_named_arg : std::false_type {}; - -template -struct is_named_arg> : std::true_type {}; - -template ::value)> -void init_named_args(named_arg_info* named_args, int arg_count, - int named_arg_count, const T&, const Tail&... args) { - init_named_args(named_args, arg_count + 1, named_arg_count, args...); -} - -template ::value)> -void init_named_args(named_arg_info* named_args, int arg_count, - int named_arg_count, const T& arg, const Tail&... args) { - named_args[named_arg_count++] = {arg.name, arg_count}; - init_named_args(named_args, arg_count + 1, named_arg_count, args...); -} - -template -FMT_CONSTEXPR FMT_INLINE void init_named_args(std::nullptr_t, int, int, - const Args&...) {} - -template constexpr auto count() -> size_t { return B ? 1 : 0; } -template constexpr auto count() -> size_t { - return (B1 ? 1 : 0) + count(); -} - -template constexpr auto count_named_args() -> size_t { - return count::value...>(); -} - -template -constexpr auto count_statically_named_args() -> size_t { - return count::value...>(); -} - -struct unformattable {}; -struct unformattable_char : unformattable {}; -struct unformattable_pointer : unformattable {}; - -template struct string_value { - const Char* data; - size_t size; -}; - -template struct named_arg_value { - const named_arg_info* data; - size_t size; -}; - -template struct custom_value { - using parse_context = typename Context::parse_context_type; - void* value; - void (*format)(void* arg, parse_context& parse_ctx, Context& ctx); -}; - -// A formatting argument value. -template class value { - public: - using char_type = typename Context::char_type; - - union { - monostate no_value; - int int_value; - unsigned uint_value; - long long long_long_value; - unsigned long long ulong_long_value; - int128_opt int128_value; - uint128_opt uint128_value; - bool bool_value; - char_type char_value; - float float_value; - double double_value; - long double long_double_value; - const void* pointer; - string_value string; - custom_value custom; - named_arg_value named_args; - }; - - constexpr FMT_INLINE value() : no_value() {} - constexpr FMT_INLINE value(int val) : int_value(val) {} - constexpr FMT_INLINE value(unsigned val) : uint_value(val) {} - constexpr FMT_INLINE value(long long val) : long_long_value(val) {} - constexpr FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {} - FMT_INLINE value(int128_opt val) : int128_value(val) {} - FMT_INLINE value(uint128_opt val) : uint128_value(val) {} - constexpr FMT_INLINE value(float val) : float_value(val) {} - constexpr FMT_INLINE value(double val) : double_value(val) {} - FMT_INLINE value(long double val) : long_double_value(val) {} - constexpr FMT_INLINE value(bool val) : bool_value(val) {} - constexpr FMT_INLINE value(char_type val) : char_value(val) {} - FMT_CONSTEXPR FMT_INLINE value(const char_type* val) { - string.data = val; - if (is_constant_evaluated()) string.size = {}; - } - FMT_CONSTEXPR FMT_INLINE value(basic_string_view val) { - string.data = val.data(); - string.size = val.size(); - } - FMT_INLINE value(const void* val) : pointer(val) {} - FMT_INLINE value(const named_arg_info* args, size_t size) - : named_args{args, size} {} - - template FMT_CONSTEXPR20 FMT_INLINE value(T& val) { - using value_type = remove_const_t; - custom.value = const_cast(std::addressof(val)); - // Get the formatter type through the context to allow different contexts - // have different extension points, e.g. `formatter` for `format` and - // `printf_formatter` for `printf`. - custom.format = format_custom_arg< - value_type, typename Context::template formatter_type>; - } - value(unformattable); - value(unformattable_char); - value(unformattable_pointer); - - private: - // Formats an argument of a custom type, such as a user-defined class. - template - static void format_custom_arg(void* arg, - typename Context::parse_context_type& parse_ctx, - Context& ctx) { - auto f = Formatter(); - parse_ctx.advance_to(f.parse(parse_ctx)); - using qualified_type = - conditional_t(), const T, T>; - // Calling format through a mutable reference is deprecated. - ctx.advance_to(f.format(*static_cast(arg), ctx)); - } -}; - -// 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; -using ulong_type = conditional_t; - -template struct format_as_result { - template ::value || std::is_class::value)> - static auto map(U*) -> remove_cvref_t()))>; - static auto map(...) -> void; - - using type = decltype(map(static_cast(nullptr))); -}; -template using format_as_t = typename format_as_result::type; - -template -struct has_format_as - : bool_constant, void>::value> {}; - -// Maps formatting arguments to core types. -// arg_mapper reports errors by returning unformattable instead of using -// static_assert because it's used in the is_formattable trait. -template struct arg_mapper { - using char_type = typename Context::char_type; - - FMT_CONSTEXPR FMT_INLINE auto map(signed char val) -> int { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(unsigned char val) -> unsigned { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(short val) -> int { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(unsigned short val) -> unsigned { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(int val) -> int { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(unsigned val) -> unsigned { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(long val) -> long_type { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(unsigned long val) -> ulong_type { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(long long val) -> long long { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(unsigned long long val) - -> unsigned long long { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(int128_opt val) -> int128_opt { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(uint128_opt val) -> uint128_opt { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(bool val) -> bool { return val; } - - template ::value || - std::is_same::value)> - FMT_CONSTEXPR FMT_INLINE auto map(T val) -> char_type { - return val; - } - template ::value || -#ifdef __cpp_char8_t - std::is_same::value || -#endif - std::is_same::value || - std::is_same::value) && - !std::is_same::value, - int> = 0> - FMT_CONSTEXPR FMT_INLINE auto map(T) -> unformattable_char { - return {}; - } - - FMT_CONSTEXPR FMT_INLINE auto map(float val) -> float { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(double val) -> double { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(long double val) -> long double { - return val; - } - - FMT_CONSTEXPR FMT_INLINE auto map(char_type* val) -> const char_type* { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(const char_type* val) -> const char_type* { - return val; - } - template ::value && !std::is_pointer::value && - std::is_same>::value)> - FMT_CONSTEXPR FMT_INLINE auto map(const T& val) - -> basic_string_view { - return to_string_view(val); - } - template ::value && !std::is_pointer::value && - !std::is_same>::value)> - FMT_CONSTEXPR FMT_INLINE auto map(const T&) -> unformattable_char { - return {}; - } - - FMT_CONSTEXPR FMT_INLINE auto map(void* val) -> const void* { return val; } - FMT_CONSTEXPR FMT_INLINE auto map(const void* val) -> const void* { - return val; - } - FMT_CONSTEXPR FMT_INLINE auto map(std::nullptr_t val) -> const void* { - return val; - } - - // Use SFINAE instead of a const T* parameter to avoid a conflict with the - // array overload. - template < - typename T, - FMT_ENABLE_IF( - std::is_pointer::value || std::is_member_pointer::value || - std::is_function::type>::value || - (std::is_array::value && - !std::is_convertible::value))> - FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer { - return {}; - } - - template ::value)> - FMT_CONSTEXPR FMT_INLINE auto map(const T (&values)[N]) -> const T (&)[N] { - return values; - } - - // Only map owning types because mapping views can be unsafe. - template , - FMT_ENABLE_IF(std::is_arithmetic::value)> - FMT_CONSTEXPR FMT_INLINE auto map(const T& val) - -> decltype(FMT_DECLTYPE_THIS map(U())) { - return map(format_as(val)); - } - - template > - struct formattable : bool_constant() || - (has_formatter::value && - !std::is_const::value)> {}; - - template ::value)> - FMT_CONSTEXPR FMT_INLINE auto do_map(T& val) -> T& { - return val; - } - template ::value)> - FMT_CONSTEXPR FMT_INLINE auto do_map(T&) -> unformattable { - return {}; - } - - template , - FMT_ENABLE_IF((std::is_class::value || std::is_enum::value || - std::is_union::value) && - !is_string::value && !is_char::value && - !is_named_arg::value && - !std::is_arithmetic>::value)> - FMT_CONSTEXPR FMT_INLINE auto map(T& val) - -> decltype(FMT_DECLTYPE_THIS do_map(val)) { - return do_map(val); - } - - template ::value)> - FMT_CONSTEXPR FMT_INLINE auto map(const T& named_arg) - -> decltype(FMT_DECLTYPE_THIS map(named_arg.value)) { - return map(named_arg.value); - } - - auto map(...) -> unformattable { return {}; } -}; - -// A type constant after applying arg_mapper. -template -using mapped_type_constant = - type_constant().map(std::declval())), - typename Context::char_type>; - -enum { packed_arg_bits = 4 }; -// Maximum number of arguments with packed types. -enum { max_packed_args = 62 / packed_arg_bits }; -enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; -enum : unsigned long long { has_named_args_bit = 1ULL << 62 }; - -template -auto copy_str(InputIt begin, InputIt end, appender out) -> appender { - get_container(out).append(begin, end); - return out; -} -template -auto copy_str(InputIt begin, InputIt end, - std::back_insert_iterator out) - -> std::back_insert_iterator { - get_container(out).append(begin, end); - return out; -} - -template -FMT_CONSTEXPR auto copy_str(R&& rng, OutputIt out) -> OutputIt { - return detail::copy_str(rng.begin(), rng.end(), out); -} - -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 500 -// A workaround for gcc 4.8 to make void_t work in a SFINAE context. -template struct void_t_impl { - using type = void; -}; -template using void_t = typename void_t_impl::type; -#else -template using void_t = void; -#endif - -template -struct is_output_iterator : std::false_type {}; - -template -struct is_output_iterator< - It, T, - void_t::iterator_category, - decltype(*std::declval() = std::declval())>> - : std::true_type {}; - -template struct is_back_insert_iterator : std::false_type {}; -template -struct is_back_insert_iterator> - : std::true_type {}; - -// A type-erased reference to an std::locale to avoid a heavy include. -class locale_ref { - private: - const void* locale_; // A type-erased pointer to std::locale. - - public: - constexpr FMT_INLINE locale_ref() : locale_(nullptr) {} - template explicit locale_ref(const Locale& loc); - - explicit operator bool() const noexcept { return locale_ != nullptr; } - - template auto get() const -> Locale; -}; - -template constexpr auto encode_types() -> unsigned long long { - return 0; -} - -template -constexpr auto encode_types() -> unsigned long long { - return static_cast(mapped_type_constant::value) | - (encode_types() << packed_arg_bits); -} - -#if defined(__cpp_if_constexpr) -// This type is intentionally undefined, only used for errors -template struct type_is_unformattable_for; -#endif - -template -FMT_CONSTEXPR FMT_INLINE auto make_arg(T& val) -> value { - using arg_type = remove_cvref_t().map(val))>; - - constexpr bool formattable_char = - !std::is_same::value; - static_assert(formattable_char, "Mixing character types is disallowed."); - - // Formatting of arbitrary pointers is disallowed. If you want to format a - // pointer cast it to `void*` or `const void*`. In particular, this forbids - // formatting of `[const] volatile char*` printed as bool by iostreams. - constexpr bool formattable_pointer = - !std::is_same::value; - static_assert(formattable_pointer, - "Formatting of non-void pointers is disallowed."); - - constexpr bool formattable = !std::is_same::value; -#if defined(__cpp_if_constexpr) - if constexpr (!formattable) { - type_is_unformattable_for _; - } -#endif - static_assert( - formattable, - "Cannot format an argument. To make type T formattable provide a " - "formatter specialization: https://fmt.dev/latest/api.html#udt"); - return {arg_mapper().map(val)}; -} - -template -FMT_CONSTEXPR auto make_arg(T& val) -> basic_format_arg { - auto arg = basic_format_arg(); - arg.type_ = mapped_type_constant::value; - arg.value_ = make_arg(val); - return arg; -} - -template -FMT_CONSTEXPR inline auto make_arg(T& val) -> basic_format_arg { - return make_arg(val); -} -} // namespace detail -FMT_BEGIN_EXPORT - -// A formatting argument. Context is a template parameter for the compiled API -// where output can be unbuffered. -template class basic_format_arg { - private: - detail::value value_; - detail::type type_; - - template - friend FMT_CONSTEXPR auto detail::make_arg(T& value) - -> basic_format_arg; - - template - friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, - const basic_format_arg& arg) - -> decltype(vis(0)); - - friend class basic_format_args; - friend class dynamic_format_arg_store; - - using char_type = typename Context::char_type; - - template - friend struct detail::arg_data; - - basic_format_arg(const detail::named_arg_info* args, size_t size) - : value_(args, size) {} - - public: - class handle { - public: - explicit handle(detail::custom_value custom) : custom_(custom) {} - - void format(typename Context::parse_context_type& parse_ctx, - Context& ctx) const { - custom_.format(custom_.value, parse_ctx, ctx); - } - - private: - detail::custom_value custom_; - }; - - constexpr basic_format_arg() : type_(detail::type::none_type) {} - - constexpr explicit operator bool() const noexcept { - return type_ != detail::type::none_type; - } - - auto type() const -> detail::type { return type_; } - - auto is_integral() const -> bool { return detail::is_integral_type(type_); } - auto is_arithmetic() const -> bool { - return detail::is_arithmetic_type(type_); - } - - FMT_INLINE auto format_custom(const char_type* parse_begin, - typename Context::parse_context_type& parse_ctx, - Context& ctx) -> bool { - if (type_ != detail::type::custom_type) return false; - parse_ctx.advance_to(parse_begin); - value_.custom.format(value_.custom.value, parse_ctx, ctx); - return true; - } -}; - -/** - \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 - */ -// DEPRECATED! -template -FMT_CONSTEXPR FMT_INLINE auto visit_format_arg( - Visitor&& vis, const basic_format_arg& arg) -> decltype(vis(0)) { - switch (arg.type_) { - case detail::type::none_type: - break; - case detail::type::int_type: - return vis(arg.value_.int_value); - case detail::type::uint_type: - return vis(arg.value_.uint_value); - case detail::type::long_long_type: - return vis(arg.value_.long_long_value); - case detail::type::ulong_long_type: - return vis(arg.value_.ulong_long_value); - case detail::type::int128_type: - return vis(detail::convert_for_visit(arg.value_.int128_value)); - case detail::type::uint128_type: - return vis(detail::convert_for_visit(arg.value_.uint128_value)); - case detail::type::bool_type: - return vis(arg.value_.bool_value); - case detail::type::char_type: - return vis(arg.value_.char_value); - case detail::type::float_type: - return vis(arg.value_.float_value); - case detail::type::double_type: - return vis(arg.value_.double_value); - case detail::type::long_double_type: - return vis(arg.value_.long_double_value); - case detail::type::cstring_type: - return vis(arg.value_.string.data); - case detail::type::string_type: - using sv = basic_string_view; - return vis(sv(arg.value_.string.data, arg.value_.string.size)); - case detail::type::pointer_type: - return vis(arg.value_.pointer); - case detail::type::custom_type: - return vis(typename basic_format_arg::handle(arg.value_.custom)); - } - return vis(monostate()); -} - -// Formatting context. -template class basic_format_context { - private: - OutputIt out_; - basic_format_args args_; - detail::locale_ref loc_; - - public: - using iterator = OutputIt; - using format_arg = basic_format_arg; - using format_args = basic_format_args; - using parse_context_type = basic_format_parse_context; - template using formatter_type = formatter; - - /** The character type for the output. */ - using char_type = Char; - - basic_format_context(basic_format_context&&) = default; - basic_format_context(const basic_format_context&) = delete; - void operator=(const basic_format_context&) = delete; - /** - Constructs a ``basic_format_context`` object. References to the arguments - are stored in the object so make sure they have appropriate lifetimes. - */ - constexpr basic_format_context(OutputIt out, format_args ctx_args, - detail::locale_ref loc = {}) - : out_(out), args_(ctx_args), loc_(loc) {} - - constexpr auto arg(int id) const -> format_arg { return args_.get(id); } - FMT_CONSTEXPR auto arg(basic_string_view name) -> format_arg { - return args_.get(name); - } - FMT_CONSTEXPR auto arg_id(basic_string_view name) -> int { - return args_.get_id(name); - } - auto args() const -> const format_args& { return args_; } - - // DEPRECATED! - FMT_CONSTEXPR auto error_handler() -> detail::error_handler { return {}; } - void on_error(const char* message) { error_handler().on_error(message); } - - // Returns an iterator to the beginning of the output range. - FMT_CONSTEXPR auto out() -> iterator { return out_; } - - // Advances the begin iterator to ``it``. - void advance_to(iterator it) { - if (!detail::is_back_insert_iterator()) out_ = it; - } - - FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; } -}; - -template -using buffer_context = - basic_format_context, Char>; -using format_context = buffer_context; - -template -using is_formattable = bool_constant>() - .map(std::declval()))>::value>; - -/** - \rst - An array of references to arguments. It can be implicitly converted into - `~fmt::basic_format_args` for passing into type-erased formatting functions - such as `~fmt::vformat`. - \endrst - */ -template -class format_arg_store -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 - // Workaround a GCC template argument substitution bug. - : public basic_format_args -#endif -{ - private: - static const size_t num_args = sizeof...(Args); - static constexpr size_t num_named_args = detail::count_named_args(); - static const bool is_packed = num_args <= detail::max_packed_args; - - using value_type = conditional_t, - basic_format_arg>; - - detail::arg_data - data_; - - friend class basic_format_args; - - static constexpr unsigned long long desc = - (is_packed ? detail::encode_types() - : detail::is_unpacked_bit | num_args) | - (num_named_args != 0 - ? static_cast(detail::has_named_args_bit) - : 0); - - public: - template - FMT_CONSTEXPR FMT_INLINE format_arg_store(T&... args) - : -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 - basic_format_args(*this), -#endif - data_{detail::make_arg(args)...} { - if (detail::const_check(num_named_args != 0)) - detail::init_named_args(data_.named_args(), 0, 0, args...); - } -}; - -/** - \rst - Constructs a `~fmt::format_arg_store` object that contains references to - arguments and can be implicitly converted to `~fmt::format_args`. `Context` - can be omitted in which case it defaults to `~fmt::format_context`. - See `~fmt::arg` for lifetime considerations. - \endrst - */ -// Arguments are taken by lvalue references to avoid some lifetime issues. -template -constexpr auto make_format_args(T&... args) - -> format_arg_store...> { - return {args...}; -} - -/** - \rst - Returns a named argument to be used in a formatting function. - It should only be used in a call to a formatting function or - `dynamic_format_arg_store::push_back`. - - **Example**:: - - fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23)); - \endrst - */ -template -inline auto arg(const Char* name, const T& arg) -> detail::named_arg { - static_assert(!detail::is_named_arg(), "nested named arguments"); - return {name, arg}; -} -FMT_END_EXPORT - -/** - \rst - A view of a collection of formatting arguments. To avoid lifetime issues it - should only be used as a parameter type in type-erased functions such as - ``vformat``:: - - void vlog(string_view format_str, format_args args); // OK - format_args args = make_format_args(); // Error: dangling reference - \endrst - */ -template class basic_format_args { - public: - using size_type = int; - using format_arg = basic_format_arg; - - private: - // A descriptor that contains information about formatting arguments. - // If the number of arguments is less or equal to max_packed_args then - // argument types are passed in the descriptor. This reduces binary code size - // per formatting function call. - unsigned long long desc_; - union { - // If is_packed() returns true then argument values are stored in values_; - // otherwise they are stored in args_. This is done to improve cache - // locality and reduce compiled code size since storing larger objects - // may require more code (at least on x86-64) even if the same amount of - // data is actually copied to stack. It saves ~10% on the bloat test. - const detail::value* values_; - const format_arg* args_; - }; - - constexpr auto is_packed() const -> bool { - return (desc_ & detail::is_unpacked_bit) == 0; - } - auto has_named_args() const -> bool { - return (desc_ & detail::has_named_args_bit) != 0; - } - - FMT_CONSTEXPR auto type(int index) const -> detail::type { - int shift = index * detail::packed_arg_bits; - unsigned int mask = (1 << detail::packed_arg_bits) - 1; - return static_cast((desc_ >> shift) & mask); - } - - constexpr FMT_INLINE basic_format_args(unsigned long long desc, - const detail::value* values) - : desc_(desc), values_(values) {} - constexpr basic_format_args(unsigned long long desc, const format_arg* args) - : desc_(desc), args_(args) {} - - public: - constexpr basic_format_args() : desc_(0), args_(nullptr) {} - - /** - \rst - Constructs a `basic_format_args` object from `~fmt::format_arg_store`. - \endrst - */ - template - constexpr FMT_INLINE basic_format_args( - const format_arg_store& store) - : basic_format_args(format_arg_store::desc, - store.data_.args()) {} - - /** - \rst - Constructs a `basic_format_args` object from - `~fmt::dynamic_format_arg_store`. - \endrst - */ - constexpr FMT_INLINE basic_format_args( - const dynamic_format_arg_store& store) - : basic_format_args(store.get_types(), store.data()) {} - - /** - \rst - Constructs a `basic_format_args` object from a dynamic set of arguments. - \endrst - */ - constexpr basic_format_args(const format_arg* args, int count) - : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count), - args) {} - - /** Returns the argument with the specified id. */ - FMT_CONSTEXPR auto get(int id) const -> format_arg { - format_arg arg; - if (!is_packed()) { - if (id < max_size()) arg = args_[id]; - return arg; - } - if (id >= detail::max_packed_args) return arg; - arg.type_ = type(id); - if (arg.type_ == detail::type::none_type) return arg; - arg.value_ = values_[id]; - return arg; - } - - template - auto get(basic_string_view name) const -> format_arg { - int id = get_id(name); - return id >= 0 ? get(id) : format_arg(); - } - - template - auto get_id(basic_string_view name) const -> int { - if (!has_named_args()) return -1; - const auto& named_args = - (is_packed() ? values_[-1] : args_[-1].value_).named_args; - for (size_t i = 0; i < named_args.size; ++i) { - if (named_args.data[i].name == name) return named_args.data[i].id; - } - return -1; - } - - auto max_size() const -> int { - unsigned long long max_packed = detail::max_packed_args; - return static_cast(is_packed() ? max_packed - : desc_ & ~detail::is_unpacked_bit); - } -}; - -/** An alias to ``basic_format_args``. */ -// A separate type would result in shorter symbols but break ABI compatibility -// between clang and gcc on ARM (#1919). -FMT_EXPORT using format_args = basic_format_args; - -// We cannot use enum classes as bit fields because of a gcc bug, so we put them -// in namespaces instead (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414). -// Additionally, if an underlying type is specified, older gcc incorrectly warns -// that the type is too small. Both bugs are fixed in gcc 9.3. -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 903 -# define FMT_ENUM_UNDERLYING_TYPE(type) -#else -# define FMT_ENUM_UNDERLYING_TYPE(type) : type -#endif -namespace align { -enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, left, right, center, - numeric}; -} -using align_t = align::type; -namespace sign { -enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, minus, plus, space}; -} -using sign_t = sign::type; - -namespace detail { - -// Workaround an array initialization issue in gcc 4.8. -template struct fill_t { - private: - enum { max_size = 4 }; - Char data_[max_size] = {Char(' '), Char(0), Char(0), Char(0)}; - unsigned char size_ = 1; - - public: - FMT_CONSTEXPR void operator=(basic_string_view s) { - auto size = s.size(); - FMT_ASSERT(size <= max_size, "invalid fill"); - for (size_t i = 0; i < size; ++i) data_[i] = s[i]; - size_ = static_cast(size); - } - - constexpr auto size() const -> size_t { return size_; } - constexpr auto data() const -> const Char* { return data_; } - - FMT_CONSTEXPR auto operator[](size_t index) -> Char& { return data_[index]; } - FMT_CONSTEXPR auto operator[](size_t index) const -> const Char& { - return data_[index]; - } -}; -} // namespace detail - -enum class presentation_type : unsigned char { - none, - dec, // 'd' - oct, // 'o' - hex_lower, // 'x' - hex_upper, // 'X' - bin_lower, // 'b' - bin_upper, // 'B' - hexfloat_lower, // 'a' - hexfloat_upper, // 'A' - exp_lower, // 'e' - exp_upper, // 'E' - fixed_lower, // 'f' - fixed_upper, // 'F' - general_lower, // 'g' - general_upper, // 'G' - chr, // 'c' - string, // 's' - pointer, // 'p' - debug // '?' -}; - -// Format specifiers for built-in and string types. -template struct format_specs { - int width; - int precision; - presentation_type type; - align_t align : 4; - sign_t sign : 3; - bool alt : 1; // Alternate form ('#'). - bool localized : 1; - detail::fill_t fill; - - constexpr format_specs() - : width(0), - precision(-1), - type(presentation_type::none), - align(align::none), - sign(sign::none), - alt(false), - localized(false) {} -}; - -namespace detail { - -enum class arg_id_kind { none, index, name }; - -// An argument reference. -template struct arg_ref { - FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {} - - FMT_CONSTEXPR explicit arg_ref(int index) - : kind(arg_id_kind::index), val(index) {} - FMT_CONSTEXPR explicit arg_ref(basic_string_view name) - : kind(arg_id_kind::name), val(name) {} - - FMT_CONSTEXPR auto operator=(int idx) -> arg_ref& { - kind = arg_id_kind::index; - val.index = idx; - return *this; - } - - arg_id_kind kind; - union value { - FMT_CONSTEXPR value(int idx = 0) : index(idx) {} - FMT_CONSTEXPR value(basic_string_view n) : name(n) {} - - int index; - basic_string_view name; - } val; -}; - -// Format specifiers with width and precision resolved at formatting rather -// than parsing time to allow reusing the same parsed specifiers with -// different sets of arguments (precompilation of format strings). -template -struct dynamic_format_specs : format_specs { - arg_ref width_ref; - arg_ref precision_ref; -}; - -// Converts a character to ASCII. Returns '\0' on conversion failure. -template ::value)> -constexpr auto to_ascii(Char c) -> char { - return c <= 0xff ? static_cast(c) : '\0'; -} -template ::value)> -constexpr auto to_ascii(Char c) -> char { - return c <= 0xff ? static_cast(c) : '\0'; -} - -// Returns the number of code units in a code point or 1 on error. -template -FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int { - if (const_check(sizeof(Char) != 1)) return 1; - auto c = static_cast(*begin); - return static_cast((0x3a55000000000000ull >> (2 * (c >> 3))) & 0x3) + 1; -} - -// Return the result via the out param to workaround gcc bug 77539. -template -FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool { - for (out = first; out != last; ++out) { - if (*out == value) return true; - } - return false; -} - -template <> -inline auto find(const char* first, const char* last, char value, - const char*& out) -> bool { - out = static_cast( - std::memchr(first, value, to_unsigned(last - first))); - return out != nullptr; -} - -// Parses the range [begin, end) as an unsigned integer. This function assumes -// that the range is non-empty and the first character is a digit. -template -FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end, - int error_value) noexcept -> int { - FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); - unsigned value = 0, prev = 0; - auto p = begin; - do { - prev = value; - value = value * 10 + unsigned(*p - '0'); - ++p; - } while (p != end && '0' <= *p && *p <= '9'); - auto num_digits = p - begin; - begin = p; - if (num_digits <= std::numeric_limits::digits10) - return static_cast(value); - // Check for overflow. - const unsigned max = to_unsigned((std::numeric_limits::max)()); - return num_digits == std::numeric_limits::digits10 + 1 && - prev * 10ull + unsigned(p[-1] - '0') <= max - ? static_cast(value) - : error_value; -} - -FMT_CONSTEXPR inline auto parse_align(char c) -> align_t { - switch (c) { - case '<': - return align::left; - case '>': - return align::right; - case '^': - return align::center; - } - return align::none; -} - -template constexpr auto is_name_start(Char c) -> bool { - return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; -} - -template -FMT_CONSTEXPR auto do_parse_arg_id(const Char* begin, const Char* end, - Handler&& handler) -> const Char* { - Char c = *begin; - if (c >= '0' && c <= '9') { - int index = 0; - constexpr int max = (std::numeric_limits::max)(); - if (c != '0') - index = parse_nonnegative_int(begin, end, max); - else - ++begin; - if (begin == end || (*begin != '}' && *begin != ':')) - throw_format_error("invalid format string"); - else - handler.on_index(index); - return begin; - } - if (!is_name_start(c)) { - throw_format_error("invalid format string"); - return begin; - } - auto it = begin; - do { - ++it; - } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9'))); - handler.on_name({begin, to_unsigned(it - begin)}); - return it; -} - -template -FMT_CONSTEXPR FMT_INLINE auto parse_arg_id(const Char* begin, const Char* end, - Handler&& handler) -> const Char* { - FMT_ASSERT(begin != end, ""); - Char c = *begin; - if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler); - handler.on_auto(); - return begin; -} - -template struct dynamic_spec_id_handler { - basic_format_parse_context& ctx; - arg_ref& ref; - - FMT_CONSTEXPR void on_auto() { - int id = ctx.next_arg_id(); - ref = arg_ref(id); - ctx.check_dynamic_spec(id); - } - FMT_CONSTEXPR void on_index(int id) { - ref = arg_ref(id); - ctx.check_arg_id(id); - ctx.check_dynamic_spec(id); - } - FMT_CONSTEXPR void on_name(basic_string_view id) { - ref = arg_ref(id); - ctx.check_arg_id(id); - } -}; - -// Parses [integer | "{" [arg_id] "}"]. -template -FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end, - int& value, arg_ref& ref, - basic_format_parse_context& ctx) - -> const Char* { - FMT_ASSERT(begin != end, ""); - if ('0' <= *begin && *begin <= '9') { - int val = parse_nonnegative_int(begin, end, -1); - if (val != -1) - value = val; - else - throw_format_error("number is too big"); - } else if (*begin == '{') { - ++begin; - auto handler = dynamic_spec_id_handler{ctx, ref}; - if (begin != end) begin = parse_arg_id(begin, end, handler); - if (begin != end && *begin == '}') return ++begin; - throw_format_error("invalid format string"); - } - return begin; -} - -template -FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end, - int& value, arg_ref& ref, - basic_format_parse_context& ctx) - -> const Char* { - ++begin; - if (begin == end || *begin == '}') { - throw_format_error("invalid precision"); - return begin; - } - return parse_dynamic_spec(begin, end, value, ref, ctx); -} - -enum class state { start, align, sign, hash, zero, width, precision, locale }; - -// Parses standard format specifiers. -template -FMT_CONSTEXPR FMT_INLINE auto parse_format_specs( - const Char* begin, const Char* end, dynamic_format_specs& specs, - basic_format_parse_context& ctx, type arg_type) -> const Char* { - auto c = '\0'; - if (end - begin > 1) { - auto next = to_ascii(begin[1]); - c = parse_align(next) == align::none ? to_ascii(*begin) : '\0'; - } else { - if (begin == end) return begin; - c = to_ascii(*begin); - } - - struct { - state current_state = state::start; - FMT_CONSTEXPR void operator()(state s, bool valid = true) { - if (current_state >= s || !valid) - throw_format_error("invalid format specifier"); - current_state = s; - } - } enter_state; - - using pres = presentation_type; - constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; - struct { - const Char*& begin; - dynamic_format_specs& specs; - type arg_type; - - FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* { - if (!in(arg_type, set)) { - if (arg_type == type::none_type) return begin; - throw_format_error("invalid format specifier"); - } - specs.type = pres_type; - return begin + 1; - } - } parse_presentation_type{begin, specs, arg_type}; - - for (;;) { - switch (c) { - case '<': - case '>': - case '^': - enter_state(state::align); - specs.align = parse_align(c); - ++begin; - break; - case '+': - case '-': - case ' ': - if (arg_type == type::none_type) return begin; - enter_state(state::sign, in(arg_type, sint_set | float_set)); - switch (c) { - case '+': - specs.sign = sign::plus; - break; - case '-': - specs.sign = sign::minus; - break; - case ' ': - specs.sign = sign::space; - break; - } - ++begin; - break; - case '#': - if (arg_type == type::none_type) return begin; - enter_state(state::hash, is_arithmetic_type(arg_type)); - specs.alt = true; - ++begin; - break; - case '0': - enter_state(state::zero); - if (!is_arithmetic_type(arg_type)) { - if (arg_type == type::none_type) return begin; - throw_format_error("format specifier requires numeric argument"); - } - if (specs.align == align::none) { - // Ignore 0 if align is specified for compatibility with std::format. - specs.align = align::numeric; - specs.fill[0] = Char('0'); - } - ++begin; - break; - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '{': - enter_state(state::width); - begin = parse_dynamic_spec(begin, end, specs.width, specs.width_ref, ctx); - break; - case '.': - if (arg_type == type::none_type) return begin; - enter_state(state::precision, - in(arg_type, float_set | string_set | cstring_set)); - begin = parse_precision(begin, end, specs.precision, specs.precision_ref, - ctx); - break; - case 'L': - if (arg_type == type::none_type) return begin; - enter_state(state::locale, is_arithmetic_type(arg_type)); - specs.localized = true; - ++begin; - break; - case 'd': - return parse_presentation_type(pres::dec, integral_set); - case 'o': - return parse_presentation_type(pres::oct, integral_set); - case 'x': - return parse_presentation_type(pres::hex_lower, integral_set); - case 'X': - return parse_presentation_type(pres::hex_upper, integral_set); - case 'b': - return parse_presentation_type(pres::bin_lower, integral_set); - case 'B': - return parse_presentation_type(pres::bin_upper, integral_set); - case 'a': - return parse_presentation_type(pres::hexfloat_lower, float_set); - case 'A': - return parse_presentation_type(pres::hexfloat_upper, float_set); - case 'e': - return parse_presentation_type(pres::exp_lower, float_set); - case 'E': - return parse_presentation_type(pres::exp_upper, float_set); - case 'f': - return parse_presentation_type(pres::fixed_lower, float_set); - case 'F': - return parse_presentation_type(pres::fixed_upper, float_set); - case 'g': - return parse_presentation_type(pres::general_lower, float_set); - case 'G': - return parse_presentation_type(pres::general_upper, float_set); - case 'c': - if (arg_type == type::bool_type) - throw_format_error("invalid format specifier"); - return parse_presentation_type(pres::chr, integral_set); - case 's': - return parse_presentation_type(pres::string, - bool_set | string_set | cstring_set); - case 'p': - return parse_presentation_type(pres::pointer, pointer_set | cstring_set); - case '?': - return parse_presentation_type(pres::debug, - char_set | string_set | cstring_set); - case '}': - return begin; - default: { - if (*begin == '}') return begin; - // Parse fill and alignment. - auto fill_end = begin + code_point_length(begin); - if (end - fill_end <= 0) { - throw_format_error("invalid format specifier"); - return begin; - } - if (*begin == '{') { - throw_format_error("invalid fill character '{'"); - return begin; - } - auto align = parse_align(to_ascii(*fill_end)); - enter_state(state::align, align != align::none); - specs.fill = {begin, to_unsigned(fill_end - begin)}; - specs.align = align; - begin = fill_end + 1; - } - } - if (begin == end) return begin; - c = to_ascii(*begin); - } -} - -template -FMT_CONSTEXPR auto parse_replacement_field(const Char* begin, const Char* end, - Handler&& handler) -> const Char* { - struct id_adapter { - Handler& handler; - int arg_id; - - FMT_CONSTEXPR void on_auto() { arg_id = handler.on_arg_id(); } - FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); } - FMT_CONSTEXPR void on_name(basic_string_view id) { - arg_id = handler.on_arg_id(id); - } - }; - - ++begin; - if (begin == end) return handler.on_error("invalid format string"), end; - if (*begin == '}') { - handler.on_replacement_field(handler.on_arg_id(), begin); - } else if (*begin == '{') { - handler.on_text(begin, begin + 1); - } else { - auto adapter = id_adapter{handler, 0}; - begin = parse_arg_id(begin, end, adapter); - Char c = begin != end ? *begin : Char(); - if (c == '}') { - handler.on_replacement_field(adapter.arg_id, begin); - } else if (c == ':') { - begin = handler.on_format_specs(adapter.arg_id, begin + 1, end); - if (begin == end || *begin != '}') - return handler.on_error("unknown format specifier"), end; - } else { - return handler.on_error("missing '}' in format string"), end; - } - } - return begin + 1; -} - -template -FMT_CONSTEXPR FMT_INLINE void parse_format_string( - basic_string_view format_str, Handler&& handler) { - auto begin = format_str.data(); - auto end = begin + format_str.size(); - if (end - begin < 32) { - // Use a simple loop instead of memchr for small strings. - const Char* p = begin; - while (p != end) { - auto c = *p++; - if (c == '{') { - handler.on_text(begin, p - 1); - begin = p = parse_replacement_field(p - 1, end, handler); - } else if (c == '}') { - if (p == end || *p != '}') - return handler.on_error("unmatched '}' in format string"); - handler.on_text(begin, p); - begin = ++p; - } - } - handler.on_text(begin, end); - return; - } - struct writer { - FMT_CONSTEXPR void operator()(const Char* from, const Char* to) { - if (from == to) return; - for (;;) { - const Char* p = nullptr; - if (!find(from, to, Char('}'), p)) - return handler_.on_text(from, to); - ++p; - if (p == to || *p != '}') - return handler_.on_error("unmatched '}' in format string"); - handler_.on_text(from, p); - from = p + 1; - } - } - Handler& handler_; - } write = {handler}; - while (begin != end) { - // Doing two passes with memchr (one for '{' and another for '}') is up to - // 2.5x faster than the naive one-pass implementation on big format strings. - const Char* p = begin; - if (*begin != '{' && !find(begin + 1, end, Char('{'), p)) - return write(begin, end); - write(begin, p); - begin = parse_replacement_field(p, end, handler); - } -} - -template ::value> struct strip_named_arg { - using type = T; -}; -template struct strip_named_arg { - using type = remove_cvref_t; -}; - -template -FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx) - -> decltype(ctx.begin()) { - using char_type = typename ParseContext::char_type; - using context = buffer_context; - using mapped_type = conditional_t< - mapped_type_constant::value != type::custom_type, - decltype(arg_mapper().map(std::declval())), - typename strip_named_arg::type>; -#if defined(__cpp_if_constexpr) - if constexpr (std::is_default_constructible< - formatter>::value) { - return formatter().parse(ctx); - } else { - type_is_unformattable_for _; - return ctx.begin(); - } -#else - return formatter().parse(ctx); -#endif -} - -// Checks char specs and returns true iff the presentation type is char-like. -template -FMT_CONSTEXPR auto check_char_specs(const format_specs& specs) -> bool { - if (specs.type != presentation_type::none && - specs.type != presentation_type::chr && - specs.type != presentation_type::debug) { - return false; - } - if (specs.align == align::numeric || specs.sign != sign::none || specs.alt) - throw_format_error("invalid format specifier for char"); - return true; -} - -#if FMT_USE_NONTYPE_TEMPLATE_ARGS -template -constexpr auto get_arg_index_by_name(basic_string_view name) -> int { - if constexpr (is_statically_named_arg()) { - if (name == T::name) return N; - } - if constexpr (sizeof...(Args) > 0) - return get_arg_index_by_name(name); - (void)name; // Workaround an MSVC bug about "unused" parameter. - return -1; -} -#endif - -template -FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view name) -> int { -#if FMT_USE_NONTYPE_TEMPLATE_ARGS - if constexpr (sizeof...(Args) > 0) - return get_arg_index_by_name<0, Args...>(name); -#endif - (void)name; - return -1; -} - -template class format_string_checker { - private: - using parse_context_type = compile_parse_context; - static constexpr int num_args = sizeof...(Args); - - // Format specifier parsing function. - // In the future basic_format_parse_context will replace compile_parse_context - // here and will use is_constant_evaluated and downcasting to access the data - // needed for compile-time checks: https://godbolt.org/z/GvWzcTjh1. - using parse_func = const Char* (*)(parse_context_type&); - - type types_[num_args > 0 ? static_cast(num_args) : 1]; - parse_context_type context_; - parse_func parse_funcs_[num_args > 0 ? static_cast(num_args) : 1]; - - public: - explicit FMT_CONSTEXPR format_string_checker(basic_string_view fmt) - : types_{mapped_type_constant>::value...}, - context_(fmt, num_args, types_), - parse_funcs_{&parse_format_specs...} {} - - FMT_CONSTEXPR void on_text(const Char*, const Char*) {} - - FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); } - FMT_CONSTEXPR auto on_arg_id(int id) -> int { - return context_.check_arg_id(id), id; - } - FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { -#if FMT_USE_NONTYPE_TEMPLATE_ARGS - auto index = get_arg_index_by_name(id); - if (index < 0) on_error("named argument is not found"); - return index; -#else - (void)id; - on_error("compile-time checks for named arguments require C++20 support"); - return 0; -#endif - } - - FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) { - on_format_specs(id, begin, begin); // Call parse() on empty specs. - } - - FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char*) - -> const Char* { - context_.advance_to(begin); - // id >= 0 check is a workaround for gcc 10 bug (#2065). - return id >= 0 && id < num_args ? parse_funcs_[id](context_) : begin; - } - - FMT_CONSTEXPR void on_error(const char* message) { - throw_format_error(message); - } -}; - -// Reports a compile-time error if S is not a valid format string. -template ::value)> -FMT_INLINE void check_format_string(const S&) { -#ifdef FMT_ENFORCE_COMPILE_STRING - static_assert(is_compile_string::value, - "FMT_ENFORCE_COMPILE_STRING requires all format strings to use " - "FMT_STRING."); -#endif -} -template ::value)> -void check_format_string(S format_str) { - using char_t = typename S::char_type; - FMT_CONSTEXPR auto s = basic_string_view(format_str); - using checker = format_string_checker...>; - FMT_CONSTEXPR bool error = (parse_format_string(s, checker(s)), true); - ignore_unused(error); -} - -template struct vformat_args { - using type = basic_format_args< - basic_format_context>, Char>>; -}; -template <> struct vformat_args { - using type = format_args; -}; - -// Use vformat_args and avoid type_identity to keep symbols short. -template -void vformat_to(buffer& buf, basic_string_view fmt, - typename vformat_args::type args, locale_ref loc = {}); - -FMT_API void vprint_mojibake(std::FILE*, string_view, format_args); -#ifndef _WIN32 -inline void vprint_mojibake(std::FILE*, string_view, format_args) {} -#endif -} // namespace detail - -FMT_BEGIN_EXPORT - -// A formatter specialization for natively supported types. -template -struct formatter::value != - detail::type::custom_type>> { - private: - detail::dynamic_format_specs specs_; - - public: - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const Char* { - auto type = detail::type_constant::value; - auto end = - detail::parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, type); - if (type == detail::type::char_type) detail::check_char_specs(specs_); - return end; - } - - template ::value, - FMT_ENABLE_IF(U == detail::type::string_type || - U == detail::type::cstring_type || - U == detail::type::char_type)> - FMT_CONSTEXPR void set_debug_format(bool set = true) { - specs_.type = set ? presentation_type::debug : presentation_type::none; - } - - template - FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const - -> decltype(ctx.out()); -}; - -template struct runtime_format_string { - basic_string_view str; -}; - -/** A compile-time format string. */ -template class basic_format_string { - private: - basic_string_view str_; - - public: - template >::value)> - FMT_CONSTEVAL FMT_INLINE basic_format_string(const S& s) : str_(s) { - static_assert( - detail::count< - (std::is_base_of>::value && - std::is_reference::value)...>() == 0, - "passing views as lvalues is disallowed"); -#ifdef FMT_HAS_CONSTEVAL - if constexpr (detail::count_named_args() == - detail::count_statically_named_args()) { - using checker = - detail::format_string_checker...>; - detail::parse_format_string(str_, checker(s)); - } -#else - detail::check_format_string(s); -#endif - } - basic_format_string(runtime_format_string fmt) : str_(fmt.str) {} - - FMT_INLINE operator basic_string_view() const { return str_; } - FMT_INLINE auto get() const -> basic_string_view { return str_; } -}; - -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 -// Workaround broken conversion on older gcc. -template using format_string = string_view; -inline auto runtime(string_view s) -> string_view { return s; } -#else -template -using format_string = basic_format_string...>; -/** - \rst - Creates a runtime format string. - - **Example**:: - - // Check format string at runtime instead of compile-time. - fmt::print(fmt::runtime("{:d}"), "I am not a number"); - \endrst - */ -inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; } -#endif - -FMT_API auto vformat(string_view fmt, format_args args) -> std::string; - -/** - \rst - Formats ``args`` according to specifications in ``fmt`` and returns the result - as a string. - - **Example**:: - - #include - std::string message = fmt::format("The answer is {}.", 42); - \endrst -*/ -template -FMT_NODISCARD FMT_INLINE auto format(format_string fmt, T&&... args) - -> std::string { - return vformat(fmt, fmt::make_format_args(args...)); -} - -/** Formats a string and writes the output to ``out``. */ -template ::value)> -auto vformat_to(OutputIt out, string_view fmt, format_args args) -> OutputIt { - auto&& buf = detail::get_buffer(out); - detail::vformat_to(buf, fmt, args, {}); - return detail::get_iterator(buf, out); -} - -/** - \rst - Formats ``args`` according to specifications in ``fmt``, writes the result to - the output iterator ``out`` and returns the iterator past the end of the output - range. `format_to` does not append a terminating null character. - - **Example**:: - - auto out = std::vector(); - fmt::format_to(std::back_inserter(out), "{}", 42); - \endrst - */ -template ::value)> -FMT_INLINE auto format_to(OutputIt out, format_string fmt, T&&... args) - -> OutputIt { - return vformat_to(out, fmt, fmt::make_format_args(args...)); -} - -template struct format_to_n_result { - /** Iterator past the end of the output range. */ - OutputIt out; - /** Total (not truncated) output size. */ - size_t size; -}; - -template ::value)> -auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args) - -> format_to_n_result { - using traits = detail::fixed_buffer_traits; - auto buf = detail::iterator_buffer(out, n); - detail::vformat_to(buf, fmt, args, {}); - return {buf.out(), buf.count()}; -} - -/** - \rst - Formats ``args`` according to specifications in ``fmt``, writes up to ``n`` - characters of the result to the output iterator ``out`` and returns the total - (not truncated) output size and the iterator past the end of the output range. - `format_to_n` does not append a terminating null character. - \endrst - */ -template ::value)> -FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string fmt, - T&&... args) -> format_to_n_result { - return vformat_to_n(out, n, fmt, fmt::make_format_args(args...)); -} - -/** Returns the number of chars in the output of ``format(fmt, args...)``. */ -template -FMT_NODISCARD FMT_INLINE auto formatted_size(format_string fmt, - T&&... args) -> size_t { - auto buf = detail::counting_buffer<>(); - detail::vformat_to(buf, fmt, fmt::make_format_args(args...), {}); - return buf.count(); -} - -FMT_API void vprint(string_view fmt, format_args args); -FMT_API void vprint(std::FILE* f, string_view fmt, format_args args); - -/** - \rst - Formats ``args`` according to specifications in ``fmt`` and writes the output - to ``stdout``. - - **Example**:: - - fmt::print("Elapsed time: {0:.2f} seconds", 1.23); - \endrst - */ -template -FMT_INLINE void print(format_string fmt, T&&... args) { - const auto& vargs = fmt::make_format_args(args...); - return detail::is_utf8() ? vprint(fmt, vargs) - : detail::vprint_mojibake(stdout, fmt, vargs); -} - -/** - \rst - Formats ``args`` according to specifications in ``fmt`` and writes the - output to the file ``f``. - - **Example**:: - - fmt::print(stderr, "Don't {}!", "panic"); - \endrst - */ -template -FMT_INLINE void print(std::FILE* f, format_string fmt, T&&... args) { - const auto& vargs = fmt::make_format_args(args...); - return detail::is_utf8() ? vprint(f, fmt, vargs) - : detail::vprint_mojibake(f, fmt, vargs); -} - -/** - Formats ``args`` according to specifications in ``fmt`` and writes the - output to the file ``f`` followed by a newline. - */ -template -FMT_INLINE void println(std::FILE* f, format_string fmt, T&&... args) { - return fmt::print(f, "{}\n", fmt::format(fmt, std::forward(args)...)); -} - -/** - Formats ``args`` according to specifications in ``fmt`` and writes the output - to ``stdout`` followed by a newline. - */ -template -FMT_INLINE void println(format_string fmt, T&&... args) { - return fmt::println(stdout, fmt, std::forward(args)...); -} - -FMT_END_EXPORT -FMT_GCC_PRAGMA("GCC pop_options") -FMT_END_NAMESPACE - -#ifdef FMT_HEADER_ONLY -# include "format.h" -#endif -#endif // FMT_CORE_H_ +#include "format.h" diff --git a/third-party/fmt/include/fmt/format-inl.h b/third-party/fmt/include/fmt/format-inl.h index efac5d1f88..a5b79dbe49 100644 --- a/third-party/fmt/include/fmt/format-inl.h +++ b/third-party/fmt/include/fmt/format-inl.h @@ -8,36 +8,36 @@ #ifndef FMT_FORMAT_INL_H_ #define FMT_FORMAT_INL_H_ -#include -#include // errno -#include -#include -#include - -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR -# include +#ifndef FMT_MODULE +# include +# include // errno +# include +# include +# include #endif -#if defined(_WIN32) && !defined(FMT_WINDOWS_NO_WCHAR) +#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) # include // _isatty #endif #include "format.h" +#if FMT_USE_LOCALE +# include +#endif + +#ifndef FMT_FUNC +# define FMT_FUNC +#endif + FMT_BEGIN_NAMESPACE namespace detail { FMT_FUNC void assert_fail(const char* file, int line, const char* message) { // Use unchecked std::fprintf to avoid triggering another assertion when - // writing to stderr fails - std::fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message); - // Chosen instead of std::abort to satisfy Clang in CUDA mode during device - // code pass. - std::terminate(); -} - -FMT_FUNC void throw_format_error(const char* message) { - FMT_THROW(format_error(message)); + // writing to stderr fails. + fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message); + abort(); } FMT_FUNC void format_error_code(detail::buffer& out, int error_code, @@ -56,89 +56,105 @@ FMT_FUNC void format_error_code(detail::buffer& out, int error_code, ++error_code_size; } error_code_size += detail::to_unsigned(detail::count_digits(abs_value)); - auto it = buffer_appender(out); + auto it = appender(out); if (message.size() <= inline_buffer_size - error_code_size) fmt::format_to(it, FMT_STRING("{}{}"), message, SEP); fmt::format_to(it, FMT_STRING("{}{}"), ERROR_STR, error_code); FMT_ASSERT(out.size() <= inline_buffer_size, ""); } -FMT_FUNC void report_error(format_func func, int error_code, - const char* message) noexcept { +FMT_FUNC void do_report_error(format_func func, int error_code, + const char* message) noexcept { memory_buffer full_message; func(full_message, error_code, message); - // Don't use fwrite_fully because the latter may throw. + // Don't use fwrite_all because the latter may throw. if (std::fwrite(full_message.data(), full_message.size(), 1, stderr) > 0) std::fputc('\n', stderr); } // A wrapper around fwrite that throws on error. -inline void fwrite_fully(const void* ptr, size_t count, FILE* stream) { +inline void fwrite_all(const void* ptr, size_t count, FILE* stream) { size_t written = std::fwrite(ptr, 1, count, stream); if (written < count) FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); } -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +#if FMT_USE_LOCALE +using std::locale; +using std::numpunct; +using std::use_facet; + template locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { - static_assert(std::is_same::value, ""); + static_assert(std::is_same::value, ""); } +#else +struct locale {}; +template struct numpunct { + auto grouping() const -> std::string { return "\03"; } + auto thousands_sep() const -> Char { return ','; } + auto decimal_point() const -> Char { return '.'; } +}; +template Facet use_facet(locale) { return {}; } +#endif // FMT_USE_LOCALE template auto locale_ref::get() const -> Locale { - static_assert(std::is_same::value, ""); - return locale_ ? *static_cast(locale_) : std::locale(); + static_assert(std::is_same::value, ""); +#if FMT_USE_LOCALE + if (locale_) return *static_cast(locale_); +#endif + return locale(); } template FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result { - auto& facet = std::use_facet>(loc.get()); + auto&& facet = use_facet>(loc.get()); auto grouping = facet.grouping(); auto thousands_sep = grouping.empty() ? Char() : facet.thousands_sep(); return {std::move(grouping), thousands_sep}; } template FMT_FUNC auto decimal_point_impl(locale_ref loc) -> Char { - return std::use_facet>(loc.get()) - .decimal_point(); + return use_facet>(loc.get()).decimal_point(); } -#else -template -FMT_FUNC auto thousands_sep_impl(locale_ref) -> thousands_sep_result { - return {"\03", FMT_STATIC_THOUSANDS_SEPARATOR}; -} -template FMT_FUNC Char decimal_point_impl(locale_ref) { - return '.'; -} -#endif +#if FMT_USE_LOCALE FMT_FUNC auto write_loc(appender out, loc_value value, - const format_specs<>& specs, locale_ref loc) -> bool { -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR + const format_specs& specs, locale_ref loc) -> bool { auto locale = loc.get(); // We cannot use the num_put facet because it may produce output in // a wrong encoding. using facet = format_facet; if (std::has_facet(locale)) - return std::use_facet(locale).put(out, value, specs); + return use_facet(locale).put(out, value, specs); return facet(locale).put(out, value, specs); -#endif - return false; } +#endif } // namespace detail +FMT_FUNC void report_error(const char* message) { +#if FMT_USE_EXCEPTIONS + // Use FMT_THROW instead of throw to avoid bogus unreachable code warnings + // from MSVC. + FMT_THROW(format_error(message)); +#else + fputs(message, stderr); + abort(); +#endif +} + template typename Locale::id format_facet::id; -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR template format_facet::format_facet(Locale& loc) { - auto& numpunct = std::use_facet>(loc); - grouping_ = numpunct.grouping(); - if (!grouping_.empty()) separator_ = std::string(1, numpunct.thousands_sep()); + auto& np = detail::use_facet>(loc); + grouping_ = np.grouping(); + if (!grouping_.empty()) separator_ = std::string(1, np.thousands_sep()); } +#if FMT_USE_LOCALE template <> FMT_API FMT_FUNC auto format_facet::do_put( - appender out, loc_value val, const format_specs<>& specs) const -> bool { + appender out, loc_value val, const format_specs& specs) const -> bool { return val.visit( detail::loc_writer<>{out, specs, separator_, grouping_, decimal_point_}); } @@ -1411,7 +1427,7 @@ FMT_FUNC void format_system_error(detail::buffer& out, int error_code, const char* message) noexcept { FMT_TRY { auto ec = std::error_code(error_code, std::generic_category()); - write(std::back_inserter(out), std::system_error(ec, message).what()); + detail::write(appender(out), std::system_error(ec, message).what()); return; } FMT_CATCH(...) {} @@ -1420,7 +1436,7 @@ FMT_FUNC void format_system_error(detail::buffer& out, int error_code, FMT_FUNC void report_system_error(int error_code, const char* message) noexcept { - report_error(format_system_error, error_code, message); + do_report_error(format_system_error, error_code, message); } FMT_FUNC auto vformat(string_view fmt, format_args args) -> std::string { @@ -1432,9 +1448,252 @@ FMT_FUNC auto vformat(string_view fmt, format_args args) -> std::string { } namespace detail { -#if !defined(_WIN32) || defined(FMT_WINDOWS_NO_WCHAR) + +FMT_FUNC void vformat_to(buffer& buf, string_view fmt, format_args args, + locale_ref loc) { + auto out = appender(buf); + if (fmt.size() == 2 && equal2(fmt.data(), "{}")) + return args.get(0).visit(default_arg_formatter{out}); + parse_format_string( + fmt, format_handler{parse_context(fmt), {out, args, loc}}); +} + +template struct span { + T* data; + size_t size; +}; + +template auto flockfile(F* f) -> decltype(_lock_file(f)) { + _lock_file(f); +} +template auto funlockfile(F* f) -> decltype(_unlock_file(f)) { + _unlock_file(f); +} + +#ifndef getc_unlocked +template auto getc_unlocked(F* f) -> decltype(_fgetc_nolock(f)) { + return _fgetc_nolock(f); +} +#endif + +template +struct has_flockfile : std::false_type {}; + +template +struct has_flockfile()))>> + : std::true_type {}; + +// A FILE wrapper. F is FILE defined as a template parameter to make system API +// detection work. +template class file_base { + public: + F* file_; + + public: + file_base(F* file) : file_(file) {} + operator F*() const { return file_; } + + // Reads a code unit from the stream. + auto get() -> int { + int result = getc_unlocked(file_); + if (result == EOF && ferror(file_) != 0) + FMT_THROW(system_error(errno, FMT_STRING("getc failed"))); + return result; + } + + // Puts the code unit back into the stream buffer. + void unget(char c) { + if (ungetc(c, file_) == EOF) + FMT_THROW(system_error(errno, FMT_STRING("ungetc failed"))); + } + + void flush() { fflush(this->file_); } +}; + +// A FILE wrapper for glibc. +template class glibc_file : public file_base { + private: + enum { + line_buffered = 0x200, // _IO_LINE_BUF + unbuffered = 2 // _IO_UNBUFFERED + }; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { + return (this->file_->_flags & unbuffered) == 0; + } + + void init_buffer() { + if (this->file_->_IO_write_ptr) return; + // Force buffer initialization by placing and removing a char in a buffer. + assume(this->file_->_IO_write_ptr >= this->file_->_IO_write_end); + putc_unlocked(0, this->file_); + --this->file_->_IO_write_ptr; + } + + // Returns the file's read buffer. + auto get_read_buffer() const -> span { + auto ptr = this->file_->_IO_read_ptr; + return {ptr, to_unsigned(this->file_->_IO_read_end - ptr)}; + } + + // Returns the file's write buffer. + auto get_write_buffer() const -> span { + auto ptr = this->file_->_IO_write_ptr; + return {ptr, to_unsigned(this->file_->_IO_buf_end - ptr)}; + } + + void advance_write_buffer(size_t size) { this->file_->_IO_write_ptr += size; } + + bool needs_flush() const { + if ((this->file_->_flags & line_buffered) == 0) return false; + char* end = this->file_->_IO_write_end; + return memchr(end, '\n', to_unsigned(this->file_->_IO_write_ptr - end)); + } + + void flush() { fflush_unlocked(this->file_); } +}; + +// A FILE wrapper for Apple's libc. +template class apple_file : public file_base { + private: + enum { + line_buffered = 1, // __SNBF + unbuffered = 2 // __SLBF + }; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { + return (this->file_->_flags & unbuffered) == 0; + } + + void init_buffer() { + if (this->file_->_p) return; + // Force buffer initialization by placing and removing a char in a buffer. + putc_unlocked(0, this->file_); + --this->file_->_p; + ++this->file_->_w; + } + + auto get_read_buffer() const -> span { + return {reinterpret_cast(this->file_->_p), + to_unsigned(this->file_->_r)}; + } + + auto get_write_buffer() const -> span { + return {reinterpret_cast(this->file_->_p), + to_unsigned(this->file_->_bf._base + this->file_->_bf._size - + this->file_->_p)}; + } + + void advance_write_buffer(size_t size) { + this->file_->_p += size; + this->file_->_w -= size; + } + + bool needs_flush() const { + if ((this->file_->_flags & line_buffered) == 0) return false; + return memchr(this->file_->_p + this->file_->_w, '\n', + to_unsigned(-this->file_->_w)); + } +}; + +// A fallback FILE wrapper. +template class fallback_file : public file_base { + private: + char next_; // The next unconsumed character in the buffer. + bool has_next_ = false; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { return false; } + auto needs_flush() const -> bool { return false; } + void init_buffer() {} + + auto get_read_buffer() const -> span { + return {&next_, has_next_ ? 1u : 0u}; + } + + auto get_write_buffer() const -> span { return {nullptr, 0}; } + + void advance_write_buffer(size_t) {} + + auto get() -> int { + has_next_ = false; + return file_base::get(); + } + + void unget(char c) { + file_base::unget(c); + next_ = c; + has_next_ = true; + } +}; + +#ifndef FMT_USE_FALLBACK_FILE +# define FMT_USE_FALLBACK_FILE 0 +#endif + +template +auto get_file(F* f, int) -> apple_file { + return f; +} +template +inline auto get_file(F* f, int) -> glibc_file { + return f; +} + +inline auto get_file(FILE* f, ...) -> fallback_file { return f; } + +using file_ref = decltype(get_file(static_cast(nullptr), 0)); + +template +class file_print_buffer : public buffer { + public: + explicit file_print_buffer(F*) : buffer(nullptr, size_t()) {} +}; + +template +class file_print_buffer::value>> + : public buffer { + private: + file_ref file_; + + static void grow(buffer& base, size_t) { + auto& self = static_cast(base); + self.file_.advance_write_buffer(self.size()); + if (self.file_.get_write_buffer().size == 0) self.file_.flush(); + auto buf = self.file_.get_write_buffer(); + FMT_ASSERT(buf.size > 0, ""); + self.set(buf.data, buf.size); + self.clear(); + } + + public: + explicit file_print_buffer(F* f) : buffer(grow, size_t()), file_(f) { + flockfile(f); + file_.init_buffer(); + auto buf = file_.get_write_buffer(); + set(buf.data, buf.size); + } + ~file_print_buffer() { + file_.advance_write_buffer(size()); + bool flush = file_.needs_flush(); + F* f = file_; // Make funlockfile depend on the template parameter F + funlockfile(f); // for the system API detection to work. + if (flush) fflush(file_); + } +}; + +#if !defined(_WIN32) || defined(FMT_USE_WRITE_CONSOLE) FMT_FUNC auto write_console(int, string_view) -> bool { return false; } -FMT_FUNC auto write_console(std::FILE*, string_view) -> bool { return false; } #else using dword = conditional_t; extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( // @@ -1445,39 +1704,51 @@ FMT_FUNC bool write_console(int fd, string_view text) { return WriteConsoleW(reinterpret_cast(_get_osfhandle(fd)), u16.c_str(), static_cast(u16.size()), nullptr, nullptr) != 0; } - -FMT_FUNC auto write_console(std::FILE* f, string_view text) -> bool { - return write_console(_fileno(f), text); -} #endif #ifdef _WIN32 // Print assuming legacy (non-Unicode) encoding. -FMT_FUNC void vprint_mojibake(std::FILE* f, string_view fmt, format_args args) { +FMT_FUNC void vprint_mojibake(std::FILE* f, string_view fmt, format_args args, + bool newline) { auto buffer = memory_buffer(); detail::vformat_to(buffer, fmt, args); - fwrite_fully(buffer.data(), buffer.size(), f); + if (newline) buffer.push_back('\n'); + fwrite_all(buffer.data(), buffer.size(), f); } #endif FMT_FUNC void print(std::FILE* f, string_view text) { -#ifdef _WIN32 +#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) int fd = _fileno(f); if (_isatty(fd)) { std::fflush(f); if (write_console(fd, text)) return; } #endif - fwrite_fully(text.data(), text.size(), f); + fwrite_all(text.data(), text.size(), f); } } // namespace detail -FMT_FUNC void vprint(std::FILE* f, string_view fmt, format_args args) { +FMT_FUNC void vprint_buffered(std::FILE* f, string_view fmt, format_args args) { auto buffer = memory_buffer(); detail::vformat_to(buffer, fmt, args); detail::print(f, {buffer.data(), buffer.size()}); } +FMT_FUNC void vprint(std::FILE* f, string_view fmt, format_args args) { + if (!detail::file_ref(f).is_buffered() || !detail::has_flockfile<>()) + return vprint_buffered(f, fmt, args); + auto&& buffer = detail::file_print_buffer<>(f); + return detail::vformat_to(buffer, fmt, args); +} + +FMT_FUNC void vprintln(std::FILE* f, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + buffer.push_back('\n'); + detail::print(f, {buffer.data(), buffer.size()}); +} + FMT_FUNC void vprint(string_view fmt, format_args args) { vprint(stdout, fmt, args); } diff --git a/third-party/fmt/include/fmt/format.h b/third-party/fmt/include/fmt/format.h index 7637c8a0d0..287e71631e 100644 --- a/third-party/fmt/include/fmt/format.h +++ b/third-party/fmt/include/fmt/format.h @@ -33,20 +33,59 @@ #ifndef FMT_FORMAT_H_ #define FMT_FORMAT_H_ -#include // std::signbit -#include // uint32_t -#include // std::memcpy -#include // std::initializer_list -#include // std::numeric_limits -#include // std::uninitialized_copy -#include // std::runtime_error -#include // std::system_error - -#ifdef __cpp_lib_bit_cast -# include // std::bit_cast +#ifndef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +# define _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +# define FMT_REMOVE_TRANSITIVE_INCLUDES #endif -#include "core.h" +#include "base.h" + +#ifndef FMT_MODULE +# include // std::signbit +# include // std::byte +# include // uint32_t +# include // std::memcpy +# include // std::numeric_limits +# include // std::bad_alloc +# if defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI) +// Workaround for pre gcc 5 libstdc++. +# include // std::allocator_traits +# endif +# include // std::runtime_error +# include // std::string +# include // std::system_error + +// Check FMT_CPLUSPLUS to avoid a warning in MSVC. +# if FMT_HAS_INCLUDE() && FMT_CPLUSPLUS > 201703L +# include // std::bit_cast +# endif + +// libc++ supports string_view in pre-c++17. +# if FMT_HAS_INCLUDE() && \ + (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION)) +# include +# define FMT_USE_STRING_VIEW +# endif + +# if FMT_MSC_VERSION +# include // _BitScanReverse[64], _umul128 +# endif +#endif // FMT_MODULE + +#if defined(FMT_USE_NONTYPE_TEMPLATE_ARGS) +// Use the provided definition. +#elif defined(__NVCOMPILER) +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 +#elif FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#elif defined(__cpp_nontype_template_args) && \ + __cpp_nontype_template_args >= 201911L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#elif FMT_CLANG_VERSION >= 1200 && FMT_CPLUSPLUS >= 202002L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#else +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 +#endif #if defined __cpp_inline_variables && __cpp_inline_variables >= 201606L # define FMT_INLINE_VARIABLE inline @@ -54,43 +93,15 @@ # define FMT_INLINE_VARIABLE #endif -#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough) -# define FMT_FALLTHROUGH [[fallthrough]] -#elif defined(__clang__) -# define FMT_FALLTHROUGH [[clang::fallthrough]] -#elif FMT_GCC_VERSION >= 700 && \ - (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520) -# define FMT_FALLTHROUGH [[gnu::fallthrough]] +// Check if RTTI is disabled. +#ifdef FMT_USE_RTTI +// Use the provided definition. +#elif defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || defined(_CPPRTTI) || \ + defined(__INTEL_RTTI__) || defined(__RTTI) +// __RTTI is for EDG compilers. _CPPRTTI is for MSVC. +# define FMT_USE_RTTI 1 #else -# define FMT_FALLTHROUGH -#endif - -#ifndef FMT_DEPRECATED -# if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VERSION >= 1900 -# define FMT_DEPRECATED [[deprecated]] -# else -# if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__) -# define FMT_DEPRECATED __attribute__((deprecated)) -# elif FMT_MSC_VERSION -# define FMT_DEPRECATED __declspec(deprecated) -# else -# define FMT_DEPRECATED /* deprecated */ -# endif -# endif -#endif - -#ifndef FMT_NO_UNIQUE_ADDRESS -# if FMT_CPLUSPLUS >= 202002L -# if FMT_HAS_CPP_ATTRIBUTE(no_unique_address) -# define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]] -// VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485) -# elif (FMT_MSC_VERSION >= 1929) && !FMT_CLANG_VERSION -# define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]] -# endif -# endif -#endif -#ifndef FMT_NO_UNIQUE_ADDRESS -# define FMT_NO_UNIQUE_ADDRESS +# define FMT_USE_RTTI 0 #endif // Visibility when compiled as a shared library/object. @@ -100,20 +111,25 @@ # define FMT_SO_VISIBILITY(value) #endif -#ifdef __has_builtin -# define FMT_HAS_BUILTIN(x) __has_builtin(x) -#else -# define FMT_HAS_BUILTIN(x) 0 -#endif - #if FMT_GCC_VERSION || FMT_CLANG_VERSION # define FMT_NOINLINE __attribute__((noinline)) #else # define FMT_NOINLINE #endif +namespace std { +template struct iterator_traits> { + using iterator_category = output_iterator_tag; + using value_type = T; + using difference_type = + decltype(static_cast(nullptr) - static_cast(nullptr)); + using pointer = void; + using reference = void; +}; +} // namespace std + #ifndef FMT_THROW -# if FMT_EXCEPTIONS +# if FMT_USE_EXCEPTIONS # if FMT_MSC_VERSION || defined(__NVCC__) FMT_BEGIN_NAMESPACE namespace detail { @@ -132,38 +148,8 @@ FMT_END_NAMESPACE # else # define FMT_THROW(x) \ ::fmt::detail::assert_fail(__FILE__, __LINE__, (x).what()) -# endif -#endif - -#if FMT_EXCEPTIONS -# define FMT_TRY try -# define FMT_CATCH(x) catch (x) -#else -# define FMT_TRY if (true) -# define FMT_CATCH(x) if (false) -#endif - -#ifndef FMT_MAYBE_UNUSED -# if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused) -# define FMT_MAYBE_UNUSED [[maybe_unused]] -# else -# define FMT_MAYBE_UNUSED -# endif -#endif - -#ifndef FMT_USE_USER_DEFINED_LITERALS -// EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs. -// -// GCC before 4.9 requires a space in `operator"" _a` which is invalid in later -// compiler versions. -# if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 409 || \ - FMT_MSC_VERSION >= 1900) && \ - (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480) -# define FMT_USE_USER_DEFINED_LITERALS 1 -# else -# define FMT_USE_USER_DEFINED_LITERALS 0 -# endif -#endif +# endif // FMT_USE_EXCEPTIONS +#endif // FMT_THROW // Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of // integer formatter template instantiations to just one by only using the @@ -173,7 +159,15 @@ FMT_END_NAMESPACE # define FMT_REDUCE_INT_INSTANTIATIONS 0 #endif -// __builtin_clz is broken in clang with Microsoft CodeGen: +FMT_BEGIN_NAMESPACE + +template +struct is_contiguous> + : std::true_type {}; + +namespace detail { + +// __builtin_clz is broken in clang with Microsoft codegen: // https://github.com/fmtlib/fmt/issues/519. #if !FMT_MSC_VERSION # if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION @@ -184,53 +178,30 @@ FMT_END_NAMESPACE # endif #endif -// __builtin_ctz is broken in Intel Compiler Classic on Windows: -// https://github.com/fmtlib/fmt/issues/2510. -#ifndef __ICL -# if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION || \ - defined(__NVCOMPILER) -# define FMT_BUILTIN_CTZ(n) __builtin_ctz(n) -# endif -# if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || \ - FMT_ICC_VERSION || defined(__NVCOMPILER) -# define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n) -# endif -#endif - -#if FMT_MSC_VERSION -# include // _BitScanReverse[64], _BitScanForward[64], _umul128 -#endif - -// Some compilers masquerade as both MSVC and GCC-likes or otherwise support +// Some compilers masquerade as both MSVC and GCC but 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_VERSION && !defined(FMT_BUILTIN_CLZLL) && \ - !defined(FMT_BUILTIN_CTZLL) -FMT_BEGIN_NAMESPACE -namespace detail { +#if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) // Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. -# if !defined(__clang__) -# pragma intrinsic(_BitScanForward) +# ifndef __clang__ # pragma intrinsic(_BitScanReverse) -# if defined(_WIN64) -# pragma intrinsic(_BitScanForward64) +# ifdef _WIN64 # pragma intrinsic(_BitScanReverse64) # endif # endif inline auto clz(uint32_t x) -> int { + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. unsigned long r = 0; _BitScanReverse(&r, x); - FMT_ASSERT(x != 0, ""); - // Static analysis complains about using uninitialized data - // "r", but the only way that can happen is if "x" is 0, - // which the callers guarantee to not happen. - FMT_MSC_WARNING(suppress : 6102) return 31 ^ static_cast(r); } # define FMT_BUILTIN_CLZ(n) detail::clz(n) inline auto clzll(uint64_t x) -> int { + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. unsigned long r = 0; # ifdef _WIN64 _BitScanReverse64(&r, x); @@ -241,43 +212,10 @@ inline auto clzll(uint64_t x) -> int { // Scan the low 32 bits. _BitScanReverse(&r, static_cast(x)); # endif - FMT_ASSERT(x != 0, ""); - FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. return 63 ^ static_cast(r); } # define FMT_BUILTIN_CLZLL(n) detail::clzll(n) - -inline auto ctz(uint32_t x) -> int { - unsigned long r = 0; - _BitScanForward(&r, x); - FMT_ASSERT(x != 0, ""); - FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. - return static_cast(r); -} -# define FMT_BUILTIN_CTZ(n) detail::ctz(n) - -inline auto ctzll(uint64_t x) -> int { - unsigned long r = 0; - FMT_ASSERT(x != 0, ""); - FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. -# ifdef _WIN64 - _BitScanForward64(&r, x); -# else - // Scan the low 32 bits. - if (_BitScanForward(&r, static_cast(x))) return static_cast(r); - // Scan the high 32 bits. - _BitScanForward(&r, static_cast(x >> 32)); - r += 32; -# endif - return static_cast(r); -} -# define FMT_BUILTIN_CTZLL(n) detail::ctzll(n) -} // namespace detail -FMT_END_NAMESPACE -#endif - -FMT_BEGIN_NAMESPACE -namespace detail { +#endif // FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) { ignore_unused(condition); @@ -286,16 +224,23 @@ FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) { #endif } -template struct string_literal { - static constexpr CharT value[sizeof...(C)] = {C...}; - constexpr operator basic_string_view() const { +#if defined(FMT_USE_STRING_VIEW) +template using std_string_view = std::basic_string_view; +#else +template struct std_string_view { + operator basic_string_view() const; +}; +#endif + +template struct string_literal { + static constexpr Char value[sizeof...(C)] = {C...}; + constexpr operator basic_string_view() const { return {value, sizeof...(C)}; } }; - #if FMT_CPLUSPLUS < 201703L -template -constexpr CharT string_literal::value[sizeof...(C)]; +template +constexpr Char string_literal::value[sizeof...(C)]; #endif // Implementation of std::bit_cast for pre-C++20. @@ -367,13 +312,14 @@ class uint128_fallback { -> uint128_fallback { return {~n.hi_, ~n.lo_}; } - friend auto operator+(const uint128_fallback& lhs, - const uint128_fallback& rhs) -> uint128_fallback { + friend FMT_CONSTEXPR auto operator+(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { auto result = uint128_fallback(lhs); result += rhs; return result; } - friend auto operator*(const uint128_fallback& lhs, uint32_t rhs) + friend FMT_CONSTEXPR auto operator*(const uint128_fallback& lhs, uint32_t rhs) -> uint128_fallback { FMT_ASSERT(lhs.hi_ == 0, ""); uint64_t hi = (lhs.lo_ >> 32) * rhs; @@ -381,7 +327,7 @@ class uint128_fallback { uint64_t new_lo = (hi << 32) + lo; return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo}; } - friend auto operator-(const uint128_fallback& lhs, uint64_t rhs) + friend constexpr auto operator-(const uint128_fallback& lhs, uint64_t rhs) -> uint128_fallback { return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs}; } @@ -454,23 +400,24 @@ template constexpr auto num_bits() -> int { } // std::numeric_limits::digits may return 0 for 128-bit ints. template <> constexpr auto num_bits() -> int { return 128; } -template <> constexpr auto num_bits() -> int { return 128; } +template <> constexpr auto num_bits() -> int { return 128; } +template <> constexpr auto num_bits() -> int { return 128; } // A heterogeneous bit_cast used for converting 96-bit long double to uint128_t // and 128-bit pointers to uint128_fallback. template sizeof(From))> inline auto bit_cast(const From& from) -> To { - constexpr auto size = static_cast(sizeof(From) / sizeof(unsigned)); + constexpr auto size = static_cast(sizeof(From) / sizeof(unsigned short)); struct data_t { - unsigned value[static_cast(size)]; + unsigned short value[static_cast(size)]; } data = bit_cast(from); auto result = To(); if (const_check(is_big_endian())) { for (int i = 0; i < size; ++i) - result = (result << num_bits()) | data.value[i]; + result = (result << num_bits()) | data.value[i]; } else { for (int i = size - 1; i >= 0; --i) - result = (result << num_bits()) | data.value[i]; + result = (result << num_bits()) | data.value[i]; } return result; } @@ -506,38 +453,25 @@ FMT_INLINE void assume(bool condition) { #endif } -// An approximation of iterator_t for pre-C++20 systems. -template -using iterator_t = decltype(std::begin(std::declval())); -template using sentinel_t = decltype(std::end(std::declval())); - -// A workaround for std::string not having mutable data() until C++17. -template -inline auto get_data(std::basic_string& s) -> Char* { - return &s[0]; -} -template -inline auto get_data(Container& c) -> typename Container::value_type* { - return c.data(); -} - // Attempts to reserve space for n extra characters in the output range. // Returns a pointer to the reserved range or a reference to it. -template ::value)> +template ::value&& + is_contiguous::value)> #if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION __attribute__((no_sanitize("undefined"))) #endif -inline auto -reserve(std::back_insert_iterator it, size_t n) -> - typename Container::value_type* { - Container& c = get_container(it); +FMT_CONSTEXPR20 inline auto +reserve(OutputIt it, size_t n) -> typename OutputIt::value_type* { + auto& c = get_container(it); size_t size = c.size(); c.resize(size + n); - return get_data(c) + size; + return &c[size]; } template -inline auto reserve(buffer_appender it, size_t n) -> buffer_appender { +FMT_CONSTEXPR20 inline auto reserve(basic_appender it, size_t n) + -> basic_appender { buffer& buf = get_container(it); buf.try_reserve(buf.size() + n); return it; @@ -556,18 +490,22 @@ template constexpr auto to_pointer(OutputIt, size_t) -> T* { return nullptr; } -template auto to_pointer(buffer_appender it, size_t n) -> T* { +template +FMT_CONSTEXPR20 auto to_pointer(basic_appender it, size_t n) -> T* { buffer& buf = get_container(it); + buf.try_reserve(buf.size() + n); auto size = buf.size(); if (buf.capacity() < size + n) return nullptr; buf.try_resize(size + n); return buf.data() + size; } -template ::value)> -inline auto base_iterator(std::back_insert_iterator it, - typename Container::value_type*) - -> std::back_insert_iterator { +template ::value&& + is_contiguous::value)> +inline auto base_iterator(OutputIt it, + typename OutputIt::container_type::value_type*) + -> OutputIt { return it; } @@ -586,23 +524,15 @@ FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value) } template FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* { - if (is_constant_evaluated()) { - return fill_n(out, count, value); - } + if (is_constant_evaluated()) return fill_n(out, count, value); std::memset(out, value, to_unsigned(count)); return out + count; } -#ifdef __cpp_char8_t -using char8_type = char8_t; -#else -enum char8_type : unsigned char {}; -#endif - template -FMT_CONSTEXPR FMT_NOINLINE auto copy_str_noinline(InputIt begin, InputIt end, - OutputIt out) -> OutputIt { - return copy_str(begin, end, out); +FMT_CONSTEXPR FMT_NOINLINE auto copy_noinline(InputIt begin, InputIt end, + OutputIt out) -> OutputIt { + return copy(begin, end, out); } // A public domain branchless UTF-8 decoder by Christopher Wellons: @@ -673,6 +603,7 @@ FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) { string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr))); return result ? (error ? buf_ptr + 1 : end) : nullptr; }; + auto p = s.data(); const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars. if (s.size() >= block_size) { @@ -681,17 +612,20 @@ FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) { if (!p) return; } } - if (auto num_chars_left = s.data() + s.size() - p) { - char buf[2 * block_size - 1] = {}; - copy_str(p, p + num_chars_left, buf); - const char* buf_ptr = buf; - do { - auto end = decode(buf_ptr, p); - if (!end) return; - p += end - buf_ptr; - buf_ptr = end; - } while (buf_ptr - buf < num_chars_left); - } + auto num_chars_left = to_unsigned(s.data() + s.size() - p); + if (num_chars_left == 0) return; + + // Suppress bogus -Wstringop-overflow. + if (FMT_GCC_VERSION) num_chars_left &= 3; + char buf[2 * block_size - 1] = {}; + copy(p, p + num_chars_left, buf); + const char* buf_ptr = buf; + do { + auto end = decode(buf_ptr, p); + if (!end) return; + p += end - buf_ptr; + buf_ptr = end; + } while (buf_ptr < buf + num_chars_left); } template @@ -706,7 +640,7 @@ FMT_CONSTEXPR inline auto compute_width(string_view s) -> size_t { struct count_code_points { size_t* count; FMT_CONSTEXPR auto operator()(uint32_t cp, string_view) const -> bool { - *count += detail::to_unsigned( + *count += to_unsigned( 1 + (cp >= 0x1100 && (cp <= 0x115f || // Hangul Jamo init. consonants @@ -734,15 +668,9 @@ FMT_CONSTEXPR inline auto compute_width(string_view s) -> size_t { return num_code_points; } -inline auto compute_width(basic_string_view s) -> size_t { - return compute_width( - string_view(reinterpret_cast(s.data()), s.size())); -} - template inline auto code_point_index(basic_string_view s, size_t n) -> size_t { - size_t size = s.size(); - return n < size ? n : size; + return min_of(n, s.size()); } // Calculates the index of the nth code point in a UTF-8 string. @@ -760,12 +688,6 @@ inline auto code_point_index(string_view s, size_t n) -> size_t { return result; } -inline auto code_point_index(basic_string_view s, size_t n) - -> size_t { - return code_point_index( - string_view(reinterpret_cast(s.data()), s.size()), n); -} - template struct is_integral : std::is_integral {}; template <> struct is_integral : std::true_type {}; template <> struct is_integral : std::true_type {}; @@ -781,38 +703,22 @@ using is_integer = !std::is_same::value && !std::is_same::value>; -#ifndef FMT_USE_FLOAT -# define FMT_USE_FLOAT 1 +#if defined(FMT_USE_FLOAT128) +// Use the provided definition. +#elif FMT_CLANG_VERSION && FMT_HAS_INCLUDE() +# define FMT_USE_FLOAT128 1 +#elif FMT_GCC_VERSION && defined(_GLIBCXX_USE_FLOAT128) && \ + !defined(__STRICT_ANSI__) +# define FMT_USE_FLOAT128 1 +#else +# define FMT_USE_FLOAT128 0 #endif -#ifndef FMT_USE_DOUBLE -# define FMT_USE_DOUBLE 1 -#endif -#ifndef FMT_USE_LONG_DOUBLE -# define FMT_USE_LONG_DOUBLE 1 -#endif - -#ifndef FMT_USE_FLOAT128 -# ifdef __clang__ -// Clang emulates GCC, so it has to appear early. -# if FMT_HAS_INCLUDE() -# define FMT_USE_FLOAT128 1 -# endif -# elif defined(__GNUC__) -// GNU C++: -# if defined(_GLIBCXX_USE_FLOAT128) && !defined(__STRICT_ANSI__) -# define FMT_USE_FLOAT128 1 -# endif -# endif -# ifndef FMT_USE_FLOAT128 -# define FMT_USE_FLOAT128 0 -# endif -#endif - #if FMT_USE_FLOAT128 using float128 = __float128; #else -using float128 = void; +struct float128 {}; #endif + template using is_float128 = std::is_same; template @@ -831,24 +737,21 @@ using is_double_double = bool_constant::digits == 106>; # define FMT_USE_FULL_CACHE_DRAGONBOX 0 #endif -template -template -void buffer::append(const U* begin, const U* end) { - while (begin != end) { - auto count = to_unsigned(end - begin); - try_reserve(size_ + count); - auto free_cap = capacity_ - size_; - if (free_cap < count) count = free_cap; - std::uninitialized_copy_n(begin, count, ptr_ + size_); - size_ += count; - begin += count; - } -} +// An allocator that uses malloc/free to allow removing dependency on the C++ +// standard libary runtime. +template struct allocator { + using value_type = T; + + T* allocate(size_t n) { + FMT_ASSERT(n <= max_value() / sizeof(T), ""); + T* p = static_cast(malloc(n * sizeof(T))); + if (!p) FMT_THROW(std::bad_alloc()); + return p; + } + + void deallocate(T* p, size_t) { free(p); } +}; -template -struct is_locale : std::false_type {}; -template -struct is_locale> : std::true_type {}; } // namespace detail FMT_BEGIN_EXPORT @@ -858,29 +761,21 @@ FMT_BEGIN_EXPORT enum { inline_buffer_size = 500 }; /** - \rst - A dynamically growing memory buffer for trivially copyable/constructible types - with the first ``SIZE`` elements stored in the object itself. - - You can use the ``memory_buffer`` type alias for ``char`` instead. - - **Example**:: - - auto out = fmt::memory_buffer(); - fmt::format_to(std::back_inserter(out), "The answer is {}.", 42); - - This will append the following output to the ``out`` object: - - .. code-block:: none - - The answer is 42. - - The output can be converted to an ``std::string`` with ``to_string(out)``. - \endrst + * A dynamically growing memory buffer for trivially copyable/constructible + * types with the first `SIZE` elements stored in the object itself. Most + * commonly used via the `memory_buffer` alias for `char`. + * + * **Example**: + * + * auto out = fmt::memory_buffer(); + * fmt::format_to(std::back_inserter(out), "The answer is {}.", 42); + * + * This will append "The answer is 42." to `out`. The buffer content can be + * converted to `std::string` with `to_string(out)`. */ template > -class basic_memory_buffer final : public detail::buffer { + typename Allocator = detail::allocator> +class basic_memory_buffer : public detail::buffer { private: T store_[SIZE]; @@ -893,37 +788,37 @@ class basic_memory_buffer final : public detail::buffer { if (data != store_) alloc_.deallocate(data, this->capacity()); } - protected: - FMT_CONSTEXPR20 void grow(size_t size) override { + static FMT_CONSTEXPR20 void grow(detail::buffer& buf, size_t size) { detail::abort_fuzzing_if(size > 5000); - const size_t max_size = std::allocator_traits::max_size(alloc_); - size_t old_capacity = this->capacity(); + auto& self = static_cast(buf); + const size_t max_size = + std::allocator_traits::max_size(self.alloc_); + size_t old_capacity = buf.capacity(); size_t new_capacity = old_capacity + old_capacity / 2; if (size > new_capacity) new_capacity = size; else if (new_capacity > max_size) - new_capacity = size > max_size ? size : max_size; - T* old_data = this->data(); - T* new_data = - std::allocator_traits::allocate(alloc_, new_capacity); + new_capacity = max_of(size, max_size); + T* old_data = buf.data(); + T* new_data = self.alloc_.allocate(new_capacity); // Suppress a bogus -Wstringop-overflow in gcc 13.1 (#3481). - detail::assume(this->size() <= new_capacity); + detail::assume(buf.size() <= new_capacity); // The following code doesn't throw, so the raw pointer above doesn't leak. - std::uninitialized_copy_n(old_data, this->size(), new_data); - this->set(new_data, new_capacity); + memcpy(new_data, old_data, buf.size() * sizeof(T)); + self.set(new_data, new_capacity); // deallocate must not throw according to the standard, but even if it does, // the buffer already uses the new storage and will deallocate it in // destructor. - if (old_data != store_) alloc_.deallocate(old_data, old_capacity); + if (old_data != self.store_) self.alloc_.deallocate(old_data, old_capacity); } public: using value_type = T; using const_reference = const T&; - FMT_CONSTEXPR20 explicit basic_memory_buffer( + FMT_CONSTEXPR explicit basic_memory_buffer( const Allocator& alloc = Allocator()) - : alloc_(alloc) { + : detail::buffer(grow), alloc_(alloc) { this->set(store_, SIZE); if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T()); } @@ -937,7 +832,7 @@ class basic_memory_buffer final : public detail::buffer { size_t size = other.size(), capacity = other.capacity(); if (data == other.store_) { this->set(store_, capacity); - detail::copy_str(other.store_, other.store_ + size, store_); + detail::copy(other.store_, other.store_ + size, store_); } else { this->set(data, capacity); // Set pointer to the inline array so that delete is not called @@ -949,21 +844,14 @@ class basic_memory_buffer final : public detail::buffer { } public: - /** - \rst - Constructs a :class:`fmt::basic_memory_buffer` object moving the content - of the other object to it. - \endrst - */ - FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept { + /// Constructs a `basic_memory_buffer` object moving the content of the other + /// object to it. + FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept + : detail::buffer(grow) { move(other); } - /** - \rst - Moves the content of the other ``basic_memory_buffer`` object to this one. - \endrst - */ + /// Moves the content of the other `basic_memory_buffer` object to this one. auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& { FMT_ASSERT(this != &other, ""); deallocate(); @@ -974,120 +862,108 @@ class basic_memory_buffer final : public detail::buffer { // Returns a copy of the allocator associated with this buffer. auto get_allocator() const -> Allocator { return alloc_; } - /** - Resizes the buffer to contain *count* elements. If T is a POD type new - elements may not be initialized. - */ - FMT_CONSTEXPR20 void resize(size_t count) { this->try_resize(count); } + /// Resizes the buffer to contain `count` elements. If T is a POD type new + /// elements may not be initialized. + FMT_CONSTEXPR void resize(size_t count) { this->try_resize(count); } - /** Increases the buffer capacity to *new_capacity*. */ + /// Increases the buffer capacity to `new_capacity`. void reserve(size_t new_capacity) { this->try_reserve(new_capacity); } using detail::buffer::append; template - void append(const ContiguousRange& range) { + FMT_CONSTEXPR20 void append(const ContiguousRange& range) { append(range.data(), range.data() + range.size()); } }; using memory_buffer = basic_memory_buffer; +template +FMT_NODISCARD auto to_string(const basic_memory_buffer& buf) + -> std::string { + auto size = buf.size(); + detail::assume(size < std::string().max_size()); + return {buf.data(), size}; +} + +// A writer to a buffered stream. It doesn't own the underlying stream. +class writer { + private: + detail::buffer* buf_; + + // We cannot create a file buffer in advance because any write to a FILE may + // invalidate it. + FILE* file_; + + public: + inline writer(FILE* f) : buf_(nullptr), file_(f) {} + inline writer(detail::buffer& buf) : buf_(&buf) {} + + /// Formats `args` according to specifications in `fmt` and writes the + /// output to the file. + template void print(format_string fmt, T&&... args) { + if (buf_) + fmt::format_to(appender(*buf_), fmt, std::forward(args)...); + else + fmt::print(file_, fmt, std::forward(args)...); + } +}; + +class string_buffer { + private: + std::string str_; + detail::container_buffer buf_; + + public: + inline string_buffer() : buf_(str_) {} + + inline operator writer() { return buf_; } + inline std::string& str() { return str_; } +}; + template struct is_contiguous> : std::true_type { }; -FMT_END_EXPORT -namespace detail { -FMT_API auto write_console(int fd, string_view text) -> bool; -FMT_API auto write_console(std::FILE* f, string_view text) -> bool; -FMT_API void print(std::FILE*, string_view); -} // namespace detail - -FMT_BEGIN_EXPORT - // Suppress a misleading warning in older versions of clang. -#if FMT_CLANG_VERSION -# pragma clang diagnostic ignored "-Wweak-vtables" -#endif +FMT_PRAGMA_CLANG(diagnostic ignored "-Wweak-vtables") -/** An error reported from a formatting function. */ +/// An error reported from a formatting function. class FMT_SO_VISIBILITY("default") format_error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; -namespace detail_exported { -#if FMT_USE_NONTYPE_TEMPLATE_ARGS +class loc_value; + +FMT_END_EXPORT +namespace detail { +FMT_API auto write_console(int fd, string_view text) -> bool; +FMT_API void print(FILE*, string_view); +} // namespace detail + +namespace detail { template struct fixed_string { - constexpr fixed_string(const Char (&str)[N]) { - detail::copy_str(static_cast(str), - str + N, data); + FMT_CONSTEXPR20 fixed_string(const Char (&s)[N]) { + detail::copy(static_cast(s), s + N, + data); } Char data[N] = {}; }; -#endif // Converts a compile-time string to basic_string_view. -template +FMT_EXPORT template constexpr auto compile_string_to_view(const Char (&s)[N]) -> basic_string_view { // Remove trailing NUL character if needed. Won't be present if this is used // with a raw character array (i.e. not defined as a string). return {s, N - (std::char_traits::to_int_type(s[N - 1]) == 0 ? 1 : 0)}; } -template -constexpr auto compile_string_to_view(detail::std_string_view s) +FMT_EXPORT template +constexpr auto compile_string_to_view(basic_string_view s) -> basic_string_view { - return {s.data(), s.size()}; + return s; } -} // namespace detail_exported - -class loc_value { - private: - basic_format_arg value_; - - public: - template ::value)> - loc_value(T value) : value_(detail::make_arg(value)) {} - - template ::value)> - loc_value(T) {} - - template auto visit(Visitor&& vis) -> decltype(vis(0)) { - return visit_format_arg(vis, value_); - } -}; - -// A locale facet that formats values in UTF-8. -// It is parameterized on the locale to avoid the heavy include. -template class format_facet : public Locale::facet { - private: - std::string separator_; - std::string grouping_; - std::string decimal_point_; - - protected: - virtual auto do_put(appender out, loc_value val, - const format_specs<>& specs) const -> bool; - - public: - static FMT_API typename Locale::id id; - - explicit format_facet(Locale& loc); - explicit format_facet(string_view sep = "", - std::initializer_list g = {3}, - std::string decimal_point = ".") - : separator_(sep.data(), sep.size()), - grouping_(g.begin(), g.end()), - decimal_point_(decimal_point) {} - - auto put(appender out, loc_value val, const format_specs<>& specs) const - -> bool { - return do_put(out, val, specs); - } -}; - -namespace detail { // Returns true if value is negative, false otherwise. // Same as `value < 0` but doesn't produce warnings if T is an unsigned type. @@ -1100,14 +976,6 @@ constexpr auto is_negative(T) -> bool { return false; } -template -FMT_CONSTEXPR auto is_supported_floating_point(T) -> bool { - if (std::is_same()) return FMT_USE_FLOAT; - if (std::is_same()) return FMT_USE_DOUBLE; - if (std::is_same()) return FMT_USE_LONG_DOUBLE; - return true; -} - // Smallest of uint32_t, uint64_t, uint128_t that is large enough to // represent all values of an integral type T. template @@ -1124,21 +992,22 @@ using uint64_or_128_t = conditional_t() <= 64, uint64_t, uint128_t>; (factor) * 100000000, (factor) * 1000000000 // Converts value in the range [0, 100) to a string. -constexpr auto digits2(size_t value) -> const char* { - // GCC generates slightly better code when value is pointer-size. - return &"0001020304050607080910111213141516171819" - "2021222324252627282930313233343536373839" - "4041424344454647484950515253545556575859" - "6061626364656667686970717273747576777879" - "8081828384858687888990919293949596979899"[value * 2]; +// GCC generates slightly better code when value is pointer-size. +inline auto digits2(size_t value) -> const char* { + // Align data since unaligned access may be slower when crossing a + // hardware-specific boundary. + alignas(2) static const char data[] = + "0001020304050607080910111213141516171819" + "2021222324252627282930313233343536373839" + "4041424344454647484950515253545556575859" + "6061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"; + return &data[value * 2]; } -// Sign is a template parameter to workaround a bug in gcc 4.8. -template constexpr auto sign(Sign s) -> Char { -#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 604 - static_assert(std::is_same::value, ""); -#endif - return static_cast("\0-+ "[s]); +template constexpr auto getsign(sign s) -> Char { + return static_cast(((' ' << 24) | ('+' << 16) | ('-' << 8)) >> + (static_cast(s) * 8)); } template FMT_CONSTEXPR auto count_digits_fallback(T n) -> int { @@ -1186,9 +1055,7 @@ inline auto do_count_digits(uint64_t n) -> int { // except for n == 0 in which case count_digits returns 1. FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int { #ifdef FMT_BUILTIN_CLZLL - if (!is_constant_evaluated()) { - return do_count_digits(n); - } + if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n); #endif return count_digits_fallback(n); } @@ -1238,9 +1105,7 @@ FMT_INLINE auto do_count_digits(uint32_t n) -> int { // Optional version of count_digits for better performance on 32-bit platforms. FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int { #ifdef FMT_BUILTIN_CLZ - if (!is_constant_evaluated()) { - return do_count_digits(n); - } + if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n); #endif return count_digits_fallback(n); } @@ -1277,6 +1142,17 @@ template <> inline auto decimal_point(locale_ref loc) -> wchar_t { return decimal_point_impl(loc); } +#ifndef FMT_HEADER_ONLY +FMT_BEGIN_EXPORT +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto decimal_point_impl(locale_ref) -> char; +extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t; +FMT_END_EXPORT +#endif // FMT_HEADER_ONLY + // Compares two characters for equality. template auto equal2(const Char* lhs, const char* rhs) -> bool { return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]); @@ -1285,83 +1161,99 @@ inline auto equal2(const char* lhs, const char* rhs) -> bool { return memcmp(lhs, rhs, 2) == 0; } -// Copies two characters from src to dst. +// Writes a two-digit value to out. template -FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) { - if (!is_constant_evaluated() && sizeof(Char) == sizeof(char)) { - memcpy(dst, src, 2); +FMT_CONSTEXPR20 FMT_INLINE void write2digits(Char* out, size_t value) { + if (!is_constant_evaluated() && std::is_same::value && + !FMT_OPTIMIZE_SIZE) { + memcpy(out, digits2(value), 2); return; } - *dst++ = static_cast(*src++); - *dst = static_cast(*src); + *out++ = static_cast('0' + value / 10); + *out = static_cast('0' + value % 10); } -template struct format_decimal_result { - Iterator begin; - Iterator end; -}; - -// Formats a decimal unsigned integer value writing into out pointing to a -// buffer of specified size. The caller must ensure that the buffer is large -// enough. +// Formats a decimal unsigned integer value writing to out pointing to a buffer +// of specified size. The caller must ensure that the buffer is large enough. template -FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size) - -> format_decimal_result { +FMT_CONSTEXPR20 auto do_format_decimal(Char* out, UInt value, int size) + -> Char* { FMT_ASSERT(size >= count_digits(value), "invalid digit count"); - out += size; - Char* end = out; + unsigned n = to_unsigned(size); while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. - out -= 2; - copy2(out, digits2(static_cast(value % 100))); + n -= 2; + write2digits(out + n, static_cast(value % 100)); value /= 100; } - if (value < 10) { - *--out = static_cast('0' + value); - return {out, end}; + if (value >= 10) { + n -= 2; + write2digits(out + n, static_cast(value)); + } else { + out[--n] = static_cast('0' + value); } - out -= 2; - copy2(out, digits2(static_cast(value))); - return {out, end}; + return out + n; } -template >::value)> -FMT_CONSTEXPR inline auto format_decimal(Iterator out, UInt value, int size) - -> format_decimal_result { - // Buffer is large enough to hold all digits (digits10 + 1). - Char buffer[digits10() + 1] = {}; - auto end = format_decimal(buffer, value, size).end; - return {out, detail::copy_str_noinline(buffer, end, out)}; +template +FMT_CONSTEXPR FMT_INLINE auto format_decimal(Char* out, UInt value, + int num_digits) -> Char* { + do_format_decimal(out, value, num_digits); + return out + num_digits; } -template -FMT_CONSTEXPR auto format_uint(Char* buffer, UInt value, int num_digits, - bool upper = false) -> Char* { - buffer += num_digits; - Char* end = buffer; - do { - const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; - unsigned digit = static_cast(value & ((1 << BASE_BITS) - 1)); - *--buffer = static_cast(BASE_BITS < 4 ? static_cast('0' + digit) - : digits[digit]); - } while ((value >>= BASE_BITS) != 0); - return end; -} - -template -FMT_CONSTEXPR inline auto format_uint(It out, UInt value, int num_digits, - bool upper = false) -> It { +template >::value)> +FMT_CONSTEXPR auto format_decimal(OutputIt out, UInt value, int num_digits) + -> OutputIt { if (auto ptr = to_pointer(out, to_unsigned(num_digits))) { - format_uint(ptr, value, num_digits, upper); + do_format_decimal(ptr, value, num_digits); return out; } - // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1). - char buffer[num_bits() / BASE_BITS + 1] = {}; - format_uint(buffer, value, num_digits, upper); - return detail::copy_str_noinline(buffer, buffer + num_digits, out); + // Buffer is large enough to hold all digits (digits10 + 1). + char buffer[digits10() + 1]; + if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0'); + do_format_decimal(buffer, value, num_digits); + return copy_noinline(buffer, buffer + num_digits, out); +} + +template +FMT_CONSTEXPR auto do_format_base2e(int base_bits, Char* out, UInt value, + int size, bool upper = false) -> Char* { + out += size; + do { + const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; + unsigned digit = static_cast(value & ((1 << base_bits) - 1)); + *--out = static_cast(base_bits < 4 ? static_cast('0' + digit) + : digits[digit]); + } while ((value >>= base_bits) != 0); + return out; +} + +// Formats an unsigned integer in the power of two base (binary, octal, hex). +template +FMT_CONSTEXPR auto format_base2e(int base_bits, Char* out, UInt value, + int num_digits, bool upper = false) -> Char* { + do_format_base2e(base_bits, out, value, num_digits, upper); + return out + num_digits; +} + +template ::value)> +FMT_CONSTEXPR inline auto format_base2e(int base_bits, OutputIt out, UInt value, + int num_digits, bool upper = false) + -> OutputIt { + if (auto ptr = to_pointer(out, to_unsigned(num_digits))) { + format_base2e(base_bits, ptr, value, num_digits, upper); + return out; + } + // Make buffer large enough for any base. + char buffer[num_bits()]; + if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0'); + format_base2e(base_bits, buffer, value, num_digits, upper); + return detail::copy_noinline(buffer, buffer + num_digits, out); } // A converter from UTF-8 to UTF-16. @@ -1371,10 +1263,12 @@ class utf8_to_utf16 { public: FMT_API explicit utf8_to_utf16(string_view s); - operator basic_string_view() const { return {&buffer_[0], size()}; } - auto size() const -> size_t { return buffer_.size() - 1; } - auto c_str() const -> const wchar_t* { return &buffer_[0]; } - auto str() const -> std::wstring { return {&buffer_[0], size()}; } + inline operator basic_string_view() const { + return {&buffer_[0], size()}; + } + inline auto size() const -> size_t { return buffer_.size() - 1; } + inline auto c_str() const -> const wchar_t* { return &buffer_[0]; } + inline auto str() const -> std::wstring { return {&buffer_[0], size()}; } }; enum class to_utf8_error_policy { abort, replace }; @@ -1421,10 +1315,12 @@ template class to_utf8 { if (policy == to_utf8_error_policy::abort) return false; buf.append(string_view("\xEF\xBF\xBD")); --p; + continue; } else { c = (c << 10) + static_cast(*p) - 0x35fdc00; } - } else if (c < 0x80) { + } + if (c < 0x80) { buf.push_back(static_cast(c)); } else if (c < 0x800) { buf.push_back(static_cast(0xc0 | (c >> 6))); @@ -1592,25 +1488,30 @@ template constexpr auto exponent_bias() -> int { } // Writes the exponent exp in the form "[+-]d{2,3}" to buffer. -template -FMT_CONSTEXPR auto write_exponent(int exp, It it) -> It { +template +FMT_CONSTEXPR auto write_exponent(int exp, OutputIt out) -> OutputIt { FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); if (exp < 0) { - *it++ = static_cast('-'); + *out++ = static_cast('-'); exp = -exp; } else { - *it++ = static_cast('+'); + *out++ = static_cast('+'); } - if (exp >= 100) { - const char* top = digits2(to_unsigned(exp / 100)); - if (exp >= 1000) *it++ = static_cast(top[0]); - *it++ = static_cast(top[1]); - exp %= 100; + auto uexp = static_cast(exp); + if (is_constant_evaluated()) { + if (uexp < 10) *out++ = '0'; + return format_decimal(out, uexp, count_digits(uexp)); } - const char* d = digits2(to_unsigned(exp)); - *it++ = static_cast(d[0]); - *it++ = static_cast(d[1]); - return it; + if (uexp >= 100u) { + const char* top = digits2(uexp / 100); + if (uexp >= 1000u) *out++ = static_cast(top[0]); + *out++ = static_cast(top[1]); + uexp %= 100; + } + const char* d = digits2(uexp); + *out++ = static_cast(d[0]); + *out++ = static_cast(d[1]); + return out; } // A floating-point number f * pow(2, e) where F is an unsigned type. @@ -1711,67 +1612,69 @@ constexpr auto convert_float(T value) -> convert_float_result { return static_cast>(value); } -template +template FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n, - const fill_t& fill) -> OutputIt { - auto fill_size = fill.size(); - if (fill_size == 1) return detail::fill_n(it, n, fill[0]); - auto data = fill.data(); - for (size_t i = 0; i < n; ++i) - it = copy_str(data, data + fill_size, it); + const basic_specs& specs) -> OutputIt { + auto fill_size = specs.fill_size(); + if (fill_size == 1) return detail::fill_n(it, n, specs.fill_unit()); + if (const Char* data = specs.fill()) { + for (size_t i = 0; i < n; ++i) it = copy(data, data + fill_size, it); + } return it; } // Writes the output of f, padded according to format specifications in specs. // size: output size in code units. // width: output display width in (terminal) column positions. -template -FMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs, +FMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs, size_t size, size_t width, F&& f) -> OutputIt { - static_assert(align == align::left || align == align::right, ""); + static_assert(default_align == align::left || default_align == align::right, + ""); unsigned spec_width = to_unsigned(specs.width); size_t padding = spec_width > width ? spec_width - width : 0; // Shifts are encoded as string literals because static constexpr is not // supported in constexpr functions. - auto* shifts = align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01"; - size_t left_padding = padding >> shifts[specs.align]; + auto* shifts = + default_align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01"; + size_t left_padding = padding >> shifts[static_cast(specs.align())]; size_t right_padding = padding - left_padding; - auto it = reserve(out, size + padding * specs.fill.size()); - if (left_padding != 0) it = fill(it, left_padding, specs.fill); + auto it = reserve(out, size + padding * specs.fill_size()); + if (left_padding != 0) it = fill(it, left_padding, specs); it = f(it); - if (right_padding != 0) it = fill(it, right_padding, specs.fill); + if (right_padding != 0) it = fill(it, right_padding, specs); return base_iterator(out, it); } -template -constexpr auto write_padded(OutputIt out, const format_specs& specs, +constexpr auto write_padded(OutputIt out, const format_specs& specs, size_t size, F&& f) -> OutputIt { - return write_padded(out, specs, size, size, f); + return write_padded(out, specs, size, size, f); } -template +template FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes, - const format_specs& specs) -> OutputIt { - return write_padded( + const format_specs& specs = {}) -> OutputIt { + return write_padded( out, specs, bytes.size(), [bytes](reserve_iterator it) { const char* data = bytes.data(); - return copy_str(data, data + bytes.size(), it); + return copy(data, data + bytes.size(), it); }); } template -auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs) +auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs) -> OutputIt { int num_digits = count_digits<4>(value); auto size = to_unsigned(num_digits) + size_t(2); auto write = [=](reserve_iterator it) { *it++ = static_cast('0'); *it++ = static_cast('x'); - return format_uint<4, Char>(it, value, num_digits); + return format_base2e(4, it, value, num_digits); }; - return specs ? write_padded(out, *specs, size, write) + return specs ? write_padded(out, *specs, size, write) : base_iterator(out, write(reserve(out, size))); } @@ -1779,8 +1682,9 @@ auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs) FMT_API auto is_printable(uint32_t cp) -> bool; inline auto needs_escape(uint32_t cp) -> bool { - return cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\' || - !is_printable(cp); + if (cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\') return true; + if (const_check(FMT_OPTIMIZE_SIZE > 1)) return false; + return !is_printable(cp); } template struct find_escape_result { @@ -1789,17 +1693,11 @@ template struct find_escape_result { uint32_t cp; }; -template -using make_unsigned_char = - typename conditional_t::value, - std::make_unsigned, - type_identity>::type; - template auto find_escape(const Char* begin, const Char* end) -> find_escape_result { for (; begin != end; ++begin) { - uint32_t cp = static_cast>(*begin); + uint32_t cp = static_cast>(*begin); if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue; if (needs_escape(cp)) return {begin, begin + 1, cp}; } @@ -1808,7 +1706,7 @@ auto find_escape(const Char* begin, const Char* end) inline auto find_escape(const char* begin, const char* end) -> find_escape_result { - if (!is_utf8()) return find_escape(begin, end); + if (const_check(!use_utf8)) return find_escape(begin, end); auto result = find_escape_result{end, nullptr, 0}; for_each_codepoint(string_view(begin, to_unsigned(end - begin)), [&](uint32_t cp, string_view sv) { @@ -1821,40 +1719,14 @@ inline auto find_escape(const char* begin, const char* end) return result; } -#define FMT_STRING_IMPL(s, base, explicit) \ - [] { \ - /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \ - /* Use a macro-like name to avoid shadowing warnings. */ \ - struct FMT_VISIBILITY("hidden") FMT_COMPILE_STRING : base { \ - using char_type FMT_MAYBE_UNUSED = fmt::remove_cvref_t; \ - FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit \ - operator fmt::basic_string_view() const { \ - return fmt::detail_exported::compile_string_to_view(s); \ - } \ - }; \ - return FMT_COMPILE_STRING(); \ - }() - -/** - \rst - Constructs a compile-time format string from a string literal *s*. - - **Example**:: - - // A compile-time error because 'd' is an invalid specifier for strings. - std::string s = fmt::format(FMT_STRING("{:d}"), "foo"); - \endrst - */ -#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string, ) - template auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt { *out++ = static_cast('\\'); *out++ = static_cast(prefix); Char buf[width]; fill_n(buf, width, static_cast('0')); - format_uint<4>(buf, cp, width); - return copy_str(buf, buf + width, out); + format_base2e(4, buf, cp, width); + return copy(buf, buf + width, out); } template @@ -1874,23 +1746,15 @@ auto write_escaped_cp(OutputIt out, const find_escape_result& escape) *out++ = static_cast('\\'); c = static_cast('t'); break; - case '"': - FMT_FALLTHROUGH; - case '\'': - FMT_FALLTHROUGH; - case '\\': - *out++ = static_cast('\\'); - break; + case '"': FMT_FALLTHROUGH; + case '\'': FMT_FALLTHROUGH; + case '\\': *out++ = static_cast('\\'); break; default: - if (escape.cp < 0x100) { - return write_codepoint<2, Char>(out, 'x', escape.cp); - } - if (escape.cp < 0x10000) { + if (escape.cp < 0x100) return write_codepoint<2, Char>(out, 'x', escape.cp); + if (escape.cp < 0x10000) return write_codepoint<4, Char>(out, 'u', escape.cp); - } - if (escape.cp < 0x110000) { + if (escape.cp < 0x110000) return write_codepoint<8, Char>(out, 'U', escape.cp); - } for (Char escape_char : basic_string_view( escape.begin, to_unsigned(escape.end - escape.begin))) { out = write_codepoint<2, Char>(out, 'x', @@ -1909,7 +1773,7 @@ auto write_escaped_string(OutputIt out, basic_string_view str) auto begin = str.begin(), end = str.end(); do { auto escape = find_escape(begin, end); - out = copy_str(begin, escape.begin, out); + out = copy(begin, escape.begin, out); begin = escape.end; if (!begin) break; out = write_escaped_cp(out, escape); @@ -1936,74 +1800,23 @@ auto write_escaped_char(OutputIt out, Char v) -> OutputIt { template FMT_CONSTEXPR auto write_char(OutputIt out, Char value, - const format_specs& specs) -> OutputIt { - bool is_debug = specs.type == presentation_type::debug; - return write_padded(out, specs, 1, [=](reserve_iterator it) { + const format_specs& specs) -> OutputIt { + bool is_debug = specs.type() == presentation_type::debug; + return write_padded(out, specs, 1, [=](reserve_iterator it) { if (is_debug) return write_escaped_char(it, value); *it++ = value; return it; }); } template -FMT_CONSTEXPR auto write(OutputIt out, Char value, - const format_specs& specs, locale_ref loc = {}) - -> OutputIt { +FMT_CONSTEXPR auto write(OutputIt out, Char value, const format_specs& specs, + locale_ref loc = {}) -> OutputIt { // char is formatted as unsigned char for consistency across platforms. using unsigned_type = conditional_t::value, unsigned char, unsigned>; return check_char_specs(specs) - ? write_char(out, value, specs) - : write(out, static_cast(value), specs, loc); -} - -// Data for write_int that doesn't depend on output iterator type. It is used to -// avoid template code bloat. -template struct write_int_data { - size_t size; - size_t padding; - - FMT_CONSTEXPR write_int_data(int num_digits, unsigned prefix, - const format_specs& specs) - : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) { - if (specs.align == align::numeric) { - auto width = to_unsigned(specs.width); - if (width > size) { - padding = width - size; - size = width; - } - } else if (specs.precision > num_digits) { - size = (prefix >> 24) + to_unsigned(specs.precision); - padding = to_unsigned(specs.precision - num_digits); - } - } -}; - -// Writes an integer in the format -// -// where are written by write_digits(it). -// prefix contains chars in three lower bytes and the size in the fourth byte. -template -FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, int num_digits, - unsigned prefix, - const format_specs& specs, - W write_digits) -> OutputIt { - // Slightly faster check for specs.width == 0 && specs.precision == -1. - if ((specs.width | (specs.precision + 1)) == 0) { - auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24)); - if (prefix != 0) { - for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) - *it++ = static_cast(p & 0xff); - } - return base_iterator(out, write_digits(it)); - } - auto data = write_int_data(num_digits, prefix, specs); - return write_padded( - out, specs, data.size, [=](reserve_iterator it) { - for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) - *it++ = static_cast(p & 0xff); - it = detail::fill_n(it, data.padding, static_cast('0')); - return write_digits(it); - }); + ? write_char(out, value, specs) + : write(out, static_cast(value), specs, loc); } template class digit_grouping { @@ -2028,7 +1841,9 @@ template class digit_grouping { } public: - explicit digit_grouping(locale_ref loc, bool localized = true) { + template ::value)> + explicit digit_grouping(Locale loc, bool localized = true) { if (!localized) return; auto sep = thousands_sep(loc); grouping_ = sep.grouping; @@ -2060,9 +1875,8 @@ template class digit_grouping { for (int i = 0, sep_index = static_cast(separators.size() - 1); i < num_digits; ++i) { if (num_digits - i == separators[sep_index]) { - out = - copy_str(thousands_sep_.data(), - thousands_sep_.data() + thousands_sep_.size(), out); + out = copy(thousands_sep_.data(), + thousands_sep_.data() + thousands_sep_.size(), out); --sep_index; } *out++ = static_cast(digits[to_unsigned(i)]); @@ -2079,54 +1893,45 @@ FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) { // Writes a decimal integer with digit grouping. template auto write_int(OutputIt out, UInt value, unsigned prefix, - const format_specs& specs, - const digit_grouping& grouping) -> OutputIt { + const format_specs& specs, const digit_grouping& grouping) + -> OutputIt { static_assert(std::is_same, UInt>::value, ""); int num_digits = 0; auto buffer = memory_buffer(); - switch (specs.type) { + switch (specs.type()) { + default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH; case presentation_type::none: - case presentation_type::dec: { + case presentation_type::dec: num_digits = count_digits(value); format_decimal(appender(buffer), value, num_digits); break; - } - case presentation_type::hex_lower: - case presentation_type::hex_upper: { - bool upper = specs.type == presentation_type::hex_upper; - if (specs.alt) - prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0'); + case presentation_type::hex: + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0'); num_digits = count_digits<4>(value); - format_uint<4, char>(appender(buffer), value, num_digits, upper); + format_base2e(4, appender(buffer), value, num_digits, specs.upper()); break; - } - case presentation_type::bin_lower: - case presentation_type::bin_upper: { - bool upper = specs.type == presentation_type::bin_upper; - if (specs.alt) - prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0'); - num_digits = count_digits<1>(value); - format_uint<1, char>(appender(buffer), value, num_digits); - break; - } - case presentation_type::oct: { + case presentation_type::oct: num_digits = count_digits<3>(value); // Octal prefix '0' is counted as a digit, so only add it if precision // is not greater than the number of digits. - if (specs.alt && specs.precision <= num_digits && value != 0) + if (specs.alt() && specs.precision <= num_digits && value != 0) prefix_append(prefix, '0'); - format_uint<3, char>(appender(buffer), value, num_digits); + format_base2e(3, appender(buffer), value, num_digits); + break; + case presentation_type::bin: + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0'); + num_digits = count_digits<1>(value); + format_base2e(1, appender(buffer), value, num_digits); break; - } case presentation_type::chr: - return write_char(out, static_cast(value), specs); - default: - throw_format_error("invalid format specifier"); + return write_char(out, static_cast(value), specs); } unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) + to_unsigned(grouping.count_separators(num_digits)); - return write_padded( + return write_padded( out, specs, size, size, [&](reserve_iterator it) { for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) *it++ = static_cast(p & 0xff); @@ -2134,11 +1939,13 @@ auto write_int(OutputIt out, UInt value, unsigned prefix, }); } +#if FMT_USE_LOCALE // Writes a localized value. -FMT_API auto write_loc(appender out, loc_value value, - const format_specs<>& specs, locale_ref loc) -> bool; -template -inline auto write_loc(OutputIt, loc_value, const format_specs&, +FMT_API auto write_loc(appender out, loc_value value, const format_specs& specs, + locale_ref loc) -> bool; +#endif +template +inline auto write_loc(OutputIt, const loc_value&, const format_specs&, locale_ref) -> bool { return false; } @@ -2149,7 +1956,7 @@ template struct write_int_arg { }; template -FMT_CONSTEXPR auto make_write_int_arg(T value, sign_t sign) +FMT_CONSTEXPR auto make_write_int_arg(T value, sign s) -> write_int_arg> { auto prefix = 0u; auto abs_value = static_cast>(value); @@ -2159,21 +1966,21 @@ FMT_CONSTEXPR auto make_write_int_arg(T value, sign_t sign) } else { constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+', 0x1000000u | ' '}; - prefix = prefixes[sign]; + prefix = prefixes[static_cast(s)]; } return {abs_value, prefix}; } template struct loc_writer { - buffer_appender out; - const format_specs& specs; + basic_appender out; + const format_specs& specs; std::basic_string sep; std::string grouping; std::basic_string decimal_point; template ::value)> auto operator()(T value) -> bool { - auto arg = make_write_int_arg(value, specs.sign); + auto arg = make_write_int_arg(value, specs.sign()); write_int(out, static_cast>(arg.abs_value), arg.prefix, specs, digit_grouping(grouping, sep)); return true; @@ -2185,167 +1992,162 @@ template struct loc_writer { } }; +// Size and padding computation separate from write_int to avoid template bloat. +struct size_padding { + unsigned size; + unsigned padding; + + FMT_CONSTEXPR size_padding(int num_digits, unsigned prefix, + const format_specs& specs) + : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) { + if (specs.align() == align::numeric) { + auto width = to_unsigned(specs.width); + if (width > size) { + padding = width - size; + size = width; + } + } else if (specs.precision > num_digits) { + size = (prefix >> 24) + to_unsigned(specs.precision); + padding = to_unsigned(specs.precision - num_digits); + } + } +}; + template FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg arg, - const format_specs& specs, - locale_ref) -> OutputIt { + const format_specs& specs) -> OutputIt { static_assert(std::is_same>::value, ""); + + constexpr int buffer_size = num_bits(); + char buffer[buffer_size]; + if (is_constant_evaluated()) fill_n(buffer, buffer_size, '\0'); + const char* begin = nullptr; + const char* end = buffer + buffer_size; + auto abs_value = arg.abs_value; auto prefix = arg.prefix; - switch (specs.type) { + switch (specs.type()) { + default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH; case presentation_type::none: - case presentation_type::dec: { - auto num_digits = count_digits(abs_value); - return write_int( - out, num_digits, prefix, specs, [=](reserve_iterator it) { - return format_decimal(it, abs_value, num_digits).end; - }); - } - case presentation_type::hex_lower: - case presentation_type::hex_upper: { - bool upper = specs.type == presentation_type::hex_upper; - if (specs.alt) - prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0'); - int num_digits = count_digits<4>(abs_value); - return write_int( - out, num_digits, prefix, specs, [=](reserve_iterator it) { - return format_uint<4, Char>(it, abs_value, num_digits, upper); - }); - } - case presentation_type::bin_lower: - case presentation_type::bin_upper: { - bool upper = specs.type == presentation_type::bin_upper; - if (specs.alt) - prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0'); - int num_digits = count_digits<1>(abs_value); - return write_int(out, num_digits, prefix, specs, - [=](reserve_iterator it) { - return format_uint<1, Char>(it, abs_value, num_digits); - }); - } + case presentation_type::dec: + begin = do_format_decimal(buffer, abs_value, buffer_size); + break; + case presentation_type::hex: + begin = do_format_base2e(4, buffer, abs_value, buffer_size, specs.upper()); + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0'); + break; case presentation_type::oct: { - int num_digits = count_digits<3>(abs_value); + begin = do_format_base2e(3, buffer, abs_value, buffer_size); // Octal prefix '0' is counted as a digit, so only add it if precision // is not greater than the number of digits. - if (specs.alt && specs.precision <= num_digits && abs_value != 0) + auto num_digits = end - begin; + if (specs.alt() && specs.precision <= num_digits && abs_value != 0) prefix_append(prefix, '0'); - return write_int(out, num_digits, prefix, specs, - [=](reserve_iterator it) { - return format_uint<3, Char>(it, abs_value, num_digits); - }); + break; } + case presentation_type::bin: + begin = do_format_base2e(1, buffer, abs_value, buffer_size); + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0'); + break; case presentation_type::chr: - return write_char(out, static_cast(abs_value), specs); - default: - throw_format_error("invalid format specifier"); + return write_char(out, static_cast(abs_value), specs); } - return out; + + // Write an integer in the format + // + // prefix contains chars in three lower bytes and the size in the fourth byte. + int num_digits = static_cast(end - begin); + // Slightly faster check for specs.width == 0 && specs.precision == -1. + if ((specs.width | (specs.precision + 1)) == 0) { + auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24)); + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + return base_iterator(out, copy(begin, end, it)); + } + auto sp = size_padding(num_digits, prefix, specs); + unsigned padding = sp.padding; + return write_padded( + out, specs, sp.size, [=](reserve_iterator it) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + it = detail::fill_n(it, padding, static_cast('0')); + return copy(begin, end, it); + }); } + template -FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline( - OutputIt out, write_int_arg arg, const format_specs& specs, - locale_ref loc) -> OutputIt { - return write_int(out, arg, specs, loc); +FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(OutputIt out, + write_int_arg arg, + const format_specs& specs) + -> OutputIt { + return write_int(out, arg, specs); } -template ::value && !std::is_same::value && - std::is_same>::value)> -FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value, - const format_specs& specs, - locale_ref loc) -> OutputIt { - if (specs.localized && write_loc(out, value, specs, loc)) return out; - return write_int_noinline(out, make_write_int_arg(value, specs.sign), specs, - loc); + !std::is_same::value)> +FMT_CONSTEXPR FMT_INLINE auto write(basic_appender out, T value, + const format_specs& specs, locale_ref loc) + -> basic_appender { + if (specs.localized() && write_loc(out, value, specs, loc)) return out; + return write_int_noinline(out, make_write_int_arg(value, specs.sign()), + specs); } + // An inlined version of write used in format string compilation. template ::value && !std::is_same::value && - !std::is_same>::value)> + !std::is_same::value && + !std::is_same>::value)> FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value, - const format_specs& specs, - locale_ref loc) -> OutputIt { - if (specs.localized && write_loc(out, value, specs, loc)) return out; - return write_int(out, make_write_int_arg(value, specs.sign), specs, loc); + const format_specs& specs, locale_ref loc) + -> OutputIt { + if (specs.localized() && write_loc(out, value, specs, loc)) return out; + return write_int(out, make_write_int_arg(value, specs.sign()), specs); } -// An output iterator that counts the number of objects written to it and -// discards them. -class counting_iterator { - private: - size_t count_; - - public: - using iterator_category = std::output_iterator_tag; - using difference_type = std::ptrdiff_t; - using pointer = void; - using reference = void; - FMT_UNCHECKED_ITERATOR(counting_iterator); - - struct value_type { - template FMT_CONSTEXPR void operator=(const T&) {} - }; - - FMT_CONSTEXPR counting_iterator() : count_(0) {} - - FMT_CONSTEXPR auto count() const -> size_t { return count_; } - - FMT_CONSTEXPR auto operator++() -> counting_iterator& { - ++count_; - return *this; - } - FMT_CONSTEXPR auto operator++(int) -> counting_iterator { - auto it = *this; - ++*this; - return it; - } - - FMT_CONSTEXPR friend auto operator+(counting_iterator it, difference_type n) - -> counting_iterator { - it.count_ += static_cast(n); - return it; - } - - FMT_CONSTEXPR auto operator*() const -> value_type { return {}; } -}; - template FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, - const format_specs& specs) -> OutputIt { + const format_specs& specs) -> OutputIt { auto data = s.data(); auto size = s.size(); if (specs.precision >= 0 && to_unsigned(specs.precision) < size) size = code_point_index(s, to_unsigned(specs.precision)); - bool is_debug = specs.type == presentation_type::debug; + + bool is_debug = specs.type() == presentation_type::debug; + if (is_debug) { + auto buf = counting_buffer(); + write_escaped_string(basic_appender(buf), s); + size = buf.count(); + } + size_t width = 0; if (specs.width != 0) { - if (is_debug) - width = write_escaped_string(counting_iterator{}, s).count(); - else - width = compute_width(basic_string_view(data, size)); + width = + is_debug ? size : compute_width(basic_string_view(data, size)); } - return write_padded(out, specs, size, width, - [=](reserve_iterator it) { - if (is_debug) return write_escaped_string(it, s); - return copy_str(data, data + size, it); - }); + return write_padded( + out, specs, size, width, [=](reserve_iterator it) { + return is_debug ? write_escaped_string(it, s) + : copy(data, data + size, it); + }); } template -FMT_CONSTEXPR auto write(OutputIt out, - basic_string_view> s, - const format_specs& specs, locale_ref) - -> OutputIt { - return write(out, s, specs); +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, + const format_specs& specs, locale_ref) -> OutputIt { + return write(out, s, specs); } template -FMT_CONSTEXPR auto write(OutputIt out, const Char* s, - const format_specs& specs, locale_ref) - -> OutputIt { - if (specs.type == presentation_type::pointer) +FMT_CONSTEXPR auto write(OutputIt out, const Char* s, const format_specs& specs, + locale_ref) -> OutputIt { + if (specs.type() == presentation_type::pointer) return write_ptr(out, bit_cast(s), &specs); - if (!s) throw_format_error("string pointer is null"); - return write(out, basic_string_view(s), specs, {}); + if (!s) report_error("string pointer is null"); + return write(out, basic_string_view(s), specs, {}); } template OutputIt { if (negative) abs_value = ~abs_value + 1; int num_digits = count_digits(abs_value); auto size = (negative ? 1 : 0) + static_cast(num_digits); - auto it = reserve(out, size); - if (auto ptr = to_pointer(it, size)) { + if (auto ptr = to_pointer(out, size)) { if (negative) *ptr++ = static_cast('-'); format_decimal(ptr, abs_value, num_digits); return out; } - if (negative) *it++ = static_cast('-'); - it = format_decimal(it, abs_value, num_digits).end; - return base_iterator(out, it); + if (negative) *out++ = static_cast('-'); + return format_decimal(out, abs_value, num_digits); } -// DEPRECATED! template FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end, - format_specs& specs) -> const Char* { + format_specs& specs) -> const Char* { FMT_ASSERT(begin != end, ""); - auto align = align::none; + auto alignment = align::none; auto p = begin + code_point_length(begin); if (end - p <= 0) p = begin; for (;;) { switch (to_ascii(*p)) { - case '<': - align = align::left; - break; - case '>': - align = align::right; - break; - case '^': - align = align::center; - break; + case '<': alignment = align::left; break; + case '>': alignment = align::right; break; + case '^': alignment = align::center; break; } - if (align != align::none) { + if (alignment != align::none) { if (p != begin) { auto c = *begin; if (c == '}') return begin; if (c == '{') { - throw_format_error("invalid fill character '{'"); + report_error("invalid fill character '{'"); return begin; } - specs.fill = {begin, to_unsigned(p - begin)}; + specs.set_fill(basic_string_view(begin, to_unsigned(p - begin))); begin = p + 1; } else { ++begin; @@ -2409,88 +2202,27 @@ FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end, } p = begin; } - specs.align = align; + specs.set_align(alignment); return begin; } -// A floating-point presentation format. -enum class float_format : unsigned char { - general, // General: exponent notation or fixed point based on magnitude. - exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3. - fixed, // Fixed point with the default precision of 6, e.g. 0.0012. - hex -}; - -struct float_specs { - int precision; - float_format format : 8; - sign_t sign : 8; - bool upper : 1; - bool locale : 1; - bool binary32 : 1; - bool showpoint : 1; -}; - -template -FMT_CONSTEXPR auto parse_float_type_spec(const format_specs& specs) - -> float_specs { - auto result = float_specs(); - result.showpoint = specs.alt; - result.locale = specs.localized; - switch (specs.type) { - case presentation_type::none: - result.format = float_format::general; - break; - case presentation_type::general_upper: - result.upper = true; - FMT_FALLTHROUGH; - case presentation_type::general_lower: - result.format = float_format::general; - break; - case presentation_type::exp_upper: - result.upper = true; - FMT_FALLTHROUGH; - case presentation_type::exp_lower: - result.format = float_format::exp; - result.showpoint |= specs.precision != 0; - break; - case presentation_type::fixed_upper: - result.upper = true; - FMT_FALLTHROUGH; - case presentation_type::fixed_lower: - result.format = float_format::fixed; - result.showpoint |= specs.precision != 0; - break; - case presentation_type::hexfloat_upper: - result.upper = true; - FMT_FALLTHROUGH; - case presentation_type::hexfloat_lower: - result.format = float_format::hex; - break; - default: - throw_format_error("invalid format specifier"); - break; - } - return result; -} - template FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan, - format_specs specs, - const float_specs& fspecs) -> OutputIt { + format_specs specs, sign s) -> OutputIt { auto str = - isnan ? (fspecs.upper ? "NAN" : "nan") : (fspecs.upper ? "INF" : "inf"); + isnan ? (specs.upper() ? "NAN" : "nan") : (specs.upper() ? "INF" : "inf"); constexpr size_t str_size = 3; - auto sign = fspecs.sign; - auto size = str_size + (sign ? 1 : 0); + auto size = str_size + (s != sign::none ? 1 : 0); // Replace '0'-padding with space for non-finite values. const bool is_zero_fill = - specs.fill.size() == 1 && *specs.fill.data() == static_cast('0'); - if (is_zero_fill) specs.fill[0] = static_cast(' '); - return write_padded(out, specs, size, [=](reserve_iterator it) { - if (sign) *it++ = detail::sign(sign); - return copy_str(str, str + str_size, it); - }); + specs.fill_size() == 1 && specs.fill_unit() == '0'; + if (is_zero_fill) specs.set_fill(' '); + return write_padded(out, specs, size, + [=](reserve_iterator it) { + if (s != sign::none) + *it++ = detail::getsign(s); + return copy(str, str + str_size, it); + }); } // A decimal floating-point number significand * pow(10, exp). @@ -2511,12 +2243,12 @@ inline auto get_significand_size(const dragonbox::decimal_fp& f) -> int { template constexpr auto write_significand(OutputIt out, const char* significand, int significand_size) -> OutputIt { - return copy_str(significand, significand + significand_size, out); + return copy(significand, significand + significand_size, out); } template inline auto write_significand(OutputIt out, UInt significand, int significand_size) -> OutputIt { - return format_decimal(out, significand, significand_size).end; + return format_decimal(out, significand, significand_size); } template FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, @@ -2536,14 +2268,13 @@ template ::value)> inline auto write_significand(Char* out, UInt significand, int significand_size, int integral_size, Char decimal_point) -> Char* { - if (!decimal_point) - return format_decimal(out, significand, significand_size).end; + if (!decimal_point) return format_decimal(out, significand, significand_size); out += significand_size + 1; Char* end = out; int floating_size = significand_size - integral_size; for (int i = floating_size / 2; i > 0; --i) { out -= 2; - copy2(out, digits2(static_cast(significand % 100))); + write2digits(out, static_cast(significand % 100)); significand /= 100; } if (floating_size % 2 != 0) { @@ -2564,19 +2295,19 @@ inline auto write_significand(OutputIt out, UInt significand, Char buffer[digits10() + 2]; auto end = write_significand(buffer, significand, significand_size, integral_size, decimal_point); - return detail::copy_str_noinline(buffer, end, out); + return detail::copy_noinline(buffer, end, out); } template FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand, int significand_size, int integral_size, Char decimal_point) -> OutputIt { - out = detail::copy_str_noinline(significand, - significand + integral_size, out); + out = detail::copy_noinline(significand, significand + integral_size, + out); if (!decimal_point) return out; *out++ = decimal_point; - return detail::copy_str_noinline(significand + integral_size, - significand + significand_size, out); + return detail::copy_noinline(significand + integral_size, + significand + significand_size, out); } template @@ -2589,44 +2320,42 @@ FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, decimal_point); } auto buffer = basic_memory_buffer(); - write_significand(buffer_appender(buffer), significand, - significand_size, integral_size, decimal_point); + write_significand(basic_appender(buffer), significand, significand_size, + integral_size, decimal_point); grouping.apply( out, basic_string_view(buffer.data(), to_unsigned(integral_size))); - return detail::copy_str_noinline(buffer.data() + integral_size, - buffer.end(), out); + return detail::copy_noinline(buffer.data() + integral_size, + buffer.end(), out); } -template > FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f, - const format_specs& specs, - float_specs fspecs, locale_ref loc) - -> OutputIt { + const format_specs& specs, sign s, + int exp_upper, locale_ref loc) -> OutputIt { auto significand = f.significand; int significand_size = get_significand_size(f); const Char zero = static_cast('0'); - auto sign = fspecs.sign; - size_t size = to_unsigned(significand_size) + (sign ? 1 : 0); + size_t size = to_unsigned(significand_size) + (s != sign::none ? 1 : 0); using iterator = reserve_iterator; - Char decimal_point = - fspecs.locale ? detail::decimal_point(loc) : static_cast('.'); + Char decimal_point = specs.localized() ? detail::decimal_point(loc) + : static_cast('.'); int output_exp = f.exponent + significand_size - 1; auto use_exp_format = [=]() { - if (fspecs.format == float_format::exp) return true; - if (fspecs.format != float_format::general) return false; + if (specs.type() == presentation_type::exp) return true; + if (specs.type() == presentation_type::fixed) return false; // Use the fixed notation if the exponent is in [exp_lower, exp_upper), // e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation. - const int exp_lower = -4, exp_upper = 16; + const int exp_lower = -4; return output_exp < exp_lower || - output_exp >= (fspecs.precision > 0 ? fspecs.precision : exp_upper); + output_exp >= (specs.precision > 0 ? specs.precision : exp_upper); }; if (use_exp_format()) { int num_zeros = 0; - if (fspecs.showpoint) { - num_zeros = fspecs.precision - significand_size; + if (specs.alt()) { + num_zeros = specs.precision - significand_size; if (num_zeros < 0) num_zeros = 0; size += to_unsigned(num_zeros); } else if (significand_size == 1) { @@ -2637,9 +2366,9 @@ FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f, if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3; size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits); - char exp_char = fspecs.upper ? 'E' : 'e'; + char exp_char = specs.upper() ? 'E' : 'e'; auto write = [=](iterator it) { - if (sign) *it++ = detail::sign(sign); + if (s != sign::none) *it++ = detail::getsign(s); // Insert a decimal point after the first digit and add an exponent. it = write_significand(it, significand, significand_size, 1, decimal_point); @@ -2647,39 +2376,41 @@ FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f, *it++ = static_cast(exp_char); return write_exponent(output_exp, it); }; - return specs.width > 0 ? write_padded(out, specs, size, write) - : base_iterator(out, write(reserve(out, size))); + return specs.width > 0 + ? write_padded(out, specs, size, write) + : base_iterator(out, write(reserve(out, size))); } int exp = f.exponent + significand_size; if (f.exponent >= 0) { // 1234e5 -> 123400000[.0+] size += to_unsigned(f.exponent); - int num_zeros = fspecs.precision - exp; + int num_zeros = specs.precision - exp; abort_fuzzing_if(num_zeros > 5000); - if (fspecs.showpoint) { + if (specs.alt()) { ++size; - if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 0; + if (num_zeros <= 0 && specs.type() != presentation_type::fixed) + num_zeros = 0; if (num_zeros > 0) size += to_unsigned(num_zeros); } - auto grouping = Grouping(loc, fspecs.locale); + auto grouping = Grouping(loc, specs.localized()); size += to_unsigned(grouping.count_separators(exp)); - return write_padded(out, specs, size, [&](iterator it) { - if (sign) *it++ = detail::sign(sign); + return write_padded(out, specs, size, [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); it = write_significand(it, significand, significand_size, f.exponent, grouping); - if (!fspecs.showpoint) return it; + if (!specs.alt()) return it; *it++ = decimal_point; return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it; }); } else if (exp > 0) { // 1234e-2 -> 12.34[0+] - int num_zeros = fspecs.showpoint ? fspecs.precision - significand_size : 0; - size += 1 + to_unsigned(num_zeros > 0 ? num_zeros : 0); - auto grouping = Grouping(loc, fspecs.locale); + int num_zeros = specs.alt() ? specs.precision - significand_size : 0; + size += 1 + static_cast(max_of(num_zeros, 0)); + auto grouping = Grouping(loc, specs.localized()); size += to_unsigned(grouping.count_separators(exp)); - return write_padded(out, specs, size, [&](iterator it) { - if (sign) *it++ = detail::sign(sign); + return write_padded(out, specs, size, [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); it = write_significand(it, significand, significand_size, exp, decimal_point, grouping); return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it; @@ -2687,14 +2418,14 @@ FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f, } // 1234e-6 -> 0.001234 int num_zeros = -exp; - if (significand_size == 0 && fspecs.precision >= 0 && - fspecs.precision < num_zeros) { - num_zeros = fspecs.precision; + if (significand_size == 0 && specs.precision >= 0 && + specs.precision < num_zeros) { + num_zeros = specs.precision; } - bool pointy = num_zeros != 0 || significand_size != 0 || fspecs.showpoint; + bool pointy = num_zeros != 0 || significand_size != 0 || specs.alt(); size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros); - return write_padded(out, specs, size, [&](iterator it) { - if (sign) *it++ = detail::sign(sign); + return write_padded(out, specs, size, [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); *it++ = zero; if (!pointy) return it; *it++ = decimal_point; @@ -2717,22 +2448,21 @@ template class fallback_digit_grouping { } }; -template +template FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f, - const format_specs& specs, - float_specs fspecs, locale_ref loc) - -> OutputIt { + const format_specs& specs, sign s, + int exp_upper, locale_ref loc) -> OutputIt { if (is_constant_evaluated()) { - return do_write_float>(out, f, specs, fspecs, - loc); + return do_write_float>(out, f, specs, s, + exp_upper, loc); } else { - return do_write_float(out, f, specs, fspecs, loc); + return do_write_float(out, f, specs, s, exp_upper, loc); } } template constexpr auto isnan(T value) -> bool { - return !(value >= value); // std::isnan doesn't support __float128. + return value != value; // std::isnan doesn't support __float128. } template @@ -2780,52 +2510,48 @@ inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) { class bigint { private: - // A bigint is stored as an array of bigits (big digits), with bigit at index - // 0 being the least significant one. - using bigit = uint32_t; + // A bigint is a number in the form bigit_[N - 1] ... bigit_[0] * 32^exp_. + using bigit = uint32_t; // A big digit. using double_bigit = uint64_t; + enum { bigit_bits = num_bits() }; enum { bigits_capacity = 32 }; basic_memory_buffer bigits_; int exp_; - FMT_CONSTEXPR20 auto operator[](int index) const -> bigit { - return bigits_[to_unsigned(index)]; - } - FMT_CONSTEXPR20 auto operator[](int index) -> bigit& { - return bigits_[to_unsigned(index)]; - } - - static constexpr const int bigit_bits = num_bits(); - friend struct formatter; - FMT_CONSTEXPR20 void subtract_bigits(int index, bigit other, bigit& borrow) { - auto result = static_cast((*this)[index]) - other - borrow; - (*this)[index] = static_cast(result); + FMT_CONSTEXPR auto get_bigit(int i) const -> bigit { + return i >= exp_ && i < num_bigits() ? bigits_[i - exp_] : 0; + } + + FMT_CONSTEXPR void subtract_bigits(int index, bigit other, bigit& borrow) { + auto result = double_bigit(bigits_[index]) - other - borrow; + bigits_[index] = static_cast(result); borrow = static_cast(result >> (bigit_bits * 2 - 1)); } - FMT_CONSTEXPR20 void remove_leading_zeros() { + FMT_CONSTEXPR void remove_leading_zeros() { int num_bigits = static_cast(bigits_.size()) - 1; - while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits; + while (num_bigits > 0 && bigits_[num_bigits] == 0) --num_bigits; bigits_.resize(to_unsigned(num_bigits + 1)); } // Computes *this -= other assuming aligned bigints and *this >= other. - FMT_CONSTEXPR20 void subtract_aligned(const bigint& other) { + FMT_CONSTEXPR void subtract_aligned(const bigint& other) { FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); FMT_ASSERT(compare(*this, other) >= 0, ""); bigit borrow = 0; int i = other.exp_ - exp_; for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j) subtract_bigits(i, other.bigits_[j], borrow); - while (borrow > 0) subtract_bigits(i, 0, borrow); + if (borrow != 0) subtract_bigits(i, 0, borrow); + FMT_ASSERT(borrow == 0, ""); remove_leading_zeros(); } - FMT_CONSTEXPR20 void multiply(uint32_t value) { - const double_bigit wide_value = value; + FMT_CONSTEXPR void multiply(uint32_t value) { bigit carry = 0; + const double_bigit wide_value = value; for (size_t i = 0, n = bigits_.size(); i < n; ++i) { double_bigit result = bigits_[i] * wide_value + carry; bigits_[i] = static_cast(result); @@ -2836,7 +2562,7 @@ class bigint { template ::value || std::is_same::value)> - FMT_CONSTEXPR20 void multiply(UInt value) { + FMT_CONSTEXPR void multiply(UInt value) { using half_uint = conditional_t::value, uint64_t, uint32_t>; const int shift = num_bits() - bigit_bits; @@ -2857,7 +2583,7 @@ class bigint { template ::value || std::is_same::value)> - FMT_CONSTEXPR20 void assign(UInt n) { + FMT_CONSTEXPR void assign(UInt n) { size_t num_bigits = 0; do { bigits_[num_bigits++] = static_cast(n); @@ -2868,30 +2594,30 @@ class bigint { } public: - FMT_CONSTEXPR20 bigint() : exp_(0) {} + FMT_CONSTEXPR bigint() : exp_(0) {} explicit bigint(uint64_t n) { assign(n); } bigint(const bigint&) = delete; void operator=(const bigint&) = delete; - FMT_CONSTEXPR20 void assign(const bigint& other) { + FMT_CONSTEXPR void assign(const bigint& other) { auto size = other.bigits_.size(); bigits_.resize(size); auto data = other.bigits_.data(); - copy_str(data, data + size, bigits_.data()); + copy(data, data + size, bigits_.data()); exp_ = other.exp_; } - template FMT_CONSTEXPR20 void operator=(Int n) { + template FMT_CONSTEXPR void operator=(Int n) { FMT_ASSERT(n > 0, ""); assign(uint64_or_128_t(n)); } - FMT_CONSTEXPR20 auto num_bigits() const -> int { + FMT_CONSTEXPR auto num_bigits() const -> int { return static_cast(bigits_.size()) + exp_; } - FMT_NOINLINE FMT_CONSTEXPR20 auto operator<<=(int shift) -> bigint& { + FMT_CONSTEXPR auto operator<<=(int shift) -> bigint& { FMT_ASSERT(shift >= 0, ""); exp_ += shift / bigit_bits; shift %= bigit_bits; @@ -2906,49 +2632,39 @@ class bigint { return *this; } - template - FMT_CONSTEXPR20 auto operator*=(Int value) -> bigint& { + template FMT_CONSTEXPR auto operator*=(Int value) -> bigint& { FMT_ASSERT(value > 0, ""); multiply(uint32_or_64_or_128_t(value)); return *this; } - friend FMT_CONSTEXPR20 auto compare(const bigint& lhs, const bigint& rhs) - -> int { - int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits(); - if (num_lhs_bigits != num_rhs_bigits) - return num_lhs_bigits > num_rhs_bigits ? 1 : -1; - int i = static_cast(lhs.bigits_.size()) - 1; - int j = static_cast(rhs.bigits_.size()) - 1; + friend FMT_CONSTEXPR auto compare(const bigint& b1, const bigint& b2) -> int { + int num_bigits1 = b1.num_bigits(), num_bigits2 = b2.num_bigits(); + if (num_bigits1 != num_bigits2) return num_bigits1 > num_bigits2 ? 1 : -1; + int i = static_cast(b1.bigits_.size()) - 1; + int j = static_cast(b2.bigits_.size()) - 1; int end = i - j; if (end < 0) end = 0; for (; i >= end; --i, --j) { - bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j]; - if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1; + bigit b1_bigit = b1.bigits_[i], b2_bigit = b2.bigits_[j]; + if (b1_bigit != b2_bigit) return b1_bigit > b2_bigit ? 1 : -1; } if (i != j) return i > j ? 1 : -1; return 0; } // Returns compare(lhs1 + lhs2, rhs). - friend FMT_CONSTEXPR20 auto add_compare(const bigint& lhs1, - const bigint& lhs2, const bigint& rhs) - -> int { - auto minimum = [](int a, int b) { return a < b ? a : b; }; - auto maximum = [](int a, int b) { return a > b ? a : b; }; - int max_lhs_bigits = maximum(lhs1.num_bigits(), lhs2.num_bigits()); + friend FMT_CONSTEXPR auto add_compare(const bigint& lhs1, const bigint& lhs2, + const bigint& rhs) -> int { + int max_lhs_bigits = max_of(lhs1.num_bigits(), lhs2.num_bigits()); int num_rhs_bigits = rhs.num_bigits(); if (max_lhs_bigits + 1 < num_rhs_bigits) return -1; if (max_lhs_bigits > num_rhs_bigits) return 1; - auto get_bigit = [](const bigint& n, int i) -> bigit { - return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0; - }; double_bigit borrow = 0; - int min_exp = minimum(minimum(lhs1.exp_, lhs2.exp_), rhs.exp_); + int min_exp = min_of(min_of(lhs1.exp_, lhs2.exp_), rhs.exp_); for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { - double_bigit sum = - static_cast(get_bigit(lhs1, i)) + get_bigit(lhs2, i); - bigit rhs_bigit = get_bigit(rhs, i); + double_bigit sum = double_bigit(lhs1.get_bigit(i)) + lhs2.get_bigit(i); + bigit rhs_bigit = rhs.get_bigit(i); if (sum > rhs_bigit + borrow) return 1; borrow = rhs_bigit + borrow - sum; if (borrow > 1) return -1; @@ -2961,10 +2677,8 @@ class bigint { FMT_CONSTEXPR20 void assign_pow10(int exp) { FMT_ASSERT(exp >= 0, ""); if (exp == 0) return *this = 1; - // Find the top bit. - int bitmask = 1; - while (exp >= bitmask) bitmask <<= 1; - bitmask >>= 1; + int bitmask = 1 << (num_bits() - + countl_zero(static_cast(exp)) - 1); // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by // repeated squaring and multiplication. *this = 5; @@ -2988,17 +2702,17 @@ class bigint { // cross-product terms n[i] * n[j] such that i + j == bigit_index. for (int i = 0, j = bigit_index; j >= 0; ++i, --j) { // Most terms are multiplied twice which can be optimized in the future. - sum += static_cast(n[i]) * n[j]; + sum += double_bigit(n[i]) * n[j]; } - (*this)[bigit_index] = static_cast(sum); + bigits_[bigit_index] = static_cast(sum); sum >>= num_bits(); // Compute the carry. } // Do the same for the top half. for (int bigit_index = num_bigits; bigit_index < num_result_bigits; ++bigit_index) { for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) - sum += static_cast(n[i++]) * n[j--]; - (*this)[bigit_index] = static_cast(sum); + sum += double_bigit(n[i++]) * n[j--]; + bigits_[bigit_index] = static_cast(sum); sum >>= num_bits(); } remove_leading_zeros(); @@ -3007,20 +2721,20 @@ class bigint { // If this bigint has a bigger exponent than other, adds trailing zero to make // exponents equal. This simplifies some operations such as subtraction. - FMT_CONSTEXPR20 void align(const bigint& other) { + FMT_CONSTEXPR void align(const bigint& other) { int exp_difference = exp_ - other.exp_; if (exp_difference <= 0) return; int num_bigits = static_cast(bigits_.size()); bigits_.resize(to_unsigned(num_bigits + exp_difference)); for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j) bigits_[j] = bigits_[i]; - std::uninitialized_fill_n(bigits_.data(), exp_difference, 0u); + memset(bigits_.data(), 0, to_unsigned(exp_difference) * sizeof(bigit)); exp_ -= exp_difference; } // Divides this bignum by divisor, assigning the remainder to this and // returning the quotient. - FMT_CONSTEXPR20 auto divmod_assign(const bigint& divisor) -> int { + FMT_CONSTEXPR auto divmod_assign(const bigint& divisor) -> int { FMT_ASSERT(this != &divisor, ""); if (compare(*this, divisor) < 0) return 0; FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, ""); @@ -3139,8 +2853,11 @@ FMT_CONSTEXPR20 inline void format_dragon(basic_fp value, // Generate the given number of digits. exp10 -= num_digits - 1; if (num_digits <= 0) { - denominator *= 10; - auto digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0'; + auto digit = '0'; + if (num_digits == 0) { + denominator *= 10; + digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0'; + } buf.push_back(digit); return; } @@ -3177,8 +2894,8 @@ FMT_CONSTEXPR20 inline void format_dragon(basic_fp value, // Formats a floating-point number using the hexfloat format. template ::value)> -FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision, - float_specs specs, buffer& buf) { +FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs, + buffer& buf) { // float is passed as double to reduce the number of instantiations and to // simplify implementation. static_assert(!std::is_same::value, ""); @@ -3188,26 +2905,25 @@ FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision, // Assume Float is in the format [sign][exponent][significand]. using carrier_uint = typename info::carrier_uint; - constexpr auto num_float_significand_bits = - detail::num_significand_bits(); + const auto num_float_significand_bits = detail::num_significand_bits(); basic_fp f(value); f.e += num_float_significand_bits; if (!has_implicit_bit()) --f.e; - constexpr auto num_fraction_bits = + const auto num_fraction_bits = num_float_significand_bits + (has_implicit_bit() ? 1 : 0); - constexpr auto num_xdigits = (num_fraction_bits + 3) / 4; + const auto num_xdigits = (num_fraction_bits + 3) / 4; - constexpr auto leading_shift = ((num_xdigits - 1) * 4); + const auto leading_shift = ((num_xdigits - 1) * 4); const auto leading_mask = carrier_uint(0xF) << leading_shift; const auto leading_xdigit = static_cast((f.f & leading_mask) >> leading_shift); if (leading_xdigit > 1) f.e -= (32 - countl_zero(leading_xdigit) - 1); int print_xdigits = num_xdigits - 1; - if (precision >= 0 && print_xdigits > precision) { - const int shift = ((print_xdigits - precision - 1) * 4); + if (specs.precision >= 0 && print_xdigits > specs.precision) { + const int shift = ((print_xdigits - specs.precision - 1) * 4); const auto mask = carrier_uint(0xF) << shift; const auto v = static_cast((f.f & mask) >> shift); @@ -3226,25 +2942,25 @@ FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision, } } - print_xdigits = precision; + print_xdigits = specs.precision; } char xdigits[num_bits() / 4]; detail::fill_n(xdigits, sizeof(xdigits), '0'); - format_uint<4>(xdigits, f.f, num_xdigits, specs.upper); + format_base2e(4, xdigits, f.f, num_xdigits, specs.upper()); // Remove zero tail while (print_xdigits > 0 && xdigits[print_xdigits] == '0') --print_xdigits; buf.push_back('0'); - buf.push_back(specs.upper ? 'X' : 'x'); + buf.push_back(specs.upper() ? 'X' : 'x'); buf.push_back(xdigits[0]); - if (specs.showpoint || print_xdigits > 0 || print_xdigits < precision) + if (specs.alt() || print_xdigits > 0 || print_xdigits < specs.precision) buf.push_back('.'); buf.append(xdigits + 1, xdigits + 1 + print_xdigits); - for (; print_xdigits < precision; ++print_xdigits) buf.push_back('0'); + for (; print_xdigits < specs.precision; ++print_xdigits) buf.push_back('0'); - buf.push_back(specs.upper ? 'P' : 'p'); + buf.push_back(specs.upper() ? 'P' : 'p'); uint32_t abs_e; if (f.e < 0) { @@ -3258,9 +2974,9 @@ FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision, } template ::value)> -FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision, - float_specs specs, buffer& buf) { - format_hexfloat(static_cast(value), precision, specs, buf); +FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs, + buffer& buf) { + format_hexfloat(static_cast(value), specs, buf); } constexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t { @@ -3275,15 +2991,15 @@ constexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t { } template -FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, +FMT_CONSTEXPR20 auto format_float(Float value, int precision, + const format_specs& specs, bool binary32, buffer& buf) -> int { // float is passed as double to reduce the number of instantiations. static_assert(!std::is_same::value, ""); - FMT_ASSERT(value >= 0, "value is negative"); auto converted_value = convert_float(value); - const bool fixed = specs.format == float_format::fixed; - if (value <= 0) { // <= instead of == to silence a warning. + const bool fixed = specs.type() == presentation_type::fixed; + if (value == 0) { if (precision <= 0 || !fixed) { buf.push_back('0'); return 0; @@ -3308,16 +3024,6 @@ FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, exp = static_cast(e); if (e > exp) ++exp; // Compute ceil. dragon_flags = dragon::fixup; - } else if (precision < 0) { - // Use Dragonbox for the shortest format. - if (specs.binary32) { - auto dec = dragonbox::to_decimal(static_cast(value)); - write(buffer_appender(buf), dec.significand); - return dec.exponent; - } - auto dec = dragonbox::to_decimal(static_cast(value)); - write(buffer_appender(buf), dec.significand); - return dec.exponent; } else { // Extract significand bits and exponent bits. using info = dragonbox::float_info; @@ -3416,7 +3122,7 @@ FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, uint64_t prod; uint32_t digits; bool should_round_up; - int number_of_digits_to_print = precision > 9 ? 9 : precision; + int number_of_digits_to_print = min_of(precision, 9); // Print a 9-digits subsegment, either the first or the second. auto print_subsegment = [&](uint32_t subsegment, char* buffer) { @@ -3444,7 +3150,7 @@ FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, // for details. prod = ((subsegment * static_cast(450359963)) >> 20) + 1; digits = static_cast(prod >> 32); - copy2(buffer, digits2(digits)); + write2digits(buffer, digits); number_of_digits_printed += 2; } @@ -3452,7 +3158,7 @@ FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, while (number_of_digits_printed < number_of_digits_to_print) { prod = static_cast(prod) * static_cast(100); digits = static_cast(prod >> 32); - copy2(buffer + number_of_digits_printed, digits2(digits)); + write2digits(buffer + number_of_digits_printed, digits); number_of_digits_printed += 2; } }; @@ -3561,9 +3267,8 @@ FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, } if (use_dragon) { auto f = basic_fp(); - bool is_predecessor_closer = specs.binary32 - ? f.assign(static_cast(value)) - : f.assign(converted_value); + bool is_predecessor_closer = binary32 ? f.assign(static_cast(value)) + : f.assign(converted_value); if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer; if (fixed) dragon_flags |= dragon::fixed; // Limit precision to the maximum possible number of significant digits in @@ -3572,7 +3277,7 @@ FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, if (precision > max_double_digits) precision = max_double_digits; format_dragon(f, dragon_flags, precision, buf, exp); } - if (!fixed && !specs.showpoint) { + if (!fixed && !specs.alt()) { // Remove trailing zeros. auto num_digits = buf.size(); while (num_digits > 0 && buf[num_digits - 1] == '0') { @@ -3583,97 +3288,106 @@ FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs, } return exp; } + +// Numbers with exponents greater or equal to the returned value will use +// the exponential notation. +template constexpr auto exp_upper() -> int { + return std::numeric_limits::digits10 != 0 + ? min_of(16, std::numeric_limits::digits10 + 1) + : 16; +} + template -FMT_CONSTEXPR20 auto write_float(OutputIt out, T value, - format_specs specs, locale_ref loc) - -> OutputIt { - float_specs fspecs = parse_float_type_spec(specs); - fspecs.sign = specs.sign; - if (detail::signbit(value)) { // value < 0 is false for NaN so use signbit. - fspecs.sign = sign::minus; - value = -value; - } else if (fspecs.sign == sign::minus) { - fspecs.sign = sign::none; - } +FMT_CONSTEXPR20 auto write_float(OutputIt out, T value, format_specs specs, + locale_ref loc) -> OutputIt { + // Use signbit because value < 0 is false for NaN. + sign s = detail::signbit(value) ? sign::minus : specs.sign(); if (!detail::isfinite(value)) - return write_nonfinite(out, detail::isnan(value), specs, fspecs); + return write_nonfinite(out, detail::isnan(value), specs, s); - if (specs.align == align::numeric && fspecs.sign) { - auto it = reserve(out, 1); - *it++ = detail::sign(fspecs.sign); - out = base_iterator(out, it); - fspecs.sign = sign::none; + if (specs.align() == align::numeric && s != sign::none) { + *out++ = detail::getsign(s); + s = sign::none; if (specs.width != 0) --specs.width; } - memory_buffer buffer; - if (fspecs.format == float_format::hex) { - if (fspecs.sign) buffer.push_back(detail::sign(fspecs.sign)); - format_hexfloat(convert_float(value), specs.precision, fspecs, buffer); - return write_bytes(out, {buffer.data(), buffer.size()}, - specs); + constexpr int exp_upper = detail::exp_upper(); + int precision = specs.precision; + if (precision < 0) { + if (specs.type() != presentation_type::none) { + precision = 6; + } else if (is_fast_float::value && !is_constant_evaluated()) { + // Use Dragonbox for the shortest format. + using floaty = conditional_t= sizeof(double), double, float>; + auto dec = dragonbox::to_decimal(static_cast(value)); + return write_float(out, dec, specs, s, exp_upper, loc); + } } - int precision = specs.precision >= 0 || specs.type == presentation_type::none - ? specs.precision - : 6; - if (fspecs.format == float_format::exp) { + + memory_buffer buffer; + if (specs.type() == presentation_type::hexfloat) { + if (s != sign::none) buffer.push_back(detail::getsign(s)); + format_hexfloat(convert_float(value), specs, buffer); + return write_bytes(out, {buffer.data(), buffer.size()}, + specs); + } + + if (specs.type() == presentation_type::exp) { if (precision == max_value()) - throw_format_error("number is too big"); + report_error("number is too big"); else ++precision; - } else if (fspecs.format != float_format::fixed && precision == 0) { + if (specs.precision != 0) specs.set_alt(); + } else if (specs.type() == presentation_type::fixed) { + if (specs.precision != 0) specs.set_alt(); + } else if (precision == 0) { precision = 1; } - if (const_check(std::is_same())) fspecs.binary32 = true; - int exp = format_float(convert_float(value), precision, fspecs, buffer); - fspecs.precision = precision; + int exp = format_float(convert_float(value), precision, specs, + std::is_same(), buffer); + + specs.precision = precision; auto f = big_decimal_fp{buffer.data(), static_cast(buffer.size()), exp}; - return write_float(out, f, specs, fspecs, loc); + return write_float(out, f, specs, s, exp_upper, loc); } template ::value)> -FMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs, +FMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs, locale_ref loc = {}) -> OutputIt { - if (const_check(!is_supported_floating_point(value))) return out; - return specs.localized && write_loc(out, value, specs, loc) + return specs.localized() && write_loc(out, value, specs, loc) ? out - : write_float(out, value, specs, loc); + : write_float(out, value, specs, loc); } template ::value)> FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt { - if (is_constant_evaluated()) return write(out, value, format_specs()); - if (const_check(!is_supported_floating_point(value))) return out; + if (is_constant_evaluated()) return write(out, value, format_specs()); - auto fspecs = float_specs(); - if (detail::signbit(value)) { - fspecs.sign = sign::minus; - value = -value; - } + auto s = detail::signbit(value) ? sign::minus : sign::none; - constexpr auto specs = format_specs(); - using floaty = conditional_t::value, double, T>; + constexpr auto specs = format_specs(); + using floaty = conditional_t= sizeof(double), double, float>; using floaty_uint = typename dragonbox::float_info::carrier_uint; floaty_uint mask = exponent_mask(); if ((bit_cast(value) & mask) == mask) - return write_nonfinite(out, std::isnan(value), specs, fspecs); + return write_nonfinite(out, std::isnan(value), specs, s); auto dec = dragonbox::to_decimal(static_cast(value)); - return write_float(out, dec, specs, fspecs, {}); + return write_float(out, dec, specs, s, exp_upper(), {}); } template ::value && !is_fast_float::value)> inline auto write(OutputIt out, T value) -> OutputIt { - return write(out, value, format_specs()); + return write(out, value, format_specs()); } template -auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {}) +auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {}) -> OutputIt { FMT_ASSERT(false, ""); return out; @@ -3682,13 +3396,11 @@ auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {}) template FMT_CONSTEXPR auto write(OutputIt out, basic_string_view value) -> OutputIt { - auto it = reserve(out, value.size()); - it = copy_str_noinline(value.begin(), value.end(), it); - return base_iterator(out, it); + return copy_noinline(value.begin(), value.end(), out); } template ::value)> + FMT_ENABLE_IF(has_to_string_view::value)> constexpr auto write(OutputIt out, const T& value) -> OutputIt { return write(out, to_string_view(value)); } @@ -3696,10 +3408,8 @@ constexpr auto write(OutputIt out, const T& value) -> OutputIt { // FMT_ENABLE_IF() condition separated to workaround an MSVC bug. template < typename Char, typename OutputIt, typename T, - bool check = - std::is_enum::value && !std::is_same::value && - mapped_type_constant>::value != - type::custom_type, + bool check = std::is_enum::value && !std::is_same::value && + mapped_type_constant::value != type::custom_type, FMT_ENABLE_IF(check)> FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { return write(out, static_cast>(value)); @@ -3707,13 +3417,12 @@ FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { template ::value)> -FMT_CONSTEXPR auto write(OutputIt out, T value, - const format_specs& specs = {}, locale_ref = {}) - -> OutputIt { - return specs.type != presentation_type::none && - specs.type != presentation_type::string - ? write(out, value ? 1 : 0, specs, {}) - : write_bytes(out, value ? "true" : "false", specs); +FMT_CONSTEXPR auto write(OutputIt out, T value, const format_specs& specs = {}, + locale_ref = {}) -> OutputIt { + return specs.type() != presentation_type::none && + specs.type() != presentation_type::string + ? write(out, value ? 1 : 0, specs, {}) + : write_bytes(out, value ? "true" : "false", specs); } template @@ -3724,171 +3433,150 @@ FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt { } template -FMT_CONSTEXPR_CHAR_TRAITS auto write(OutputIt out, const Char* value) - -> OutputIt { +FMT_CONSTEXPR20 auto write(OutputIt out, const Char* value) -> OutputIt { if (value) return write(out, basic_string_view(value)); - throw_format_error("string pointer is null"); + report_error("string pointer is null"); return out; } template ::value)> -auto write(OutputIt out, const T* value, const format_specs& specs = {}, +auto write(OutputIt out, const T* value, const format_specs& specs = {}, locale_ref = {}) -> OutputIt { return write_ptr(out, bit_cast(value), &specs); } -// A write overload that handles implicit conversions. template > -FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> enable_if_t< - std::is_class::value && !is_string::value && - !is_floating_point::value && !std::is_same::value && - !std::is_same().map( - value))>>::value, - OutputIt> { - return write(out, arg_mapper().map(value)); + FMT_ENABLE_IF(mapped_type_constant::value == + type::custom_type && + !std::is_fundamental::value)> +FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> OutputIt { + auto f = formatter(); + auto parse_ctx = parse_context({}); + f.parse(parse_ctx); + auto ctx = basic_format_context(out, {}, {}); + return f.format(value, ctx); } -template > -FMT_CONSTEXPR auto write(OutputIt out, const T& value) - -> enable_if_t::value == type::custom_type, - OutputIt> { - auto formatter = typename Context::template formatter_type(); - auto parse_ctx = typename Context::parse_context_type({}); - formatter.parse(parse_ctx); - auto ctx = Context(out, {}, {}); - return formatter.format(value, ctx); -} +template +using is_builtin = + bool_constant::value || FMT_BUILTIN_TYPES>; // An argument visitor that formats the argument and writes it via the output // iterator. It's a class and not a generic lambda for compatibility with C++11. template struct default_arg_formatter { - using iterator = buffer_appender; - using context = buffer_context; + using context = buffered_context; - iterator out; - basic_format_args args; - locale_ref loc; + basic_appender out; - template auto operator()(T value) -> iterator { - return write(out, value); + void operator()(monostate) { report_error("argument not found"); } + + template ::value)> + void operator()(T value) { + write(out, value); } - auto operator()(typename basic_format_arg::handle h) -> iterator { - basic_format_parse_context parse_ctx({}); - context format_ctx(out, args, loc); + + template ::value)> + void operator()(T) { + FMT_ASSERT(false, ""); + } + + void operator()(typename basic_format_arg::handle h) { + // Use a null locale since the default format must be unlocalized. + auto parse_ctx = parse_context({}); + auto format_ctx = context(out, {}, {}); h.format(parse_ctx, format_ctx); - return format_ctx.out(); } }; template struct arg_formatter { - using iterator = buffer_appender; - using context = buffer_context; + basic_appender out; + const format_specs& specs; + FMT_NO_UNIQUE_ADDRESS locale_ref locale; - iterator out; - const format_specs& specs; - locale_ref locale; - - template - FMT_CONSTEXPR FMT_INLINE auto operator()(T value) -> iterator { - return detail::write(out, value, specs, locale); + template ::value)> + FMT_CONSTEXPR FMT_INLINE void operator()(T value) { + detail::write(out, value, specs, locale); } - auto operator()(typename basic_format_arg::handle) -> iterator { + + template ::value)> + void operator()(T) { + FMT_ASSERT(false, ""); + } + + void operator()(typename basic_format_arg>::handle) { // User-defined types are handled separately because they require access // to the parse context. - return out; } }; -struct width_checker { +struct dynamic_spec_getter { template ::value)> FMT_CONSTEXPR auto operator()(T value) -> unsigned long long { - if (is_negative(value)) throw_format_error("negative width"); - return static_cast(value); + return is_negative(value) ? ~0ull : static_cast(value); } template ::value)> FMT_CONSTEXPR auto operator()(T) -> unsigned long long { - throw_format_error("width is not integer"); + report_error("width/precision is not integer"); return 0; } }; -struct precision_checker { - template ::value)> - FMT_CONSTEXPR auto operator()(T value) -> unsigned long long { - if (is_negative(value)) throw_format_error("negative precision"); - return static_cast(value); - } - - template ::value)> - FMT_CONSTEXPR auto operator()(T) -> unsigned long long { - throw_format_error("precision is not integer"); - return 0; - } -}; - -template -FMT_CONSTEXPR auto get_dynamic_spec(FormatArg arg) -> int { - unsigned long long value = visit_format_arg(Handler(), arg); - if (value > to_unsigned(max_value())) - throw_format_error("number is too big"); - return static_cast(value); -} - template -FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) -> decltype(ctx.arg(id)) { +FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) -> basic_format_arg { auto arg = ctx.arg(id); - if (!arg) ctx.on_error("argument not found"); + if (!arg) report_error("argument not found"); return arg; } -template -FMT_CONSTEXPR void handle_dynamic_spec(int& value, - arg_ref ref, - Context& ctx) { - switch (ref.kind) { - case arg_id_kind::none: - break; - case arg_id_kind::index: - value = detail::get_dynamic_spec(get_arg(ctx, ref.val.index)); - break; - case arg_id_kind::name: - value = detail::get_dynamic_spec(get_arg(ctx, ref.val.name)); - break; - } +template +FMT_CONSTEXPR int get_dynamic_spec( + arg_id_kind kind, const arg_ref& ref, + Context& ctx) { + FMT_ASSERT(kind != arg_id_kind::none, ""); + auto arg = + kind == arg_id_kind::index ? ctx.arg(ref.index) : ctx.arg(ref.name); + if (!arg) report_error("argument not found"); + unsigned long long value = arg.visit(dynamic_spec_getter()); + if (value > to_unsigned(max_value())) + report_error("width/precision is out of range"); + return static_cast(value); } -#if FMT_USE_USER_DEFINED_LITERALS -# if FMT_USE_NONTYPE_TEMPLATE_ARGS +template +FMT_CONSTEXPR void handle_dynamic_spec( + arg_id_kind kind, int& value, + const arg_ref& ref, Context& ctx) { + if (kind != arg_id_kind::none) value = get_dynamic_spec(kind, ref, ctx); +} + +#if FMT_USE_NONTYPE_TEMPLATE_ARGS template Str> -struct statically_named_arg : view { + fmt::detail::fixed_string Str> +struct static_named_arg : view { static constexpr auto name = Str.data; const T& value; - statically_named_arg(const T& v) : value(v) {} + static_named_arg(const T& v) : value(v) {} }; template Str> -struct is_named_arg> : std::true_type {}; + fmt::detail::fixed_string Str> +struct is_named_arg> : std::true_type {}; template Str> -struct is_statically_named_arg> - : std::true_type {}; + fmt::detail::fixed_string Str> +struct is_static_named_arg> : std::true_type { +}; -template Str> +template Str> struct udl_arg { template auto operator=(T&& value) const { - return statically_named_arg(std::forward(value)); + return static_named_arg(std::forward(value)); } }; -# else +#else template struct udl_arg { const Char* str; @@ -3896,149 +3584,198 @@ template struct udl_arg { return {str, std::forward(value)}; } }; -# endif -#endif // FMT_USE_USER_DEFINED_LITERALS +#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS -template -auto vformat(const Locale& loc, basic_string_view fmt, - basic_format_args>> args) - -> std::basic_string { - auto buf = basic_memory_buffer(); - detail::vformat_to(buf, fmt, args, detail::locale_ref(loc)); - return {buf.data(), buf.size()}; -} +template struct format_handler { + parse_context parse_ctx; + buffered_context ctx; + + void on_text(const Char* begin, const Char* end) { + copy_noinline(begin, end, ctx.out()); + } + + FMT_CONSTEXPR auto on_arg_id() -> int { return parse_ctx.next_arg_id(); } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + parse_ctx.check_arg_id(id); + return id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { + parse_ctx.check_arg_id(id); + int arg_id = ctx.arg_id(id); + if (arg_id < 0) report_error("argument not found"); + return arg_id; + } + + FMT_INLINE void on_replacement_field(int id, const Char*) { + ctx.arg(id).visit(default_arg_formatter{ctx.out()}); + } + + auto on_format_specs(int id, const Char* begin, const Char* end) + -> const Char* { + auto arg = get_arg(ctx, id); + // Not using a visitor for custom types gives better codegen. + if (arg.format_custom(begin, parse_ctx, ctx)) return parse_ctx.begin(); + + auto specs = dynamic_format_specs(); + begin = parse_format_specs(begin, end, specs, parse_ctx, arg.type()); + if (specs.dynamic()) { + handle_dynamic_spec(specs.dynamic_width(), specs.width, specs.width_ref, + ctx); + handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + } + + arg.visit(arg_formatter{ctx.out(), specs, ctx.locale()}); + return begin; + } + + FMT_NORETURN void on_error(const char* message) { report_error(message); } +}; using format_func = void (*)(detail::buffer&, int, const char*); +FMT_API void do_report_error(format_func func, int error_code, + const char* message) noexcept; FMT_API void format_error_code(buffer& out, int error_code, string_view message) noexcept; -FMT_API void report_error(format_func func, int error_code, - const char* message) noexcept; -} // namespace detail - -FMT_API auto vsystem_error(int error_code, string_view format_str, - format_args args) -> std::system_error; - -/** - \rst - Constructs :class:`std::system_error` with a message formatted with - ``fmt::format(fmt, args...)``. - *error_code* is a system error code as given by ``errno``. - - **Example**:: - - // This throws std::system_error with the description - // cannot open file 'madeup': No such file or directory - // or similar (system message may vary). - const char* filename = "madeup"; - std::FILE* file = std::fopen(filename, "r"); - if (!file) - throw fmt::system_error(errno, "cannot open file '{}'", filename); - \endrst - */ -template -auto system_error(int error_code, format_string fmt, T&&... args) - -> std::system_error { - return vsystem_error(error_code, fmt, fmt::make_format_args(args...)); +template +template +FMT_CONSTEXPR auto native_formatter::format( + const T& val, FormatContext& ctx) const -> decltype(ctx.out()) { + if (!specs_.dynamic()) + return write(ctx.out(), val, specs_, ctx.locale()); + auto specs = format_specs(specs_); + handle_dynamic_spec(specs.dynamic_width(), specs.width, specs_.width_ref, + ctx); + handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs_.precision_ref, ctx); + return write(ctx.out(), val, specs, ctx.locale()); } -/** - \rst - Formats an error message for an error returned by an operating system or a - language runtime, for example a file opening error, and writes it to *out*. - The format is the same as the one used by ``std::system_error(ec, message)`` - where ``ec`` is ``std::error_code(error_code, std::generic_category()})``. - It is implementation-defined but normally looks like: +// DEPRECATED! https://github.com/fmtlib/fmt/issues/4292. +template +struct is_locale : std::false_type {}; +template +struct is_locale> : std::true_type {}; - .. parsed-literal:: - **: ** +// DEPRECATED! +template struct vformat_args { + using type = basic_format_args>; +}; +template <> struct vformat_args { + using type = format_args; +}; - where ** is the passed message and ** is the system - message corresponding to the error code. - *error_code* is a system error code as given by ``errno``. - \endrst - */ -FMT_API void format_system_error(detail::buffer& out, int error_code, - const char* message) noexcept; +template +void vformat_to(buffer& buf, basic_string_view fmt, + typename vformat_args::type args, locale_ref loc = {}) { + auto out = basic_appender(buf); + parse_format_string( + fmt, format_handler{parse_context(fmt), {out, args, loc}}); +} +} // namespace detail -// Reports a system error without throwing an exception. -// Can be used to report errors from destructors. -FMT_API void report_system_error(int error_code, const char* message) noexcept; +FMT_BEGIN_EXPORT -/** Fast integer formatter. */ -class format_int { +// A generic formatting context with custom output iterator and character +// (code unit) support. Char is the format string code unit type which can be +// different from OutputIt::value_type. +template class generic_context { private: - // Buffer should be large enough to hold all digits (digits10 + 1), - // a sign and a null character. - enum { buffer_size = std::numeric_limits::digits10 + 3 }; - mutable char buffer_[buffer_size]; - char* str_; - - template auto format_unsigned(UInt value) -> char* { - auto n = static_cast>(value); - return detail::format_decimal(buffer_, n, buffer_size - 1).begin; - } - - template auto format_signed(Int value) -> char* { - auto abs_value = static_cast>(value); - bool negative = value < 0; - if (negative) abs_value = 0 - abs_value; - auto begin = format_unsigned(abs_value); - if (negative) *--begin = '-'; - return begin; - } + OutputIt out_; + basic_format_args args_; + detail::locale_ref loc_; public: - explicit format_int(int value) : str_(format_signed(value)) {} - explicit format_int(long value) : str_(format_signed(value)) {} - explicit format_int(long long value) : str_(format_signed(value)) {} - explicit format_int(unsigned value) : str_(format_unsigned(value)) {} - explicit format_int(unsigned long value) : str_(format_unsigned(value)) {} - explicit format_int(unsigned long long value) - : str_(format_unsigned(value)) {} + using char_type = Char; + using iterator = OutputIt; + using parse_context_type FMT_DEPRECATED = parse_context; + template + using formatter_type FMT_DEPRECATED = formatter; + enum { builtin_types = FMT_BUILTIN_TYPES }; - /** Returns the number of characters written to the output buffer. */ - auto size() const -> size_t { - return detail::to_unsigned(buffer_ - str_ + buffer_size - 1); + constexpr generic_context(OutputIt out, + basic_format_args args, + detail::locale_ref loc = {}) + : out_(out), args_(args), loc_(loc) {} + generic_context(generic_context&&) = default; + generic_context(const generic_context&) = delete; + void operator=(const generic_context&) = delete; + + constexpr auto arg(int id) const -> basic_format_arg { + return args_.get(id); + } + auto arg(basic_string_view name) const + -> basic_format_arg { + return args_.get(name); + } + constexpr auto arg_id(basic_string_view name) const -> int { + return args_.get_id(name); } - /** - Returns a pointer to the output buffer content. No terminating null - character is appended. - */ - auto data() const -> const char* { return str_; } + constexpr auto out() const -> iterator { return out_; } - /** - Returns a pointer to the output buffer content with terminating null - character appended. - */ - auto c_str() const -> const char* { - buffer_[buffer_size - 1] = '\0'; - return str_; + void advance_to(iterator it) { + if (!detail::is_back_insert_iterator()) out_ = it; } - /** - \rst - Returns the content of the output buffer as an ``std::string``. - \endrst - */ - auto str() const -> std::string { return std::string(str_, size()); } + constexpr auto locale() const -> detail::locale_ref { return loc_; } }; -template -struct formatter::value>> - : formatter, Char> { - template - auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) { - using base = formatter, Char>; - return base::format(format_as(value), ctx); +class loc_value { + private: + basic_format_arg value_; + + public: + template ::value)> + loc_value(T value) : value_(value) {} + + template ::value)> + loc_value(T) {} + + template auto visit(Visitor&& vis) -> decltype(vis(0)) { + return value_.visit(vis); } }; -#define FMT_FORMAT_AS(Type, Base) \ - template \ - struct formatter : formatter {} +// A locale facet that formats values in UTF-8. +// It is parameterized on the locale to avoid the heavy include. +template class format_facet : public Locale::facet { + private: + std::string separator_; + std::string grouping_; + std::string decimal_point_; + + protected: + virtual auto do_put(appender out, loc_value val, + const format_specs& specs) const -> bool; + + public: + static FMT_API typename Locale::id id; + + explicit format_facet(Locale& loc); + explicit format_facet(string_view sep = "", std::string grouping = "\3", + std::string decimal_point = ".") + : separator_(sep.data(), sep.size()), + grouping_(grouping), + decimal_point_(decimal_point) {} + + auto put(appender out, loc_value val, const format_specs& specs) const + -> bool { + return do_put(out, val, specs); + } +}; + +#define FMT_FORMAT_AS(Type, Base) \ + template \ + struct formatter : formatter { \ + template \ + FMT_CONSTEXPR auto format(Type value, FormatContext& ctx) const \ + -> decltype(ctx.out()) { \ + return formatter::format(value, ctx); \ + } \ + } FMT_FORMAT_AS(signed char, int); FMT_FORMAT_AS(unsigned char, unsigned); @@ -4047,44 +3784,58 @@ FMT_FORMAT_AS(unsigned short, unsigned); FMT_FORMAT_AS(long, detail::long_type); FMT_FORMAT_AS(unsigned long, detail::ulong_type); FMT_FORMAT_AS(Char*, const Char*); -FMT_FORMAT_AS(std::basic_string, basic_string_view); -FMT_FORMAT_AS(std::nullptr_t, const void*); FMT_FORMAT_AS(detail::std_string_view, basic_string_view); +FMT_FORMAT_AS(std::nullptr_t, const void*); FMT_FORMAT_AS(void*, const void*); template struct formatter : formatter, Char> {}; +template +class formatter, Char> + : public formatter, Char> {}; + +template +struct formatter, Char> : formatter {}; +template +struct formatter, Char> + : formatter {}; + +template +struct formatter + : detail::native_formatter {}; + +template +struct formatter>> + : formatter, Char> { + template + FMT_CONSTEXPR auto format(const T& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto&& val = format_as(value); // Make an lvalue reference for format. + return formatter, Char>::format(val, ctx); + } +}; + /** - \rst - Converts ``p`` to ``const void*`` for pointer formatting. - - **Example**:: - - auto s = fmt::format("{}", fmt::ptr(p)); - \endrst + * Converts `p` to `const void*` for pointer formatting. + * + * **Example**: + * + * auto s = fmt::format("{}", fmt::ptr(p)); */ template auto ptr(T p) -> const void* { static_assert(std::is_pointer::value, ""); return detail::bit_cast(p); } -template -auto ptr(const std::unique_ptr& p) -> const void* { - return p.get(); -} -template auto ptr(const std::shared_ptr& p) -> const void* { - return p.get(); -} /** - \rst - Converts ``e`` to the underlying type. - - **Example**:: - - enum class color { red, green, blue }; - auto s = fmt::format("{}", fmt::underlying(color::red)); - \endrst + * Converts `e` to the underlying type. + * + * **Example**: + * + * enum class color { red, green, blue }; + * auto s = fmt::format("{}", fmt::underlying(color::red)); // s == "0" */ template constexpr auto underlying(Enum e) noexcept -> underlying_t { @@ -4098,13 +3849,22 @@ constexpr auto format_as(Enum e) noexcept -> underlying_t { } } // namespace enums -class bytes { - private: - string_view data_; - friend struct formatter; +#ifdef __cpp_lib_byte +template <> struct formatter : formatter { + static auto format_as(std::byte b) -> unsigned char { + return static_cast(b); + } + template + auto format(std::byte b, Context& ctx) const -> decltype(ctx.out()) { + return formatter::format(format_as(b), ctx); + } +}; +#endif - public: - explicit bytes(string_view data) : data_(data) {} +struct bytes { + string_view data; + + inline explicit bytes(string_view s) : data(s) {} }; template <> struct formatter { @@ -4112,19 +3872,19 @@ template <> struct formatter { detail::dynamic_format_specs<> specs_; public: - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const char* { + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, detail::type::string_type); } template - auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) { - detail::handle_dynamic_spec(specs_.width, - specs_.width_ref, ctx); - detail::handle_dynamic_spec( - specs_.precision, specs_.precision_ref, ctx); - return detail::write_bytes(ctx.out(), b.data_, specs_); + auto format(bytes b, FormatContext& ctx) const -> decltype(ctx.out()) { + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + return detail::write_bytes(ctx.out(), b.data, specs); } }; @@ -4134,15 +3894,13 @@ template struct group_digits_view { }; /** - \rst - Returns a view that formats an integer value using ',' as a locale-independent - thousands separator. - - **Example**:: - - fmt::print("{}", fmt::group_digits(12345)); - // Output: "12,345" - \endrst + * Returns a view that formats an integer value using ',' as a + * locale-independent thousands separator. + * + * **Example**: + * + * fmt::print("{}", fmt::group_digits(12345)); + * // Output: "12,345" */ template auto group_digits(T value) -> group_digits_view { return {value}; @@ -4153,331 +3911,255 @@ template struct formatter> : formatter { detail::dynamic_format_specs<> specs_; public: - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const char* { + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, detail::type::int_type); } template - auto format(group_digits_view t, FormatContext& ctx) + auto format(group_digits_view view, FormatContext& ctx) const -> decltype(ctx.out()) { - detail::handle_dynamic_spec(specs_.width, - specs_.width_ref, ctx); - detail::handle_dynamic_spec( - specs_.precision, specs_.precision_ref, ctx); + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + auto arg = detail::make_write_int_arg(view.value, specs.sign()); return detail::write_int( - ctx.out(), static_cast>(t.value), 0, specs_, - detail::digit_grouping("\3", ",")); + ctx.out(), static_cast>(arg.abs_value), + arg.prefix, specs, detail::digit_grouping("\3", ",")); } }; -template struct nested_view { - const formatter* fmt; +template struct nested_view { + const formatter* fmt; const T* value; }; -template struct formatter> { - FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> const char* { +template +struct formatter, Char> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { return ctx.begin(); } - auto format(nested_view view, format_context& ctx) const + template + auto format(nested_view view, FormatContext& ctx) const -> decltype(ctx.out()) { return view.fmt->format(*view.value, ctx); } }; -template struct nested_formatter { +template struct nested_formatter { private: + basic_specs specs_; int width_; - detail::fill_t fill_; - align_t align_ : 4; - formatter formatter_; + formatter formatter_; public: - constexpr nested_formatter() : width_(0), align_(align_t::none) {} + constexpr nested_formatter() : width_(0) {} - FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> const char* { - auto specs = detail::dynamic_format_specs(); - auto it = parse_format_specs(ctx.begin(), ctx.end(), specs, ctx, - detail::type::none_type); - width_ = specs.width; - fill_ = specs.fill; - align_ = specs.align; + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + auto specs = format_specs(); + it = detail::parse_align(it, end, specs); + specs_ = specs; + Char c = *it; + auto width_ref = detail::arg_ref(); + if ((c >= '0' && c <= '9') || c == '{') { + it = detail::parse_width(it, end, specs, width_ref, ctx); + width_ = specs.width; + } ctx.advance_to(it); return formatter_.parse(ctx); } - template - auto write_padded(format_context& ctx, F write) const -> decltype(ctx.out()) { + template + auto write_padded(FormatContext& ctx, F write) const -> decltype(ctx.out()) { if (width_ == 0) return write(ctx.out()); - auto buf = memory_buffer(); - write(std::back_inserter(buf)); - auto specs = format_specs<>(); + auto buf = basic_memory_buffer(); + write(basic_appender(buf)); + auto specs = format_specs(); specs.width = width_; - specs.fill = fill_; - specs.align = align_; - return detail::write(ctx.out(), string_view(buf.data(), buf.size()), specs); + specs.copy_fill_from(specs_); + specs.set_align(specs_.align()); + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); } - auto nested(const T& value) const -> nested_view { - return nested_view{&formatter_, &value}; + auto nested(const T& value) const -> nested_view { + return nested_view{&formatter_, &value}; } }; -// DEPRECATED! join_view will be moved to ranges.h. -template -struct join_view : detail::view { - It begin; - Sentinel end; - basic_string_view sep; - - join_view(It b, Sentinel e, basic_string_view s) - : begin(b), end(e), sep(s) {} -}; - -template -struct formatter, Char> { - private: - using value_type = -#ifdef __cpp_lib_ranges - std::iter_value_t; -#else - typename std::iterator_traits::value_type; -#endif - formatter, Char> value_formatter_; - - public: - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const Char* { - return value_formatter_.parse(ctx); - } - - template - auto format(const join_view& value, - FormatContext& ctx) const -> decltype(ctx.out()) { - auto it = value.begin; - auto out = ctx.out(); - if (it != value.end) { - out = value_formatter_.format(*it, ctx); - ++it; - while (it != value.end) { - out = detail::copy_str(value.sep.begin(), value.sep.end(), out); - ctx.advance_to(out); - out = value_formatter_.format(*it, ctx); - ++it; - } - } - return out; - } -}; - -/** - Returns a view that formats the iterator range `[begin, end)` with elements - separated by `sep`. - */ -template -auto join(It begin, Sentinel end, string_view sep) -> join_view { - return {begin, end, sep}; -} - -/** - \rst - Returns a view that formats `range` with elements separated by `sep`. - - **Example**:: - - std::vector v = {1, 2, 3}; - fmt::print("{}", fmt::join(v, ", ")); - // Output: "1, 2, 3" - - ``fmt::join`` applies passed format specifiers to the range elements:: - - fmt::print("{:02}", fmt::join(v, ", ")); - // Output: "01, 02, 03" - \endrst - */ -template -auto join(Range&& range, string_view sep) - -> join_view, detail::sentinel_t> { - return join(std::begin(range), std::end(range), sep); -} - -/** - \rst - Converts *value* to ``std::string`` using the default format for type *T*. - - **Example**:: - - #include - - std::string answer = fmt::to_string(42); - \endrst - */ -template ::value && - !detail::has_format_as::value)> -inline auto to_string(const T& value) -> std::string { - auto buffer = memory_buffer(); - detail::write(appender(buffer), value); - return {buffer.data(), buffer.size()}; -} - -template ::value)> -FMT_NODISCARD inline auto to_string(T value) -> std::string { - // The buffer should be large enough to store the number including the sign - // or "false" for bool. - constexpr int max_size = detail::digits10() + 2; - char buffer[max_size > 5 ? static_cast(max_size) : 5]; - char* begin = buffer; - return std::string(begin, detail::write(begin, value)); -} - -template -FMT_NODISCARD auto to_string(const basic_memory_buffer& buf) - -> std::basic_string { - auto size = buf.size(); - detail::assume(size < std::basic_string().max_size()); - return std::basic_string(buf.data(), size); -} - -template ::value && - detail::has_format_as::value)> -inline auto to_string(const T& value) -> std::string { - return to_string(format_as(value)); -} - -FMT_END_EXPORT - -namespace detail { - -template -void vformat_to(buffer& buf, basic_string_view fmt, - typename vformat_args::type args, locale_ref loc) { - auto out = buffer_appender(buf); - if (fmt.size() == 2 && equal2(fmt.data(), "{}")) { - auto arg = args.get(0); - if (!arg) throw_format_error("argument not found"); - visit_format_arg(default_arg_formatter{out, args, loc}, arg); - return; - } - - struct format_handler : error_handler { - basic_format_parse_context parse_context; - buffer_context context; - - format_handler(buffer_appender p_out, basic_string_view str, - basic_format_args> p_args, - locale_ref p_loc) - : parse_context(str), context(p_out, p_args, p_loc) {} - - void on_text(const Char* begin, const Char* end) { - auto text = basic_string_view(begin, to_unsigned(end - begin)); - context.advance_to(write(context.out(), text)); - } - - FMT_CONSTEXPR auto on_arg_id() -> int { - return parse_context.next_arg_id(); - } - FMT_CONSTEXPR auto on_arg_id(int id) -> int { - return parse_context.check_arg_id(id), id; - } - FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { - int arg_id = context.arg_id(id); - if (arg_id < 0) throw_format_error("argument not found"); - return arg_id; - } - - FMT_INLINE void on_replacement_field(int id, const Char*) { - auto arg = get_arg(context, id); - context.advance_to(visit_format_arg( - default_arg_formatter{context.out(), context.args(), - context.locale()}, - arg)); - } - - auto on_format_specs(int id, const Char* begin, const Char* end) - -> const Char* { - auto arg = get_arg(context, id); - // Not using a visitor for custom types gives better codegen. - if (arg.format_custom(begin, parse_context, context)) - return parse_context.begin(); - auto specs = detail::dynamic_format_specs(); - begin = parse_format_specs(begin, end, specs, parse_context, arg.type()); - detail::handle_dynamic_spec( - specs.width, specs.width_ref, context); - detail::handle_dynamic_spec( - specs.precision, specs.precision_ref, context); - if (begin == end || *begin != '}') - throw_format_error("missing '}' in format string"); - auto f = arg_formatter{context.out(), specs, context.locale()}; - context.advance_to(visit_format_arg(f, arg)); - return begin; - } - }; - detail::parse_format_string(fmt, format_handler(out, fmt, args, loc)); -} - -FMT_BEGIN_EXPORT - -#ifndef FMT_HEADER_ONLY -extern template FMT_API void vformat_to(buffer&, string_view, - typename vformat_args<>::type, - locale_ref); -extern template FMT_API auto thousands_sep_impl(locale_ref) - -> thousands_sep_result; -extern template FMT_API auto thousands_sep_impl(locale_ref) - -> thousands_sep_result; -extern template FMT_API auto decimal_point_impl(locale_ref) -> char; -extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t; -#endif // FMT_HEADER_ONLY - -} // namespace detail - -#if FMT_USE_USER_DEFINED_LITERALS inline namespace literals { -/** - \rst - User-defined literal equivalent of :func:`fmt::arg`. - - **Example**:: - - using namespace fmt::literals; - fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); - \endrst - */ -# if FMT_USE_NONTYPE_TEMPLATE_ARGS -template constexpr auto operator""_a() { - using char_t = remove_cvref_t; - return detail::udl_arg(); +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template constexpr auto operator""_a() { + using char_t = remove_cvref_t; + return detail::udl_arg(); } -# else +#else +/** + * User-defined literal equivalent of `fmt::arg`. + * + * **Example**: + * + * using namespace fmt::literals; + * fmt::print("The answer is {answer}.", "answer"_a=42); + */ constexpr auto operator""_a(const char* s, size_t) -> detail::udl_arg { return {s}; } -# endif +#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS } // namespace literals -#endif // FMT_USE_USER_DEFINED_LITERALS + +/// A fast integer formatter. +class format_int { + private: + // Buffer should be large enough to hold all digits (digits10 + 1), + // a sign and a null character. + enum { buffer_size = std::numeric_limits::digits10 + 3 }; + mutable char buffer_[buffer_size]; + char* str_; + + template + FMT_CONSTEXPR20 auto format_unsigned(UInt value) -> char* { + auto n = static_cast>(value); + return detail::do_format_decimal(buffer_, n, buffer_size - 1); + } + + template + FMT_CONSTEXPR20 auto format_signed(Int value) -> char* { + auto abs_value = static_cast>(value); + bool negative = value < 0; + if (negative) abs_value = 0 - abs_value; + auto begin = format_unsigned(abs_value); + if (negative) *--begin = '-'; + return begin; + } + + public: + FMT_CONSTEXPR20 explicit format_int(int value) : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(long value) + : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(long long value) + : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned value) + : str_(format_unsigned(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned long value) + : str_(format_unsigned(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned long long value) + : str_(format_unsigned(value)) {} + + /// Returns the number of characters written to the output buffer. + FMT_CONSTEXPR20 auto size() const -> size_t { + return detail::to_unsigned(buffer_ - str_ + buffer_size - 1); + } + + /// Returns a pointer to the output buffer content. No terminating null + /// character is appended. + FMT_CONSTEXPR20 auto data() const -> const char* { return str_; } + + /// Returns a pointer to the output buffer content with terminating null + /// character appended. + FMT_CONSTEXPR20 auto c_str() const -> const char* { + buffer_[buffer_size - 1] = '\0'; + return str_; + } + + /// Returns the content of the output buffer as an `std::string`. + inline auto str() const -> std::string { return {str_, size()}; } +}; + +#define FMT_STRING_IMPL(s, base) \ + [] { \ + /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \ + /* Use a macro-like name to avoid shadowing warnings. */ \ + struct FMT_VISIBILITY("hidden") FMT_COMPILE_STRING : base { \ + using char_type = fmt::remove_cvref_t; \ + constexpr explicit operator fmt::basic_string_view() const { \ + return fmt::detail::compile_string_to_view(s); \ + } \ + }; \ + using FMT_STRING_VIEW = \ + fmt::basic_string_view; \ + fmt::detail::ignore_unused(FMT_STRING_VIEW(FMT_COMPILE_STRING())); \ + return FMT_COMPILE_STRING(); \ + }() + +/** + * Constructs a legacy compile-time format string from a string literal `s`. + * + * **Example**: + * + * // A compile-time error because 'd' is an invalid specifier for strings. + * std::string s = fmt::format(FMT_STRING("{:d}"), "foo"); + */ +#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string) + +FMT_API auto vsystem_error(int error_code, string_view fmt, format_args args) + -> std::system_error; + +/** + * Constructs `std::system_error` with a message formatted with + * `fmt::format(fmt, args...)`. + * `error_code` is a system error code as given by `errno`. + * + * **Example**: + * + * // This throws std::system_error with the description + * // cannot open file 'madeup': No such file or directory + * // or similar (system message may vary). + * const char* filename = "madeup"; + * FILE* file = fopen(filename, "r"); + * if (!file) + * throw fmt::system_error(errno, "cannot open file '{}'", filename); + */ +template +auto system_error(int error_code, format_string fmt, T&&... args) + -> std::system_error { + return vsystem_error(error_code, fmt.str, vargs{{args...}}); +} + +/** + * Formats an error message for an error returned by an operating system or a + * language runtime, for example a file opening error, and writes it to `out`. + * The format is the same as the one used by `std::system_error(ec, message)` + * where `ec` is `std::error_code(error_code, std::generic_category())`. + * It is implementation-defined but normally looks like: + * + * : + * + * where `` is the passed message and `` is the system + * message corresponding to the error code. + * `error_code` is a system error code as given by `errno`. + */ +FMT_API void format_system_error(detail::buffer& out, int error_code, + const char* message) noexcept; + +// Reports a system error without throwing an exception. +// Can be used to report errors from destructors. +FMT_API void report_system_error(int error_code, const char* message) noexcept; template ::value)> inline auto vformat(const Locale& loc, string_view fmt, format_args args) -> std::string { - return detail::vformat(loc, fmt, args); + auto buf = memory_buffer(); + detail::vformat_to(buf, fmt, args, detail::locale_ref(loc)); + return {buf.data(), buf.size()}; } template ::value)> -inline auto format(const Locale& loc, format_string fmt, T&&... args) +FMT_INLINE auto format(const Locale& loc, format_string fmt, T&&... args) -> std::string { - return fmt::vformat(loc, string_view(fmt), fmt::make_format_args(args...)); + return vformat(loc, fmt.str, vargs{{args...}}); } template ::value&& - detail::is_locale::value)> + FMT_ENABLE_IF(detail::is_output_iterator::value)> auto vformat_to(OutputIt out, const Locale& loc, string_view fmt, format_args args) -> OutputIt { - using detail::get_buffer; - auto&& buf = get_buffer(out); + auto&& buf = detail::get_buffer(out); detail::vformat_to(buf, fmt, args, detail::locale_ref(loc)); return detail::get_iterator(buf, out); } @@ -4487,7 +4169,7 @@ template ::value)> FMT_INLINE auto format_to(OutputIt out, const Locale& loc, format_string fmt, T&&... args) -> OutputIt { - return vformat_to(out, loc, fmt, fmt::make_format_args(args...)); + return fmt::vformat_to(out, loc, fmt.str, vargs{{args...}}); } template fmt, T&&... args) -> size_t { auto buf = detail::counting_buffer<>(); - detail::vformat_to(buf, fmt, fmt::make_format_args(args...), - detail::locale_ref(loc)); + detail::vformat_to(buf, fmt.str, vargs{{args...}}, + detail::locale_ref(loc)); return buf.count(); } -FMT_END_EXPORT +FMT_API auto vformat(string_view fmt, format_args args) -> std::string; -template -template -FMT_CONSTEXPR FMT_INLINE auto -formatter::value != - detail::type::custom_type>>::format(const T& val, - FormatContext& ctx) - const -> decltype(ctx.out()) { - if (specs_.width_ref.kind == detail::arg_id_kind::none && - specs_.precision_ref.kind == detail::arg_id_kind::none) { - return detail::write(ctx.out(), val, specs_, ctx.locale()); - } - auto specs = specs_; - detail::handle_dynamic_spec(specs.width, - specs.width_ref, ctx); - detail::handle_dynamic_spec( - specs.precision, specs.precision_ref, ctx); - return detail::write(ctx.out(), val, specs, ctx.locale()); +/** + * Formats `args` according to specifications in `fmt` and returns the result + * as a string. + * + * **Example**: + * + * #include + * std::string message = fmt::format("The answer is {}.", 42); + */ +template +FMT_NODISCARD FMT_INLINE auto format(format_string fmt, T&&... args) + -> std::string { + return vformat(fmt.str, vargs{{args...}}); } +/** + * Converts `value` to `std::string` using the default format for type `T`. + * + * **Example**: + * + * std::string answer = fmt::to_string(42); + */ +template ::value)> +FMT_NODISCARD auto to_string(T value) -> std::string { + // The buffer should be large enough to store the number including the sign + // or "false" for bool. + char buffer[max_of(detail::digits10() + 2, 5)]; + return {buffer, detail::write(buffer, value)}; +} + +template ::value)> +FMT_NODISCARD auto to_string(const T& value) -> std::string { + return to_string(format_as(value)); +} + +template ::value && + !detail::use_format_as::value)> +FMT_NODISCARD auto to_string(const T& value) -> std::string { + auto buffer = memory_buffer(); + detail::write(appender(buffer), value); + return {buffer.data(), buffer.size()}; +} + +FMT_END_EXPORT FMT_END_NAMESPACE #ifdef FMT_HEADER_ONLY # define FMT_FUNC inline # include "format-inl.h" -#else -# define FMT_FUNC +#endif + +// Restore _LIBCPP_REMOVE_TRANSITIVE_INCLUDES. +#ifdef FMT_REMOVE_TRANSITIVE_INCLUDES +# undef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES #endif #endif // FMT_FORMAT_H_ diff --git a/third-party/fmt/include/fmt/os.h b/third-party/fmt/include/fmt/os.h index 3c7b3ccb48..b2cc5e4b85 100644 --- a/third-party/fmt/include/fmt/os.h +++ b/third-party/fmt/include/fmt/os.h @@ -8,18 +8,18 @@ #ifndef FMT_OS_H_ #define FMT_OS_H_ -#include -#include -#include -#include // std::system_error - #include "format.h" -#if defined __APPLE__ || defined(__FreeBSD__) +#ifndef FMT_MODULE +# include +# include +# include +# include // std::system_error + # if FMT_HAS_INCLUDE() -# include // for LC_NUMERIC_MASK on OS X +# include // LC_NUMERIC_MASK on macOS # endif -#endif +#endif // FMT_MODULE #ifndef FMT_USE_FCNTL // UWP doesn't provide _pipe. @@ -77,46 +77,33 @@ FMT_BEGIN_NAMESPACE FMT_BEGIN_EXPORT /** - \rst - A reference to a null-terminated string. It can be constructed from a C - string or ``std::string``. - - You can use one of the following type aliases for common character types: - - +---------------+-----------------------------+ - | Type | Definition | - +===============+=============================+ - | cstring_view | basic_cstring_view | - +---------------+-----------------------------+ - | wcstring_view | basic_cstring_view | - +---------------+-----------------------------+ - - This class is most useful as a parameter type to allow passing - different types of strings to a function, for example:: - - template - std::string format(cstring_view format_str, const Args & ... args); - - format("{}", 42); - format(std::string("{}"), 42); - \endrst + * A reference to a null-terminated string. It can be constructed from a C + * string or `std::string`. + * + * You can use one of the following type aliases for common character types: + * + * +---------------+-----------------------------+ + * | Type | Definition | + * +===============+=============================+ + * | cstring_view | basic_cstring_view | + * +---------------+-----------------------------+ + * | wcstring_view | basic_cstring_view | + * +---------------+-----------------------------+ + * + * This class is most useful as a parameter type for functions that wrap C APIs. */ template class basic_cstring_view { private: const Char* data_; public: - /** Constructs a string reference object from a C string. */ + /// Constructs a string reference object from a C string. basic_cstring_view(const Char* s) : data_(s) {} - /** - \rst - Constructs a string reference from an ``std::string`` object. - \endrst - */ + /// Constructs a string reference from an `std::string` object. basic_cstring_view(const std::basic_string& s) : data_(s.c_str()) {} - /** Returns the pointer to a C string. */ + /// Returns the pointer to a C string. auto c_str() const -> const Char* { return data_; } }; @@ -131,41 +118,38 @@ FMT_API void format_windows_error(buffer& out, int error_code, const char* message) noexcept; } -FMT_API std::system_error vwindows_error(int error_code, string_view format_str, +FMT_API std::system_error vwindows_error(int error_code, string_view fmt, format_args args); /** - \rst - Constructs a :class:`std::system_error` object with the description - of the form - - .. parsed-literal:: - **: ** - - where ** is the formatted message and ** is the - system message corresponding to the error code. - *error_code* is a Windows error code as given by ``GetLastError``. - If *error_code* is not a valid error code such as -1, the system message - will look like "error -1". - - **Example**:: - - // This throws a system_error with the description - // cannot open file 'madeup': The system cannot find the file specified. - // or similar (system message may vary). - const char *filename = "madeup"; - LPOFSTRUCT of = LPOFSTRUCT(); - HFILE file = OpenFile(filename, &of, OF_READ); - if (file == HFILE_ERROR) { - throw fmt::windows_error(GetLastError(), - "cannot open file '{}'", filename); - } - \endrst -*/ -template -std::system_error windows_error(int error_code, string_view message, - const Args&... args) { - return vwindows_error(error_code, message, fmt::make_format_args(args...)); + * Constructs a `std::system_error` object with the description of the form + * + * : + * + * where `` is the formatted message and `` is the + * system message corresponding to the error code. + * `error_code` is a Windows error code as given by `GetLastError`. + * If `error_code` is not a valid error code such as -1, the system message + * will look like "error -1". + * + * **Example**: + * + * // This throws a system_error with the description + * // cannot open file 'madeup': The system cannot find the file + * specified. + * // or similar (system message may vary). + * const char *filename = "madeup"; + * LPOFSTRUCT of = LPOFSTRUCT(); + * HFILE file = OpenFile(filename, &of, OF_READ); + * if (file == HFILE_ERROR) { + * throw fmt::windows_error(GetLastError(), + * "cannot open file '{}'", filename); + * } + */ +template +auto windows_error(int error_code, string_view message, const T&... args) + -> std::system_error { + return vwindows_error(error_code, message, vargs{{args...}}); } // Reports a Windows error without throwing an exception. @@ -180,8 +164,8 @@ inline auto system_category() noexcept -> const std::error_category& { // std::system is not available on some platforms such as iOS (#2248). #ifdef __OSX__ template > -void say(const S& format_str, Args&&... args) { - std::system(format("say \"{}\"", format(format_str, args...)).c_str()); +void say(const S& fmt, Args&&... args) { + std::system(format("say \"{}\"", format(fmt, args...)).c_str()); } #endif @@ -192,24 +176,24 @@ class buffered_file { friend class file; - explicit buffered_file(FILE* f) : file_(f) {} + inline explicit buffered_file(FILE* f) : file_(f) {} public: buffered_file(const buffered_file&) = delete; void operator=(const buffered_file&) = delete; // Constructs a buffered_file object which doesn't represent any file. - buffered_file() noexcept : file_(nullptr) {} + inline buffered_file() noexcept : file_(nullptr) {} // Destroys the object closing the file it represents if any. FMT_API ~buffered_file() noexcept; public: - buffered_file(buffered_file&& other) noexcept : file_(other.file_) { + inline buffered_file(buffered_file&& other) noexcept : file_(other.file_) { other.file_ = nullptr; } - auto operator=(buffered_file&& other) -> buffered_file& { + inline auto operator=(buffered_file&& other) -> buffered_file& { close(); file_ = other.file_; other.file_ = nullptr; @@ -223,21 +207,20 @@ class buffered_file { FMT_API void close(); // Returns the pointer to a FILE object representing this file. - auto get() const noexcept -> FILE* { return file_; } + inline auto get() const noexcept -> FILE* { return file_; } FMT_API auto descriptor() const -> int; - void vprint(string_view format_str, format_args args) { - fmt::vprint(file_, format_str, args); - } - - template - inline void print(string_view format_str, const Args&... args) { - vprint(format_str, fmt::make_format_args(args...)); + template + inline void print(string_view fmt, const T&... args) { + fmt::vargs vargs = {{args...}}; + detail::is_locking() ? fmt::vprint_buffered(file_, fmt, vargs) + : fmt::vprint(file_, fmt, vargs); } }; #if FMT_USE_FCNTL + // A file. Closed file is represented by a file object with descriptor -1. // Methods that are not declared with noexcept may throw // fmt::system_error in case of failure. Note that some errors such as @@ -251,6 +234,8 @@ class FMT_API file { // Constructs a file object with a given descriptor. explicit file(int fd) : fd_(fd) {} + friend struct pipe; + public: // Possible values for the oflag argument to the constructor. enum { @@ -263,7 +248,7 @@ class FMT_API file { }; // Constructs a file object which doesn't represent any file. - file() noexcept : fd_(-1) {} + inline file() noexcept : fd_(-1) {} // Opens a file and constructs a file object representing this file. file(cstring_view path, int oflag); @@ -272,10 +257,10 @@ class FMT_API file { file(const file&) = delete; void operator=(const file&) = delete; - file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; } + inline file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; } // Move assignment is not noexcept because close may throw. - auto operator=(file&& other) -> file& { + inline auto operator=(file&& other) -> file& { close(); fd_ = other.fd_; other.fd_ = -1; @@ -286,7 +271,7 @@ class FMT_API file { ~file() noexcept; // Returns the file descriptor. - auto descriptor() const noexcept -> int { return fd_; } + inline auto descriptor() const noexcept -> int { return fd_; } // Closes the file. void close(); @@ -313,11 +298,6 @@ class FMT_API file { // necessary. void dup2(int fd, std::error_code& ec) noexcept; - // Creates a pipe setting up read_end and write_end file objects for reading - // and writing respectively. - // DEPRECATED! Taking files as out parameters is deprecated. - 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. auto fdopen(const char* mode) -> buffered_file; @@ -329,15 +309,24 @@ class FMT_API file { # endif }; +struct FMT_API pipe { + file read_end; + file write_end; + + // Creates a pipe setting up read_end and write_end file objects for reading + // and writing respectively. + pipe(); +}; + // Returns the memory page size. auto getpagesize() -> long; namespace detail { struct buffer_size { - buffer_size() = default; + constexpr buffer_size() = default; size_t value = 0; - auto operator=(size_t val) const -> buffer_size { + FMT_CONSTEXPR auto operator=(size_t val) const -> buffer_size { auto bs = buffer_size(); bs.value = val; return bs; @@ -348,7 +337,7 @@ struct ostream_params { int oflag = file::WRONLY | file::CREATE | file::TRUNC; size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768; - ostream_params() {} + constexpr ostream_params() {} template ostream_params(T... params, int new_oflag) : ostream_params(params...) { @@ -369,79 +358,62 @@ struct ostream_params { # endif }; -class file_buffer final : public buffer { +} // namespace detail + +FMT_INLINE_VARIABLE constexpr auto buffer_size = detail::buffer_size(); + +/// A fast buffered output stream for writing from a single thread. Writing from +/// multiple threads without external synchronization may result in a data race. +class FMT_API ostream : private detail::buffer { + private: file file_; - FMT_API void grow(size_t) override; + ostream(cstring_view path, const detail::ostream_params& params); + + static void grow(buffer& buf, size_t); public: - FMT_API file_buffer(cstring_view path, const ostream_params& params); - FMT_API file_buffer(file_buffer&& other); - FMT_API ~file_buffer(); + ostream(ostream&& other) noexcept; + ~ostream(); - void flush() { + operator writer() { + detail::buffer& buf = *this; + return buf; + } + + inline void flush() { if (size() == 0) return; file_.write(data(), size() * sizeof(data()[0])); clear(); } - void close() { - flush(); - file_.close(); - } -}; - -} // namespace detail - -// Added {} below to work around default constructor error known to -// occur in Xcode versions 7.2.1 and 8.2.1. -constexpr detail::buffer_size buffer_size{}; - -/** A fast output stream which is not thread-safe. */ -class FMT_API ostream { - private: - FMT_MSC_WARNING(suppress : 4251) - detail::file_buffer buffer_; - - ostream(cstring_view path, const detail::ostream_params& params) - : buffer_(path, params) {} - - public: - ostream(ostream&& other) : buffer_(std::move(other.buffer_)) {} - - ~ostream(); - - void flush() { buffer_.flush(); } - template friend auto output_file(cstring_view path, T... params) -> ostream; - void close() { buffer_.close(); } + inline void close() { + flush(); + file_.close(); + } - /** - Formats ``args`` according to specifications in ``fmt`` and writes the - output to the file. - */ + /// Formats `args` according to specifications in `fmt` and writes the + /// output to the file. template void print(format_string fmt, T&&... args) { - vformat_to(std::back_inserter(buffer_), fmt, - fmt::make_format_args(args...)); + vformat_to(appender(*this), fmt.str, vargs{{args...}}); } }; /** - \rst - Opens a file for writing. Supported parameters passed in *params*: - - * ````: Flags passed to `open - `_ - (``file::WRONLY | file::CREATE | file::TRUNC`` by default) - * ``buffer_size=``: Output buffer size - - **Example**:: - - auto out = fmt::output_file("guide.txt"); - out.print("Don't {}", "Panic"); - \endrst + * Opens a file for writing. Supported parameters passed in `params`: + * + * - ``: Flags passed to [open]( + * https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html) + * (`file::WRONLY | file::CREATE | file::TRUNC` by default) + * - `buffer_size=`: Output buffer size + * + * **Example**: + * + * auto out = fmt::output_file("guide.txt"); + * out.print("Don't {}", "Panic"); */ template inline auto output_file(cstring_view path, T... params) -> ostream { diff --git a/third-party/fmt/include/fmt/ostream.h b/third-party/fmt/include/fmt/ostream.h index 26fb3b5ac0..71fd6c887e 100644 --- a/third-party/fmt/include/fmt/ostream.h +++ b/third-party/fmt/include/fmt/ostream.h @@ -8,7 +8,9 @@ #ifndef FMT_OSTREAM_H_ #define FMT_OSTREAM_H_ -#include // std::filebuf +#ifndef FMT_MODULE +# include // std::filebuf +#endif #ifdef _WIN32 # ifdef __GLIBCXX__ @@ -18,42 +20,19 @@ # include #endif -#include "format.h" +#include "chrono.h" // formatbuf + +#ifdef _MSVC_STL_UPDATE +# define FMT_MSVC_STL_UPDATE _MSVC_STL_UPDATE +#elif defined(_MSC_VER) && _MSC_VER < 1912 // VS 15.5 +# define FMT_MSVC_STL_UPDATE _MSVC_LANG +#else +# define FMT_MSVC_STL_UPDATE 0 +#endif FMT_BEGIN_NAMESPACE namespace detail { -template class formatbuf : public Streambuf { - private: - using char_type = typename Streambuf::char_type; - using streamsize = decltype(std::declval().sputn(nullptr, 0)); - using int_type = typename Streambuf::int_type; - using traits_type = typename Streambuf::traits_type; - - buffer& buffer_; - - public: - explicit formatbuf(buffer& buf) : buffer_(buf) {} - - protected: - // The put area is always empty. This makes the implementation simpler and has - // the advantage that the streambuf and the buffer are always in sync and - // sputc never writes into uninitialized memory. A disadvantage is that each - // call to sputc always results in a (virtual) call to overflow. There is no - // disadvantage here for sputn since this always results in a call to xsputn. - - auto overflow(int_type ch) -> int_type override { - if (!traits_type::eq_int_type(ch, traits_type::eof())) - buffer_.push_back(static_cast(ch)); - return ch; - } - - auto xsputn(const char_type* s, streamsize count) -> streamsize override { - buffer_.append(s, s + count); - return count; - } -}; - // Generate a unique explicit instantion in every translation unit using a tag // type in an anonymous namespace. namespace { @@ -64,53 +43,18 @@ class file_access { friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; } }; -#if FMT_MSC_VERSION +#if FMT_MSVC_STL_UPDATE template class file_access; auto get_file(std::filebuf&) -> FILE*; #endif -inline auto write_ostream_unicode(std::ostream& os, fmt::string_view data) - -> bool { - FILE* f = nullptr; -#if FMT_MSC_VERSION - if (auto* buf = dynamic_cast(os.rdbuf())) - f = get_file(*buf); - else - return false; -#elif defined(_WIN32) && defined(__GLIBCXX__) - auto* rdbuf = os.rdbuf(); - if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf*>(rdbuf)) - f = sfbuf->file(); - else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf*>(rdbuf)) - f = fbuf->file(); - else - return false; -#else - ignore_unused(os, data, f); -#endif -#ifdef _WIN32 - if (f) { - int fd = _fileno(f); - if (_isatty(fd)) { - os.flush(); - return write_console(fd, data); - } - } -#endif - return false; -} -inline auto write_ostream_unicode(std::wostream&, - fmt::basic_string_view) -> bool { - return false; -} - // Write the content of buf to os. // It is a separate function rather than a part of vprint to simplify testing. template void write_buffer(std::basic_ostream& os, buffer& buf) { const Char* buf_data = buf.data(); - using unsigned_streamsize = std::make_unsigned::type; + using unsigned_streamsize = make_unsigned_t; unsigned_streamsize size = buf.size(); unsigned_streamsize max_size = to_unsigned(max_value()); do { @@ -121,21 +65,9 @@ void write_buffer(std::basic_ostream& os, buffer& buf) { } while (size != 0); } -template -void format_value(buffer& buf, const T& value) { - auto&& format_buf = formatbuf>(buf); - auto&& output = std::basic_ostream(&format_buf); -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) - output.imbue(std::locale::classic()); // The default is always unlocalized. -#endif - output << value; - output.exceptions(std::ios_base::failbit | std::ios_base::badbit); -} - template struct streamed_view { const T& value; }; - } // namespace detail // Formats an object of type T that has an overloaded ostream operator<<. @@ -143,11 +75,14 @@ template struct basic_ostream_formatter : formatter, Char> { void set_debug_format() = delete; - template - auto format(const T& value, basic_format_context& ctx) const - -> OutputIt { + template + auto format(const T& value, Context& ctx) const -> decltype(ctx.out()) { auto buffer = basic_memory_buffer(); - detail::format_value(buffer, value); + auto&& formatbuf = detail::formatbuf>(buffer); + auto&& output = std::basic_ostream(&formatbuf); + output.imbue(std::locale::classic()); // The default is always unlocalized. + output << value; + output.exceptions(std::ios_base::failbit | std::ios_base::badbit); return formatter, Char>::format( {buffer.data(), buffer.size()}, ctx); } @@ -158,73 +93,67 @@ using ostream_formatter = basic_ostream_formatter; template struct formatter, Char> : basic_ostream_formatter { - template - auto format(detail::streamed_view view, - basic_format_context& ctx) const -> OutputIt { + template + auto format(detail::streamed_view view, Context& ctx) const + -> decltype(ctx.out()) { return basic_ostream_formatter::format(view.value, ctx); } }; /** - \rst - Returns a view that formats `value` via an ostream ``operator<<``. - - **Example**:: - - fmt::print("Current thread id: {}\n", - fmt::streamed(std::this_thread::get_id())); - \endrst + * Returns a view that formats `value` via an ostream `operator<<`. + * + * **Example**: + * + * fmt::print("Current thread id: {}\n", + * fmt::streamed(std::this_thread::get_id())); */ template constexpr auto streamed(const T& value) -> detail::streamed_view { return {value}; } -namespace detail { - -inline void vprint_directly(std::ostream& os, string_view format_str, - format_args args) { +inline void vprint(std::ostream& os, string_view fmt, format_args args) { auto buffer = memory_buffer(); - detail::vformat_to(buffer, format_str, args); - detail::write_buffer(os, buffer); -} - -} // namespace detail - -FMT_EXPORT template -void vprint(std::basic_ostream& os, - basic_string_view> format_str, - basic_format_args>> args) { - auto buffer = basic_memory_buffer(); - detail::vformat_to(buffer, format_str, args); - if (detail::write_ostream_unicode(os, {buffer.data(), buffer.size()})) return; + detail::vformat_to(buffer, fmt, args); + FILE* f = nullptr; +#if FMT_MSVC_STL_UPDATE && FMT_USE_RTTI + if (auto* buf = dynamic_cast(os.rdbuf())) + f = detail::get_file(*buf); +#elif defined(_WIN32) && defined(__GLIBCXX__) && FMT_USE_RTTI + auto* rdbuf = os.rdbuf(); + if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf*>(rdbuf)) + f = sfbuf->file(); + else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf*>(rdbuf)) + f = fbuf->file(); +#endif +#ifdef _WIN32 + if (f) { + int fd = _fileno(f); + if (_isatty(fd)) { + os.flush(); + if (detail::write_console(fd, {buffer.data(), buffer.size()})) return; + } + } +#endif + detail::ignore_unused(f); detail::write_buffer(os, buffer); } /** - \rst - Prints formatted data to the stream *os*. - - **Example**:: - - fmt::print(cerr, "Don't {}!", "panic"); - \endrst + * Prints formatted data to the stream `os`. + * + * **Example**: + * + * fmt::print(cerr, "Don't {}!", "panic"); */ FMT_EXPORT template void print(std::ostream& os, format_string fmt, T&&... args) { - const auto& vargs = fmt::make_format_args(args...); - if (detail::is_utf8()) - vprint(os, fmt, vargs); - else - detail::vprint_directly(os, fmt, vargs); -} - -FMT_EXPORT -template -void print(std::wostream& os, - basic_format_string...> fmt, - Args&&... args) { - vprint(os, fmt, fmt::make_format_args>(args...)); + fmt::vargs vargs = {{args...}}; + if (detail::const_check(detail::use_utf8)) return vprint(os, fmt.str, vargs); + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt.str, vargs); + detail::write_buffer(os, buffer); } FMT_EXPORT template @@ -232,14 +161,6 @@ void println(std::ostream& os, format_string fmt, T&&... args) { fmt::print(os, "{}\n", fmt::format(fmt, std::forward(args)...)); } -FMT_EXPORT -template -void println(std::wostream& os, - basic_format_string...> fmt, - Args&&... args) { - print(os, L"{}\n", fmt::format(fmt, std::forward(args)...)); -} - FMT_END_NAMESPACE #endif // FMT_OSTREAM_H_ diff --git a/third-party/fmt/include/fmt/printf.h b/third-party/fmt/include/fmt/printf.h index 07e81577cf..e726840185 100644 --- a/third-party/fmt/include/fmt/printf.h +++ b/third-party/fmt/include/fmt/printf.h @@ -8,8 +8,10 @@ #ifndef FMT_PRINTF_H_ #define FMT_PRINTF_H_ -#include // std::max -#include // std::numeric_limits +#ifndef FMT_MODULE +# include // std::max +# include // std::numeric_limits +#endif #include "format.h" @@ -22,7 +24,7 @@ template struct printf_formatter { template class basic_printf_context { private: - detail::buffer_appender out_; + basic_appender out_; basic_format_args args_; static_assert(std::is_same::value || @@ -31,43 +33,53 @@ template class basic_printf_context { public: using char_type = Char; - using parse_context_type = basic_format_parse_context; + using parse_context_type = parse_context; template using formatter_type = printf_formatter; + enum { builtin_types = 1 }; - /** - \rst - Constructs a ``printf_context`` object. References to the arguments are - stored in the context object so make sure they have appropriate lifetimes. - \endrst - */ - basic_printf_context(detail::buffer_appender out, + /// Constructs a `printf_context` object. References to the arguments are + /// stored in the context object so make sure they have appropriate lifetimes. + basic_printf_context(basic_appender out, basic_format_args args) : out_(out), args_(args) {} - auto out() -> detail::buffer_appender { return out_; } - void advance_to(detail::buffer_appender) {} + auto out() -> basic_appender { return out_; } + void advance_to(basic_appender) {} auto locale() -> detail::locale_ref { return {}; } auto arg(int id) const -> basic_format_arg { return args_.get(id); } - - FMT_CONSTEXPR void on_error(const char* message) { - detail::error_handler().on_error(message); - } }; namespace detail { +// Return the result via the out param to workaround gcc bug 77539. +template +FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool { + for (out = first; out != last; ++out) { + if (*out == value) return true; + } + return false; +} + +template <> +inline auto find(const char* first, const char* last, char value, + const char*& out) -> bool { + out = + static_cast(memchr(first, value, to_unsigned(last - first))); + return out != nullptr; +} + // Checks if a value fits in int - used to avoid warnings about comparing // signed and unsigned integers. template struct int_checker { template static auto fits_in_int(T value) -> bool { - unsigned max = max_value(); + unsigned max = to_unsigned(max_value()); return value <= max; } - static auto fits_in_int(bool) -> bool { return true; } + inline static auto fits_in_int(bool) -> bool { return true; } }; template <> struct int_checker { @@ -75,20 +87,20 @@ template <> struct int_checker { return value >= (std::numeric_limits::min)() && value <= max_value(); } - static auto fits_in_int(int) -> bool { return true; } + inline static auto fits_in_int(int) -> bool { return true; } }; struct printf_precision_handler { template ::value)> auto operator()(T value) -> int { if (!int_checker::is_signed>::fits_in_int(value)) - throw_format_error("number is too big"); + report_error("number is too big"); return (std::max)(static_cast(value), 0); } template ::value)> auto operator()(T) -> int { - throw_format_error("precision is not integer"); + report_error("precision is not integer"); return 0; } }; @@ -133,25 +145,19 @@ template class arg_converter { using target_type = conditional_t::value, U, T>; if (const_check(sizeof(target_type) <= sizeof(int))) { // Extra casts are used to silence warnings. - if (is_signed) { - auto n = static_cast(static_cast(value)); - arg_ = detail::make_arg(n); - } else { - using unsigned_type = typename make_unsigned_or_bool::type; - auto n = static_cast(static_cast(value)); - arg_ = detail::make_arg(n); - } + using unsigned_type = typename make_unsigned_or_bool::type; + if (is_signed) + arg_ = static_cast(static_cast(value)); + else + arg_ = static_cast(static_cast(value)); } else { - if (is_signed) { - // glibc's printf doesn't sign extend arguments of smaller types: - // std::printf("%lld", -42); // prints "4294967254" - // but we don't have to do the same because it's a UB. - auto n = static_cast(value); - arg_ = detail::make_arg(n); - } else { - auto n = static_cast::type>(value); - arg_ = detail::make_arg(n); - } + // glibc's printf doesn't sign extend arguments of smaller types: + // std::printf("%lld", -42); // prints "4294967254" + // but we don't have to do the same because it's a UB. + if (is_signed) + arg_ = static_cast(value); + else + arg_ = static_cast::type>(value); } } @@ -165,7 +171,7 @@ template class arg_converter { // unsigned). template void convert_arg(basic_format_arg& arg, Char type) { - visit_format_arg(arg_converter(arg, type), arg); + arg.visit(arg_converter(arg, type)); } // Converts an integer argument to char for printf. @@ -178,8 +184,7 @@ template class char_converter { template ::value)> void operator()(T value) { - auto c = static_cast(value); - arg_ = detail::make_arg(c); + arg_ = static_cast(value); } template ::value)> @@ -195,28 +200,28 @@ template struct get_cstring { // Checks if an argument is a valid printf width specifier and sets // left alignment if it is negative. -template class printf_width_handler { +class printf_width_handler { private: - format_specs& specs_; + format_specs& specs_; public: - explicit printf_width_handler(format_specs& specs) : specs_(specs) {} + inline explicit printf_width_handler(format_specs& specs) : specs_(specs) {} template ::value)> auto operator()(T value) -> unsigned { auto width = static_cast>(value); if (detail::is_negative(value)) { - specs_.align = align::left; + specs_.set_align(align::left); width = 0 - width; } - unsigned int_max = max_value(); - if (width > int_max) throw_format_error("number is too big"); + unsigned int_max = to_unsigned(max_value()); + if (width > int_max) report_error("number is too big"); return static_cast(width); } template ::value)> auto operator()(T) -> unsigned { - throw_format_error("width is not integer"); + report_error("width is not integer"); return 0; } }; @@ -224,12 +229,12 @@ template class printf_width_handler { // Workaround for a bug with the XL compiler when initializing // printf_arg_formatter's base class. template -auto make_arg_formatter(buffer_appender iter, format_specs& s) +auto make_arg_formatter(basic_appender iter, format_specs& s) -> arg_formatter { return {iter, s, locale_ref()}; } -// The ``printf`` argument formatter. +// The `printf` argument formatter. template class printf_arg_formatter : public arg_formatter { private: @@ -240,105 +245,96 @@ class printf_arg_formatter : public arg_formatter { void write_null_pointer(bool is_string = false) { auto s = this->specs; - s.type = presentation_type::none; - write_bytes(this->out, is_string ? "(null)" : "(nil)", s); + s.set_type(presentation_type::none); + write_bytes(this->out, is_string ? "(null)" : "(nil)", s); + } + + template void write(T value) { + detail::write(this->out, value, this->specs, this->locale); } public: - printf_arg_formatter(buffer_appender iter, format_specs& s, + printf_arg_formatter(basic_appender iter, format_specs& s, context_type& ctx) : base(make_arg_formatter(iter, s)), context_(ctx) {} - void operator()(monostate value) { base::operator()(value); } + void operator()(monostate value) { write(value); } template ::value)> void operator()(T value) { // MSVC2013 fails to compile separate overloads for bool and Char so use // std::is_same instead. if (!std::is_same::value) { - base::operator()(value); + write(value); return; } - format_specs fmt_specs = this->specs; - if (fmt_specs.type != presentation_type::none && - fmt_specs.type != presentation_type::chr) { + format_specs s = this->specs; + if (s.type() != presentation_type::none && + s.type() != presentation_type::chr) { return (*this)(static_cast(value)); } - fmt_specs.sign = sign::none; - fmt_specs.alt = false; - fmt_specs.fill[0] = ' '; // Ignore '0' flag for char types. + s.set_sign(sign::none); + s.clear_alt(); + s.set_fill(' '); // Ignore '0' flag for char types. // align::numeric needs to be overwritten here since the '0' flag is // ignored for non-numeric types - if (fmt_specs.align == align::none || fmt_specs.align == align::numeric) - fmt_specs.align = align::right; - write(this->out, static_cast(value), fmt_specs); + if (s.align() == align::none || s.align() == align::numeric) + s.set_align(align::right); + detail::write(this->out, static_cast(value), s); } template ::value)> void operator()(T value) { - base::operator()(value); + write(value); } - /** Formats a null-terminated C string. */ void operator()(const char* value) { if (value) - base::operator()(value); + write(value); else - write_null_pointer(this->specs.type != presentation_type::pointer); + write_null_pointer(this->specs.type() != presentation_type::pointer); } - /** Formats a null-terminated wide C string. */ void operator()(const wchar_t* value) { if (value) - base::operator()(value); + write(value); else - write_null_pointer(this->specs.type != presentation_type::pointer); + write_null_pointer(this->specs.type() != presentation_type::pointer); } - void operator()(basic_string_view value) { base::operator()(value); } + void operator()(basic_string_view value) { write(value); } - /** Formats a pointer. */ void operator()(const void* value) { if (value) - base::operator()(value); + write(value); else write_null_pointer(); } - /** Formats an argument of a custom (user-defined) type. */ void operator()(typename basic_format_arg::handle handle) { - auto parse_ctx = basic_format_parse_context({}); + auto parse_ctx = parse_context({}); handle.format(parse_ctx, context_); } }; template -void parse_flags(format_specs& specs, const Char*& it, const Char* end) { +void 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.set_align(align::left); break; + case '+': specs.set_sign(sign::plus); break; + case '0': specs.set_fill('0'); break; case ' ': - if (specs.sign != sign::plus) specs.sign = sign::space; + if (specs.sign() != sign::plus) specs.set_sign(sign::space); break; - case '#': - specs.alt = true; - break; - default: - return; + case '#': specs.set_alt(); break; + default: return; } } } template -auto parse_header(const Char*& it, const Char* end, format_specs& specs, +auto parse_header(const Char*& it, const Char* end, format_specs& specs, GetArg get_arg) -> int { int arg_index = -1; Char c = *it; @@ -350,11 +346,11 @@ auto parse_header(const Char*& it, const Char* end, format_specs& specs, ++it; arg_index = value != -1 ? value : max_value(); } else { - if (c == '0') specs.fill[0] = '0'; + if (c == '0') specs.set_fill('0'); if (value != 0) { // Nonzero value means that we parsed width and don't need to // parse it or flags again, so return now. - if (value == -1) throw_format_error("number is too big"); + if (value == -1) report_error("number is too big"); specs.width = value; return arg_index; } @@ -365,63 +361,47 @@ auto parse_header(const Char*& it, const Char* end, format_specs& specs, if (it != end) { if (*it >= '0' && *it <= '9') { specs.width = parse_nonnegative_int(it, end, -1); - if (specs.width == -1) throw_format_error("number is too big"); + if (specs.width == -1) report_error("number is too big"); } else if (*it == '*') { ++it; - specs.width = static_cast(visit_format_arg( - detail::printf_width_handler(specs), get_arg(-1))); + specs.width = static_cast( + get_arg(-1).visit(detail::printf_width_handler(specs))); } } return arg_index; } -inline auto parse_printf_presentation_type(char c, type t) +inline auto parse_printf_presentation_type(char c, type t, bool& upper) -> presentation_type { using pt = presentation_type; constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; switch (c) { - case 'd': - return in(t, integral_set) ? pt::dec : pt::none; - case 'o': - return in(t, integral_set) ? pt::oct : pt::none; - case 'x': - return in(t, integral_set) ? pt::hex_lower : pt::none; - case 'X': - return in(t, integral_set) ? pt::hex_upper : pt::none; - case 'a': - return in(t, float_set) ? pt::hexfloat_lower : pt::none; - case 'A': - return in(t, float_set) ? pt::hexfloat_upper : pt::none; - case 'e': - return in(t, float_set) ? pt::exp_lower : pt::none; - case 'E': - return in(t, float_set) ? pt::exp_upper : pt::none; - case 'f': - return in(t, float_set) ? pt::fixed_lower : pt::none; - case 'F': - return in(t, float_set) ? pt::fixed_upper : pt::none; - case 'g': - return in(t, float_set) ? pt::general_lower : pt::none; - case 'G': - return in(t, float_set) ? pt::general_upper : pt::none; - case 'c': - return in(t, integral_set) ? pt::chr : pt::none; - case 's': - return in(t, string_set | cstring_set) ? pt::string : pt::none; - case 'p': - return in(t, pointer_set | cstring_set) ? pt::pointer : pt::none; - default: - return pt::none; + case 'd': return in(t, integral_set) ? pt::dec : pt::none; + case 'o': return in(t, integral_set) ? pt::oct : pt::none; + case 'X': upper = true; FMT_FALLTHROUGH; + case 'x': return in(t, integral_set) ? pt::hex : pt::none; + case 'E': upper = true; FMT_FALLTHROUGH; + case 'e': return in(t, float_set) ? pt::exp : pt::none; + case 'F': upper = true; FMT_FALLTHROUGH; + case 'f': return in(t, float_set) ? pt::fixed : pt::none; + case 'G': upper = true; FMT_FALLTHROUGH; + case 'g': return in(t, float_set) ? pt::general : pt::none; + case 'A': upper = true; FMT_FALLTHROUGH; + case 'a': return in(t, float_set) ? pt::hexfloat : pt::none; + case 'c': return in(t, integral_set) ? pt::chr : pt::none; + case 's': return in(t, string_set | cstring_set) ? pt::string : pt::none; + case 'p': return in(t, pointer_set | cstring_set) ? pt::pointer : pt::none; + default: return pt::none; } } template void vprintf(buffer& buf, basic_string_view format, basic_format_args args) { - using iterator = buffer_appender; + using iterator = basic_appender; auto out = iterator(buf); auto context = basic_printf_context(out, args); - auto parse_ctx = basic_format_parse_context(format); + auto parse_ctx = parse_context(format); // Returns the argument with specified index or, if arg_index is -1, the next // argument. @@ -449,12 +429,12 @@ void vprintf(buffer& buf, basic_string_view format, } write(out, basic_string_view(start, to_unsigned(it - 1 - start))); - auto specs = format_specs(); - specs.align = align::right; + auto specs = format_specs(); + specs.set_align(align::right); // Parse argument index, flags and width. int arg_index = parse_header(it, end, specs, get_arg); - if (arg_index == 0) throw_format_error("argument not found"); + if (arg_index == 0) report_error("argument not found"); // Parse precision. if (it != end && *it == '.') { @@ -464,8 +444,8 @@ void vprintf(buffer& buf, basic_string_view format, specs.precision = parse_nonnegative_int(it, end, 0); } else if (c == '*') { ++it; - specs.precision = static_cast( - visit_format_arg(printf_precision_handler(), get_arg(-1))); + specs.precision = + static_cast(get_arg(-1).visit(printf_precision_handler())); } else { specs.precision = 0; } @@ -474,25 +454,26 @@ void vprintf(buffer& buf, basic_string_view format, auto arg = get_arg(arg_index); // For d, i, o, u, x, and X conversion specifiers, if a precision is // specified, the '0' flag is ignored - if (specs.precision >= 0 && arg.is_integral()) { + if (specs.precision >= 0 && is_integral_type(arg.type())) { // Ignore '0' for non-numeric types or if '-' present. - specs.fill[0] = ' '; + specs.set_fill(' '); } if (specs.precision >= 0 && arg.type() == type::cstring_type) { - auto str = visit_format_arg(get_cstring(), arg); + auto str = arg.visit(get_cstring()); auto str_end = str + specs.precision; auto nul = std::find(str, str_end, Char()); auto sv = basic_string_view( str, to_unsigned(nul != str_end ? nul - str : specs.precision)); - arg = make_arg>(sv); + arg = sv; } - if (specs.alt && visit_format_arg(is_zero_int(), arg)) specs.alt = false; - if (specs.fill[0] == '0') { - if (arg.is_arithmetic() && specs.align != align::left) - specs.align = align::numeric; - else - specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types or if '-' - // flag is also present. + if (specs.alt() && arg.visit(is_zero_int())) specs.clear_alt(); + if (specs.fill_unit() == '0') { + if (is_arithmetic_type(arg.type()) && specs.align() != align::left) { + specs.set_align(align::numeric); + } else { + // Ignore '0' flag for non-numeric types or if '-' flag is also present. + specs.set_fill(' '); + } } // Parse length and convert the argument to the required type. @@ -517,47 +498,39 @@ void vprintf(buffer& buf, basic_string_view format, convert_arg(arg, t); } break; - case 'j': - convert_arg(arg, t); - break; - case 'z': - convert_arg(arg, t); - break; - case 't': - convert_arg(arg, t); - break; + case 'j': convert_arg(arg, t); break; + case 'z': convert_arg(arg, t); break; + case 't': convert_arg(arg, t); break; case 'L': // printf produces garbage when 'L' is omitted for long double, no // need to do the same. break; - default: - --it; - convert_arg(arg, c); + default: --it; convert_arg(arg, c); } // Parse type. - if (it == end) throw_format_error("invalid format string"); + if (it == end) report_error("invalid format string"); char type = static_cast(*it++); - if (arg.is_integral()) { + if (is_integral_type(arg.type())) { // Normalize type. switch (type) { case 'i': - case 'u': - type = 'd'; - break; + case 'u': type = 'd'; break; case 'c': - visit_format_arg(char_converter>(arg), arg); + arg.visit(char_converter>(arg)); break; } } - specs.type = parse_printf_presentation_type(type, arg.type()); - if (specs.type == presentation_type::none) - throw_format_error("invalid format specifier"); + bool upper = false; + specs.set_type(parse_printf_presentation_type(type, arg.type(), upper)); + if (specs.type() == presentation_type::none) + report_error("invalid format specifier"); + if (upper) specs.set_upper(); start = it; // Format argument. - visit_format_arg(printf_arg_formatter(out, specs, context), arg); + arg.visit(printf_arg_formatter(out, specs, context)); } write(out, basic_string_view(start, to_unsigned(it - start))); } @@ -569,56 +542,44 @@ using wprintf_context = basic_printf_context; using printf_args = basic_format_args; using wprintf_args = basic_format_args; -/** - \rst - Constructs an `~fmt::format_arg_store` object that contains references to - arguments and can be implicitly converted to `~fmt::printf_args`. - \endrst - */ -template -inline auto make_printf_args(const T&... args) - -> format_arg_store { - return {args...}; +/// Constructs an `format_arg_store` object that contains references to +/// arguments and can be implicitly converted to `printf_args`. +template +inline auto make_printf_args(T&... args) + -> decltype(fmt::make_format_args>(args...)) { + return fmt::make_format_args>(args...); } -// DEPRECATED! -template -inline auto make_wprintf_args(const T&... args) - -> format_arg_store { - return {args...}; -} +template struct vprintf_args { + using type = basic_format_args>; +}; template -inline auto vsprintf( - basic_string_view fmt, - basic_format_args>> args) +inline auto vsprintf(basic_string_view fmt, + typename vprintf_args::type args) -> std::basic_string { auto buf = basic_memory_buffer(); detail::vprintf(buf, fmt, args); - return to_string(buf); + return {buf.data(), buf.size()}; } /** - \rst - Formats arguments and returns the result as a string. - - **Example**:: - - std::string message = fmt::sprintf("The answer is %d", 42); - \endrst -*/ -template ::value, char_t>> + * Formats `args` according to specifications in `fmt` and returns the result + * as as string. + * + * **Example**: + * + * std::string message = fmt::sprintf("The answer is %d", 42); + */ +template > inline auto sprintf(const S& fmt, const T&... args) -> std::basic_string { return vsprintf(detail::to_string_view(fmt), fmt::make_format_args>(args...)); } template -inline auto vfprintf( - std::FILE* f, basic_string_view fmt, - basic_format_args>> args) - -> int { +inline auto vfprintf(std::FILE* f, basic_string_view fmt, + typename vprintf_args::type args) -> int { auto buf = basic_memory_buffer(); detail::vprintf(buf, fmt, args); size_t size = buf.size(); @@ -628,36 +589,33 @@ inline auto vfprintf( } /** - \rst - Prints formatted data to the file *f*. - - **Example**:: - - fmt::fprintf(stderr, "Don't %s!", "panic"); - \endrst + * Formats `args` according to specifications in `fmt` and writes the output + * to `f`. + * + * **Example**: + * + * fmt::fprintf(stderr, "Don't %s!", "panic"); */ -template > +template > inline auto fprintf(std::FILE* f, const S& fmt, const T&... args) -> int { return vfprintf(f, detail::to_string_view(fmt), - fmt::make_format_args>(args...)); + make_printf_args(args...)); } template -FMT_DEPRECATED inline auto vprintf( - basic_string_view fmt, - basic_format_args>> args) +FMT_DEPRECATED inline auto vprintf(basic_string_view fmt, + typename vprintf_args::type args) -> int { return vfprintf(stdout, fmt, args); } /** - \rst - Prints formatted data to ``stdout``. - - **Example**:: - - fmt::printf("Elapsed time: %.2f seconds", 1.23); - \endrst + * Formats `args` according to specifications in `fmt` and writes the output + * to `stdout`. + * + * **Example**: + * + * fmt::printf("Elapsed time: %.2f seconds", 1.23); */ template inline auto printf(string_view fmt, const T&... args) -> int { @@ -666,7 +624,7 @@ inline auto printf(string_view fmt, const T&... args) -> int { template FMT_DEPRECATED inline auto printf(basic_string_view fmt, const T&... args) -> int { - return vfprintf(stdout, fmt, make_wprintf_args(args...)); + return vfprintf(stdout, fmt, make_printf_args(args...)); } FMT_END_EXPORT diff --git a/third-party/fmt/include/fmt/ranges.h b/third-party/fmt/include/fmt/ranges.h index 3638fffb83..77d645f8e1 100644 --- a/third-party/fmt/include/fmt/ranges.h +++ b/third-party/fmt/include/fmt/ranges.h @@ -8,67 +8,31 @@ #ifndef FMT_RANGES_H_ #define FMT_RANGES_H_ -#include -#include -#include +#ifndef FMT_MODULE +# include +# include +# include +# include +# include +# include +#endif #include "format.h" FMT_BEGIN_NAMESPACE +FMT_EXPORT +enum class range_format { disabled, map, set, sequence, string, debug_string }; + namespace detail { -template -auto copy(const Range& range, OutputIt out) -> OutputIt { - for (auto it = range.begin(), end = range.end(); it != end; ++it) - *out++ = *it; - return out; -} - -template -auto copy(const char* str, OutputIt out) -> OutputIt { - while (*str) *out++ = *str++; - return out; -} - -template auto copy(char ch, OutputIt out) -> OutputIt { - *out++ = ch; - return out; -} - -template auto copy(wchar_t ch, OutputIt out) -> OutputIt { - *out++ = ch; - return out; -} - -// Returns true if T has a std::string-like interface, like std::string_view. -template class is_std_string_like { - template - static auto check(U* p) - -> decltype((void)p->find('a'), p->length(), (void)p->data(), int()); - template static void check(...); - - public: - static constexpr const bool value = - is_string::value || - std::is_convertible>::value || - !std::is_void(nullptr))>::value; -}; - -template -struct is_std_string_like> : std::true_type {}; - template class is_map { template static auto check(U*) -> typename U::mapped_type; template static void check(...); public: -#ifdef FMT_FORMAT_MAP_AS_LIST // DEPRECATED! - static constexpr const bool value = false; -#else static constexpr const bool value = !std::is_void(nullptr))>::value; -#endif }; template class is_set { @@ -76,26 +40,10 @@ template class is_set { template static void check(...); public: -#ifdef FMT_FORMAT_SET_AS_LIST // DEPRECATED! - static constexpr const bool value = false; -#else static constexpr const bool value = !std::is_void(nullptr))>::value && !is_map::value; -#endif }; -template struct conditional_helper {}; - -template struct is_range_ : std::false_type {}; - -#if !FMT_MSC_VERSION || FMT_MSC_VERSION > 1800 - -# define FMT_DECLTYPE_RETURN(val) \ - ->decltype(val) { return val; } \ - static_assert( \ - true, "") // This makes it so that a semicolon is required after the - // macro, which helps clang-format handle the formatting. - // C array overload template auto range_begin(const T (&arr)[N]) -> const T* { @@ -110,17 +58,21 @@ template struct has_member_fn_begin_end_t : std::false_type {}; template -struct has_member_fn_begin_end_t().begin()), +struct has_member_fn_begin_end_t().begin()), decltype(std::declval().end())>> : std::true_type {}; -// Member function overload +// Member function overloads. template -auto range_begin(T&& rng) FMT_DECLTYPE_RETURN(static_cast(rng).begin()); +auto range_begin(T&& rng) -> decltype(static_cast(rng).begin()) { + return static_cast(rng).begin(); +} template -auto range_end(T&& rng) FMT_DECLTYPE_RETURN(static_cast(rng).end()); +auto range_end(T&& rng) -> decltype(static_cast(rng).end()) { + return static_cast(rng).end(); +} -// ADL overload. Only participates in overload resolution if member functions +// ADL overloads. Only participate in overload resolution if member functions // are not found. template auto range_begin(T&& rng) @@ -141,31 +93,30 @@ struct has_mutable_begin_end : std::false_type {}; template struct has_const_begin_end< - T, - void_t< - decltype(detail::range_begin(std::declval&>())), - decltype(detail::range_end(std::declval&>()))>> + T, void_t&>())), + decltype(detail::range_end( + std::declval&>()))>> : std::true_type {}; template struct has_mutable_begin_end< - T, void_t())), - decltype(detail::range_end(std::declval())), + T, void_t())), + decltype(detail::range_end(std::declval())), // the extra int here is because older versions of MSVC don't // SFINAE properly unless there are distinct types int>> : std::true_type {}; +template struct is_range_ : std::false_type {}; template struct is_range_ : std::integral_constant::value || has_mutable_begin_end::value)> {}; -# undef FMT_DECLTYPE_RETURN -#endif // tuple_size and tuple_element check. template class is_tuple_like_ { - template - static auto check(U* p) -> decltype(std::tuple_size::value, int()); + template ::type> + static auto check(U* p) -> decltype(std::tuple_size::value, 0); template static void check(...); public: @@ -206,12 +157,13 @@ class is_tuple_formattable_ { static constexpr const bool value = false; }; template class is_tuple_formattable_ { - template - static auto check2(index_sequence, - integer_sequence) -> std::true_type; - static auto check2(...) -> std::false_type; - template - static auto check(index_sequence) -> decltype(check2( + template + static auto all_true(index_sequence, + integer_sequence= 0)...>) -> std::true_type; + static auto all_true(...) -> std::false_type; + + template + static auto check(index_sequence) -> decltype(all_true( index_sequence{}, integer_sequence::type, @@ -292,21 +244,32 @@ FMT_CONSTEXPR auto maybe_set_debug_format(Formatter& f, bool set) template FMT_CONSTEXPR void maybe_set_debug_format(Formatter&, ...) {} +template +struct range_format_kind_ + : std::integral_constant, T>::value + ? range_format::disabled + : is_map::value ? range_format::map + : is_set::value ? range_format::set + : range_format::sequence> {}; + +template +using range_format_constant = std::integral_constant; + // These are not generic lambdas for compatibility with C++11. -template struct parse_empty_specs { +template struct parse_empty_specs { template FMT_CONSTEXPR void operator()(Formatter& f) { f.parse(ctx); detail::maybe_set_debug_format(f, true); } - ParseContext& ctx; + parse_context& ctx; }; template struct format_tuple_element { using char_type = typename FormatContext::char_type; template void operator()(const formatter& f, const T& v) { - if (i > 0) - ctx.advance_to(detail::copy_str(separator, ctx.out())); + if (i > 0) ctx.advance_to(detail::copy(separator, ctx.out())); ctx.advance_to(f.format(v, ctx)); ++i; } @@ -355,66 +318,48 @@ struct formatter - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { auto it = ctx.begin(); - if (it != ctx.end() && *it != '}') - FMT_THROW(format_error("invalid format specifier")); - detail::for_each(formatters_, detail::parse_empty_specs{ctx}); + auto end = ctx.end(); + if (it != end && detail::to_ascii(*it) == 'n') { + ++it; + set_brackets({}, {}); + set_separator({}); + } + if (it != end && *it != '}') report_error("invalid format specifier"); + ctx.advance_to(it); + detail::for_each(formatters_, detail::parse_empty_specs{ctx}); return it; } template auto format(const Tuple& value, FormatContext& ctx) const -> decltype(ctx.out()) { - ctx.advance_to(detail::copy_str(opening_bracket_, ctx.out())); + ctx.advance_to(detail::copy(opening_bracket_, ctx.out())); detail::for_each2( formatters_, value, detail::format_tuple_element{0, ctx, separator_}); - return detail::copy_str(closing_bracket_, ctx.out()); + return detail::copy(closing_bracket_, ctx.out()); } }; template struct is_range { static constexpr const bool value = - detail::is_range_::value && !detail::is_std_string_like::value && - !std::is_convertible>::value && - !std::is_convertible>::value; + detail::is_range_::value && !detail::has_to_string_view::value; }; namespace detail { -template struct range_mapper { - using mapper = arg_mapper; - - template , Context>::value)> - static auto map(T&& value) -> T&& { - return static_cast(value); - } - template , Context>::value)> - static auto map(T&& value) - -> decltype(mapper().map(static_cast(value))) { - return mapper().map(static_cast(value)); - } -}; template -using range_formatter_type = - formatter>{}.map( - std::declval()))>, - Char>; +using range_formatter_type = formatter, Char>; template using maybe_const_range = conditional_t::value, const R, R>; -// Workaround a bug in MSVC 2015 and earlier. -#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910 template struct is_formattable_delayed : is_formattable>, Char> {}; -#endif } // namespace detail template struct conjunction : std::true_type {}; @@ -438,6 +383,24 @@ struct range_formatter< detail::string_literal{}; basic_string_view closing_bracket_ = detail::string_literal{}; + bool is_debug = false; + + template ::value)> + auto write_debug_string(Output& out, It it, Sentinel end) const -> Output { + auto buf = basic_memory_buffer(); + for (; it != end; ++it) buf.push_back(*it); + auto specs = format_specs(); + specs.set_type(presentation_type::debug); + return detail::write( + out, basic_string_view(buf.data(), buf.size()), specs); + } + + template ::value)> + auto write_debug_string(Output& out, It, Sentinel) const -> Output { + return out; + } public: FMT_CONSTEXPR range_formatter() {} @@ -456,21 +419,40 @@ struct range_formatter< closing_bracket_ = close; } - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { auto it = ctx.begin(); auto end = ctx.end(); + detail::maybe_set_debug_format(underlying_, true); + if (it == end) return underlying_.parse(ctx); - if (it != end && *it == 'n') { + switch (detail::to_ascii(*it)) { + case 'n': set_brackets({}, {}); ++it; + break; + case '?': + is_debug = true; + set_brackets({}, {}); + ++it; + if (it == end || *it != 's') report_error("invalid format specifier"); + FMT_FALLTHROUGH; + case 's': + if (!std::is_same::value) + report_error("invalid format specifier"); + if (!is_debug) { + set_brackets(detail::string_literal{}, + detail::string_literal{}); + set_separator({}); + detail::maybe_set_debug_format(underlying_, false); + } + ++it; + return it; } if (it != end && *it != '}') { - if (*it != ':') FMT_THROW(format_error("invalid format specifier")); + if (*it != ':') report_error("invalid format specifier"); + detail::maybe_set_debug_format(underlying_, false); ++it; - } else { - detail::maybe_set_debug_format(underlying_, true); } ctx.advance_to(it); @@ -479,80 +461,26 @@ struct range_formatter< template auto format(R&& range, FormatContext& ctx) const -> decltype(ctx.out()) { - detail::range_mapper> mapper; auto out = ctx.out(); - out = detail::copy_str(opening_bracket_, out); - int i = 0; auto it = detail::range_begin(range); auto end = detail::range_end(range); + if (is_debug) return write_debug_string(out, std::move(it), end); + + out = detail::copy(opening_bracket_, out); + int i = 0; for (; it != end; ++it) { - if (i > 0) out = detail::copy_str(separator_, out); + if (i > 0) out = detail::copy(separator_, out); ctx.advance_to(out); - auto&& item = *it; - out = underlying_.format(mapper.map(item), ctx); + auto&& item = *it; // Need an lvalue + out = underlying_.format(item, ctx); ++i; } - out = detail::copy_str(closing_bracket_, out); + out = detail::copy(closing_bracket_, out); return out; } }; -enum class range_format { disabled, map, set, sequence, string, debug_string }; - -namespace detail { -template -struct range_format_kind_ - : std::integral_constant, T>::value - ? range_format::disabled - : is_map::value ? range_format::map - : is_set::value ? range_format::set - : range_format::sequence> {}; - -template -struct range_default_formatter; - -template -using range_format_constant = std::integral_constant; - -template -struct range_default_formatter< - K, R, Char, - enable_if_t<(K == range_format::sequence || K == range_format::map || - K == range_format::set)>> { - using range_type = detail::maybe_const_range; - range_formatter, Char> underlying_; - - FMT_CONSTEXPR range_default_formatter() { init(range_format_constant()); } - - FMT_CONSTEXPR void init(range_format_constant) { - underlying_.set_brackets(detail::string_literal{}, - detail::string_literal{}); - } - - FMT_CONSTEXPR void init(range_format_constant) { - underlying_.set_brackets(detail::string_literal{}, - detail::string_literal{}); - underlying_.underlying().set_brackets({}, {}); - underlying_.underlying().set_separator( - detail::string_literal{}); - } - - FMT_CONSTEXPR void init(range_format_constant) {} - - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return underlying_.parse(ctx); - } - - template - auto format(range_type& range, FormatContext& ctx) const - -> decltype(ctx.out()) { - return underlying_.format(range, ctx); - } -}; -} // namespace detail - +FMT_EXPORT template struct range_format_kind : conditional_t< @@ -562,23 +490,191 @@ struct range_format_kind template struct formatter< R, Char, - enable_if_t::value != - range_format::disabled> -// Workaround a bug in MSVC 2015 and earlier. -#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910 - , - detail::is_formattable_delayed -#endif - >::value>> - : detail::range_default_formatter::value, R, - Char> { + enable_if_t::value != range_format::disabled && + range_format_kind::value != range_format::map && + range_format_kind::value != range_format::string && + range_format_kind::value != range_format::debug_string>, + detail::is_formattable_delayed>::value>> { + private: + using range_type = detail::maybe_const_range; + range_formatter, Char> range_formatter_; + + public: + using nonlocking = void; + + FMT_CONSTEXPR formatter() { + if (detail::const_check(range_format_kind::value != + range_format::set)) + return; + range_formatter_.set_brackets(detail::string_literal{}, + detail::string_literal{}); + } + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return range_formatter_.parse(ctx); + } + + template + auto format(range_type& range, FormatContext& ctx) const + -> decltype(ctx.out()) { + return range_formatter_.format(range, ctx); + } }; -template struct tuple_join_view : detail::view { - const std::tuple& tuple; +// A map formatter. +template +struct formatter< + R, Char, + enable_if_t::value == range_format::map>, + detail::is_formattable_delayed>::value>> { + private: + using map_type = detail::maybe_const_range; + using element_type = detail::uncvref_type; + + decltype(detail::tuple::get_formatters( + detail::tuple_index_sequence())) formatters_; + bool no_delimiters_ = false; + + public: + FMT_CONSTEXPR formatter() {} + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(); + auto end = ctx.end(); + if (it != end) { + if (detail::to_ascii(*it) == 'n') { + no_delimiters_ = true; + ++it; + } + if (it != end && *it != '}') { + if (*it != ':') report_error("invalid format specifier"); + ++it; + } + ctx.advance_to(it); + } + detail::for_each(formatters_, detail::parse_empty_specs{ctx}); + return it; + } + + template + auto format(map_type& map, FormatContext& ctx) const -> decltype(ctx.out()) { + auto out = ctx.out(); + basic_string_view open = detail::string_literal{}; + if (!no_delimiters_) out = detail::copy(open, out); + int i = 0; + basic_string_view sep = detail::string_literal{}; + for (auto&& value : map) { + if (i > 0) out = detail::copy(sep, out); + ctx.advance_to(out); + detail::for_each2(formatters_, value, + detail::format_tuple_element{ + 0, ctx, detail::string_literal{}}); + ++i; + } + basic_string_view close = detail::string_literal{}; + if (!no_delimiters_) out = detail::copy(close, out); + return out; + } +}; + +// A (debug_)string formatter. +template +struct formatter< + R, Char, + enable_if_t::value == range_format::string || + range_format_kind::value == + range_format::debug_string>> { + private: + using range_type = detail::maybe_const_range; + using string_type = + conditional_t, + decltype(detail::range_begin(std::declval())), + decltype(detail::range_end(std::declval()))>::value, + detail::std_string_view, std::basic_string>; + + formatter underlying_; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return underlying_.parse(ctx); + } + + template + auto format(range_type& range, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + if (detail::const_check(range_format_kind::value == + range_format::debug_string)) + *out++ = '"'; + out = underlying_.format( + string_type{detail::range_begin(range), detail::range_end(range)}, ctx); + if (detail::const_check(range_format_kind::value == + range_format::debug_string)) + *out++ = '"'; + return out; + } +}; + +template +struct join_view : detail::view { + It begin; + Sentinel end; basic_string_view sep; - tuple_join_view(const std::tuple& t, basic_string_view s) + join_view(It b, Sentinel e, basic_string_view s) + : begin(std::move(b)), end(e), sep(s) {} +}; + +template +struct formatter, Char> { + private: + using value_type = +#ifdef __cpp_lib_ranges + std::iter_value_t; +#else + typename std::iterator_traits::value_type; +#endif + formatter, Char> value_formatter_; + + using view = conditional_t::value, + const join_view, + join_view>; + + public: + using nonlocking = void; + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return value_formatter_.parse(ctx); + } + + template + auto format(view& value, FormatContext& ctx) const -> decltype(ctx.out()) { + using iter = + conditional_t::value, It, It&>; + iter it = value.begin; + auto out = ctx.out(); + if (it == value.end) return out; + out = value_formatter_.format(*it, ctx); + ++it; + while (it != value.end) { + out = detail::copy(value.sep.begin(), value.sep.end(), out); + ctx.advance_to(out); + out = value_formatter_.format(*it, ctx); + ++it; + } + return out; + } +}; + +template struct tuple_join_view : detail::view { + const Tuple& tuple; + basic_string_view sep; + + tuple_join_view(const Tuple& t, basic_string_view s) : tuple(t), sep{s} {} }; @@ -589,65 +685,64 @@ template struct tuple_join_view : detail::view { # define FMT_TUPLE_JOIN_SPECIFIERS 0 #endif -template -struct formatter, Char> { - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return do_parse(ctx, std::integral_constant()); +template +struct formatter, Char, + enable_if_t::value>> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return do_parse(ctx, std::tuple_size()); } template - auto format(const tuple_join_view& value, + auto format(const tuple_join_view& value, FormatContext& ctx) const -> typename FormatContext::iterator { - return do_format(value, ctx, - std::integral_constant()); + return do_format(value, ctx, std::tuple_size()); } private: - std::tuple::type, Char>...> formatters_; + decltype(detail::tuple::get_formatters( + detail::tuple_index_sequence())) formatters_; - template - FMT_CONSTEXPR auto do_parse(ParseContext& ctx, + FMT_CONSTEXPR auto do_parse(parse_context& ctx, std::integral_constant) - -> decltype(ctx.begin()) { + -> const Char* { return ctx.begin(); } - template - FMT_CONSTEXPR auto do_parse(ParseContext& ctx, + template + FMT_CONSTEXPR auto do_parse(parse_context& ctx, std::integral_constant) - -> decltype(ctx.begin()) { + -> const Char* { auto end = ctx.begin(); #if FMT_TUPLE_JOIN_SPECIFIERS - end = std::get(formatters_).parse(ctx); + end = std::get::value - N>(formatters_).parse(ctx); if (N > 1) { auto end1 = do_parse(ctx, std::integral_constant()); if (end != end1) - FMT_THROW(format_error("incompatible format specs for tuple elements")); + report_error("incompatible format specs for tuple elements"); } #endif return end; } template - auto do_format(const tuple_join_view&, FormatContext& ctx, + auto do_format(const tuple_join_view&, FormatContext& ctx, std::integral_constant) const -> typename FormatContext::iterator { return ctx.out(); } template - auto do_format(const tuple_join_view& value, FormatContext& ctx, + auto do_format(const tuple_join_view& value, FormatContext& ctx, std::integral_constant) const -> typename FormatContext::iterator { - auto out = std::get(formatters_) - .format(std::get(value.tuple), ctx); - if (N > 1) { - out = std::copy(value.sep.begin(), value.sep.end(), out); - ctx.advance_to(out); - return do_format(value, ctx, std::integral_constant()); - } - return out; + using std::get; + auto out = + std::get::value - N>(formatters_) + .format(get::value - N>(value.tuple), ctx); + if (N <= 1) return out; + out = detail::copy(value.sep, out); + ctx.advance_to(out); + return do_format(value, ctx, std::integral_constant()); } }; @@ -691,40 +786,57 @@ struct formatter< FMT_BEGIN_EXPORT +/// Returns a view that formats the iterator range `[begin, end)` with elements +/// separated by `sep`. +template +auto join(It begin, Sentinel end, string_view sep) -> join_view { + return {std::move(begin), end, sep}; +} + /** - \rst - Returns an object that formats `tuple` with elements separated by `sep`. - - **Example**:: - - std::tuple t = {1, 'a'}; - fmt::print("{}", fmt::join(t, ", ")); - // Output: "1, a" - \endrst + * Returns a view that formats `range` with elements separated by `sep`. + * + * **Example**: + * + * auto v = std::vector{1, 2, 3}; + * fmt::print("{}", fmt::join(v, ", ")); + * // Output: 1, 2, 3 + * + * `fmt::join` applies passed format specifiers to the range elements: + * + * fmt::print("{:02}", fmt::join(v, ", ")); + * // Output: 01, 02, 03 */ -template -FMT_CONSTEXPR auto join(const std::tuple& tuple, string_view sep) - -> tuple_join_view { - return {tuple, sep}; +template ::value)> +auto join(Range&& r, string_view sep) + -> join_view { + return {detail::range_begin(r), detail::range_end(r), sep}; } -template -FMT_CONSTEXPR auto join(const std::tuple& tuple, - basic_string_view sep) - -> tuple_join_view { +/** + * Returns an object that formats `std::tuple` with elements separated by `sep`. + * + * **Example**: + * + * auto t = std::tuple{1, 'a'}; + * fmt::print("{}", fmt::join(t, ", ")); + * // Output: 1, a + */ +template ::value)> +FMT_CONSTEXPR auto join(const Tuple& tuple, string_view sep) + -> tuple_join_view { return {tuple, sep}; } /** - \rst - Returns an object that formats `initializer_list` with elements separated by - `sep`. - - **Example**:: - - fmt::print("{}", fmt::join({1, 2, 3}, ", ")); - // Output: "1, 2, 3" - \endrst + * Returns an object that formats `std::initializer_list` with elements + * separated by `sep`. + * + * **Example**: + * + * fmt::print("{}", fmt::join({1, 2, 3}, ", ")); + * // Output: "1, 2, 3" */ template auto join(std::initializer_list list, string_view sep) diff --git a/third-party/fmt/include/fmt/std.h b/third-party/fmt/include/fmt/std.h index 7cff115920..54eb2c2a73 100644 --- a/third-party/fmt/include/fmt/std.h +++ b/third-party/fmt/include/fmt/std.h @@ -8,39 +8,49 @@ #ifndef FMT_STD_H_ #define FMT_STD_H_ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #include "format.h" #include "ostream.h" +#ifndef FMT_MODULE +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include + +// Check FMT_CPLUSPLUS to suppress a bogus warning in MSVC. +# if FMT_CPLUSPLUS >= 201703L +# if FMT_HAS_INCLUDE() && \ + (!defined(FMT_CPP_LIB_FILESYSTEM) || FMT_CPP_LIB_FILESYSTEM != 0) +# include +# endif +# if FMT_HAS_INCLUDE() +# include +# endif +# if FMT_HAS_INCLUDE() +# include +# endif +# endif +// Use > instead of >= in the version check because may be +// available after C++17 but before C++20 is marked as implemented. +# if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE() +# include +# endif +# if FMT_CPLUSPLUS > 202002L && FMT_HAS_INCLUDE() +# include +# endif +#endif // FMT_MODULE + #if FMT_HAS_INCLUDE() # include #endif -// Checking FMT_CPLUSPLUS for warning suppression in MSVC. -#if FMT_CPLUSPLUS >= 201703L -# if FMT_HAS_INCLUDE() -# include -# endif -# if FMT_HAS_INCLUDE() -# include -# endif -# if FMT_HAS_INCLUDE() -# include -# endif -#endif - -#if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE() -# include -#endif // GCC 4 does not support FMT_HAS_INCLUDE. #if FMT_HAS_INCLUDE() || defined(__GLIBCXX__) @@ -52,17 +62,6 @@ # endif #endif -// Check if typeid is available. -#ifndef FMT_USE_TYPEID -// __RTTI is for EDG compilers. In MSVC typeid is available without RTTI. -# if defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || FMT_MSC_VERSION || \ - defined(__INTEL_RTTI__) || defined(__RTTI) -# define FMT_USE_TYPEID 1 -# else -# define FMT_USE_TYPEID 0 -# endif -#endif - // For older Xcode versions, __cpp_lib_xxx flags are inaccurately defined. #ifndef FMT_CPP_LIB_FILESYSTEM # ifdef __cpp_lib_filesystem @@ -117,7 +116,7 @@ void write_escaped_path(basic_memory_buffer& quoted, FMT_EXPORT template struct formatter { private: - format_specs specs_; + format_specs specs_; detail::arg_ref width_ref_; bool debug_ = false; char path_type_ = 0; @@ -125,33 +124,33 @@ template struct formatter { public: FMT_CONSTEXPR void set_debug_format(bool set = true) { debug_ = set; } - template FMT_CONSTEXPR auto parse(ParseContext& ctx) { + FMT_CONSTEXPR auto parse(parse_context& ctx) { auto it = ctx.begin(), end = ctx.end(); if (it == end) return it; it = detail::parse_align(it, end, specs_); if (it == end) return it; - it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx); + Char c = *it; + if ((c >= '0' && c <= '9') || c == '{') + it = detail::parse_width(it, end, specs_, width_ref_, ctx); if (it != end && *it == '?') { debug_ = true; ++it; } - if (it != end && (*it == 'g')) path_type_ = *it++; + if (it != end && (*it == 'g')) path_type_ = detail::to_ascii(*it++); return it; } template auto format(const std::filesystem::path& p, FormatContext& ctx) const { auto specs = specs_; -# ifdef _WIN32 - auto path_string = !path_type_ ? p.native() : p.generic_wstring(); -# else - auto path_string = !path_type_ ? p.native() : p.generic_string(); -# endif + auto path_string = + !path_type_ ? p.native() + : p.generic_string(); - detail::handle_dynamic_spec(specs.width, width_ref_, - ctx); + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); if (!debug_) { auto s = detail::get_path_string(p, path_string); return detail::write(ctx.out(), basic_string_view(s), specs); @@ -163,13 +162,30 @@ template struct formatter { specs); } }; + +class path : public std::filesystem::path { + public: + auto display_string() const -> std::string { + const std::filesystem::path& base = *this; + return fmt::format(FMT_STRING("{}"), base); + } + auto system_string() const -> std::string { return string(); } + + auto generic_display_string() const -> std::string { + const std::filesystem::path& base = *this; + return fmt::format(FMT_STRING("{:g}"), base); + } + auto generic_system_string() const -> std::string { return generic_string(); } +}; + FMT_END_NAMESPACE #endif // FMT_CPP_LIB_FILESYSTEM FMT_BEGIN_NAMESPACE FMT_EXPORT template -struct formatter, Char> : nested_formatter { +struct formatter, Char> + : nested_formatter, Char> { private: // Functor because C++11 doesn't support generic lambdas. struct writer { @@ -189,7 +205,7 @@ struct formatter, Char> : nested_formatter { template auto format(const std::bitset& bs, FormatContext& ctx) const -> decltype(ctx.out()) { - return write_padded(ctx, writer{bs}); + return this->write_padded(ctx, writer{bs}); } }; @@ -222,7 +238,7 @@ struct formatter, Char, FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {} public: - template FMT_CONSTEXPR auto parse(ParseContext& ctx) { + FMT_CONSTEXPR auto parse(parse_context& ctx) { maybe_set_debug_format(underlying_, true); return underlying_.parse(ctx); } @@ -242,13 +258,62 @@ struct formatter, Char, FMT_END_NAMESPACE #endif // __cpp_lib_optional +#if defined(__cpp_lib_expected) || FMT_CPP_LIB_VARIANT + +FMT_BEGIN_NAMESPACE +namespace detail { + +template +auto write_escaped_alternative(OutputIt out, const T& v) -> OutputIt { + if constexpr (has_to_string_view::value) + return write_escaped_string(out, detail::to_string_view(v)); + if constexpr (std::is_same_v) return write_escaped_char(out, v); + return write(out, v); +} + +} // namespace detail + +FMT_END_NAMESPACE +#endif + +#ifdef __cpp_lib_expected +FMT_BEGIN_NAMESPACE + +FMT_EXPORT +template +struct formatter, Char, + std::enable_if_t<(std::is_void::value || + is_formattable::value) && + is_formattable::value>> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return ctx.begin(); + } + + template + auto format(const std::expected& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + + if (value.has_value()) { + out = detail::write(out, "expected("); + if constexpr (!std::is_void::value) + out = detail::write_escaped_alternative(out, *value); + } else { + out = detail::write(out, "unexpected("); + out = detail::write_escaped_alternative(out, value.error()); + } + *out++ = ')'; + return out; + } +}; +FMT_END_NAMESPACE +#endif // __cpp_lib_expected + #ifdef __cpp_lib_source_location FMT_BEGIN_NAMESPACE FMT_EXPORT template <> struct formatter { - template FMT_CONSTEXPR auto parse(ParseContext& ctx) { - return ctx.begin(); - } + FMT_CONSTEXPR auto parse(parse_context<>& ctx) { return ctx.begin(); } template auto format(const std::source_location& loc, FormatContext& ctx) const @@ -291,16 +356,6 @@ template class is_variant_formattable_ { decltype(check(variant_index_sequence{}))::value; }; -template -auto write_variant_alternative(OutputIt out, const T& v) -> OutputIt { - if constexpr (is_string::value) - return write_escaped_string(out, detail::to_string_view(v)); - else if constexpr (std::is_same_v) - return write_escaped_char(out, v); - else - return write(out, v); -} - } // namespace detail template struct is_variant_like { @@ -314,8 +369,7 @@ template struct is_variant_formattable { FMT_EXPORT template struct formatter { - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { return ctx.begin(); } @@ -332,8 +386,7 @@ struct formatter< Variant, Char, std::enable_if_t, is_variant_formattable>>> { - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { return ctx.begin(); } @@ -346,7 +399,7 @@ struct formatter< FMT_TRY { std::visit( [&](const auto& v) { - out = detail::write_variant_alternative(out, v); + out = detail::write_escaped_alternative(out, v); }, value); } @@ -362,23 +415,128 @@ FMT_END_NAMESPACE FMT_BEGIN_NAMESPACE FMT_EXPORT -template struct formatter { - template - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); +template <> struct formatter { + private: + format_specs specs_; + detail::arg_ref width_ref_; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + char c = *it; + if ((c >= '0' && c <= '9') || c == '{') + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + return it; } template - FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const - -> decltype(ctx.out()) { - auto out = ctx.out(); - out = detail::write_bytes(out, ec.category().name(), format_specs()); - out = detail::write(out, Char(':')); - out = detail::write(out, ec.value()); - return out; + FMT_CONSTEXPR20 auto format(const std::error_code& ec, + FormatContext& ctx) const -> decltype(ctx.out()) { + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); + memory_buffer buf; + buf.append(string_view(ec.category().name())); + buf.push_back(':'); + detail::write(appender(buf), ec.value()); + return detail::write(ctx.out(), string_view(buf.data(), buf.size()), + specs); } }; +#if FMT_USE_RTTI +namespace detail { + +template +auto write_demangled_name(OutputIt out, const std::type_info& ti) -> OutputIt { +# ifdef FMT_HAS_ABI_CXA_DEMANGLE + int status = 0; + std::size_t size = 0; + std::unique_ptr demangled_name_ptr( + abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free); + + string_view demangled_name_view; + if (demangled_name_ptr) { + demangled_name_view = demangled_name_ptr.get(); + + // Normalization of stdlib inline namespace names. + // libc++ inline namespaces. + // std::__1::* -> std::* + // std::__1::__fs::* -> std::* + // libstdc++ inline namespaces. + // std::__cxx11::* -> std::* + // std::filesystem::__cxx11::* -> std::filesystem::* + if (demangled_name_view.starts_with("std::")) { + char* begin = demangled_name_ptr.get(); + char* to = begin + 5; // std:: + for (char *from = to, *end = begin + demangled_name_view.size(); + from < end;) { + // This is safe, because demangled_name is NUL-terminated. + if (from[0] == '_' && from[1] == '_') { + char* next = from + 1; + while (next < end && *next != ':') next++; + if (next[0] == ':' && next[1] == ':') { + from = next + 2; + continue; + } + } + *to++ = *from++; + } + demangled_name_view = {begin, detail::to_unsigned(to - begin)}; + } + } else { + demangled_name_view = string_view(ti.name()); + } + return detail::write_bytes(out, demangled_name_view); +# elif FMT_MSC_VERSION + const string_view demangled_name(ti.name()); + for (std::size_t i = 0; i < demangled_name.size(); ++i) { + auto sub = demangled_name; + sub.remove_prefix(i); + if (sub.starts_with("enum ")) { + i += 4; + continue; + } + if (sub.starts_with("class ") || sub.starts_with("union ")) { + i += 5; + continue; + } + if (sub.starts_with("struct ")) { + i += 6; + continue; + } + if (*sub.begin() != ' ') *out++ = *sub.begin(); + } + return out; +# else + return detail::write_bytes(out, string_view(ti.name())); +# endif +} + +} // namespace detail + +FMT_EXPORT +template +struct formatter { + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return ctx.begin(); + } + + template + auto format(const std::type_info& ti, Context& ctx) const + -> decltype(ctx.out()) { + return detail::write_demangled_name(ctx.out(), ti); + } +}; +#endif + FMT_EXPORT template struct formatter< @@ -388,81 +546,29 @@ struct formatter< bool with_typename_ = false; public: - FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) - -> decltype(ctx.begin()) { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { auto it = ctx.begin(); auto end = ctx.end(); if (it == end || *it == '}') return it; if (*it == 't') { ++it; - with_typename_ = FMT_USE_TYPEID != 0; + with_typename_ = FMT_USE_RTTI != 0; } return it; } - template - auto format(const std::exception& ex, - basic_format_context& ctx) const -> OutputIt { - format_specs spec; + template + auto format(const std::exception& ex, Context& ctx) const + -> decltype(ctx.out()) { auto out = ctx.out(); - if (!with_typename_) - return detail::write_bytes(out, string_view(ex.what()), spec); - -#if FMT_USE_TYPEID - const std::type_info& ti = typeid(ex); -# ifdef FMT_HAS_ABI_CXA_DEMANGLE - int status = 0; - std::size_t size = 0; - std::unique_ptr demangled_name_ptr( - abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free); - - string_view demangled_name_view; - if (demangled_name_ptr) { - demangled_name_view = demangled_name_ptr.get(); - - // Normalization of stdlib inline namespace names. - // libc++ inline namespaces. - // std::__1::* -> std::* - // std::__1::__fs::* -> std::* - // libstdc++ inline namespaces. - // std::__cxx11::* -> std::* - // std::filesystem::__cxx11::* -> std::filesystem::* - if (demangled_name_view.starts_with("std::")) { - char* begin = demangled_name_ptr.get(); - char* to = begin + 5; // std:: - for (char *from = to, *end = begin + demangled_name_view.size(); - from < end;) { - // This is safe, because demangled_name is NUL-terminated. - if (from[0] == '_' && from[1] == '_') { - char* next = from + 1; - while (next < end && *next != ':') next++; - if (next[0] == ':' && next[1] == ':') { - from = next + 2; - continue; - } - } - *to++ = *from++; - } - demangled_name_view = {begin, detail::to_unsigned(to - begin)}; - } - } else { - demangled_name_view = string_view(ti.name()); +#if FMT_USE_RTTI + if (with_typename_) { + out = detail::write_demangled_name(out, typeid(ex)); + *out++ = ':'; + *out++ = ' '; } - out = detail::write_bytes(out, demangled_name_view, spec); -# elif FMT_MSC_VERSION - string_view demangled_name_view(ti.name()); - if (demangled_name_view.starts_with("class ")) - demangled_name_view.remove_prefix(6); - else if (demangled_name_view.starts_with("struct ")) - demangled_name_view.remove_prefix(7); - out = detail::write_bytes(out, demangled_name_view, spec); -# else - out = detail::write_bytes(out, string_view(ti.name()), spec); -# endif - *out++ = ':'; - *out++ = ' '; - return detail::write_bytes(out, string_view(ex.what()), spec); #endif + return detail::write_bytes(out, string_view(ex.what())); } }; @@ -509,6 +615,14 @@ struct formatter +auto ptr(const std::unique_ptr& p) -> const void* { + return p.get(); +} +template auto ptr(const std::shared_ptr& p) -> const void* { + return p.get(); +} + FMT_EXPORT template struct formatter, Char, @@ -533,5 +647,80 @@ struct formatter : formatter { }; #endif // __cpp_lib_atomic_flag_test +FMT_EXPORT +template struct formatter, Char> { + private: + detail::dynamic_format_specs specs_; + + template + FMT_CONSTEXPR auto do_format(const std::complex& c, + detail::dynamic_format_specs& specs, + FormatContext& ctx, OutputIt out) const + -> OutputIt { + if (c.real() != 0) { + *out++ = Char('('); + out = detail::write(out, c.real(), specs, ctx.locale()); + specs.set_sign(sign::plus); + out = detail::write(out, c.imag(), specs, ctx.locale()); + if (!detail::isfinite(c.imag())) *out++ = Char(' '); + *out++ = Char('i'); + *out++ = Char(')'); + return out; + } + out = detail::write(out, c.imag(), specs, ctx.locale()); + if (!detail::isfinite(c.imag())) *out++ = Char(' '); + *out++ = Char('i'); + return out; + } + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin(); + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type_constant::value); + } + + template + auto format(const std::complex& c, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto specs = specs_; + if (specs.dynamic()) { + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + } + + if (specs.width == 0) return do_format(c, specs, ctx, ctx.out()); + auto buf = basic_memory_buffer(); + + auto outer_specs = format_specs(); + outer_specs.width = specs.width; + outer_specs.copy_fill_from(specs); + outer_specs.set_align(specs.align()); + + specs.width = 0; + specs.set_fill({}); + specs.set_align(align::none); + + do_format(c, specs, ctx, basic_appender(buf)); + return detail::write(ctx.out(), + basic_string_view(buf.data(), buf.size()), + outer_specs); + } +}; + +FMT_EXPORT +template +struct formatter, Char, + enable_if_t, Char>::value>> + : formatter, Char> { + template + auto format(std::reference_wrapper ref, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter, Char>::format(ref.get(), ctx); + } +}; + FMT_END_NAMESPACE #endif // FMT_STD_H_ diff --git a/third-party/fmt/include/fmt/xchar.h b/third-party/fmt/include/fmt/xchar.h index f609c5c41a..9f7f889d64 100644 --- a/third-party/fmt/include/fmt/xchar.h +++ b/third-party/fmt/include/fmt/xchar.h @@ -8,12 +8,16 @@ #ifndef FMT_XCHAR_H_ #define FMT_XCHAR_H_ -#include - +#include "color.h" #include "format.h" +#include "ostream.h" +#include "ranges.h" -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR -# include +#ifndef FMT_MODULE +# include +# if FMT_USE_LOCALE +# include +# endif #endif FMT_BEGIN_NAMESPACE @@ -22,10 +26,26 @@ namespace detail { template using is_exotic_char = bool_constant::value>; -inline auto write_loc(std::back_insert_iterator> out, - loc_value value, const format_specs& specs, - locale_ref loc) -> bool { -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +template struct format_string_char {}; + +template +struct format_string_char< + S, void_t())))>> { + using type = char_t; +}; + +template +struct format_string_char< + S, enable_if_t::value>> { + using type = typename S::char_type; +}; + +template +using format_string_char_t = typename format_string_char::type; + +inline auto write_loc(basic_appender out, loc_value value, + const format_specs& specs, locale_ref loc) -> bool { +#if FMT_USE_LOCALE auto& numpunct = std::use_facet>(loc.get()); auto separator = std::wstring(); @@ -40,42 +60,79 @@ inline auto write_loc(std::back_insert_iterator> out, FMT_BEGIN_EXPORT using wstring_view = basic_string_view; -using wformat_parse_context = basic_format_parse_context; -using wformat_context = buffer_context; +using wformat_parse_context = parse_context; +using wformat_context = buffered_context; using wformat_args = basic_format_args; using wmemory_buffer = basic_memory_buffer; -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 -// Workaround broken conversion on older gcc. -template using wformat_string = wstring_view; -inline auto runtime(wstring_view s) -> wstring_view { return s; } -#else -template -using wformat_string = basic_format_string...>; +template struct basic_fstring { + private: + basic_string_view str_; + + static constexpr int num_static_named_args = + detail::count_static_named_args(); + + using checker = detail::format_string_checker< + Char, static_cast(sizeof...(T)), num_static_named_args, + num_static_named_args != detail::count_named_args()>; + + using arg_pack = detail::arg_pack; + + public: + using t = basic_fstring; + + template >::value)> + FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_fstring(const S& s) : str_(s) { + if (FMT_USE_CONSTEVAL) + detail::parse_format_string(s, checker(s, arg_pack())); + } + template ::value&& + std::is_same::value)> + FMT_ALWAYS_INLINE basic_fstring(const S&) : str_(S()) { + FMT_CONSTEXPR auto sv = basic_string_view(S()); + FMT_CONSTEXPR int ignore = + (parse_format_string(sv, checker(sv, arg_pack())), 0); + detail::ignore_unused(ignore); + } + basic_fstring(runtime_format_string fmt) : str_(fmt.str) {} + + operator basic_string_view() const { return str_; } + auto get() const -> basic_string_view { return str_; } +}; + +template +using basic_format_string = basic_fstring; + +template +using wformat_string = typename basic_format_string::t; inline auto runtime(wstring_view s) -> runtime_format_string { return {{s}}; } -#endif template <> struct is_char : std::true_type {}; -template <> struct is_char : std::true_type {}; template <> struct is_char : std::true_type {}; template <> struct is_char : std::true_type {}; +#ifdef __cpp_char8_t +template <> struct is_char : bool_constant {}; +#endif + template -constexpr auto make_wformat_args(const T&... args) - -> format_arg_store { - return {args...}; +constexpr auto make_wformat_args(T&... args) + -> decltype(fmt::make_format_args(args...)) { + return fmt::make_format_args(args...); } +#if !FMT_USE_NONTYPE_TEMPLATE_ARGS inline namespace literals { -#if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_ARGS -constexpr auto operator""_a(const wchar_t* s, size_t) - -> detail::udl_arg { +inline auto operator""_a(const wchar_t* s, size_t) -> detail::udl_arg { return {s}; } -#endif } // namespace literals +#endif template auto join(It begin, Sentinel end, wstring_view sep) @@ -83,9 +140,9 @@ auto join(It begin, Sentinel end, wstring_view sep) return {begin, end, sep}; } -template +template ::value)> auto join(Range&& range, wstring_view sep) - -> join_view, detail::sentinel_t, + -> join_view { return join(std::begin(range), std::end(range), sep); } @@ -96,13 +153,19 @@ auto join(std::initializer_list list, wstring_view sep) return join(std::begin(list), std::end(list), sep); } +template ::value)> +auto join(const Tuple& tuple, basic_string_view sep) + -> tuple_join_view { + return {tuple, sep}; +} + template ::value)> -auto vformat(basic_string_view format_str, - basic_format_args>> args) +auto vformat(basic_string_view fmt, + typename detail::vformat_args::type args) -> std::basic_string { auto buf = basic_memory_buffer(); - detail::vformat_to(buf, format_str, args); - return to_string(buf); + detail::vformat_to(buf, fmt, args); + return {buf.data(), buf.size()}; } template @@ -110,110 +173,122 @@ auto format(wformat_string fmt, T&&... args) -> std::wstring { return vformat(fmt::wstring_view(fmt), fmt::make_wformat_args(args...)); } +template +auto format_to(OutputIt out, wformat_string fmt, T&&... args) + -> OutputIt { + return vformat_to(out, fmt::wstring_view(fmt), + fmt::make_wformat_args(args...)); +} + // Pass char_t as a default template parameter instead of using // std::basic_string> to reduce the symbol size. -template , +template , FMT_ENABLE_IF(!std::is_same::value && !std::is_same::value)> -auto format(const S& format_str, T&&... args) -> std::basic_string { - return vformat(detail::to_string_view(format_str), - fmt::make_format_args>(args...)); +auto format(const S& fmt, T&&... args) -> std::basic_string { + return vformat(detail::to_string_view(fmt), + fmt::make_format_args>(args...)); } -template , +template , FMT_ENABLE_IF(detail::is_locale::value&& detail::is_exotic_char::value)> -inline auto vformat( - const Locale& loc, const S& format_str, - basic_format_args>> args) +inline auto vformat(const Locale& loc, const S& fmt, + typename detail::vformat_args::type args) -> std::basic_string { - return detail::vformat(loc, detail::to_string_view(format_str), args); + auto buf = basic_memory_buffer(); + detail::vformat_to(buf, detail::to_string_view(fmt), args, + detail::locale_ref(loc)); + return {buf.data(), buf.size()}; } -template , +template , FMT_ENABLE_IF(detail::is_locale::value&& detail::is_exotic_char::value)> -inline auto format(const Locale& loc, const S& format_str, T&&... args) +inline auto format(const Locale& loc, const S& fmt, T&&... args) -> std::basic_string { - return detail::vformat(loc, detail::to_string_view(format_str), - fmt::make_format_args>(args...)); + return vformat(loc, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); } -template , +template , FMT_ENABLE_IF(detail::is_output_iterator::value&& detail::is_exotic_char::value)> -auto vformat_to(OutputIt out, const S& format_str, - basic_format_args>> args) - -> OutputIt { +auto vformat_to(OutputIt out, const S& fmt, + typename detail::vformat_args::type args) -> OutputIt { auto&& buf = detail::get_buffer(out); - detail::vformat_to(buf, detail::to_string_view(format_str), args); + detail::vformat_to(buf, detail::to_string_view(fmt), args); return detail::get_iterator(buf, out); } template , - FMT_ENABLE_IF(detail::is_output_iterator::value&& - detail::is_exotic_char::value)> + typename Char = detail::format_string_char_t, + FMT_ENABLE_IF(detail::is_output_iterator::value && + !std::is_same::value && + !std::is_same::value)> inline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt { return vformat_to(out, detail::to_string_view(fmt), - fmt::make_format_args>(args...)); + fmt::make_format_args>(args...)); } template , + typename Char = detail::format_string_char_t, FMT_ENABLE_IF(detail::is_output_iterator::value&& detail::is_locale::value&& detail::is_exotic_char::value)> -inline auto vformat_to( - OutputIt out, const Locale& loc, const S& format_str, - basic_format_args>> args) -> OutputIt { +inline auto vformat_to(OutputIt out, const Locale& loc, const S& fmt, + typename detail::vformat_args::type args) + -> OutputIt { auto&& buf = detail::get_buffer(out); - vformat_to(buf, detail::to_string_view(format_str), args, - detail::locale_ref(loc)); + vformat_to(buf, detail::to_string_view(fmt), args, detail::locale_ref(loc)); return detail::get_iterator(buf, out); } -template , +template , bool enable = detail::is_output_iterator::value && detail::is_locale::value && detail::is_exotic_char::value> -inline auto format_to(OutputIt out, const Locale& loc, const S& format_str, +inline auto format_to(OutputIt out, const Locale& loc, const S& fmt, T&&... args) -> typename std::enable_if::type { - return vformat_to(out, loc, detail::to_string_view(format_str), - fmt::make_format_args>(args...)); + return vformat_to(out, loc, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); } template ::value&& detail::is_exotic_char::value)> -inline auto vformat_to_n( - OutputIt out, size_t n, basic_string_view format_str, - basic_format_args>> args) +inline auto vformat_to_n(OutputIt out, size_t n, basic_string_view fmt, + typename detail::vformat_args::type args) -> format_to_n_result { using traits = detail::fixed_buffer_traits; auto buf = detail::iterator_buffer(out, n); - detail::vformat_to(buf, format_str, args); + detail::vformat_to(buf, fmt, args); return {buf.out(), buf.count()}; } template , + typename Char = detail::format_string_char_t, FMT_ENABLE_IF(detail::is_output_iterator::value&& detail::is_exotic_char::value)> inline auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args) -> format_to_n_result { - return vformat_to_n(out, n, detail::to_string_view(fmt), - fmt::make_format_args>(args...)); + return vformat_to_n(out, n, fmt::basic_string_view(fmt), + fmt::make_format_args>(args...)); } -template , +template , FMT_ENABLE_IF(detail::is_exotic_char::value)> inline auto formatted_size(const S& fmt, T&&... args) -> size_t { auto buf = detail::counting_buffer(); detail::vformat_to(buf, detail::to_string_view(fmt), - fmt::make_format_args>(args...)); + fmt::make_format_args>(args...)); return buf.count(); } @@ -247,9 +322,48 @@ template void println(wformat_string fmt, T&&... args) { return print(L"{}\n", fmt::format(fmt, std::forward(args)...)); } -/** - Converts *value* to ``std::wstring`` using the default format for type *T*. - */ +inline auto vformat(const text_style& ts, wstring_view fmt, wformat_args args) + -> std::wstring { + auto buf = wmemory_buffer(); + detail::vformat_to(buf, ts, fmt, args); + return {buf.data(), buf.size()}; +} + +template +inline auto format(const text_style& ts, wformat_string fmt, T&&... args) + -> std::wstring { + return fmt::vformat(ts, fmt, fmt::make_wformat_args(args...)); +} + +template +FMT_DEPRECATED void print(std::FILE* f, const text_style& ts, + wformat_string fmt, const T&... args) { + vprint(f, ts, fmt, fmt::make_wformat_args(args...)); +} + +template +FMT_DEPRECATED void print(const text_style& ts, wformat_string fmt, + const T&... args) { + return print(stdout, ts, fmt, args...); +} + +inline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) { + auto buffer = basic_memory_buffer(); + detail::vformat_to(buffer, fmt, args); + detail::write_buffer(os, buffer); +} + +template +void print(std::wostream& os, wformat_string fmt, T&&... args) { + vprint(os, fmt, fmt::make_format_args>(args...)); +} + +template +void println(std::wostream& os, wformat_string fmt, T&&... args) { + print(os, L"{}\n", fmt::format(fmt, std::forward(args)...)); +} + +/// Converts `value` to `std::wstring` using the default format for type `T`. template inline auto to_wstring(const T& value) -> std::wstring { return format(FMT_STRING(L"{}"), value); } diff --git a/third-party/fmt/src/fmt.cc b/third-party/fmt/src/fmt.cc index 5330463a93..671fd69589 100644 --- a/third-party/fmt/src/fmt.cc +++ b/third-party/fmt/src/fmt.cc @@ -1,38 +1,59 @@ module; +#define FMT_MODULE + +#ifdef _MSVC_LANG +# define FMT_CPLUSPLUS _MSVC_LANG +#else +# define FMT_CPLUSPLUS __cplusplus +#endif + // Put all implementation-provided headers into the global module fragment // to prevent attachment to this module. -#include +#ifndef FMT_IMPORT_STD +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# if FMT_CPLUSPLUS > 202002L +# include +# endif +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +#else +# include +# include +# include +# include +#endif #include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #if __has_include() @@ -70,6 +91,10 @@ module; export module fmt; +#ifdef FMT_IMPORT_STD +import std; +#endif + #define FMT_EXPORT export #define FMT_BEGIN_EXPORT export { #define FMT_END_EXPORT } @@ -83,6 +108,10 @@ export module fmt; extern "C++" { #endif +#ifndef FMT_OS +# define FMT_OS 1 +#endif + // All library-provided declarations and definitions must be in the module // purview to be exported. #include "fmt/args.h" @@ -90,8 +119,12 @@ extern "C++" { #include "fmt/color.h" #include "fmt/compile.h" #include "fmt/format.h" -#include "fmt/os.h" +#if FMT_OS +# include "fmt/os.h" +#endif +#include "fmt/ostream.h" #include "fmt/printf.h" +#include "fmt/ranges.h" #include "fmt/std.h" #include "fmt/xchar.h" @@ -104,5 +137,17 @@ extern "C++" { module :private; #endif -#include "format.cc" -#include "os.cc" +#ifdef FMT_ATTACH_TO_GLOBAL_MODULE +extern "C++" { +#endif + +#if FMT_HAS_INCLUDE("format.cc") +# include "format.cc" +#endif +#if FMT_OS && FMT_HAS_INCLUDE("os.cc") +# include "os.cc" +#endif + +#ifdef FMT_ATTACH_TO_GLOBAL_MODULE +} +#endif diff --git a/third-party/fmt/src/format.cc b/third-party/fmt/src/format.cc index 391d3a248c..3ccd806848 100644 --- a/third-party/fmt/src/format.cc +++ b/third-party/fmt/src/format.cc @@ -15,7 +15,8 @@ template FMT_API auto dragonbox::to_decimal(float x) noexcept template FMT_API auto dragonbox::to_decimal(double x) noexcept -> dragonbox::decimal_fp; -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +#if FMT_USE_LOCALE +// DEPRECATED! locale_ref in the detail namespace template FMT_API locale_ref::locale_ref(const std::locale& loc); template FMT_API auto locale_ref::get() const -> std::locale; #endif @@ -26,8 +27,10 @@ template FMT_API auto thousands_sep_impl(locale_ref) -> thousands_sep_result; template FMT_API auto decimal_point_impl(locale_ref) -> char; +// DEPRECATED! template FMT_API void buffer::append(const char*, const char*); +// DEPRECATED! template FMT_API void vformat_to(buffer&, string_view, typename vformat_args<>::type, locale_ref); diff --git a/third-party/fmt/src/os.cc b/third-party/fmt/src/os.cc index a639e78c60..c833a05141 100644 --- a/third-party/fmt/src/os.cc +++ b/third-party/fmt/src/os.cc @@ -12,47 +12,51 @@ #include "fmt/os.h" -#include +#ifndef FMT_MODULE +# include -#if FMT_USE_FCNTL -# include -# include +# if FMT_USE_FCNTL +# include +# include -# ifdef _WRS_KERNEL // VxWorks7 kernel -# include // getpagesize +# ifdef _WRS_KERNEL // VxWorks7 kernel +# include // getpagesize +# endif + +# ifndef _WIN32 +# include +# else +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# endif // _WIN32 +# endif // FMT_USE_FCNTL + +# ifdef _WIN32 +# include # endif - -# ifndef _WIN32 -# include -# else -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include - -# ifndef S_IRUSR -# define S_IRUSR _S_IREAD -# endif -# ifndef S_IWUSR -# define S_IWUSR _S_IWRITE -# endif -# ifndef S_IRGRP -# define S_IRGRP 0 -# endif -# ifndef S_IWGRP -# define S_IWGRP 0 -# endif -# ifndef S_IROTH -# define S_IROTH 0 -# endif -# ifndef S_IWOTH -# define S_IWOTH 0 -# endif -# endif // _WIN32 -#endif // FMT_USE_FCNTL +#endif #ifdef _WIN32 -# include +# ifndef S_IRUSR +# define S_IRUSR _S_IREAD +# endif +# ifndef S_IWUSR +# define S_IWUSR _S_IWRITE +# endif +# ifndef S_IRGRP +# define S_IRGRP 0 +# endif +# ifndef S_IWGRP +# define S_IWGRP 0 +# endif +# ifndef S_IROTH +# define S_IROTH 0 +# endif +# ifndef S_IWOTH +# define S_IWOTH 0 +# endif #endif namespace { @@ -156,7 +160,7 @@ void detail::format_windows_error(detail::buffer& out, int error_code, } void report_windows_error(int error_code, const char* message) noexcept { - report_error(detail::format_windows_error, error_code, message); + do_report_error(detail::format_windows_error, error_code, message); } #endif // _WIN32 @@ -182,12 +186,14 @@ void buffered_file::close() { } int buffered_file::descriptor() const { -#if !defined(fileno) +#ifdef FMT_HAS_SYSTEM + // fileno is a macro on OpenBSD. +# ifdef fileno +# undef fileno +# endif int fd = FMT_POSIX_CALL(fileno(file_)); -#elif defined(FMT_HAS_SYSTEM) - // fileno is a macro on OpenBSD so we cannot use FMT_POSIX_CALL. -# define FMT_DISABLE_MACRO - int fd = FMT_SYSTEM(fileno FMT_DISABLE_MACRO(file_)); +#elif defined(_WIN32) + int fd = _fileno(file_); #else int fd = fileno(file_); #endif @@ -200,6 +206,7 @@ int buffered_file::descriptor() const { # ifdef _WIN32 using mode_t = int; # endif + constexpr mode_t default_open_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; @@ -301,29 +308,6 @@ void file::dup2(int fd, std::error_code& ec) noexcept { if (result == -1) ec = std::error_code(errno, std::generic_category()); } -void file::pipe(file& read_end, file& write_end) { - // Close the descriptors first to make sure that assignments don't throw - // and there are no leaks. - read_end.close(); - write_end.close(); - int fds[2] = {}; -# ifdef _WIN32 - // Make the default pipe capacity same as on Linux 2.6.11+. - enum { DEFAULT_CAPACITY = 65536 }; - int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); -# else - // Don't retry as the pipe function doesn't return EINTR. - // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html - int result = FMT_POSIX_CALL(pipe(fds)); -# endif - if (result != 0) - FMT_THROW(system_error(errno, FMT_STRING("cannot create pipe"))); - // The following assignments don't throw because read_fd and write_fd - // are closed. - read_end = file(fds[0]); - write_end = file(fds[1]); -} - buffered_file file::fdopen(const char* mode) { // Don't retry as fdopen doesn't return EINTR. # if defined(__MINGW32__) && defined(_POSIX_) @@ -352,6 +336,24 @@ file file::open_windows_file(wcstring_view path, int oflag) { } # endif +pipe::pipe() { + int fds[2] = {}; +# ifdef _WIN32 + // Make the default pipe capacity same as on Linux 2.6.11+. + enum { DEFAULT_CAPACITY = 65536 }; + int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); +# else + // Don't retry as the pipe function doesn't return EINTR. + // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html + int result = FMT_POSIX_CALL(pipe(fds)); +# endif + if (result != 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot create pipe"))); + // The following assignments don't throw. + read_end = file(fds[0]); + write_end = file(fds[1]); +} + # if !defined(__MSDOS__) long getpagesize() { # ifdef _WIN32 @@ -372,31 +374,25 @@ long getpagesize() { } # endif -namespace detail { - -void file_buffer::grow(size_t) { - if (this->size() == this->capacity()) flush(); +void ostream::grow(buffer& buf, size_t) { + if (buf.size() == buf.capacity()) static_cast(buf).flush(); } -file_buffer::file_buffer(cstring_view path, - const detail::ostream_params& params) - : file_(path, params.oflag) { +ostream::ostream(cstring_view path, const detail::ostream_params& params) + : buffer(grow), file_(path, params.oflag) { set(new char[params.buffer_size], params.buffer_size); } -file_buffer::file_buffer(file_buffer&& other) - : detail::buffer(other.data(), other.size(), other.capacity()), +ostream::ostream(ostream&& other) noexcept + : buffer(grow, other.data(), other.size(), other.capacity()), file_(std::move(other.file_)) { other.clear(); other.set(nullptr, 0); } -file_buffer::~file_buffer() { +ostream::~ostream() { flush(); delete[] data(); } -} // namespace detail - -ostream::~ostream() = default; #endif // FMT_USE_FCNTL FMT_END_NAMESPACE diff --git a/third-party/fmt/support/Vagrantfile b/third-party/fmt/support/Vagrantfile index 9680a1a184..9d0ff6a531 100644 --- a/third-party/fmt/support/Vagrantfile +++ b/third-party/fmt/support/Vagrantfile @@ -3,10 +3,9 @@ # A vagrant config for testing against gcc-4.8. Vagrant.configure("2") do |config| - config.vm.box = "ubuntu/xenial64" - config.disksize.size = '15GB' + config.vm.box = "bento/ubuntu-22.04-arm64" - config.vm.provider "virtualbox" do |vb| + config.vm.provider "vmware_desktop" do |vb| vb.memory = "4096" end diff --git a/third-party/fmt/support/bazel/.bazelversion b/third-party/fmt/support/bazel/.bazelversion index 5e3254243a..a8a1887568 100644 --- a/third-party/fmt/support/bazel/.bazelversion +++ b/third-party/fmt/support/bazel/.bazelversion @@ -1 +1 @@ -6.1.2 +7.1.2 diff --git a/third-party/fmt/support/bazel/BUILD.bazel b/third-party/fmt/support/bazel/BUILD.bazel index 29f639becd..1a06ed52b9 100644 --- a/third-party/fmt/support/bazel/BUILD.bazel +++ b/third-party/fmt/support/bazel/BUILD.bazel @@ -1,25 +1,17 @@ cc_library( name = "fmt", srcs = [ - #"src/fmt.cc", # No C++ module support + #"src/fmt.cc", # No C++ module support, yet in Bazel (https://github.com/bazelbuild/bazel/pull/19940) "src/format.cc", "src/os.cc", ], - hdrs = [ - "include/fmt/args.h", - "include/fmt/chrono.h", - "include/fmt/color.h", - "include/fmt/compile.h", - "include/fmt/core.h", - "include/fmt/format.h", - "include/fmt/format-inl.h", - "include/fmt/os.h", - "include/fmt/ostream.h", - "include/fmt/printf.h", - "include/fmt/ranges.h", - "include/fmt/std.h", - "include/fmt/xchar.h", - ], + hdrs = glob([ + "include/fmt/*.h", + ]), + copts = select({ + "@platforms//os:windows": ["-utf-8"], + "//conditions:default": [], + }), includes = [ "include", ], diff --git a/third-party/fmt/support/bazel/MODULE.bazel b/third-party/fmt/support/bazel/MODULE.bazel new file mode 100644 index 0000000000..6023f362c0 --- /dev/null +++ b/third-party/fmt/support/bazel/MODULE.bazel @@ -0,0 +1,6 @@ +module( + name = "fmt", + compatibility_level = 10, +) + +bazel_dep(name = "platforms", version = "0.0.10") diff --git a/third-party/fmt/support/bazel/README.md b/third-party/fmt/support/bazel/README.md index 4c29febb1e..44508f1c25 100644 --- a/third-party/fmt/support/bazel/README.md +++ b/third-party/fmt/support/bazel/README.md @@ -1,74 +1,28 @@ # Bazel support -To get [Bazel](https://bazel.build/) working with {fmt} you can copy the files `BUILD.bazel`, `WORKSPACE.bazel`, and `.bazelversion` from this folder (`support/bazel`) to the root folder of this project. This way {fmt} gets bazelized and can be used with Bazel (e.g. doing a `bazel build //...` on {fmt}). +To get [Bazel](https://bazel.build/) working with {fmt} you can copy the files `BUILD.bazel`, +`MODULE.bazel`, `WORKSPACE.bazel`, and `.bazelversion` from this folder (`support/bazel`) to the root folder of this project. +This way {fmt} gets bazelized and can be used with Bazel (e.g. doing a `bazel build //...` on {fmt}). ## Using {fmt} as a dependency -The following minimal example shows how to use {fmt} as a dependency within a Bazel project. +### Using Bzlmod -The following file structure is assumed: +The [Bazel Central Registry](https://github.com/bazelbuild/bazel-central-registry/tree/main/modules/fmt) provides support for {fmt}. + +For instance, to use {fmt} add to your `MODULE.bazel` file: ``` -example -├── BUILD.bazel -├── main.cpp -└── WORKSPACE.bazel +bazel_dep(name = "fmt", version = "10.2.1") ``` -*main.cpp*: +### Live at head -```c++ -#include "fmt/core.h" +For a live-at-head approach, you can copy the contents of this repository and move the Bazel-related build files to the root folder of this project as described above and make use of `local_path_override`, e.g.: -int main() { - fmt::print("The answer is {}\n", 42); -} ``` - -The expected output of this example is `The answer is 42`. - -*WORKSPACE.bazel*: - -```python -load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") - -git_repository( - name = "fmt", - branch = "master", - remote = "https://github.com/fmtlib/fmt", - patch_cmds = [ - "mv support/bazel/.bazelversion .bazelversion", - "mv support/bazel/BUILD.bazel BUILD.bazel", - "mv support/bazel/WORKSPACE.bazel WORKSPACE.bazel", - ], - # Windows-related patch commands are only needed in the case MSYS2 is not installed. - # More details about the installation process of MSYS2 on Windows systems can be found here: - # https://docs.bazel.build/versions/main/install-windows.html#installing-compilers-and-language-runtimes - # Even if MSYS2 is installed the Windows related patch commands can still be used. - patch_cmds_win = [ - "Move-Item -Path support/bazel/.bazelversion -Destination .bazelversion", - "Move-Item -Path support/bazel/BUILD.bazel -Destination BUILD.bazel", - "Move-Item -Path support/bazel/WORKSPACE.bazel -Destination WORKSPACE.bazel", - ], +local_path_override( + module_name = "fmt", + path = "../third_party/fmt", ) ``` - -In the *WORKSPACE* file, the {fmt} GitHub repository is fetched. Using the attribute `patch_cmds` the files `BUILD.bazel`, `WORKSPACE.bazel`, and `.bazelversion` are moved to the root of the {fmt} repository. This way the {fmt} repository is recognized as a bazelized workspace. - -*BUILD.bazel*: - -```python -cc_binary( - name = "Demo", - srcs = ["main.cpp"], - deps = ["@fmt"], -) -``` - -The *BUILD* file defines a binary named `Demo` that has a dependency to {fmt}. - -To execute the binary you can run `bazel run //:Demo`. - -# Using Bzlmod - -The [Bazel Central Registry](https://github.com/bazelbuild/bazel-central-registry/tree/main/modules/fmt) also provides support for {fmt}. diff --git a/third-party/fmt/support/bazel/WORKSPACE.bazel b/third-party/fmt/support/bazel/WORKSPACE.bazel index 5be77811bd..b1be18f38a 100644 --- a/third-party/fmt/support/bazel/WORKSPACE.bazel +++ b/third-party/fmt/support/bazel/WORKSPACE.bazel @@ -1 +1,2 @@ -workspace(name = "fmt") +# WORKSPACE marker file needed by Bazel + diff --git a/third-party/fmt/support/build-docs.py b/third-party/fmt/support/build-docs.py deleted file mode 100644 index f1395cd6cd..0000000000 --- a/third-party/fmt/support/build-docs.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# Build the documentation in CI. - -from __future__ import print_function -import errno, os, shutil, subprocess, sys, urllib -from subprocess import call, check_call, Popen, PIPE, STDOUT - -def rmtree_if_exists(dir): - try: - shutil.rmtree(dir) - except OSError as e: - if e.errno == errno.ENOENT: - pass - -# Build the docs. -fmt_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) -sys.path.insert(0, os.path.join(fmt_dir, 'doc')) -import build -build.create_build_env() -html_dir = build.build_docs() - -repo = 'fmtlib.github.io' -branch = os.environ['GITHUB_REF'] -is_ci = 'CI' in os.environ -if is_ci and branch != 'refs/heads/master': - print('Branch: ' + branch) - exit(0) # Ignore non-master branches -if is_ci and 'KEY' not in os.environ: - # Don't update the repo if building in CI from an account that doesn't have - # push access. - print('Skipping update of ' + repo) - exit(0) - -# Clone the fmtlib.github.io repo. -rmtree_if_exists(repo) -git_url = 'https://github.com/' if is_ci else 'git@github.com:' -check_call(['git', 'clone', git_url + 'fmtlib/{}.git'.format(repo)]) - -# Copy docs to the repo. -target_dir = os.path.join(repo, 'dev') -rmtree_if_exists(target_dir) -shutil.copytree(html_dir, target_dir, ignore=shutil.ignore_patterns('.*')) -if is_ci: - check_call(['git', 'config', '--global', 'user.name', 'fmtbot']) - check_call(['git', 'config', '--global', 'user.email', 'viz@fmt.dev']) - -# Push docs to GitHub pages. -check_call(['git', 'add', '--all'], cwd=repo) -if call(['git', 'diff-index', '--quiet', 'HEAD'], cwd=repo): - check_call(['git', 'commit', '-m', 'Update documentation'], cwd=repo) - cmd = 'git push' - if is_ci: - cmd += ' https://$KEY@github.com/fmtlib/fmtlib.github.io.git master' - p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, cwd=repo) - # Print the output without the key. - print(p.communicate()[0].decode('utf-8').replace(os.environ['KEY'], '$KEY')) - if p.returncode != 0: - raise subprocess.CalledProcessError(p.returncode, cmd) diff --git a/third-party/fmt/support/check-commits b/third-party/fmt/support/check-commits new file mode 100755 index 0000000000..11472d41f4 --- /dev/null +++ b/third-party/fmt/support/check-commits @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 + +"""Compile source on a range of commits + +Usage: + check-commits +""" + +import docopt, os, sys, tempfile +from subprocess import check_call, check_output, run + +args = docopt.docopt(__doc__) +start = args.get('') +source = args.get('') + +cwd = os.getcwd() + +with tempfile.TemporaryDirectory() as work_dir: + check_call(['git', 'clone', 'https://github.com/fmtlib/fmt.git'], + cwd=work_dir) + repo_dir = os.path.join(work_dir, 'fmt') + commits = check_output( + ['git', 'rev-list', f'{start}..HEAD', '--abbrev-commit', + '--', 'include', 'src'], + text=True, cwd=repo_dir).rstrip().split('\n') + commits.reverse() + print('Time\tCommit') + for commit in commits: + check_call(['git', '-c', 'advice.detachedHead=false', 'checkout', commit], + cwd=repo_dir) + returncode = run( + ['c++', '-std=c++11', '-O3', '-DNDEBUG', '-I', 'include', + 'src/format.cc', os.path.join(cwd, source)], cwd=repo_dir).returncode + if returncode != 0: + continue + times = [] + for i in range(5): + output = check_output([os.path.join(repo_dir, 'a.out')], text=True) + times.append(float(output)) + message = check_output(['git', 'log', '-1', '--pretty=format:%s', commit], + cwd=repo_dir, text=True) + print(f'{min(times)}\t{commit} {message[:40]}') + sys.stdout.flush() diff --git a/third-party/fmt/support/compute-powers.py b/third-party/fmt/support/compute-powers.py deleted file mode 100644 index 601063d424..0000000000 --- a/third-party/fmt/support/compute-powers.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# Compute 10 ** exp with exp in the range [min_exponent, max_exponent] and print -# normalized (with most-significant bit equal to 1) significands in hexadecimal. - -from __future__ import print_function - -min_exponent = -348 -max_exponent = 340 -step = 8 -significand_size = 64 -exp_offset = 2000 - -class fp: - pass - -powers = [] -for i, exp in enumerate(range(min_exponent, max_exponent + 1, step)): - result = fp() - n = 10 ** exp if exp >= 0 else 2 ** exp_offset / 10 ** -exp - k = significand_size + 1 - # Convert to binary and round. - binary = '{:b}'.format(n) - result.f = (int('{:0<{}}'.format(binary[:k], k), 2) + 1) / 2 - result.e = len(binary) - (exp_offset if exp < 0 else 0) - significand_size - powers.append(result) - # Sanity check. - exp_offset10 = 400 - actual = result.f * 10 ** exp_offset10 - if result.e > 0: - actual *= 2 ** result.e - else: - for j in range(-result.e): - actual /= 2 - expected = 10 ** (exp_offset10 + exp) - precision = len('{}'.format(expected)) - len('{}'.format(actual - expected)) - if precision < 19: - print('low precision:', precision) - exit(1) - -print('Significands:', end='') -for i, fp in enumerate(powers): - if i % 3 == 0: - print(end='\n ') - print(' {:0<#16x}'.format(fp.f, ), end=',') - -print('\n\nExponents:', end='') -for i, fp in enumerate(powers): - if i % 11 == 0: - print(end='\n ') - print(' {:5}'.format(fp.e), end=',') - -print('\n\nMax exponent difference:', - max([x.e - powers[i - 1].e for i, x in enumerate(powers)][1:])) diff --git a/third-party/fmt/support/manage.py b/third-party/fmt/support/manage.py deleted file mode 100644 index cfb49797d7..0000000000 --- a/third-party/fmt/support/manage.py +++ /dev/null @@ -1,329 +0,0 @@ -#!/usr/bin/env python3 - -"""Manage site and releases. - -Usage: - manage.py release [] - 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 -import datetime, docopt, errno, fileinput, json, os -import re, requests, shutil, sys -from contextlib import contextmanager -from distutils.version import LooseVersion -from subprocess import check_call - - -class Git: - def __init__(self, dir): - self.dir = dir - - def call(self, method, args, **kwargs): - return check_call(['git', method] + list(args), **kwargs) - - def add(self, *args): - return self.call('add', args, cwd=self.dir) - - def checkout(self, *args): - return self.call('checkout', args, cwd=self.dir) - - def clean(self, *args): - return self.call('clean', args, cwd=self.dir) - - def clone(self, *args): - return self.call('clone', list(args) + [self.dir]) - - def commit(self, *args): - return self.call('commit', args, cwd=self.dir) - - def pull(self, *args): - return self.call('pull', args, cwd=self.dir) - - def push(self, *args): - return self.call('push', args, cwd=self.dir) - - def reset(self, *args): - return self.call('reset', args, cwd=self.dir) - - def update(self, *args): - clone = not os.path.exists(self.dir) - if clone: - self.clone(*args) - return clone - - -def clean_checkout(repo, branch): - repo.clean('-f', '-d') - repo.reset('--hard') - repo.checkout(branch) - - -class Runner: - def __init__(self, cwd): - self.cwd = cwd - - def __call__(self, *args, **kwargs): - kwargs['cwd'] = kwargs.get('cwd', self.cwd) - check_call(args, **kwargs) - - -def create_build_env(): - """Create a build environment.""" - class Env: - pass - env = Env() - - # Import the documentation build module. - env.fmt_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - sys.path.insert(0, os.path.join(env.fmt_dir, 'doc')) - import build - - env.build_dir = 'build' - env.versions = build.versions - - # Virtualenv and repos are cached to speed up builds. - build.create_build_env(os.path.join(env.build_dir, 'virtualenv')) - - env.fmt_repo = Git(os.path.join(env.build_dir, 'fmt')) - return env - - -@contextmanager -def rewrite(filename): - class Buffer: - pass - buffer = Buffer() - if not os.path.exists(filename): - buffer.data = '' - yield buffer - return - with open(filename) as f: - buffer.data = f.read() - yield buffer - with open(filename, 'w') as f: - f.write(buffer.data) - - -fmt_repo_url = 'git@github.com:fmtlib/fmt' - - -def update_site(env): - env.fmt_repo.update(fmt_repo_url) - - doc_repo = Git(os.path.join(env.build_dir, 'fmtlib.github.io')) - doc_repo.update('git@github.com:fmtlib/fmtlib.github.io') - - for version in env.versions: - clean_checkout(env.fmt_repo, version) - target_doc_dir = os.path.join(env.fmt_repo.dir, 'doc') - # Remove the old theme. - for entry in os.listdir(target_doc_dir): - path = os.path.join(target_doc_dir, entry) - if os.path.isdir(path): - shutil.rmtree(path) - # Copy the new theme. - for entry in ['_static', '_templates', 'basic-bootstrap', 'bootstrap', - 'conf.py', 'fmt.less']: - src = os.path.join(env.fmt_dir, 'doc', entry) - dst = os.path.join(target_doc_dir, entry) - copy = shutil.copytree if os.path.isdir(src) else shutil.copyfile - copy(src, dst) - # Rename index to contents. - contents = os.path.join(target_doc_dir, 'contents.rst') - if not os.path.exists(contents): - os.rename(os.path.join(target_doc_dir, 'index.rst'), contents) - # Fix issues in reference.rst/api.rst. - for filename in ['reference.rst', 'api.rst', 'index.rst']: - pattern = re.compile('doxygenfunction.. (bin|oct|hexu|hex)$', re.M) - with rewrite(os.path.join(target_doc_dir, filename)) as b: - b.data = b.data.replace('std::ostream &', 'std::ostream&') - b.data = re.sub(pattern, r'doxygenfunction:: \1(int)', b.data) - 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( - 'format_to_n(OutputIt, size_t, string_view, Args&&', - 'format_to_n(OutputIt, size_t, const S&, const Args&') - b.data = b.data.replace( - 'format_to_n(OutputIt, std::size_t, string_view, Args&&', - 'format_to_n(OutputIt, std::size_t, const S&, const Args&') - if version == ('3.0.2'): - b.data = b.data.replace( - 'fprintf(std::ostream&', 'fprintf(std::ostream &') - if version == ('5.3.0'): - b.data = b.data.replace( - 'format_to(OutputIt, const S&, const Args&...)', - 'format_to(OutputIt, const S &, const Args &...)') - if version.startswith('5.') or version.startswith('6.'): - b.data = b.data.replace(', size_t', ', std::size_t') - if version.startswith('7.'): - b.data = b.data.replace(', std::size_t', ', size_t') - b.data = b.data.replace('join(It, It', 'join(It, Sentinel') - if version.startswith('7.1.'): - b.data = b.data.replace(', std::size_t', ', size_t') - b.data = b.data.replace('join(It, It', 'join(It, Sentinel') - b.data = b.data.replace( - 'fmt::format_to(OutputIt, const S&, Args&&...)', - 'fmt::format_to(OutputIt, const S&, Args&&...) -> ' + - 'typename std::enable_if::type') - b.data = b.data.replace('aa long', 'a long') - b.data = b.data.replace('serveral', 'several') - if version.startswith('6.2.'): - b.data = b.data.replace( - 'vformat(const S&, basic_format_args<' + - 'buffer_context>)', - 'vformat(const S&, basic_format_args<' + - 'buffer_context>>)') - # Fix a broken link in index.rst. - index = os.path.join(target_doc_dir, 'index.rst') - with rewrite(index) as b: - b.data = b.data.replace( - 'doc/latest/index.html#format-string-syntax', 'syntax.html') - # Fix issues in syntax.rst. - index = os.path.join(target_doc_dir, 'syntax.rst') - with rewrite(index) as b: - b.data = b.data.replace( - '..productionlist:: sf\n', '.. productionlist:: sf\n ') - b.data = b.data.replace('Examples:\n', 'Examples::\n') - # Build the docs. - html_dir = os.path.join(env.build_dir, 'html') - if os.path.exists(html_dir): - shutil.rmtree(html_dir) - include_dir = env.fmt_repo.dir - if LooseVersion(version) >= LooseVersion('5.0.0'): - include_dir = os.path.join(include_dir, 'include', 'fmt') - elif LooseVersion(version) >= LooseVersion('3.0.0'): - include_dir = os.path.join(include_dir, 'fmt') - import build - build.build_docs(version, doc_dir=target_doc_dir, - include_dir=include_dir, work_dir=env.build_dir) - shutil.rmtree(os.path.join(html_dir, '.doctrees')) - # Create symlinks for older versions. - for link, target in {'index': 'contents', 'api': 'reference'}.items(): - link = os.path.join(html_dir, link) + '.html' - target += '.html' - if os.path.exists(os.path.join(html_dir, target)) and \ - not os.path.exists(link): - os.symlink(target, link) - # Copy docs to the website. - version_doc_dir = os.path.join(doc_repo.dir, version) - try: - shutil.rmtree(version_doc_dir) - except OSError as e: - if e.errno != errno.ENOENT: - raise - shutil.move(html_dir, version_doc_dir) - - -def release(args): - env = create_build_env() - fmt_repo = env.fmt_repo - - branch = args.get('') - if branch is None: - branch = 'master' - if not fmt_repo.update('-b', branch, fmt_repo_url): - clean_checkout(fmt_repo, branch) - - # Update the date in the changelog and extract the version and the first - # section content. - changelog = 'ChangeLog.md' - changelog_path = os.path.join(fmt_repo.dir, changelog) - is_first_section = True - first_section = [] - for i, line in enumerate(fileinput.input(changelog_path, inplace=True)): - if i == 0: - version = re.match(r'# (.*) - TBD', line).group(1) - line = '# {} - {}\n'.format( - version, datetime.date.today().isoformat()) - elif not is_first_section: - pass - elif line.startswith('#'): - is_first_section = False - else: - first_section.append(line) - sys.stdout.write(line) - if first_section[0] == '\n': - first_section.pop(0) - - changes = '' - code_block = False - stripped = False - for line in first_section: - if re.match(r'^\s*```', line): - code_block = not code_block - changes += line - stripped = False - continue - if code_block: - changes += line - continue - if line == '\n': - changes += line - if stripped: - changes += line - stripped = False - continue - if stripped: - line = ' ' + line.lstrip() - changes += line.rstrip() - stripped = True - - cmakelists = 'CMakeLists.txt' - for line in fileinput.input(os.path.join(fmt_repo.dir, cmakelists), - inplace=True): - prefix = 'set(FMT_VERSION ' - if line.startswith(prefix): - line = prefix + version + ')\n' - sys.stdout.write(line) - - # Add the version to the build script. - script = os.path.join('doc', 'build.py') - script_path = os.path.join(fmt_repo.dir, script) - for line in fileinput.input(script_path, inplace=True): - m = re.match(r'( *versions \+= )\[(.+)\]', line) - if m: - line = '{}[{}, \'{}\']\n'.format(m.group(1), m.group(2), version) - sys.stdout.write(line) - - fmt_repo.checkout('-B', 'release') - fmt_repo.add(changelog, cmakelists, script) - fmt_repo.commit('-m', 'Update version') - - # Build the docs and package. - run = Runner(fmt_repo.dir) - run('cmake', '.') - run('make', 'doc', 'package_source') - update_site(env) - - # Create a release on GitHub. - fmt_repo.push('origin', 'release') - auth_headers = {'Authorization': 'token ' + os.getenv('FMT_TOKEN')} - r = requests.post('https://api.github.com/repos/fmtlib/fmt/releases', - headers=auth_headers, - data=json.dumps({'tag_name': version, - 'target_commitish': 'release', - 'body': changes, 'draft': True})) - if r.status_code != 201: - raise Exception('Failed to create a release ' + str(r)) - id = r.json()['id'] - uploads_url = 'https://uploads.github.com/repos/fmtlib/fmt/releases' - package = 'fmt-{}.zip'.format(version) - r = requests.post( - '{}/{}/assets?name={}'.format(uploads_url, id, package), - headers={'Content-Type': 'application/zip'} | auth_headers, - data=open('build/fmt/' + package, 'rb')) - if r.status_code != 201: - raise Exception('Failed to upload an asset ' + str(r)) - - -if __name__ == '__main__': - args = docopt.docopt(__doc__) - if args.get('release'): - release(args) - elif args.get('site'): - update_site(create_build_env()) diff --git a/third-party/fmt/support/mkdocs b/third-party/fmt/support/mkdocs new file mode 100755 index 0000000000..e554c1fdca --- /dev/null +++ b/third-party/fmt/support/mkdocs @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# A script to invoke mkdocs with the correct environment. +# Additionally supports deploying via mike: +# ./mkdocs deploy [mike-deploy-options] + +import errno, os, shutil, sys +from subprocess import call + +support_dir = os.path.dirname(os.path.normpath(__file__)) +build_dir = os.path.join(os.path.dirname(support_dir), 'build') + +# Set PYTHONPATH for the mkdocstrings handler. +env = os.environ.copy() +path = env.get('PYTHONPATH') +env['PYTHONPATH'] = \ + (path + ':' if path else '') + os.path.join(support_dir, 'python') + +redirect_page = \ +''' + + + + Redirecting + + + + + Redirecting to api... + + +''' + +config_path = os.path.join(support_dir, 'mkdocs.yml') +args = sys.argv[1:] +if len(args) > 0: + command = args[0] + if command == 'deploy': + git_url = 'https://github.com/' if 'CI' in os.environ else 'git@github.com:' + site_repo = git_url + 'fmtlib/fmt.dev.git' + + site_dir = os.path.join(build_dir, 'fmt.dev') + try: + shutil.rmtree(site_dir) + except OSError as e: + if e.errno == errno.ENOENT: + pass + ret = call(['git', 'clone', '--depth=1', site_repo, site_dir]) + if ret != 0: + sys.exit(ret) + + # Copy the config to the build dir because the site is built relative to it. + config_build_path = os.path.join(build_dir, 'mkdocs.yml') + shutil.copyfile(config_path, config_build_path) + + version = args[1] + ret = call(['mike'] + args + ['--config-file', config_build_path, + '--branch', 'master'], cwd=site_dir, env=env) + if ret != 0 or version == 'dev': + sys.exit(ret) + redirect_page_path = os.path.join(site_dir, version, 'api.html') + with open(redirect_page_path, "w") as file: + file.write(redirect_page) + ret = call(['git', 'add', redirect_page_path], cwd=site_dir) + if ret != 0: + sys.exit(ret) + ret = call(['git', 'commit', '--amend', '--no-edit'], cwd=site_dir) + sys.exit(ret) + elif not command.startswith('-'): + args += ['-f', config_path] +sys.exit(call(['mkdocs'] + args, env=env)) diff --git a/third-party/fmt/support/mkdocs.yml b/third-party/fmt/support/mkdocs.yml new file mode 100644 index 0000000000..17034cd1ff --- /dev/null +++ b/third-party/fmt/support/mkdocs.yml @@ -0,0 +1,48 @@ +site_name: '{fmt}' + +docs_dir: ../doc + +repo_url: https://github.com/fmtlib/fmt + +theme: + name: material + features: + - navigation.tabs + - navigation.top + - toc.integrate + +extra_javascript: + - https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/highlight.min.js + - fmt.js + +extra_css: + - https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/styles/default.min.css + - fmt.css + +markdown_extensions: + - pymdownx.highlight: + # Use JavaScript syntax highlighter instead of Pygments because it + # automatically applies to code blocks extracted through Doxygen. + use_pygments: false + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite + - pymdownx.snippets + +plugins: + - search + - mkdocstrings: + default_handler: cxx +nav: + - Home: index.md + - Get Started: get-started.md + - API: api.md + - Syntax: syntax.md + +exclude_docs: ChangeLog-old.md + +extra: + version: + provider: mike + generator: false diff --git a/third-party/fmt/support/printable.py b/third-party/fmt/support/printable.py old mode 100644 new mode 100755 diff --git a/third-party/fmt/support/python/mkdocstrings_handlers/cxx/__init__.py b/third-party/fmt/support/python/mkdocstrings_handlers/cxx/__init__.py new file mode 100644 index 0000000000..85d52a5806 --- /dev/null +++ b/third-party/fmt/support/python/mkdocstrings_handlers/cxx/__init__.py @@ -0,0 +1,338 @@ +# A basic mkdocstrings handler for {fmt}. +# Copyright (c) 2012 - present, Victor Zverovich +# https://github.com/fmtlib/fmt/blob/master/LICENSE + +import os +import xml.etree.ElementTree as ElementTree +from pathlib import Path +from subprocess import PIPE, STDOUT, CalledProcessError, Popen +from typing import Any, List, Mapping, Optional + +from mkdocstrings.handlers.base import BaseHandler + + +class Definition: + """A definition extracted by Doxygen.""" + + def __init__(self, name: str, kind: Optional[str] = None, + node: Optional[ElementTree.Element] = None, + is_member: bool = False): + self.name = name + self.kind = kind if kind is not None else node.get('kind') + self.desc = None + self.id = name if not is_member else None + self.members = None + self.params = None + self.template_params = None + self.trailing_return_type = None + self.type = None + + +# A map from Doxygen to HTML tags. +tag_map = { + 'bold': 'b', + 'emphasis': 'em', + 'computeroutput': 'code', + 'para': 'p', + 'programlisting': 'pre', + 'verbatim': 'pre' +} + +# A map from Doxygen tags to text. +tag_text_map = { + 'codeline': '', + 'highlight': '', + 'sp': ' ' +} + + +def escape_html(s: str) -> str: + return s.replace("<", "<") + + +def doxyxml2html(nodes: List[ElementTree.Element]): + out = '' + for n in nodes: + tag = tag_map.get(n.tag) + if not tag: + out += tag_text_map[n.tag] + out += '<' + tag + '>' if tag else '' + out += '' if tag == 'pre' else '' + if n.text: + out += escape_html(n.text) + out += doxyxml2html(list(n)) + out += '' if tag == 'pre' else '' + out += '' if tag else '' + if n.tail: + out += n.tail + return out + + +def convert_template_params(node: ElementTree.Element) -> Optional[List[Definition]]: + template_param_list = node.find('templateparamlist') + if template_param_list is None: + return None + params = [] + for param_node in template_param_list.findall('param'): + name = param_node.find('declname') + param = Definition(name.text if name is not None else '', 'param') + param.type = param_node.find('type').text + params.append(param) + return params + + +def get_description(node: ElementTree.Element) -> List[ElementTree.Element]: + return node.findall('briefdescription/para') + \ + node.findall('detaileddescription/para') + + +def normalize_type(type_: str) -> str: + type_ = type_.replace('< ', '<').replace(' >', '>') + return type_.replace(' &', '&').replace(' *', '*') + + +def convert_type(type_: ElementTree.Element) -> Optional[str]: + if type_ is None: + return None + result = type_.text if type_.text else '' + for ref in type_: + result += ref.text + if ref.tail: + result += ref.tail + result += type_.tail.strip() + return normalize_type(result) + + +def convert_params(func: ElementTree.Element) -> List[Definition]: + params = [] + for p in func.findall('param'): + d = Definition(p.find('declname').text, 'param') + d.type = convert_type(p.find('type')) + params.append(d) + return params + + +def convert_return_type(d: Definition, node: ElementTree.Element) -> None: + d.trailing_return_type = None + if d.type == 'auto' or d.type == 'constexpr auto': + parts = node.find('argsstring').text.split(' -> ') + if len(parts) > 1: + d.trailing_return_type = normalize_type(parts[1]) + + +def render_param(param: Definition) -> str: + return param.type + (f' {param.name}' if len(param.name) > 0 else '') + + +def render_decl(d: Definition) -> str: + text = '' + if d.id is not None: + text += f'\n' + text += '
'
+
+    text += '
' + if d.template_params is not None: + text += 'template <' + text += ', '.join([render_param(p) for p in d.template_params]) + text += '>\n' + text += '
' + + text += '
' + end = ';' + if d.kind == 'function' or d.kind == 'variable': + text += d.type + ' ' if len(d.type) > 0 else '' + elif d.kind == 'typedef': + text += 'using ' + elif d.kind == 'define': + end = '' + else: + text += d.kind + ' ' + text += d.name + + if d.params is not None: + params = ', '.join([ + (p.type + ' ' if p.type else '') + p.name for p in d.params]) + text += '(' + escape_html(params) + ')' + if d.trailing_return_type: + text += ' -⁠> ' + escape_html(d.trailing_return_type) + elif d.kind == 'typedef': + text += ' = ' + escape_html(d.type) + + text += end + text += '
' + text += '
\n' + if d.id is not None: + text += f'
\n' + return text + + +class CxxHandler(BaseHandler): + def __init__(self, **kwargs: Any) -> None: + super().__init__(handler='cxx', **kwargs) + + headers = [ + 'args.h', 'base.h', 'chrono.h', 'color.h', 'compile.h', 'format.h', + 'os.h', 'ostream.h', 'printf.h', 'ranges.h', 'std.h', 'xchar.h' + ] + + # Run doxygen. + cmd = ['doxygen', '-'] + support_dir = Path(__file__).parents[3] + top_dir = os.path.dirname(support_dir) + include_dir = os.path.join(top_dir, 'include', 'fmt') + self._ns2doxyxml = {} + build_dir = os.path.join(top_dir, 'build') + os.makedirs(build_dir, exist_ok=True) + self._doxyxml_dir = os.path.join(build_dir, 'doxyxml') + p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT) + _, _ = p.communicate(input=r''' + PROJECT_NAME = fmt + GENERATE_XML = YES + GENERATE_LATEX = NO + GENERATE_HTML = NO + INPUT = {0} + XML_OUTPUT = {1} + QUIET = YES + AUTOLINK_SUPPORT = NO + MACRO_EXPANSION = YES + PREDEFINED = _WIN32=1 \ + __linux__=1 \ + FMT_ENABLE_IF(...)= \ + FMT_USE_USER_LITERALS=1 \ + FMT_USE_ALIAS_TEMPLATES=1 \ + FMT_USE_NONTYPE_TEMPLATE_ARGS=1 \ + FMT_API= \ + "FMT_BEGIN_NAMESPACE=namespace fmt {{" \ + "FMT_END_NAMESPACE=}}" \ + "FMT_DOC=1" + '''.format( + ' '.join([os.path.join(include_dir, h) for h in headers]), + self._doxyxml_dir).encode('utf-8')) + if p.returncode != 0: + raise CalledProcessError(p.returncode, cmd) + + # Merge all file-level XMLs into one to simplify search. + self._file_doxyxml = None + for h in headers: + filename = h.replace(".h", "_8h.xml") + with open(os.path.join(self._doxyxml_dir, filename)) as f: + doxyxml = ElementTree.parse(f) + if self._file_doxyxml is None: + self._file_doxyxml = doxyxml + continue + root = self._file_doxyxml.getroot() + for node in doxyxml.getroot(): + root.append(node) + + def collect_compound(self, identifier: str, + cls: List[ElementTree.Element]) -> Definition: + """Collect a compound definition such as a struct.""" + path = os.path.join(self._doxyxml_dir, cls[0].get('refid') + '.xml') + with open(path) as f: + xml = ElementTree.parse(f) + node = xml.find('compounddef') + d = Definition(identifier, node=node) + d.template_params = convert_template_params(node) + d.desc = get_description(node) + d.members = [] + for m in \ + node.findall('sectiondef[@kind="public-attrib"]/memberdef') + \ + node.findall('sectiondef[@kind="public-func"]/memberdef'): + name = m.find('name').text + # Doxygen incorrectly classifies members of private unnamed unions as + # public members of the containing class. + if name.endswith('_'): + continue + desc = get_description(m) + if len(desc) == 0: + continue + kind = m.get('kind') + member = Definition(name if name else '', kind=kind, is_member=True) + type_text = m.find('type').text + member.type = type_text if type_text else '' + if kind == 'function': + member.params = convert_params(m) + convert_return_type(member, m) + member.template_params = None + member.desc = desc + d.members.append(member) + return d + + def collect(self, identifier: str, _config: Mapping[str, Any]) -> Definition: + qual_name = 'fmt::' + identifier + + param_str = None + paren = qual_name.find('(') + if paren > 0: + qual_name, param_str = qual_name[:paren], qual_name[paren + 1:-1] + + colons = qual_name.rfind('::') + namespace, name = qual_name[:colons], qual_name[colons + 2:] + + # Load XML. + doxyxml = self._ns2doxyxml.get(namespace) + if doxyxml is None: + path = f'namespace{namespace.replace("::", "_1_1")}.xml' + with open(os.path.join(self._doxyxml_dir, path)) as f: + doxyxml = ElementTree.parse(f) + self._ns2doxyxml[namespace] = doxyxml + + nodes = doxyxml.findall( + f"compounddef/sectiondef/memberdef/name[.='{name}']/..") + if len(nodes) == 0: + nodes = self._file_doxyxml.findall( + f"compounddef/sectiondef/memberdef/name[.='{name}']/..") + candidates = [] + for node in nodes: + # Process a function or a typedef. + params = None + d = Definition(name, node=node) + if d.kind == 'function': + params = convert_params(node) + node_param_str = ', '.join([p.type for p in params]) + if param_str and param_str != node_param_str: + candidates.append(f'{name}({node_param_str})') + continue + elif d.kind == 'define': + params = [] + for p in node.findall('param'): + param = Definition(p.find('defname').text, kind='param') + param.type = None + params.append(param) + d.type = convert_type(node.find('type')) + d.template_params = convert_template_params(node) + d.params = params + convert_return_type(d, node) + d.desc = get_description(node) + return d + + cls = doxyxml.findall(f"compounddef/innerclass[.='{qual_name}']") + if not cls: + raise Exception(f'Cannot find {identifier}. Candidates: {candidates}') + return self.collect_compound(identifier, cls) + + def render(self, d: Definition, config: dict) -> str: + if d.id is not None: + self.do_heading('', 0, id=d.id) + text = '
\n' + text += render_decl(d) + text += '
\n' + text += doxyxml2html(d.desc) + if d.members is not None: + for m in d.members: + text += self.render(m, config) + text += '
\n' + text += '
\n' + return text + + +def get_handler(theme: str, custom_templates: Optional[str] = None, + **_config: Any) -> CxxHandler: + """Return an instance of `CxxHandler`. + + Arguments: + theme: The theme to use when rendering contents. + custom_templates: Directory containing custom templates. + **_config: Configuration passed to the handler. + """ + return CxxHandler(theme=theme, custom_templates=custom_templates) diff --git a/third-party/fmt/support/python/mkdocstrings_handlers/cxx/templates/README b/third-party/fmt/support/python/mkdocstrings_handlers/cxx/templates/README new file mode 100644 index 0000000000..7da18db541 --- /dev/null +++ b/third-party/fmt/support/python/mkdocstrings_handlers/cxx/templates/README @@ -0,0 +1 @@ +mkdocsstrings requires a handler to have a templates directory. diff --git a/third-party/fmt/support/release.py b/third-party/fmt/support/release.py new file mode 100755 index 0000000000..26de7f4fd4 --- /dev/null +++ b/third-party/fmt/support/release.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 + +"""Make a release. + +Usage: + release.py [] + +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 +import datetime, docopt, errno, fileinput, json, os +import re, shutil, sys +from subprocess import check_call +import urllib.request + + +class Git: + def __init__(self, dir): + self.dir = dir + + def call(self, method, args, **kwargs): + return check_call(['git', method] + list(args), **kwargs) + + def add(self, *args): + return self.call('add', args, cwd=self.dir) + + def checkout(self, *args): + return self.call('checkout', args, cwd=self.dir) + + def clean(self, *args): + return self.call('clean', args, cwd=self.dir) + + def clone(self, *args): + return self.call('clone', list(args) + [self.dir]) + + def commit(self, *args): + return self.call('commit', args, cwd=self.dir) + + def pull(self, *args): + return self.call('pull', args, cwd=self.dir) + + def push(self, *args): + return self.call('push', args, cwd=self.dir) + + def reset(self, *args): + return self.call('reset', args, cwd=self.dir) + + def update(self, *args): + clone = not os.path.exists(self.dir) + if clone: + self.clone(*args) + return clone + + +def clean_checkout(repo, branch): + repo.clean('-f', '-d') + repo.reset('--hard') + repo.checkout(branch) + + +class Runner: + def __init__(self, cwd): + self.cwd = cwd + + def __call__(self, *args, **kwargs): + kwargs['cwd'] = kwargs.get('cwd', self.cwd) + check_call(args, **kwargs) + + +def create_build_env(): + """Create a build environment.""" + class Env: + pass + env = Env() + env.fmt_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + env.build_dir = 'build' + env.fmt_repo = Git(os.path.join(env.build_dir, 'fmt')) + return env + + +if __name__ == '__main__': + args = docopt.docopt(__doc__) + env = create_build_env() + fmt_repo = env.fmt_repo + + branch = args.get('') + if branch is None: + branch = 'master' + if not fmt_repo.update('-b', branch, 'git@github.com:fmtlib/fmt'): + clean_checkout(fmt_repo, branch) + + # Update the date in the changelog and extract the version and the first + # section content. + changelog = 'ChangeLog.md' + changelog_path = os.path.join(fmt_repo.dir, changelog) + is_first_section = True + first_section = [] + for i, line in enumerate(fileinput.input(changelog_path, inplace=True)): + if i == 0: + version = re.match(r'# (.*) - TBD', line).group(1) + line = '# {} - {}\n'.format( + version, datetime.date.today().isoformat()) + elif not is_first_section: + pass + elif line.startswith('#'): + is_first_section = False + else: + first_section.append(line) + sys.stdout.write(line) + if first_section[0] == '\n': + first_section.pop(0) + + ns_version = None + base_h_path = os.path.join(fmt_repo.dir, 'include', 'fmt', 'base.h') + for line in fileinput.input(base_h_path): + m = re.match(r'\s*inline namespace v(.*) .*', line) + if m: + ns_version = m.group(1) + break + major_version = version.split('.')[0] + if not ns_version or ns_version != major_version: + raise Exception(f'Version mismatch {ns_version} != {major_version}') + + # Workaround GitHub-flavored Markdown treating newlines as
. + changes = '' + code_block = False + stripped = False + for line in first_section: + if re.match(r'^\s*```', line): + code_block = not code_block + changes += line + stripped = False + continue + if code_block: + changes += line + continue + if line == '\n' or re.match(r'^\s*\|.*', line): + if stripped: + changes += '\n' + stripped = False + changes += line + continue + if stripped: + line = ' ' + line.lstrip() + changes += line.rstrip() + stripped = True + + fmt_repo.checkout('-B', 'release') + fmt_repo.add(changelog) + fmt_repo.commit('-m', 'Update version') + + # Build the docs and package. + run = Runner(fmt_repo.dir) + run('cmake', '.') + run('make', 'doc', 'package_source') + + # Create a release on GitHub. + fmt_repo.push('origin', 'release') + auth_headers = {'Authorization': 'token ' + os.getenv('FMT_TOKEN')} + req = urllib.request.Request( + 'https://api.github.com/repos/fmtlib/fmt/releases', + data=json.dumps({'tag_name': version, + 'target_commitish': 'release', + 'body': changes, 'draft': True}).encode('utf-8'), + headers=auth_headers, method='POST') + with urllib.request.urlopen(req) as response: + if response.status != 201: + raise Exception(f'Failed to create a release ' + + '{response.status} {response.reason}') + response_data = json.loads(response.read().decode('utf-8')) + id = response_data['id'] + + # Upload the package. + uploads_url = 'https://uploads.github.com/repos/fmtlib/fmt/releases' + package = 'fmt-{}.zip'.format(version) + req = urllib.request.Request( + f'{uploads_url}/{id}/assets?name={package}', + headers={'Content-Type': 'application/zip'} | auth_headers, + data=open('build/fmt/' + package, 'rb').read(), method='POST') + with urllib.request.urlopen(req) as response: + if response.status != 201: + raise Exception(f'Failed to upload an asset ' + '{response.status} {response.reason}') + + short_version = '.'.join(version.split('.')[:-1]) + check_call(['./mkdocs', 'deploy', short_version]) diff --git a/third-party/fmt/support/rtd/conf.py b/third-party/fmt/support/rtd/conf.py deleted file mode 100644 index 124fb9d4c8..0000000000 --- a/third-party/fmt/support/rtd/conf.py +++ /dev/null @@ -1,7 +0,0 @@ -# Sphinx configuration for readthedocs. - -import os, sys - -master_doc = 'index' -html_theme = 'theme' -html_theme_path = ["."] diff --git a/third-party/fmt/support/rtd/index.rst b/third-party/fmt/support/rtd/index.rst deleted file mode 100644 index 7c88322f62..0000000000 --- a/third-party/fmt/support/rtd/index.rst +++ /dev/null @@ -1,2 +0,0 @@ -If you are not redirected automatically, follow the -`link to the fmt documentation `_. diff --git a/third-party/fmt/support/rtd/theme/layout.html b/third-party/fmt/support/rtd/theme/layout.html deleted file mode 100644 index 29ebc55bb4..0000000000 --- a/third-party/fmt/support/rtd/theme/layout.html +++ /dev/null @@ -1,17 +0,0 @@ -{% extends "basic/layout.html" %} - -{% block extrahead %} - - - -Page Redirection -{% endblock %} - -{% block document %} -If you are not redirected automatically, follow the link to the fmt documentation. -{% endblock %} - -{% block footer %} -{% endblock %} diff --git a/third-party/fmt/support/rtd/theme/theme.conf b/third-party/fmt/support/rtd/theme/theme.conf deleted file mode 100644 index 89e03bbdac..0000000000 --- a/third-party/fmt/support/rtd/theme/theme.conf +++ /dev/null @@ -1,2 +0,0 @@ -[theme] -inherit = basic diff --git a/third-party/fmt/test/CMakeLists.txt b/third-party/fmt/test/CMakeLists.txt index ec97ac29a7..e1ea260d9a 100644 --- a/third-party/fmt/test/CMakeLists.txt +++ b/third-party/fmt/test/CMakeLists.txt @@ -8,22 +8,6 @@ target_include_directories(test-main PUBLIC $) target_link_libraries(test-main gtest fmt) -function(add_fmt_executable name) - add_executable(${name} ${ARGN}) - # (Wstringop-overflow) - [meta-bug] bogus/missing -Wstringop-overflow warnings - # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88443 - # Bogus -Wstringop-overflow warning - # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100395 - # [10 Regression] spurious -Wstringop-overflow writing to a trailing array plus offset - # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95353 - if (CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND - NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0) - target_compile_options(${name} PRIVATE -Wno-stringop-overflow) - # The linker flag is needed for LTO. - target_link_libraries(${name} -Wno-stringop-overflow) - endif () -endfunction() - # Adds a test. # Usage: add_fmt_test(name srcs...) function(add_fmt_test name) @@ -42,9 +26,13 @@ function(add_fmt_test name) else () set(libs test-main fmt) endif () - add_fmt_executable(${name} ${sources}) + add_executable(${name} ${sources}) target_link_libraries(${name} ${libs}) + if (ADD_FMT_TEST_HEADER_ONLY AND NOT FMT_UNICODE) + target_compile_definitions(${name} PUBLIC FMT_UNICODE=0) + endif () + # Define if certain C++ features can be used. if (FMT_PEDANTIC) target_compile_options(${name} PRIVATE ${PEDANTIC_COMPILE_FLAGS}) @@ -60,10 +48,10 @@ if (FMT_MODULE) endif () add_fmt_test(args-test) +add_fmt_test(base-test) add_fmt_test(assert-test) add_fmt_test(chrono-test) add_fmt_test(color-test) -add_fmt_test(core-test) add_fmt_test(gtest-extra-test) add_fmt_test(format-test mock-allocator.h) if (MSVC) @@ -74,15 +62,16 @@ if (NOT (MSVC AND BUILD_SHARED_LIBS)) endif () add_fmt_test(ostream-test) add_fmt_test(compile-test) -add_fmt_test(compile-fp-test HEADER_ONLY) +add_fmt_test(compile-fp-test) if (MSVC) # Without this option, MSVC returns 199711L for the __cplusplus macro. target_compile_options(compile-fp-test PRIVATE /Zc:__cplusplus) endif() add_fmt_test(printf-test) add_fmt_test(ranges-test ranges-odr-test.cc) +add_fmt_test(no-builtin-types-test HEADER_ONLY) -add_fmt_test(scan-test) +add_fmt_test(scan-test HEADER_ONLY) check_symbol_exists(strptime "time.h" HAVE_STRPTIME) if (HAVE_STRPTIME) target_compile_definitions(scan-test PRIVATE FMT_HAVE_STRPTIME) @@ -106,6 +95,9 @@ add_fmt_test(enforce-checks-test) target_compile_definitions(enforce-checks-test PRIVATE -DFMT_ENFORCE_COMPILE_STRING) +add_executable(perf-sanity perf-sanity.cc) +target_link_libraries(perf-sanity fmt::fmt) + if (FMT_MODULE) # The tests need {fmt} to be compiled as traditional library # because of visibility of implementation details. @@ -138,7 +130,7 @@ if (NOT DEFINED MSVC_STATIC_RUNTIME AND MSVC) endif() if (NOT MSVC_STATIC_RUNTIME) - add_fmt_executable(posix-mock-test + add_executable(posix-mock-test posix-mock-test.cc ../src/format.cc ${TEST_MAIN_SRC}) target_include_directories( posix-mock-test PRIVATE ${PROJECT_SOURCE_DIR}/include) @@ -146,6 +138,9 @@ if (NOT MSVC_STATIC_RUNTIME) if (FMT_PEDANTIC) target_compile_options(posix-mock-test PRIVATE ${PEDANTIC_COMPILE_FLAGS}) endif () + if (MSVC) + target_compile_options(posix-mock-test PRIVATE /utf-8) + endif () add_test(NAME posix-mock-test COMMAND posix-mock-test) add_fmt_test(os-test) endif () @@ -226,7 +221,7 @@ if (FMT_PEDANTIC AND NOT WIN32 AND NOT ( "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}") endif () -# This test are disabled on Windows because it is only *NIX issue. +# This test is disabled on Windows because it is POSIX-specific. if (FMT_PEDANTIC AND NOT WIN32) add_test(static-export-test ${CMAKE_CTEST_COMMAND} -C ${CMAKE_BUILD_TYPE} diff --git a/third-party/fmt/test/add-subdirectory-test/main.cc b/third-party/fmt/test/add-subdirectory-test/main.cc index fcdf232e05..1d31cb9053 100644 --- a/third-party/fmt/test/add-subdirectory-test/main.cc +++ b/third-party/fmt/test/add-subdirectory-test/main.cc @@ -1,4 +1,4 @@ -#include "fmt/core.h" +#include "fmt/base.h" int main(int argc, char** argv) { for (int i = 0; i < argc; ++i) fmt::print("{}: {}\n", i, argv[i]); diff --git a/third-party/fmt/test/args-test.cc b/third-party/fmt/test/args-test.cc index 3ab3133598..e3efa244bf 100644 --- a/third-party/fmt/test/args-test.cc +++ b/third-party/fmt/test/args-test.cc @@ -38,12 +38,13 @@ struct custom_type { FMT_BEGIN_NAMESPACE template <> struct formatter { - auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) { + auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } template - auto format(const custom_type& p, FormatContext& ctx) -> decltype(ctx.out()) { + auto format(const custom_type& p, FormatContext& ctx) const + -> decltype(ctx.out()) { return fmt::format_to(ctx.out(), "cust={}", p.i); } }; @@ -68,11 +69,11 @@ struct to_stringable { FMT_BEGIN_NAMESPACE template <> struct formatter { - auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) { + auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } - auto format(to_stringable, format_context& ctx) -> decltype(ctx.out()) { + auto format(to_stringable, format_context& ctx) const -> decltype(ctx.out()) { return ctx.out(); } }; @@ -143,9 +144,9 @@ TEST(args_test, reserve) { fmt::dynamic_format_arg_store store; store.reserve(2, 1); store.push_back(1.5f); - store.push_back(fmt::arg("a1", 42)); - auto result = fmt::vformat("{a1} and {}", store); - EXPECT_EQ("42 and 1.5", result); + store.push_back(fmt::arg("a", 42)); + auto result = fmt::vformat("{} and {a}", store); + EXPECT_EQ("1.5 and 42", result); } struct copy_throwable { @@ -155,10 +156,11 @@ struct copy_throwable { FMT_BEGIN_NAMESPACE template <> struct formatter { - auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) { + auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } - auto format(copy_throwable, format_context& ctx) -> decltype(ctx.out()) { + auto format(copy_throwable, format_context& ctx) const + -> decltype(ctx.out()) { return ctx.out(); } }; @@ -184,3 +186,17 @@ TEST(args_test, move_constructor) { store.reset(); EXPECT_EQ(fmt::vformat("{} {} {a1}", moved_store), "42 foo foo"); } + +TEST(args_test, size) { + fmt::dynamic_format_arg_store store; + EXPECT_EQ(store.size(), 0); + + store.push_back(42); + EXPECT_EQ(store.size(), 1); + + store.push_back("Molybdenum"); + EXPECT_EQ(store.size(), 2); + + store.clear(); + EXPECT_EQ(store.size(), 0); +} diff --git a/third-party/fmt/test/assert-test.cc b/third-party/fmt/test/assert-test.cc index c74e617e68..368fb58782 100644 --- a/third-party/fmt/test/assert-test.cc +++ b/third-party/fmt/test/assert-test.cc @@ -9,7 +9,7 @@ // // For the license information refer to format.h. -#include "fmt/core.h" +#include "fmt/base.h" #include "gtest/gtest.h" TEST(assert_test, fail) { diff --git a/third-party/fmt/test/core-test.cc b/third-party/fmt/test/base-test.cc similarity index 61% rename from third-party/fmt/test/core-test.cc rename to third-party/fmt/test/base-test.cc index 1d84ffd774..f8af275d53 100644 --- a/third-party/fmt/test/core-test.cc +++ b/third-party/fmt/test/base-test.cc @@ -9,13 +9,12 @@ #include "test-assert.h" // clang-format on -#include "fmt/core.h" +#include "fmt/base.h" -#include // std::copy_n #include // INT_MAX #include // std::strlen #include // std::equal_to -#include // std::back_insert_iterator +#include // std::back_insert_iterator, std::distance #include // std::numeric_limits #include // std::string #include // std::is_same @@ -33,6 +32,11 @@ using testing::Return; # error core-test includes format.h #endif +fmt::appender copy(fmt::string_view s, fmt::appender out) { + for (char c : s) *out++ = c; + return out; +} + TEST(string_view_test, value_type) { static_assert(std::is_same::value, ""); } @@ -88,7 +92,11 @@ TEST(string_view_test, compare) { check_op(); } -TEST(core_test, is_output_iterator) { +TEST(base_test, is_locking) { + EXPECT_FALSE(fmt::detail::is_locking()); +} + +TEST(base_test, is_output_iterator) { EXPECT_TRUE((fmt::detail::is_output_iterator::value)); EXPECT_FALSE((fmt::detail::is_output_iterator::value)); EXPECT_FALSE((fmt::detail::is_output_iterator::value)); @@ -101,20 +109,11 @@ TEST(core_test, is_output_iterator) { char>::value)); } -TEST(core_test, buffer_appender) { - // back_insert_iterator is not default-constructible before C++20, so - // buffer_appender can only be default-constructible when back_insert_iterator - // is. - static_assert( - std::is_default_constructible< - std::back_insert_iterator>>::value == - std::is_default_constructible< - fmt::detail::buffer_appender>::value, - ""); - -#ifdef __cpp_lib_ranges - static_assert(std::output_iterator, char>); -#endif +TEST(base_test, is_back_insert_iterator) { + EXPECT_TRUE(fmt::detail::is_back_insert_iterator< + std::back_insert_iterator>::value); + EXPECT_FALSE(fmt::detail::is_back_insert_iterator< + std::front_insert_iterator>::value); } #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470 @@ -143,11 +142,12 @@ TEST(buffer_test, indestructible) { template struct mock_buffer final : buffer { MOCK_METHOD(size_t, do_grow, (size_t)); - void grow(size_t capacity) override { - this->set(this->data(), do_grow(capacity)); + static void grow(buffer& buf, size_t capacity) { + auto& self = static_cast(buf); + self.set(buf.data(), self.do_grow(capacity)); } - mock_buffer(T* data = nullptr, size_t buf_capacity = 0) { + mock_buffer(T* data = nullptr, size_t buf_capacity = 0) : buffer(grow) { this->set(data, buf_capacity); ON_CALL(*this, do_grow(_)).WillByDefault(Invoke([](size_t capacity) { return capacity; @@ -266,25 +266,15 @@ TEST(buffer_test, append_allocates_enough_storage) { buffer.append(test, test + 9); } -struct custom_context { - using char_type = char; - using parse_context_type = fmt::format_parse_context; - - bool called = false; - - template struct formatter_type { - FMT_CONSTEXPR auto parse(fmt::format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - const char* format(const T&, custom_context& ctx) { - ctx.called = true; - return nullptr; - } - }; - - void advance_to(const char*) {} -}; +TEST(base_test, get_buffer) { + mock_buffer buffer; + void* buffer_ptr = &buffer; + auto&& appender_result = fmt::detail::get_buffer(fmt::appender(buffer)); + EXPECT_EQ(&appender_result, buffer_ptr); + auto&& back_inserter_result = + fmt::detail::get_buffer(std::back_inserter(buffer)); + EXPECT_EQ(&back_inserter_result, buffer_ptr); +} struct test_struct {}; @@ -295,8 +285,7 @@ template struct formatter { } auto format(test_struct, format_context& ctx) const -> decltype(ctx.out()) { - auto test = string_view("test"); - return std::copy_n(test.data(), test.size(), ctx.out()); + return copy("test", ctx.out()); } }; FMT_END_NAMESPACE @@ -306,22 +295,14 @@ TEST(arg_test, format_args) { EXPECT_FALSE(args.get(1)); } -TEST(arg_test, make_value_with_custom_context) { - auto t = test_struct(); - auto arg = fmt::detail::value( - fmt::detail::arg_mapper().map(t)); - auto ctx = custom_context(); - auto parse_ctx = fmt::format_parse_context(""); - arg.custom.format(&t, parse_ctx, ctx); - EXPECT_TRUE(ctx.called); -} - // Use a unique result type to make sure that there are no undesirable // conversions. struct test_result {}; template struct mock_visitor { - template struct result { using type = test_result; }; + template struct result { + using type = test_result; + }; mock_visitor() { ON_CALL(*this, visit(_)).WillByDefault(Return(test_result())); @@ -338,10 +319,14 @@ template struct mock_visitor { } }; -template struct visit_type { using type = T; }; +template struct visit_type { + using type = T; +}; -#define VISIT_TYPE(type_, visit_type_) \ - template <> struct visit_type { using type = visit_type_; } +#define VISIT_TYPE(type_, visit_type_) \ + template <> struct visit_type { \ + using type = visit_type_; \ + } VISIT_TYPE(signed char, int); VISIT_TYPE(unsigned char, unsigned); @@ -356,32 +341,35 @@ VISIT_TYPE(long, long long); VISIT_TYPE(unsigned long, unsigned long long); #endif -#define CHECK_ARG(Char, expected, value) \ - { \ - testing::StrictMock> visitor; \ - EXPECT_CALL(visitor, visit(expected)); \ - using iterator = std::back_insert_iterator>; \ - auto var = value; \ - fmt::visit_format_arg( \ - visitor, \ - fmt::detail::make_arg>( \ - var)); \ - } +#if FMT_BUILTIN_TYPES +# define CHECK_ARG(expected, value) \ + { \ + testing::StrictMock> visitor; \ + EXPECT_CALL(visitor, visit(expected)); \ + auto var = value; \ + fmt::basic_format_arg(var).visit(visitor); \ + } +#else +# define CHECK_ARG(expected, value) +#endif #define CHECK_ARG_SIMPLE(value) \ { \ using value_type = decltype(value); \ typename visit_type::type expected = value; \ - CHECK_ARG(char, expected, value) \ - CHECK_ARG(wchar_t, expected, value) \ + CHECK_ARG(expected, value) \ } template class numeric_arg_test : public testing::Test {}; +#if FMT_BUILTIN_TYPES using test_types = testing::Types; +#else +using test_types = testing::Types; +#endif TYPED_TEST_SUITE(numeric_arg_test, test_types); template ::value, int> = 0> @@ -401,49 +389,44 @@ TYPED_TEST(numeric_arg_test, make_and_visit) { CHECK_ARG_SIMPLE(std::numeric_limits::max()); } -TEST(arg_test, char_arg) { CHECK_ARG(char, 'a', 'a'); } +TEST(arg_test, char_arg) { CHECK_ARG('a', 'a'); } TEST(arg_test, string_arg) { char str_data[] = "test"; char* str = str_data; const char* cstr = str; - CHECK_ARG(char, cstr, str); + CHECK_ARG(cstr, str); auto sv = fmt::string_view(str); - CHECK_ARG(char, sv, std::string(str)); -} - -TEST(arg_test, wstring_arg) { - wchar_t str_data[] = L"test"; - wchar_t* str = str_data; - const wchar_t* cstr = str; - - auto sv = fmt::basic_string_view(str); - CHECK_ARG(wchar_t, cstr, str); - CHECK_ARG(wchar_t, cstr, cstr); - CHECK_ARG(wchar_t, sv, std::wstring(str)); - CHECK_ARG(wchar_t, sv, fmt::basic_string_view(str)); + CHECK_ARG(sv, std::string(str)); } TEST(arg_test, pointer_arg) { void* p = nullptr; const void* cp = nullptr; - CHECK_ARG(char, cp, p); - CHECK_ARG(wchar_t, cp, p); + CHECK_ARG(cp, p); CHECK_ARG_SIMPLE(cp); } +TEST(arg_test, volatile_pointer_arg) { + const void* p = nullptr; + volatile int* vip = nullptr; + const volatile int* cvip = nullptr; + CHECK_ARG(p, static_cast(vip)); + CHECK_ARG(p, static_cast(cvip)); +} + struct check_custom { auto operator()(fmt::basic_format_arg::handle h) const -> test_result { struct test_buffer final : fmt::detail::buffer { char data[10]; - test_buffer() : fmt::detail::buffer(data, 0, 10) {} - void grow(size_t) override {} + test_buffer() + : fmt::detail::buffer([](buffer&, size_t) {}, data, 0, + 10) {} } buffer; auto parse_ctx = fmt::format_parse_context(""); - auto ctx = fmt::format_context(fmt::detail::buffer_appender(buffer), - fmt::format_args()); + auto ctx = fmt::format_context(fmt::appender(buffer), fmt::format_args()); h.format(parse_ctx, ctx); EXPECT_EQ("test", std::string(buffer.data, buffer.size())); return test_result(); @@ -456,26 +439,23 @@ TEST(arg_test, custom_arg) { mock_visitor::handle>; auto&& v = testing::StrictMock(); EXPECT_CALL(v, visit(_)).WillOnce(Invoke(check_custom())); - fmt::visit_format_arg(v, fmt::detail::make_arg(test)); + fmt::basic_format_arg(test).visit(v); } TEST(arg_test, visit_invalid_arg) { auto&& visitor = testing::StrictMock>(); EXPECT_CALL(visitor, visit(_)); - auto arg = fmt::basic_format_arg(); - fmt::visit_format_arg(visitor, arg); + fmt::basic_format_arg().visit(visitor); } #if FMT_USE_CONSTEXPR -enum class arg_id_result { none, empty, index, name }; +enum class arg_id_result { none, index, name }; struct test_arg_id_handler { arg_id_result res = arg_id_result::none; int index = 0; string_view name; - constexpr void on_auto() { res = arg_id_result::empty; } - constexpr void on_index(int i) { res = arg_id_result::index; index = i; @@ -494,9 +474,7 @@ constexpr test_arg_id_handler parse_arg_id(const char (&s)[N]) { return h; } -TEST(core_test, constexpr_parse_arg_id) { - static_assert(parse_arg_id(":").res == arg_id_result::empty, ""); - static_assert(parse_arg_id("}").res == arg_id_result::empty, ""); +TEST(base_test, constexpr_parse_arg_id) { static_assert(parse_arg_id("42:").res == arg_id_result::index, ""); static_assert(parse_arg_id("42:").index == 42, ""); static_assert(parse_arg_id("foo:").res == arg_id_result::name, ""); @@ -512,21 +490,21 @@ template constexpr auto parse_test_specs(const char (&s)[N]) { return specs; } -TEST(core_test, constexpr_parse_format_specs) { - static_assert(parse_test_specs("<").align == fmt::align::left, ""); - static_assert(parse_test_specs("*^").fill[0] == '*', ""); - static_assert(parse_test_specs("+").sign == fmt::sign::plus, ""); - static_assert(parse_test_specs("-").sign == fmt::sign::minus, ""); - static_assert(parse_test_specs(" ").sign == fmt::sign::space, ""); - static_assert(parse_test_specs("#").alt, ""); - static_assert(parse_test_specs("0").align == fmt::align::numeric, ""); - static_assert(parse_test_specs("L").localized, ""); +TEST(base_test, constexpr_parse_format_specs) { + static_assert(parse_test_specs("<").align() == fmt::align::left, ""); + static_assert(parse_test_specs("*^").fill_unit() == '*', ""); + static_assert(parse_test_specs("+").sign() == fmt::sign::plus, ""); + static_assert(parse_test_specs("-").sign() == fmt::sign::none, ""); + static_assert(parse_test_specs(" ").sign() == fmt::sign::space, ""); + static_assert(parse_test_specs("#").alt(), ""); + static_assert(parse_test_specs("0").align() == fmt::align::numeric, ""); + static_assert(parse_test_specs("L").localized(), ""); static_assert(parse_test_specs("42").width == 42, ""); - static_assert(parse_test_specs("{42}").width_ref.val.index == 42, ""); + static_assert(parse_test_specs("{42}").width_ref.index == 42, ""); static_assert(parse_test_specs(".42").precision == 42, ""); - static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, ""); - static_assert( - parse_test_specs("f").type == fmt::presentation_type::fixed_lower, ""); + static_assert(parse_test_specs(".{42}").precision_ref.index == 42, ""); + static_assert(parse_test_specs("f").type() == fmt::presentation_type::fixed, + ""); } struct test_format_string_handler { @@ -550,11 +528,11 @@ struct test_format_string_handler { template constexpr bool parse_string(const char (&s)[N]) { auto h = test_format_string_handler(); - fmt::detail::parse_format_string(fmt::string_view(s, N - 1), h); + fmt::detail::parse_format_string(fmt::string_view(s, N - 1), h); return !h.error; } -TEST(core_test, constexpr_parse_format_string) { +TEST(base_test, constexpr_parse_format_string) { static_assert(parse_string("foo"), ""); static_assert(!parse_string("}"), ""); static_assert(parse_string("{}"), ""); @@ -593,15 +571,6 @@ template <> struct formatter { }; FMT_END_NAMESPACE -TEST(core_test, has_formatter) { - using fmt::has_formatter; - using context = fmt::format_context; - static_assert(has_formatter::value, ""); - static_assert(!has_formatter::value, ""); - static_assert(!has_formatter::value, - ""); -} - struct const_formattable {}; struct nonconst_formattable {}; @@ -611,10 +580,9 @@ template <> struct formatter { return ctx.begin(); } - auto format(const const_formattable&, format_context& ctx) + auto format(const const_formattable&, format_context& ctx) const -> decltype(ctx.out()) { - auto test = string_view("test"); - return std::copy_n(test.data(), test.size(), ctx.out()); + return copy("test", ctx.out()); } }; @@ -623,10 +591,9 @@ template <> struct formatter { return ctx.begin(); } - auto format(nonconst_formattable&, format_context& ctx) + auto format(nonconst_formattable&, format_context& ctx) const -> decltype(ctx.out()) { - auto test = string_view("test"); - return std::copy_n(test.data(), test.size(), ctx.out()); + return copy("test", ctx.out()); } }; FMT_END_NAMESPACE @@ -647,189 +614,202 @@ template <> struct formatter { auto format(convertible_to_pointer_formattable, format_context& ctx) const -> decltype(ctx.out()) { - auto test = string_view("test"); - return std::copy_n(test.data(), test.size(), ctx.out()); + return copy("test", ctx.out()); } }; FMT_END_NAMESPACE enum class unformattable_scoped_enum {}; -TEST(core_test, is_formattable) { - static_assert(!fmt::is_formattable::value, ""); +TEST(base_test, is_formattable) { + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); #ifdef __cpp_char8_t - static_assert(!fmt::is_formattable::value, ""); + EXPECT_FALSE(fmt::is_formattable::value); #endif - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable>::value, - ""); - static_assert(fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, - ""); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable>::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); - static_assert(fmt::is_formattable::value, ""); - static_assert(fmt::is_formattable::value, ""); + EXPECT_TRUE(fmt::is_formattable::value); + EXPECT_TRUE(fmt::is_formattable::value); + EXPECT_TRUE(fmt::is_formattable::value); - static_assert(fmt::is_formattable::value, ""); -#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910 - static_assert(!fmt::is_formattable::value, ""); -#endif + EXPECT_TRUE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); - static_assert(!fmt::is_formattable::value, ""); + EXPECT_FALSE(fmt::is_formattable::value); const auto f = convertible_to_pointer_formattable(); - EXPECT_EQ(fmt::format("{}", f), "test"); + auto str = std::string(); + fmt::format_to(std::back_inserter(str), "{}", f); + EXPECT_EQ(str, "test"); - static_assert(!fmt::is_formattable::value, ""); + EXPECT_FALSE(fmt::is_formattable::value); struct s; - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); - static_assert(!fmt::is_formattable::value, ""); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable::value); } -TEST(core_test, format) { EXPECT_EQ(fmt::format("{}", 42), "42"); } +#ifdef __cpp_concepts +TEST(base_test, formattable_concept) { + static_assert(fmt::formattable); + static_assert(fmt::formattable); + static_assert(fmt::formattable); + static_assert(fmt::formattable); + static_assert(fmt::formattable); + static_assert(fmt::formattable); + static_assert(fmt::formattable); + static_assert(!fmt::formattable); +} +#endif -TEST(core_test, format_to) { +TEST(base_test, format_to) { auto s = std::string(); fmt::format_to(std::back_inserter(s), "{}", 42); EXPECT_EQ(s, "42"); } -#ifdef __cpp_lib_byte -TEST(core_test, format_byte) { - EXPECT_EQ(fmt::format("{}", std::byte(42)), "42"); -} -#endif +TEST(base_test, format_to_array) { + char buffer[4]; + auto result = fmt::format_to(buffer, "{}", 12345); + EXPECT_EQ(4, std::distance(&buffer[0], result.out)); + EXPECT_TRUE(result.truncated); + EXPECT_EQ(buffer + 4, result.out); + EXPECT_EQ("1234", fmt::string_view(buffer, 4)); -struct convertible_to_int { - operator int() const { return 42; } -}; + char* out = nullptr; + EXPECT_THROW(out = result, std::runtime_error); + (void)out; -struct convertible_to_cstring { - operator const char*() const { return "foo"; } -}; + result = fmt::format_to(buffer, "{:s}", "foobar"); + EXPECT_EQ(4, std::distance(&buffer[0], result.out)); + EXPECT_TRUE(result.truncated); + EXPECT_EQ(buffer + 4, result.out); + EXPECT_EQ("foob", fmt::string_view(buffer, 4)); -FMT_BEGIN_NAMESPACE -template <> struct formatter { - FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - auto format(convertible_to_int, format_context& ctx) const - -> decltype(ctx.out()) { - return std::copy_n("foo", 3, ctx.out()); - } -}; + buffer[0] = 'x'; + buffer[1] = 'x'; + buffer[2] = 'x'; + buffer[3] = 'x'; + result = fmt::format_to(buffer, "{}", 'A'); + EXPECT_EQ(1, std::distance(&buffer[0], result.out)); + EXPECT_FALSE(result.truncated); + EXPECT_EQ(buffer + 1, result.out); + EXPECT_EQ("Axxx", fmt::string_view(buffer, 4)); -template <> struct formatter { - FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - auto format(convertible_to_cstring, format_context& ctx) const - -> decltype(ctx.out()) { - return std::copy_n("bar", 3, ctx.out()); - } -}; -FMT_END_NAMESPACE + result = fmt::format_to(buffer, "{}{} ", 'B', 'C'); + EXPECT_EQ(3, std::distance(&buffer[0], result.out)); + EXPECT_FALSE(result.truncated); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("BC x", fmt::string_view(buffer, 4)); -TEST(core_test, formatter_overrides_implicit_conversion) { - EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo"); - EXPECT_EQ(fmt::format("{}", convertible_to_cstring()), "bar"); + result = fmt::format_to(buffer, "{}", "ABCDE"); + EXPECT_EQ(4, std::distance(&buffer[0], result.out)); + EXPECT_TRUE(result.truncated); + EXPECT_EQ("ABCD", fmt::string_view(buffer, 4)); + + result = fmt::format_to(buffer, "{}", std::string(1000, '*').c_str()); + EXPECT_EQ(4, std::distance(&buffer[0], result.out)); + EXPECT_TRUE(result.truncated); + EXPECT_EQ("****", fmt::string_view(buffer, 4)); } // Test that check is not found by ADL. template void check(T); -TEST(core_test, adl_check) { - EXPECT_EQ(fmt::format("{}", test_struct()), "test"); +TEST(base_test, adl_check) { + auto s = std::string(); + fmt::format_to(std::back_inserter(s), "{}", test_struct()); + EXPECT_EQ(s, "test"); } struct implicitly_convertible_to_string_view { operator fmt::string_view() const { return "foo"; } }; -TEST(core_test, no_implicit_conversion_to_string_view) { +TEST(base_test, no_implicit_conversion_to_string_view) { EXPECT_FALSE( fmt::is_formattable::value); } -#ifdef FMT_USE_STRING_VIEW -struct implicitly_convertible_to_std_string_view { - operator std::string_view() const { return "foo"; } -}; - -TEST(core_test, no_implicit_conversion_to_std_string_view) { - EXPECT_FALSE( - fmt::is_formattable::value); -} -#endif - -// std::is_constructible is broken in MSVC until version 2015. -#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1900 struct explicitly_convertible_to_string_view { explicit operator fmt::string_view() const { return "foo"; } }; -TEST(core_test, format_explicitly_convertible_to_string_view) { +TEST(base_test, format_explicitly_convertible_to_string_view) { // Types explicitly convertible to string_view are not formattable by // default because it may introduce ODR violations. static_assert( !fmt::is_formattable::value, ""); } -# ifdef FMT_USE_STRING_VIEW +#if FMT_CPLUSPLUS >= 201703L +struct implicitly_convertible_to_std_string_view { + operator std::string_view() const { return "foo"; } +}; + +TEST(base_test, no_implicit_conversion_to_std_string_view) { + EXPECT_FALSE( + fmt::is_formattable::value); +} + struct explicitly_convertible_to_std_string_view { explicit operator std::string_view() const { return "foo"; } }; -TEST(core_test, format_explicitly_convertible_to_std_string_view) { +TEST(base_test, format_explicitly_convertible_to_std_string_view) { // Types explicitly convertible to string_view are not formattable by // default because it may introduce ODR violations. static_assert( !fmt::is_formattable::value, ""); } -# endif -#endif +#endif // FMT_CPLUSPLUS >= 201703L -namespace adl_test { -template void make_format_args(const T&...) = delete; - -struct string : std::string {}; -} // namespace adl_test - -// Test that formatting functions compile when make_format_args is found by ADL. -TEST(core_test, adl) { - // Only check compilation and don't run the code to avoid polluting the output - // and since the output is tested elsewhere. - if (fmt::detail::const_check(true)) return; - auto s = adl_test::string(); - char buf[10]; - (void)fmt::format("{}", s); - fmt::format_to(buf, "{}", s); - fmt::format_to_n(buf, 10, "{}", s); - (void)fmt::formatted_size("{}", s); - fmt::print("{}", s); - fmt::print(stdout, "{}", s); +TEST(base_test, has_formatter) { + EXPECT_TRUE((fmt::detail::has_formatter())); + EXPECT_FALSE( + (fmt::detail::has_formatter())); } -TEST(core_test, has_const_formatter) { - EXPECT_TRUE((fmt::detail::has_const_formatter())); - EXPECT_FALSE((fmt::detail::has_const_formatter())); +TEST(base_test, format_nonconst) { + auto s = std::string(); + fmt::format_to(std::back_inserter(s), "{}", nonconst_formattable()); + EXPECT_EQ(s, "test"); } -TEST(core_test, format_nonconst) { - EXPECT_EQ(fmt::format("{}", nonconst_formattable()), "test"); +TEST(base_test, throw_in_buffer_dtor) { + enum { buffer_size = 256 }; + + struct throwing_iterator { + int& count; + + auto operator=(char) -> throwing_iterator& { + if (++count > buffer_size) throw std::exception(); + return *this; + } + auto operator*() -> throwing_iterator& { return *this; } + auto operator++() -> throwing_iterator& { return *this; } + auto operator++(int) -> throwing_iterator { return *this; } + }; + + try { + int count = 0; + fmt::format_to(throwing_iterator{count}, fmt::runtime("{:{}}{"), "", + buffer_size + 1); + } catch (const std::exception&) { + } } struct its_a_trap { @@ -846,13 +826,61 @@ template <> struct formatter { return ctx.begin(); } - auto format(its_a_trap, format_context& ctx) const -> decltype(ctx.out()) { - auto s = string_view("42"); - return std::copy(s.begin(), s.end(), ctx.out()); + auto format(its_a_trap, format_context& ctx) const + -> decltype(ctx.out()) const { + auto out = ctx.out(); + *out++ = 'x'; + return out; } }; FMT_END_NAMESPACE -TEST(core_test, trappy_conversion) { - EXPECT_EQ(fmt::format("{}", its_a_trap()), "42"); +TEST(base_test, trappy_conversion) { + auto s = std::string(); + fmt::format_to(std::back_inserter(s), "{}", its_a_trap()); + EXPECT_EQ(s, "x"); +} + +struct custom_container { + char data; + + using value_type = char; + + size_t size() const { return 0; } + void resize(size_t) {} + + void push_back(char) {} + char& operator[](size_t) { return data; } +}; + +FMT_BEGIN_NAMESPACE +template <> struct is_contiguous : std::true_type {}; +FMT_END_NAMESPACE + +TEST(base_test, format_to_custom_container) { + auto c = custom_container(); + fmt::format_to(std::back_inserter(c), ""); +} + +struct nondeterministic_format_string { + mutable int i = 0; + FMT_CONSTEXPR operator string_view() const { + return string_view("{}", i++ != 0 ? 2 : 0); + } +}; + +TEST(base_test, no_repeated_format_string_conversions) { +#if !FMT_GCC_VERSION + char buf[10]; + fmt::format_to(buf, nondeterministic_format_string()); +#endif +} + +TEST(base_test, format_context_accessors) { + class copier { + static fmt::format_context copy(fmt::appender app, + const fmt::format_context& ctx) { + return fmt::format_context(std::move(app), ctx.args(), ctx.locale()); + } + }; } diff --git a/third-party/fmt/test/chrono-test.cc b/third-party/fmt/test/chrono-test.cc index b2d03f9795..33eeb1847b 100644 --- a/third-party/fmt/test/chrono-test.cc +++ b/third-party/fmt/test/chrono-test.cc @@ -539,6 +539,7 @@ TEST(chrono_test, format_specs) { EXPECT_EQ(fmt::format("{:%I}", std::chrono::hours(24)), "12"); EXPECT_EQ(fmt::format("{:%I}", std::chrono::hours(4)), "04"); EXPECT_EQ(fmt::format("{:%I}", std::chrono::hours(14)), "02"); + EXPECT_EQ(fmt::format("{:%j}", days(12)), "12"); EXPECT_EQ(fmt::format("{:%j}", days(12345)), "12345"); EXPECT_EQ(fmt::format("{:%j}", std::chrono::hours(12345 * 24 + 12)), "12345"); EXPECT_EQ(fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345)), @@ -751,17 +752,21 @@ TEST(chrono_test, unsigned_duration) { TEST(chrono_test, weekday) { auto loc = get_locale("es_ES.UTF-8"); std::locale::global(loc); + auto sat = fmt::weekday(6); auto tm = std::tm(); tm.tm_wday = static_cast(sat.c_encoding()); EXPECT_EQ(fmt::format("{}", sat), "Sat"); + EXPECT_EQ(fmt::format("{:%a}", sat), "Sat"); + EXPECT_EQ(fmt::format("{:%A}", sat), "Saturday"); EXPECT_EQ(fmt::format("{:%a}", tm), "Sat"); if (loc != std::locale::classic()) { - auto saturdays = std::vector{"sáb", "sá."}; + auto saturdays = std::vector{"sáb", "sá.", "sáb."}; EXPECT_THAT(saturdays, Contains(fmt::format(loc, "{:L}", sat))); + EXPECT_THAT(saturdays, Contains(fmt::format(loc, "{:%a}", sat))); EXPECT_THAT(saturdays, Contains(fmt::format(loc, "{:%a}", tm))); } } @@ -791,6 +796,14 @@ TEST(chrono_test, cpp20_duration_subsecond_support) { "01.234000"); EXPECT_EQ(fmt::format("{:.6%S}", std::chrono::milliseconds{-1234}), "-01.234000"); + EXPECT_EQ(fmt::format("{:.2%S}", std::chrono::milliseconds{12345}), "12.34"); + EXPECT_EQ(fmt::format("{:.2%S}", std::chrono::milliseconds{12375}), "12.37"); + EXPECT_EQ(fmt::format("{:.2%S}", std::chrono::milliseconds{-12375}), + "-12.37"); + EXPECT_EQ(fmt::format("{:.0%S}", std::chrono::milliseconds{12054}), "12"); + EXPECT_EQ(fmt::format("{:.2%S}", std::chrono::milliseconds{99999}), "39.99"); + EXPECT_EQ(fmt::format("{:.2%S}", std::chrono::milliseconds{1000}), "01.00"); + EXPECT_EQ(fmt::format("{:.3%S}", std::chrono::milliseconds{1}), "00.001"); EXPECT_EQ(fmt::format("{:.3%S}", std::chrono::seconds{1234}), "34.000"); EXPECT_EQ(fmt::format("{:.3%S}", std::chrono::hours{1234}), "00.000"); EXPECT_EQ(fmt::format("{:.5%S}", dms(1.234)), "00.00123"); @@ -953,12 +966,11 @@ TEST(chrono_test, glibc_extensions) { std::chrono::seconds(3); EXPECT_EQ(fmt::format("{:%I,%H,%M,%S}", d), "01,01,02,03"); - EXPECT_EQ(fmt::format("{:%0I,%0H,%0M,%0S}", d), "01,01,02,03"); EXPECT_EQ(fmt::format("{:%_I,%_H,%_M,%_S}", d), " 1, 1, 2, 3"); EXPECT_EQ(fmt::format("{:%-I,%-H,%-M,%-S}", d), "1,1,2,3"); + EXPECT_EQ(fmt::format("{:%-I,%H,%M,%S}", d), "1,01,02,03"); EXPECT_EQ(fmt::format("{:%OI,%OH,%OM,%OS}", d), "01,01,02,03"); - EXPECT_EQ(fmt::format("{:%0OI,%0OH,%0OM,%0OS}", d), "01,01,02,03"); EXPECT_EQ(fmt::format("{:%_OI,%_OH,%_OM,%_OS}", d), " 1, 1, 2, 3"); EXPECT_EQ(fmt::format("{:%-OI,%-OH,%-OM,%-OS}", d), "1,1,2,3"); } @@ -966,12 +978,10 @@ TEST(chrono_test, glibc_extensions) { { const auto tm = make_tm(1970, 1, 1, 1, 2, 3); EXPECT_EQ(fmt::format("{:%I,%H,%M,%S}", tm), "01,01,02,03"); - EXPECT_EQ(fmt::format("{:%0I,%0H,%0M,%0S}", tm), "01,01,02,03"); EXPECT_EQ(fmt::format("{:%_I,%_H,%_M,%_S}", tm), " 1, 1, 2, 3"); EXPECT_EQ(fmt::format("{:%-I,%-H,%-M,%-S}", tm), "1,1,2,3"); EXPECT_EQ(fmt::format("{:%OI,%OH,%OM,%OS}", tm), "01,01,02,03"); - EXPECT_EQ(fmt::format("{:%0OI,%0OH,%0OM,%0OS}", tm), "01,01,02,03"); EXPECT_EQ(fmt::format("{:%_OI,%_OH,%_OM,%_OS}", tm), " 1, 1, 2, 3"); EXPECT_EQ(fmt::format("{:%-OI,%-OH,%-OM,%-OS}", tm), "1,1,2,3"); } @@ -979,21 +989,100 @@ TEST(chrono_test, glibc_extensions) { { const auto d = std::chrono::seconds(3) + std::chrono::milliseconds(140); EXPECT_EQ(fmt::format("{:%S}", d), "03.140"); - EXPECT_EQ(fmt::format("{:%0S}", d), "03.140"); EXPECT_EQ(fmt::format("{:%_S}", d), " 3.140"); EXPECT_EQ(fmt::format("{:%-S}", d), "3.140"); } { - const auto d = std::chrono::duration(3.14); + auto d = std::chrono::duration(3.14); EXPECT_EQ(fmt::format("{:%S}", d), "03.140000"); - EXPECT_EQ(fmt::format("{:%0S}", d), "03.140000"); EXPECT_EQ(fmt::format("{:%_S}", d), " 3.140000"); EXPECT_EQ(fmt::format("{:%-S}", d), "3.140000"); } + + { + auto t = std::tm(); + t.tm_yday = 7; + EXPECT_EQ(fmt::format("{:%U,%W,%V}", t), "02,01,01"); + EXPECT_EQ(fmt::format("{:%_U,%_W,%_V}", t), " 2, 1, 1"); + EXPECT_EQ(fmt::format("{:%-U,%-W,%-V}", t), "2,1,1"); + + EXPECT_EQ(fmt::format("{:%j}", t), "008"); + EXPECT_EQ(fmt::format("{:%_j}", t), " 8"); + EXPECT_EQ(fmt::format("{:%-j}", t), "8"); + } + + { + auto t = std::tm(); + t.tm_mday = 7; + EXPECT_EQ(fmt::format("{:%d}", t), "07"); + EXPECT_EQ(fmt::format("{:%_d}", t), " 7"); + EXPECT_EQ(fmt::format("{:%-d}", t), "7"); + + EXPECT_EQ(fmt::format("{:%e}", t), " 7"); + } + + { + auto t = std::tm(); + t.tm_year = 7 - 1900; + EXPECT_EQ(fmt::format("{:%Y}", t), "0007"); + EXPECT_EQ(fmt::format("{:%_Y}", t), " 7"); + EXPECT_EQ(fmt::format("{:%-Y}", t), "7"); + } + + { + auto t = std::tm(); + t.tm_year = -5 - 1900; + EXPECT_EQ(fmt::format( "{:%Y}", t), "-005"); + EXPECT_EQ(fmt::format("{:%_Y}", t), " -5"); + EXPECT_EQ(fmt::format("{:%-Y}", t), "-5"); + } + + { + auto t = std::tm(); + t.tm_mon = 7 - 1; + EXPECT_EQ(fmt::format("{:%m}", t), "07"); + EXPECT_EQ(fmt::format("{:%_m}", t), " 7"); + EXPECT_EQ(fmt::format("{:%-m}", t), "7"); + } + + } TEST(chrono_test, out_of_range) { auto d = std::chrono::duration(538976288); EXPECT_THROW((void)fmt::format("{:%j}", d), fmt::format_error); -} \ No newline at end of file +} + +TEST(chrono_test, year_month_day) { + auto loc = get_locale("es_ES.UTF-8"); + std::locale::global(loc); + + auto year = fmt::year(2024); + auto month = fmt::month(1); + auto day = fmt::day(1); + auto ymd = fmt::year_month_day(year, month, day); + + EXPECT_EQ(fmt::format("{}", year), "2024"); + EXPECT_EQ(fmt::format("{:%Y}", year), "2024"); + EXPECT_EQ(fmt::format("{:%y}", year), "24"); + + EXPECT_EQ(fmt::format("{}", month), "Jan"); + EXPECT_EQ(fmt::format("{:%m}", month), "01"); + EXPECT_EQ(fmt::format("{:%b}", month), "Jan"); + EXPECT_EQ(fmt::format("{:%B}", month), "January"); + + EXPECT_EQ(fmt::format("{}", day), "01"); + EXPECT_EQ(fmt::format("{:%d}", day), "01"); + + EXPECT_EQ(fmt::format("{}", ymd), "2024-01-01"); + EXPECT_EQ(fmt::format("{:%Y-%m-%d}", ymd), "2024-01-01"); + EXPECT_EQ(fmt::format("{:%Y-%b-%d}", ymd), "2024-Jan-01"); + EXPECT_EQ(fmt::format("{:%Y-%B-%d}", ymd), "2024-January-01"); + + if (loc != std::locale::classic()) { + auto months = std::vector{"ene.", "ene"}; + EXPECT_THAT(months, Contains(fmt::format(loc, "{:L}", month))); + EXPECT_THAT(months, Contains(fmt::format(loc, "{:%b}", month))); + } +} diff --git a/third-party/fmt/test/compile-error-test/CMakeLists.txt b/third-party/fmt/test/compile-error-test/CMakeLists.txt index c4a160688d..a86996e21f 100644 --- a/third-party/fmt/test/compile-error-test/CMakeLists.txt +++ b/third-party/fmt/test/compile-error-test/CMakeLists.txt @@ -115,8 +115,7 @@ function (run_tests) endif () endfunction () - -# check if the source file skeleton compiles +# Check if the source file skeleton compiles. expect_compile(check "") expect_compile(check-error "compilation_error" ERROR) @@ -166,31 +165,6 @@ expect_compile(format-lots-of-arguments-with-function " fmt::format(\"\", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, f); " ERROR) -# Check if user-defined literals are available -include(CheckCXXSourceCompiles) -set(CMAKE_REQUIRED_FLAGS ${CXX_STANDARD_FLAG}) -check_cxx_source_compiles(" - void operator\"\" _udl(long double); - int main() {}" - SUPPORTS_USER_DEFINED_LITERALS) -set(CMAKE_REQUIRED_FLAGS ) -if (NOT SUPPORTS_USER_DEFINED_LITERALS) - set (SUPPORTS_USER_DEFINED_LITERALS OFF) -endif () - -# Make sure that compiler features detected in the header -# match the features detected in CMake. -if (SUPPORTS_USER_DEFINED_LITERALS) - set(supports_udl 1) -else () - set(supports_udl 0) -endif () -expect_compile(udl-check " - #if FMT_USE_USER_DEFINED_LITERALS != ${supports_udl} - # error - #endif -") - if (CMAKE_CXX_STANDARD GREATER_EQUAL 20) # Compile-time argument type check expect_compile(format-string-number-spec " diff --git a/third-party/fmt/test/compile-fp-test.cc b/third-party/fmt/test/compile-fp-test.cc index 5b46d74bcd..3afb769084 100644 --- a/third-party/fmt/test/compile-fp-test.cc +++ b/third-party/fmt/test/compile-fp-test.cc @@ -8,10 +8,7 @@ #include "fmt/compile.h" #include "gmock/gmock.h" -#if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806 && \ - defined(__cpp_constexpr) && __cpp_constexpr >= 201907 && \ - defined(__cpp_constexpr_dynamic_alloc) && \ - __cpp_constexpr_dynamic_alloc >= 201907 && FMT_CPLUSPLUS >= 202002L +#if FMT_USE_CONSTEVAL template struct test_string { template constexpr bool operator==(const T& rhs) const noexcept { @@ -60,4 +57,5 @@ TEST(compile_time_formatting_test, floating_point) { EXPECT_EQ("+inf", test_format<5>(FMT_COMPILE("{:+}"), inf)); EXPECT_EQ("-inf", test_format<5>(FMT_COMPILE("{}"), -inf)); } -#endif + +#endif // FMT_USE_CONSTEVAL diff --git a/third-party/fmt/test/compile-test.cc b/third-party/fmt/test/compile-test.cc index 8551303efc..b4c7e4b87f 100644 --- a/third-party/fmt/test/compile-test.cc +++ b/third-party/fmt/test/compile-test.cc @@ -7,20 +7,16 @@ #include "fmt/compile.h" +#include +#include #include +#include #include "fmt/chrono.h" +#include "fmt/ranges.h" #include "gmock/gmock.h" #include "gtest-extra.h" -TEST(iterator_test, counting_iterator) { - auto it = fmt::detail::counting_iterator(); - auto prev = it++; - EXPECT_EQ(prev.count(), 0); - EXPECT_EQ(it.count(), 1); - EXPECT_EQ((it + 41).count(), 42); -} - TEST(compile_test, compile_fallback) { // FMT_COMPILE should fallback on runtime formatting when `if constexpr` is // not available. @@ -34,7 +30,7 @@ struct type_with_get { FMT_BEGIN_NAMESPACE template <> struct formatter : formatter { template - auto format(type_with_get, FormatContext& ctx) -> decltype(ctx.out()) { + auto format(type_with_get, FormatContext& ctx) const -> decltype(ctx.out()) { return formatter::format(42, ctx); } }; @@ -84,6 +80,16 @@ TEST(compile_test, format_default) { # endif } +TEST(compile_test, format_escape) { + EXPECT_EQ("\"string\"", fmt::format(FMT_COMPILE("{:?}"), "string")); + EXPECT_EQ("prefix \"string\"", + fmt::format(FMT_COMPILE("prefix {:?}"), "string")); + EXPECT_EQ("\"string\" suffix", + fmt::format(FMT_COMPILE("{:?} suffix"), "string")); + EXPECT_EQ("\"abc\"", fmt::format(FMT_COMPILE("{0:<5?}"), "abc")); + EXPECT_EQ("\"abc\" ", fmt::format(FMT_COMPILE("{0:<7?}"), "abc")); +} + TEST(compile_test, format_wide_string) { EXPECT_EQ(L"42", fmt::format(FMT_COMPILE(L"{}"), 42)); } @@ -195,7 +201,22 @@ TEST(compile_test, format_to_n) { EXPECT_STREQ("2a", buffer); } -# ifdef __cpp_lib_bit_cast +TEST(compile_test, output_iterators) { + std::list out; + fmt::format_to(std::back_inserter(out), FMT_COMPILE("{}"), 42); + EXPECT_EQ("42", std::string(out.begin(), out.end())); + + std::stringstream s; + fmt::format_to(std::ostream_iterator(s), FMT_COMPILE("{}"), 42); + EXPECT_EQ("42", s.str()); + + std::stringstream s2; + fmt::format_to(std::ostreambuf_iterator(s2), FMT_COMPILE("{}.{:06d}"), + 42, 43); + EXPECT_EQ("42.000043", s2.str()); +} + +# if FMT_USE_CONSTEVAL && (!FMT_MSC_VERSION || FMT_MSC_VERSION >= 1940) TEST(compile_test, constexpr_formatted_size) { FMT_CONSTEXPR20 size_t size = fmt::formatted_size(FMT_COMPILE("{}"), 42); EXPECT_EQ(size, 2); @@ -226,10 +247,14 @@ TEST(compile_test, unknown_format_fallback) { EXPECT_EQ(" 42 ", fmt::format(FMT_COMPILE("{name:^4}"), fmt::arg("name", 42))); - std::vector v; - fmt::format_to(std::back_inserter(v), FMT_COMPILE("{name:^4}"), + std::vector v1; + fmt::format_to(std::back_inserter(v1), FMT_COMPILE("{}"), 42); + EXPECT_EQ("42", fmt::string_view(v1.data(), v1.size())); + + std::vector v2; + fmt::format_to(std::back_inserter(v2), FMT_COMPILE("{name:^4}"), fmt::arg("name", 42)); - EXPECT_EQ(" 42 ", fmt::string_view(v.data(), v.size())); + EXPECT_EQ(" 42 ", fmt::string_view(v2.data(), v2.size())); char buffer[4]; auto result = fmt::format_to_n(buffer, 4, FMT_COMPILE("{name:^5}"), @@ -262,11 +287,23 @@ TEST(compile_test, to_string_and_formatter) { fmt::format(FMT_COMPILE("{}"), to_stringable()); } +struct std_context_test {}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter : formatter { + auto format(std_context_test, format_context& ctx) const + -> decltype(ctx.out()) { + return ctx.out(); + } +}; +FMT_END_NAMESPACE + TEST(compile_test, print) { EXPECT_WRITE(stdout, fmt::print(FMT_COMPILE("Don't {}!"), "panic"), "Don't panic!"); EXPECT_WRITE(stderr, fmt::print(stderr, FMT_COMPILE("Don't {}!"), "panic"), "Don't panic!"); + fmt::print(FMT_COMPILE("{}"), std_context_test()); } #endif @@ -279,21 +316,29 @@ TEST(compile_test, compile_format_string_literal) { } #endif -// MSVS 2019 19.29.30145.0 - Support C++20 and OK. +#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) +template auto check_is_compiled_string(const S&) -> bool { + return fmt::is_compiled_string::value; +} + +TEST(compile_test, is_compiled_string) { + EXPECT_TRUE(check_is_compiled_string(FMT_COMPILE("asdf"))); + EXPECT_TRUE(check_is_compiled_string(FMT_COMPILE("{}"))); +} +#endif + +// MSVS 2019 19.29.30145.0 - OK // MSVS 2022 19.32.31332.0, 19.37.32826.1 - compile-test.cc(362,3): fatal error // C1001: Internal compiler error. // (compiler file // 'D:\a\_work\1\s\src\vctools\Compiler\CxxFE\sl\p1\c\constexpr\constexpr.cpp', // line 8635) -#if (FMT_CPLUSPLUS >= 202002L || \ - (FMT_CPLUSPLUS >= 201709L && FMT_GCC_VERSION >= 1002)) && \ - ((!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE >= 10) && \ - (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION >= 10000) && \ - (!FMT_MSC_VERSION || \ - (FMT_MSC_VERSION >= 1928 && FMT_MSC_VERSION < 1930))) && \ +#if FMT_USE_CONSTEVAL && \ + (!FMT_MSC_VERSION || \ + (FMT_MSC_VERSION >= 1928 && FMT_MSC_VERSION < 1930)) && \ defined(__cpp_lib_is_constant_evaluated) template struct test_string { - template constexpr bool operator==(const T& rhs) const noexcept { + template constexpr auto operator==(const T& rhs) const -> bool { return fmt::basic_string_view(rhs).compare(buffer) == 0; } Char buffer[max_string_length]{}; @@ -334,6 +379,7 @@ TEST(compile_time_formatting_test, integer) { EXPECT_EQ("0X4A", test_format<5>(FMT_COMPILE("{:#X}"), 0x4a)); EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42)); + EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42l)); EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42ll)); EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42ull)); diff --git a/third-party/fmt/test/cuda-test/cpp14.cc b/third-party/fmt/test/cuda-test/cpp14.cc index ad8463962f..59db442edd 100644 --- a/third-party/fmt/test/cuda-test/cpp14.cc +++ b/third-party/fmt/test/cuda-test/cpp14.cc @@ -1,4 +1,4 @@ -#include +#include // The purpose of this part is to ensure NVCC's host compiler also supports // the standard version. See 'cuda-cpp14.cu'. diff --git a/third-party/fmt/test/cuda-test/cuda-cpp14.cu b/third-party/fmt/test/cuda-test/cuda-cpp14.cu index 76a9d08836..9fc36c931a 100644 --- a/third-party/fmt/test/cuda-test/cuda-cpp14.cu +++ b/third-party/fmt/test/cuda-test/cuda-cpp14.cu @@ -10,7 +10,7 @@ // https://en.cppreference.com/w/cpp/preprocessor/replace#Predefined_macros static_assert(__cplusplus >= 201402L, "expect C++ 2014 for nvcc"); -#include +#include #include #include diff --git a/third-party/fmt/test/format-impl-test.cc b/third-party/fmt/test/format-impl-test.cc index eda1f23958..4ebf2a6eb4 100644 --- a/third-party/fmt/test/format-impl-test.cc +++ b/third-party/fmt/test/format-impl-test.cc @@ -283,7 +283,7 @@ struct double_double { double a; double b; - explicit constexpr double_double(double a_val = 0, double b_val = 0) + constexpr explicit double_double(double a_val = 0, double b_val = 0) : a(a_val), b(b_val) {} operator double() const { return a + b; } @@ -299,7 +299,7 @@ bool operator>=(const double_double& lhs, const double_double& rhs) { struct slow_float { float value; - explicit constexpr slow_float(float val = 0) : value(val) {} + constexpr explicit slow_float(float val = 0) : value(val) {} operator float() const { return value; } auto operator-() const -> slow_float { return slow_float(-value); } }; @@ -312,6 +312,7 @@ template <> struct numeric_limits { // is_iec559 is true for double-double in libstdc++. static constexpr bool is_iec559 = true; static constexpr int digits = 106; + static constexpr int digits10 = 33; }; template <> struct is_floating_point : std::true_type {}; @@ -341,10 +342,10 @@ TEST(format_impl_test, write_dragon_even) { auto s = std::string(); fmt::detail::write(std::back_inserter(s), slow_float(33554450.0f), {}); // Specializing is_floating_point is broken in MSVC. - if (!FMT_MSC_VERSION) EXPECT_EQ(s, "33554450"); + if (!FMT_MSC_VERSION) EXPECT_EQ(s, "3.355445e+07"); } -#if defined(_WIN32) && !defined(FMT_WINDOWS_NO_WCHAR) +#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) # include TEST(format_impl_test, write_console_signature) { diff --git a/third-party/fmt/test/format-test.cc b/third-party/fmt/test/format-test.cc index 325bef996b..c16f895bed 100644 --- a/third-party/fmt/test/format-test.cc +++ b/third-party/fmt/test/format-test.cc @@ -15,18 +15,28 @@ #include // uint32_t -#include // INT_MAX -#include // std::signbit -#include // std::strlen -#include // std::back_inserter -#include // std::list -#include // std::unique_ptr -#include // std::is_default_constructible +#include // fegetexceptflag and FE_ALL_EXCEPT +#include // INT_MAX +#include // std::signbit +#include // std::condition_variable +#include // std::strlen +#include // std::back_inserter +#include // std::list +#include // std::mutex +#include // std::string +#include // std::thread +#include // std::is_default_constructible +#if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE() +# include +#endif + +#include + +#include #include "gtest-extra.h" #include "mock-allocator.h" #include "util.h" - using fmt::basic_memory_buffer; using fmt::format_error; using fmt::memory_buffer; @@ -38,6 +48,10 @@ using fmt::detail::uint128_fallback; using testing::Return; using testing::StrictMock; +#ifdef __cpp_lib_concepts +static_assert(std::output_iterator); +#endif + enum { buffer_size = 256 }; TEST(uint128_test, ctor) { @@ -106,6 +120,14 @@ TEST(float_test, isfinite) { #endif } +void check_no_fp_exception() { + fexcept_t fe; + fegetexceptflag(&fe, FE_ALL_EXCEPT); + + // No exception flags should have been set + EXPECT_TRUE(fe == 0); +} + template void check_isnan() { using fmt::detail::isnan; EXPECT_FALSE(isnan(Float(0.0))); @@ -118,6 +140,17 @@ template void check_isnan() { EXPECT_FALSE(isnan(Float(-limits::infinity()))); EXPECT_TRUE(isnan(Float(limits::quiet_NaN()))); EXPECT_TRUE(isnan(Float(-limits::quiet_NaN()))); + + // Sanity check: make sure no error has occurred before we start + check_no_fp_exception(); + + // Check that no exception is raised for the non-NaN case + isnan(Float(42.0)); + check_no_fp_exception(); + + // Check that no exception is raised for the NaN case + isnan(Float(limits::quiet_NaN())); + check_no_fp_exception(); } TEST(float_test, isnan) { @@ -240,7 +273,8 @@ TEST(util_test, format_system_error) { throws_on_alloc = true; } if (!throws_on_alloc) { - fmt::print("warning: std::allocator allocates {} chars\n", max_size); + fmt::print(stderr, "warning: std::allocator allocates {} chars\n", + max_size); return; } } @@ -447,8 +481,14 @@ TEST(memory_buffer_test, max_size_allocator_overflow) { EXPECT_THROW(buffer.resize(161), std::exception); } +TEST(format_test, digits2_alignment) { + auto p = + fmt::detail::bit_cast(fmt::detail::digits2(0)); + EXPECT_EQ(p % 2, 0); +} + TEST(format_test, exception_from_lib) { - EXPECT_THROW_MSG(fmt::throw_format_error("test"), format_error, "test"); + EXPECT_THROW_MSG(fmt::report_error("test"), format_error, "test"); } TEST(format_test, escape) { @@ -556,6 +596,9 @@ TEST(format_test, named_arg) { "argument not found"); EXPECT_THROW_MSG((void)fmt::format(runtime("{a}"), 42), format_error, "argument not found"); + EXPECT_THROW_MSG((void)fmt::format(runtime("{a} {}"), fmt::arg("a", 2), 42), + format_error, + "cannot switch from manual to automatic argument indexing"); } TEST(format_test, auto_arg_index) { @@ -767,7 +810,7 @@ TEST(format_test, hash_flag) { EXPECT_EQ(fmt::format("{:#.2g}", 0.5), "0.50"); EXPECT_EQ(fmt::format("{:#.0f}", 0.5), "0."); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#"), 'c'), format_error, - "missing '}' in format string"); + "invalid format specifier for char"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#}"), 'c'), format_error, "invalid format specifier for char"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#}"), "abc"), format_error, @@ -788,7 +831,7 @@ TEST(format_test, zero_flag) { EXPECT_EQ(fmt::format("{0:07}", -42.0), "-000042"); EXPECT_EQ(fmt::format("{0:07}", -42.0l), "-000042"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:0"), 'c'), format_error, - "missing '}' in format string"); + "invalid format specifier for char"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:05}"), 'c'), format_error, "invalid format specifier for char"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:05}"), "abc"), format_error, @@ -835,6 +878,10 @@ TEST(format_test, width) { EXPECT_EQ(fmt::format("{:>06.0f}", 0.00884311), " 0"); } +auto bad_dynamic_spec_msg = FMT_BUILTIN_TYPES + ? "width/precision is out of range" + : "width/precision is not integer"; + TEST(format_test, runtime_width) { auto int_maxer = std::to_string(INT_MAX + 1u); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{" + int_maxer), 0), @@ -857,23 +904,23 @@ TEST(format_test, runtime_width) { "invalid format string"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, -1), format_error, - "negative width"); + "width/precision is out of range"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (INT_MAX + 1u)), - format_error, "number is too big"); + format_error, bad_dynamic_spec_msg); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, -1l), format_error, - "negative width"); + bad_dynamic_spec_msg); if (fmt::detail::const_check(sizeof(long) > sizeof(int))) { long value = INT_MAX; EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (value + 1)), - format_error, "number is too big"); + format_error, bad_dynamic_spec_msg); } EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (INT_MAX + 1ul)), - format_error, "number is too big"); + format_error, bad_dynamic_spec_msg); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, '0'), format_error, - "width is not integer"); + "width/precision is not integer"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, 0.0), format_error, - "width is not integer"); + "width/precision is not integer"); EXPECT_EQ(fmt::format("{0:{1}}", -42, 4), " -42"); EXPECT_EQ(fmt::format("{0:{1}}", 42u, 5), " 42"); @@ -890,6 +937,10 @@ TEST(format_test, runtime_width) { EXPECT_EQ(fmt::format("{:{}}", 42, short(4)), " 42"); } +TEST(format_test, exponent_range) { + for (int e = -1074; e <= 1023; ++e) (void)fmt::format("{}", std::ldexp(1, e)); +} + TEST(format_test, precision) { char format_str[buffer_size]; safe_sprintf(format_str, "{0:.%u", UINT_MAX); @@ -912,7 +963,7 @@ TEST(format_test, precision) { EXPECT_THROW_MSG((void)fmt::format(runtime("{0:."), 0.0), format_error, "invalid precision"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.}"), 0.0), format_error, - "invalid precision"); + "invalid format string"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2"), 0), format_error, "invalid format specifier"); @@ -948,6 +999,9 @@ TEST(format_test, precision) { EXPECT_EQ(fmt::format("{0:.3}", 1.1), "1.1"); EXPECT_EQ(fmt::format("{:.0e}", 1.0L), "1e+00"); EXPECT_EQ(fmt::format("{:9.1e}", 0.0), " 0.0e+00"); + EXPECT_EQ(fmt::format("{:.7f}", 0.0000000000000071054273576010018587L), + "0.0000000"); + EXPECT_EQ( fmt::format("{:.494}", 4.9406564584124654E-324), "4.9406564584124654417656879286822137236505980261432476442558568250067550" @@ -1014,7 +1068,8 @@ TEST(format_test, precision) { EXPECT_EQ(fmt::format("{:#.0f}", 123.0), "123."); EXPECT_EQ(fmt::format("{:.02f}", 1.234), "1.23"); EXPECT_EQ(fmt::format("{:.1g}", 0.001), "0.001"); - EXPECT_EQ(fmt::format("{}", 1019666432.0f), "1019666400"); + EXPECT_EQ(fmt::format("{}", 123456789.0f), "1.2345679e+08"); + EXPECT_EQ(fmt::format("{}", 1019666432.0f), "1.0196664e+09"); EXPECT_EQ(fmt::format("{:.0e}", 9.5), "1e+01"); EXPECT_EQ(fmt::format("{:.1e}", 1e-34), "1.0e-34"); @@ -1030,13 +1085,15 @@ TEST(format_test, precision) { EXPECT_THROW_MSG( (void)fmt::format("{:.2147483646f}", -2.2121295195081227E+304), format_error, "number is too big"); + EXPECT_THROW_MSG((void)fmt::format(runtime("{:.f}"), 42.0), format_error, + "invalid format string"); EXPECT_EQ(fmt::format("{0:.2}", "str"), "st"); EXPECT_EQ(fmt::format("{0:.5}", "вожыкі"), "вожык"); EXPECT_EQ(fmt::format("{0:.6}", "123456\xad"), "123456"); } -TEST(xchar_test, utf8_precision) { +TEST(format_test, utf8_precision) { auto result = fmt::format("{:.4}", "caf\u00e9s"); // cafés EXPECT_EQ(fmt::detail::compute_width(result), 4); EXPECT_EQ(result, "caf\u00e9"); @@ -1073,23 +1130,23 @@ TEST(format_test, runtime_precision) { "invalid format string"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, -1), - format_error, "negative precision"); + format_error, "width/precision is out of range"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, (INT_MAX + 1u)), - format_error, "number is too big"); + format_error, bad_dynamic_spec_msg); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, -1l), - format_error, "negative precision"); + format_error, bad_dynamic_spec_msg); if (fmt::detail::const_check(sizeof(long) > sizeof(int))) { long value = INT_MAX; EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, (value + 1)), - format_error, "number is too big"); + format_error, bad_dynamic_spec_msg); } EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, (INT_MAX + 1ul)), - format_error, "number is too big"); + format_error, bad_dynamic_spec_msg); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, '0'), - format_error, "precision is not integer"); + format_error, "width/precision is not integer"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, 0.0), - format_error, "precision is not integer"); + format_error, "width/precision is not integer"); EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42, 2), format_error, "invalid format specifier"); @@ -1540,18 +1597,6 @@ TEST(format_test, format_pointer) { fmt::format("{0}", reinterpret_cast(~uintptr_t()))); EXPECT_EQ("0x1234", fmt::format("{}", fmt::ptr(reinterpret_cast(0x1234)))); - std::unique_ptr up(new int(1)); - EXPECT_EQ(fmt::format("{}", fmt::ptr(up.get())), - fmt::format("{}", fmt::ptr(up))); - struct custom_deleter { - void operator()(int* p) const { delete p; } - }; - std::unique_ptr upcd(new int(1)); - EXPECT_EQ(fmt::format("{}", fmt::ptr(upcd.get())), - fmt::format("{}", fmt::ptr(upcd))); - std::shared_ptr sp(new int(1)); - EXPECT_EQ(fmt::format("{}", fmt::ptr(sp.get())), - fmt::format("{}", fmt::ptr(sp))); EXPECT_EQ(fmt::format("{}", fmt::detail::bit_cast( &function_pointer_test)), fmt::format("{}", fmt::ptr(function_pointer_test))); @@ -1603,7 +1648,8 @@ struct string_viewable {}; FMT_BEGIN_NAMESPACE template <> struct formatter : formatter { - auto format(string_viewable, format_context& ctx) -> decltype(ctx.out()) { + auto format(string_viewable, format_context& ctx) const + -> decltype(ctx.out()) { return formatter::format("foo", ctx); } }; @@ -1621,8 +1667,8 @@ struct explicitly_convertible_to_std_string_view { template <> struct fmt::formatter : formatter { - auto format(explicitly_convertible_to_std_string_view v, format_context& ctx) - -> decltype(ctx.out()) { + auto format(explicitly_convertible_to_std_string_view v, + format_context& ctx) const -> decltype(ctx.out()) { return fmt::format_to(ctx.out(), "'{}'", std::string_view(v)); } }; @@ -1631,6 +1677,20 @@ TEST(format_test, format_explicitly_convertible_to_std_string_view) { EXPECT_EQ("'foo'", fmt::format("{}", explicitly_convertible_to_std_string_view())); } + +struct convertible_to_std_string_view { + operator std::string_view() const noexcept { return "Hi there"; } +}; +FMT_BEGIN_NAMESPACE +template <> +class formatter + : public formatter {}; +FMT_END_NAMESPACE + +TEST(format_test, format_implicitly_convertible_and_inherits_string_view) { + static_assert(fmt::is_formattable{}, ""); + EXPECT_EQ("Hi there", fmt::format("{}", convertible_to_std_string_view{})); +} #endif class Answer {}; @@ -1644,7 +1704,7 @@ template <> struct formatter { return it; } - auto format(const date& d, format_context& ctx) -> decltype(ctx.out()) { + auto format(const date& d, format_context& ctx) const -> decltype(ctx.out()) { // Namespace-qualify to avoid ambiguity with std::format_to. fmt::format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day()); return ctx.out(); @@ -1653,7 +1713,7 @@ template <> struct formatter { template <> struct formatter : formatter { template - auto format(Answer, FormatContext& ctx) -> decltype(ctx.out()) { + auto format(Answer, FormatContext& ctx) const -> decltype(ctx.out()) { return formatter::format(42, ctx); } }; @@ -1753,6 +1813,100 @@ TEST(format_test, print) { "Don't panic!\n"); } +TEST(format_test, big_print) { + enum { count = 5000 }; + auto big_print = []() { + for (int i = 0; i < count / 5; ++i) fmt::print("xxxxx"); + }; + EXPECT_WRITE(stdout, big_print(), std::string(count, 'x')); +} + +// Windows CRT implements _IOLBF incorrectly (full buffering). +#if FMT_USE_FCNTL + +# ifndef _WIN32 +TEST(format_test, line_buffering) { + auto pipe = fmt::pipe(); + + int write_fd = pipe.write_end.descriptor(); + auto write_end = pipe.write_end.fdopen("w"); + setvbuf(write_end.get(), nullptr, _IOLBF, 4096); + write_end.print("42\n"); + close(write_fd); + try { + write_end.close(); + } catch (const std::system_error&) { + } + + auto read_end = pipe.read_end.fdopen("r"); + std::thread reader([&]() { + int n = 0; + int result = fscanf(read_end.get(), "%d", &n); + (void)result; + EXPECT_EQ(n, 42); + }); + + reader.join(); +} +# endif + +TEST(format_test, buffer_boundary) { + auto pipe = fmt::pipe(); + + auto write_end = pipe.write_end.fdopen("w"); + setvbuf(write_end.get(), nullptr, _IOFBF, 4096); + for (int i = 3; i < 4094; i++) + write_end.print("{}", (i % 73) != 0 ? 'x' : '\n'); + write_end.print("{} {}", 1234, 567); + write_end.close(); + + auto read_end = pipe.read_end.fdopen("r"); + char buf[4091] = {}; + size_t n = fread(buf, 1, sizeof(buf), read_end.get()); + EXPECT_EQ(n, sizeof(buf)); + EXPECT_STREQ(fgets(buf, sizeof(buf), read_end.get()), "1234 567"); +} + +#endif // FMT_USE_FCNTL + +struct deadlockable { + int value = 0; + mutable std::mutex mutex; +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter { + FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + auto format(const deadlockable& d, format_context& ctx) const + -> decltype(ctx.out()) { + std::lock_guard lock(d.mutex); + return format_to(ctx.out(), "{}", d.value); + } +}; +FMT_END_NAMESPACE + +TEST(format_test, locking_formatter) { + auto f = fmt::buffered_file(); + try { + f = fmt::buffered_file("/dev/null", "w"); + } catch (const std::system_error&) { + fmt::print(stderr, "warning: /dev/null is not supported\n"); + return; + } + deadlockable d; + auto t = std::thread([&]() { + fmt::print(f.get(), "start t\n"); + std::lock_guard lock(d.mutex); + for (int i = 0; i < 1000000; ++i) d.value += 10; + fmt::print(f.get(), "done\n"); + }); + for (int i = 0; i < 100; ++i) fmt::print(f.get(), "{}", d); + t.join(); +} + TEST(format_test, variadic) { EXPECT_EQ(fmt::format("{}c{}", "ab", 1), "abc1"); } @@ -1766,6 +1920,9 @@ TEST(format_test, bytes) { TEST(format_test, group_digits_view) { EXPECT_EQ(fmt::format("{}", fmt::group_digits(10000000)), "10,000,000"); EXPECT_EQ(fmt::format("{:8}", fmt::group_digits(1000)), " 1,000"); + EXPECT_EQ(fmt::format("{}", fmt::group_digits(-10000000)), "-10,000,000"); + EXPECT_EQ(fmt::format("{:8}", fmt::group_digits(-1000)), " -1,000"); + EXPECT_EQ(fmt::format("{:8}", fmt::group_digits(-100)), " -100"); } #ifdef __cpp_generic_lambdas @@ -1777,7 +1934,8 @@ FMT_BEGIN_NAMESPACE template <> struct formatter : nested_formatter { auto format(point p, format_context& ctx) const -> decltype(ctx.out()) { return write_padded(ctx, [this, p](auto out) -> decltype(out) { - return fmt::format_to(out, "({}, {})", nested(p.x), nested(p.y)); + return fmt::format_to(out, "({}, {})", this->nested(p.x), + this->nested(p.y)); }); } }; @@ -1791,40 +1949,6 @@ TEST(format_test, nested_formatter) { enum test_enum { foo, bar }; auto format_as(test_enum e) -> int { return e; } -TEST(format_test, join) { - using fmt::join; - int v1[3] = {1, 2, 3}; - auto v2 = std::vector(); - v2.push_back(1.2f); - v2.push_back(3.4f); - void* v3[2] = {&v1[0], &v1[1]}; - - EXPECT_EQ(fmt::format("({})", join(v1, v1 + 3, ", ")), "(1, 2, 3)"); - EXPECT_EQ(fmt::format("({})", join(v1, v1 + 1, ", ")), "(1)"); - EXPECT_EQ(fmt::format("({})", join(v1, v1, ", ")), "()"); - EXPECT_EQ(fmt::format("({:03})", join(v1, v1 + 3, ", ")), "(001, 002, 003)"); - EXPECT_EQ("(+01.20, +03.40)", - fmt::format("({:+06.2f})", join(v2.begin(), v2.end(), ", "))); - - EXPECT_EQ(fmt::format("{0:{1}}", join(v1, v1 + 3, ", "), 1), "1, 2, 3"); - - EXPECT_EQ(fmt::format("{}, {}", v3[0], v3[1]), - fmt::format("{}", join(v3, v3 + 2, ", "))); - - EXPECT_EQ(fmt::format("({})", join(v1, ", ")), "(1, 2, 3)"); - EXPECT_EQ(fmt::format("({:+06.2f})", join(v2, ", ")), "(+01.20, +03.40)"); - - auto v4 = std::vector{foo, bar, foo}; - EXPECT_EQ(fmt::format("{}", join(v4, " ")), "0 1 0"); -} - -#ifdef __cpp_lib_byte -TEST(format_test, join_bytes) { - auto v = std::vector{std::byte(1), std::byte(2), std::byte(3)}; - EXPECT_EQ(fmt::format("{}", fmt::join(v, ", ")), "1, 2, 3"); -} -#endif - std::string vformat_message(int id, const char* format, fmt::format_args args) { auto buffer = fmt::memory_buffer(); fmt::format_to(fmt::appender(buffer), "[{}] ", id); @@ -1903,7 +2027,6 @@ TEST(format_test, custom_format_compile_time_string) { EXPECT_EQ(fmt::format(FMT_STRING("{}"), const_answer), "42"); } -#if FMT_USE_USER_DEFINED_LITERALS TEST(format_test, named_arg_udl) { using namespace fmt::literals; auto udl_a = fmt::format("{first}{second}{first}{third}", "first"_a = "abra", @@ -1915,13 +2038,12 @@ TEST(format_test, named_arg_udl) { EXPECT_EQ(fmt::format("{answer}", "answer"_a = Answer()), "42"); } -#endif // FMT_USE_USER_DEFINED_LITERALS TEST(format_test, enum) { EXPECT_EQ(fmt::format("{}", foo), "0"); } TEST(format_test, formatter_not_specialized) { - static_assert(!fmt::has_formatter, - fmt::format_context>::value, + static_assert(!fmt::is_formattable, + fmt::format_context>::value, ""); } @@ -1930,6 +2052,8 @@ enum big_enum : unsigned long long { big_enum_value = 5000000000ULL }; auto format_as(big_enum e) -> unsigned long long { return e; } TEST(format_test, strong_enum) { + auto arg = fmt::basic_format_arg(big_enum_value); + EXPECT_EQ(arg.type(), fmt::detail::type::ulong_long_type); EXPECT_EQ(fmt::format("{}", big_enum_value), "5000000000"); } #endif @@ -1950,7 +2074,7 @@ template void write(OutputIt, foo) = delete; FMT_BEGIN_NAMESPACE template <> struct formatter : formatter { - auto format(adl_test::fmt::detail::foo, format_context& ctx) + auto format(adl_test::fmt::detail::foo, format_context& ctx) const -> decltype(ctx.out()) { return formatter::format("foo", ctx); } @@ -1979,6 +2103,17 @@ TEST(format_test, output_iterators) { std::stringstream s; fmt::format_to(std::ostream_iterator(s), "{}", 42); EXPECT_EQ("42", s.str()); + + std::stringstream s2; + fmt::format_to(std::ostreambuf_iterator(s2), "{}.{:06d}", 42, 43); + EXPECT_EQ("42.000043", s2.str()); +} + +TEST(format_test, fill_via_appender) { + fmt::memory_buffer buf; + auto it = fmt::appender(buf); + std::fill_n(it, 3, '~'); + EXPECT_EQ(fmt::to_string(buf), "~~~"); } TEST(format_test, formatted_size) { @@ -2094,7 +2229,7 @@ TEST(format_test, vformat_to) { fmt::vformat_to(std::back_inserter(s), "{}", args); EXPECT_EQ(s, "42"); s.clear(); - fmt::vformat_to(std::back_inserter(s), FMT_STRING("{}"), args); + fmt::vformat_to(std::back_inserter(s), "{}", args); EXPECT_EQ(s, "42"); } @@ -2119,7 +2254,7 @@ template <> struct formatter { } template - auto format(check_back_appender, Context& ctx) -> decltype(ctx.out()) { + auto format(check_back_appender, Context& ctx) const -> decltype(ctx.out()) { auto out = ctx.out(); static_assert(std::is_same::value, "needs to satisfy weakly_incrementable"); @@ -2181,16 +2316,21 @@ template void check_enabled_formatters() { } TEST(format_test, test_formatters_enabled) { + using custom_string = + std::basic_string, mock_allocator>; + using custom_wstring = std::basic_string, + mock_allocator>; + check_enabled_formatters(); - check_enabled_formatters(); + std::string, custom_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, custom_wstring, std::nullptr_t>(); } TEST(format_int_test, data) { @@ -2206,7 +2346,7 @@ TEST(format_int_test, format_int) { EXPECT_EQ(fmt::format_int(42ul).str(), "42"); EXPECT_EQ(fmt::format_int(-42l).str(), "-42"); EXPECT_EQ(fmt::format_int(42ull).str(), "42"); - EXPECT_EQ(fmt::format_int(-42ll).str(), "-42");\ + EXPECT_EQ(fmt::format_int(-42ll).str(), "-42"); EXPECT_EQ(fmt::format_int(max_value()).str(), std::to_string(max_value())); } @@ -2233,11 +2373,11 @@ class format_facet : public fmt::format_facet { }; auto do_put(fmt::appender out, fmt::loc_value val, - const fmt::format_specs<>&) const -> bool override; + const fmt::format_specs&) const -> bool override; }; auto format_facet::do_put(fmt::appender out, fmt::loc_value val, - const fmt::format_specs<>&) const -> bool { + const fmt::format_specs&) const -> bool { return val.visit(int_formatter{out}); } @@ -2293,3 +2433,154 @@ FMT_END_NAMESPACE TEST(format_test, formatter_nonconst_char) { EXPECT_EQ(fmt::format("{}", convertible_to_nonconst_cstring()), "bar"); } + +namespace adl_test { +template void make_format_args(const T&...) = delete; + +struct string : std::string {}; +auto format_as(const string& s) -> std::string { return s; } +} // namespace adl_test + +// Test that formatting functions compile when make_format_args is found by ADL. +TEST(format_test, adl) { + // Only check compilation and don't run the code to avoid polluting the output + // and since the output is tested elsewhere. + if (fmt::detail::const_check(true)) return; + auto s = adl_test::string(); + char buf[10]; + (void)fmt::format("{}", s); + fmt::format_to(buf, "{}", s); + fmt::format_to_n(buf, 10, "{}", s); + (void)fmt::formatted_size("{}", s); + fmt::print("{}", s); + fmt::print(stdout, "{}", s); +} + +struct convertible_to_int { + operator int() const { return 42; } +}; + +struct convertible_to_cstring { + operator const char*() const { return "foo"; } +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter { + FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + auto format(convertible_to_int, format_context& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + *out++ = 'x'; + return out; + } +}; + +template <> struct formatter { + FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + auto format(convertible_to_cstring, format_context& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + *out++ = 'y'; + return out; + } +}; +FMT_END_NAMESPACE + +TEST(format_test, formatter_overrides_implicit_conversion) { + EXPECT_EQ(fmt::format("{}", convertible_to_int()), "x"); + EXPECT_EQ(fmt::format("{}", convertible_to_cstring()), "y"); +} + +struct ustring { + using value_type = unsigned; + + auto find_first_of(value_type, size_t) const -> size_t; + + auto data() const -> const char*; + auto size() const -> size_t; +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter : formatter { + auto format(const ustring&, format_context& ctx) const + -> decltype(ctx.out()) { + return formatter::format("ustring", ctx); + } +}; +FMT_END_NAMESPACE + +TEST(format_test, ustring) { + EXPECT_EQ(fmt::format("{}", ustring()), "ustring"); +} + +TEST(format_test, writer) { + auto write_to_stdout = []() { + auto w = fmt::writer(stdout); + w.print("{}", 42); + }; + EXPECT_WRITE(stdout, write_to_stdout(), "42"); + +#if FMT_USE_FCNTL + auto pipe = fmt::pipe(); + auto write_end = pipe.write_end.fdopen("w"); + fmt::writer(write_end.get()).print("42"); + write_end.close(); + auto read_end = pipe.read_end.fdopen("r"); + int n = 0; + int result = fscanf(read_end.get(), "%d", &n); + (void)result; + EXPECT_EQ(n, 42); +#endif + + auto s = fmt::string_buffer(); + fmt::writer(s).print("foo"); + EXPECT_EQ(s.str(), "foo"); +} + +#if FMT_USE_BITINT +FMT_PRAGMA_CLANG(diagnostic ignored "-Wbit-int-extension") + +TEST(format_test, bitint) { + using fmt::detail::bitint; + using fmt::detail::ubitint; + + EXPECT_EQ(fmt::format("{}", ubitint<3>(7)), "7"); + EXPECT_EQ(fmt::format("{}", bitint<7>()), "0"); + + EXPECT_EQ(fmt::format("{}", ubitint<15>(31000)), "31000"); + EXPECT_EQ(fmt::format("{}", bitint<16>(INT16_MIN)), "-32768"); + EXPECT_EQ(fmt::format("{}", bitint<16>(INT16_MAX)), "32767"); + + EXPECT_EQ(fmt::format("{}", ubitint<32>(4294967295)), "4294967295"); + + EXPECT_EQ(fmt::format("{}", ubitint<47>(140737488355327ULL)), + "140737488355327"); + EXPECT_EQ(fmt::format("{}", bitint<47>(-40737488355327LL)), + "-40737488355327"); + + // Check lvalues and const + auto a = bitint<8>(0); + auto b = ubitint<32>(4294967295); + const auto c = bitint<7>(0); + const auto d = ubitint<32>(4294967295); + EXPECT_EQ(fmt::format("{}", a), "0"); + EXPECT_EQ(fmt::format("{}", b), "4294967295"); + EXPECT_EQ(fmt::format("{}", c), "0"); + EXPECT_EQ(fmt::format("{}", d), "4294967295"); + + static_assert(fmt::is_formattable, char>{}, ""); + static_assert(fmt::is_formattable, char>{}, ""); +} +#endif + +#ifdef __cpp_lib_byte +TEST(base_test, format_byte) { + auto s = std::string(); + fmt::format_to(std::back_inserter(s), "{}", std::byte(42)); + EXPECT_EQ(s, "42"); +} +#endif diff --git a/third-party/fmt/test/fuzzing/.gitignore b/third-party/fmt/test/fuzzing/.gitignore deleted file mode 100644 index ea41040261..0000000000 --- a/third-party/fmt/test/fuzzing/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# ignore artifacts from the build.sh script -build-*/ - diff --git a/third-party/fmt/test/fuzzing/build.sh b/third-party/fmt/test/fuzzing/build.sh old mode 100644 new mode 100755 diff --git a/third-party/fmt/test/fuzzing/fuzzer-common.h b/third-party/fmt/test/fuzzing/fuzzer-common.h index c0a2467228..eaae5a6e46 100644 --- a/third-party/fmt/test/fuzzing/fuzzer-common.h +++ b/third-party/fmt/test/fuzzing/fuzzer-common.h @@ -4,7 +4,7 @@ #ifndef FUZZER_COMMON_H #define FUZZER_COMMON_H -#include +#include #include // std::uint8_t #include // memcpy diff --git a/third-party/fmt/test/gtest-extra-test.cc b/third-party/fmt/test/gtest-extra-test.cc index 34054b6870..5c86040015 100644 --- a/third-party/fmt/test/gtest-extra-test.cc +++ b/third-party/fmt/test/gtest-extra-test.cc @@ -316,10 +316,9 @@ using fmt::buffered_file; using fmt::file; TEST(output_redirect_test, scoped_redirect) { - file read_end, write_end; - file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); { - buffered_file file(write_end.fdopen("w")); + buffered_file file(pipe.write_end.fdopen("w")); std::fprintf(file.get(), "[[["); { output_redirect redir(file.get()); @@ -327,16 +326,15 @@ TEST(output_redirect_test, scoped_redirect) { } std::fprintf(file.get(), "]]]"); } - EXPECT_READ(read_end, "[[[]]]"); + EXPECT_READ(pipe.read_end, "[[[]]]"); } // Test that output_redirect handles errors in flush correctly. TEST(output_redirect_test, flush_error_in_ctor) { - file read_end, write_end; - file::pipe(read_end, write_end); - int write_fd = write_end.descriptor(); - file write_copy = write_end.dup(write_fd); - buffered_file f = write_end.fdopen("w"); + auto pipe = fmt::pipe(); + int write_fd = pipe.write_end.descriptor(); + file write_copy = pipe.write_end.dup(write_fd); + buffered_file f = pipe.write_end.fdopen("w"); // Put a character in a file buffer. EXPECT_EQ('x', fputc('x', f.get())); FMT_POSIX(close(write_fd)); @@ -360,9 +358,8 @@ TEST(output_redirect_test, dup_error_in_ctor) { } TEST(output_redirect_test, restore_and_read) { - file read_end, write_end; - file::pipe(read_end, write_end); - buffered_file file(write_end.fdopen("w")); + auto pipe = fmt::pipe(); + buffered_file file(pipe.write_end.fdopen("w")); std::fprintf(file.get(), "[[["); output_redirect redir(file.get()); std::fprintf(file.get(), "censored"); @@ -370,16 +367,15 @@ TEST(output_redirect_test, restore_and_read) { EXPECT_EQ("", redir.restore_and_read()); std::fprintf(file.get(), "]]]"); file = buffered_file(); - EXPECT_READ(read_end, "[[[]]]"); + EXPECT_READ(pipe.read_end, "[[[]]]"); } // Test that OutputRedirect handles errors in flush correctly. TEST(output_redirect_test, flush_error_in_restore_and_read) { - file read_end, write_end; - file::pipe(read_end, write_end); - int write_fd = write_end.descriptor(); - file write_copy = write_end.dup(write_fd); - buffered_file f = write_end.fdopen("w"); + auto pipe = fmt::pipe(); + int write_fd = pipe.write_end.descriptor(); + file write_copy = pipe.write_end.dup(write_fd); + buffered_file f = pipe.write_end.fdopen("w"); output_redirect redir(f.get()); // Put a character in a file buffer. EXPECT_EQ('x', fputc('x', f.get())); @@ -390,11 +386,10 @@ TEST(output_redirect_test, flush_error_in_restore_and_read) { } TEST(output_redirect_test, error_in_dtor) { - file read_end, write_end; - file::pipe(read_end, write_end); - int write_fd = write_end.descriptor(); - file write_copy = write_end.dup(write_fd); - buffered_file f = write_end.fdopen("w"); + auto pipe = fmt::pipe(); + int write_fd = pipe.write_end.descriptor(); + file write_copy = pipe.write_end.dup(write_fd); + buffered_file f = pipe.write_end.fdopen("w"); std::unique_ptr redir(new output_redirect(f.get())); // Put a character in a file buffer. EXPECT_EQ('x', fputc('x', f.get())); diff --git a/third-party/fmt/test/gtest-extra.cc b/third-party/fmt/test/gtest-extra.cc index 3d27cf96b3..0f9fff5ee2 100644 --- a/third-party/fmt/test/gtest-extra.cc +++ b/third-party/fmt/test/gtest-extra.cc @@ -17,10 +17,10 @@ output_redirect::output_redirect(FILE* f, bool flush) : file_(f) { // Create a file object referring to the original file. original_ = file::dup(fd); // Create a pipe. - file write_end; - file::pipe(read_end_, write_end); + auto pipe = fmt::pipe(); + read_end_ = std::move(pipe.read_end); // Connect the passed FILE object to the write end of the pipe. - write_end.dup2(fd); + pipe.write_end.dup2(fd); } output_redirect::~output_redirect() noexcept { diff --git a/third-party/fmt/test/gtest/gmock-gtest-all.cc b/third-party/fmt/test/gtest/gmock-gtest-all.cc index 9d3b9bc1c9..6642abef83 100644 --- a/third-party/fmt/test/gtest/gmock-gtest-all.cc +++ b/third-party/fmt/test/gtest/gmock-gtest-all.cc @@ -13360,6 +13360,7 @@ bool UnorderedElementsAreMatcherImplBase::FindPairing( #include #include #include +#include #include @@ -13983,46 +13984,50 @@ MockObjectRegistry g_mock_object_registry; // Maps a mock object to the reaction Google Mock should have when an // uninteresting method is called. Protected by g_gmock_mutex. -std::map g_uninteresting_call_reaction; +std::unordered_map& +UninterestingCallReactionMap() { + static auto* map = new std::unordered_map; + return *map; +} // Sets the reaction Google Mock should have when an uninteresting // method of the given mock object is called. -void SetReactionOnUninterestingCalls(const void* mock_obj, +void SetReactionOnUninterestingCalls(uintptr_t mock_obj, internal::CallReaction reaction) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); - g_uninteresting_call_reaction[mock_obj] = reaction; + UninterestingCallReactionMap()[mock_obj] = reaction; } } // namespace // Tells Google Mock to allow uninteresting calls on the given mock // object. -void Mock::AllowUninterestingCalls(const void* mock_obj) +void Mock::AllowUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); } // Tells Google Mock to warn the user about uninteresting calls on the // given mock object. -void Mock::WarnUninterestingCalls(const void* mock_obj) +void Mock::WarnUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); } // Tells Google Mock to fail uninteresting calls on the given mock // object. -void Mock::FailUninterestingCalls(const void* mock_obj) +void Mock::FailUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kFail); } // Tells Google Mock the given mock object is being destroyed and its // entry in the call-reaction table should be removed. -void Mock::UnregisterCallReaction(const void* mock_obj) +void Mock::UnregisterCallReaction(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); - g_uninteresting_call_reaction.erase(mock_obj); + UninterestingCallReactionMap().erase(static_cast(mock_obj)); } // Returns the reaction Google Mock will have on uninteresting calls @@ -14031,9 +14036,12 @@ internal::CallReaction Mock::GetReactionOnUninterestingCalls( 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::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) : - g_uninteresting_call_reaction[mock_obj]; + return (UninterestingCallReactionMap().count( + reinterpret_cast(mock_obj)) == 0) + ? internal::intToCallReaction( + GMOCK_FLAG(default_mock_behavior)) + : UninterestingCallReactionMap()[reinterpret_cast( + mock_obj)]; } // Tells Google Mock to ignore mock_obj when checking for leaked mock diff --git a/third-party/fmt/test/gtest/gmock/gmock.h b/third-party/fmt/test/gtest/gmock/gmock.h index d121f7df2b..c6eef53189 100644 --- a/third-party/fmt/test/gtest/gmock/gmock.h +++ b/third-party/fmt/test/gtest/gmock/gmock.h @@ -2860,6 +2860,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ +#include #include #include #include @@ -8646,22 +8647,22 @@ class GTEST_API_ Mock { // Tells Google Mock to allow uninteresting calls on the given mock // object. - static void AllowUninterestingCalls(const void* mock_obj) + static void AllowUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to warn the user about uninteresting calls on // the given mock object. - static void WarnUninterestingCalls(const void* mock_obj) + static void WarnUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to fail uninteresting calls on the given mock // object. - static void FailUninterestingCalls(const void* mock_obj) + static void FailUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock the given mock object is being destroyed and // its entry in the call-reaction table should be removed. - static void UnregisterCallReaction(const void* mock_obj) + static void UnregisterCallReaction(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Returns the reaction Google Mock will have on uninteresting calls @@ -11417,6 +11418,7 @@ MATCHER(IsFalse, negation ? "is true" : "is false") { #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ +#include #include @@ -11461,25 +11463,37 @@ constexpr bool HasStrictnessModifier() { template class NiceMockImpl { public: - NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); } + NiceMockImpl() { + ::testing::Mock::AllowUninterestingCalls(reinterpret_cast(this)); + } - ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } + ~NiceMockImpl() { + ::testing::Mock::UnregisterCallReaction(reinterpret_cast(this)); + } }; template class NaggyMockImpl { public: - NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); } + NaggyMockImpl() { + ::testing::Mock::WarnUninterestingCalls(reinterpret_cast(this)); + } - ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } + ~NaggyMockImpl() { + ::testing::Mock::UnregisterCallReaction(reinterpret_cast(this)); + } }; template class StrictMockImpl { public: - StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); } + StrictMockImpl() { + ::testing::Mock::FailUninterestingCalls(reinterpret_cast(this)); + } - ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } + ~StrictMockImpl() { + ::testing::Mock::UnregisterCallReaction(reinterpret_cast(this)); + } }; } // namespace internal diff --git a/third-party/fmt/test/gtest/gtest/gtest.h b/third-party/fmt/test/gtest/gtest/gtest.h index 55a31d0a87..cb994607ac 100644 --- a/third-party/fmt/test/gtest/gtest/gtest.h +++ b/third-party/fmt/test/gtest/gtest/gtest.h @@ -6390,17 +6390,18 @@ class MatcherBase : private MatcherDescriberInterface { } protected: - MatcherBase() : vtable_(nullptr) {} + MatcherBase() : vtable_(nullptr), buffer_() {} // Constructs a matcher from its implementation. template - explicit MatcherBase(const MatcherInterface* impl) { + explicit MatcherBase(const MatcherInterface* impl) + : vtable_(nullptr), buffer_() { Init(impl); } template ::type::is_gtest_matcher> - MatcherBase(M&& m) { // NOLINT + MatcherBase(M&& m) : vtable_(nullptr), buffer_() { // NOLINT Init(std::forward(m)); } diff --git a/third-party/fmt/test/header-only-test.cc b/third-party/fmt/test/header-only-test.cc index 570f09a563..8c99f857bb 100644 --- a/third-party/fmt/test/header-only-test.cc +++ b/third-party/fmt/test/header-only-test.cc @@ -1,6 +1,6 @@ // Header-only configuration test -#include "fmt/core.h" +#include "fmt/base.h" #include "fmt/ostream.h" #include "gtest/gtest.h" diff --git a/third-party/fmt/test/mock-allocator.h b/third-party/fmt/test/mock-allocator.h index dc4942f175..32c4caae6a 100644 --- a/third-party/fmt/test/mock-allocator.h +++ b/third-party/fmt/test/mock-allocator.h @@ -17,9 +17,22 @@ template class mock_allocator { public: + using value_type = T; + using size_type = size_t; + + using pointer = T*; + using const_pointer = const T*; + using reference = T&; + using const_reference = const T&; + using difference_type = ptrdiff_t; + + template struct rebind { + using other = mock_allocator; + }; + mock_allocator() {} mock_allocator(const mock_allocator&) {} - using value_type = T; + MOCK_METHOD(T*, allocate, (size_t)); MOCK_METHOD(void, deallocate, (T*, size_t)); }; diff --git a/third-party/fmt/test/no-builtin-types-test.cc b/third-party/fmt/test/no-builtin-types-test.cc new file mode 100644 index 0000000000..fd15d0020f --- /dev/null +++ b/third-party/fmt/test/no-builtin-types-test.cc @@ -0,0 +1,24 @@ +// 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 "gtest/gtest.h" + +#if !defined(__GNUC__) || __GNUC__ >= 5 +#define FMT_BUILTIN_TYPES 0 +#include "fmt/format.h" + +TEST(no_builtin_types_test, format) { + EXPECT_EQ(fmt::format("{}", 42), "42"); +} + +TEST(no_builtin_types_test, double_is_custom_type) { + double d = 42; + auto args = fmt::make_format_args(d); + EXPECT_EQ(fmt::format_args(args).get(0).type(), + fmt::detail::type::custom_type); +} +#endif diff --git a/third-party/fmt/test/noexception-test.cc b/third-party/fmt/test/noexception-test.cc index bf3472fd10..0e44e13bb2 100644 --- a/third-party/fmt/test/noexception-test.cc +++ b/third-party/fmt/test/noexception-test.cc @@ -6,10 +6,10 @@ // For the license information refer to format.h. #include "fmt/args.h" +#include "fmt/base.h" #include "fmt/chrono.h" #include "fmt/color.h" #include "fmt/compile.h" -#include "fmt/core.h" #include "fmt/format.h" #include "fmt/os.h" #include "fmt/ostream.h" diff --git a/third-party/fmt/test/os-test.cc b/third-party/fmt/test/os-test.cc index 1e6c7c4b39..8f73935ca8 100644 --- a/third-party/fmt/test/os-test.cc +++ b/third-party/fmt/test/os-test.cc @@ -18,6 +18,10 @@ using fmt::buffered_file; using testing::HasSubstr; using wstring_view = fmt::basic_string_view; +static std::string uniq_file_name(unsigned line_number) { + return "test-file" + std::to_string(line_number); +} + #ifdef _WIN32 # include @@ -104,7 +108,7 @@ TEST(file_test, open_windows_file) { using fmt::file; -bool isclosed(int fd) { +auto isclosed(int fd) -> bool { char buffer; auto result = std::streamsize(); SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1))); @@ -112,12 +116,11 @@ bool isclosed(int fd) { } // Opens a file for reading. -file open_file() { - file read_end, write_end; - file::pipe(read_end, write_end); - write_end.write(file_content, std::strlen(file_content)); - write_end.close(); - return read_end; +auto open_file() -> file { + auto pipe = fmt::pipe(); + pipe.write_end.write(file_content, std::strlen(file_content)); + pipe.write_end.close(); + return std::move(pipe.read_end); } // Attempts to write a string to a file. @@ -233,69 +236,75 @@ TEST(buffered_file_test, descriptor) { } TEST(ostream_test, move) { - fmt::ostream out = fmt::output_file("test-file"); + auto test_file = uniq_file_name(__LINE__); + fmt::ostream out = fmt::output_file(test_file); fmt::ostream moved(std::move(out)); moved.print("hello"); } TEST(ostream_test, move_while_holding_data) { + auto test_file = uniq_file_name(__LINE__); { - fmt::ostream out = fmt::output_file("test-file"); + fmt::ostream out = fmt::output_file(test_file); out.print("Hello, "); fmt::ostream moved(std::move(out)); moved.print("world!\n"); } { - file in("test-file", file::RDONLY); + file in(test_file, file::RDONLY); EXPECT_READ(in, "Hello, world!\n"); } } TEST(ostream_test, print) { - fmt::ostream out = fmt::output_file("test-file"); - out.print("The answer is {}.\n", - fmt::join(std::initializer_list{42}, ", ")); + auto test_file = uniq_file_name(__LINE__); + fmt::ostream out = fmt::output_file(test_file); + out.print("The answer is {}.\n", 42); out.close(); - file in("test-file", file::RDONLY); + file in(test_file, file::RDONLY); EXPECT_READ(in, "The answer is 42.\n"); } TEST(ostream_test, buffer_boundary) { auto str = std::string(4096, 'x'); - fmt::ostream out = fmt::output_file("test-file"); + auto test_file = uniq_file_name(__LINE__); + fmt::ostream out = fmt::output_file(test_file); out.print("{}", str); out.print("{}", str); out.close(); - file in("test-file", file::RDONLY); + file in(test_file, file::RDONLY); EXPECT_READ(in, str + str); } TEST(ostream_test, buffer_size) { - fmt::ostream out = fmt::output_file("test-file", fmt::buffer_size = 1); + auto test_file = uniq_file_name(__LINE__); + fmt::ostream out = fmt::output_file(test_file, fmt::buffer_size = 1); out.print("{}", "foo"); out.close(); - file in("test-file", file::RDONLY); + file in(test_file, file::RDONLY); EXPECT_READ(in, "foo"); } TEST(ostream_test, truncate) { + auto test_file = uniq_file_name(__LINE__); { - fmt::ostream out = fmt::output_file("test-file"); + fmt::ostream out = fmt::output_file(test_file); out.print("0123456789"); } { - fmt::ostream out = fmt::output_file("test-file"); + fmt::ostream out = fmt::output_file(test_file); out.print("foo"); } - file in("test-file", file::RDONLY); + file in(test_file, file::RDONLY); EXPECT_EQ("foo", read(in, 4)); } TEST(ostream_test, flush) { - auto out = fmt::output_file("test-file"); + auto test_file = uniq_file_name(__LINE__); + auto out = fmt::output_file(test_file); out.print("x"); out.flush(); - auto in = fmt::file("test-file", file::RDONLY); + auto in = fmt::file(test_file, file::RDONLY); EXPECT_READ(in, "x"); } @@ -305,10 +314,11 @@ TEST(file_test, default_ctor) { } TEST(file_test, open_buffered_file_in_ctor) { - FILE* fp = safe_fopen("test-file", "w"); + auto test_file = uniq_file_name(__LINE__); + FILE* fp = safe_fopen(test_file.c_str(), "w"); std::fputs(file_content, fp); std::fclose(fp); - file f("test-file", file::RDONLY); + file f(test_file.c_str(), file::RDONLY); // Check if the file is open by reading one character from it. char buffer; bool isopen = FMT_POSIX(read(f.descriptor(), &buffer, 1)) == 1; @@ -419,7 +429,8 @@ TEST(file_test, read) { } TEST(file_test, read_error) { - file f("test-file", file::WRONLY); + auto test_file = uniq_file_name(__LINE__); + file f(test_file, file::WRONLY | file::CREATE); char buf; // We intentionally read from a file opened in the write-only mode to // cause error. @@ -427,15 +438,16 @@ TEST(file_test, read_error) { } TEST(file_test, write) { - file read_end, write_end; - file::pipe(read_end, write_end); - write(write_end, "test"); - write_end.close(); - EXPECT_READ(read_end, "test"); + auto pipe = fmt::pipe(); + auto test_file = uniq_file_name(__LINE__); + write(pipe.write_end, test_file); + pipe.write_end.close(); + EXPECT_READ(pipe.read_end, test_file); } TEST(file_test, write_error) { - file f("test-file", file::RDONLY); + auto test_file = uniq_file_name(__LINE__); + file f(test_file, file::RDONLY | file::CREATE); // We intentionally write to a file opened in the read-only mode to // cause error. EXPECT_SYSTEM_ERROR(f.write(" ", 1), EBADF, "cannot write to file"); @@ -489,18 +501,16 @@ TEST(file_test, dup2_noexcept_error) { } TEST(file_test, pipe) { - file read_end, write_end; - file::pipe(read_end, write_end); - EXPECT_NE(-1, read_end.descriptor()); - EXPECT_NE(-1, write_end.descriptor()); - write(write_end, "test"); - EXPECT_READ(read_end, "test"); + auto pipe = fmt::pipe(); + EXPECT_NE(-1, pipe.read_end.descriptor()); + EXPECT_NE(-1, pipe.write_end.descriptor()); + write(pipe.write_end, "test"); + EXPECT_READ(pipe.read_end, "test"); } TEST(file_test, fdopen) { - file read_end, write_end; - file::pipe(read_end, write_end); - int read_fd = read_end.descriptor(); - EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get()))); + auto pipe = fmt::pipe(); + int read_fd = pipe.read_end.descriptor(); + EXPECT_EQ(read_fd, FMT_POSIX(fileno(pipe.read_end.fdopen("r").get()))); } #endif // FMT_USE_FCNTL diff --git a/third-party/fmt/test/ostream-test.cc b/third-party/fmt/test/ostream-test.cc index 98ee0757b2..cc28885a43 100644 --- a/third-party/fmt/test/ostream-test.cc +++ b/third-party/fmt/test/ostream-test.cc @@ -135,8 +135,8 @@ TEST(ostream_test, write_to_ostream_max_size) { struct test_buffer final : fmt::detail::buffer { explicit test_buffer(size_t size) - : fmt::detail::buffer(nullptr, size, size) {} - void grow(size_t) override {} + : fmt::detail::buffer([](buffer&, size_t) {}, nullptr, size, + size) {} } buffer(max_size); struct mock_streambuf : std::streambuf { @@ -201,7 +201,8 @@ auto operator<<(std::ostream& os, test_template) -> std::ostream& { namespace fmt { template struct formatter> : formatter { - auto format(test_template, format_context& ctx) -> decltype(ctx.out()) { + auto format(test_template, format_context& ctx) const + -> decltype(ctx.out()) { return formatter::format(2, ctx); } }; @@ -292,8 +293,7 @@ TEST(ostream_test, closed_ofstream) { struct unlocalized {}; -auto operator<<(std::ostream& os, unlocalized) - -> std::ostream& { +auto operator<<(std::ostream& os, unlocalized) -> std::ostream& { return os << 12345; } diff --git a/third-party/fmt/test/perf-sanity.cc b/third-party/fmt/test/perf-sanity.cc new file mode 100644 index 0000000000..aa0c0caefe --- /dev/null +++ b/third-party/fmt/test/perf-sanity.cc @@ -0,0 +1,25 @@ +// A quick and dirty performance test. +// For actual benchmarks see https://github.com/fmtlib/format-benchmark. + +#include +#include +#include + +#include "fmt/format.h" + +int main() { + const int n = 10000000; + + auto start = std::chrono::steady_clock::now(); + for (int iteration = 0; iteration < n; ++iteration) { + auto buf = fmt::memory_buffer(); + fmt::format_to(std::back_inserter(buf), + "Hello, {}. The answer is {} and {}.", 1, 2345, 6789); + } + std::atomic_signal_fence(std::memory_order_acq_rel); // Clobber memory. + auto end = std::chrono::steady_clock::now(); + + // Print time in milliseconds. + std::chrono::duration duration = end - start; + fmt::print("{:.1f}\n", duration.count() * 1000); +} diff --git a/third-party/fmt/test/posix-mock-test.cc b/third-party/fmt/test/posix-mock-test.cc index 32078bf8a5..bcd330d4ad 100644 --- a/third-party/fmt/test/posix-mock-test.cc +++ b/third-party/fmt/test/posix-mock-test.cc @@ -225,9 +225,8 @@ TEST(file_test, open_retry) { } TEST(file_test, close_no_retry_in_dtor) { - file read_end, write_end; - file::pipe(read_end, write_end); - std::unique_ptr f(new file(std::move(read_end))); + auto pipe = fmt::pipe(); + std::unique_ptr f(new file(std::move(pipe.read_end))); int saved_close_count = 0; EXPECT_WRITE( stderr, @@ -242,10 +241,9 @@ TEST(file_test, close_no_retry_in_dtor) { } TEST(file_test, close_no_retry) { - file read_end, write_end; - file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); close_count = 1; - EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file"); + EXPECT_SYSTEM_ERROR(pipe.read_end.close(), EINTR, "cannot close file"); EXPECT_EQ(2, close_count); close_count = 0; } @@ -283,30 +281,28 @@ TEST(file_test, max_size) { } TEST(file_test, read_retry) { - file read_end, write_end; - file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); enum { SIZE = 4 }; - write_end.write("test", SIZE); - write_end.close(); + pipe.write_end.write("test", SIZE); + pipe.write_end.close(); char buffer[SIZE]; size_t count = 0; - EXPECT_RETRY(count = read_end.read(buffer, SIZE), read, + EXPECT_RETRY(count = pipe.read_end.read(buffer, SIZE), read, "cannot read from file"); EXPECT_EQ_POSIX(static_cast(SIZE), count); } TEST(file_test, write_retry) { - file read_end, write_end; - file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); enum { SIZE = 4 }; size_t count = 0; - EXPECT_RETRY(count = write_end.write("test", SIZE), write, + EXPECT_RETRY(count = pipe.write_end.write("test", SIZE), write, "cannot write to file"); - write_end.close(); + pipe.write_end.close(); # ifndef _WIN32 EXPECT_EQ(static_cast(SIZE), count); char buffer[SIZE + 1]; - read_end.read(buffer, SIZE); + pipe.read_end.read(buffer, SIZE); buffer[SIZE] = '\0'; EXPECT_STREQ("test", buffer); # endif @@ -314,27 +310,25 @@ TEST(file_test, write_retry) { # ifdef _WIN32 TEST(file_test, convert_read_count) { - file read_end, write_end; - file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); char c; size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(size_t)) ++size; read_count = 1; read_nbyte = 0; - EXPECT_THROW(read_end.read(&c, size), std::system_error); + EXPECT_THROW(pipe.read_end.read(&c, size), std::system_error); read_count = 0; EXPECT_EQ(UINT_MAX, read_nbyte); } TEST(file_test, convert_write_count) { - file read_end, write_end; - file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); char c; size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(size_t)) ++size; write_count = 1; write_nbyte = 0; - EXPECT_THROW(write_end.write(&c, size), std::system_error); + EXPECT_THROW(pipe.write_end.write(&c, size), std::system_error); write_count = 0; EXPECT_EQ(UINT_MAX, write_nbyte); } @@ -372,18 +366,15 @@ TEST(file_test, dup2_no_except_retry) { } TEST(file_test, pipe_no_retry) { - file read_end, write_end; pipe_count = 1; - EXPECT_SYSTEM_ERROR(file::pipe(read_end, write_end), EINTR, - "cannot create pipe"); + EXPECT_SYSTEM_ERROR(fmt::pipe(), EINTR, "cannot create pipe"); pipe_count = 0; } TEST(file_test, fdopen_no_retry) { - file read_end, write_end; - file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); fdopen_count = 1; - EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR, + EXPECT_SYSTEM_ERROR(pipe.read_end.fdopen("r"), EINTR, "cannot associate stream with file descriptor"); fdopen_count = 0; } @@ -401,9 +392,9 @@ TEST(buffered_file_test, open_retry) { } TEST(buffered_file_test, close_no_retry_in_dtor) { - file read_end, write_end; - file::pipe(read_end, write_end); - std::unique_ptr f(new buffered_file(read_end.fdopen("r"))); + auto pipe = fmt::pipe(); + std::unique_ptr f( + new buffered_file(pipe.read_end.fdopen("r"))); int saved_fclose_count = 0; EXPECT_WRITE( stderr, @@ -418,9 +409,8 @@ TEST(buffered_file_test, close_no_retry_in_dtor) { } TEST(buffered_file_test, close_no_retry) { - file read_end, write_end; - file::pipe(read_end, write_end); - buffered_file f = read_end.fdopen("r"); + auto pipe = fmt::pipe(); + buffered_file f = pipe.read_end.fdopen("r"); fclose_count = 1; EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file"); EXPECT_EQ(2, fclose_count); @@ -428,9 +418,8 @@ TEST(buffered_file_test, close_no_retry) { } TEST(buffered_file_test, fileno_no_retry) { - file read_end, write_end; - file::pipe(read_end, write_end); - buffered_file f = read_end.fdopen("r"); + auto pipe = fmt::pipe(); + buffered_file f = pipe.read_end.fdopen("r"); fileno_count = 1; EXPECT_SYSTEM_ERROR((f.descriptor)(), EINTR, "cannot get file descriptor"); EXPECT_EQ(2, fileno_count); @@ -440,7 +429,7 @@ TEST(buffered_file_test, fileno_no_retry) { struct test_mock { static test_mock* instance; -} * test_mock::instance; +}* test_mock::instance; TEST(scoped_mock, scope) { { diff --git a/third-party/fmt/test/printf-test.cc b/third-party/fmt/test/printf-test.cc index 7e09ecca7d..ee5cf0b0e0 100644 --- a/third-party/fmt/test/printf-test.cc +++ b/third-party/fmt/test/printf-test.cc @@ -6,6 +6,10 @@ // For the license information refer to format.h. #include "fmt/printf.h" +// include if possible for https://github.com/fmtlib/fmt/pull/4042 +#if FMT_HAS_INCLUDE() && FMT_CPLUSPLUS > 201703L +# include +#endif #include #include @@ -310,10 +314,14 @@ TEST(printf_test, dynamic_precision) { } } -template struct make_signed { using type = T; }; +template struct make_signed { + using type = T; +}; -#define SPECIALIZE_MAKE_SIGNED(T, S) \ - template <> struct make_signed { using type = S; } +#define SPECIALIZE_MAKE_SIGNED(T, S) \ + template <> struct make_signed { \ + using type = S; \ + } SPECIALIZE_MAKE_SIGNED(char, signed char); SPECIALIZE_MAKE_SIGNED(unsigned char, signed char); @@ -517,9 +525,8 @@ TEST(printf_test, examples) { } TEST(printf_test, printf_error) { - fmt::file read_end, write_end; - fmt::file::pipe(read_end, write_end); - int result = fmt::fprintf(read_end.fdopen("r").get(), "test"); + auto pipe = fmt::pipe(); + int result = fmt::fprintf(pipe.read_end.fdopen("r").get(), "test"); EXPECT_LT(result, 0); } #endif @@ -530,7 +537,7 @@ TEST(printf_test, wide_string) { TEST(printf_test, vprintf) { int n = 42; - auto store = fmt::format_arg_store(n); + auto store = fmt::make_format_args(n); auto args = fmt::basic_format_args(store); EXPECT_EQ(fmt::vsprintf(fmt::string_view("%d"), args), "42"); EXPECT_WRITE(stdout, fmt::vfprintf(stdout, fmt::string_view("%d"), args), @@ -551,10 +558,11 @@ TEST(printf_test, fixed_large_exponent) { } TEST(printf_test, make_printf_args) { + int n = 42; EXPECT_EQ("[42] something happened", fmt::vsprintf(fmt::string_view("[%d] %s happened"), - {fmt::make_printf_args(42, "something")})); + {fmt::make_printf_args(n, "something")})); EXPECT_EQ(L"[42] something happened", fmt::vsprintf(fmt::basic_string_view(L"[%d] %s happened"), - {fmt::make_wprintf_args(42, L"something")})); + {fmt::make_printf_args(n, L"something")})); } diff --git a/third-party/fmt/test/ranges-odr-test.cc b/third-party/fmt/test/ranges-odr-test.cc index 031354d3c2..6115dcb740 100644 --- a/third-party/fmt/test/ranges-odr-test.cc +++ b/third-party/fmt/test/ranges-odr-test.cc @@ -7,6 +7,7 @@ #include +#include "fmt/format.h" #include "fmt/ranges.h" #include "gtest/gtest.h" diff --git a/third-party/fmt/test/ranges-test.cc b/third-party/fmt/test/ranges-test.cc index 8ab66b3387..be541818f4 100644 --- a/third-party/fmt/test/ranges-test.cc +++ b/third-party/fmt/test/ranges-test.cc @@ -7,6 +7,7 @@ #include "fmt/ranges.h" +#include #include #include #include @@ -16,21 +17,17 @@ #include #include -#if FMT_HAS_INCLUDE() +#if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE() # include #endif +#include "fmt/format.h" #include "gtest/gtest.h" #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 601 # define FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY #endif -#if !FMT_MSC_VERSION || FMT_MSC_VERSION > 1910 -# define FMT_RANGES_TEST_ENABLE_JOIN -# define FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT -#endif - #ifdef FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY TEST(ranges_test, format_array) { int arr[] = {1, 2, 3, 5, 7, 11}; @@ -50,6 +47,8 @@ TEST(ranges_test, format_array_of_literals) { } #endif // FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY +struct unformattable {}; + TEST(ranges_test, format_vector) { auto v = std::vector{1, 2, 3, 5, 7, 11}; EXPECT_EQ(fmt::format("{}", v), "[1, 2, 3, 5, 7, 11]"); @@ -57,12 +56,20 @@ TEST(ranges_test, format_vector) { EXPECT_EQ(fmt::format("{:n:#x}", v), "0x1, 0x2, 0x3, 0x5, 0x7, 0xb"); auto vc = std::vector{'a', 'b', 'c'}; + auto vec = std::vector{'a', '\n', '\t'}; auto vvc = std::vector>{vc, vc}; EXPECT_EQ(fmt::format("{}", vc), "['a', 'b', 'c']"); + EXPECT_EQ(fmt::format("{:s}", vc), "\"abc\""); + EXPECT_EQ(fmt::format("{:?s}", vec), "\"a\\n\\t\""); + EXPECT_EQ(fmt::format("{:s}", vec), "\"a\n\t\""); + EXPECT_EQ(fmt::format("{::s}", vvc), "[\"abc\", \"abc\"]"); EXPECT_EQ(fmt::format("{}", vvc), "[['a', 'b', 'c'], ['a', 'b', 'c']]"); EXPECT_EQ(fmt::format("{:n}", vvc), "['a', 'b', 'c'], ['a', 'b', 'c']"); EXPECT_EQ(fmt::format("{:n:n}", vvc), "'a', 'b', 'c', 'a', 'b', 'c'"); EXPECT_EQ(fmt::format("{:n:n:}", vvc), "a, b, c, a, b, c"); + + EXPECT_FALSE(fmt::is_formattable::value); + EXPECT_FALSE(fmt::is_formattable>::value); } TEST(ranges_test, format_nested_vector) { @@ -81,6 +88,37 @@ TEST(ranges_test, format_map) { auto m = std::map{{"one", 1}, {"two", 2}}; EXPECT_EQ(fmt::format("{}", m), "{\"one\": 1, \"two\": 2}"); EXPECT_EQ(fmt::format("{:n}", m), "\"one\": 1, \"two\": 2"); + + EXPECT_FALSE((fmt::is_formattable>::value)); +} + +struct test_map_value {}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter : formatter { + auto format(test_map_value, format_context& ctx) const + -> format_context::iterator { + return formatter::format("foo", ctx); + } +}; + +template +struct formatter> : formatter { + auto format(std::pair, format_context& ctx) const + -> format_context::iterator { + return ctx.out(); + } +}; + +template +struct is_tuple_formattable, char> + : std::false_type {}; + +FMT_END_NAMESPACE + +TEST(ranges_test, format_map_custom_pair) { + EXPECT_EQ(fmt::format("{}", std::map{{42, {}}}), + "{42: \"foo\"}"); } TEST(ranges_test, format_set) { @@ -115,6 +153,7 @@ template class flat_set { TEST(ranges_test, format_flat_set) { EXPECT_EQ(fmt::format("{}", flat_set{"one", "two"}), "{\"one\", \"two\"}"); + EXPECT_FALSE(fmt::is_formattable>::value); } namespace adl { @@ -134,19 +173,19 @@ TEST(ranges_test, format_adl_begin_end) { TEST(ranges_test, format_pair) { auto p = std::pair(42, 1.5f); EXPECT_EQ(fmt::format("{}", p), "(42, 1.5)"); + EXPECT_EQ(fmt::format("{:}", p), "(42, 1.5)"); + EXPECT_EQ(fmt::format("{:n}", p), "421.5"); } -struct unformattable {}; - TEST(ranges_test, format_tuple) { auto t = std::tuple(42, 1.5f, "this is tuple", 'i'); EXPECT_EQ(fmt::format("{}", t), "(42, 1.5, \"this is tuple\", 'i')"); + EXPECT_EQ(fmt::format("{:n}", t), "421.5\"this is tuple\"'i'"); EXPECT_EQ(fmt::format("{}", std::tuple<>()), "()"); EXPECT_TRUE((fmt::is_formattable>::value)); - EXPECT_FALSE((fmt::is_formattable::value)); EXPECT_FALSE((fmt::is_formattable>::value)); EXPECT_FALSE((fmt::is_formattable>::value)); EXPECT_FALSE((fmt::is_formattable>::value)); @@ -174,7 +213,6 @@ TEST(ranges_test, tuple_parse_calls_element_parse) { EXPECT_THROW(f.parse(ctx), bad_format); } -#ifdef FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT struct tuple_like { int i; std::string str; @@ -207,7 +245,6 @@ TEST(ranges_test, format_struct) { auto t = tuple_like{42, "foo"}; EXPECT_EQ(fmt::format("{}", t), "(42, \"foo\")"); } -#endif // FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT TEST(ranges_test, format_to) { char buf[10]; @@ -232,6 +269,33 @@ TEST(ranges_test, disabled_range_formatting_of_path) { fmt::range_format::disabled); } +struct vector_string : std::vector { + using base = std::vector; + using base::base; +}; +struct vector_debug_string : std::vector { + using base = std::vector; + using base::base; +}; +FMT_BEGIN_NAMESPACE +template <> +struct range_format_kind + : std::integral_constant {}; +template <> +struct range_format_kind + : std::integral_constant {}; +FMT_END_NAMESPACE + +TEST(ranges_test, range_format_string) { + const vector_string v{'f', 'o', 'o'}; + EXPECT_EQ(fmt::format("{}", v), "foo"); +} + +TEST(ranges_test, range_format_debug_string) { + const vector_debug_string v{'f', 'o', 'o'}; + EXPECT_EQ(fmt::format("{}", v), "\"foo\""); +} + // A range that provides non-const only begin()/end() to test fmt::join // handles that. // @@ -287,7 +351,7 @@ TEST(ranges_test, range) { EXPECT_EQ(fmt::format("{}", z), "[0, 0, 0]"); } -enum test_enum { foo }; +enum test_enum { foo, bar }; auto format_as(test_enum e) -> int { return e; } TEST(ranges_test, enum_range) { @@ -297,12 +361,44 @@ TEST(ranges_test, enum_range) { #if !FMT_MSC_VERSION TEST(ranges_test, unformattable_range) { - EXPECT_FALSE((fmt::has_formatter, - fmt::format_context>::value)); + EXPECT_FALSE((fmt::is_formattable, char>::value)); +} +#endif + +TEST(ranges_test, join) { + using fmt::join; + int v1[3] = {1, 2, 3}; + auto v2 = std::vector(); + v2.push_back(1.2f); + v2.push_back(3.4f); + void* v3[2] = {&v1[0], &v1[1]}; + + EXPECT_EQ(fmt::format("({})", join(v1, v1 + 3, ", ")), "(1, 2, 3)"); + EXPECT_EQ(fmt::format("({})", join(v1, v1 + 1, ", ")), "(1)"); + EXPECT_EQ(fmt::format("({})", join(v1, v1, ", ")), "()"); + EXPECT_EQ(fmt::format("({:03})", join(v1, v1 + 3, ", ")), "(001, 002, 003)"); + EXPECT_EQ("(+01.20, +03.40)", + fmt::format("({:+06.2f})", join(v2.begin(), v2.end(), ", "))); + + EXPECT_EQ(fmt::format("{0:{1}}", join(v1, v1 + 3, ", "), 1), "1, 2, 3"); + + EXPECT_EQ(fmt::format("{}, {}", v3[0], v3[1]), + fmt::format("{}", join(v3, v3 + 2, ", "))); + + EXPECT_EQ(fmt::format("({})", join(v1, ", ")), "(1, 2, 3)"); + EXPECT_EQ(fmt::format("({:+06.2f})", join(v2, ", ")), "(+01.20, +03.40)"); + + auto v4 = std::vector{foo, bar, foo}; + EXPECT_EQ(fmt::format("{}", join(v4, " ")), "0 1 0"); +} + +#ifdef __cpp_lib_byte +TEST(ranges_test, join_bytes) { + auto v = std::vector{std::byte(1), std::byte(2), std::byte(3)}; + EXPECT_EQ(fmt::format("{}", fmt::join(v, ", ")), "1, 2, 3"); } #endif -#ifdef FMT_RANGES_TEST_ENABLE_JOIN TEST(ranges_test, join_tuple) { // Value tuple args. auto t1 = std::tuple('a', 1, 2.0f); @@ -321,6 +417,10 @@ TEST(ranges_test, join_tuple) { auto t4 = std::tuple(4.0f); EXPECT_EQ(fmt::format("{}", fmt::join(t4, "/")), "4"); + // Tuple-like. + auto t5 = tuple_like{42, "foo"}; + EXPECT_EQ(fmt::format("{}", fmt::join(t5, ", ")), "42, foo"); + # if FMT_TUPLE_JOIN_SPECIFIERS // Specs applied to each element. auto t5 = std::tuple(-3, 100, 1); @@ -420,9 +520,21 @@ TEST(ranges_test, join_range) { "0,1,2,3,4"); # endif } -#endif // FMT_RANGES_TEST_ENABLE_JOIN -#if defined(__cpp_lib_ranges) && __cpp_lib_ranges >= 202302L +namespace adl { +struct vec { + int n[2] = {42, 43}; +}; + +auto begin(const vec& v) -> const int* { return v.n; } +auto end(const vec& v) -> const int* { return v.n + 2; } +} // namespace adl + +TEST(ranges_test, format_join_adl_begin_end) { + EXPECT_EQ(fmt::format("{}", fmt::join(adl::vec(), "/")), "42/43"); +} + +#if defined(__cpp_lib_ranges) && __cpp_lib_ranges >= 202207L TEST(ranges_test, nested_ranges) { auto l = std::list{1, 2, 3}; auto r = std::views::iota(0, 3) | std::views::transform([&l](auto i) { @@ -447,7 +559,7 @@ TEST(ranges_test, escape) { EXPECT_EQ(fmt::format("{}", vec{"\x7f"}), "[\"\\x7f\"]"); EXPECT_EQ(fmt::format("{}", vec{"n\xcc\x83"}), "[\"n\xcc\x83\"]"); - if (fmt::detail::is_utf8()) { + if (fmt::detail::use_utf8) { EXPECT_EQ(fmt::format("{}", vec{"\xcd\xb8"}), "[\"\\u0378\"]"); // Unassigned Unicode code points. EXPECT_EQ(fmt::format("{}", vec{"\xf0\xaa\x9b\x9e"}), "[\"\\U0002a6de\"]"); @@ -465,7 +577,11 @@ TEST(ranges_test, escape) { EXPECT_EQ(fmt::format("{}", std::vector>{{'x'}}), "[['x']]"); + +// Disabled due to a clang 17 bug: https://github.com/fmtlib/fmt/issues/4144. +#if FMT_CLANG_VERSION >= 1800 EXPECT_EQ(fmt::format("{}", std::tuple>{{'x'}}), "(['x'])"); +#endif } template struct fmt_ref_view { @@ -544,6 +660,8 @@ TEST(ranges_test, container_adaptor) { m.push(2); EXPECT_EQ(fmt::format("{}", m), "[1, 2]"); } + + EXPECT_FALSE(fmt::is_formattable>::value); } struct tieable { @@ -558,3 +676,121 @@ auto format_as(const tieable& t) -> std::tuple { TEST(ranges_test, format_as_tie) { EXPECT_EQ(fmt::format("{}", tieable()), "(3, 0.42)"); } + +struct lvalue_qualified_begin_end { + int arr[5] = {1, 2, 3, 4, 5}; + + auto begin() & -> const int* { return arr; } + auto end() & -> const int* { return arr + 5; } +}; + +TEST(ranges_test, lvalue_qualified_begin_end) { + EXPECT_EQ(fmt::format("{}", lvalue_qualified_begin_end{}), "[1, 2, 3, 4, 5]"); +} + +#if !defined(__cpp_lib_ranges) || __cpp_lib_ranges <= 202106L +# define ENABLE_STD_VIEWS_TESTS 0 +#elif FMT_CLANG_VERSION +# if FMT_CLANG_VERSION > 1500 +# define ENABLE_STD_VIEWS_TESTS 1 +# else +# define ENABLE_STD_VIEWS_TESTS 0 +# endif +#else +# define ENABLE_STD_VIEWS_TESTS 1 +#endif + +#if ENABLE_STD_VIEWS_TESTS +TEST(ranges_test, input_range_join) { + auto iss = std::istringstream("1 2 3 4 5"); + auto view = std::views::istream(iss); + EXPECT_EQ("1, 2, 3, 4, 5", + fmt::format("{}", fmt::join(view.begin(), view.end(), ", "))); +} + +TEST(ranges_test, input_range_join_overload) { + auto iss = std::istringstream("1 2 3 4 5"); + EXPECT_EQ( + "1.2.3.4.5", + fmt::format("{}", fmt::join(std::views::istream(iss), "."))); +} + +namespace views_filter_view_test { +struct codec_mask { + static constexpr auto codecs = std::array{0, 1, 2, 3}; + int except = 0; +}; + +auto format_as(codec_mask mask) { + // Careful not to capture param by reference here, it will dangle. + return codec_mask::codecs | + std::views::filter([mask](auto c) { return c != mask.except; }); +} +} // namespace views_filter_view_test + +TEST(ranges_test, format_as_with_ranges_mutable_begin_end) { + using namespace views_filter_view_test; + { + auto make_filter_view = []() { + return codec_mask::codecs | + std::views::filter([](auto c) { return c != 2; }); + }; + auto r = make_filter_view(); + EXPECT_EQ("[0, 1, 3]", fmt::format("{}", r)); + EXPECT_EQ("[0, 1, 3]", fmt::format("{}", make_filter_view())); + } + + { + auto mask = codec_mask{2}; + const auto const_mask = codec_mask{2}; + + EXPECT_EQ("[0, 1, 3]", fmt::format("{}", mask)); + EXPECT_EQ("[0, 1, 3]", fmt::format("{}", const_mask)); + EXPECT_EQ("[0, 1, 3]", fmt::format("{}", codec_mask{2})); + } +} + +#endif + +TEST(ranges_test, std_istream_iterator_join) { + auto&& iss = std::istringstream("1 2 3 4 5"); + auto first = std::istream_iterator(iss); + auto last = std::istream_iterator(); + EXPECT_EQ("1, 2, 3, 4, 5", fmt::format("{}", fmt::join(first, last, ", "))); +} + +// Mirrors C++20 std::ranges::basic_istream_view::iterator. +struct noncopyable_istream_iterator : std::istream_iterator { + using base = std::istream_iterator; + explicit noncopyable_istream_iterator(std::istringstream& iss) : base{iss} {} + noncopyable_istream_iterator(const noncopyable_istream_iterator&) = delete; + noncopyable_istream_iterator(noncopyable_istream_iterator&&) = default; +}; +static_assert(!std::is_copy_constructible::value, + ""); + +TEST(ranges_test, movable_only_istream_iter_join) { + auto&& iss = std::istringstream("1 2 3 4 5"); + auto first = noncopyable_istream_iterator(iss); + auto last = std::istream_iterator(); + EXPECT_EQ("1, 2, 3, 4, 5", + fmt::format("{}", fmt::join(std::move(first), last, ", "))); +} + +struct movable_iter_range { + std::istringstream iss{"1 2 3 4 5"}; + noncopyable_istream_iterator begin() { + return noncopyable_istream_iterator{iss}; + } + std::istream_iterator end() { return {}; } +}; + +TEST(ranges_test, movable_only_istream_iter_join2) { + EXPECT_EQ("[1, 2, 3, 4, 5]", fmt::format("{}", movable_iter_range{})); +} + +struct not_range { + void begin() const {} + void end() const {} +}; +static_assert(!fmt::is_formattable{}, ""); diff --git a/third-party/fmt/test/scan-test.cc b/third-party/fmt/test/scan-test.cc index f0ede192fb..03b26e5d8a 100644 --- a/third-party/fmt/test/scan-test.cc +++ b/third-party/fmt/test/scan-test.cc @@ -18,71 +18,57 @@ TEST(scan_test, read_text) { fmt::string_view s = "foo"; - auto end = fmt::scan(s, "foo"); + auto end = fmt::scan_to(s, "foo"); EXPECT_EQ(end, s.end()); - EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); + EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, + "invalid input"); } TEST(scan_test, read_int) { - int n = 0; - fmt::scan("42", "{}", n); - EXPECT_EQ(n, 42); - fmt::scan("-42", "{}", n); - EXPECT_EQ(n, -42); - fmt::scan("42", "{:}", n); - EXPECT_EQ(n, 42); - EXPECT_THROW_MSG(fmt::scan(std::to_string(INT_MAX + 1u), "{}", n), + EXPECT_EQ(fmt::scan("42", "{}")->value(), 42); + EXPECT_EQ(fmt::scan("-42", "{}")->value(), -42); + EXPECT_EQ(fmt::scan("42", "{:}")->value(), 42); + EXPECT_THROW_MSG(fmt::scan(std::to_string(INT_MAX + 1u), "{}"), fmt::format_error, "number is too big"); } -TEST(scan_test, read_longlong) { - long long n = 0; - fmt::scan("42", "{}", n); - EXPECT_EQ(n, 42); - fmt::scan("-42", "{}", n); - EXPECT_EQ(n, -42); +TEST(scan_test, read_long_long) { + EXPECT_EQ(fmt::scan("42", "{}")->value(), 42); + EXPECT_EQ(fmt::scan("-42", "{}")->value(), -42); } TEST(scan_test, read_uint) { - unsigned n = 0; - fmt::scan("42", "{}", n); - EXPECT_EQ(n, 42); - EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, + EXPECT_EQ(fmt::scan("42", "{}")->value(), 42); + EXPECT_THROW_MSG(fmt::scan("-42", "{}"), fmt::format_error, "invalid input"); } -TEST(scan_test, read_ulonglong) { - 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(scan_test, read_ulong_long) { + EXPECT_EQ(fmt::scan("42", "{}")->value(), 42); + EXPECT_THROW_MSG(fmt::scan("-42", "{}")->value(), + fmt::format_error, "invalid input"); } TEST(scan_test, read_hex) { - unsigned n = 0; - fmt::scan("2a", "{:x}", n); - EXPECT_EQ(n, 42); + EXPECT_EQ(fmt::scan("2a", "{:x}")->value(), 42); auto num_digits = std::numeric_limits::digits / 4; - EXPECT_THROW_MSG(fmt::scan(fmt::format("1{:0{}}", 0, num_digits), "{:x}", n), - fmt::format_error, "number is too big"); + EXPECT_THROW_MSG( + fmt::scan(fmt::format("1{:0{}}", 0, num_digits), "{:x}") + ->value(), + fmt::format_error, "number is too big"); } TEST(scan_test, read_string) { - std::string s; - fmt::scan("foo", "{}", s); - EXPECT_EQ(s, "foo"); + EXPECT_EQ(fmt::scan("foo", "{}")->value(), "foo"); } TEST(scan_test, read_string_view) { - fmt::string_view s; - fmt::scan("foo", "{}", s); - EXPECT_EQ(s, "foo"); + EXPECT_EQ(fmt::scan("foo", "{}")->value(), "foo"); } TEST(scan_test, separator) { int n1 = 0, n2 = 0; - fmt::scan("10 20", "{} {}", n1, n2); + fmt::scan_to("10 20", "{} {}", n1, n2); EXPECT_EQ(n1, 10); EXPECT_EQ(n2, 20); } @@ -97,79 +83,90 @@ template <> struct scanner { auto parse(scan_parse_context& ctx) -> scan_parse_context::iterator { auto it = ctx.begin(), end = ctx.end(); - if (it != end && *it == 'x') hex = true; - if (it != end && *it != '}') throw_format_error("invalid format"); + if (it != end && *it == 'x') { + hex = true; + ++it; + } + if (it != end && *it != '}') report_error("invalid format"); return it; } template auto scan(num& n, ScanContext& ctx) const -> typename ScanContext::iterator { - // TODO: handle specifier - return fmt::scan(ctx, "{}", n.value); + return hex ? scan_to(ctx, "{:x}", n.value) : scan_to(ctx, "{}", n.value); } }; } // namespace fmt TEST(scan_test, read_custom) { - auto input = "42"; - auto n = num(); - fmt::scan(input, "{:}", n); - EXPECT_EQ(n.value, 42); + EXPECT_EQ(fmt::scan("42", "{}")->value().value, 42); + EXPECT_EQ(fmt::scan("2a", "{:x}")->value().value, 42); } TEST(scan_test, invalid_format) { - EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error, + EXPECT_THROW_MSG(fmt::scan_to("", "{}"), fmt::format_error, "argument index out of range"); - EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error, + EXPECT_THROW_MSG(fmt::scan_to("", "{"), fmt::format_error, "invalid format string"); } +namespace std { +using fmt::scan; +using fmt::scan_error; +} // namespace std + TEST(scan_test, example) { - std::string key; - int value = 0; - fmt::scan("answer = 42", "{} = {}", key, value); - EXPECT_EQ(key, "answer"); - EXPECT_EQ(value, 42); + // Example from https://wg21.link/p1729r3. + if (auto result = std::scan("answer = 42", "{} = {}")) { + auto range = result->range(); + EXPECT_EQ(range.begin(), range.end()); + EXPECT_EQ(result->begin(), result->end()); +#ifdef __cpp_structured_bindings + const auto& [key, value] = result->values(); + EXPECT_EQ(key, "answer"); + EXPECT_EQ(value, 42); +#endif + } else { + std::scan_error error = result.error(); + (void)error; + FAIL(); + } } -TEST(scan_test, end_of_input) { - int value = 0; - fmt::scan("", "{}", value); -} +TEST(scan_test, end_of_input) { fmt::scan("", "{}"); } #if FMT_USE_FCNTL TEST(scan_test, file) { - fmt::file read_end, write_end; - fmt::file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); fmt::string_view input = "10 20"; - write_end.write(input.data(), input.size()); - write_end.close(); + pipe.write_end.write(input.data(), input.size()); + pipe.write_end.close(); int n1 = 0, n2 = 0; - fmt::buffered_file f = read_end.fdopen("r"); - fmt::scan(f.get(), "{} {}", n1, n2); + fmt::buffered_file f = pipe.read_end.fdopen("r"); + fmt::scan_to(f.get(), "{} {}", n1, n2); EXPECT_EQ(n1, 10); EXPECT_EQ(n2, 20); } TEST(scan_test, lock) { - fmt::file read_end, write_end; - fmt::file::pipe(read_end, write_end); + auto pipe = fmt::pipe(); std::thread producer([&]() { fmt::string_view input = "42 "; - for (int i = 0; i < 1000; ++i) write_end.write(input.data(), input.size()); - write_end.close(); + for (int i = 0; i < 1000; ++i) + pipe.write_end.write(input.data(), input.size()); + pipe.write_end.close(); }); std::atomic count(0); - fmt::buffered_file f = read_end.fdopen("r"); + fmt::buffered_file f = pipe.read_end.fdopen("r"); auto fun = [&]() { int value = 0; - while (fmt::scan(f.get(), "{}", value)) { + while (fmt::scan_to(f.get(), "{}", value)) { if (value != 42) { - read_end.close(); + pipe.read_end.close(); EXPECT_EQ(value, 42); break; } @@ -178,11 +175,10 @@ TEST(scan_test, lock) { }; std::thread consumer1(fun); std::thread consumer2(fun); - + producer.join(); consumer1.join(); consumer2.join(); EXPECT_EQ(count, 1000); - } #endif // FMT_USE_FCNTL diff --git a/third-party/fmt/test/scan.h b/third-party/fmt/test/scan.h index a68c77c3b4..8a58ea7bc2 100644 --- a/third-party/fmt/test/scan.h +++ b/third-party/fmt/test/scan.h @@ -8,15 +8,16 @@ #include #include #include +#include -#include "fmt/format.h" +#include "fmt/format-inl.h" FMT_BEGIN_NAMESPACE namespace detail { inline auto is_whitespace(char c) -> bool { return c == ' ' || c == '\n'; } -// If c is a hex digit returns its numeric value, othewise -1. +// If c is a hex digit returns its numeric value, otherwise -1. inline auto to_hex_digit(char c) -> int { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; @@ -42,9 +43,9 @@ class scan_buffer { : ptr_(ptr), end_(end), contiguous_(contiguous) {} ~scan_buffer() = default; - void set(string_view buf) { - ptr_ = buf.begin(); - end_ = buf.end(); + void set(span buf) { + ptr_ = buf.data; + end_ = buf.data + buf.size; } auto ptr() const -> const char* { return ptr_; } @@ -141,7 +142,7 @@ class scan_buffer { using scan_iterator = scan_buffer::iterator; using scan_sentinel = scan_buffer::sentinel; -class string_scan_buffer : public scan_buffer { +class string_scan_buffer final : public scan_buffer { private: void consume() override {} @@ -150,90 +151,15 @@ class string_scan_buffer : public scan_buffer { : scan_buffer(s.begin(), s.end(), true) {} }; -#ifdef _WIN32 -void flockfile(FILE* f) { _lock_file(f); } -void funlockfile(FILE* f) { _unlock_file(f); } -int getc_unlocked(FILE* f) { return _fgetc_nolock(f); } -#endif - -// A FILE wrapper. F is FILE defined as a template parameter to make -// system-specific API detection work. -template class file_base { - protected: - F* file_; - - public: - file_base(F* file) : file_(file) {} - operator F*() const { return file_; } - - // Reads a code unit from the stream. - auto get() -> int { - int result = getc_unlocked(file_); - if (result == EOF && ferror(file_) != 0) - FMT_THROW(system_error(errno, FMT_STRING("getc failed"))); - return result; - } - - // Puts the code unit back into the stream buffer. - void unget(char c) { - if (ungetc(c, file_) == EOF) - FMT_THROW(system_error(errno, FMT_STRING("ungetc failed"))); - } -}; - -// A FILE wrapper for glibc. -template class glibc_file : public file_base { - public: - using file_base::file_base; - - // Returns the file's read buffer as a string_view. - auto buffer() const -> string_view { - return {this->file_->_IO_read_ptr, - to_unsigned(this->file_->_IO_read_end - this->file_->_IO_read_ptr)}; - } -}; - -// A FILE wrapper for Apple's libc. -template class apple_file : public file_base { - public: - using file_base::file_base; - - auto buffer() const -> string_view { - return {reinterpret_cast(this->file_->_p), - to_unsigned(this->file_->_r)}; - } -}; - -// A fallback FILE wrapper. -template class fallback_file : public file_base { +class file_scan_buffer final : public scan_buffer { private: - char next_; // The next unconsumed character in the buffer. - bool has_next_ = false; - - public: - using file_base::file_base; - - auto buffer() const -> string_view { return {&next_, has_next_ ? 1u : 0u}; } - - auto get() -> int { - has_next_ = false; - return file_base::get(); - } - - void unget(char c) { - file_base::unget(c); - next_ = c; - has_next_ = true; - } -}; - -class file_scan_buffer : public scan_buffer { - private: - template + template static auto get_file(F* f, int) -> glibc_file { return f; } - template + template static auto get_file(F* f, int) -> apple_file { return f; } @@ -243,19 +169,19 @@ class file_scan_buffer : public scan_buffer { // Fills the buffer if it is empty. void fill() { - string_view buf = file_.buffer(); - if (buf.size() == 0) { + span buf = file_.get_read_buffer(); + if (buf.size == 0) { int c = file_.get(); // Put the character back since we are only filling the buffer. if (c != EOF) file_.unget(static_cast(c)); - buf = file_.buffer(); + buf = file_.get_read_buffer(); } set(buf); } void consume() override { // Consume the current buffer content. - size_t n = to_unsigned(ptr() - file_.buffer().begin()); + size_t n = to_unsigned(ptr() - file_.get_read_buffer().data); for (size_t i = 0; i != n; ++i) file_.get(); fill(); } @@ -266,7 +192,10 @@ class file_scan_buffer : public scan_buffer { flockfile(f); fill(); } - ~file_scan_buffer() { funlockfile(file_); } + ~file_scan_buffer() { + FILE* f = file_; + funlockfile(f); + } }; } // namespace detail @@ -282,7 +211,7 @@ class scan_parse_context { public: using iterator = string_view::iterator; - explicit FMT_CONSTEXPR scan_parse_context(string_view format) + FMT_CONSTEXPR explicit scan_parse_context(string_view format) : format_(format) {} FMT_CONSTEXPR auto begin() const -> iterator { return format_.begin(); } @@ -418,7 +347,7 @@ class scan_context { using iterator = detail::scan_iterator; using sentinel = detail::scan_sentinel; - explicit FMT_CONSTEXPR scan_context(detail::scan_buffer& buf, scan_args args) + FMT_CONSTEXPR explicit scan_context(detail::scan_buffer& buf, scan_args args) : buf_(buf), args_(args) {} FMT_CONSTEXPR auto arg(int id) const -> scan_arg { @@ -434,12 +363,12 @@ class scan_context { namespace detail { const char* parse_scan_specs(const char* begin, const char* end, - format_specs<>& specs, scan_type) { + format_specs& specs, scan_type) { while (begin != end) { switch (to_ascii(*begin)) { // TODO: parse more scan format specifiers case 'x': - specs.type = presentation_type::hex_lower; + specs.set_type(presentation_type::hex); ++begin; break; case '}': @@ -450,11 +379,10 @@ const char* parse_scan_specs(const char* begin, const char* end, } template ::value)> -auto read(scan_iterator it, T& value) - -> scan_iterator { +auto read(scan_iterator it, T& value) -> scan_iterator { if (it == scan_sentinel()) return it; char c = *it; - if (c < '0' || c > '9') throw_format_error("invalid input"); + if (c < '0' || c > '9') report_error("invalid input"); int num_digits = 0; T n = 0, prev = 0; @@ -478,17 +406,16 @@ auto read(scan_iterator it, T& value) prev * 10ull + unsigned(prev_digit - '0') <= max) { value = n; } else { - throw_format_error("number is too big"); + report_error("number is too big"); } return it; } template ::value)> -auto read_hex(scan_iterator it, T& value) - -> scan_iterator { +auto read_hex(scan_iterator it, T& value) -> scan_iterator { if (it == scan_sentinel()) return it; int digit = to_hex_digit(*it); - if (digit < 0) throw_format_error("invalid input"); + if (digit < 0) report_error("invalid input"); int num_digits = 0; T n = 0; @@ -503,45 +430,44 @@ auto read_hex(scan_iterator it, T& value) if (num_digits <= (std::numeric_limits::digits >> 2)) value = n; else - throw_format_error("number is too big"); + report_error("number is too big"); return it; } template ::value)> -auto read(scan_iterator it, T& value, const format_specs<>& specs) +auto read(scan_iterator it, T& value, const format_specs& specs) -> scan_iterator { - if (specs.type == presentation_type::hex_lower) - return read_hex(it, value); + if (specs.type() == presentation_type::hex) return read_hex(it, value); return read(it, value); } template ::value)> -auto read(scan_iterator it, T& value, const format_specs<>& = {}) +auto read(scan_iterator it, T& value, const format_specs& specs = {}) -> scan_iterator { bool negative = it != scan_sentinel() && *it == '-'; if (negative) { ++it; - if (it == scan_sentinel()) throw_format_error("invalid input"); + if (it == scan_sentinel()) report_error("invalid input"); } using unsigned_type = typename std::make_unsigned::type; unsigned_type abs_value = 0; - it = read(it, abs_value); + it = read(it, abs_value, specs); auto n = static_cast(abs_value); value = negative ? -n : n; return it; } -auto read(scan_iterator it, std::string& value, const format_specs<>& = {}) +auto read(scan_iterator it, std::string& value, const format_specs& = {}) -> scan_iterator { while (it != scan_sentinel() && *it != ' ') value.push_back(*it++); return it; } -auto read(scan_iterator it, string_view& value, const format_specs<>& = {}) +auto read(scan_iterator it, string_view& value, const format_specs& = {}) -> scan_iterator { auto range = to_contiguous(it); // This could also be checked at compile time in scan. - if (!range) throw_format_error("string_view requires contiguous input"); + if (!range) report_error("string_view requires contiguous input"); auto p = range.begin; while (p != range.end && *p != ' ') ++p; size_t size = to_unsigned(p - range.begin); @@ -549,7 +475,7 @@ auto read(scan_iterator it, string_view& value, const format_specs<>& = {}) return advance(it, size); } -auto read(scan_iterator it, monostate, const format_specs<>& = {}) +auto read(scan_iterator it, monostate, const format_specs& = {}) -> scan_iterator { return it; } @@ -566,14 +492,14 @@ struct default_arg_scanner { // An argument scanner with format specifiers. struct arg_scanner { scan_iterator it; - const format_specs<>& specs; + const format_specs& specs; template auto operator()(T&& value) -> scan_iterator { return read(it, value, specs); } }; -struct scan_handler : error_handler { +struct scan_handler { private: scan_parse_context parse_ctx_; scan_context scan_ctx_; @@ -607,8 +533,9 @@ struct scan_handler : error_handler { return 0; } - void on_replacement_field(int arg_id, const char*) { + void on_replacement_field(int arg_id, const char* begin) { scan_arg arg = scan_ctx_.arg(arg_id); + if (arg.scan_custom(begin, parse_ctx_, scan_ctx_)) return; auto it = scan_ctx_.begin(); while (it != sentinel() && is_whitespace(*it)) ++it; scan_ctx_.advance_to(arg.visit(default_arg_scanner{it})); @@ -619,47 +546,123 @@ struct scan_handler : error_handler { scan_arg arg = scan_ctx_.arg(arg_id); if (arg.scan_custom(begin, parse_ctx_, scan_ctx_)) return parse_ctx_.begin(); - auto specs = format_specs<>(); + auto specs = format_specs(); begin = parse_scan_specs(begin, end, specs, arg.type()); if (begin == end || *begin != '}') on_error("missing '}' in format string"); scan_ctx_.advance_to(arg.visit(arg_scanner{scan_ctx_.begin(), specs})); return begin; } - void on_error(const char* message) { error_handler::on_error(message); } + FMT_NORETURN void on_error(const char* message) { report_error(message); } }; + +void vscan(detail::scan_buffer& buf, string_view fmt, scan_args args) { + auto h = detail::scan_handler(fmt, buf, args); + detail::parse_format_string(fmt, h); +} + +template +void make_args(std::array&, std::tuple&) {} + +template +void make_args(std::array& args, + std::tuple& values) { + using element_type = typename std::tuple_element>::type; + static_assert(std::is_same, element_type>::value, + ""); + args[I] = std::get(values); + make_args(args, values); +} } // namespace detail +template class scan_data { + private: + std::tuple values_; + Range range_; + + public: + scan_data() = default; + scan_data(T... values) : values_(std::move(values)...) {} + + auto value() const -> decltype(std::get<0>(values_)) { + return std::get<0>(values_); + } + + auto values() const -> const std::tuple& { return values_; } + + auto make_args() -> std::array { + auto args = std::array(); + detail::make_args<0>(args, values_); + return args; + } + + auto range() const -> Range { return range_; } + + auto begin() const -> decltype(range_.begin()) { return range_.begin(); } + auto end() const -> decltype(range_.end()) { return range_.end(); } +}; + template auto make_scan_args(T&... args) -> std::array { return {{args...}}; } -void vscan(detail::scan_buffer& buf, string_view fmt, scan_args args) { - auto h = detail::scan_handler(fmt, buf, args); - detail::parse_format_string(fmt, h); -} +class scan_error {}; -template -auto scan(string_view input, string_view fmt, T&... args) +// A rudimentary version of std::expected for testing the API shape. +template class expected { + private: + T value_; + bool has_value_ = true; + + public: + expected(T value) : value_(std::move(value)) {} + + explicit operator bool() const { return has_value_; } + + auto operator->() const -> const T* { return &value_; } + + auto error() -> E const { return E(); } +}; + +template +using scan_result = expected, scan_error>; + +auto vscan(string_view input, string_view fmt, scan_args args) -> string_view::iterator { auto&& buf = detail::string_scan_buffer(input); - vscan(buf, fmt, make_scan_args(args...)); + detail::vscan(buf, fmt, args); return input.begin() + (buf.begin().base() - input.data()); } -template ::value)> -auto scan(InputRange&& input, string_view fmt, T&... args) +// Scans the input and stores the results (in)to args. +template +auto scan_to(string_view input, string_view fmt, T&... args) + -> string_view::iterator { + return vscan(input, fmt, make_scan_args(args...)); +} + +template +auto scan(string_view input, string_view fmt) + -> scan_result { + auto data = scan_data(); + vscan(input, fmt, data.make_args()); + return data; +} + +template ::value)> +auto scan_to(Range&& input, string_view fmt, T&... args) -> decltype(std::begin(input)) { auto it = std::begin(input); - vscan(get_buffer(it), fmt, make_scan_args(args...)); + detail::vscan(get_buffer(it), fmt, make_scan_args(args...)); return it; } -template bool scan(std::FILE* f, string_view fmt, T&... args) { +template +auto scan_to(FILE* f, string_view fmt, T&... args) -> bool { auto&& buf = detail::file_scan_buffer(f); - vscan(buf, fmt, make_scan_args(args...)); + detail::vscan(buf, fmt, make_scan_args(args...)); return buf.begin() != buf.end(); } diff --git a/third-party/fmt/test/std-test.cc b/third-party/fmt/test/std-test.cc index de3feaa051..760daf8f1a 100644 --- a/third-party/fmt/test/std-test.cc +++ b/third-party/fmt/test/std-test.cc @@ -13,13 +13,17 @@ #include #include "fmt/os.h" // fmt::system_category -#include "fmt/ranges.h" #include "gtest-extra.h" // StartsWith #ifdef __cpp_lib_filesystem TEST(std_test, path) { using std::filesystem::path; EXPECT_EQ(fmt::format("{}", path("/usr/bin")), "/usr/bin"); + + // see #4303 + const path p = "/usr/bin"; + EXPECT_EQ(fmt::format("{}", p), "/usr/bin"); + EXPECT_EQ(fmt::format("{:?}", path("/usr/bin")), "\"/usr/bin\""); EXPECT_EQ(fmt::format("{:8}", path("foo")), "foo "); @@ -35,10 +39,18 @@ TEST(std_test, path) { L"\x0447\x044B\x043D\x0430")), "Шчучыншчына"); EXPECT_EQ(fmt::format("{}", path(L"\xd800")), "�"); + EXPECT_EQ(fmt::format("{}", path(L"HEAD \xd800 TAIL")), "HEAD � TAIL"); + EXPECT_EQ(fmt::format("{}", path(L"HEAD \xD83D\xDE00 TAIL")), + "HEAD \xF0\x9F\x98\x80 TAIL"); + EXPECT_EQ(fmt::format("{}", path(L"HEAD \xD83D\xD83D\xDE00 TAIL")), + "HEAD �\xF0\x9F\x98\x80 TAIL"); EXPECT_EQ(fmt::format("{:?}", path(L"\xd800")), "\"\\ud800\""); # endif } +// Intentionally delayed include to test #4303 +#include "fmt/ranges.h" + // Test ambiguity problem described in #2954. TEST(ranges_std_test, format_vector_path) { auto p = std::filesystem::path("foo/bar.txt"); @@ -65,6 +77,40 @@ TEST(std_test, thread_id) { EXPECT_FALSE(fmt::format("{}", std::this_thread::get_id()).empty()); } +TEST(std_test, complex) { + using limits = std::numeric_limits; + EXPECT_EQ(fmt::format("{}", std::complex(1, limits::quiet_NaN())), + "(1+nan i)"); + EXPECT_EQ(fmt::format("{}", std::complex(1, -limits::infinity())), + "(1-inf i)"); + + EXPECT_EQ(fmt::format("{}", std::complex(1, 2)), "(1+2i)"); + + EXPECT_EQ(fmt::format("{}", std::complex(1, 2.2)), "(1+2.2i)"); + EXPECT_EQ(fmt::format("{}", std::complex(1, -2.2)), "(1-2.2i)"); + EXPECT_EQ(fmt::format("{}", std::complex(0, 2.2)), "2.2i"); + EXPECT_EQ(fmt::format("{}", std::complex(0, -2.2)), "-2.2i"); + + EXPECT_EQ(fmt::format("{:+}", std::complex(0, 2.2)), "+2.2i"); + EXPECT_EQ(fmt::format("{:+}", std::complex(0, -2.2)), "-2.2i"); + EXPECT_EQ(fmt::format("{:+}", std::complex(1, -2.2)), "(+1-2.2i)"); + EXPECT_EQ(fmt::format("{:+}", std::complex(1, 2.2)), "(+1+2.2i)"); + EXPECT_EQ(fmt::format("{: }", std::complex(1, 2.2)), "( 1+2.2i)"); + EXPECT_EQ(fmt::format("{: }", std::complex(1, -2.2)), "( 1-2.2i)"); + + EXPECT_EQ(fmt::format("{:8}", std::complex(1, 2)), "(1+2i) "); + EXPECT_EQ(fmt::format("{:-<8}", std::complex(1, 2)), "(1+2i)--"); + + EXPECT_EQ(fmt::format("{:>20.2f}", std::complex(1, 2.2)), + " (1.00+2.20i)"); + EXPECT_EQ(fmt::format("{:<20.2f}", std::complex(1, 2.2)), + "(1.00+2.20i) "); + EXPECT_EQ(fmt::format("{:<20.2f}", std::complex(1, -2.2)), + "(1.00-2.20i) "); + EXPECT_EQ(fmt::format("{:<{}.{}f}", std::complex(1, -2.2), 20, 2), + "(1.00-2.20i) "); +} + #ifdef __cpp_lib_source_location TEST(std_test, source_location) { std::source_location loc = std::source_location::current(); @@ -102,6 +148,36 @@ TEST(std_test, optional) { #endif } +TEST(std_test, expected) { +#ifdef __cpp_lib_expected + EXPECT_EQ(fmt::format("{}", std::expected{}), "expected()"); + EXPECT_EQ(fmt::format("{}", std::expected{1}), "expected(1)"); + EXPECT_EQ(fmt::format("{}", std::expected{std::unexpected(1)}), + "unexpected(1)"); + EXPECT_EQ(fmt::format("{}", std::expected{"test"}), + "expected(\"test\")"); + EXPECT_EQ(fmt::format( + "{}", std::expected{std::unexpected("test")}), + "unexpected(\"test\")"); + EXPECT_EQ(fmt::format("{}", std::expected{'a'}), "expected('a')"); + EXPECT_EQ(fmt::format("{}", std::expected{std::unexpected('a')}), + "unexpected('a')"); + + struct unformattable1 {}; + struct unformattable2 {}; + EXPECT_FALSE((fmt::is_formattable::value)); + EXPECT_FALSE((fmt::is_formattable::value)); + EXPECT_FALSE((fmt::is_formattable< + std::expected>::value)); + EXPECT_FALSE( + (fmt::is_formattable>::value)); + EXPECT_FALSE( + (fmt::is_formattable>::value)); + EXPECT_TRUE((fmt::is_formattable>::value)); + EXPECT_TRUE((fmt::is_formattable>::value)); +#endif +} + namespace my_nso { enum class my_number { one, @@ -199,9 +275,13 @@ TEST(std_test, variant) { } TEST(std_test, error_code) { + auto& generic = std::generic_category(); EXPECT_EQ("generic:42", - fmt::format(FMT_STRING("{0}"), - std::error_code(42, std::generic_category()))); + fmt::format(FMT_STRING("{0}"), std::error_code(42, generic))); + EXPECT_EQ(" generic:42", + fmt::format(FMT_STRING("{:>12}"), std::error_code(42, generic))); + EXPECT_EQ("generic:42 ", + fmt::format(FMT_STRING("{:12}"), std::error_code(42, generic))); EXPECT_EQ("system:42", fmt::format(FMT_STRING("{0}"), std::error_code(42, fmt::system_category()))); @@ -265,6 +345,13 @@ TEST(std_test, exception) { #endif } +#if FMT_USE_RTTI +TEST(std_test, type_info) { + EXPECT_EQ(fmt::format("{}", typeid(std::runtime_error)), + "std::runtime_error"); +} +#endif + TEST(std_test, format_bit_reference) { std::bitset<2> bs(1); EXPECT_EQ(fmt::format("{} {}", bs[0], bs[1]), "true false"); @@ -304,3 +391,26 @@ TEST(std_test, format_atomic_flag) { EXPECT_EQ(fmt::format("{}", cf), "false"); } #endif // __cpp_lib_atomic_flag_test + +TEST(std_test, format_unique_ptr) { + std::unique_ptr up(new int(1)); + EXPECT_EQ(fmt::format("{}", fmt::ptr(up.get())), + fmt::format("{}", fmt::ptr(up))); + struct custom_deleter { + void operator()(int* p) const { delete p; } + }; + std::unique_ptr upcd(new int(1)); + EXPECT_EQ(fmt::format("{}", fmt::ptr(upcd.get())), + fmt::format("{}", fmt::ptr(upcd))); +} + +TEST(std_test, format_shared_ptr) { + std::shared_ptr sp(new int(1)); + EXPECT_EQ(fmt::format("{}", fmt::ptr(sp.get())), + fmt::format("{}", fmt::ptr(sp))); +} + +TEST(std_test, format_reference_wrapper) { + int num = 35; + EXPECT_EQ("35", fmt::to_string(std::cref(num))); +} diff --git a/third-party/fmt/test/test-assert.h b/third-party/fmt/test/test-assert.h index ab7b2bf732..bec3dfc3e9 100644 --- a/third-party/fmt/test/test-assert.h +++ b/third-party/fmt/test/test-assert.h @@ -12,7 +12,7 @@ void throw_assertion_failure(const char* message); #define FMT_ASSERT(condition, message) \ - if (!(condition)) throw_assertion_failure(message); + ((condition) ? (void)0 : throw_assertion_failure(message)) #include "gtest/gtest.h" diff --git a/third-party/fmt/test/unicode-test.cc b/third-party/fmt/test/unicode-test.cc index e9ea5e5e07..2b59cff979 100644 --- a/third-party/fmt/test/unicode-test.cc +++ b/third-party/fmt/test/unicode-test.cc @@ -15,7 +15,7 @@ using testing::Contains; -TEST(unicode_test, is_utf8) { EXPECT_TRUE(fmt::detail::is_utf8()); } +TEST(unicode_test, use_utf8) { EXPECT_TRUE(fmt::detail::use_utf8); } TEST(unicode_test, legacy_locale) { auto loc = get_locale("be_BY.CP1251", "Belarusian_Belarus.1251"); diff --git a/third-party/fmt/test/util.cc b/third-party/fmt/test/util.cc index d3f2dc7375..8ea2661084 100644 --- a/third-party/fmt/test/util.cc +++ b/third-party/fmt/test/util.cc @@ -13,11 +13,10 @@ const char* const file_content = "Don't panic!"; fmt::buffered_file open_buffered_file(FILE** fp) { #if FMT_USE_FCNTL - fmt::file read_end, write_end; - fmt::file::pipe(read_end, write_end); - write_end.write(file_content, std::strlen(file_content)); - write_end.close(); - fmt::buffered_file f = read_end.fdopen("r"); + auto pipe = fmt::pipe(); + pipe.write_end.write(file_content, std::strlen(file_content)); + pipe.write_end.close(); + fmt::buffered_file f = pipe.read_end.fdopen("r"); if (fp) *fp = f.get(); #else fmt::buffered_file f("test-file", "w"); @@ -37,12 +36,11 @@ std::locale do_get_locale(const char* name) { std::locale get_locale(const char* name, const char* alt_name) { auto loc = do_get_locale(name); - if (loc == std::locale::classic() && alt_name) - loc = do_get_locale(alt_name); + if (loc == std::locale::classic() && alt_name) loc = do_get_locale(alt_name); #ifdef __OpenBSD__ - // Locales are not working in OpenBSD: - // https://github.com/fmtlib/fmt/issues/3670. - loc = std::locale::classic(); + // Locales are not working in OpenBSD: + // https://github.com/fmtlib/fmt/issues/3670. + loc = std::locale::classic(); #endif if (loc == std::locale::classic()) fmt::print(stderr, "{} locale is missing.\n", name); diff --git a/third-party/fmt/test/xchar-test.cc b/third-party/fmt/test/xchar-test.cc index 7f33fb27aa..fd613e820a 100644 --- a/third-party/fmt/test/xchar-test.cc +++ b/third-party/fmt/test/xchar-test.cc @@ -32,27 +32,29 @@ using testing::Contains; struct non_string {}; -template class is_string_test : public testing::Test {}; +template class has_to_string_view_test : public testing::Test {}; using string_char_types = testing::Types; -TYPED_TEST_SUITE(is_string_test, string_char_types); +TYPED_TEST_SUITE(has_to_string_view_test, string_char_types); template struct derived_from_string_view : fmt::basic_string_view {}; -TYPED_TEST(is_string_test, is_string) { - EXPECT_TRUE(fmt::detail::is_string::value); - EXPECT_TRUE(fmt::detail::is_string::value); - EXPECT_TRUE(fmt::detail::is_string::value); - EXPECT_TRUE(fmt::detail::is_string::value); - EXPECT_TRUE(fmt::detail::is_string>::value); - EXPECT_TRUE(fmt::detail::is_string>::value); +TYPED_TEST(has_to_string_view_test, has_to_string_view) { + EXPECT_TRUE(fmt::detail::has_to_string_view::value); + EXPECT_TRUE(fmt::detail::has_to_string_view::value); + EXPECT_TRUE(fmt::detail::has_to_string_view::value); + EXPECT_TRUE(fmt::detail::has_to_string_view::value); EXPECT_TRUE( - fmt::detail::is_string>::value); + fmt::detail::has_to_string_view>::value); + EXPECT_TRUE(fmt::detail::has_to_string_view< + fmt::basic_string_view>::value); + EXPECT_TRUE(fmt::detail::has_to_string_view< + derived_from_string_view>::value); using fmt_string_view = fmt::detail::std_string_view; EXPECT_TRUE(std::is_empty::value != - fmt::detail::is_string::value); - EXPECT_FALSE(fmt::detail::is_string::value); + fmt::detail::has_to_string_view::value); + EXPECT_FALSE(fmt::detail::has_to_string_view::value); } // std::is_constructible is broken in MSVC until version 2015. @@ -70,17 +72,17 @@ TEST(xchar_test, format_explicitly_convertible_to_wstring_view) { #endif TEST(xchar_test, format) { - EXPECT_EQ(L"42", fmt::format(L"{}", 42)); - EXPECT_EQ(L"4.2", fmt::format(L"{}", 4.2)); - EXPECT_EQ(L"abc", fmt::format(L"{}", L"abc")); - EXPECT_EQ(L"z", fmt::format(L"{}", L'z')); + EXPECT_EQ(fmt::format(L"{}", 42), L"42"); + EXPECT_EQ(fmt::format(L"{}", 4.2), L"4.2"); + EXPECT_EQ(fmt::format(L"{}", L"abc"), L"abc"); + EXPECT_EQ(fmt::format(L"{}", L'z'), L"z"); EXPECT_THROW(fmt::format(fmt::runtime(L"{:*\x343E}"), 42), fmt::format_error); - EXPECT_EQ(L"true", fmt::format(L"{}", true)); - EXPECT_EQ(L"a", fmt::format(L"{0}", 'a')); - EXPECT_EQ(L"a", fmt::format(L"{0}", L'a')); - EXPECT_EQ(L"Cyrillic letter \x42e", - fmt::format(L"Cyrillic letter {}", L'\x42e')); - EXPECT_EQ(L"abc1", fmt::format(L"{}c{}", L"ab", 1)); + EXPECT_EQ(fmt::format(L"{}", true), L"true"); + EXPECT_EQ(fmt::format(L"{0}", L'a'), L"a"); + EXPECT_EQ(fmt::format(L"Letter {}", L'\x40e'), L"Letter \x40e"); // Ў + if (sizeof(wchar_t) == 4) + EXPECT_EQ(fmt::format(fmt::runtime(L"{:𓀨>3}"), 42), L"𓀨42"); + EXPECT_EQ(fmt::format(L"{}c{}", L"ab", 1), L"abc1"); } TEST(xchar_test, is_formattable) { @@ -94,107 +96,21 @@ TEST(xchar_test, compile_time_string) { #endif } -#if FMT_CPLUSPLUS > 201103L -struct custom_char { - int value; - custom_char() = default; - - template - constexpr custom_char(T val) : value(static_cast(val)) {} - - constexpr operator char() const { - return value <= 0xff ? static_cast(value) : '\0'; - } - constexpr bool operator<(custom_char c) const { return value < c.value; } -}; - -namespace std { - -template <> struct char_traits { - using char_type = custom_char; - using int_type = int; - using off_type = streamoff; - using pos_type = streampos; - using state_type = mbstate_t; - - static constexpr void assign(char_type& r, const char_type& a) { r = a; } - static constexpr bool eq(char_type a, char_type b) { return a == b; } - static constexpr bool lt(char_type a, char_type b) { return a < b; } - static FMT_CONSTEXPR int compare(const char_type* s1, const char_type* s2, - size_t count) { - for (; count; count--, s1++, s2++) { - if (lt(*s1, *s2)) return -1; - if (lt(*s2, *s1)) return 1; - } - return 0; - } - static FMT_CONSTEXPR size_t length(const char_type* s) { - size_t count = 0; - while (!eq(*s++, custom_char(0))) count++; - return count; - } - static const char_type* find(const char_type*, size_t, const char_type&); - static FMT_CONSTEXPR char_type* move(char_type* dest, const char_type* src, - size_t count) { - if (count == 0) return dest; - char_type* ret = dest; - if (src < dest) { - dest += count; - src += count; - for (; count; count--) assign(*--dest, *--src); - } else if (src > dest) - copy(dest, src, count); - return ret; - } - static FMT_CONSTEXPR char_type* copy(char_type* dest, const char_type* src, - size_t count) { - char_type* ret = dest; - for (; count; count--) assign(*dest++, *src++); - return ret; - } - static FMT_CONSTEXPR char_type* assign(char_type* dest, std::size_t count, - char_type a) { - char_type* ret = dest; - for (; count; count--) assign(*dest++, a); - return ret; - } - static int_type not_eof(int_type); - static char_type to_char_type(int_type); - static int_type to_int_type(char_type); - static bool eq_int_type(int_type, int_type); - static int_type eof(); -}; - -} // namespace std - -auto to_ascii(custom_char c) -> char { return c; } - -FMT_BEGIN_NAMESPACE -template <> struct is_char : std::true_type {}; -FMT_END_NAMESPACE - -TEST(xchar_test, format_custom_char) { - const custom_char format[] = {'{', '}', 0}; - auto result = fmt::format(format, custom_char('x')); - EXPECT_EQ(result.size(), 1); - EXPECT_EQ(result[0], custom_char('x')); -} -#endif - -// Convert a char8_t string to std::string. Otherwise GTest will insist on -// inserting `char8_t` NTBS into a `char` stream which is disabled by P1423. -template std::string from_u8str(const S& str) { - return std::string(str.begin(), str.end()); -} - TEST(xchar_test, format_to) { auto buf = std::vector(); fmt::format_to(std::back_inserter(buf), L"{}{}", 42, L'\0'); EXPECT_STREQ(buf.data(), L"42"); } +TEST(xchar_test, compile_time_string_format_to) { + std::wstring ws; + fmt::format_to(std::back_inserter(ws), FMT_STRING(L"{}"), 42); + EXPECT_EQ(L"42", ws); +} + TEST(xchar_test, vformat_to) { - auto args = fmt::make_wformat_args(42); + int n = 42; + auto args = fmt::make_wformat_args(n); auto w = std::wstring(); fmt::vformat_to(std::back_inserter(w), L"{}", args); EXPECT_EQ(L"42", w); @@ -229,7 +145,6 @@ TEST(format_test, wide_format_to_n) { EXPECT_EQ(L"BC x", fmt::wstring_view(buffer, 4)); } -#if FMT_USE_USER_DEFINED_LITERALS TEST(xchar_test, named_arg_udl) { using namespace fmt::literals; auto udl_a = @@ -240,7 +155,6 @@ TEST(xchar_test, named_arg_udl) { fmt::arg(L"second", L"cad"), fmt::arg(L"third", 99)), udl_a); } -#endif // FMT_USE_USER_DEFINED_LITERALS TEST(xchar_test, print) { // Check that the wide print overload compiles. @@ -514,7 +428,7 @@ TEST(locale_test, format) { fmt::format(small_grouping_loc, "{:L}", max_value())); } -TEST(locale_test, format_detault_align) { +TEST(locale_test, format_default_align) { auto loc = std::locale({}, new special_grouping()); EXPECT_EQ(" 12,345", fmt::format(loc, "{:8L}", 12345)); } @@ -559,56 +473,15 @@ TEST(locale_test, int_formatter) { EXPECT_EQ(fmt::to_string(buf), "12,345"); } -FMT_BEGIN_NAMESPACE -template struct formatter, charT> { - private: - detail::dynamic_format_specs specs_; - - public: - FMT_CONSTEXPR typename basic_format_parse_context::iterator parse( - basic_format_parse_context& ctx) { - auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, - detail::type::float_type); - detail::parse_float_type_spec(specs_); - return end; - } - - template - typename FormatContext::iterator format(const std::complex& c, - FormatContext& ctx) { - detail::handle_dynamic_spec( - specs_.precision, specs_.precision_ref, ctx); - auto specs = std::string(); - if (specs_.precision > 0) specs = fmt::format(".{}", specs_.precision); - if (specs_.type == presentation_type::fixed_lower) specs += 'f'; - auto real = fmt::format(ctx.locale().template get(), - fmt::runtime("{:" + specs + "}"), c.real()); - auto imag = fmt::format(ctx.locale().template get(), - fmt::runtime("{:" + specs + "}"), c.imag()); - auto fill_align_width = std::string(); - if (specs_.width > 0) fill_align_width = fmt::format(">{}", specs_.width); - return fmt::format_to(ctx.out(), runtime("{:" + fill_align_width + "}"), - c.real() != 0 ? fmt::format("({}+{}i)", real, imag) - : fmt::format("{}i", imag)); - } -}; -FMT_END_NAMESPACE - -TEST(locale_test, complex) { - std::string s = fmt::format("{}", std::complex(1, 2)); - EXPECT_EQ(s, "(1+2i)"); - EXPECT_EQ(fmt::format("{:.2f}", std::complex(1, 2)), "(1.00+2.00i)"); - EXPECT_EQ(fmt::format("{:8}", std::complex(1, 2)), " (1+2i)"); -} - TEST(locale_test, chrono_weekday) { auto loc = get_locale("es_ES.UTF-8", "Spanish_Spain.1252"); auto loc_old = std::locale::global(loc); auto sat = fmt::weekday(6); EXPECT_EQ(fmt::format(L"{}", sat), L"Sat"); if (loc != std::locale::classic()) { - // L'\xE1' is 'á'. - auto saturdays = std::vector{L"s\xE1""b", L"s\xE1."}; + // L'\341' is 'á'. + auto saturdays = + std::vector{L"s\341b", L"s\341.", L"s\341b."}; EXPECT_THAT(saturdays, Contains(fmt::format(loc, L"{:L}", sat))); } std::locale::global(loc_old); @@ -618,6 +491,22 @@ TEST(locale_test, sign) { EXPECT_EQ(fmt::format(std::locale(), L"{:L}", -50), L"-50"); } +TEST(std_test_xchar, format_bitset) { + auto bs = std::bitset<6>(42); + EXPECT_EQ(fmt::format(L"{}", bs), L"101010"); + EXPECT_EQ(fmt::format(L"{:0>8}", bs), L"00101010"); + EXPECT_EQ(fmt::format(L"{:-^12}", bs), L"---101010---"); +} + +TEST(std_test_xchar, complex) { + auto s = fmt::format(L"{}", std::complex(1, 2)); + EXPECT_EQ(s, L"(1+2i)"); + EXPECT_EQ(fmt::format(L"{:.2f}", std::complex(1, 2)), + L"(1.00+2.00i)"); + EXPECT_EQ(fmt::format(L"{:8}", std::complex(1, 2)), L"(1+2i) "); + EXPECT_EQ(fmt::format(L"{:-<8}", std::complex(1, 2)), L"(1+2i)--"); +} + TEST(std_test_xchar, optional) { # ifdef __cpp_lib_optional EXPECT_EQ(fmt::format(L"{}", std::optional{L'C'}), L"optional(\'C\')"); diff --git a/vendor.yaml b/vendor.yaml index c20b37fde6..a1425c2e6a 100644 --- a/vendor.yaml +++ b/vendor.yaml @@ -26,7 +26,7 @@ third-party/sqlite3: release: sqlite-amalgamation-3420000 url: "https://www.sqlite.org/download.html" third-party/fmt: - git: https://github.com/fmtlib/fmt/tree/10.2.1 + git: https://github.com/fmtlib/fmt/tree/11.1.4 third-party/SDL: git: https://github.com/libsdl-org/SDL/commit/dc13a6ae95fda976e6719fe55be7f4baa877cd2b third-party/imgui: