Codebase list blockattack / ce007f1
New upstream version 2.8.0 Markus Koschany 1 year, 7 months ago
200 changed file(s) with 0 addition(s) and 86184 deletion(s). Raw diff Collapse all Expand all
+0
-37
source/misc/embedded_libs/fmt-8.1.1/.gitignore less more
0 .vscode/
1 .vs/
2
3 *.iml
4 .idea/
5 .externalNativeBuild/
6 .gradle/
7 gradle/
8 gradlew*
9 local.properties
10 build/
11 support/.cxx
12
13 bin/
14 /_CPack_Packages
15 /CMakeScripts
16 /doc/doxyxml
17 /doc/html
18 /doc/node_modules
19 virtualenv
20 /Testing
21 /install_manifest.txt
22 *~
23 *.a
24 *.so*
25 *.xcodeproj
26 *.zip
27 cmake_install.cmake
28 CPack*.cmake
29 fmt-*.cmake
30 CTestTestfile.cmake
31 CMakeCache.txt
32 CMakeFiles
33 FMT.build
34 Makefile
35 run-msbuild.bat
36 fmt.pc
+0
-415
source/misc/embedded_libs/fmt-8.1.1/CMakeLists.txt less more
0 cmake_minimum_required(VERSION 3.1...3.18)
1
2 # Fallback for using newer policies on CMake <3.12.
3 if(${CMAKE_VERSION} VERSION_LESS 3.12)
4 cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
5 endif()
6
7 # Determine if fmt is built as a subproject (using add_subdirectory)
8 # or if it is the master project.
9 if (NOT DEFINED FMT_MASTER_PROJECT)
10 set(FMT_MASTER_PROJECT OFF)
11 if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
12 set(FMT_MASTER_PROJECT ON)
13 message(STATUS "CMake version: ${CMAKE_VERSION}")
14 endif ()
15 endif ()
16
17 # Joins arguments and places the results in ${result_var}.
18 function(join result_var)
19 set(result "")
20 foreach (arg ${ARGN})
21 set(result "${result}${arg}")
22 endforeach ()
23 set(${result_var} "${result}" PARENT_SCOPE)
24 endfunction()
25
26 function(enable_module target)
27 if (MSVC)
28 set(BMI ${CMAKE_CURRENT_BINARY_DIR}/${target}.ifc)
29 target_compile_options(${target}
30 PRIVATE /interface /ifcOutput ${BMI}
31 INTERFACE /reference fmt=${BMI})
32 endif ()
33 set_target_properties(${target} PROPERTIES ADDITIONAL_CLEAN_FILES ${BMI})
34 set_source_files_properties(${BMI} PROPERTIES GENERATED ON)
35 endfunction()
36
37 include(CMakeParseArguments)
38
39 # Sets a cache variable with a docstring joined from multiple arguments:
40 # set(<variable> <value>... CACHE <type> <docstring>...)
41 # This allows splitting a long docstring for readability.
42 function(set_verbose)
43 # cmake_parse_arguments is broken in CMake 3.4 (cannot parse CACHE) so use
44 # list instead.
45 list(GET ARGN 0 var)
46 list(REMOVE_AT ARGN 0)
47 list(GET ARGN 0 val)
48 list(REMOVE_AT ARGN 0)
49 list(REMOVE_AT ARGN 0)
50 list(GET ARGN 0 type)
51 list(REMOVE_AT ARGN 0)
52 join(doc ${ARGN})
53 set(${var} ${val} CACHE ${type} ${doc})
54 endfunction()
55
56 # Set the default CMAKE_BUILD_TYPE to Release.
57 # This should be done before the project command since the latter can set
58 # CMAKE_BUILD_TYPE itself (it does so for nmake).
59 if (FMT_MASTER_PROJECT AND NOT CMAKE_BUILD_TYPE)
60 set_verbose(CMAKE_BUILD_TYPE Release CACHE STRING
61 "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or "
62 "CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.")
63 endif ()
64
65 project(FMT CXX)
66 include(GNUInstallDirs)
67 set_verbose(FMT_INC_DIR ${CMAKE_INSTALL_INCLUDEDIR} CACHE STRING
68 "Installation directory for include files, a relative path that "
69 "will be joined with ${CMAKE_INSTALL_PREFIX} or an absolute path.")
70
71 option(FMT_PEDANTIC "Enable extra warnings and expensive tests." OFF)
72 option(FMT_WERROR "Halt the compilation with an error on compiler warnings."
73 OFF)
74
75 # Options that control generation of various targets.
76 option(FMT_DOC "Generate the doc target." ${FMT_MASTER_PROJECT})
77 option(FMT_INSTALL "Generate the install target." ${FMT_MASTER_PROJECT})
78 option(FMT_TEST "Generate the test target." ${FMT_MASTER_PROJECT})
79 option(FMT_FUZZ "Generate the fuzz target." OFF)
80 option(FMT_CUDA_TEST "Generate the cuda-test target." OFF)
81 option(FMT_OS "Include core requiring OS (Windows/Posix) " ON)
82 option(FMT_MODULE "Build a module instead of a traditional library." OFF)
83 option(FMT_SYSTEM_HEADERS "Expose headers with marking them as system." OFF)
84
85 set(FMT_CAN_MODULE OFF)
86 if (CMAKE_CXX_STANDARD GREATER 17 AND
87 # msvc 16.10-pre4
88 MSVC AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.29.30035)
89 set(FMT_CAN_MODULE OFF)
90 endif ()
91 if (NOT FMT_CAN_MODULE)
92 set(FMT_MODULE OFF)
93 message(STATUS "Module support is disabled.")
94 endif ()
95 if (FMT_TEST AND FMT_MODULE)
96 # The tests require {fmt} to be compiled as traditional library
97 message(STATUS "Testing is incompatible with build mode 'module'.")
98 endif ()
99 set(FMT_SYSTEM_HEADERS_ATTRIBUTE "")
100 if (FMT_SYSTEM_HEADERS)
101 set(FMT_SYSTEM_HEADERS_ATTRIBUTE SYSTEM)
102 endif ()
103
104 # Get version from core.h
105 file(READ include/fmt/core.h core_h)
106 if (NOT core_h MATCHES "FMT_VERSION ([0-9]+)([0-9][0-9])([0-9][0-9])")
107 message(FATAL_ERROR "Cannot get FMT_VERSION from core.h.")
108 endif ()
109 # Use math to skip leading zeros if any.
110 math(EXPR CPACK_PACKAGE_VERSION_MAJOR ${CMAKE_MATCH_1})
111 math(EXPR CPACK_PACKAGE_VERSION_MINOR ${CMAKE_MATCH_2})
112 math(EXPR CPACK_PACKAGE_VERSION_PATCH ${CMAKE_MATCH_3})
113 join(FMT_VERSION ${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.
114 ${CPACK_PACKAGE_VERSION_PATCH})
115 message(STATUS "Version: ${FMT_VERSION}")
116
117 message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
118
119 if (NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY)
120 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
121 endif ()
122
123 set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
124 "${CMAKE_CURRENT_SOURCE_DIR}/support/cmake")
125
126 include(cxx14)
127 include(CheckCXXCompilerFlag)
128 include(JoinPaths)
129
130 list(FIND CMAKE_CXX_COMPILE_FEATURES "cxx_variadic_templates" index)
131 if (${index} GREATER -1)
132 # Use cxx_variadic_templates instead of more appropriate cxx_std_11 for
133 # compatibility with older CMake versions.
134 set(FMT_REQUIRED_FEATURES cxx_variadic_templates)
135 endif ()
136 message(STATUS "Required features: ${FMT_REQUIRED_FEATURES}")
137
138 if (FMT_MASTER_PROJECT AND NOT DEFINED CMAKE_CXX_VISIBILITY_PRESET)
139 set_verbose(CMAKE_CXX_VISIBILITY_PRESET hidden CACHE STRING
140 "Preset for the export of private symbols")
141 set_property(CACHE CMAKE_CXX_VISIBILITY_PRESET PROPERTY STRINGS
142 hidden default)
143 endif ()
144
145 if (FMT_MASTER_PROJECT AND NOT DEFINED CMAKE_VISIBILITY_INLINES_HIDDEN)
146 set_verbose(CMAKE_VISIBILITY_INLINES_HIDDEN ON CACHE BOOL
147 "Whether to add a compile flag to hide symbols of inline functions")
148 endif ()
149
150 if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
151 set(PEDANTIC_COMPILE_FLAGS -pedantic-errors -Wall -Wextra -pedantic
152 -Wold-style-cast -Wundef
153 -Wredundant-decls -Wwrite-strings -Wpointer-arith
154 -Wcast-qual -Wformat=2 -Wmissing-include-dirs
155 -Wcast-align
156 -Wctor-dtor-privacy -Wdisabled-optimization
157 -Winvalid-pch -Woverloaded-virtual
158 -Wconversion -Wundef
159 -Wno-ctor-dtor-privacy -Wno-format-nonliteral)
160 if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.6)
161 set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS}
162 -Wno-dangling-else -Wno-unused-local-typedefs)
163 endif ()
164 if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)
165 set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wdouble-promotion
166 -Wtrampolines -Wzero-as-null-pointer-constant -Wuseless-cast
167 -Wvector-operation-performance -Wsized-deallocation -Wshadow)
168 endif ()
169 if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.0)
170 set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wshift-overflow=2
171 -Wnull-dereference -Wduplicated-cond)
172 endif ()
173 set(WERROR_FLAG -Werror)
174 endif ()
175
176 if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
177 set(PEDANTIC_COMPILE_FLAGS -Wall -Wextra -pedantic -Wconversion -Wundef
178 -Wdeprecated -Wweak-vtables -Wshadow
179 -Wno-gnu-zero-variadic-macro-arguments)
180 check_cxx_compiler_flag(-Wzero-as-null-pointer-constant HAS_NULLPTR_WARNING)
181 if (HAS_NULLPTR_WARNING)
182 set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS}
183 -Wzero-as-null-pointer-constant)
184 endif ()
185 set(WERROR_FLAG -Werror)
186 endif ()
187
188 if (MSVC)
189 set(PEDANTIC_COMPILE_FLAGS /W3)
190 set(WERROR_FLAG /WX)
191 endif ()
192
193 if (FMT_MASTER_PROJECT AND CMAKE_GENERATOR MATCHES "Visual Studio")
194 # If Microsoft SDK is installed create script run-msbuild.bat that
195 # calls SetEnv.cmd to set up build environment and runs msbuild.
196 # It is useful when building Visual Studio projects with the SDK
197 # toolchain rather than Visual Studio.
198 include(FindSetEnv)
199 if (WINSDK_SETENV)
200 set(MSBUILD_SETUP "call \"${WINSDK_SETENV}\"")
201 endif ()
202 # Set FrameworkPathOverride to get rid of MSB3644 warnings.
203 join(netfxpath
204 "C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\"
205 ".NETFramework\\v4.0")
206 file(WRITE run-msbuild.bat "
207 ${MSBUILD_SETUP}
208 ${CMAKE_MAKE_PROGRAM} -p:FrameworkPathOverride=\"${netfxpath}\" %*")
209 endif ()
210
211 set(strtod_l_headers stdlib.h)
212 if (APPLE)
213 set(strtod_l_headers ${strtod_l_headers} xlocale.h)
214 endif ()
215
216 include(CheckSymbolExists)
217 if (WIN32)
218 check_symbol_exists(_strtod_l "${strtod_l_headers}" HAVE_STRTOD_L)
219 else ()
220 check_symbol_exists(strtod_l "${strtod_l_headers}" HAVE_STRTOD_L)
221 endif ()
222
223 function(add_headers VAR)
224 set(headers ${${VAR}})
225 foreach (header ${ARGN})
226 set(headers ${headers} include/fmt/${header})
227 endforeach()
228 set(${VAR} ${headers} PARENT_SCOPE)
229 endfunction()
230
231 # Define the fmt library, its includes and the needed defines.
232 add_headers(FMT_HEADERS args.h chrono.h color.h compile.h core.h format.h
233 format-inl.h locale.h os.h ostream.h printf.h ranges.h
234 xchar.h)
235 if (FMT_MODULE)
236 set(FMT_SOURCES src/fmt.cc)
237 elseif (FMT_OS)
238 set(FMT_SOURCES src/format.cc src/os.cc)
239 else()
240 set(FMT_SOURCES src/format.cc)
241 endif ()
242
243 add_library(fmt ${FMT_SOURCES} ${FMT_HEADERS} README.rst ChangeLog.rst)
244 add_library(fmt::fmt ALIAS fmt)
245
246 if (HAVE_STRTOD_L)
247 target_compile_definitions(fmt PUBLIC FMT_LOCALE)
248 endif ()
249
250 if (MINGW)
251 check_cxx_compiler_flag("-Wa,-mbig-obj" FMT_HAS_MBIG_OBJ)
252 if (${FMT_HAS_MBIG_OBJ})
253 target_compile_options(fmt PUBLIC "-Wa,-mbig-obj")
254 endif()
255 endif ()
256
257 if (FMT_WERROR)
258 target_compile_options(fmt PRIVATE ${WERROR_FLAG})
259 endif ()
260 if (FMT_PEDANTIC)
261 target_compile_options(fmt PRIVATE ${PEDANTIC_COMPILE_FLAGS})
262 endif ()
263 if (FMT_MODULE)
264 enable_module(fmt)
265 endif ()
266
267 target_compile_features(fmt INTERFACE ${FMT_REQUIRED_FEATURES})
268
269 target_include_directories(fmt ${FMT_SYSTEM_HEADERS_ATTRIBUTE} PUBLIC
270 $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
271 $<INSTALL_INTERFACE:${FMT_INC_DIR}>)
272
273 set(FMT_DEBUG_POSTFIX d CACHE STRING "Debug library postfix.")
274
275 set_target_properties(fmt PROPERTIES
276 VERSION ${FMT_VERSION} SOVERSION ${CPACK_PACKAGE_VERSION_MAJOR}
277 DEBUG_POSTFIX "${FMT_DEBUG_POSTFIX}")
278
279 # Set FMT_LIB_NAME for pkg-config fmt.pc. We cannot use the OUTPUT_NAME target
280 # property because it's not set by default.
281 set(FMT_LIB_NAME fmt)
282 if (CMAKE_BUILD_TYPE STREQUAL "Debug")
283 set(FMT_LIB_NAME ${FMT_LIB_NAME}${FMT_DEBUG_POSTFIX})
284 endif ()
285
286 if (BUILD_SHARED_LIBS)
287 if (UNIX AND NOT APPLE AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "SunOS" AND
288 NOT EMSCRIPTEN)
289 # Fix rpmlint warning:
290 # unused-direct-shlib-dependency /usr/lib/libformat.so.1.1.0 /lib/libm.so.6.
291 target_link_libraries(fmt -Wl,--as-needed)
292 endif ()
293 target_compile_definitions(fmt PRIVATE FMT_EXPORT INTERFACE FMT_SHARED)
294 endif ()
295 if (FMT_SAFE_DURATION_CAST)
296 target_compile_definitions(fmt PUBLIC FMT_SAFE_DURATION_CAST)
297 endif()
298
299 add_library(fmt-header-only INTERFACE)
300 add_library(fmt::fmt-header-only ALIAS fmt-header-only)
301
302 target_compile_definitions(fmt-header-only INTERFACE FMT_HEADER_ONLY=1)
303 target_compile_features(fmt-header-only INTERFACE ${FMT_REQUIRED_FEATURES})
304
305 target_include_directories(fmt-header-only ${FMT_SYSTEM_HEADERS_ATTRIBUTE} INTERFACE
306 $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
307 $<INSTALL_INTERFACE:${FMT_INC_DIR}>)
308
309 # Install targets.
310 if (FMT_INSTALL)
311 include(CMakePackageConfigHelpers)
312 set_verbose(FMT_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/fmt CACHE STRING
313 "Installation directory for cmake files, a relative path that "
314 "will be joined with ${CMAKE_INSTALL_PREFIX} or an absolute "
315 "path.")
316 set(version_config ${PROJECT_BINARY_DIR}/fmt-config-version.cmake)
317 set(project_config ${PROJECT_BINARY_DIR}/fmt-config.cmake)
318 set(pkgconfig ${PROJECT_BINARY_DIR}/fmt.pc)
319 set(targets_export_name fmt-targets)
320
321 set_verbose(FMT_LIB_DIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING
322 "Installation directory for libraries, a relative path that "
323 "will be joined to ${CMAKE_INSTALL_PREFIX} or an absolute path.")
324
325 set_verbose(FMT_PKGCONFIG_DIR ${CMAKE_INSTALL_LIBDIR}/pkgconfig CACHE PATH
326 "Installation directory for pkgconfig (.pc) files, a relative "
327 "path that will be joined with ${CMAKE_INSTALL_PREFIX} or an "
328 "absolute path.")
329
330 # Generate the version, config and target files into the build directory.
331 write_basic_package_version_file(
332 ${version_config}
333 VERSION ${FMT_VERSION}
334 COMPATIBILITY AnyNewerVersion)
335
336 join_paths(libdir_for_pc_file "\${exec_prefix}" "${FMT_LIB_DIR}")
337 join_paths(includedir_for_pc_file "\${prefix}" "${FMT_INC_DIR}")
338
339 configure_file(
340 "${PROJECT_SOURCE_DIR}/support/cmake/fmt.pc.in"
341 "${pkgconfig}"
342 @ONLY)
343 configure_package_config_file(
344 ${PROJECT_SOURCE_DIR}/support/cmake/fmt-config.cmake.in
345 ${project_config}
346 INSTALL_DESTINATION ${FMT_CMAKE_DIR})
347
348 set(INSTALL_TARGETS fmt fmt-header-only)
349
350 # Install the library and headers.
351 install(TARGETS ${INSTALL_TARGETS} EXPORT ${targets_export_name}
352 LIBRARY DESTINATION ${FMT_LIB_DIR}
353 ARCHIVE DESTINATION ${FMT_LIB_DIR}
354 RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
355
356 # Use a namespace because CMake provides better diagnostics for namespaced
357 # imported targets.
358 export(TARGETS ${INSTALL_TARGETS} NAMESPACE fmt::
359 FILE ${PROJECT_BINARY_DIR}/${targets_export_name}.cmake)
360
361 # Install version, config and target files.
362 install(
363 FILES ${project_config} ${version_config}
364 DESTINATION ${FMT_CMAKE_DIR})
365 install(EXPORT ${targets_export_name} DESTINATION ${FMT_CMAKE_DIR}
366 NAMESPACE fmt::)
367
368 install(FILES $<TARGET_PDB_FILE:${INSTALL_TARGETS}>
369 DESTINATION ${FMT_LIB_DIR} OPTIONAL)
370 install(FILES ${FMT_HEADERS} DESTINATION "${FMT_INC_DIR}/fmt")
371 install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}")
372 endif ()
373
374 if (FMT_DOC)
375 add_subdirectory(doc)
376 endif ()
377
378 if (FMT_TEST)
379 enable_testing()
380 add_subdirectory(test)
381 endif ()
382
383 # Control fuzzing independent of the unit tests.
384 if (FMT_FUZZ)
385 add_subdirectory(test/fuzzing)
386
387 # The FMT_FUZZ macro is used to prevent resource exhaustion in fuzzing
388 # mode and make fuzzing practically possible. It is similar to
389 # FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION but uses a different name to
390 # avoid interfering with fuzzing of projects that use {fmt}.
391 # See also https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode.
392 target_compile_definitions(fmt PUBLIC FMT_FUZZ)
393 endif ()
394
395 set(gitignore ${PROJECT_SOURCE_DIR}/.gitignore)
396 if (FMT_MASTER_PROJECT AND EXISTS ${gitignore})
397 # Get the list of ignored files from .gitignore.
398 file (STRINGS ${gitignore} lines)
399 list(REMOVE_ITEM lines /doc/html)
400 foreach (line ${lines})
401 string(REPLACE "." "[.]" line "${line}")
402 string(REPLACE "*" ".*" line "${line}")
403 set(ignored_files ${ignored_files} "${line}$" "${line}/")
404 endforeach ()
405 set(ignored_files ${ignored_files}
406 /.git /breathe /format-benchmark sphinx/ .buildinfo .doctrees)
407
408 set(CPACK_SOURCE_GENERATOR ZIP)
409 set(CPACK_SOURCE_IGNORE_FILES ${ignored_files})
410 set(CPACK_SOURCE_PACKAGE_FILE_NAME fmt-${FMT_VERSION})
411 set(CPACK_PACKAGE_NAME fmt)
412 set(CPACK_RESOURCE_FILE_README ${PROJECT_SOURCE_DIR}/README.rst)
413 include(CPack)
414 endif ()
+0
-20
source/misc/embedded_libs/fmt-8.1.1/CONTRIBUTING.md less more
0 Contributing to {fmt}
1 =====================
2
3 By submitting a pull request or a patch, you represent that you have the right
4 to license your contribution to the {fmt} project owners and the community,
5 agree that your contributions are licensed under the {fmt} license, and agree
6 to future changes to the licensing.
7
8 All C++ code must adhere to [Google C++ Style Guide](
9 https://google.github.io/styleguide/cppguide.html) with the following
10 exceptions:
11
12 * Exceptions are permitted
13 * snake_case should be used instead of UpperCamelCase for function and type
14 names
15
16 All documentation must adhere to the [Google Developer Documentation Style
17 Guide](https://developers.google.com/style).
18
19 Thanks for contributing!
+0
-4738
source/misc/embedded_libs/fmt-8.1.1/ChangeLog.rst less more
0 8.1.1 - 2022-01-06
1 ------------------
2
3 * Restored ABI compatibility with version 8.0.x
4 (`#2695 <https://github.com/fmtlib/fmt/issues/2695>`_,
5 `#2696 <https://github.com/fmtlib/fmt/pull/2696>`_).
6 Thanks `@saraedum (Julian Rüth) <https://github.com/saraedum>`_.
7
8 * Fixed chorno formatting on big endian systems
9 (`#2698 <https://github.com/fmtlib/fmt/issues/2698>`_,
10 `#2699 <https://github.com/fmtlib/fmt/pull/2699>`_).
11 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_ and
12 `@xvitaly (Vitaly Zaitsev) <https://github.com/xvitaly>`_.
13
14 * Fixed a linkage error with mingw
15 (`#2691 <https://github.com/fmtlib/fmt/issues/2691>`_,
16 `#2692 <https://github.com/fmtlib/fmt/pull/2692>`_).
17 Thanks `@rbberger (Richard Berger) <https://github.com/rbberger>`_.
18
19 8.1.0 - 2022-01-02
20 ------------------
21
22 * Optimized chrono formatting
23 (`#2500 <https://github.com/fmtlib/fmt/pull/2500>`_,
24 `#2537 <https://github.com/fmtlib/fmt/pull/2537>`_,
25 `#2541 <https://github.com/fmtlib/fmt/issues/2541>`_,
26 `#2544 <https://github.com/fmtlib/fmt/pull/2544>`_,
27 `#2550 <https://github.com/fmtlib/fmt/pull/2550>`_,
28 `#2551 <https://github.com/fmtlib/fmt/pull/2551>`_,
29 `#2576 <https://github.com/fmtlib/fmt/pull/2576>`_,
30 `#2577 <https://github.com/fmtlib/fmt/issues/2577>`_,
31 `#2586 <https://github.com/fmtlib/fmt/pull/2586>`_,
32 `#2591 <https://github.com/fmtlib/fmt/pull/2591>`_,
33 `#2594 <https://github.com/fmtlib/fmt/pull/2594>`_,
34 `#2602 <https://github.com/fmtlib/fmt/pull/2602>`_,
35 `#2617 <https://github.com/fmtlib/fmt/pull/2617>`_,
36 `#2628 <https://github.com/fmtlib/fmt/issues/2628>`_,
37 `#2633 <https://github.com/fmtlib/fmt/pull/2633>`_,
38 `#2670 <https://github.com/fmtlib/fmt/issues/2670>`_,
39 `#2671 <https://github.com/fmtlib/fmt/pull/2671>`_).
40
41 Processing of some specifiers such as ``%z`` and ``%Y`` is now up to 10-20
42 times faster, for example on GCC 11 with libstdc++::
43
44 ----------------------------------------------------------------------------
45 Benchmark Before After
46 ----------------------------------------------------------------------------
47 FMTFormatter_z 261 ns 26.3 ns
48 FMTFormatterCompile_z 246 ns 11.6 ns
49 FMTFormatter_Y 263 ns 26.1 ns
50 FMTFormatterCompile_Y 244 ns 10.5 ns
51 ----------------------------------------------------------------------------
52
53 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_ and
54 `@toughengineer (Pavel Novikov) <https://github.com/toughengineer>`_.
55
56 * Implemented subsecond formatting for chrono durations
57 (`#2623 <https://github.com/fmtlib/fmt/pull/2623>`_).
58 For example (`godbolt <https://godbolt.org/z/es7vWTETe>`__):
59
60 .. code:: c++
61
62 #include <fmt/chrono.h>
63
64 int main() {
65 fmt::print("{:%S}", std::chrono::milliseconds(1234));
66 }
67
68 prints "01.234".
69
70 Thanks `@matrackif <https://github.com/matrackif>`_.
71
72 * Fixed handling of precision 0 when formatting chrono durations
73 (`#2587 <https://github.com/fmtlib/fmt/issues/2587>`_,
74 `#2588 <https://github.com/fmtlib/fmt/pull/2588>`_).
75 Thanks `@lukester1975 <https://github.com/lukester1975>`_.
76
77 * Fixed an overflow on invalid inputs in the ``tm`` formatter
78 (`#2564 <https://github.com/fmtlib/fmt/pull/2564>`_).
79 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
80
81 * Added ``fmt::group_digits`` that formats integers with a non-localized digit
82 separator (comma) for groups of three digits.
83 For example (`godbolt <https://godbolt.org/z/TxGxG9Poq>`__):
84
85 .. code:: c++
86
87 #include <fmt/format.h>
88
89 int main() {
90 fmt::print("{} dollars", fmt::group_digits(1000000));
91 }
92
93 prints "1,000,000 dollars".
94
95 * Added support for faint, conceal, reverse and blink text styles
96 (`#2394 <https://github.com/fmtlib/fmt/pull/2394>`_):
97
98 https://user-images.githubusercontent.com/576385/147710227-c68f5317-f8fa-42c3-9123-7c4ba3c398cb.mp4
99
100 Thanks `@benit8 (Benoît Lormeau) <https://github.com/benit8>`_ and
101 `@data-man (Dmitry Atamanov) <https://github.com/data-man>`_.
102
103 * Added experimental support for compile-time floating point formatting
104 (`#2426 <https://github.com/fmtlib/fmt/pull/2426>`_,
105 `#2470 <https://github.com/fmtlib/fmt/pull/2470>`_).
106 It is currently limited to the header-only mode.
107 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
108
109 * Added UDL-based named argument support to compile-time format string checks
110 (`#2640 <https://github.com/fmtlib/fmt/issues/2640>`_,
111 `#2649 <https://github.com/fmtlib/fmt/pull/2649>`_).
112 For example (`godbolt <https://godbolt.org/z/ohGbbvonv>`__):
113
114 .. code:: c++
115
116 #include <fmt/format.h>
117
118 int main() {
119 using namespace fmt::literals;
120 fmt::print("{answer:s}", "answer"_a=42);
121 }
122
123 gives a compile-time error on compilers with C++20 ``consteval`` and non-type
124 template parameter support (gcc 10+) because ``s`` is not a valid format
125 specifier for an integer.
126
127 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
128
129 * Implemented escaping of string range elements.
130 For example (`godbolt <https://godbolt.org/z/rKvM1vKf3>`__):
131
132 .. code:: c++
133
134 #include <fmt/ranges.h>
135 #include <vector>
136
137 int main() {
138 fmt::print("{}", std::vector<std::string>{"\naan"});
139 }
140
141 is now printed as::
142
143 ["\naan"]
144
145 instead of::
146
147 ["
148 aan"]
149
150 * Switched to JSON-like representation of maps and sets for consistency with
151 Python's ``str.format``.
152 For example (`godbolt <https://godbolt.org/z/seKjoY9W5>`__):
153
154 .. code:: c++
155
156 #include <fmt/ranges.h>
157 #include <map>
158
159 int main() {
160 fmt::print("{}", std::map<std::string, int>{{"answer", 42}});
161 }
162
163 is now printed as::
164
165 {"answer": 42}
166
167 * Extended ``fmt::join`` to support C++20-only ranges
168 (`#2549 <https://github.com/fmtlib/fmt/pull/2549>`_).
169 Thanks `@BRevzin (Barry Revzin) <https://github.com/BRevzin>`_.
170
171 * Optimized handling of non-const-iterable ranges and implemented initial
172 support for non-const-formattable types.
173
174 * Disabled implicit conversions of scoped enums to integers that was
175 accidentally introduced in earlier versions
176 (`#1841 <https://github.com/fmtlib/fmt/pull/1841>`_).
177
178 * Deprecated implicit conversion of ``[const] signed char*`` and
179 ``[const] unsigned char*`` to C strings.
180
181 * Deprecated ``_format``, a legacy UDL-based format API
182 (`#2646 <https://github.com/fmtlib/fmt/pull/2646>`_).
183 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
184
185 * Marked ``format``, ``formatted_size`` and ``to_string`` as ``[[nodiscard]]``
186 (`#2612 <https://github.com/fmtlib/fmt/pull/2612>`_).
187 `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_.
188
189 * Added missing diagnostic when trying to format function and member pointers
190 as well as objects convertible to pointers which is explicitly disallowed
191 (`#2598 <https://github.com/fmtlib/fmt/issues/2598>`_,
192 `#2609 <https://github.com/fmtlib/fmt/pull/2609>`_,
193 `#2610 <https://github.com/fmtlib/fmt/pull/2610>`_).
194 Thanks `@AlexGuteniev (Alex Guteniev) <https://github.com/AlexGuteniev>`_.
195
196 * Optimized writing to a contiguous buffer with ``format_to_n``
197 (`#2489 <https://github.com/fmtlib/fmt/pull/2489>`_).
198 Thanks `@Roman-Koshelev <https://github.com/Roman-Koshelev>`_.
199
200 * Optimized writing to non-``char`` buffers
201 (`#2477 <https://github.com/fmtlib/fmt/pull/2477>`_).
202 Thanks `@Roman-Koshelev <https://github.com/Roman-Koshelev>`_.
203
204 * Decimal point is now localized when using the ``L`` specifier.
205
206 * Improved floating point formatter implementation
207 (`#2498 <https://github.com/fmtlib/fmt/pull/2498>`_,
208 `#2499 <https://github.com/fmtlib/fmt/pull/2499>`_).
209 Thanks `@Roman-Koshelev <https://github.com/Roman-Koshelev>`_.
210
211 * Fixed handling of very large precision in fixed format
212 (`#2616 <https://github.com/fmtlib/fmt/pull/2616>`_).
213
214 * Made a table of cached powers used in FP formatting static
215 (`#2509 <https://github.com/fmtlib/fmt/pull/2509>`_).
216 Thanks `@jk-jeon (Junekey Jeon) <https://github.com/jk-jeon>`_.
217
218 * Resolved a lookup ambiguity with C++20 format-related functions due to ADL
219 (`#2639 <https://github.com/fmtlib/fmt/issues/2639>`_,
220 `#2641 <https://github.com/fmtlib/fmt/pull/2641>`_).
221 Thanks `@mkurdej (Marek Kurdej) <https://github.com/mkurdej>`_.
222
223 * Removed unnecessary inline namespace qualification
224 (`#2642 <https://github.com/fmtlib/fmt/issues/2642>`_,
225 `#2643 <https://github.com/fmtlib/fmt/pull/2643>`_).
226 Thanks `@mkurdej (Marek Kurdej) <https://github.com/mkurdej>`_.
227
228 * Implemented argument forwarding in ``format_to_n``
229 (`#2462 <https://github.com/fmtlib/fmt/issues/2462>`_,
230 `#2463 <https://github.com/fmtlib/fmt/pull/2463>`_).
231 Thanks `@owent (WenTao Ou) <https://github.com/owent>`_.
232
233 * Fixed handling of implicit conversions in ``fmt::to_string`` and format string
234 compilation (`#2565 <https://github.com/fmtlib/fmt/issues/2565>`_).
235
236 * Changed the default access mode of files created by ``fmt::output_file`` to
237 ``-rw-r--r--`` for consistency with ``fopen``
238 (`#2530 <https://github.com/fmtlib/fmt/issues/2530>`_).
239
240 * Make ``fmt::ostream::flush`` public
241 (`#2435 <https://github.com/fmtlib/fmt/issues/2435>`_).
242
243 * Improved C++14/17 attribute detection
244 (`#2615 <https://github.com/fmtlib/fmt/pull/2615>`_).
245 Thanks `@AlexGuteniev (Alex Guteniev) <https://github.com/AlexGuteniev>`_.
246
247 * Improved ``consteval`` detection for MSVC
248 (`#2559 <https://github.com/fmtlib/fmt/pull/2559>`_).
249 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
250
251 * Improved documentation
252 (`#2406 <https://github.com/fmtlib/fmt/issues/2406>`_,
253 `#2446 <https://github.com/fmtlib/fmt/pull/2446>`_,
254 `#2493 <https://github.com/fmtlib/fmt/issues/2493>`_,
255 `#2513 <https://github.com/fmtlib/fmt/issues/2513>`_,
256 `#2515 <https://github.com/fmtlib/fmt/pull/2515>`_,
257 `#2522 <https://github.com/fmtlib/fmt/issues/2522>`_,
258 `#2562 <https://github.com/fmtlib/fmt/pull/2562>`_,
259 `#2575 <https://github.com/fmtlib/fmt/pull/2575>`_,
260 `#2606 <https://github.com/fmtlib/fmt/pull/2606>`_,
261 `#2620 <https://github.com/fmtlib/fmt/pull/2620>`_,
262 `#2676 <https://github.com/fmtlib/fmt/issues/2676>`_).
263 Thanks `@sobolevn (Nikita Sobolev) <https://github.com/sobolevn>`_,
264 `@UnePierre (Max FERGER) <https://github.com/UnePierre>`_,
265 `@zhsj <https://github.com/zhsj>`_,
266 `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_,
267 `@ericcurtin (Eric Curtin) <https://github.com/ericcurtin>`_,
268 `@Lounarok <https://github.com/Lounarok>`_.
269
270 * Improved fuzzers and added a fuzzer for chrono timepoint formatting
271 (`#2461 <https://github.com/fmtlib/fmt/pull/2461>`_,
272 `#2469 <https://github.com/fmtlib/fmt/pull/2469>`_).
273 `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_,
274
275 * Added the ``FMT_SYSTEM_HEADERS`` CMake option setting which marks {fmt}'s
276 headers as system. It can be used to suppress warnings
277 (`#2644 <https://github.com/fmtlib/fmt/issues/2644>`_,
278 `#2651 <https://github.com/fmtlib/fmt/pull/2651>`_).
279 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
280
281 * Added the Bazel build system support
282 (`#2505 <https://github.com/fmtlib/fmt/pull/2505>`_,
283 `#2516 <https://github.com/fmtlib/fmt/pull/2516>`_).
284 Thanks `@Vertexwahn <https://github.com/Vertexwahn>`_.
285
286 * Improved build configuration and tests
287 (`#2437 <https://github.com/fmtlib/fmt/issues/2437>`_,
288 `#2558 <https://github.com/fmtlib/fmt/pull/2558>`_,
289 `#2648 <https://github.com/fmtlib/fmt/pull/2648>`_,
290 `#2650 <https://github.com/fmtlib/fmt/pull/2650>`_,
291 `#2663 <https://github.com/fmtlib/fmt/pull/2663>`_,
292 `#2677 <https://github.com/fmtlib/fmt/pull/2677>`_).
293 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
294 `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_,
295 `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
296
297 * Fixed various warnings and compilation issues
298 (`#2353 <https://github.com/fmtlib/fmt/pull/2353>`_,
299 `#2356 <https://github.com/fmtlib/fmt/pull/2356>`_,
300 `#2399 <https://github.com/fmtlib/fmt/pull/2399>`_,
301 `#2408 <https://github.com/fmtlib/fmt/issues/2408>`_,
302 `#2414 <https://github.com/fmtlib/fmt/pull/2414>`_,
303 `#2427 <https://github.com/fmtlib/fmt/pull/2427>`_,
304 `#2432 <https://github.com/fmtlib/fmt/pull/2432>`_,
305 `#2442 <https://github.com/fmtlib/fmt/pull/2442>`_,
306 `#2434 <https://github.com/fmtlib/fmt/pull/2434>`_,
307 `#2439 <https://github.com/fmtlib/fmt/issues/2439>`_,
308 `#2447 <https://github.com/fmtlib/fmt/pull/2447>`_,
309 `#2450 <https://github.com/fmtlib/fmt/pull/2450>`_,
310 `#2455 <https://github.com/fmtlib/fmt/issues/2455>`_,
311 `#2465 <https://github.com/fmtlib/fmt/issues/2465>`_,
312 `#2472 <https://github.com/fmtlib/fmt/issues/2472>`_,
313 `#2474 <https://github.com/fmtlib/fmt/issues/2474>`_,
314 `#2476 <https://github.com/fmtlib/fmt/pull/2476>`_,
315 `#2478 <https://github.com/fmtlib/fmt/issues/2478>`_,
316 `#2479 <https://github.com/fmtlib/fmt/issues/2479>`_,
317 `#2481 <https://github.com/fmtlib/fmt/issues/2481>`_,
318 `#2482 <https://github.com/fmtlib/fmt/pull/2482>`_,
319 `#2483 <https://github.com/fmtlib/fmt/pull/2483>`_,
320 `#2490 <https://github.com/fmtlib/fmt/issues/2490>`_,
321 `#2491 <https://github.com/fmtlib/fmt/pull/2491>`_,
322 `#2510 <https://github.com/fmtlib/fmt/pull/2510>`_,
323 `#2518 <https://github.com/fmtlib/fmt/pull/2518>`_,
324 `#2528 <https://github.com/fmtlib/fmt/issues/2528>`_,
325 `#2529 <https://github.com/fmtlib/fmt/pull/2529>`_,
326 `#2539 <https://github.com/fmtlib/fmt/pull/2539>`_,
327 `#2540 <https://github.com/fmtlib/fmt/issues/2540>`_,
328 `#2545 <https://github.com/fmtlib/fmt/pull/2545>`_,
329 `#2555 <https://github.com/fmtlib/fmt/pull/2555>`_,
330 `#2557 <https://github.com/fmtlib/fmt/issues/2557>`_,
331 `#2570 <https://github.com/fmtlib/fmt/issues/2570>`_,
332 `#2573 <https://github.com/fmtlib/fmt/pull/2573>`_,
333 `#2582 <https://github.com/fmtlib/fmt/pull/2582>`_,
334 `#2605 <https://github.com/fmtlib/fmt/issues/2605>`_,
335 `#2611 <https://github.com/fmtlib/fmt/pull/2611>`_,
336 `#2647 <https://github.com/fmtlib/fmt/pull/2647>`_,
337 `#2627 <https://github.com/fmtlib/fmt/issues/2627>`_,
338 `#2630 <https://github.com/fmtlib/fmt/pull/2630>`_,
339 `#2635 <https://github.com/fmtlib/fmt/issues/2635>`_,
340 `#2638 <https://github.com/fmtlib/fmt/issues/2638>`_,
341 `#2653 <https://github.com/fmtlib/fmt/issues/2653>`_,
342 `#2654 <https://github.com/fmtlib/fmt/issues/2654>`_,
343 `#2661 <https://github.com/fmtlib/fmt/issues/2661>`_,
344 `#2664 <https://github.com/fmtlib/fmt/pull/2664>`_,
345 `#2684 <https://github.com/fmtlib/fmt/pull/2684>`_).
346 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
347 `@mwinterb <https://github.com/mwinterb>`_,
348 `@cdacamar (Cameron DaCamara) <https://github.com/cdacamar>`_,
349 `@TrebledJ (Johnathan) <https://github.com/TrebledJ>`_,
350 `@bodomartin (brm) <https://github.com/bodomartin>`_,
351 `@cquammen (Cory Quammen) <https://github.com/cquammen>`_,
352 `@white238 (Chris White) <https://github.com/white238>`_,
353 `@mmarkeloff (Max) <https://github.com/mmarkeloff>`_,
354 `@palacaze (Pierre-Antoine Lacaze) <https://github.com/palacaze>`_,
355 `@jcelerier (Jean-Michaël Celerier) <https://github.com/jcelerier>`_,
356 `@mborn-adi (Mathias Born) <https://github.com/mborn-adi>`_,
357 `@BrukerJWD (Jonathan W) <https://github.com/BrukerJWD>`_,
358 `@spyridon97 (Spiros Tsalikis) <https://github.com/spyridon97>`_,
359 `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_,
360 `@oliverlee (Oliver Lee) <https://github.com/oliverlee>`_,
361 `@joshessman-llnl (Josh Essman) <https://github.com/joshessman-llnl>`_,
362 `@akohlmey (Axel Kohlmeyer) <https://github.com/akohlmey>`_,
363 `@timkalu <https://github.com/timkalu>`_,
364 `@olupton (Olli Lupton) <https://github.com/olupton>`_,
365 `@Acretock <https://github.com/Acretock>`_,
366 `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_,
367 `@andrewcorrigan (Andrew Corrigan) <https://github.com/andrewcorrigan>`_,
368 `@lucpelletier <https://github.com/lucpelletier>`_,
369 `@HazardyKnusperkeks (Björn Schäpers) <https://github.com/HazardyKnusperkeks>`_.
370
371 8.0.1 - 2021-07-02
372 ------------------
373
374 * Fixed the version number in the inline namespace
375 (`#2374 <https://github.com/fmtlib/fmt/issues/2374>`_).
376
377 * Added a missing presentation type check for ``std::string``
378 (`#2402 <https://github.com/fmtlib/fmt/issues/2402>`_).
379
380 * Fixed a linkage error when mixing code built with clang and gcc
381 (`#2377 <https://github.com/fmtlib/fmt/issues/2377>`_).
382
383 * Fixed documentation issues
384 (`#2396 <https://github.com/fmtlib/fmt/pull/2396>`_,
385 `#2403 <https://github.com/fmtlib/fmt/issues/2403>`_,
386 `#2406 <https://github.com/fmtlib/fmt/issues/2406>`_).
387 Thanks `@mkurdej (Marek Kurdej) <https://github.com/mkurdej>`_.
388
389 * Removed dead code in FP formatter (
390 `#2398 <https://github.com/fmtlib/fmt/pull/2398>`_).
391 Thanks `@javierhonduco (Javier Honduvilla Coto)
392 <https://github.com/javierhonduco>`_.
393
394 * Fixed various warnings and compilation issues
395 (`#2351 <https://github.com/fmtlib/fmt/issues/2351>`_,
396 `#2359 <https://github.com/fmtlib/fmt/issues/2359>`_,
397 `#2365 <https://github.com/fmtlib/fmt/pull/2365>`_,
398 `#2368 <https://github.com/fmtlib/fmt/issues/2368>`_,
399 `#2370 <https://github.com/fmtlib/fmt/pull/2370>`_,
400 `#2376 <https://github.com/fmtlib/fmt/pull/2376>`_,
401 `#2381 <https://github.com/fmtlib/fmt/pull/2381>`_,
402 `#2382 <https://github.com/fmtlib/fmt/pull/2382>`_,
403 `#2386 <https://github.com/fmtlib/fmt/issues/2386>`_,
404 `#2389 <https://github.com/fmtlib/fmt/pull/2389>`_,
405 `#2395 <https://github.com/fmtlib/fmt/pull/2395>`_,
406 `#2397 <https://github.com/fmtlib/fmt/pull/2397>`_,
407 `#2400 <https://github.com/fmtlib/fmt/issues/2400>`_,
408 `#2401 <https://github.com/fmtlib/fmt/issues/2401>`_,
409 `#2407 <https://github.com/fmtlib/fmt/pull/2407>`_).
410 Thanks `@zx2c4 (Jason A. Donenfeld) <https://github.com/zx2c4>`_,
411 `@AidanSun05 (Aidan Sun) <https://github.com/AidanSun05>`_,
412 `@mattiasljungstrom (Mattias Ljungström)
413 <https://github.com/mattiasljungstrom>`_,
414 `@joemmett (Jonathan Emmett) <https://github.com/joemmett>`_,
415 `@erengy (Eren Okka) <https://github.com/erengy>`_,
416 `@patlkli (Patrick Geltinger) <https://github.com/patlkli>`_,
417 `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
418 `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
419
420 8.0.0 - 2021-06-21
421 ------------------
422
423 * Enabled compile-time format string checks by default.
424 For example (`godbolt <https://godbolt.org/z/sMxcohGjz>`__):
425
426 .. code:: c++
427
428 #include <fmt/core.h>
429
430 int main() {
431 fmt::print("{:d}", "I am not a number");
432 }
433
434 gives a compile-time error on compilers with C++20 ``consteval`` support
435 (gcc 10+, clang 11+) because ``d`` is not a valid format specifier for a
436 string.
437
438 To pass a runtime string wrap it in ``fmt::runtime``:
439
440 .. code:: c++
441
442 fmt::print(fmt::runtime("{:d}"), "I am not a number");
443
444 * Added compile-time formatting
445 (`#2019 <https://github.com/fmtlib/fmt/pull/2019>`_,
446 `#2044 <https://github.com/fmtlib/fmt/pull/2044>`_,
447 `#2056 <https://github.com/fmtlib/fmt/pull/2056>`_,
448 `#2072 <https://github.com/fmtlib/fmt/pull/2072>`_,
449 `#2075 <https://github.com/fmtlib/fmt/pull/2075>`_,
450 `#2078 <https://github.com/fmtlib/fmt/issues/2078>`_,
451 `#2129 <https://github.com/fmtlib/fmt/pull/2129>`_,
452 `#2326 <https://github.com/fmtlib/fmt/pull/2326>`_).
453 For example (`godbolt <https://godbolt.org/z/Mxx9d89jM>`__):
454
455 .. code:: c++
456
457 #include <fmt/compile.h>
458
459 consteval auto compile_time_itoa(int value) -> std::array<char, 10> {
460 auto result = std::array<char, 10>();
461 fmt::format_to(result.data(), FMT_COMPILE("{}"), value);
462 return result;
463 }
464
465 constexpr auto answer = compile_time_itoa(42);
466
467 Most of the formatting functionality is available at compile time with a
468 notable exception of floating-point numbers and pointers.
469 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
470
471 * Optimized handling of format specifiers during format string compilation.
472 For example, hexadecimal formatting (``"{:x}"``) is now 3-7x faster than
473 before when using ``format_to`` with format string compilation and a
474 stack-allocated buffer (`#1944 <https://github.com/fmtlib/fmt/issues/1944>`_).
475
476 Before (7.1.3)::
477
478 ----------------------------------------------------------------------------
479 Benchmark Time CPU Iterations
480 ----------------------------------------------------------------------------
481 FMTCompileOld/0 15.5 ns 15.5 ns 43302898
482 FMTCompileOld/42 16.6 ns 16.6 ns 43278267
483 FMTCompileOld/273123 18.7 ns 18.6 ns 37035861
484 FMTCompileOld/9223372036854775807 19.4 ns 19.4 ns 35243000
485 ----------------------------------------------------------------------------
486
487 After (8.x)::
488
489 ----------------------------------------------------------------------------
490 Benchmark Time CPU Iterations
491 ----------------------------------------------------------------------------
492 FMTCompileNew/0 1.99 ns 1.99 ns 360523686
493 FMTCompileNew/42 2.33 ns 2.33 ns 279865664
494 FMTCompileNew/273123 3.72 ns 3.71 ns 190230315
495 FMTCompileNew/9223372036854775807 5.28 ns 5.26 ns 130711631
496 ----------------------------------------------------------------------------
497
498 It is even faster than ``std::to_chars`` from libc++ compiled with clang on
499 macOS::
500
501 ----------------------------------------------------------------------------
502 Benchmark Time CPU Iterations
503 ----------------------------------------------------------------------------
504 ToChars/0 4.42 ns 4.41 ns 160196630
505 ToChars/42 5.00 ns 4.98 ns 140735201
506 ToChars/273123 7.26 ns 7.24 ns 95784130
507 ToChars/9223372036854775807 8.77 ns 8.75 ns 75872534
508 ----------------------------------------------------------------------------
509
510 In other cases, especially involving ``std::string`` construction, the
511 speed up is usually lower because handling format specifiers takes a smaller
512 fraction of the total time.
513
514 * Added the ``_cf`` user-defined literal to represent a compiled format string.
515 It can be used instead of the ``FMT_COMPILE`` macro
516 (`#2043 <https://github.com/fmtlib/fmt/pull/2043>`_,
517 `#2242 <https://github.com/fmtlib/fmt/pull/2242>`_):
518
519 .. code:: c++
520
521 #include <fmt/compile.h>
522
523 using namespace fmt::literals;
524 auto s = fmt::format(FMT_COMPILE("{}"), 42); // 🙁 not modern
525 auto s = fmt::format("{}"_cf, 42); // 🙂 modern as hell
526
527 It requires compiler support for class types in non-type template parameters
528 (a C++20 feature) which is available in GCC 9.3+.
529 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
530
531 * Format string compilation now requires ``format`` functions of ``formatter``
532 specializations for user-defined types to be ``const``:
533
534 .. code:: c++
535
536 template <> struct fmt::formatter<my_type>: formatter<string_view> {
537 template <typename FormatContext>
538 auto format(my_type obj, FormatContext& ctx) const { // Note const here.
539 // ...
540 }
541 };
542
543 * Added UDL-based named argument support to format string compilation
544 (`#2243 <https://github.com/fmtlib/fmt/pull/2243>`_,
545 `#2281 <https://github.com/fmtlib/fmt/pull/2281>`_). For example:
546
547 .. code:: c++
548
549 #include <fmt/compile.h>
550
551 using namespace fmt::literals;
552 auto s = fmt::format(FMT_COMPILE("{answer}"), "answer"_a = 42);
553
554 Here the argument named "answer" is resolved at compile time with no
555 runtime overhead.
556 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
557
558 * Added format string compilation support to ``fmt::print``
559 (`#2280 <https://github.com/fmtlib/fmt/issues/2280>`_,
560 `#2304 <https://github.com/fmtlib/fmt/pull/2304>`_).
561 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
562
563 * Added initial support for compiling {fmt} as a C++20 module
564 (`#2235 <https://github.com/fmtlib/fmt/pull/2235>`_,
565 `#2240 <https://github.com/fmtlib/fmt/pull/2240>`_,
566 `#2260 <https://github.com/fmtlib/fmt/pull/2260>`_,
567 `#2282 <https://github.com/fmtlib/fmt/pull/2282>`_,
568 `#2283 <https://github.com/fmtlib/fmt/pull/2283>`_,
569 `#2288 <https://github.com/fmtlib/fmt/pull/2288>`_,
570 `#2298 <https://github.com/fmtlib/fmt/pull/2298>`_,
571 `#2306 <https://github.com/fmtlib/fmt/pull/2306>`_,
572 `#2307 <https://github.com/fmtlib/fmt/pull/2307>`_,
573 `#2309 <https://github.com/fmtlib/fmt/pull/2309>`_,
574 `#2318 <https://github.com/fmtlib/fmt/pull/2318>`_,
575 `#2324 <https://github.com/fmtlib/fmt/pull/2324>`_,
576 `#2332 <https://github.com/fmtlib/fmt/pull/2332>`_,
577 `#2340 <https://github.com/fmtlib/fmt/pull/2340>`_).
578 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
579
580 * Made symbols private by default reducing shared library size
581 (`#2301 <https://github.com/fmtlib/fmt/pull/2301>`_). For example there was
582 a ~15% reported reduction on one platform.
583 Thanks `@sergiud (Sergiu Deitsch) <https://github.com/sergiud>`_.
584
585 * Optimized includes making the result of preprocessing ``fmt/format.h``
586 ~20% smaller with libstdc++/C++20 and slightly improving build times
587 (`#1998 <https://github.com/fmtlib/fmt/issues/1998>`_).
588
589 * Added support of ranges with non-const ``begin`` / ``end``
590 (`#1953 <https://github.com/fmtlib/fmt/pull/1953>`_).
591 Thanks `@kitegi (sarah) <https://github.com/kitegi>`_.
592
593 * Added support of ``std::byte`` and other formattable types to ``fmt::join``
594 (`#1981 <https://github.com/fmtlib/fmt/issues/1981>`_,
595 `#2040 <https://github.com/fmtlib/fmt/issues/2040>`_,
596 `#2050 <https://github.com/fmtlib/fmt/pull/2050>`_,
597 `#2262 <https://github.com/fmtlib/fmt/issues/2262>`_). For example:
598
599 .. code:: c++
600
601 #include <fmt/format.h>
602 #include <cstddef>
603 #include <vector>
604
605 int main() {
606 auto bytes = std::vector{std::byte(4), std::byte(2)};
607 fmt::print("{}", fmt::join(bytes, ""));
608 }
609
610 prints "42".
611
612 Thanks `@kamibo (Camille Bordignon) <https://github.com/kamibo>`_.
613
614 * Implemented the default format for ``std::chrono::system_clock``
615 (`#2319 <https://github.com/fmtlib/fmt/issues/2319>`_,
616 `#2345 <https://github.com/fmtlib/fmt/pull/2345>`_). For example:
617
618 .. code:: c++
619
620 #include <fmt/chrono.h>
621
622 int main() {
623 fmt::print("{}", std::chrono::system_clock::now());
624 }
625
626 prints "2021-06-18 15:22:00" (the output depends on the current date and
627 time). Thanks `@sunmy2019 <https://github.com/sunmy2019>`_.
628
629 * Made more chrono specifiers locale independent by default. Use the ``'L'``
630 specifier to get localized formatting. For example:
631
632 .. code:: c++
633
634 #include <fmt/chrono.h>
635
636 int main() {
637 std::locale::global(std::locale("ru_RU.UTF-8"));
638 auto monday = std::chrono::weekday(1);
639 fmt::print("{}\n", monday); // prints "Mon"
640 fmt::print("{:L}\n", monday); // prints "пн"
641 }
642
643 * Improved locale handling in chrono formatting
644 (`#2337 <https://github.com/fmtlib/fmt/issues/2337>`_,
645 `#2349 <https://github.com/fmtlib/fmt/pull/2349>`_,
646 `#2350 <https://github.com/fmtlib/fmt/pull/2350>`_).
647 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
648
649 * Deprecated ``fmt/locale.h`` moving the formatting functions that take a
650 locale to ``fmt/format.h`` (``char``) and ``fmt/xchar`` (other overloads).
651 This doesn't introduce a dependency on ``<locale>`` so there is virtually no
652 compile time effect.
653
654 * Deprecated an undocumented ``format_to`` overload that takes
655 ``basic_memory_buffer``.
656
657 * Made parameter order in ``vformat_to`` consistent with ``format_to``
658 (`#2327 <https://github.com/fmtlib/fmt/issues/2327>`_).
659
660 * Added support for time points with arbitrary durations
661 (`#2208 <https://github.com/fmtlib/fmt/issues/2208>`_). For example:
662
663 .. code:: c++
664
665 #include <fmt/chrono.h>
666
667 int main() {
668 using tp = std::chrono::time_point<
669 std::chrono::system_clock, std::chrono::seconds>;
670 fmt::print("{:%S}", tp(std::chrono::seconds(42)));
671 }
672
673 prints "42".
674
675 * Formatting floating-point numbers no longer produces trailing zeros by default
676 for consistency with ``std::format``. For example:
677
678 .. code:: c++
679
680 #include <fmt/core.h>
681
682 int main() {
683 fmt::print("{0:.3}", 1.1);
684 }
685
686 prints "1.1". Use the ``'#'`` specifier to keep trailing zeros.
687
688 * Dropped a limit on the number of elements in a range and replaced ``{}`` with
689 ``[]`` as range delimiters for consistency with Python's ``str.format``.
690
691 * The ``'L'`` specifier for locale-specific numeric formatting can now be
692 combined with presentation specifiers as in ``std::format``. For example:
693
694 .. code:: c++
695
696 #include <fmt/core.h>
697 #include <locale>
698
699 int main() {
700 std::locale::global(std::locale("fr_FR.UTF-8"));
701 fmt::print("{0:.2Lf}", 0.42);
702 }
703
704 prints "0,42". The deprecated ``'n'`` specifier has been removed.
705
706 * Made the ``0`` specifier ignored for infinity and NaN
707 (`#2305 <https://github.com/fmtlib/fmt/issues/2305>`_,
708 `#2310 <https://github.com/fmtlib/fmt/pull/2310>`_).
709 Thanks `@Liedtke (Matthias Liedtke) <https://github.com/Liedtke>`_.
710
711 * Made the hexfloat formatting use the right alignment by default
712 (`#2308 <https://github.com/fmtlib/fmt/issues/2308>`_,
713 `#2317 <https://github.com/fmtlib/fmt/pull/2317>`_).
714 Thanks `@Liedtke (Matthias Liedtke) <https://github.com/Liedtke>`_.
715
716 * Removed the deprecated numeric alignment (``'='``). Use the ``'0'`` specifier
717 instead.
718
719 * Removed the deprecated ``fmt/posix.h`` header that has been replaced with
720 ``fmt/os.h``.
721
722 * Removed the deprecated ``format_to_n_context``, ``format_to_n_args`` and
723 ``make_format_to_n_args``. They have been replaced with ``format_context``,
724 ``format_args` and ``make_format_args`` respectively.
725
726 * Moved ``wchar_t``-specific functions and types to ``fmt/xchar.h``.
727 You can define ``FMT_DEPRECATED_INCLUDE_XCHAR`` to automatically include
728 ``fmt/xchar.h`` from ``fmt/format.h`` but this will be disabled in the next
729 major release.
730
731 * Fixed handling of the ``'+'`` specifier in localized formatting
732 (`#2133 <https://github.com/fmtlib/fmt/issues/2133>`_).
733
734 * Added support for the ``'s'`` format specifier that gives textual
735 representation of ``bool``
736 (`#2094 <https://github.com/fmtlib/fmt/issues/2094>`_,
737 `#2109 <https://github.com/fmtlib/fmt/pull/2109>`_). For example:
738
739 .. code:: c++
740
741 #include <fmt/core.h>
742
743 int main() {
744 fmt::print("{:s}", true);
745 }
746
747 prints "true".
748 Thanks `@powercoderlol (Ivan Polyakov) <https://github.com/powercoderlol>`_.
749
750 * Made ``fmt::ptr`` work with function pointers
751 (`#2131 <https://github.com/fmtlib/fmt/pull/2131>`_). For example:
752
753 .. code:: c++
754
755 #include <fmt/format.h>
756
757 int main() {
758 fmt::print("My main: {}\n", fmt::ptr(main));
759 }
760
761 Thanks `@mikecrowe (Mike Crowe) <https://github.com/mikecrowe>`_.
762
763 * The undocumented support for specializing ``formatter`` for pointer types
764 has been removed.
765
766 * Fixed ``fmt::formatted_size`` with format string compilation
767 (`#2141 <https://github.com/fmtlib/fmt/pull/2141>`_,
768 `#2161 <https://github.com/fmtlib/fmt/pull/2161>`_).
769 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
770
771 * Fixed handling of empty format strings during format string compilation
772 (`#2042 <https://github.com/fmtlib/fmt/issues/2042>`_):
773
774 .. code:: c++
775
776 auto s = fmt::format(FMT_COMPILE(""));
777
778 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
779
780 * Fixed handling of enums in ``fmt::to_string``
781 (`#2036 <https://github.com/fmtlib/fmt/issues/2036>`_).
782
783 * Improved width computation
784 (`#2033 <https://github.com/fmtlib/fmt/issues/2033>`_,
785 `#2091 <https://github.com/fmtlib/fmt/issues/2091>`_). For example:
786
787 .. code:: c++
788
789 #include <fmt/core.h>
790
791 int main() {
792 fmt::print("{:-<10}{}\n", "你好", "世界");
793 fmt::print("{:-<10}{}\n", "hello", "world");
794 }
795
796 prints
797
798 .. image:: https://user-images.githubusercontent.com/576385/
799 119840373-cea3ca80-beb9-11eb-91e0-54266c48e181.png
800
801 on a modern terminal.
802
803 * The experimental fast output stream (``fmt::ostream``) is now truncated by
804 default for consistency with ``fopen``
805 (`#2018 <https://github.com/fmtlib/fmt/issues/2018>`_). For example:
806
807 .. code:: c++
808
809 #include <fmt/os.h>
810
811 int main() {
812 fmt::ostream out1 = fmt::output_file("guide");
813 out1.print("Zaphod");
814 out1.close();
815 fmt::ostream out2 = fmt::output_file("guide");
816 out2.print("Ford");
817 }
818
819 writes "Ford" to the file "guide". To preserve the old file content if any
820 pass ``fmt::file::WRONLY | fmt::file::CREATE`` flags to ``fmt::output_file``.
821
822 * Fixed moving of ``fmt::ostream`` that holds buffered data
823 (`#2197 <https://github.com/fmtlib/fmt/issues/2197>`_,
824 `#2198 <https://github.com/fmtlib/fmt/pull/2198>`_).
825 Thanks `@vtta <https://github.com/vtta>`_.
826
827 * Replaced the ``fmt::system_error`` exception with a function of the same
828 name that constructs ``std::system_error``
829 (`#2266 <https://github.com/fmtlib/fmt/issues/2266>`_).
830
831 * Replaced the ``fmt::windows_error`` exception with a function of the same
832 name that constructs ``std::system_error`` with the category returned by
833 ``fmt::system_category()``
834 (`#2274 <https://github.com/fmtlib/fmt/issues/2274>`_,
835 `#2275 <https://github.com/fmtlib/fmt/pull/2275>`_).
836 The latter is similar to ``std::sytem_category`` but correctly handles UTF-8.
837 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
838
839 * Replaced ``fmt::error_code`` with ``std::error_code`` and made it formattable
840 (`#2269 <https://github.com/fmtlib/fmt/issues/2269>`_,
841 `#2270 <https://github.com/fmtlib/fmt/pull/2270>`_,
842 `#2273 <https://github.com/fmtlib/fmt/pull/2273>`_).
843 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
844
845 * Added speech synthesis support
846 (`#2206 <https://github.com/fmtlib/fmt/pull/2206>`_).
847
848 * Made ``format_to`` work with a memory buffer that has a custom allocator
849 (`#2300 <https://github.com/fmtlib/fmt/pull/2300>`_).
850 Thanks `@voxmea <https://github.com/voxmea>`_.
851
852 * Added ``Allocator::max_size`` support to ``basic_memory_buffer``.
853 (`#1960 <https://github.com/fmtlib/fmt/pull/1960>`_).
854 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
855
856 * Added wide string support to ``fmt::join``
857 (`#2236 <https://github.com/fmtlib/fmt/pull/2236>`_).
858 Thanks `@crbrz <https://github.com/crbrz>`_.
859
860 * Made iterators passed to ``formatter`` specializations via a format context
861 satisfy C++20 ``std::output_iterator`` requirements
862 (`#2156 <https://github.com/fmtlib/fmt/issues/2156>`_,
863 `#2158 <https://github.com/fmtlib/fmt/pull/2158>`_,
864 `#2195 <https://github.com/fmtlib/fmt/issues/2195>`_,
865 `#2204 <https://github.com/fmtlib/fmt/pull/2204>`_).
866 Thanks `@randomnetcat (Jason Cobb) <https://github.com/randomnetcat>`_.
867
868 * Optimized the ``printf`` implementation
869 (`#1982 <https://github.com/fmtlib/fmt/pull/1982>`_,
870 `#1984 <https://github.com/fmtlib/fmt/pull/1984>`_,
871 `#2016 <https://github.com/fmtlib/fmt/pull/2016>`_,
872 `#2164 <https://github.com/fmtlib/fmt/pull/2164>`_).
873 Thanks `@rimathia <https://github.com/rimathia>`_ and
874 `@moiwi <https://github.com/moiwi>`_.
875
876 * Improved detection of ``constexpr`` ``char_traits``
877 (`#2246 <https://github.com/fmtlib/fmt/pull/2246>`_,
878 `#2257 <https://github.com/fmtlib/fmt/pull/2257>`_).
879 Thanks `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_.
880
881 * Fixed writing to ``stdout`` when it is redirected to ``NUL`` on Windows
882 (`#2080 <https://github.com/fmtlib/fmt/issues/2080>`_).
883
884 * Fixed exception propagation from iterators
885 (`#2097 <https://github.com/fmtlib/fmt/issues/2097>`_).
886
887 * Improved ``strftime`` error handling
888 (`#2238 <https://github.com/fmtlib/fmt/issues/2238>`_,
889 `#2244 <https://github.com/fmtlib/fmt/pull/2244>`_).
890 Thanks `@yumeyao <https://github.com/yumeyao>`_.
891
892 * Stopped using deprecated GCC UDL template extension.
893
894 * Added ``fmt/args.h`` to the install target
895 (`#2096 <https://github.com/fmtlib/fmt/issues/2096>`_).
896
897 * Error messages are now passed to assert when exceptions are disabled
898 (`#2145 <https://github.com/fmtlib/fmt/pull/2145>`_).
899 Thanks `@NobodyXu (Jiahao XU) <https://github.com/NobodyXu>`_.
900
901 * Added the ``FMT_MASTER_PROJECT`` CMake option to control build and install
902 targets when {fmt} is included via ``add_subdirectory``
903 (`#2098 <https://github.com/fmtlib/fmt/issues/2098>`_,
904 `#2100 <https://github.com/fmtlib/fmt/pull/2100>`_).
905 Thanks `@randomizedthinking <https://github.com/randomizedthinking>`_.
906
907 * Improved build configuration
908 (`#2026 <https://github.com/fmtlib/fmt/pull/2026>`_,
909 `#2122 <https://github.com/fmtlib/fmt/pull/2122>`_).
910 Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_ and
911 `@ibaned (Dan Ibanez) <https://github.com/ibaned>`_.
912
913 * Fixed various warnings and compilation issues
914 (`#1947 <https://github.com/fmtlib/fmt/issues/1947>`_,
915 `#1959 <https://github.com/fmtlib/fmt/pull/1959>`_,
916 `#1963 <https://github.com/fmtlib/fmt/pull/1963>`_,
917 `#1965 <https://github.com/fmtlib/fmt/pull/1965>`_,
918 `#1966 <https://github.com/fmtlib/fmt/issues/1966>`_,
919 `#1974 <https://github.com/fmtlib/fmt/pull/1974>`_,
920 `#1975 <https://github.com/fmtlib/fmt/pull/1975>`_,
921 `#1990 <https://github.com/fmtlib/fmt/pull/1990>`_,
922 `#2000 <https://github.com/fmtlib/fmt/issues/2000>`_,
923 `#2001 <https://github.com/fmtlib/fmt/pull/2001>`_,
924 `#2002 <https://github.com/fmtlib/fmt/issues/2002>`_,
925 `#2004 <https://github.com/fmtlib/fmt/issues/2004>`_,
926 `#2006 <https://github.com/fmtlib/fmt/pull/2006>`_,
927 `#2009 <https://github.com/fmtlib/fmt/pull/2009>`_,
928 `#2010 <https://github.com/fmtlib/fmt/pull/2010>`_,
929 `#2038 <https://github.com/fmtlib/fmt/issues/2038>`_,
930 `#2039 <https://github.com/fmtlib/fmt/issues/2039>`_,
931 `#2047 <https://github.com/fmtlib/fmt/issues/2047>`_,
932 `#2053 <https://github.com/fmtlib/fmt/pull/2053>`_,
933 `#2059 <https://github.com/fmtlib/fmt/issues/2059>`_,
934 `#2065 <https://github.com/fmtlib/fmt/pull/2065>`_,
935 `#2067 <https://github.com/fmtlib/fmt/pull/2067>`_,
936 `#2068 <https://github.com/fmtlib/fmt/pull/2068>`_,
937 `#2073 <https://github.com/fmtlib/fmt/pull/2073>`_,
938 `#2103 <https://github.com/fmtlib/fmt/issues/2103>`_,
939 `#2105 <https://github.com/fmtlib/fmt/issues/2105>`_,
940 `#2106 <https://github.com/fmtlib/fmt/pull/2106>`_,
941 `#2107 <https://github.com/fmtlib/fmt/pull/2107>`_,
942 `#2116 <https://github.com/fmtlib/fmt/issues/2116>`_,
943 `#2117 <https://github.com/fmtlib/fmt/pull/2117>`_,
944 `#2118 <https://github.com/fmtlib/fmt/issues/2118>`_,
945 `#2119 <https://github.com/fmtlib/fmt/pull/2119>`_,
946 `#2127 <https://github.com/fmtlib/fmt/issues/2127>`_,
947 `#2128 <https://github.com/fmtlib/fmt/pull/2128>`_,
948 `#2140 <https://github.com/fmtlib/fmt/issues/2140>`_,
949 `#2142 <https://github.com/fmtlib/fmt/issues/2142>`_,
950 `#2143 <https://github.com/fmtlib/fmt/pull/2143>`_,
951 `#2144 <https://github.com/fmtlib/fmt/pull/2144>`_,
952 `#2147 <https://github.com/fmtlib/fmt/issues/2147>`_,
953 `#2148 <https://github.com/fmtlib/fmt/issues/2148>`_,
954 `#2149 <https://github.com/fmtlib/fmt/issues/2149>`_,
955 `#2152 <https://github.com/fmtlib/fmt/pull/2152>`_,
956 `#2160 <https://github.com/fmtlib/fmt/pull/2160>`_,
957 `#2170 <https://github.com/fmtlib/fmt/issues/2170>`_,
958 `#2175 <https://github.com/fmtlib/fmt/issues/2175>`_,
959 `#2176 <https://github.com/fmtlib/fmt/issues/2176>`_,
960 `#2177 <https://github.com/fmtlib/fmt/pull/2177>`_,
961 `#2178 <https://github.com/fmtlib/fmt/issues/2178>`_,
962 `#2179 <https://github.com/fmtlib/fmt/pull/2179>`_,
963 `#2180 <https://github.com/fmtlib/fmt/issues/2180>`_,
964 `#2181 <https://github.com/fmtlib/fmt/issues/2181>`_,
965 `#2183 <https://github.com/fmtlib/fmt/pull/2183>`_,
966 `#2184 <https://github.com/fmtlib/fmt/issues/2184>`_,
967 `#2185 <https://github.com/fmtlib/fmt/issues/2185>`_,
968 `#2186 <https://github.com/fmtlib/fmt/pull/2186>`_,
969 `#2187 <https://github.com/fmtlib/fmt/pull/2187>`_,
970 `#2190 <https://github.com/fmtlib/fmt/pull/2190>`_,
971 `#2192 <https://github.com/fmtlib/fmt/pull/2192>`_,
972 `#2194 <https://github.com/fmtlib/fmt/pull/2194>`_,
973 `#2205 <https://github.com/fmtlib/fmt/pull/2205>`_,
974 `#2210 <https://github.com/fmtlib/fmt/issues/2210>`_,
975 `#2211 <https://github.com/fmtlib/fmt/pull/2211>`_,
976 `#2215 <https://github.com/fmtlib/fmt/pull/2215>`_,
977 `#2216 <https://github.com/fmtlib/fmt/pull/2216>`_,
978 `#2218 <https://github.com/fmtlib/fmt/pull/2218>`_,
979 `#2220 <https://github.com/fmtlib/fmt/pull/2220>`_,
980 `#2228 <https://github.com/fmtlib/fmt/issues/2228>`_,
981 `#2229 <https://github.com/fmtlib/fmt/pull/2229>`_,
982 `#2230 <https://github.com/fmtlib/fmt/pull/2230>`_,
983 `#2233 <https://github.com/fmtlib/fmt/issues/2233>`_,
984 `#2239 <https://github.com/fmtlib/fmt/pull/2239>`_,
985 `#2248 <https://github.com/fmtlib/fmt/issues/2248>`_,
986 `#2252 <https://github.com/fmtlib/fmt/issues/2252>`_,
987 `#2253 <https://github.com/fmtlib/fmt/pull/2253>`_,
988 `#2255 <https://github.com/fmtlib/fmt/pull/2255>`_,
989 `#2261 <https://github.com/fmtlib/fmt/issues/2261>`_,
990 `#2278 <https://github.com/fmtlib/fmt/issues/2278>`_,
991 `#2284 <https://github.com/fmtlib/fmt/issues/2284>`_,
992 `#2287 <https://github.com/fmtlib/fmt/pull/2287>`_,
993 `#2289 <https://github.com/fmtlib/fmt/pull/2289>`_,
994 `#2290 <https://github.com/fmtlib/fmt/pull/2290>`_,
995 `#2293 <https://github.com/fmtlib/fmt/pull/2293>`_,
996 `#2295 <https://github.com/fmtlib/fmt/issues/2295>`_,
997 `#2296 <https://github.com/fmtlib/fmt/pull/2296>`_,
998 `#2297 <https://github.com/fmtlib/fmt/pull/2297>`_,
999 `#2311 <https://github.com/fmtlib/fmt/issues/2311>`_,
1000 `#2313 <https://github.com/fmtlib/fmt/pull/2313>`_,
1001 `#2315 <https://github.com/fmtlib/fmt/pull/2315>`_,
1002 `#2320 <https://github.com/fmtlib/fmt/issues/2320>`_,
1003 `#2321 <https://github.com/fmtlib/fmt/pull/2321>`_,
1004 `#2323 <https://github.com/fmtlib/fmt/pull/2323>`_,
1005 `#2328 <https://github.com/fmtlib/fmt/issues/2328>`_,
1006 `#2329 <https://github.com/fmtlib/fmt/pull/2329>`_,
1007 `#2333 <https://github.com/fmtlib/fmt/pull/2333>`_,
1008 `#2338 <https://github.com/fmtlib/fmt/pull/2338>`_,
1009 `#2341 <https://github.com/fmtlib/fmt/pull/2341>`_).
1010 Thanks `@darklukee <https://github.com/darklukee>`_,
1011 `@fagg (Ashton Fagg) <https://github.com/fagg>`_,
1012 `@killerbot242 (Lieven de Cock) <https://github.com/killerbot242>`_,
1013 `@jgopel (Jonathan Gopel) <https://github.com/jgopel>`_,
1014 `@yeswalrus (Walter Gray) <https://github.com/yeswalrus>`_,
1015 `@Finkman <https://github.com/Finkman>`_,
1016 `@HazardyKnusperkeks (Björn Schäpers) <https://github.com/HazardyKnusperkeks>`_,
1017 `@dkavolis (Daumantas Kavolis) <https://github.com/dkavolis>`_,
1018 `@concatime (Issam Maghni) <https://github.com/concatime>`_,
1019 `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_,
1020 `@summivox (Yin Zhong) <https://github.com/summivox>`_,
1021 `@yNeo <https://github.com/yNeo>`_,
1022 `@Apache-HB (Elliot) <https://github.com/Apache-HB>`_,
1023 `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_,
1024 `@toojays (John Steele Scott) <https://github.com/toojays>`_,
1025 `@Brainy0207 <https://github.com/Brainy0207>`_,
1026 `@vadz (VZ) <https://github.com/vadz>`_,
1027 `@imsherlock (Ryan Sherlock) <https://github.com/imsherlock>`_,
1028 `@phprus (Vladislav Shchapov) <https://github.com/phprus>`_,
1029 `@white238 (Chris White) <https://github.com/white238>`_,
1030 `@yafshar (Yaser Afshar) <https://github.com/yafshar>`_,
1031 `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_,
1032 `@jstaahl <https://github.com/jstaahl>`_,
1033 `@denchat <https://github.com/denchat>`_,
1034 `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
1035 `@ilyakurdyukov (Ilya Kurdyukov) <https://github.com/ilyakurdyukov>`_,
1036 `@ilmai <https://github.com/ilmai>`_,
1037 `@JessyDL (Jessy De Lannoit) <https://github.com/JessyDL>`_,
1038 `@sergiud (Sergiu Deitsch) <https://github.com/sergiud>`_,
1039 `@mwinterb <https://github.com/mwinterb>`_,
1040 `@sven-herrmann <https://github.com/sven-herrmann>`_,
1041 `@jmelas (John Melas) <https://github.com/jmelas>`_,
1042 `@twoixter (Jose Miguel Pérez) <https://github.com/twoixter>`_,
1043 `@crbrz <https://github.com/crbrz>`_,
1044 `@upsj (Tobias Ribizel) <https://github.com/upsj>`_.
1045
1046 * Improved documentation
1047 (`#1986 <https://github.com/fmtlib/fmt/issues/1986>`_,
1048 `#2051 <https://github.com/fmtlib/fmt/pull/2051>`_,
1049 `#2057 <https://github.com/fmtlib/fmt/issues/2057>`_,
1050 `#2081 <https://github.com/fmtlib/fmt/pull/2081>`_,
1051 `#2084 <https://github.com/fmtlib/fmt/issues/2084>`_,
1052 `#2312 <https://github.com/fmtlib/fmt/pull/2312>`_).
1053 Thanks `@imba-tjd (谭九鼎) <https://github.com/imba-tjd>`_,
1054 `@0x416c69 (AlιAѕѕaѕѕιN) <https://github.com/0x416c69>`_,
1055 `@mordante <https://github.com/mordante>`_.
1056
1057 * Continuous integration and test improvements
1058 (`#1969 <https://github.com/fmtlib/fmt/issues/1969>`_,
1059 `#1991 <https://github.com/fmtlib/fmt/pull/1991>`_,
1060 `#2020 <https://github.com/fmtlib/fmt/pull/2020>`_,
1061 `#2110 <https://github.com/fmtlib/fmt/pull/2110>`_,
1062 `#2114 <https://github.com/fmtlib/fmt/pull/2114>`_,
1063 `#2196 <https://github.com/fmtlib/fmt/issues/2196>`_,
1064 `#2217 <https://github.com/fmtlib/fmt/pull/2217>`_,
1065 `#2247 <https://github.com/fmtlib/fmt/pull/2247>`_,
1066 `#2256 <https://github.com/fmtlib/fmt/pull/2256>`_,
1067 `#2336 <https://github.com/fmtlib/fmt/pull/2336>`_,
1068 `#2346 <https://github.com/fmtlib/fmt/pull/2346>`_).
1069 Thanks `@jgopel (Jonathan Gopel) <https://github.com/jgopel>`_,
1070 `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_ and
1071 `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
1072
1073 7.1.3 - 2020-11-24
1074 ------------------
1075
1076 * Fixed handling of buffer boundaries in ``format_to_n``
1077 (`#1996 <https://github.com/fmtlib/fmt/issues/1996>`_,
1078 `#2029 <https://github.com/fmtlib/fmt/issues/2029>`_).
1079
1080 * Fixed linkage errors when linking with a shared library
1081 (`#2011 <https://github.com/fmtlib/fmt/issues/2011>`_).
1082
1083 * Reintroduced ostream support to range formatters
1084 (`#2014 <https://github.com/fmtlib/fmt/issues/2014>`_).
1085
1086 * Worked around an issue with mixing std versions in gcc
1087 (`#2017 <https://github.com/fmtlib/fmt/issues/2017>`_).
1088
1089 7.1.2 - 2020-11-04
1090 ------------------
1091
1092 * Fixed floating point formatting with large precision
1093 (`#1976 <https://github.com/fmtlib/fmt/issues/1976>`_).
1094
1095 7.1.1 - 2020-11-01
1096 ------------------
1097
1098 * Fixed ABI compatibility with 7.0.x
1099 (`#1961 <https://github.com/fmtlib/fmt/issues/1961>`_).
1100
1101 * Added the ``FMT_ARM_ABI_COMPATIBILITY`` macro to work around ABI
1102 incompatibility between GCC and Clang on ARM
1103 (`#1919 <https://github.com/fmtlib/fmt/issues/1919>`_).
1104
1105 * Worked around a SFINAE bug in GCC 8
1106 (`#1957 <https://github.com/fmtlib/fmt/issues/1957>`_).
1107
1108 * Fixed linkage errors when building with GCC's LTO
1109 (`#1955 <https://github.com/fmtlib/fmt/issues/1955>`_).
1110
1111 * Fixed a compilation error when building without ``__builtin_clz`` or equivalent
1112 (`#1968 <https://github.com/fmtlib/fmt/pull/1968>`_).
1113 Thanks `@tohammer (Tobias Hammer) <https://github.com/tohammer>`_.
1114
1115 * Fixed a sign conversion warning
1116 (`#1964 <https://github.com/fmtlib/fmt/pull/1964>`_).
1117 Thanks `@OptoCloud <https://github.com/OptoCloud>`_.
1118
1119 7.1.0 - 2020-10-25
1120 ------------------
1121
1122 * Switched from `Grisu3
1123 <https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf>`_
1124 to `Dragonbox <https://github.com/jk-jeon/dragonbox>`_ for the default
1125 floating-point formatting which gives the shortest decimal representation
1126 with round-trip guarantee and correct rounding
1127 (`#1882 <https://github.com/fmtlib/fmt/pull/1882>`_,
1128 `#1887 <https://github.com/fmtlib/fmt/pull/1887>`_,
1129 `#1894 <https://github.com/fmtlib/fmt/pull/1894>`_). This makes {fmt} up to
1130 20-30x faster than common implementations of ``std::ostringstream`` and
1131 ``sprintf`` on `dtoa-benchmark <https://github.com/fmtlib/dtoa-benchmark>`_
1132 and faster than double-conversion and Ryū:
1133
1134 .. image:: https://user-images.githubusercontent.com/576385/
1135 95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png
1136
1137 It is possible to get even better performance at the cost of larger binary
1138 size by compiling with the ``FMT_USE_FULL_CACHE_DRAGONBOX`` macro set to 1.
1139
1140 Thanks `@jk-jeon (Junekey Jeon) <https://github.com/jk-jeon>`_.
1141
1142 * Added an experimental unsynchronized file output API which, together with
1143 `format string compilation <https://fmt.dev/latest/api.html#compile-api>`_,
1144 can give `5-9 times speed up compared to fprintf
1145 <https://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html>`_
1146 on common platforms (`godbolt <https://godbolt.org/z/nsTcG8>`__):
1147
1148 .. code:: c++
1149
1150 #include <fmt/os.h>
1151
1152 int main() {
1153 auto f = fmt::output_file("guide");
1154 f.print("The answer is {}.", 42);
1155 }
1156
1157 * Added a formatter for ``std::chrono::time_point<system_clock>``
1158 (`#1819 <https://github.com/fmtlib/fmt/issues/1819>`_,
1159 `#1837 <https://github.com/fmtlib/fmt/pull/1837>`_). For example
1160 (`godbolt <https://godbolt.org/z/c4M6fh>`__):
1161
1162 .. code:: c++
1163
1164 #include <fmt/chrono.h>
1165
1166 int main() {
1167 auto now = std::chrono::system_clock::now();
1168 fmt::print("The time is {:%H:%M:%S}.\n", now);
1169 }
1170
1171 Thanks `@adamburgess (Adam Burgess) <https://github.com/adamburgess>`_.
1172
1173 * Added support for ranges with non-const ``begin``/``end`` to ``fmt::join``
1174 (`#1784 <https://github.com/fmtlib/fmt/issues/1784>`_,
1175 `#1786 <https://github.com/fmtlib/fmt/pull/1786>`_). For example
1176 (`godbolt <https://godbolt.org/z/jP63Tv>`__):
1177
1178 .. code:: c++
1179
1180 #include <fmt/ranges.h>
1181 #include <range/v3/view/filter.hpp>
1182
1183 int main() {
1184 using std::literals::string_literals::operator""s;
1185 auto strs = std::array{"a"s, "bb"s, "ccc"s};
1186 auto range = strs | ranges::views::filter(
1187 [] (const std::string &x) { return x.size() != 2; }
1188 );
1189 fmt::print("{}\n", fmt::join(range, ""));
1190 }
1191
1192 prints "accc".
1193
1194 Thanks `@tonyelewis (Tony E Lewis) <https://github.com/tonyelewis>`_.
1195
1196 * Added a ``memory_buffer::append`` overload that takes a range
1197 (`#1806 <https://github.com/fmtlib/fmt/pull/1806>`_).
1198 Thanks `@BRevzin (Barry Revzin) <https://github.com/BRevzin>`_.
1199
1200 * Improved handling of single code units in ``FMT_COMPILE``. For example:
1201
1202 .. code:: c++
1203
1204 #include <fmt/compile.h>
1205
1206 char* f(char* buf) {
1207 return fmt::format_to(buf, FMT_COMPILE("x{}"), 42);
1208 }
1209
1210 compiles to just (`godbolt <https://godbolt.org/z/5vncz3>`__):
1211
1212 .. code:: asm
1213
1214 _Z1fPc:
1215 movb $120, (%rdi)
1216 xorl %edx, %edx
1217 cmpl $42, _ZN3fmt2v76detail10basic_dataIvE23zero_or_powers_of_10_32E+8(%rip)
1218 movl $3, %eax
1219 seta %dl
1220 subl %edx, %eax
1221 movzwl _ZN3fmt2v76detail10basic_dataIvE6digitsE+84(%rip), %edx
1222 cltq
1223 addq %rdi, %rax
1224 movw %dx, -2(%rax)
1225 ret
1226
1227 Here a single ``mov`` instruction writes ``'x'`` (``$120``) to the output
1228 buffer.
1229
1230 * Added dynamic width support to format string compilation
1231 (`#1809 <https://github.com/fmtlib/fmt/issues/1809>`_).
1232
1233 * Improved error reporting for unformattable types: now you'll get the type name
1234 directly in the error message instead of the note:
1235
1236 .. code:: c++
1237
1238 #include <fmt/core.h>
1239
1240 struct how_about_no {};
1241
1242 int main() {
1243 fmt::print("{}", how_about_no());
1244 }
1245
1246 Error (`godbolt <https://godbolt.org/z/GoxM4e>`__):
1247
1248 ``fmt/core.h:1438:3: error: static_assert failed due to requirement
1249 'fmt::v7::formattable<how_about_no>()' "Cannot format an argument.
1250 To make type T formattable provide a formatter<T> specialization:
1251 https://fmt.dev/latest/api.html#udt"
1252 ...``
1253
1254 * Added the `make_args_checked <https://fmt.dev/7.1.0/api.html#argument-lists>`_
1255 function template that allows you to write formatting functions with
1256 compile-time format string checks and avoid binary code bloat
1257 (`godbolt <https://godbolt.org/z/PEf9qr>`__):
1258
1259 .. code:: c++
1260
1261 void vlog(const char* file, int line, fmt::string_view format,
1262 fmt::format_args args) {
1263 fmt::print("{}: {}: ", file, line);
1264 fmt::vprint(format, args);
1265 }
1266
1267 template <typename S, typename... Args>
1268 void log(const char* file, int line, const S& format, Args&&... args) {
1269 vlog(file, line, format,
1270 fmt::make_args_checked<Args...>(format, args...));
1271 }
1272
1273 #define MY_LOG(format, ...) \
1274 log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__)
1275
1276 MY_LOG("invalid squishiness: {}", 42);
1277
1278 * Replaced ``snprintf`` fallback with a faster internal IEEE 754 ``float`` and
1279 ``double`` formatter for arbitrary precision. For example
1280 (`godbolt <https://godbolt.org/z/dPhWvj>`__):
1281
1282 .. code:: c++
1283
1284 #include <fmt/core.h>
1285
1286 int main() {
1287 fmt::print("{:.500}\n", 4.9406564584124654E-324);
1288 }
1289
1290 prints
1291
1292 ``4.9406564584124654417656879286822137236505980261432476442558568250067550727020875186529983636163599237979656469544571773092665671035593979639877479601078187812630071319031140452784581716784898210368871863605699873072305000638740915356498438731247339727316961514003171538539807412623856559117102665855668676818703956031062493194527159149245532930545654440112748012970999954193198940908041656332452475714786901472678015935523861155013480352649347201937902681071074917033322268447533357208324319360923829e-324``.
1293
1294 * Made ``format_to_n`` and ``formatted_size`` part of the `core API
1295 <https://fmt.dev/latest/api.html#core-api>`__
1296 (`godbolt <https://godbolt.org/z/sPjY1K>`__):
1297
1298 .. code:: c++
1299
1300 #include <fmt/core.h>
1301
1302 int main() {
1303 char buffer[10];
1304 auto result = fmt::format_to_n(buffer, sizeof(buffer), "{}", 42);
1305 }
1306
1307 * Added ``fmt::format_to_n`` overload with format string compilation
1308 (`#1764 <https://github.com/fmtlib/fmt/issues/1764>`_,
1309 `#1767 <https://github.com/fmtlib/fmt/pull/1767>`_,
1310 `#1869 <https://github.com/fmtlib/fmt/pull/1869>`_). For example
1311 (`godbolt <https://godbolt.org/z/93h86q>`__):
1312
1313 .. code:: c++
1314
1315 #include <fmt/compile.h>
1316
1317 int main() {
1318 char buffer[8];
1319 fmt::format_to_n(buffer, sizeof(buffer), FMT_COMPILE("{}"), 42);
1320 }
1321
1322 Thanks `@Kurkin (Dmitry Kurkin) <https://github.com/Kurkin>`_,
1323 `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
1324
1325 * Added ``fmt::format_to`` overload that take ``text_style``
1326 (`#1593 <https://github.com/fmtlib/fmt/issues/1593>`_,
1327 `#1842 <https://github.com/fmtlib/fmt/issues/1842>`_,
1328 `#1843 <https://github.com/fmtlib/fmt/pull/1843>`_). For example
1329 (`godbolt <https://godbolt.org/z/91153r>`__):
1330
1331 .. code:: c++
1332
1333 #include <fmt/color.h>
1334
1335 int main() {
1336 std::string out;
1337 fmt::format_to(std::back_inserter(out),
1338 fmt::emphasis::bold | fg(fmt::color::red),
1339 "The answer is {}.", 42);
1340 }
1341
1342 Thanks `@Naios (Denis Blank) <https://github.com/Naios>`_.
1343
1344 * Made the ``'#'`` specifier emit trailing zeros in addition to the decimal
1345 point (`#1797 <https://github.com/fmtlib/fmt/issues/1797>`_). For example
1346 (`godbolt <https://godbolt.org/z/bhdcW9>`__):
1347
1348 .. code:: c++
1349
1350 #include <fmt/core.h>
1351
1352 int main() {
1353 fmt::print("{:#.2g}", 0.5);
1354 }
1355
1356 prints ``0.50``.
1357
1358 * Changed the default floating point format to not include ``.0`` for
1359 consistency with ``std::format`` and ``std::to_chars``
1360 (`#1893 <https://github.com/fmtlib/fmt/issues/1893>`_,
1361 `#1943 <https://github.com/fmtlib/fmt/issues/1943>`_). It is possible to get
1362 the decimal point and trailing zero with the ``#`` specifier.
1363
1364 * Fixed an issue with floating-point formatting that could result in addition of
1365 a non-significant trailing zero in rare cases e.g. ``1.00e-34`` instead of
1366 ``1.0e-34`` (`#1873 <https://github.com/fmtlib/fmt/issues/1873>`_,
1367 `#1917 <https://github.com/fmtlib/fmt/issues/1917>`_).
1368
1369 * Made ``fmt::to_string`` fallback on ``ostream`` insertion operator if
1370 the ``formatter`` specialization is not provided
1371 (`#1815 <https://github.com/fmtlib/fmt/issues/1815>`_,
1372 `#1829 <https://github.com/fmtlib/fmt/pull/1829>`_).
1373 Thanks `@alexezeder (Alexey Ochapov) <https://github.com/alexezeder>`_.
1374
1375 * Added support for the append mode to the experimental file API and
1376 improved ``fcntl.h`` detection.
1377 (`#1847 <https://github.com/fmtlib/fmt/pull/1847>`_,
1378 `#1848 <https://github.com/fmtlib/fmt/pull/1848>`_).
1379 Thanks `@t-wiser <https://github.com/t-wiser>`_.
1380
1381 * Fixed handling of types that have both an implicit conversion operator and
1382 an overloaded ``ostream`` insertion operator
1383 (`#1766 <https://github.com/fmtlib/fmt/issues/1766>`_).
1384
1385 * Fixed a slicing issue in an internal iterator type
1386 (`#1822 <https://github.com/fmtlib/fmt/pull/1822>`_).
1387 Thanks `@BRevzin (Barry Revzin) <https://github.com/BRevzin>`_.
1388
1389 * Fixed an issue in locale-specific integer formatting
1390 (`#1927 <https://github.com/fmtlib/fmt/issues/1927>`_).
1391
1392 * Fixed handling of exotic code unit types
1393 (`#1870 <https://github.com/fmtlib/fmt/issues/1870>`_,
1394 `#1932 <https://github.com/fmtlib/fmt/issues/1932>`_).
1395
1396 * Improved ``FMT_ALWAYS_INLINE``
1397 (`#1878 <https://github.com/fmtlib/fmt/pull/1878>`_).
1398 Thanks `@jk-jeon (Junekey Jeon) <https://github.com/jk-jeon>`_.
1399
1400 * Removed dependency on ``windows.h``
1401 (`#1900 <https://github.com/fmtlib/fmt/pull/1900>`_).
1402 Thanks `@bernd5 (Bernd Baumanns) <https://github.com/bernd5>`_.
1403
1404 * Optimized counting of decimal digits on MSVC
1405 (`#1890 <https://github.com/fmtlib/fmt/pull/1890>`_).
1406 Thanks `@mwinterb <https://github.com/mwinterb>`_.
1407
1408 * Improved documentation
1409 (`#1772 <https://github.com/fmtlib/fmt/issues/1772>`_,
1410 `#1775 <https://github.com/fmtlib/fmt/pull/1775>`_,
1411 `#1792 <https://github.com/fmtlib/fmt/pull/1792>`_,
1412 `#1838 <https://github.com/fmtlib/fmt/pull/1838>`_,
1413 `#1888 <https://github.com/fmtlib/fmt/pull/1888>`_,
1414 `#1918 <https://github.com/fmtlib/fmt/pull/1918>`_,
1415 `#1939 <https://github.com/fmtlib/fmt/pull/1939>`_).
1416 Thanks `@leolchat (Léonard Gérard) <https://github.com/leolchat>`_,
1417 `@pepsiman (Malcolm Parsons) <https://github.com/pepsiman>`_,
1418 `@Klaim (Joël Lamotte) <https://github.com/Klaim>`_,
1419 `@ravijanjam (Ravi J) <https://github.com/ravijanjam>`_,
1420 `@francesco-st <https://github.com/francesco-st>`_,
1421 `@udnaan (Adnan) <https://github.com/udnaan>`_.
1422
1423 * Added the ``FMT_REDUCE_INT_INSTANTIATIONS`` CMake option that reduces the
1424 binary code size at the cost of some integer formatting performance. This can
1425 be useful for extremely memory-constrained embedded systems
1426 (`#1778 <https://github.com/fmtlib/fmt/issues/1778>`_,
1427 `#1781 <https://github.com/fmtlib/fmt/pull/1781>`_).
1428 Thanks `@kammce (Khalil Estell) <https://github.com/kammce>`_.
1429
1430 * Added the ``FMT_USE_INLINE_NAMESPACES`` macro to control usage of inline
1431 namespaces (`#1945 <https://github.com/fmtlib/fmt/pull/1945>`_).
1432 Thanks `@darklukee <https://github.com/darklukee>`_.
1433
1434 * Improved build configuration
1435 (`#1760 <https://github.com/fmtlib/fmt/pull/1760>`_,
1436 `#1770 <https://github.com/fmtlib/fmt/pull/1770>`_,
1437 `#1779 <https://github.com/fmtlib/fmt/issues/1779>`_,
1438 `#1783 <https://github.com/fmtlib/fmt/pull/1783>`_,
1439 `#1823 <https://github.com/fmtlib/fmt/pull/1823>`_).
1440 Thanks `@dvetutnev (Dmitriy Vetutnev) <https://github.com/dvetutnev>`_,
1441 `@xvitaly (Vitaly Zaitsev) <https://github.com/xvitaly>`_,
1442 `@tambry (Raul Tambre) <https://github.com/tambry>`_,
1443 `@medithe <https://github.com/medithe>`_,
1444 `@martinwuehrer (Martin Wührer) <https://github.com/martinwuehrer>`_.
1445
1446 * Fixed various warnings and compilation issues
1447 (`#1790 <https://github.com/fmtlib/fmt/pull/1790>`_,
1448 `#1802 <https://github.com/fmtlib/fmt/pull/1802>`_,
1449 `#1808 <https://github.com/fmtlib/fmt/pull/1808>`_,
1450 `#1810 <https://github.com/fmtlib/fmt/issues/1810>`_,
1451 `#1811 <https://github.com/fmtlib/fmt/issues/1811>`_,
1452 `#1812 <https://github.com/fmtlib/fmt/pull/1812>`_,
1453 `#1814 <https://github.com/fmtlib/fmt/pull/1814>`_,
1454 `#1816 <https://github.com/fmtlib/fmt/pull/1816>`_,
1455 `#1817 <https://github.com/fmtlib/fmt/pull/1817>`_,
1456 `#1818 <https://github.com/fmtlib/fmt/pull/1818>`_,
1457 `#1825 <https://github.com/fmtlib/fmt/issues/1825>`_,
1458 `#1836 <https://github.com/fmtlib/fmt/pull/1836>`_,
1459 `#1855 <https://github.com/fmtlib/fmt/pull/1855>`_,
1460 `#1856 <https://github.com/fmtlib/fmt/pull/1856>`_,
1461 `#1860 <https://github.com/fmtlib/fmt/pull/1860>`_,
1462 `#1877 <https://github.com/fmtlib/fmt/pull/1877>`_,
1463 `#1879 <https://github.com/fmtlib/fmt/pull/1879>`_,
1464 `#1880 <https://github.com/fmtlib/fmt/pull/1880>`_,
1465 `#1896 <https://github.com/fmtlib/fmt/issues/1896>`_,
1466 `#1897 <https://github.com/fmtlib/fmt/pull/1897>`_,
1467 `#1898 <https://github.com/fmtlib/fmt/pull/1898>`_,
1468 `#1904 <https://github.com/fmtlib/fmt/issues/1904>`_,
1469 `#1908 <https://github.com/fmtlib/fmt/pull/1908>`_,
1470 `#1911 <https://github.com/fmtlib/fmt/issues/1911>`_,
1471 `#1912 <https://github.com/fmtlib/fmt/issues/1912>`_,
1472 `#1928 <https://github.com/fmtlib/fmt/issues/1928>`_,
1473 `#1929 <https://github.com/fmtlib/fmt/pull/1929>`_,
1474 `#1935 <https://github.com/fmtlib/fmt/issues/1935>`_,
1475 `#1937 <https://github.com/fmtlib/fmt/pull/1937>`_,
1476 `#1942 <https://github.com/fmtlib/fmt/pull/1942>`_,
1477 `#1949 <https://github.com/fmtlib/fmt/issues/1949>`_).
1478 Thanks `@TheQwertiest <https://github.com/TheQwertiest>`_,
1479 `@medithe <https://github.com/medithe>`_,
1480 `@martinwuehrer (Martin Wührer) <https://github.com/martinwuehrer>`_,
1481 `@n16h7hunt3r <https://github.com/n16h7hunt3r>`_,
1482 `@Othereum (Seokjin Lee) <https://github.com/Othereum>`_,
1483 `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
1484 `@AlexanderLanin (Alexander Lanin) <https://github.com/AlexanderLanin>`_,
1485 `@gcerretani (Giovanni Cerretani) <https://github.com/gcerretani>`_,
1486 `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_,
1487 `@noizefloor (Jan Schwers) <https://github.com/noizefloor>`_,
1488 `@akohlmey (Axel Kohlmeyer) <https://github.com/akohlmey>`_,
1489 `@jk-jeon (Junekey Jeon) <https://github.com/jk-jeon>`_,
1490 `@rimathia <https://github.com/rimathia>`_,
1491 `@rglarix (Riccardo Ghetta (larix)) <https://github.com/rglarix>`_,
1492 `@moiwi <https://github.com/moiwi>`_,
1493 `@heckad (Kazantcev Andrey) <https://github.com/heckad>`_,
1494 `@MarcDirven <https://github.com/MarcDirven>`_.
1495 `@BartSiwek (Bart Siwek) <https://github.com/BartSiwek>`_,
1496 `@darklukee <https://github.com/darklukee>`_.
1497
1498 7.0.3 - 2020-08-06
1499 ------------------
1500
1501 * Worked around broken ``numeric_limits`` for 128-bit integers
1502 (`#1787 <https://github.com/fmtlib/fmt/issues/1787>`_).
1503
1504 * Added error reporting on missing named arguments
1505 (`#1796 <https://github.com/fmtlib/fmt/issues/1796>`_).
1506
1507 * Stopped using 128-bit integers with clang-cl
1508 (`#1800 <https://github.com/fmtlib/fmt/pull/1800>`_).
1509 Thanks `@Kingcom <https://github.com/Kingcom>`_.
1510
1511 * Fixed issues in locale-specific integer formatting
1512 (`#1782 <https://github.com/fmtlib/fmt/issues/1782>`_,
1513 `#1801 <https://github.com/fmtlib/fmt/issues/1801>`_).
1514
1515 7.0.2 - 2020-07-29
1516 ------------------
1517
1518 * Worked around broken ``numeric_limits`` for 128-bit integers
1519 (`#1725 <https://github.com/fmtlib/fmt/issues/1725>`_).
1520
1521 * Fixed compatibility with CMake 3.4
1522 (`#1779 <https://github.com/fmtlib/fmt/issues/1779>`_).
1523
1524 * Fixed handling of digit separators in locale-specific formatting
1525 (`#1782 <https://github.com/fmtlib/fmt/issues/1782>`_).
1526
1527 7.0.1 - 2020-07-07
1528 ------------------
1529
1530 * Updated the inline version namespace name.
1531
1532 * Worked around a gcc bug in mangling of alias templates
1533 (`#1753 <https://github.com/fmtlib/fmt/issues/1753>`_).
1534
1535 * Fixed a linkage error on Windows
1536 (`#1757 <https://github.com/fmtlib/fmt/issues/1757>`_).
1537 Thanks `@Kurkin (Dmitry Kurkin) <https://github.com/Kurkin>`_.
1538
1539 * Fixed minor issues with the documentation.
1540
1541 7.0.0 - 2020-07-05
1542 ------------------
1543
1544 * Reduced the library size. For example, on macOS a stripped test binary
1545 statically linked with {fmt} `shrank from ~368k to less than 100k
1546 <http://www.zverovich.net/2020/05/21/reducing-library-size.html>`_.
1547
1548 * Added a simpler and more efficient `format string compilation API
1549 <https://fmt.dev/7.0.0/api.html#compile-api>`_:
1550
1551 .. code:: c++
1552
1553 #include <fmt/compile.h>
1554
1555 // Converts 42 into std::string using the most efficient method and no
1556 // runtime format string processing.
1557 std::string s = fmt::format(FMT_COMPILE("{}"), 42);
1558
1559 The old ``fmt::compile`` API is now deprecated.
1560
1561 * Optimized integer formatting: ``format_to`` with format string compilation
1562 and a stack-allocated buffer is now `faster than to_chars on both
1563 libc++ and libstdc++
1564 <http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_.
1565
1566 * Optimized handling of small format strings. For example,
1567
1568 .. code:: c++
1569
1570 fmt::format("Result: {}: ({},{},{},{})", str1, str2, str3, str4, str5)
1571
1572 is now ~40% faster (`#1685 <https://github.com/fmtlib/fmt/issues/1685>`_).
1573
1574 * Applied extern templates to improve compile times when using the core API
1575 and ``fmt/format.h`` (`#1452 <https://github.com/fmtlib/fmt/issues/1452>`_).
1576 For example, on macOS with clang the compile time of a test translation unit
1577 dropped from 2.3s to 0.3s with ``-O2`` and from 0.6s to 0.3s with the default
1578 settings (``-O0``).
1579
1580 Before (``-O2``)::
1581
1582 % time c++ -c test.cc -I include -std=c++17 -O2
1583 c++ -c test.cc -I include -std=c++17 -O2 2.22s user 0.08s system 99% cpu 2.311 total
1584
1585 After (``-O2``)::
1586
1587 % time c++ -c test.cc -I include -std=c++17 -O2
1588 c++ -c test.cc -I include -std=c++17 -O2 0.26s user 0.04s system 98% cpu 0.303 total
1589
1590 Before (default)::
1591
1592 % time c++ -c test.cc -I include -std=c++17
1593 c++ -c test.cc -I include -std=c++17 0.53s user 0.06s system 98% cpu 0.601 total
1594
1595 After (default)::
1596
1597 % time c++ -c test.cc -I include -std=c++17
1598 c++ -c test.cc -I include -std=c++17 0.24s user 0.06s system 98% cpu 0.301 total
1599
1600 It is still recommended to use ``fmt/core.h`` instead of ``fmt/format.h`` but
1601 the compile time difference is now smaller. Thanks
1602 `@alex3d <https://github.com/alex3d>`_ for the suggestion.
1603
1604 * Named arguments are now stored on stack (no dynamic memory allocations) and
1605 the compiled code is more compact and efficient. For example
1606
1607 .. code:: c++
1608
1609 #include <fmt/core.h>
1610
1611 int main() {
1612 fmt::print("The answer is {answer}\n", fmt::arg("answer", 42));
1613 }
1614
1615 compiles to just (`godbolt <https://godbolt.org/z/NcfEp_>`__)
1616
1617 .. code:: asm
1618
1619 .LC0:
1620 .string "answer"
1621 .LC1:
1622 .string "The answer is {answer}\n"
1623 main:
1624 sub rsp, 56
1625 mov edi, OFFSET FLAT:.LC1
1626 mov esi, 23
1627 movabs rdx, 4611686018427387905
1628 lea rax, [rsp+32]
1629 lea rcx, [rsp+16]
1630 mov QWORD PTR [rsp+8], 1
1631 mov QWORD PTR [rsp], rax
1632 mov DWORD PTR [rsp+16], 42
1633 mov QWORD PTR [rsp+32], OFFSET FLAT:.LC0
1634 mov DWORD PTR [rsp+40], 0
1635 call fmt::v6::vprint(fmt::v6::basic_string_view<char>,
1636 fmt::v6::format_args)
1637 xor eax, eax
1638 add rsp, 56
1639 ret
1640
1641 .L.str.1:
1642 .asciz "answer"
1643
1644 * Implemented compile-time checks for dynamic width and precision
1645 (`#1614 <https://github.com/fmtlib/fmt/issues/1614>`_):
1646
1647 .. code:: c++
1648
1649 #include <fmt/format.h>
1650
1651 int main() {
1652 fmt::print(FMT_STRING("{0:{1}}"), 42);
1653 }
1654
1655 now gives a compilation error because argument 1 doesn't exist::
1656
1657 In file included from test.cc:1:
1658 include/fmt/format.h:2726:27: error: constexpr variable 'invalid_format' must be
1659 initialized by a constant expression
1660 FMT_CONSTEXPR_DECL bool invalid_format =
1661 ^
1662 ...
1663 include/fmt/core.h:569:26: note: in call to
1664 '&checker(s, {}).context_->on_error(&"argument not found"[0])'
1665 if (id >= num_args_) on_error("argument not found");
1666 ^
1667
1668 * Added sentinel support to ``fmt::join``
1669 (`#1689 <https://github.com/fmtlib/fmt/pull/1689>`_)
1670
1671 .. code:: c++
1672
1673 struct zstring_sentinel {};
1674 bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; }
1675 bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; }
1676
1677 struct zstring {
1678 const char* p;
1679 const char* begin() const { return p; }
1680 zstring_sentinel end() const { return {}; }
1681 };
1682
1683 auto s = fmt::format("{}", fmt::join(zstring{"hello"}, "_"));
1684 // s == "h_e_l_l_o"
1685
1686 Thanks `@BRevzin (Barry Revzin) <https://github.com/BRevzin>`_.
1687
1688 * Added support for named arguments, ``clear`` and ``reserve`` to
1689 ``dynamic_format_arg_store``
1690 (`#1655 <https://github.com/fmtlib/fmt/issues/1655>`_,
1691 `#1663 <https://github.com/fmtlib/fmt/pull/1663>`_,
1692 `#1674 <https://github.com/fmtlib/fmt/pull/1674>`_,
1693 `#1677 <https://github.com/fmtlib/fmt/pull/1677>`_).
1694 Thanks `@vsolontsov-ll (Vladimir Solontsov)
1695 <https://github.com/vsolontsov-ll>`_.
1696
1697 * Added support for the ``'c'`` format specifier to integral types for
1698 compatibility with ``std::format``
1699 (`#1652 <https://github.com/fmtlib/fmt/issues/1652>`_).
1700
1701 * Replaced the ``'n'`` format specifier with ``'L'`` for compatibility with
1702 ``std::format`` (`#1624 <https://github.com/fmtlib/fmt/issues/1624>`_).
1703 The ``'n'`` specifier can be enabled via the ``FMT_DEPRECATED_N_SPECIFIER``
1704 macro.
1705
1706 * The ``'='`` format specifier is now disabled by default for compatibility with
1707 ``std::format``. It can be enabled via the ``FMT_DEPRECATED_NUMERIC_ALIGN``
1708 macro.
1709
1710 * Removed the following deprecated APIs:
1711
1712 * ``FMT_STRING_ALIAS`` and ``fmt`` macros - replaced by ``FMT_STRING``
1713 * ``fmt::basic_string_view::char_type`` - replaced by
1714 ``fmt::basic_string_view::value_type``
1715 * ``convert_to_int``
1716 * ``format_arg_store::types``
1717 * ``*parse_context`` - replaced by ``*format_parse_context``
1718 * ``FMT_DEPRECATED_INCLUDE_OS``
1719 * ``FMT_DEPRECATED_PERCENT`` - incompatible with ``std::format``
1720 * ``*writer`` - replaced by compiled format API
1721
1722 * Renamed the ``internal`` namespace to ``detail``
1723 (`#1538 <https://github.com/fmtlib/fmt/issues/1538>`_). The former is still
1724 provided as an alias if the ``FMT_USE_INTERNAL`` macro is defined.
1725
1726 * Improved compatibility between ``fmt::printf`` with the standard specs
1727 (`#1595 <https://github.com/fmtlib/fmt/issues/1595>`_,
1728 `#1682 <https://github.com/fmtlib/fmt/pull/1682>`_,
1729 `#1683 <https://github.com/fmtlib/fmt/pull/1683>`_,
1730 `#1687 <https://github.com/fmtlib/fmt/pull/1687>`_,
1731 `#1699 <https://github.com/fmtlib/fmt/pull/1699>`_).
1732 Thanks `@rimathia <https://github.com/rimathia>`_.
1733
1734 * Fixed handling of ``operator<<`` overloads that use ``copyfmt``
1735 (`#1666 <https://github.com/fmtlib/fmt/issues/1666>`_).
1736
1737 * Added the ``FMT_OS`` CMake option to control inclusion of OS-specific APIs
1738 in the fmt target. This can be useful for embedded platforms
1739 (`#1654 <https://github.com/fmtlib/fmt/issues/1654>`_,
1740 `#1656 <https://github.com/fmtlib/fmt/pull/1656>`_).
1741 Thanks `@kwesolowski (Krzysztof Wesolowski)
1742 <https://github.com/kwesolowski>`_.
1743
1744 * Replaced ``FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION`` with the ``FMT_FUZZ``
1745 macro to prevent interferring with fuzzing of projects using {fmt}
1746 (`#1650 <https://github.com/fmtlib/fmt/pull/1650>`_).
1747 Thanks `@asraa (Asra Ali) <https://github.com/asraa>`_.
1748
1749 * Fixed compatibility with emscripten
1750 (`#1636 <https://github.com/fmtlib/fmt/issues/1636>`_,
1751 `#1637 <https://github.com/fmtlib/fmt/pull/1637>`_).
1752 Thanks `@ArthurSonzogni (Arthur Sonzogni)
1753 <https://github.com/ArthurSonzogni>`_.
1754
1755 * Improved documentation
1756 (`#704 <https://github.com/fmtlib/fmt/issues/704>`_,
1757 `#1643 <https://github.com/fmtlib/fmt/pull/1643>`_,
1758 `#1660 <https://github.com/fmtlib/fmt/pull/1660>`_,
1759 `#1681 <https://github.com/fmtlib/fmt/pull/1681>`_,
1760 `#1691 <https://github.com/fmtlib/fmt/pull/1691>`_,
1761 `#1706 <https://github.com/fmtlib/fmt/pull/1706>`_,
1762 `#1714 <https://github.com/fmtlib/fmt/pull/1714>`_,
1763 `#1721 <https://github.com/fmtlib/fmt/pull/1721>`_,
1764 `#1739 <https://github.com/fmtlib/fmt/pull/1739>`_,
1765 `#1740 <https://github.com/fmtlib/fmt/pull/1740>`_,
1766 `#1741 <https://github.com/fmtlib/fmt/pull/1741>`_,
1767 `#1751 <https://github.com/fmtlib/fmt/pull/1751>`_).
1768 Thanks `@senior7515 (Alexander Gallego) <https://github.com/senior7515>`_,
1769 `@lsr0 (Lindsay Roberts) <https://github.com/lsr0>`_,
1770 `@puetzk (Kevin Puetz) <https://github.com/puetzk>`_,
1771 `@fpelliccioni (Fernando Pelliccioni) <https://github.com/fpelliccioni>`_,
1772 Alexey Kuzmenko, `@jelly (jelle van der Waa) <https://github.com/jelly>`_,
1773 `@claremacrae (Clare Macrae) <https://github.com/claremacrae>`_,
1774 `@jiapengwen (文佳鹏) <https://github.com/jiapengwen>`_,
1775 `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
1776 `@alexey-milovidov <https://github.com/alexey-milovidov>`_.
1777
1778 * Implemented various build configuration fixes and improvements
1779 (`#1603 <https://github.com/fmtlib/fmt/pull/1603>`_,
1780 `#1657 <https://github.com/fmtlib/fmt/pull/1657>`_,
1781 `#1702 <https://github.com/fmtlib/fmt/pull/1702>`_,
1782 `#1728 <https://github.com/fmtlib/fmt/pull/1728>`_).
1783 Thanks `@scramsby (Scott Ramsby) <https://github.com/scramsby>`_,
1784 `@jtojnar (Jan Tojnar) <https://github.com/jtojnar>`_,
1785 `@orivej (Orivej Desh) <https://github.com/orivej>`_,
1786 `@flagarde <https://github.com/flagarde>`_.
1787
1788 * Fixed various warnings and compilation issues
1789 (`#1616 <https://github.com/fmtlib/fmt/pull/1616>`_,
1790 `#1620 <https://github.com/fmtlib/fmt/issues/1620>`_,
1791 `#1622 <https://github.com/fmtlib/fmt/issues/1622>`_,
1792 `#1625 <https://github.com/fmtlib/fmt/issues/1625>`_,
1793 `#1627 <https://github.com/fmtlib/fmt/pull/1627>`_,
1794 `#1628 <https://github.com/fmtlib/fmt/issues/1628>`_,
1795 `#1629 <https://github.com/fmtlib/fmt/pull/1629>`_,
1796 `#1631 <https://github.com/fmtlib/fmt/issues/1631>`_,
1797 `#1633 <https://github.com/fmtlib/fmt/pull/1633>`_,
1798 `#1649 <https://github.com/fmtlib/fmt/pull/1649>`_,
1799 `#1658 <https://github.com/fmtlib/fmt/issues/1658>`_,
1800 `#1661 <https://github.com/fmtlib/fmt/pull/1661>`_,
1801 `#1667 <https://github.com/fmtlib/fmt/pull/1667>`_,
1802 `#1668 <https://github.com/fmtlib/fmt/issues/1668>`_,
1803 `#1669 <https://github.com/fmtlib/fmt/pull/1669>`_,
1804 `#1692 <https://github.com/fmtlib/fmt/issues/1692>`_,
1805 `#1696 <https://github.com/fmtlib/fmt/pull/1696>`_,
1806 `#1697 <https://github.com/fmtlib/fmt/pull/1697>`_,
1807 `#1707 <https://github.com/fmtlib/fmt/issues/1707>`_,
1808 `#1712 <https://github.com/fmtlib/fmt/pull/1712>`_,
1809 `#1716 <https://github.com/fmtlib/fmt/pull/1716>`_,
1810 `#1722 <https://github.com/fmtlib/fmt/pull/1722>`_,
1811 `#1724 <https://github.com/fmtlib/fmt/issues/1724>`_,
1812 `#1729 <https://github.com/fmtlib/fmt/pull/1729>`_,
1813 `#1738 <https://github.com/fmtlib/fmt/pull/1738>`_,
1814 `#1742 <https://github.com/fmtlib/fmt/issues/1742>`_,
1815 `#1743 <https://github.com/fmtlib/fmt/issues/1743>`_,
1816 `#1744 <https://github.com/fmtlib/fmt/pull/1744>`_,
1817 `#1747 <https://github.com/fmtlib/fmt/issues/1747>`_,
1818 `#1750 <https://github.com/fmtlib/fmt/pull/1750>`_).
1819 Thanks `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
1820 `@gabime (Gabi Melman) <https://github.com/gabime>`_,
1821 `@johnor (Johan) <https://github.com/johnor>`_,
1822 `@Kurkin (Dmitry Kurkin) <https://github.com/Kurkin>`_,
1823 `@invexed (James Beach) <https://github.com/invexed>`_,
1824 `@peterbell10 <https://github.com/peterbell10>`_,
1825 `@daixtrose (Markus Werle) <https://github.com/daixtrose>`_,
1826 `@petrutlucian94 (Lucian Petrut) <https://github.com/petrutlucian94>`_,
1827 `@Neargye (Daniil Goncharov) <https://github.com/Neargye>`_,
1828 `@ambitslix (Attila M. Szilagyi) <https://github.com/ambitslix>`_,
1829 `@gabime (Gabi Melman) <https://github.com/gabime>`_,
1830 `@erthink (Leonid Yuriev) <https://github.com/erthink>`_,
1831 `@tohammer (Tobias Hammer) <https://github.com/tohammer>`_,
1832 `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_.
1833
1834 6.2.1 - 2020-05-09
1835 ------------------
1836
1837 * Fixed ostream support in ``sprintf``
1838 (`#1631 <https://github.com/fmtlib/fmt/issues/1631>`_).
1839
1840 * Fixed type detection when using implicit conversion to ``string_view`` and
1841 ostream ``operator<<`` inconsistently
1842 (`#1662 <https://github.com/fmtlib/fmt/issues/1662>`_).
1843
1844 6.2.0 - 2020-04-05
1845 ------------------
1846
1847 * Improved error reporting when trying to format an object of a non-formattable
1848 type:
1849
1850 .. code:: c++
1851
1852 fmt::format("{}", S());
1853
1854 now gives::
1855
1856 include/fmt/core.h:1015:5: error: static_assert failed due to requirement
1857 'formattable' "Cannot format argument. To make type T formattable provide a
1858 formatter<T> specialization:
1859 https://fmt.dev/latest/api.html#formatting-user-defined-types"
1860 static_assert(
1861 ^
1862 ...
1863 note: in instantiation of function template specialization
1864 'fmt::v6::format<char [3], S, char>' requested here
1865 fmt::format("{}", S());
1866 ^
1867
1868 if ``S`` is not formattable.
1869
1870 * Reduced the library size by ~10%.
1871
1872 * Always print decimal point if ``#`` is specified
1873 (`#1476 <https://github.com/fmtlib/fmt/issues/1476>`_,
1874 `#1498 <https://github.com/fmtlib/fmt/issues/1498>`_):
1875
1876 .. code:: c++
1877
1878 fmt::print("{:#.0f}", 42.0);
1879
1880 now prints ``42.``
1881
1882 * Implemented the ``'L'`` specifier for locale-specific numeric formatting to
1883 improve compatibility with ``std::format``. The ``'n'`` specifier is now
1884 deprecated and will be removed in the next major release.
1885
1886 * Moved OS-specific APIs such as ``windows_error`` from ``fmt/format.h`` to
1887 ``fmt/os.h``. You can define ``FMT_DEPRECATED_INCLUDE_OS`` to automatically
1888 include ``fmt/os.h`` from ``fmt/format.h`` for compatibility but this will be
1889 disabled in the next major release.
1890
1891 * Added precision overflow detection in floating-point formatting.
1892
1893 * Implemented detection of invalid use of ``fmt::arg``.
1894
1895 * Used ``type_identity`` to block unnecessary template argument deduction.
1896 Thanks Tim Song.
1897
1898 * Improved UTF-8 handling
1899 (`#1109 <https://github.com/fmtlib/fmt/issues/1109>`_):
1900
1901 .. code:: c++
1902
1903 fmt::print("┌{0:─^{2}}┐\n"
1904 "│{1: ^{2}}│\n"
1905 "└{0:─^{2}}┘\n", "", "Привет, мир!", 20);
1906
1907 now prints::
1908
1909 ┌────────────────────┐
1910 │ Привет, мир! │
1911 └────────────────────┘
1912
1913 on systems that support Unicode.
1914
1915 * Added experimental dynamic argument storage
1916 (`#1170 <https://github.com/fmtlib/fmt/issues/1170>`_,
1917 `#1584 <https://github.com/fmtlib/fmt/pull/1584>`_):
1918
1919 .. code:: c++
1920
1921 fmt::dynamic_format_arg_store<fmt::format_context> store;
1922 store.push_back("answer");
1923 store.push_back(42);
1924 fmt::vprint("The {} is {}.\n", store);
1925
1926 prints::
1927
1928 The answer is 42.
1929
1930 Thanks `@vsolontsov-ll (Vladimir Solontsov)
1931 <https://github.com/vsolontsov-ll>`_.
1932
1933 * Made ``fmt::join`` accept ``initializer_list``
1934 (`#1591 <https://github.com/fmtlib/fmt/pull/1591>`_).
1935 Thanks `@Rapotkinnik (Nikolay Rapotkin) <https://github.com/Rapotkinnik>`_.
1936
1937 * Fixed handling of empty tuples
1938 (`#1588 <https://github.com/fmtlib/fmt/issues/1588>`_).
1939
1940 * Fixed handling of output iterators in ``format_to_n``
1941 (`#1506 <https://github.com/fmtlib/fmt/issues/1506>`_).
1942
1943 * Fixed formatting of ``std::chrono::duration`` types to wide output
1944 (`#1533 <https://github.com/fmtlib/fmt/pull/1533>`_).
1945 Thanks `@zeffy (pilao) <https://github.com/zeffy>`_.
1946
1947 * Added const ``begin`` and ``end`` overload to buffers
1948 (`#1553 <https://github.com/fmtlib/fmt/pull/1553>`_).
1949 Thanks `@dominicpoeschko <https://github.com/dominicpoeschko>`_.
1950
1951 * Added the ability to disable floating-point formatting via ``FMT_USE_FLOAT``,
1952 ``FMT_USE_DOUBLE`` and ``FMT_USE_LONG_DOUBLE`` macros for extremely
1953 memory-constrained embedded system
1954 (`#1590 <https://github.com/fmtlib/fmt/pull/1590>`_).
1955 Thanks `@albaguirre (Alberto Aguirre) <https://github.com/albaguirre>`_.
1956
1957 * Made ``FMT_STRING`` work with ``constexpr`` ``string_view``
1958 (`#1589 <https://github.com/fmtlib/fmt/pull/1589>`_).
1959 Thanks `@scramsby (Scott Ramsby) <https://github.com/scramsby>`_.
1960
1961 * Implemented a minor optimization in the format string parser
1962 (`#1560 <https://github.com/fmtlib/fmt/pull/1560>`_).
1963 Thanks `@IkarusDeveloper <https://github.com/IkarusDeveloper>`_.
1964
1965 * Improved attribute detection
1966 (`#1469 <https://github.com/fmtlib/fmt/pull/1469>`_,
1967 `#1475 <https://github.com/fmtlib/fmt/pull/1475>`_,
1968 `#1576 <https://github.com/fmtlib/fmt/pull/1576>`_).
1969 Thanks `@federico-busato (Federico) <https://github.com/federico-busato>`_,
1970 `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_,
1971 `@refnum <https://github.com/refnum>`_.
1972
1973 * Improved documentation
1974 (`#1481 <https://github.com/fmtlib/fmt/pull/1481>`_,
1975 `#1523 <https://github.com/fmtlib/fmt/pull/1523>`_).
1976 Thanks `@JackBoosY (Jack·Boos·Yu) <https://github.com/JackBoosY>`_,
1977 `@imba-tjd (谭九鼎) <https://github.com/imba-tjd>`_.
1978
1979 * Fixed symbol visibility on Linux when compiling with ``-fvisibility=hidden``
1980 (`#1535 <https://github.com/fmtlib/fmt/pull/1535>`_).
1981 Thanks `@milianw (Milian Wolff) <https://github.com/milianw>`_.
1982
1983 * Implemented various build configuration fixes and improvements
1984 (`#1264 <https://github.com/fmtlib/fmt/issues/1264>`_,
1985 `#1460 <https://github.com/fmtlib/fmt/issues/1460>`_,
1986 `#1534 <https://github.com/fmtlib/fmt/pull/1534>`_,
1987 `#1536 <https://github.com/fmtlib/fmt/issues/1536>`_,
1988 `#1545 <https://github.com/fmtlib/fmt/issues/1545>`_,
1989 `#1546 <https://github.com/fmtlib/fmt/pull/1546>`_,
1990 `#1566 <https://github.com/fmtlib/fmt/issues/1566>`_,
1991 `#1582 <https://github.com/fmtlib/fmt/pull/1582>`_,
1992 `#1597 <https://github.com/fmtlib/fmt/issues/1597>`_,
1993 `#1598 <https://github.com/fmtlib/fmt/pull/1598>`_).
1994 Thanks `@ambitslix (Attila M. Szilagyi) <https://github.com/ambitslix>`_,
1995 `@jwillikers (Jordan Williams) <https://github.com/jwillikers>`_,
1996 `@stac47 (Laurent Stacul) <https://github.com/stac47>`_.
1997
1998 * Fixed various warnings and compilation issues
1999 (`#1433 <https://github.com/fmtlib/fmt/pull/1433>`_,
2000 `#1461 <https://github.com/fmtlib/fmt/issues/1461>`_,
2001 `#1470 <https://github.com/fmtlib/fmt/pull/1470>`_,
2002 `#1480 <https://github.com/fmtlib/fmt/pull/1480>`_,
2003 `#1485 <https://github.com/fmtlib/fmt/pull/1485>`_,
2004 `#1492 <https://github.com/fmtlib/fmt/pull/1492>`_,
2005 `#1493 <https://github.com/fmtlib/fmt/issues/1493>`_,
2006 `#1504 <https://github.com/fmtlib/fmt/issues/1504>`_,
2007 `#1505 <https://github.com/fmtlib/fmt/pull/1505>`_,
2008 `#1512 <https://github.com/fmtlib/fmt/pull/1512>`_,
2009 `#1515 <https://github.com/fmtlib/fmt/issues/1515>`_,
2010 `#1516 <https://github.com/fmtlib/fmt/pull/1516>`_,
2011 `#1518 <https://github.com/fmtlib/fmt/pull/1518>`_,
2012 `#1519 <https://github.com/fmtlib/fmt/pull/1519>`_,
2013 `#1520 <https://github.com/fmtlib/fmt/pull/1520>`_,
2014 `#1521 <https://github.com/fmtlib/fmt/pull/1521>`_,
2015 `#1522 <https://github.com/fmtlib/fmt/pull/1522>`_,
2016 `#1524 <https://github.com/fmtlib/fmt/issues/1524>`_,
2017 `#1530 <https://github.com/fmtlib/fmt/pull/1530>`_,
2018 `#1531 <https://github.com/fmtlib/fmt/issues/1531>`_,
2019 `#1532 <https://github.com/fmtlib/fmt/pull/1532>`_,
2020 `#1539 <https://github.com/fmtlib/fmt/issues/1539>`_,
2021 `#1547 <https://github.com/fmtlib/fmt/issues/1547>`_,
2022 `#1548 <https://github.com/fmtlib/fmt/issues/1548>`_,
2023 `#1554 <https://github.com/fmtlib/fmt/pull/1554>`_,
2024 `#1567 <https://github.com/fmtlib/fmt/issues/1567>`_,
2025 `#1568 <https://github.com/fmtlib/fmt/pull/1568>`_,
2026 `#1569 <https://github.com/fmtlib/fmt/pull/1569>`_,
2027 `#1571 <https://github.com/fmtlib/fmt/pull/1571>`_,
2028 `#1573 <https://github.com/fmtlib/fmt/pull/1573>`_,
2029 `#1575 <https://github.com/fmtlib/fmt/pull/1575>`_,
2030 `#1581 <https://github.com/fmtlib/fmt/pull/1581>`_,
2031 `#1583 <https://github.com/fmtlib/fmt/issues/1583>`_,
2032 `#1586 <https://github.com/fmtlib/fmt/issues/1586>`_,
2033 `#1587 <https://github.com/fmtlib/fmt/issues/1587>`_,
2034 `#1594 <https://github.com/fmtlib/fmt/issues/1594>`_,
2035 `#1596 <https://github.com/fmtlib/fmt/pull/1596>`_,
2036 `#1604 <https://github.com/fmtlib/fmt/issues/1604>`_,
2037 `#1606 <https://github.com/fmtlib/fmt/pull/1606>`_,
2038 `#1607 <https://github.com/fmtlib/fmt/issues/1607>`_,
2039 `#1609 <https://github.com/fmtlib/fmt/issues/1609>`_).
2040 Thanks `@marti4d (Chris Martin) <https://github.com/marti4d>`_,
2041 `@iPherian <https://github.com/iPherian>`_,
2042 `@parkertomatoes <https://github.com/parkertomatoes>`_,
2043 `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
2044 `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_,
2045 `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
2046 `@torsten48 <https://github.com/torsten48>`_,
2047 `@tohammer (Tobias Hammer) <https://github.com/tohammer>`_,
2048 `@lefticus (Jason Turner) <https://github.com/lefticus>`_,
2049 `@ryusakki (Haise) <https://github.com/ryusakki>`_,
2050 `@adnsv (Alex Denisov) <https://github.com/adnsv>`_,
2051 `@fghzxm <https://github.com/fghzxm>`_,
2052 `@refnum <https://github.com/refnum>`_,
2053 `@pramodk (Pramod Kumbhar) <https://github.com/pramodk>`_,
2054 `@Spirrwell <https://github.com/Spirrwell>`_,
2055 `@scramsby (Scott Ramsby) <https://github.com/scramsby>`_.
2056
2057 6.1.2 - 2019-12-11
2058 ------------------
2059
2060 * Fixed ABI compatibility with ``libfmt.so.6.0.0``
2061 (`#1471 <https://github.com/fmtlib/fmt/issues/1471>`_).
2062
2063 * Fixed handling types convertible to ``std::string_view``
2064 (`#1451 <https://github.com/fmtlib/fmt/pull/1451>`_).
2065 Thanks `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_.
2066
2067 * Made CUDA test an opt-in enabled via the ``FMT_CUDA_TEST`` CMake option.
2068
2069 * Fixed sign conversion warnings
2070 (`#1440 <https://github.com/fmtlib/fmt/pull/1440>`_).
2071 Thanks `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_.
2072
2073 6.1.1 - 2019-12-04
2074 ------------------
2075
2076 * Fixed shared library build on Windows
2077 (`#1443 <https://github.com/fmtlib/fmt/pull/1443>`_,
2078 `#1445 <https://github.com/fmtlib/fmt/issues/1445>`_,
2079 `#1446 <https://github.com/fmtlib/fmt/pull/1446>`_,
2080 `#1450 <https://github.com/fmtlib/fmt/issues/1450>`_).
2081 Thanks `@egorpugin (Egor Pugin) <https://github.com/egorpugin>`_,
2082 `@bbolli (Beat Bolli) <https://github.com/bbolli>`_.
2083
2084 * Added a missing decimal point in exponent notation with trailing zeros.
2085
2086 * Removed deprecated ``format_arg_store::TYPES``.
2087
2088 6.1.0 - 2019-12-01
2089 ------------------
2090
2091 * {fmt} now formats IEEE 754 ``float`` and ``double`` using the shortest decimal
2092 representation with correct rounding by default:
2093
2094 .. code:: c++
2095
2096 #include <cmath>
2097 #include <fmt/core.h>
2098
2099 int main() {
2100 fmt::print("{}", M_PI);
2101 }
2102
2103 prints ``3.141592653589793``.
2104
2105 * Made the fast binary to decimal floating-point formatter the default,
2106 simplified it and improved performance. {fmt} is now 15 times faster than
2107 libc++'s ``std::ostringstream``, 11 times faster than ``printf`` and 10%
2108 faster than double-conversion on `dtoa-benchmark
2109 <https://github.com/fmtlib/dtoa-benchmark>`_:
2110
2111 ================== ========= =======
2112 Function Time (ns) Speedup
2113 ================== ========= =======
2114 ostringstream 1,346.30 1.00x
2115 ostrstream 1,195.74 1.13x
2116 sprintf 995.08 1.35x
2117 doubleconv 99.10 13.59x
2118 fmt 88.34 15.24x
2119 ================== ========= =======
2120
2121 .. image:: https://user-images.githubusercontent.com/576385/
2122 69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png
2123
2124 * {fmt} no longer converts ``float`` arguments to ``double``. In particular this
2125 improves the default (shortest) representation of floats and makes
2126 ``fmt::format`` consistent with ``std::format`` specs
2127 (`#1336 <https://github.com/fmtlib/fmt/issues/1336>`_,
2128 `#1353 <https://github.com/fmtlib/fmt/issues/1353>`_,
2129 `#1360 <https://github.com/fmtlib/fmt/pull/1360>`_,
2130 `#1361 <https://github.com/fmtlib/fmt/pull/1361>`_):
2131
2132 .. code:: c++
2133
2134 fmt::print("{}", 0.1f);
2135
2136 prints ``0.1`` instead of ``0.10000000149011612``.
2137
2138 Thanks `@orivej (Orivej Desh) <https://github.com/orivej>`_.
2139
2140 * Made floating-point formatting output consistent with ``printf``/iostreams
2141 (`#1376 <https://github.com/fmtlib/fmt/issues/1376>`_,
2142 `#1417 <https://github.com/fmtlib/fmt/issues/1417>`_).
2143
2144 * Added support for 128-bit integers
2145 (`#1287 <https://github.com/fmtlib/fmt/pull/1287>`_):
2146
2147 .. code:: c++
2148
2149 fmt::print("{}", std::numeric_limits<__int128_t>::max());
2150
2151 prints ``170141183460469231731687303715884105727``.
2152
2153 Thanks `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_.
2154
2155 * The overload of ``print`` that takes ``text_style`` is now atomic, i.e. the
2156 output from different threads doesn't interleave
2157 (`#1351 <https://github.com/fmtlib/fmt/pull/1351>`_).
2158 Thanks `@tankiJong (Tanki Zhang) <https://github.com/tankiJong>`_.
2159
2160 * Made compile time in the header-only mode ~20% faster by reducing the number
2161 of template instantiations. ``wchar_t`` overload of ``vprint`` was moved from
2162 ``fmt/core.h`` to ``fmt/format.h``.
2163
2164 * Added an overload of ``fmt::join`` that works with tuples
2165 (`#1322 <https://github.com/fmtlib/fmt/issues/1322>`_,
2166 `#1330 <https://github.com/fmtlib/fmt/pull/1330>`_):
2167
2168 .. code:: c++
2169
2170 #include <tuple>
2171 #include <fmt/ranges.h>
2172
2173 int main() {
2174 std::tuple<char, int, float> t{'a', 1, 2.0f};
2175 fmt::print("{}", t);
2176 }
2177
2178 prints ``('a', 1, 2.0)``.
2179
2180 Thanks `@jeremyong (Jeremy Ong) <https://github.com/jeremyong>`_.
2181
2182 * Changed formatting of octal zero with prefix from "00" to "0":
2183
2184 .. code:: c++
2185
2186 fmt::print("{:#o}", 0);
2187
2188 prints ``0``.
2189
2190 * The locale is now passed to ostream insertion (``<<``) operators
2191 (`#1406 <https://github.com/fmtlib/fmt/pull/1406>`_):
2192
2193 .. code:: c++
2194
2195 #include <fmt/locale.h>
2196 #include <fmt/ostream.h>
2197
2198 struct S {
2199 double value;
2200 };
2201
2202 std::ostream& operator<<(std::ostream& os, S s) {
2203 return os << s.value;
2204 }
2205
2206 int main() {
2207 auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42});
2208 // s == "0,42"
2209 }
2210
2211 Thanks `@dlaugt (Daniel Laügt) <https://github.com/dlaugt>`_.
2212
2213 * Locale-specific number formatting now uses grouping
2214 (`#1393 <https://github.com/fmtlib/fmt/issues/1393>`_
2215 `#1394 <https://github.com/fmtlib/fmt/pull/1394>`_).
2216 Thanks `@skrdaniel <https://github.com/skrdaniel>`_.
2217
2218 * Fixed handling of types with deleted implicit rvalue conversion to
2219 ``const char**`` (`#1421 <https://github.com/fmtlib/fmt/issues/1421>`_):
2220
2221 .. code:: c++
2222
2223 struct mystring {
2224 operator const char*() const&;
2225 operator const char*() &;
2226 operator const char*() const&& = delete;
2227 operator const char*() && = delete;
2228 };
2229 mystring str;
2230 fmt::print("{}", str); // now compiles
2231
2232 * Enums are now mapped to correct underlying types instead of ``int``
2233 (`#1286 <https://github.com/fmtlib/fmt/pull/1286>`_).
2234 Thanks `@agmt (Egor Seredin) <https://github.com/agmt>`_.
2235
2236 * Enum classes are no longer implicitly converted to ``int``
2237 (`#1424 <https://github.com/fmtlib/fmt/issues/1424>`_).
2238
2239 * Added ``basic_format_parse_context`` for consistency with C++20
2240 ``std::format`` and deprecated ``basic_parse_context``.
2241
2242 * Fixed handling of UTF-8 in precision
2243 (`#1389 <https://github.com/fmtlib/fmt/issues/1389>`_,
2244 `#1390 <https://github.com/fmtlib/fmt/pull/1390>`_).
2245 Thanks `@tajtiattila (Attila Tajti) <https://github.com/tajtiattila>`_.
2246
2247 * {fmt} can now be installed on Linux, macOS and Windows with
2248 `Conda <https://docs.conda.io/en/latest/>`__ using its
2249 `conda-forge <https://conda-forge.org>`__
2250 `package <https://github.com/conda-forge/fmt-feedstock>`__
2251 (`#1410 <https://github.com/fmtlib/fmt/pull/1410>`_)::
2252
2253 conda install -c conda-forge fmt
2254
2255 Thanks `@tdegeus (Tom de Geus) <https://github.com/tdegeus>`_.
2256
2257 * Added a CUDA test (`#1285 <https://github.com/fmtlib/fmt/pull/1285>`_,
2258 `#1317 <https://github.com/fmtlib/fmt/pull/1317>`_).
2259 Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_ and
2260 `@risa2000 <https://github.com/risa2000>`_.
2261
2262 * Improved documentation (`#1276 <https://github.com/fmtlib/fmt/pull/1276>`_,
2263 `#1291 <https://github.com/fmtlib/fmt/issues/1291>`_,
2264 `#1296 <https://github.com/fmtlib/fmt/issues/1296>`_,
2265 `#1315 <https://github.com/fmtlib/fmt/pull/1315>`_,
2266 `#1332 <https://github.com/fmtlib/fmt/pull/1332>`_,
2267 `#1337 <https://github.com/fmtlib/fmt/pull/1337>`_,
2268 `#1395 <https://github.com/fmtlib/fmt/issues/1395>`_
2269 `#1418 <https://github.com/fmtlib/fmt/pull/1418>`_).
2270 Thanks
2271 `@waywardmonkeys (Bruce Mitchener) <https://github.com/waywardmonkeys>`_,
2272 `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_,
2273 `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_.
2274
2275 * Various code improvements
2276 (`#1358 <https://github.com/fmtlib/fmt/pull/1358>`_,
2277 `#1407 <https://github.com/fmtlib/fmt/pull/1407>`_).
2278 Thanks `@orivej (Orivej Desh) <https://github.com/orivej>`_,
2279 `@dpacbach (David P. Sicilia) <https://github.com/dpacbach>`_,
2280
2281 * Fixed compile-time format string checks for user-defined types
2282 (`#1292 <https://github.com/fmtlib/fmt/issues/1292>`_).
2283
2284 * Worked around a false positive in ``unsigned-integer-overflow`` sanitizer
2285 (`#1377 <https://github.com/fmtlib/fmt/issues/1377>`_).
2286
2287 * Fixed various warnings and compilation issues
2288 (`#1273 <https://github.com/fmtlib/fmt/issues/1273>`_,
2289 `#1278 <https://github.com/fmtlib/fmt/pull/1278>`_,
2290 `#1280 <https://github.com/fmtlib/fmt/pull/1280>`_,
2291 `#1281 <https://github.com/fmtlib/fmt/issues/1281>`_,
2292 `#1288 <https://github.com/fmtlib/fmt/issues/1288>`_,
2293 `#1290 <https://github.com/fmtlib/fmt/pull/1290>`_,
2294 `#1301 <https://github.com/fmtlib/fmt/pull/1301>`_,
2295 `#1305 <https://github.com/fmtlib/fmt/issues/1305>`_,
2296 `#1306 <https://github.com/fmtlib/fmt/issues/1306>`_,
2297 `#1309 <https://github.com/fmtlib/fmt/issues/1309>`_,
2298 `#1312 <https://github.com/fmtlib/fmt/pull/1312>`_,
2299 `#1313 <https://github.com/fmtlib/fmt/issues/1313>`_,
2300 `#1316 <https://github.com/fmtlib/fmt/issues/1316>`_,
2301 `#1319 <https://github.com/fmtlib/fmt/issues/1319>`_,
2302 `#1320 <https://github.com/fmtlib/fmt/pull/1320>`_,
2303 `#1326 <https://github.com/fmtlib/fmt/pull/1326>`_,
2304 `#1328 <https://github.com/fmtlib/fmt/pull/1328>`_,
2305 `#1344 <https://github.com/fmtlib/fmt/issues/1344>`_,
2306 `#1345 <https://github.com/fmtlib/fmt/pull/1345>`_,
2307 `#1347 <https://github.com/fmtlib/fmt/pull/1347>`_,
2308 `#1349 <https://github.com/fmtlib/fmt/pull/1349>`_,
2309 `#1354 <https://github.com/fmtlib/fmt/issues/1354>`_,
2310 `#1362 <https://github.com/fmtlib/fmt/issues/1362>`_,
2311 `#1366 <https://github.com/fmtlib/fmt/issues/1366>`_,
2312 `#1364 <https://github.com/fmtlib/fmt/pull/1364>`_,
2313 `#1370 <https://github.com/fmtlib/fmt/pull/1370>`_,
2314 `#1371 <https://github.com/fmtlib/fmt/pull/1371>`_,
2315 `#1385 <https://github.com/fmtlib/fmt/issues/1385>`_,
2316 `#1388 <https://github.com/fmtlib/fmt/issues/1388>`_,
2317 `#1397 <https://github.com/fmtlib/fmt/pull/1397>`_,
2318 `#1414 <https://github.com/fmtlib/fmt/pull/1414>`_,
2319 `#1416 <https://github.com/fmtlib/fmt/pull/1416>`_,
2320 `#1422 <https://github.com/fmtlib/fmt/issues/1422>`_
2321 `#1427 <https://github.com/fmtlib/fmt/pull/1427>`_,
2322 `#1431 <https://github.com/fmtlib/fmt/issues/1431>`_,
2323 `#1433 <https://github.com/fmtlib/fmt/pull/1433>`_).
2324 Thanks `@hhb <https://github.com/hhb>`_,
2325 `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
2326 `@gabime (Gabi Melman) <https://github.com/gabime>`_,
2327 `@neheb (Rosen Penev) <https://github.com/neheb>`_,
2328 `@vedranmiletic (Vedran Miletić) <https://github.com/vedranmiletic>`_,
2329 `@dkavolis (Daumantas Kavolis) <https://github.com/dkavolis>`_,
2330 `@mwinterb <https://github.com/mwinterb>`_,
2331 `@orivej (Orivej Desh) <https://github.com/orivej>`_,
2332 `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_
2333 `@leonklingele <https://github.com/leonklingele>`_,
2334 `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_,
2335 `@kent-tri <https://github.com/kent-tri>`_,
2336 `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_,
2337 `@marti4d (Chris Martin) <https://github.com/marti4d>`_.
2338
2339 6.0.0 - 2019-08-26
2340 ------------------
2341
2342 * Switched to the `MIT license
2343 <https://github.com/fmtlib/fmt/blob/5a4b24613ba16cc689977c3b5bd8274a3ba1dd1f/LICENSE.rst>`_
2344 with an optional exception that allows distributing binary code without
2345 attribution.
2346
2347 * Floating-point formatting is now locale-independent by default:
2348
2349 .. code:: c++
2350
2351 #include <locale>
2352 #include <fmt/core.h>
2353
2354 int main() {
2355 std::locale::global(std::locale("ru_RU.UTF-8"));
2356 fmt::print("value = {}", 4.2);
2357 }
2358
2359 prints "value = 4.2" regardless of the locale.
2360
2361 For locale-specific formatting use the ``n`` specifier:
2362
2363 .. code:: c++
2364
2365 std::locale::global(std::locale("ru_RU.UTF-8"));
2366 fmt::print("value = {:n}", 4.2);
2367
2368 prints "value = 4,2".
2369
2370 * Added an experimental Grisu floating-point formatting algorithm
2371 implementation (disabled by default). To enable it compile with the
2372 ``FMT_USE_GRISU`` macro defined to 1:
2373
2374 .. code:: c++
2375
2376 #define FMT_USE_GRISU 1
2377 #include <fmt/format.h>
2378
2379 auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu
2380
2381 With Grisu enabled, {fmt} is 13x faster than ``std::ostringstream`` (libc++)
2382 and 10x faster than ``sprintf`` on `dtoa-benchmark
2383 <https://github.com/fmtlib/dtoa-benchmark>`_ (`full results
2384 <https://fmt.dev/unknown_mac64_clang10.0.html>`_):
2385
2386 .. image:: https://user-images.githubusercontent.com/576385/
2387 54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg
2388
2389 * Separated formatting and parsing contexts for consistency with
2390 `C++20 std::format <http://eel.is/c++draft/format>`_, removing the
2391 undocumented ``basic_format_context::parse_context()`` function.
2392
2393 * Added `oss-fuzz <https://github.com/google/oss-fuzz>`_ support
2394 (`#1199 <https://github.com/fmtlib/fmt/pull/1199>`_).
2395 Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_.
2396
2397 * ``formatter`` specializations now always take precedence over ``operator<<``
2398 (`#952 <https://github.com/fmtlib/fmt/issues/952>`_):
2399
2400 .. code:: c++
2401
2402 #include <iostream>
2403 #include <fmt/ostream.h>
2404
2405 struct S {};
2406
2407 std::ostream& operator<<(std::ostream& os, S) {
2408 return os << 1;
2409 }
2410
2411 template <>
2412 struct fmt::formatter<S> : fmt::formatter<int> {
2413 auto format(S, format_context& ctx) {
2414 return formatter<int>::format(2, ctx);
2415 }
2416 };
2417
2418 int main() {
2419 std::cout << S() << "\n"; // prints 1 using operator<<
2420 fmt::print("{}\n", S()); // prints 2 using formatter
2421 }
2422
2423 * Introduced the experimental ``fmt::compile`` function that does format string
2424 compilation (`#618 <https://github.com/fmtlib/fmt/issues/618>`_,
2425 `#1169 <https://github.com/fmtlib/fmt/issues/1169>`_,
2426 `#1171 <https://github.com/fmtlib/fmt/pull/1171>`_):
2427
2428 .. code:: c++
2429
2430 #include <fmt/compile.h>
2431
2432 auto f = fmt::compile<int>("{}");
2433 std::string s = fmt::format(f, 42); // can be called multiple times to
2434 // format different values
2435 // s == "42"
2436
2437 It moves the cost of parsing a format string outside of the format function
2438 which can be beneficial when identically formatting many objects of the same
2439 types. Thanks `@stryku (Mateusz Janek) <https://github.com/stryku>`_.
2440
2441 * Added experimental ``%`` format specifier that formats floating-point values
2442 as percentages (`#1060 <https://github.com/fmtlib/fmt/pull/1060>`_,
2443 `#1069 <https://github.com/fmtlib/fmt/pull/1069>`_,
2444 `#1071 <https://github.com/fmtlib/fmt/pull/1071>`_):
2445
2446 .. code:: c++
2447
2448 auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%"
2449
2450 Thanks `@gawain-bolton (Gawain Bolton) <https://github.com/gawain-bolton>`_.
2451
2452 * Implemented precision for floating-point durations
2453 (`#1004 <https://github.com/fmtlib/fmt/issues/1004>`_,
2454 `#1012 <https://github.com/fmtlib/fmt/pull/1012>`_):
2455
2456 .. code:: c++
2457
2458 auto s = fmt::format("{:.1}", std::chrono::duration<double>(1.234));
2459 // s == 1.2s
2460
2461 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2462
2463 * Implemented ``chrono`` format specifiers ``%Q`` and ``%q`` that give the value
2464 and the unit respectively (`#1019 <https://github.com/fmtlib/fmt/pull/1019>`_):
2465
2466 .. code:: c++
2467
2468 auto value = fmt::format("{:%Q}", 42s); // value == "42"
2469 auto unit = fmt::format("{:%q}", 42s); // unit == "s"
2470
2471 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2472
2473 * Fixed handling of dynamic width in chrono formatter:
2474
2475 .. code:: c++
2476
2477 auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12);
2478 // ^ width argument index ^ width
2479 // s == "03:25:45 "
2480
2481 Thanks Howard Hinnant.
2482
2483 * Removed deprecated ``fmt/time.h``. Use ``fmt/chrono.h`` instead.
2484
2485 * Added ``fmt::format`` and ``fmt::vformat`` overloads that take ``text_style``
2486 (`#993 <https://github.com/fmtlib/fmt/issues/993>`_,
2487 `#994 <https://github.com/fmtlib/fmt/pull/994>`_):
2488
2489 .. code:: c++
2490
2491 #include <fmt/color.h>
2492
2493 std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),
2494 "The answer is {}.", 42);
2495
2496 Thanks `@Naios (Denis Blank) <https://github.com/Naios>`_.
2497
2498 * Removed the deprecated color API (``print_colored``). Use the new API, namely
2499 ``print`` overloads that take ``text_style`` instead.
2500
2501 * Made ``std::unique_ptr`` and ``std::shared_ptr`` formattable as pointers via
2502 ``fmt::ptr`` (`#1121 <https://github.com/fmtlib/fmt/pull/1121>`_):
2503
2504 .. code:: c++
2505
2506 std::unique_ptr<int> p = ...;
2507 fmt::print("{}", fmt::ptr(p)); // prints p as a pointer
2508
2509 Thanks `@sighingnow (Tao He) <https://github.com/sighingnow>`_.
2510
2511 * Made ``print`` and ``vprint`` report I/O errors
2512 (`#1098 <https://github.com/fmtlib/fmt/issues/1098>`_,
2513 `#1099 <https://github.com/fmtlib/fmt/pull/1099>`_).
2514 Thanks `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_.
2515
2516 * Marked deprecated APIs with the ``[[deprecated]]`` attribute and removed
2517 internal uses of deprecated APIs
2518 (`#1022 <https://github.com/fmtlib/fmt/pull/1022>`_).
2519 Thanks `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_.
2520
2521 * Modernized the codebase using more C++11 features and removing workarounds.
2522 Most importantly, ``buffer_context`` is now an alias template, so
2523 use ``buffer_context<T>`` instead of ``buffer_context<T>::type``.
2524 These features require GCC 4.8 or later.
2525
2526 * ``formatter`` specializations now always take precedence over implicit
2527 conversions to ``int`` and the undocumented ``convert_to_int`` trait
2528 is now deprecated.
2529
2530 * Moved the undocumented ``basic_writer``, ``writer``, and ``wwriter`` types
2531 to the ``internal`` namespace.
2532
2533 * Removed deprecated ``basic_format_context::begin()``. Use ``out()`` instead.
2534
2535 * Disallowed passing the result of ``join`` as an lvalue to prevent misuse.
2536
2537 * Refactored the undocumented structs that represent parsed format specifiers
2538 to simplify the API and allow multibyte fill.
2539
2540 * Moved SFINAE to template parameters to reduce symbol sizes.
2541
2542 * Switched to ``fputws`` for writing wide strings so that it's no longer
2543 required to call ``_setmode`` on Windows
2544 (`#1229 <https://github.com/fmtlib/fmt/issues/1229>`_,
2545 `#1243 <https://github.com/fmtlib/fmt/pull/1243>`_).
2546 Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_.
2547
2548 * Improved literal-based API
2549 (`#1254 <https://github.com/fmtlib/fmt/pull/1254>`_).
2550 Thanks `@sylveon (Charles Milette) <https://github.com/sylveon>`_.
2551
2552 * Added support for exotic platforms without ``uintptr_t`` such as IBM i
2553 (AS/400) which has 128-bit pointers and only 64-bit integers
2554 (`#1059 <https://github.com/fmtlib/fmt/issues/1059>`_).
2555
2556 * Added `Sublime Text syntax highlighting config
2557 <https://github.com/fmtlib/fmt/blob/master/support/C%2B%2B.sublime-syntax>`_
2558 (`#1037 <https://github.com/fmtlib/fmt/issues/1037>`_).
2559 Thanks `@Kronuz (Germán Méndez Bravo) <https://github.com/Kronuz>`_.
2560
2561 * Added the ``FMT_ENFORCE_COMPILE_STRING`` macro to enforce the use of
2562 compile-time format strings
2563 (`#1231 <https://github.com/fmtlib/fmt/pull/1231>`_).
2564 Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_.
2565
2566 * Stopped setting ``CMAKE_BUILD_TYPE`` if {fmt} is a subproject
2567 (`#1081 <https://github.com/fmtlib/fmt/issues/1081>`_).
2568
2569 * Various build improvements
2570 (`#1039 <https://github.com/fmtlib/fmt/pull/1039>`_,
2571 `#1078 <https://github.com/fmtlib/fmt/pull/1078>`_,
2572 `#1091 <https://github.com/fmtlib/fmt/pull/1091>`_,
2573 `#1103 <https://github.com/fmtlib/fmt/pull/1103>`_,
2574 `#1177 <https://github.com/fmtlib/fmt/pull/1177>`_).
2575 Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_,
2576 `@jasonszang (Jason Shuo Zang) <https://github.com/jasonszang>`_,
2577 `@olafhering (Olaf Hering) <https://github.com/olafhering>`_,
2578 `@Lecetem <https://github.com/Lectem>`_,
2579 `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_.
2580
2581 * Improved documentation
2582 (`#1049 <https://github.com/fmtlib/fmt/issues/1049>`_,
2583 `#1051 <https://github.com/fmtlib/fmt/pull/1051>`_,
2584 `#1083 <https://github.com/fmtlib/fmt/pull/1083>`_,
2585 `#1113 <https://github.com/fmtlib/fmt/pull/1113>`_,
2586 `#1114 <https://github.com/fmtlib/fmt/pull/1114>`_,
2587 `#1146 <https://github.com/fmtlib/fmt/issues/1146>`_,
2588 `#1180 <https://github.com/fmtlib/fmt/issues/1180>`_,
2589 `#1250 <https://github.com/fmtlib/fmt/pull/1250>`_,
2590 `#1252 <https://github.com/fmtlib/fmt/pull/1252>`_,
2591 `#1265 <https://github.com/fmtlib/fmt/pull/1265>`_).
2592 Thanks `@mikelui (Michael Lui) <https://github.com/mikelui>`_,
2593 `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_,
2594 `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_,
2595 `@jwakely (Jonathan Wakely) <https://github.com/jwakely>`_,
2596 `@kaisbe (Kais Ben Salah) <https://github.com/kaisbe>`_,
2597 `@sdebionne (Samuel Debionne) <https://github.com/sdebionne>`_.
2598
2599 * Fixed ambiguous formatter specialization in ``fmt/ranges.h``
2600 (`#1123 <https://github.com/fmtlib/fmt/issues/1123>`_).
2601
2602 * Fixed formatting of a non-empty ``std::filesystem::path`` which is an
2603 infinitely deep range of its components
2604 (`#1268 <https://github.com/fmtlib/fmt/issues/1268>`_).
2605
2606 * Fixed handling of general output iterators when formatting characters
2607 (`#1056 <https://github.com/fmtlib/fmt/issues/1056>`_,
2608 `#1058 <https://github.com/fmtlib/fmt/pull/1058>`_).
2609 Thanks `@abolz (Alexander Bolz) <https://github.com/abolz>`_.
2610
2611 * Fixed handling of output iterators in ``formatter`` specialization for
2612 ranges (`#1064 <https://github.com/fmtlib/fmt/issues/1064>`_).
2613
2614 * Fixed handling of exotic character types
2615 (`#1188 <https://github.com/fmtlib/fmt/issues/1188>`_).
2616
2617 * Made chrono formatting work with exceptions disabled
2618 (`#1062 <https://github.com/fmtlib/fmt/issues/1062>`_).
2619
2620 * Fixed DLL visibility issues
2621 (`#1134 <https://github.com/fmtlib/fmt/pull/1134>`_,
2622 `#1147 <https://github.com/fmtlib/fmt/pull/1147>`_).
2623 Thanks `@denchat <https://github.com/denchat>`_.
2624
2625 * Disabled the use of UDL template extension on GCC 9
2626 (`#1148 <https://github.com/fmtlib/fmt/issues/1148>`_).
2627
2628 * Removed misplaced ``format`` compile-time checks from ``printf``
2629 (`#1173 <https://github.com/fmtlib/fmt/issues/1173>`_).
2630
2631 * Fixed issues in the experimental floating-point formatter
2632 (`#1072 <https://github.com/fmtlib/fmt/issues/1072>`_,
2633 `#1129 <https://github.com/fmtlib/fmt/issues/1129>`_,
2634 `#1153 <https://github.com/fmtlib/fmt/issues/1153>`_,
2635 `#1155 <https://github.com/fmtlib/fmt/pull/1155>`_,
2636 `#1210 <https://github.com/fmtlib/fmt/issues/1210>`_,
2637 `#1222 <https://github.com/fmtlib/fmt/issues/1222>`_).
2638 Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_.
2639
2640 * Fixed bugs discovered by fuzzing or during fuzzing integration
2641 (`#1124 <https://github.com/fmtlib/fmt/issues/1124>`_,
2642 `#1127 <https://github.com/fmtlib/fmt/issues/1127>`_,
2643 `#1132 <https://github.com/fmtlib/fmt/issues/1132>`_,
2644 `#1135 <https://github.com/fmtlib/fmt/pull/1135>`_,
2645 `#1136 <https://github.com/fmtlib/fmt/issues/1136>`_,
2646 `#1141 <https://github.com/fmtlib/fmt/issues/1141>`_,
2647 `#1142 <https://github.com/fmtlib/fmt/issues/1142>`_,
2648 `#1178 <https://github.com/fmtlib/fmt/issues/1178>`_,
2649 `#1179 <https://github.com/fmtlib/fmt/issues/1179>`_,
2650 `#1194 <https://github.com/fmtlib/fmt/issues/1194>`_).
2651 Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_.
2652
2653 * Fixed building tests on FreeBSD and Hurd
2654 (`#1043 <https://github.com/fmtlib/fmt/issues/1043>`_).
2655 Thanks `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_.
2656
2657 * Fixed various warnings and compilation issues
2658 (`#998 <https://github.com/fmtlib/fmt/pull/998>`_,
2659 `#1006 <https://github.com/fmtlib/fmt/pull/1006>`_,
2660 `#1008 <https://github.com/fmtlib/fmt/issues/1008>`_,
2661 `#1011 <https://github.com/fmtlib/fmt/issues/1011>`_,
2662 `#1025 <https://github.com/fmtlib/fmt/issues/1025>`_,
2663 `#1027 <https://github.com/fmtlib/fmt/pull/1027>`_,
2664 `#1028 <https://github.com/fmtlib/fmt/pull/1028>`_,
2665 `#1029 <https://github.com/fmtlib/fmt/pull/1029>`_,
2666 `#1030 <https://github.com/fmtlib/fmt/pull/1030>`_,
2667 `#1031 <https://github.com/fmtlib/fmt/pull/1031>`_,
2668 `#1054 <https://github.com/fmtlib/fmt/pull/1054>`_,
2669 `#1063 <https://github.com/fmtlib/fmt/issues/1063>`_,
2670 `#1068 <https://github.com/fmtlib/fmt/pull/1068>`_,
2671 `#1074 <https://github.com/fmtlib/fmt/pull/1074>`_,
2672 `#1075 <https://github.com/fmtlib/fmt/pull/1075>`_,
2673 `#1079 <https://github.com/fmtlib/fmt/pull/1079>`_,
2674 `#1086 <https://github.com/fmtlib/fmt/pull/1086>`_,
2675 `#1088 <https://github.com/fmtlib/fmt/issues/1088>`_,
2676 `#1089 <https://github.com/fmtlib/fmt/pull/1089>`_,
2677 `#1094 <https://github.com/fmtlib/fmt/pull/1094>`_,
2678 `#1101 <https://github.com/fmtlib/fmt/issues/1101>`_,
2679 `#1102 <https://github.com/fmtlib/fmt/pull/1102>`_,
2680 `#1105 <https://github.com/fmtlib/fmt/issues/1105>`_,
2681 `#1107 <https://github.com/fmtlib/fmt/pull/1107>`_,
2682 `#1115 <https://github.com/fmtlib/fmt/issues/1115>`_,
2683 `#1117 <https://github.com/fmtlib/fmt/issues/1117>`_,
2684 `#1118 <https://github.com/fmtlib/fmt/issues/1118>`_,
2685 `#1120 <https://github.com/fmtlib/fmt/issues/1120>`_,
2686 `#1123 <https://github.com/fmtlib/fmt/issues/1123>`_,
2687 `#1139 <https://github.com/fmtlib/fmt/pull/1139>`_,
2688 `#1140 <https://github.com/fmtlib/fmt/issues/1140>`_,
2689 `#1143 <https://github.com/fmtlib/fmt/issues/1143>`_,
2690 `#1144 <https://github.com/fmtlib/fmt/pull/1144>`_,
2691 `#1150 <https://github.com/fmtlib/fmt/pull/1150>`_,
2692 `#1151 <https://github.com/fmtlib/fmt/pull/1151>`_,
2693 `#1152 <https://github.com/fmtlib/fmt/issues/1152>`_,
2694 `#1154 <https://github.com/fmtlib/fmt/issues/1154>`_,
2695 `#1156 <https://github.com/fmtlib/fmt/issues/1156>`_,
2696 `#1159 <https://github.com/fmtlib/fmt/pull/1159>`_,
2697 `#1175 <https://github.com/fmtlib/fmt/issues/1175>`_,
2698 `#1181 <https://github.com/fmtlib/fmt/issues/1181>`_,
2699 `#1186 <https://github.com/fmtlib/fmt/issues/1186>`_,
2700 `#1187 <https://github.com/fmtlib/fmt/pull/1187>`_,
2701 `#1191 <https://github.com/fmtlib/fmt/pull/1191>`_,
2702 `#1197 <https://github.com/fmtlib/fmt/issues/1197>`_,
2703 `#1200 <https://github.com/fmtlib/fmt/issues/1200>`_,
2704 `#1203 <https://github.com/fmtlib/fmt/issues/1203>`_,
2705 `#1205 <https://github.com/fmtlib/fmt/issues/1205>`_,
2706 `#1206 <https://github.com/fmtlib/fmt/pull/1206>`_,
2707 `#1213 <https://github.com/fmtlib/fmt/issues/1213>`_,
2708 `#1214 <https://github.com/fmtlib/fmt/issues/1214>`_,
2709 `#1217 <https://github.com/fmtlib/fmt/pull/1217>`_,
2710 `#1228 <https://github.com/fmtlib/fmt/issues/1228>`_,
2711 `#1230 <https://github.com/fmtlib/fmt/pull/1230>`_,
2712 `#1232 <https://github.com/fmtlib/fmt/issues/1232>`_,
2713 `#1235 <https://github.com/fmtlib/fmt/pull/1235>`_,
2714 `#1236 <https://github.com/fmtlib/fmt/pull/1236>`_,
2715 `#1240 <https://github.com/fmtlib/fmt/issues/1240>`_).
2716 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
2717 `@mwinterb <https://github.com/mwinterb>`_,
2718 `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_,
2719 `@morinmorin <https://github.com/morinmorin>`_,
2720 `@ricco19 (Brian Ricciardelli) <https://github.com/ricco19>`_,
2721 `@waywardmonkeys (Bruce Mitchener) <https://github.com/waywardmonkeys>`_,
2722 `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_,
2723 `@remyabel <https://github.com/remyabel>`_,
2724 `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_,
2725 `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
2726 `@rcane (Ronny Krüger) <https://github.com/rcane>`_,
2727 `@mocabe <https://github.com/mocabe>`_,
2728 `@denchat <https://github.com/denchat>`_,
2729 `@cjdb (Christopher Di Bella) <https://github.com/cjdb>`_,
2730 `@HazardyKnusperkeks (Björn Schäpers) <https://github.com/HazardyKnusperkeks>`_,
2731 `@vedranmiletic (Vedran Miletić) <https://github.com/vedranmiletic>`_,
2732 `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_,
2733 `@DaanDeMeyer (Daan De Meyer) <https://github.com/DaanDeMeyer>`_,
2734 `@starkmapper (Mark Stapper) <https://github.com/starkmapper>`_.
2735
2736 5.3.0 - 2018-12-28
2737 ------------------
2738
2739 * Introduced experimental chrono formatting support:
2740
2741 .. code:: c++
2742
2743 #include <fmt/chrono.h>
2744
2745 int main() {
2746 using namespace std::literals::chrono_literals;
2747 fmt::print("Default format: {} {}\n", 42s, 100ms);
2748 fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
2749 }
2750
2751 prints::
2752
2753 Default format: 42s 100ms
2754 strftime-like format: 03:15:30
2755
2756 * Added experimental support for emphasis (bold, italic, underline,
2757 strikethrough), colored output to a file stream, and improved colored
2758 formatting API
2759 (`#961 <https://github.com/fmtlib/fmt/pull/961>`_,
2760 `#967 <https://github.com/fmtlib/fmt/pull/967>`_,
2761 `#973 <https://github.com/fmtlib/fmt/pull/973>`_):
2762
2763 .. code:: c++
2764
2765 #include <fmt/color.h>
2766
2767 int main() {
2768 print(fg(fmt::color::crimson) | fmt::emphasis::bold,
2769 "Hello, {}!\n", "world");
2770 print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
2771 fmt::emphasis::underline, "Hello, {}!\n", "мир");
2772 print(fg(fmt::color::steel_blue) | fmt::emphasis::italic,
2773 "Hello, {}!\n", "世界");
2774 }
2775
2776 prints the following on modern terminals with RGB color support:
2777
2778 .. image:: https://user-images.githubusercontent.com/576385/
2779 50405788-b66e7500-076e-11e9-9592-7324d1f951d8.png
2780
2781 Thanks `@Rakete1111 (Nicolas) <https://github.com/Rakete1111>`_.
2782
2783 * Added support for 4-bit terminal colors
2784 (`#968 <https://github.com/fmtlib/fmt/issues/968>`_,
2785 `#974 <https://github.com/fmtlib/fmt/pull/974>`_)
2786
2787 .. code:: c++
2788
2789 #include <fmt/color.h>
2790
2791 int main() {
2792 print(fg(fmt::terminal_color::red), "stop\n");
2793 }
2794
2795 Note that these colors vary by terminal:
2796
2797 .. image:: https://user-images.githubusercontent.com/576385/
2798 50405925-dbfc7e00-0770-11e9-9b85-333fab0af9ac.png
2799
2800 Thanks `@Rakete1111 (Nicolas) <https://github.com/Rakete1111>`_.
2801
2802 * Parameterized formatting functions on the type of the format string
2803 (`#880 <https://github.com/fmtlib/fmt/issues/880>`_,
2804 `#881 <https://github.com/fmtlib/fmt/pull/881>`_,
2805 `#883 <https://github.com/fmtlib/fmt/pull/883>`_,
2806 `#885 <https://github.com/fmtlib/fmt/pull/885>`_,
2807 `#897 <https://github.com/fmtlib/fmt/pull/897>`_,
2808 `#920 <https://github.com/fmtlib/fmt/issues/920>`_).
2809 Any object of type ``S`` that has an overloaded ``to_string_view(const S&)``
2810 returning ``fmt::string_view`` can be used as a format string:
2811
2812 .. code:: c++
2813
2814 namespace my_ns {
2815 inline string_view to_string_view(const my_string& s) {
2816 return {s.data(), s.length()};
2817 }
2818 }
2819
2820 std::string message = fmt::format(my_string("The answer is {}."), 42);
2821
2822 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2823
2824 * Made ``std::string_view`` work as a format string
2825 (`#898 <https://github.com/fmtlib/fmt/pull/898>`_):
2826
2827 .. code:: c++
2828
2829 auto message = fmt::format(std::string_view("The answer is {}."), 42);
2830
2831 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2832
2833 * Added wide string support to compile-time format string checks
2834 (`#924 <https://github.com/fmtlib/fmt/pull/924>`_):
2835
2836 .. code:: c++
2837
2838 print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier
2839
2840 Thanks `@XZiar <https://github.com/XZiar>`_.
2841
2842 * Made colored print functions work with wide strings
2843 (`#867 <https://github.com/fmtlib/fmt/pull/867>`_):
2844
2845 .. code:: c++
2846
2847 #include <fmt/color.h>
2848
2849 int main() {
2850 print(fg(fmt::color::red), L"{}\n", 42);
2851 }
2852
2853 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2854
2855 * Introduced experimental Unicode support
2856 (`#628 <https://github.com/fmtlib/fmt/issues/628>`_,
2857 `#891 <https://github.com/fmtlib/fmt/pull/891>`_):
2858
2859 .. code:: c++
2860
2861 using namespace fmt::literals;
2862 auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u
2863
2864 * Improved locale support:
2865
2866 .. code:: c++
2867
2868 #include <fmt/locale.h>
2869
2870 struct numpunct : std::numpunct<char> {
2871 protected:
2872 char do_thousands_sep() const override { return '~'; }
2873 };
2874
2875 std::locale loc;
2876 auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567);
2877 // s == "1~234~567"
2878
2879 * Constrained formatting functions on proper iterator types
2880 (`#921 <https://github.com/fmtlib/fmt/pull/921>`_).
2881 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2882
2883 * Added ``make_printf_args`` and ``make_wprintf_args`` functions
2884 (`#934 <https://github.com/fmtlib/fmt/pull/934>`_).
2885 Thanks `@tnovotny <https://github.com/tnovotny>`_.
2886
2887 * Deprecated ``fmt::visit``, ``parse_context``, and ``wparse_context``.
2888 Use ``fmt::visit_format_arg``, ``format_parse_context``, and
2889 ``wformat_parse_context`` instead.
2890
2891 * Removed undocumented ``basic_fixed_buffer`` which has been superseded by the
2892 iterator-based API
2893 (`#873 <https://github.com/fmtlib/fmt/issues/873>`_,
2894 `#902 <https://github.com/fmtlib/fmt/pull/902>`_).
2895 Thanks `@superfunc (hollywood programmer) <https://github.com/superfunc>`_.
2896
2897 * Disallowed repeated leading zeros in an argument ID:
2898
2899 .. code:: c++
2900
2901 fmt::print("{000}", 42); // error
2902
2903 * Reintroduced support for gcc 4.4.
2904
2905 * Fixed compilation on platforms with exotic ``double``
2906 (`#878 <https://github.com/fmtlib/fmt/issues/878>`_).
2907
2908 * Improved documentation
2909 (`#164 <https://github.com/fmtlib/fmt/issues/164>`_,
2910 `#877 <https://github.com/fmtlib/fmt/issues/877>`_,
2911 `#901 <https://github.com/fmtlib/fmt/pull/901>`_,
2912 `#906 <https://github.com/fmtlib/fmt/pull/906>`_,
2913 `#979 <https://github.com/fmtlib/fmt/pull/979>`_).
2914 Thanks `@kookjr (Mathew Cucuzella) <https://github.com/kookjr>`_,
2915 `@DarkDimius (Dmitry Petrashko) <https://github.com/DarkDimius>`_,
2916 `@HecticSerenity <https://github.com/HecticSerenity>`_.
2917
2918 * Added pkgconfig support which makes it easier to consume the library from
2919 meson and other build systems
2920 (`#916 <https://github.com/fmtlib/fmt/pull/916>`_).
2921 Thanks `@colemickens (Cole Mickens) <https://github.com/colemickens>`_.
2922
2923 * Various build improvements
2924 (`#909 <https://github.com/fmtlib/fmt/pull/909>`_,
2925 `#926 <https://github.com/fmtlib/fmt/pull/926>`_,
2926 `#937 <https://github.com/fmtlib/fmt/pull/937>`_,
2927 `#953 <https://github.com/fmtlib/fmt/pull/953>`_,
2928 `#959 <https://github.com/fmtlib/fmt/pull/959>`_).
2929 Thanks `@tchaikov (Kefu Chai) <https://github.com/tchaikov>`_,
2930 `@luncliff (Park DongHa) <https://github.com/luncliff>`_,
2931 `@AndreasSchoenle (Andreas Schönle) <https://github.com/AndreasSchoenle>`_,
2932 `@hotwatermorning <https://github.com/hotwatermorning>`_,
2933 `@Zefz (JohanJansen) <https://github.com/Zefz>`_.
2934
2935 * Improved ``string_view`` construction performance
2936 (`#914 <https://github.com/fmtlib/fmt/pull/914>`_).
2937 Thanks `@gabime (Gabi Melman) <https://github.com/gabime>`_.
2938
2939 * Fixed non-matching char types
2940 (`#895 <https://github.com/fmtlib/fmt/pull/895>`_).
2941 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2942
2943 * Fixed ``format_to_n`` with ``std::back_insert_iterator``
2944 (`#913 <https://github.com/fmtlib/fmt/pull/913>`_).
2945 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
2946
2947 * Fixed locale-dependent formatting
2948 (`#905 <https://github.com/fmtlib/fmt/issues/905>`_).
2949
2950 * Fixed various compiler warnings and errors
2951 (`#882 <https://github.com/fmtlib/fmt/pull/882>`_,
2952 `#886 <https://github.com/fmtlib/fmt/pull/886>`_,
2953 `#933 <https://github.com/fmtlib/fmt/pull/933>`_,
2954 `#941 <https://github.com/fmtlib/fmt/pull/941>`_,
2955 `#931 <https://github.com/fmtlib/fmt/issues/931>`_,
2956 `#943 <https://github.com/fmtlib/fmt/pull/943>`_,
2957 `#954 <https://github.com/fmtlib/fmt/pull/954>`_,
2958 `#956 <https://github.com/fmtlib/fmt/pull/956>`_,
2959 `#962 <https://github.com/fmtlib/fmt/pull/962>`_,
2960 `#965 <https://github.com/fmtlib/fmt/issues/965>`_,
2961 `#977 <https://github.com/fmtlib/fmt/issues/977>`_,
2962 `#983 <https://github.com/fmtlib/fmt/pull/983>`_,
2963 `#989 <https://github.com/fmtlib/fmt/pull/989>`_).
2964 Thanks `@Luthaf (Guillaume Fraux) <https://github.com/Luthaf>`_,
2965 `@stevenhoving (Steven Hoving) <https://github.com/stevenhoving>`_,
2966 `@christinaa (Kristina Brooks) <https://github.com/christinaa>`_,
2967 `@lgritz (Larry Gritz) <https://github.com/lgritz>`_,
2968 `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
2969 `@0x8000-0000 (Sign Bit) <https://github.com/0x8000-0000>`_,
2970 `@liuping1997 <https://github.com/liuping1997>`_.
2971
2972 5.2.1 - 2018-09-21
2973 ------------------
2974
2975 * Fixed ``visit`` lookup issues on gcc 7 & 8
2976 (`#870 <https://github.com/fmtlib/fmt/pull/870>`_).
2977 Thanks `@medithe <https://github.com/medithe>`_.
2978
2979 * Fixed linkage errors on older gcc.
2980
2981 * Prevented ``fmt/range.h`` from specializing ``fmt::basic_string_view``
2982 (`#865 <https://github.com/fmtlib/fmt/issues/865>`_,
2983 `#868 <https://github.com/fmtlib/fmt/pull/868>`_).
2984 Thanks `@hhggit (dual) <https://github.com/hhggit>`_.
2985
2986 * Improved error message when formatting unknown types
2987 (`#872 <https://github.com/fmtlib/fmt/pull/872>`_).
2988 Thanks `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_,
2989
2990 * Disabled templated user-defined literals when compiled under nvcc
2991 (`#875 <https://github.com/fmtlib/fmt/pull/875>`_).
2992 Thanks `@CandyGumdrop (Candy Gumdrop) <https://github.com/CandyGumdrop>`_,
2993
2994 * Fixed ``format_to`` formatting to ``wmemory_buffer``
2995 (`#874 <https://github.com/fmtlib/fmt/issues/874>`_).
2996
2997 5.2.0 - 2018-09-13
2998 ------------------
2999
3000 * Optimized format string parsing and argument processing which resulted in up
3001 to 5x speed up on long format strings and significant performance boost on
3002 various benchmarks. For example, version 5.2 is 2.22x faster than 5.1 on
3003 decimal integer formatting with ``format_to`` (macOS, clang-902.0.39.2):
3004
3005 ================== ======= =======
3006 Method Time, s Speedup
3007 ================== ======= =======
3008 fmt::format 5.1 0.58
3009 fmt::format 5.2 0.35 1.66x
3010 fmt::format_to 5.1 0.51
3011 fmt::format_to 5.2 0.23 2.22x
3012 sprintf 0.71
3013 std::to_string 1.01
3014 std::stringstream 1.73
3015 ================== ======= =======
3016
3017 * Changed the ``fmt`` macro from opt-out to opt-in to prevent name collisions.
3018 To enable it define the ``FMT_STRING_ALIAS`` macro to 1 before including
3019 ``fmt/format.h``:
3020
3021 .. code:: c++
3022
3023 #define FMT_STRING_ALIAS 1
3024 #include <fmt/format.h>
3025 std::string answer = format(fmt("{}"), 42);
3026
3027 * Added compile-time format string checks to ``format_to`` overload that takes
3028 ``fmt::memory_buffer`` (`#783 <https://github.com/fmtlib/fmt/issues/783>`_):
3029
3030 .. code:: c++
3031
3032 fmt::memory_buffer buf;
3033 // Compile-time error: invalid type specifier.
3034 fmt::format_to(buf, fmt("{:d}"), "foo");
3035
3036 * Moved experimental color support to ``fmt/color.h`` and enabled the
3037 new API by default. The old API can be enabled by defining the
3038 ``FMT_DEPRECATED_COLORS`` macro.
3039
3040 * Added formatting support for types explicitly convertible to
3041 ``fmt::string_view``:
3042
3043 .. code:: c++
3044
3045 struct foo {
3046 explicit operator fmt::string_view() const { return "foo"; }
3047 };
3048 auto s = format("{}", foo());
3049
3050 In particular, this makes formatting function work with
3051 ``folly::StringPiece``.
3052
3053 * Implemented preliminary support for ``char*_t`` by replacing the ``format``
3054 function overloads with a single function template parameterized on the string
3055 type.
3056
3057 * Added support for dynamic argument lists
3058 (`#814 <https://github.com/fmtlib/fmt/issues/814>`_,
3059 `#819 <https://github.com/fmtlib/fmt/pull/819>`_).
3060 Thanks `@MikePopoloski (Michael Popoloski)
3061 <https://github.com/MikePopoloski>`_.
3062
3063 * Reduced executable size overhead for embedded targets using newlib nano by
3064 making locale dependency optional
3065 (`#839 <https://github.com/fmtlib/fmt/pull/839>`_).
3066 Thanks `@teajay-fr (Thomas Benard) <https://github.com/teajay-fr>`_.
3067
3068 * Keep ``noexcept`` specifier when exceptions are disabled
3069 (`#801 <https://github.com/fmtlib/fmt/issues/801>`_,
3070 `#810 <https://github.com/fmtlib/fmt/pull/810>`_).
3071 Thanks `@qis (Alexej Harm) <https://github.com/qis>`_.
3072
3073 * Fixed formatting of user-defined types providing ``operator<<`` with
3074 ``format_to_n``
3075 (`#806 <https://github.com/fmtlib/fmt/pull/806>`_).
3076 Thanks `@mkurdej (Marek Kurdej) <https://github.com/mkurdej>`_.
3077
3078 * Fixed dynamic linkage of new symbols
3079 (`#808 <https://github.com/fmtlib/fmt/issues/808>`_).
3080
3081 * Fixed global initialization issue
3082 (`#807 <https://github.com/fmtlib/fmt/issues/807>`_):
3083
3084 .. code:: c++
3085
3086 // This works on compilers with constexpr support.
3087 static const std::string answer = fmt::format("{}", 42);
3088
3089 * Fixed various compiler warnings and errors
3090 (`#804 <https://github.com/fmtlib/fmt/pull/804>`_,
3091 `#809 <https://github.com/fmtlib/fmt/issues/809>`_,
3092 `#811 <https://github.com/fmtlib/fmt/pull/811>`_,
3093 `#822 <https://github.com/fmtlib/fmt/issues/822>`_,
3094 `#827 <https://github.com/fmtlib/fmt/pull/827>`_,
3095 `#830 <https://github.com/fmtlib/fmt/issues/830>`_,
3096 `#838 <https://github.com/fmtlib/fmt/pull/838>`_,
3097 `#843 <https://github.com/fmtlib/fmt/issues/843>`_,
3098 `#844 <https://github.com/fmtlib/fmt/pull/844>`_,
3099 `#851 <https://github.com/fmtlib/fmt/issues/851>`_,
3100 `#852 <https://github.com/fmtlib/fmt/pull/852>`_,
3101 `#854 <https://github.com/fmtlib/fmt/pull/854>`_).
3102 Thanks `@henryiii (Henry Schreiner) <https://github.com/henryiii>`_,
3103 `@medithe <https://github.com/medithe>`_, and
3104 `@eliasdaler (Elias Daler) <https://github.com/eliasdaler>`_.
3105
3106 5.1.0 - 2018-07-05
3107 ------------------
3108
3109 * Added experimental support for RGB color output enabled with
3110 the ``FMT_EXTENDED_COLORS`` macro:
3111
3112 .. code:: c++
3113
3114 #define FMT_EXTENDED_COLORS
3115 #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined
3116 #include <fmt/format.h>
3117
3118 fmt::print(fmt::color::steel_blue, "Some beautiful text");
3119
3120 The old API (the ``print_colored`` and ``vprint_colored`` functions and the
3121 ``color`` enum) is now deprecated.
3122 (`#762 <https://github.com/fmtlib/fmt/issues/762>`_
3123 `#767 <https://github.com/fmtlib/fmt/pull/767>`_).
3124 thanks `@Remotion (Remo) <https://github.com/Remotion>`_.
3125
3126 * Added quotes to strings in ranges and tuples
3127 (`#766 <https://github.com/fmtlib/fmt/pull/766>`_).
3128 Thanks `@Remotion (Remo) <https://github.com/Remotion>`_.
3129
3130 * Made ``format_to`` work with ``basic_memory_buffer``
3131 (`#776 <https://github.com/fmtlib/fmt/issues/776>`_).
3132
3133 * Added ``vformat_to_n`` and ``wchar_t`` overload of ``format_to_n``
3134 (`#764 <https://github.com/fmtlib/fmt/issues/764>`_,
3135 `#769 <https://github.com/fmtlib/fmt/issues/769>`_).
3136
3137 * Made ``is_range`` and ``is_tuple_like`` part of public (experimental) API
3138 to allow specialization for user-defined types
3139 (`#751 <https://github.com/fmtlib/fmt/issues/751>`_,
3140 `#759 <https://github.com/fmtlib/fmt/pull/759>`_).
3141 Thanks `@drrlvn (Dror Levin) <https://github.com/drrlvn>`_.
3142
3143 * Added more compilers to continuous integration and increased ``FMT_PEDANTIC``
3144 warning levels
3145 (`#736 <https://github.com/fmtlib/fmt/pull/736>`_).
3146 Thanks `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_.
3147
3148 * Fixed compilation with MSVC 2013.
3149
3150 * Fixed handling of user-defined types in ``format_to``
3151 (`#793 <https://github.com/fmtlib/fmt/issues/793>`_).
3152
3153 * Forced linking of inline ``vformat`` functions into the library
3154 (`#795 <https://github.com/fmtlib/fmt/issues/795>`_).
3155
3156 * Fixed incorrect call to on_align in ``'{:}='``
3157 (`#750 <https://github.com/fmtlib/fmt/issues/750>`_).
3158
3159 * Fixed floating-point formatting to a non-back_insert_iterator with sign &
3160 numeric alignment specified
3161 (`#756 <https://github.com/fmtlib/fmt/issues/756>`_).
3162
3163 * Fixed formatting to an array with ``format_to_n``
3164 (`#778 <https://github.com/fmtlib/fmt/issues/778>`_).
3165
3166 * Fixed formatting of more than 15 named arguments
3167 (`#754 <https://github.com/fmtlib/fmt/issues/754>`_).
3168
3169 * Fixed handling of compile-time strings when including ``fmt/ostream.h``.
3170 (`#768 <https://github.com/fmtlib/fmt/issues/768>`_).
3171
3172 * Fixed various compiler warnings and errors
3173 (`#742 <https://github.com/fmtlib/fmt/issues/742>`_,
3174 `#748 <https://github.com/fmtlib/fmt/issues/748>`_,
3175 `#752 <https://github.com/fmtlib/fmt/issues/752>`_,
3176 `#770 <https://github.com/fmtlib/fmt/issues/770>`_,
3177 `#775 <https://github.com/fmtlib/fmt/pull/775>`_,
3178 `#779 <https://github.com/fmtlib/fmt/issues/779>`_,
3179 `#780 <https://github.com/fmtlib/fmt/pull/780>`_,
3180 `#790 <https://github.com/fmtlib/fmt/pull/790>`_,
3181 `#792 <https://github.com/fmtlib/fmt/pull/792>`_,
3182 `#800 <https://github.com/fmtlib/fmt/pull/800>`_).
3183 Thanks `@Remotion (Remo) <https://github.com/Remotion>`_,
3184 `@gabime (Gabi Melman) <https://github.com/gabime>`_,
3185 `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_,
3186 `@Dark-Passenger (Dhruv Paranjape) <https://github.com/Dark-Passenger>`_, and
3187 `@0x8000-0000 (Sign Bit) <https://github.com/0x8000-0000>`_.
3188
3189 5.0.0 - 2018-05-21
3190 ------------------
3191
3192 * Added a requirement for partial C++11 support, most importantly variadic
3193 templates and type traits, and dropped ``FMT_VARIADIC_*`` emulation macros.
3194 Variadic templates are available since GCC 4.4, Clang 2.9 and MSVC 18.0 (2013).
3195 For older compilers use {fmt} `version 4.x
3196 <https://github.com/fmtlib/fmt/releases/tag/4.1.0>`_ which continues to be
3197 maintained and works with C++98 compilers.
3198
3199 * Renamed symbols to follow standard C++ naming conventions and proposed a subset
3200 of the library for standardization in `P0645R2 Text Formatting
3201 <https://wg21.link/P0645>`_.
3202
3203 * Implemented ``constexpr`` parsing of format strings and `compile-time format
3204 string checks
3205 <https://fmt.dev/latest/api.html#compile-time-format-string-checks>`_. For
3206 example
3207
3208 .. code:: c++
3209
3210 #include <fmt/format.h>
3211
3212 std::string s = format(fmt("{:d}"), "foo");
3213
3214 gives a compile-time error because ``d`` is an invalid specifier for strings
3215 (`godbolt <https://godbolt.org/g/rnCy9Q>`__)::
3216
3217 ...
3218 <source>:4:19: note: in instantiation of function template specialization 'fmt::v5::format<S, char [4]>' requested here
3219 std::string s = format(fmt("{:d}"), "foo");
3220 ^
3221 format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression
3222 handler.on_error("invalid type specifier");
3223
3224 Compile-time checks require relaxed ``constexpr`` (C++14 feature) support. If
3225 the latter is not available, checks will be performed at runtime.
3226
3227 * Separated format string parsing and formatting in the extension API to enable
3228 compile-time format string processing. For example
3229
3230 .. code:: c++
3231
3232 struct Answer {};
3233
3234 namespace fmt {
3235 template <>
3236 struct formatter<Answer> {
3237 constexpr auto parse(parse_context& ctx) {
3238 auto it = ctx.begin();
3239 spec = *it;
3240 if (spec != 'd' && spec != 's')
3241 throw format_error("invalid specifier");
3242 return ++it;
3243 }
3244
3245 template <typename FormatContext>
3246 auto format(Answer, FormatContext& ctx) {
3247 return spec == 's' ?
3248 format_to(ctx.begin(), "{}", "fourty-two") :
3249 format_to(ctx.begin(), "{}", 42);
3250 }
3251
3252 char spec = 0;
3253 };
3254 }
3255
3256 std::string s = format(fmt("{:x}"), Answer());
3257
3258 gives a compile-time error due to invalid format specifier (`godbolt
3259 <https://godbolt.org/g/2jQ1Dv>`__)::
3260
3261 ...
3262 <source>:12:45: error: expression '<throw-expression>' is not a constant expression
3263 throw format_error("invalid specifier");
3264
3265 * Added `iterator support
3266 <https://fmt.dev/latest/api.html#output-iterator-support>`_:
3267
3268 .. code:: c++
3269
3270 #include <vector>
3271 #include <fmt/format.h>
3272
3273 std::vector<char> out;
3274 fmt::format_to(std::back_inserter(out), "{}", 42);
3275
3276 * Added the `format_to_n
3277 <https://fmt.dev/latest/api.html#_CPPv2N3fmt11format_to_nE8OutputItNSt6size_tE11string_viewDpRK4Args>`_
3278 function that restricts the output to the specified number of characters
3279 (`#298 <https://github.com/fmtlib/fmt/issues/298>`_):
3280
3281 .. code:: c++
3282
3283 char out[4];
3284 fmt::format_to_n(out, sizeof(out), "{}", 12345);
3285 // out == "1234" (without terminating '\0')
3286
3287 * Added the `formatted_size
3288 <https://fmt.dev/latest/api.html#_CPPv2N3fmt14formatted_sizeE11string_viewDpRK4Args>`_
3289 function for computing the output size:
3290
3291 .. code:: c++
3292
3293 #include <fmt/format.h>
3294
3295 auto size = fmt::formatted_size("{}", 12345); // size == 5
3296
3297 * Improved compile times by reducing dependencies on standard headers and
3298 providing a lightweight `core API <https://fmt.dev/latest/api.html#core-api>`_:
3299
3300 .. code:: c++
3301
3302 #include <fmt/core.h>
3303
3304 fmt::print("The answer is {}.", 42);
3305
3306 See `Compile time and code bloat
3307 <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_.
3308
3309 * Added the `make_format_args
3310 <https://fmt.dev/latest/api.html#_CPPv2N3fmt16make_format_argsEDpRK4Args>`_
3311 function for capturing formatting arguments:
3312
3313 .. code:: c++
3314
3315 // Prints formatted error message.
3316 void vreport_error(const char *format, fmt::format_args args) {
3317 fmt::print("Error: ");
3318 fmt::vprint(format, args);
3319 }
3320 template <typename... Args>
3321 void report_error(const char *format, const Args & ... args) {
3322 vreport_error(format, fmt::make_format_args(args...));
3323 }
3324
3325 * Added the ``make_printf_args`` function for capturing ``printf`` arguments
3326 (`#687 <https://github.com/fmtlib/fmt/issues/687>`_,
3327 `#694 <https://github.com/fmtlib/fmt/pull/694>`_).
3328 Thanks `@Kronuz (Germán Méndez Bravo) <https://github.com/Kronuz>`_.
3329
3330 * Added prefix ``v`` to non-variadic functions taking ``format_args`` to
3331 distinguish them from variadic ones:
3332
3333 .. code:: c++
3334
3335 std::string vformat(string_view format_str, format_args args);
3336
3337 template <typename... Args>
3338 std::string format(string_view format_str, const Args & ... args);
3339
3340 * Added experimental support for formatting ranges, containers and tuple-like
3341 types in ``fmt/ranges.h`` (`#735 <https://github.com/fmtlib/fmt/pull/735>`_):
3342
3343 .. code:: c++
3344
3345 #include <fmt/ranges.h>
3346
3347 std::vector<int> v = {1, 2, 3};
3348 fmt::print("{}", v); // prints {1, 2, 3}
3349
3350 Thanks `@Remotion (Remo) <https://github.com/Remotion>`_.
3351
3352 * Implemented ``wchar_t`` date and time formatting
3353 (`#712 <https://github.com/fmtlib/fmt/pull/712>`_):
3354
3355 .. code:: c++
3356
3357 #include <fmt/time.h>
3358
3359 std::time_t t = std::time(nullptr);
3360 auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t));
3361
3362 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
3363
3364 * Provided more wide string overloads
3365 (`#724 <https://github.com/fmtlib/fmt/pull/724>`_).
3366 Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
3367
3368 * Switched from a custom null-terminated string view class to ``string_view``
3369 in the format API and provided ``fmt::string_view`` which implements a subset
3370 of ``std::string_view`` API for pre-C++17 systems.
3371
3372 * Added support for ``std::experimental::string_view``
3373 (`#607 <https://github.com/fmtlib/fmt/pull/607>`_):
3374
3375 .. code:: c++
3376
3377 #include <fmt/core.h>
3378 #include <experimental/string_view>
3379
3380 fmt::print("{}", std::experimental::string_view("foo"));
3381
3382 Thanks `@virgiliofornazin (Virgilio Alexandre Fornazin)
3383 <https://github.com/virgiliofornazin>`__.
3384
3385 * Allowed mixing named and automatic arguments:
3386
3387 .. code:: c++
3388
3389 fmt::format("{} {two}", 1, fmt::arg("two", 2));
3390
3391 * Removed the write API in favor of the `format API
3392 <https://fmt.dev/latest/api.html#format-api>`_ with compile-time handling of
3393 format strings.
3394
3395 * Disallowed formatting of multibyte strings into a wide character target
3396 (`#606 <https://github.com/fmtlib/fmt/pull/606>`_).
3397
3398 * Improved documentation
3399 (`#515 <https://github.com/fmtlib/fmt/pull/515>`_,
3400 `#614 <https://github.com/fmtlib/fmt/issues/614>`_,
3401 `#617 <https://github.com/fmtlib/fmt/pull/617>`_,
3402 `#661 <https://github.com/fmtlib/fmt/pull/661>`_,
3403 `#680 <https://github.com/fmtlib/fmt/pull/680>`_).
3404 Thanks `@ibell (Ian Bell) <https://github.com/ibell>`_,
3405 `@mihaitodor (Mihai Todor) <https://github.com/mihaitodor>`_, and
3406 `@johnthagen <https://github.com/johnthagen>`_.
3407
3408 * Implemented more efficient handling of large number of format arguments.
3409
3410 * Introduced an inline namespace for symbol versioning.
3411
3412 * Added debug postfix ``d`` to the ``fmt`` library name
3413 (`#636 <https://github.com/fmtlib/fmt/issues/636>`_).
3414
3415 * Removed unnecessary ``fmt/`` prefix in includes
3416 (`#397 <https://github.com/fmtlib/fmt/pull/397>`_).
3417 Thanks `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_.
3418
3419 * Moved ``fmt/*.h`` to ``include/fmt/*.h`` to prevent irrelevant files and
3420 directories appearing on the include search paths when fmt is used as a
3421 subproject and moved source files to the ``src`` directory.
3422
3423 * Added qmake project file ``support/fmt.pro``
3424 (`#641 <https://github.com/fmtlib/fmt/pull/641>`_).
3425 Thanks `@cowo78 (Giuseppe Corbelli) <https://github.com/cowo78>`_.
3426
3427 * Added Gradle build file ``support/build.gradle``
3428 (`#649 <https://github.com/fmtlib/fmt/pull/649>`_).
3429 Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_.
3430
3431 * Removed ``FMT_CPPFORMAT`` CMake option.
3432
3433 * Fixed a name conflict with the macro ``CHAR_WIDTH`` in glibc
3434 (`#616 <https://github.com/fmtlib/fmt/pull/616>`_).
3435 Thanks `@aroig (Abdó Roig-Maranges) <https://github.com/aroig>`_.
3436
3437 * Fixed handling of nested braces in ``fmt::join``
3438 (`#638 <https://github.com/fmtlib/fmt/issues/638>`_).
3439
3440 * Added ``SOURCELINK_SUFFIX`` for compatibility with Sphinx 1.5
3441 (`#497 <https://github.com/fmtlib/fmt/pull/497>`_).
3442 Thanks `@ginggs (Graham Inggs) <https://github.com/ginggs>`_.
3443
3444 * Added a missing ``inline`` in the header-only mode
3445 (`#626 <https://github.com/fmtlib/fmt/pull/626>`_).
3446 Thanks `@aroig (Abdó Roig-Maranges) <https://github.com/aroig>`_.
3447
3448 * Fixed various compiler warnings
3449 (`#640 <https://github.com/fmtlib/fmt/pull/640>`_,
3450 `#656 <https://github.com/fmtlib/fmt/pull/656>`_,
3451 `#679 <https://github.com/fmtlib/fmt/pull/679>`_,
3452 `#681 <https://github.com/fmtlib/fmt/pull/681>`_,
3453 `#705 <https://github.com/fmtlib/fmt/pull/705>`__,
3454 `#715 <https://github.com/fmtlib/fmt/issues/715>`_,
3455 `#717 <https://github.com/fmtlib/fmt/pull/717>`_,
3456 `#720 <https://github.com/fmtlib/fmt/pull/720>`_,
3457 `#723 <https://github.com/fmtlib/fmt/pull/723>`_,
3458 `#726 <https://github.com/fmtlib/fmt/pull/726>`_,
3459 `#730 <https://github.com/fmtlib/fmt/pull/730>`_,
3460 `#739 <https://github.com/fmtlib/fmt/pull/739>`_).
3461 Thanks `@peterbell10 <https://github.com/peterbell10>`_,
3462 `@LarsGullik <https://github.com/LarsGullik>`_,
3463 `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_,
3464 `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_,
3465 `@christianparpart (Christian Parpart) <https://github.com/christianparpart>`_,
3466 `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
3467 and `@mwinterb <https://github.com/mwinterb>`_.
3468
3469 * Worked around an MSVC bug and fixed several warnings
3470 (`#653 <https://github.com/fmtlib/fmt/pull/653>`_).
3471 Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_.
3472
3473 * Worked around GCC bug 67371
3474 (`#682 <https://github.com/fmtlib/fmt/issues/682>`_).
3475
3476 * Fixed compilation with ``-fno-exceptions``
3477 (`#655 <https://github.com/fmtlib/fmt/pull/655>`_).
3478 Thanks `@chenxiaolong (Andrew Gunnerson) <https://github.com/chenxiaolong>`_.
3479
3480 * Made ``constexpr remove_prefix`` gcc version check tighter
3481 (`#648 <https://github.com/fmtlib/fmt/issues/648>`_).
3482
3483 * Renamed internal type enum constants to prevent collision with poorly written
3484 C libraries (`#644 <https://github.com/fmtlib/fmt/issues/644>`_).
3485
3486 * Added detection of ``wostream operator<<``
3487 (`#650 <https://github.com/fmtlib/fmt/issues/650>`_).
3488
3489 * Fixed compilation on OpenBSD
3490 (`#660 <https://github.com/fmtlib/fmt/pull/660>`_).
3491 Thanks `@hubslave <https://github.com/hubslave>`_.
3492
3493 * Fixed compilation on FreeBSD 12
3494 (`#732 <https://github.com/fmtlib/fmt/pull/732>`_).
3495 Thanks `@dankm <https://github.com/dankm>`_.
3496
3497 * Fixed compilation when there is a mismatch between ``-std`` options between
3498 the library and user code
3499 (`#664 <https://github.com/fmtlib/fmt/issues/664>`_).
3500
3501 * Fixed compilation with GCC 7 and ``-std=c++11``
3502 (`#734 <https://github.com/fmtlib/fmt/issues/734>`_).
3503
3504 * Improved generated binary code on GCC 7 and older
3505 (`#668 <https://github.com/fmtlib/fmt/issues/668>`_).
3506
3507 * Fixed handling of numeric alignment with no width
3508 (`#675 <https://github.com/fmtlib/fmt/issues/675>`_).
3509
3510 * Fixed handling of empty strings in UTF8/16 converters
3511 (`#676 <https://github.com/fmtlib/fmt/pull/676>`_).
3512 Thanks `@vgalka-sl (Vasili Galka) <https://github.com/vgalka-sl>`_.
3513
3514 * Fixed formatting of an empty ``string_view``
3515 (`#689 <https://github.com/fmtlib/fmt/issues/689>`_).
3516
3517 * Fixed detection of ``string_view`` on libc++
3518 (`#686 <https://github.com/fmtlib/fmt/issues/686>`_).
3519
3520 * Fixed DLL issues (`#696 <https://github.com/fmtlib/fmt/pull/696>`_).
3521 Thanks `@sebkoenig <https://github.com/sebkoenig>`_.
3522
3523 * Fixed compile checks for mixing narrow and wide strings
3524 (`#690 <https://github.com/fmtlib/fmt/issues/690>`_).
3525
3526 * Disabled unsafe implicit conversion to ``std::string``
3527 (`#729 <https://github.com/fmtlib/fmt/issues/729>`_).
3528
3529 * Fixed handling of reused format specs (as in ``fmt::join``) for pointers
3530 (`#725 <https://github.com/fmtlib/fmt/pull/725>`_).
3531 Thanks `@mwinterb <https://github.com/mwinterb>`_.
3532
3533 * Fixed installation of ``fmt/ranges.h``
3534 (`#738 <https://github.com/fmtlib/fmt/pull/738>`_).
3535 Thanks `@sv1990 <https://github.com/sv1990>`_.
3536
3537 4.1.0 - 2017-12-20
3538 ------------------
3539
3540 * Added ``fmt::to_wstring()`` in addition to ``fmt::to_string()``
3541 (`#559 <https://github.com/fmtlib/fmt/pull/559>`_).
3542 Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_.
3543
3544 * Added support for C++17 ``std::string_view``
3545 (`#571 <https://github.com/fmtlib/fmt/pull/571>`_ and
3546 `#578 <https://github.com/fmtlib/fmt/pull/578>`_).
3547 Thanks `@thelostt (Mário Feroldi) <https://github.com/thelostt>`_ and
3548 `@mwinterb <https://github.com/mwinterb>`_.
3549
3550 * Enabled stream exceptions to catch errors
3551 (`#581 <https://github.com/fmtlib/fmt/issues/581>`_).
3552 Thanks `@crusader-mike <https://github.com/crusader-mike>`_.
3553
3554 * Allowed formatting of class hierarchies with ``fmt::format_arg()``
3555 (`#547 <https://github.com/fmtlib/fmt/pull/547>`_).
3556 Thanks `@rollbear (Björn Fahller) <https://github.com/rollbear>`_.
3557
3558 * Removed limitations on character types
3559 (`#563 <https://github.com/fmtlib/fmt/pull/563>`_).
3560 Thanks `@Yelnats321 (Elnar Dakeshov) <https://github.com/Yelnats321>`_.
3561
3562 * Conditionally enabled use of ``std::allocator_traits``
3563 (`#583 <https://github.com/fmtlib/fmt/pull/583>`_).
3564 Thanks `@mwinterb <https://github.com/mwinterb>`_.
3565
3566 * Added support for ``const`` variadic member function emulation with
3567 ``FMT_VARIADIC_CONST`` (`#591 <https://github.com/fmtlib/fmt/pull/591>`_).
3568 Thanks `@ludekvodicka (Ludek Vodicka) <https://github.com/ludekvodicka>`_.
3569
3570 * Various bugfixes: bad overflow check, unsupported implicit type conversion
3571 when determining formatting function, test segfaults
3572 (`#551 <https://github.com/fmtlib/fmt/issues/551>`_), ill-formed macros
3573 (`#542 <https://github.com/fmtlib/fmt/pull/542>`_) and ambiguous overloads
3574 (`#580 <https://github.com/fmtlib/fmt/issues/580>`_).
3575 Thanks `@xylosper (Byoung-young Lee) <https://github.com/xylosper>`_.
3576
3577 * Prevented warnings on MSVC (`#605 <https://github.com/fmtlib/fmt/pull/605>`_,
3578 `#602 <https://github.com/fmtlib/fmt/pull/602>`_, and
3579 `#545 <https://github.com/fmtlib/fmt/pull/545>`_),
3580 clang (`#582 <https://github.com/fmtlib/fmt/pull/582>`_),
3581 GCC (`#573 <https://github.com/fmtlib/fmt/issues/573>`_),
3582 various conversion warnings (`#609 <https://github.com/fmtlib/fmt/pull/609>`_,
3583 `#567 <https://github.com/fmtlib/fmt/pull/567>`_,
3584 `#553 <https://github.com/fmtlib/fmt/pull/553>`_ and
3585 `#553 <https://github.com/fmtlib/fmt/pull/553>`_), and added ``override`` and
3586 ``[[noreturn]]`` (`#549 <https://github.com/fmtlib/fmt/pull/549>`_ and
3587 `#555 <https://github.com/fmtlib/fmt/issues/555>`_).
3588 Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_,
3589 `@virgiliofornazin (Virgilio Alexandre Fornazin)
3590 <https://gihtub.com/virgiliofornazin>`_,
3591 `@alexanderbock (Alexander Bock) <https://github.com/alexanderbock>`_,
3592 `@yumetodo <https://github.com/yumetodo>`_,
3593 `@VaderY (Császár Mátyás) <https://github.com/VaderY>`_,
3594 `@jpcima (JP Cimalando) <https://github.com/jpcima>`_,
3595 `@thelostt (Mário Feroldi) <https://github.com/thelostt>`_, and
3596 `@Manu343726 (Manu Sánchez) <https://github.com/Manu343726>`_.
3597
3598 * Improved CMake: Used ``GNUInstallDirs`` to set installation location
3599 (`#610 <https://github.com/fmtlib/fmt/pull/610>`_) and fixed warnings
3600 (`#536 <https://github.com/fmtlib/fmt/pull/536>`_ and
3601 `#556 <https://github.com/fmtlib/fmt/pull/556>`_).
3602 Thanks `@mikecrowe (Mike Crowe) <https://github.com/mikecrowe>`_,
3603 `@evgen231 <https://github.com/evgen231>`_ and
3604 `@henryiii (Henry Schreiner) <https://github.com/henryiii>`_.
3605
3606 4.0.0 - 2017-06-27
3607 ------------------
3608
3609 * Removed old compatibility headers ``cppformat/*.h`` and CMake options
3610 (`#527 <https://github.com/fmtlib/fmt/pull/527>`_).
3611 Thanks `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_.
3612
3613 * Added ``string.h`` containing ``fmt::to_string()`` as alternative to
3614 ``std::to_string()`` as well as other string writer functionality
3615 (`#326 <https://github.com/fmtlib/fmt/issues/326>`_ and
3616 `#441 <https://github.com/fmtlib/fmt/pull/441>`_):
3617
3618 .. code:: c++
3619
3620 #include "fmt/string.h"
3621
3622 std::string answer = fmt::to_string(42);
3623
3624 Thanks to `@glebov-andrey (Andrey Glebov)
3625 <https://github.com/glebov-andrey>`_.
3626
3627 * Moved ``fmt::printf()`` to new ``printf.h`` header and allowed ``%s`` as
3628 generic specifier (`#453 <https://github.com/fmtlib/fmt/pull/453>`_),
3629 made ``%.f`` more conformant to regular ``printf()``
3630 (`#490 <https://github.com/fmtlib/fmt/pull/490>`_), added custom writer
3631 support (`#476 <https://github.com/fmtlib/fmt/issues/476>`_) and implemented
3632 missing custom argument formatting
3633 (`#339 <https://github.com/fmtlib/fmt/pull/339>`_ and
3634 `#340 <https://github.com/fmtlib/fmt/pull/340>`_):
3635
3636 .. code:: c++
3637
3638 #include "fmt/printf.h"
3639
3640 // %s format specifier can be used with any argument type.
3641 fmt::printf("%s", 42);
3642
3643 Thanks `@mojoBrendan <https://github.com/mojoBrendan>`_,
3644 `@manylegged (Arthur Danskin) <https://github.com/manylegged>`_ and
3645 `@spacemoose (Glen Stark) <https://github.com/spacemoose>`_.
3646 See also `#360 <https://github.com/fmtlib/fmt/issues/360>`_,
3647 `#335 <https://github.com/fmtlib/fmt/issues/335>`_ and
3648 `#331 <https://github.com/fmtlib/fmt/issues/331>`_.
3649
3650 * Added ``container.h`` containing a ``BasicContainerWriter``
3651 to write to containers like ``std::vector``
3652 (`#450 <https://github.com/fmtlib/fmt/pull/450>`_).
3653 Thanks `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_.
3654
3655 * Added ``fmt::join()`` function that takes a range and formats
3656 its elements separated by a given string
3657 (`#466 <https://github.com/fmtlib/fmt/pull/466>`_):
3658
3659 .. code:: c++
3660
3661 #include "fmt/format.h"
3662
3663 std::vector<double> v = {1.2, 3.4, 5.6};
3664 // Prints "(+01.20, +03.40, +05.60)".
3665 fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", "));
3666
3667 Thanks `@olivier80 <https://github.com/olivier80>`_.
3668
3669 * Added support for custom formatting specifications to simplify customization
3670 of built-in formatting (`#444 <https://github.com/fmtlib/fmt/pull/444>`_).
3671 Thanks `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_.
3672 See also `#439 <https://github.com/fmtlib/fmt/issues/439>`_.
3673
3674 * Added ``fmt::format_system_error()`` for error code formatting
3675 (`#323 <https://github.com/fmtlib/fmt/issues/323>`_ and
3676 `#526 <https://github.com/fmtlib/fmt/pull/526>`_).
3677 Thanks `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_.
3678
3679 * Added thread-safe ``fmt::localtime()`` and ``fmt::gmtime()``
3680 as replacement for the standard version to ``time.h``
3681 (`#396 <https://github.com/fmtlib/fmt/pull/396>`_).
3682 Thanks `@codicodi <https://github.com/codicodi>`_.
3683
3684 * Internal improvements to ``NamedArg`` and ``ArgLists``
3685 (`#389 <https://github.com/fmtlib/fmt/pull/389>`_ and
3686 `#390 <https://github.com/fmtlib/fmt/pull/390>`_).
3687 Thanks `@chronoxor <https://github.com/chronoxor>`_.
3688
3689 * Fixed crash due to bug in ``FormatBuf``
3690 (`#493 <https://github.com/fmtlib/fmt/pull/493>`_).
3691 Thanks `@effzeh <https://github.com/effzeh>`_. See also
3692 `#480 <https://github.com/fmtlib/fmt/issues/480>`_ and
3693 `#491 <https://github.com/fmtlib/fmt/issues/491>`_.
3694
3695 * Fixed handling of wide strings in ``fmt::StringWriter``.
3696
3697 * Improved compiler error messages
3698 (`#357 <https://github.com/fmtlib/fmt/issues/357>`_).
3699
3700 * Fixed various warnings and issues with various compilers
3701 (`#494 <https://github.com/fmtlib/fmt/pull/494>`_,
3702 `#499 <https://github.com/fmtlib/fmt/pull/499>`_,
3703 `#483 <https://github.com/fmtlib/fmt/pull/483>`_,
3704 `#485 <https://github.com/fmtlib/fmt/pull/485>`_,
3705 `#482 <https://github.com/fmtlib/fmt/pull/482>`_,
3706 `#475 <https://github.com/fmtlib/fmt/pull/475>`_,
3707 `#473 <https://github.com/fmtlib/fmt/pull/473>`_ and
3708 `#414 <https://github.com/fmtlib/fmt/pull/414>`_).
3709 Thanks `@chronoxor <https://github.com/chronoxor>`_,
3710 `@zhaohuaxishi <https://github.com/zhaohuaxishi>`_,
3711 `@pkestene (Pierre Kestener) <https://github.com/pkestene>`_,
3712 `@dschmidt (Dominik Schmidt) <https://github.com/dschmidt>`_ and
3713 `@0x414c (Alexey Gorishny) <https://github.com/0x414c>`_ .
3714
3715 * Improved CMake: targets are now namespaced
3716 (`#511 <https://github.com/fmtlib/fmt/pull/511>`_ and
3717 `#513 <https://github.com/fmtlib/fmt/pull/513>`_), supported header-only
3718 ``printf.h`` (`#354 <https://github.com/fmtlib/fmt/pull/354>`_), fixed issue
3719 with minimal supported library subset
3720 (`#418 <https://github.com/fmtlib/fmt/issues/418>`_,
3721 `#419 <https://github.com/fmtlib/fmt/pull/419>`_ and
3722 `#420 <https://github.com/fmtlib/fmt/pull/420>`_).
3723 Thanks `@bjoernthiel (Bjoern Thiel) <https://github.com/bjoernthiel>`_,
3724 `@niosHD (Mario Werner) <https://github.com/niosHD>`_,
3725 `@LogicalKnight (Sean LK) <https://github.com/LogicalKnight>`_ and
3726 `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_.
3727
3728 * Improved documentation. Thanks to
3729 `@pwm1234 (Phil) <https://github.com/pwm1234>`_ for
3730 `#393 <https://github.com/fmtlib/fmt/pull/393>`_.
3731
3732 3.0.2 - 2017-06-14
3733 ------------------
3734
3735 * Added ``FMT_VERSION`` macro
3736 (`#411 <https://github.com/fmtlib/fmt/issues/411>`_).
3737
3738 * Used ``FMT_NULL`` instead of literal ``0``
3739 (`#409 <https://github.com/fmtlib/fmt/pull/409>`_).
3740 Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_.
3741
3742 * Added extern templates for ``format_float``
3743 (`#413 <https://github.com/fmtlib/fmt/issues/413>`_).
3744
3745 * Fixed implicit conversion issue
3746 (`#507 <https://github.com/fmtlib/fmt/issues/507>`_).
3747
3748 * Fixed signbit detection (`#423 <https://github.com/fmtlib/fmt/issues/423>`_).
3749
3750 * Fixed naming collision (`#425 <https://github.com/fmtlib/fmt/issues/425>`_).
3751
3752 * Fixed missing intrinsic for C++/CLI
3753 (`#457 <https://github.com/fmtlib/fmt/pull/457>`_).
3754 Thanks `@calumr (Calum Robinson) <https://github.com/calumr>`_
3755
3756 * Fixed Android detection (`#458 <https://github.com/fmtlib/fmt/pull/458>`_).
3757 Thanks `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_.
3758
3759 * Use lean ``windows.h`` if not in header-only mode
3760 (`#503 <https://github.com/fmtlib/fmt/pull/503>`_).
3761 Thanks `@Quentin01 (Quentin Buathier) <https://github.com/Quentin01>`_.
3762
3763 * Fixed issue with CMake exporting C++11 flag
3764 (`#445 <https://github.com/fmtlib/fmt/pull/455>`_).
3765 Thanks `@EricWF (Eric) <https://github.com/EricWF>`_.
3766
3767 * Fixed issue with nvcc and MSVC compiler bug and MinGW
3768 (`#505 <https://github.com/fmtlib/fmt/issues/505>`_).
3769
3770 * Fixed DLL issues (`#469 <https://github.com/fmtlib/fmt/pull/469>`_ and
3771 `#502 <https://github.com/fmtlib/fmt/pull/502>`_).
3772 Thanks `@richardeakin (Richard Eakin) <https://github.com/richardeakin>`_ and
3773 `@AndreasSchoenle (Andreas Schönle) <https://github.com/AndreasSchoenle>`_.
3774
3775 * Fixed test compilation under FreeBSD
3776 (`#433 <https://github.com/fmtlib/fmt/issues/433>`_).
3777
3778 * Fixed various warnings (`#403 <https://github.com/fmtlib/fmt/pull/403>`_,
3779 `#410 <https://github.com/fmtlib/fmt/pull/410>`_ and
3780 `#510 <https://github.com/fmtlib/fmt/pull/510>`_).
3781 Thanks `@Lecetem <https://github.com/Lectem>`_,
3782 `@chenhayat (Chen Hayat) <https://github.com/chenhayat>`_ and
3783 `@trozen <https://github.com/trozen>`_.
3784
3785 * Worked around a broken ``__builtin_clz`` in clang with MS codegen
3786 (`#519 <https://github.com/fmtlib/fmt/issues/519>`_).
3787
3788 * Removed redundant include
3789 (`#479 <https://github.com/fmtlib/fmt/issues/479>`_).
3790
3791 * Fixed documentation issues.
3792
3793 3.0.1 - 2016-11-01
3794 ------------------
3795 * Fixed handling of thousands separator
3796 (`#353 <https://github.com/fmtlib/fmt/issues/353>`_).
3797
3798 * Fixed handling of ``unsigned char`` strings
3799 (`#373 <https://github.com/fmtlib/fmt/issues/373>`_).
3800
3801 * Corrected buffer growth when formatting time
3802 (`#367 <https://github.com/fmtlib/fmt/issues/367>`_).
3803
3804 * Removed warnings under MSVC and clang
3805 (`#318 <https://github.com/fmtlib/fmt/issues/318>`_,
3806 `#250 <https://github.com/fmtlib/fmt/issues/250>`_, also merged
3807 `#385 <https://github.com/fmtlib/fmt/pull/385>`_ and
3808 `#361 <https://github.com/fmtlib/fmt/pull/361>`_).
3809 Thanks `@jcelerier (Jean-Michaël Celerier) <https://github.com/jcelerier>`_
3810 and `@nmoehrle (Nils Moehrle) <https://github.com/nmoehrle>`_.
3811
3812 * Fixed compilation issues under Android
3813 (`#327 <https://github.com/fmtlib/fmt/pull/327>`_,
3814 `#345 <https://github.com/fmtlib/fmt/issues/345>`_ and
3815 `#381 <https://github.com/fmtlib/fmt/pull/381>`_),
3816 FreeBSD (`#358 <https://github.com/fmtlib/fmt/pull/358>`_),
3817 Cygwin (`#388 <https://github.com/fmtlib/fmt/issues/388>`_),
3818 MinGW (`#355 <https://github.com/fmtlib/fmt/issues/355>`_) as well as other
3819 issues (`#350 <https://github.com/fmtlib/fmt/issues/350>`_,
3820 `#366 <https://github.com/fmtlib/fmt/issues/355>`_,
3821 `#348 <https://github.com/fmtlib/fmt/pull/348>`_,
3822 `#402 <https://github.com/fmtlib/fmt/pull/402>`_,
3823 `#405 <https://github.com/fmtlib/fmt/pull/405>`_).
3824 Thanks to `@dpantele (Dmitry) <https://github.com/dpantele>`_,
3825 `@hghwng (Hugh Wang) <https://github.com/hghwng>`_,
3826 `@arvedarved (Tilman Keskinöz) <https://github.com/arvedarved>`_,
3827 `@LogicalKnight (Sean) <https://github.com/LogicalKnight>`_ and
3828 `@JanHellwig (Jan Hellwig) <https://github.com/janhellwig>`_.
3829
3830 * Fixed some documentation issues and extended specification
3831 (`#320 <https://github.com/fmtlib/fmt/issues/320>`_,
3832 `#333 <https://github.com/fmtlib/fmt/pull/333>`_,
3833 `#347 <https://github.com/fmtlib/fmt/issues/347>`_,
3834 `#362 <https://github.com/fmtlib/fmt/pull/362>`_).
3835 Thanks to `@smellman (Taro Matsuzawa aka. btm)
3836 <https://github.com/smellman>`_.
3837
3838 3.0.0 - 2016-05-07
3839 ------------------
3840
3841 * The project has been renamed from C++ Format (cppformat) to fmt for
3842 consistency with the used namespace and macro prefix
3843 (`#307 <https://github.com/fmtlib/fmt/issues/307>`_).
3844 Library headers are now located in the ``fmt`` directory:
3845
3846 .. code:: c++
3847
3848 #include "fmt/format.h"
3849
3850 Including ``format.h`` from the ``cppformat`` directory is deprecated
3851 but works via a proxy header which will be removed in the next major version.
3852
3853 The documentation is now available at https://fmt.dev.
3854
3855 * Added support for `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like
3856 `date and time formatting <https://fmt.dev/3.0.0/api.html#date-and-time-formatting>`_
3857 (`#283 <https://github.com/fmtlib/fmt/issues/283>`_):
3858
3859 .. code:: c++
3860
3861 #include "fmt/time.h"
3862
3863 std::time_t t = std::time(nullptr);
3864 // Prints "The date is 2016-04-29." (with the current date)
3865 fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));
3866
3867 * ``std::ostream`` support including formatting of user-defined types that provide
3868 overloaded ``operator<<`` has been moved to ``fmt/ostream.h``:
3869
3870 .. code:: c++
3871
3872 #include "fmt/ostream.h"
3873
3874 class Date {
3875 int year_, month_, day_;
3876 public:
3877 Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}
3878
3879 friend std::ostream &operator<<(std::ostream &os, const Date &d) {
3880 return os << d.year_ << '-' << d.month_ << '-' << d.day_;
3881 }
3882 };
3883
3884 std::string s = fmt::format("The date is {}", Date(2012, 12, 9));
3885 // s == "The date is 2012-12-9"
3886
3887 * Added support for `custom argument formatters
3888 <https://fmt.dev/3.0.0/api.html#argument-formatters>`_
3889 (`#235 <https://github.com/fmtlib/fmt/issues/235>`_).
3890
3891 * Added support for locale-specific integer formatting with the ``n`` specifier
3892 (`#305 <https://github.com/fmtlib/fmt/issues/305>`_):
3893
3894 .. code:: c++
3895
3896 std::setlocale(LC_ALL, "en_US.utf8");
3897 fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567
3898
3899 * Sign is now preserved when formatting an integer with an incorrect ``printf``
3900 format specifier (`#265 <https://github.com/fmtlib/fmt/issues/265>`_):
3901
3902 .. code:: c++
3903
3904 fmt::printf("%lld", -42); // prints -42
3905
3906 Note that it would be an undefined behavior in ``std::printf``.
3907
3908 * Length modifiers such as ``ll`` are now optional in printf formatting
3909 functions and the correct type is determined automatically
3910 (`#255 <https://github.com/fmtlib/fmt/issues/255>`_):
3911
3912 .. code:: c++
3913
3914 fmt::printf("%d", std::numeric_limits<long long>::max());
3915
3916 Note that it would be an undefined behavior in ``std::printf``.
3917
3918 * Added initial support for custom formatters
3919 (`#231 <https://github.com/fmtlib/fmt/issues/231>`_).
3920
3921 * Fixed detection of user-defined literal support on Intel C++ compiler
3922 (`#311 <https://github.com/fmtlib/fmt/issues/311>`_,
3923 `#312 <https://github.com/fmtlib/fmt/pull/312>`_).
3924 Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_ and
3925 `@speth (Ray Speth) <https://github.com/speth>`_.
3926
3927 * Reduced compile time
3928 (`#243 <https://github.com/fmtlib/fmt/pull/243>`_,
3929 `#249 <https://github.com/fmtlib/fmt/pull/249>`_,
3930 `#317 <https://github.com/fmtlib/fmt/issues/317>`_):
3931
3932 .. image:: https://cloud.githubusercontent.com/assets/4831417/11614060/
3933 b9e826d2-9c36-11e5-8666-d4131bf503ef.png
3934
3935 .. image:: https://cloud.githubusercontent.com/assets/4831417/11614080/
3936 6ac903cc-9c37-11e5-8165-26df6efae364.png
3937
3938 Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_.
3939
3940 * Compile test fixes (`#313 <https://github.com/fmtlib/fmt/pull/313>`_).
3941 Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_.
3942
3943 * Documentation fixes (`#239 <https://github.com/fmtlib/fmt/pull/239>`_,
3944 `#248 <https://github.com/fmtlib/fmt/issues/248>`_,
3945 `#252 <https://github.com/fmtlib/fmt/issues/252>`_,
3946 `#258 <https://github.com/fmtlib/fmt/pull/258>`_,
3947 `#260 <https://github.com/fmtlib/fmt/issues/260>`_,
3948 `#301 <https://github.com/fmtlib/fmt/issues/301>`_,
3949 `#309 <https://github.com/fmtlib/fmt/pull/309>`_).
3950 Thanks to `@ReadmeCritic <https://github.com/ReadmeCritic>`_
3951 `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_ and
3952 `@jwilk (Jakub Wilk) <https://github.com/jwilk>`_.
3953
3954 * Fixed compiler and sanitizer warnings
3955 (`#244 <https://github.com/fmtlib/fmt/issues/244>`_,
3956 `#256 <https://github.com/fmtlib/fmt/pull/256>`_,
3957 `#259 <https://github.com/fmtlib/fmt/pull/259>`_,
3958 `#263 <https://github.com/fmtlib/fmt/issues/263>`_,
3959 `#274 <https://github.com/fmtlib/fmt/issues/274>`_,
3960 `#277 <https://github.com/fmtlib/fmt/pull/277>`_,
3961 `#286 <https://github.com/fmtlib/fmt/pull/286>`_,
3962 `#291 <https://github.com/fmtlib/fmt/issues/291>`_,
3963 `#296 <https://github.com/fmtlib/fmt/issues/296>`_,
3964 `#308 <https://github.com/fmtlib/fmt/issues/308>`_)
3965 Thanks to `@mwinterb <https://github.com/mwinterb>`_,
3966 `@pweiskircher (Patrik Weiskircher) <https://github.com/pweiskircher>`_,
3967 `@Naios <https://github.com/Naios>`_.
3968
3969 * Improved compatibility with Windows Store apps
3970 (`#280 <https://github.com/fmtlib/fmt/issues/280>`_,
3971 `#285 <https://github.com/fmtlib/fmt/pull/285>`_)
3972 Thanks to `@mwinterb <https://github.com/mwinterb>`_.
3973
3974 * Added tests of compatibility with older C++ standards
3975 (`#273 <https://github.com/fmtlib/fmt/pull/273>`_).
3976 Thanks to `@niosHD <https://github.com/niosHD>`_.
3977
3978 * Fixed Android build (`#271 <https://github.com/fmtlib/fmt/pull/271>`_).
3979 Thanks to `@newnon <https://github.com/newnon>`_.
3980
3981 * Changed ``ArgMap`` to be backed by a vector instead of a map.
3982 (`#261 <https://github.com/fmtlib/fmt/issues/261>`_,
3983 `#262 <https://github.com/fmtlib/fmt/pull/262>`_).
3984 Thanks to `@mwinterb <https://github.com/mwinterb>`_.
3985
3986 * Added ``fprintf`` overload that writes to a ``std::ostream``
3987 (`#251 <https://github.com/fmtlib/fmt/pull/251>`_).
3988 Thanks to `nickhutchinson (Nicholas Hutchinson) <https://github.com/nickhutchinson>`_.
3989
3990 * Export symbols when building a Windows DLL
3991 (`#245 <https://github.com/fmtlib/fmt/pull/245>`_).
3992 Thanks to `macdems (Maciek Dems) <https://github.com/macdems>`_.
3993
3994 * Fixed compilation on Cygwin (`#304 <https://github.com/fmtlib/fmt/issues/304>`_).
3995
3996 * Implemented a workaround for a bug in Apple LLVM version 4.2 of clang
3997 (`#276 <https://github.com/fmtlib/fmt/issues/276>`_).
3998
3999 * Implemented a workaround for Google Test bug
4000 `#705 <https://github.com/google/googletest/issues/705>`_ on gcc 6
4001 (`#268 <https://github.com/fmtlib/fmt/issues/268>`_).
4002 Thanks to `octoploid <https://github.com/octoploid>`_.
4003
4004 * Removed Biicode support because the latter has been discontinued.
4005
4006 2.1.1 - 2016-04-11
4007 ------------------
4008
4009 * The install location for generated CMake files is now configurable via
4010 the ``FMT_CMAKE_DIR`` CMake variable
4011 (`#299 <https://github.com/fmtlib/fmt/pull/299>`_).
4012 Thanks to `@niosHD <https://github.com/niosHD>`_.
4013
4014 * Documentation fixes (`#252 <https://github.com/fmtlib/fmt/issues/252>`_).
4015
4016 2.1.0 - 2016-03-21
4017 ------------------
4018
4019 * Project layout and build system improvements
4020 (`#267 <https://github.com/fmtlib/fmt/pull/267>`_):
4021
4022 * The code have been moved to the ``cppformat`` directory.
4023 Including ``format.h`` from the top-level directory is deprecated
4024 but works via a proxy header which will be removed in the next
4025 major version.
4026
4027 * C++ Format CMake targets now have proper interface definitions.
4028
4029 * Installed version of the library now supports the header-only
4030 configuration.
4031
4032 * Targets ``doc``, ``install``, and ``test`` are now disabled if C++ Format
4033 is included as a CMake subproject. They can be enabled by setting
4034 ``FMT_DOC``, ``FMT_INSTALL``, and ``FMT_TEST`` in the parent project.
4035
4036 Thanks to `@niosHD <https://github.com/niosHD>`_.
4037
4038 2.0.1 - 2016-03-13
4039 ------------------
4040
4041 * Improved CMake find and package support
4042 (`#264 <https://github.com/fmtlib/fmt/issues/264>`_).
4043 Thanks to `@niosHD <https://github.com/niosHD>`_.
4044
4045 * Fix compile error with Android NDK and mingw32
4046 (`#241 <https://github.com/fmtlib/fmt/issues/241>`_).
4047 Thanks to `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_.
4048
4049 * Documentation fixes
4050 (`#248 <https://github.com/fmtlib/fmt/issues/248>`_,
4051 `#260 <https://github.com/fmtlib/fmt/issues/260>`_).
4052
4053 2.0.0 - 2015-12-01
4054 ------------------
4055
4056 General
4057 ~~~~~~~
4058
4059 * [Breaking] Named arguments
4060 (`#169 <https://github.com/fmtlib/fmt/pull/169>`_,
4061 `#173 <https://github.com/fmtlib/fmt/pull/173>`_,
4062 `#174 <https://github.com/fmtlib/fmt/pull/174>`_):
4063
4064 .. code:: c++
4065
4066 fmt::print("The answer is {answer}.", fmt::arg("answer", 42));
4067
4068 Thanks to `@jamboree <https://github.com/jamboree>`_.
4069
4070 * [Experimental] User-defined literals for format and named arguments
4071 (`#204 <https://github.com/fmtlib/fmt/pull/204>`_,
4072 `#206 <https://github.com/fmtlib/fmt/pull/206>`_,
4073 `#207 <https://github.com/fmtlib/fmt/pull/207>`_):
4074
4075 .. code:: c++
4076
4077 using namespace fmt::literals;
4078 fmt::print("The answer is {answer}.", "answer"_a=42);
4079
4080 Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_.
4081
4082 * [Breaking] Formatting of more than 16 arguments is now supported when using
4083 variadic templates
4084 (`#141 <https://github.com/fmtlib/fmt/issues/141>`_).
4085 Thanks to `@Shauren <https://github.com/Shauren>`_.
4086
4087 * Runtime width specification
4088 (`#168 <https://github.com/fmtlib/fmt/pull/168>`_):
4089
4090 .. code:: c++
4091
4092 fmt::format("{0:{1}}", 42, 5); // gives " 42"
4093
4094 Thanks to `@jamboree <https://github.com/jamboree>`_.
4095
4096 * [Breaking] Enums are now formatted with an overloaded ``std::ostream`` insertion
4097 operator (``operator<<``) if available
4098 (`#232 <https://github.com/fmtlib/fmt/issues/232>`_).
4099
4100 * [Breaking] Changed default ``bool`` format to textual, "true" or "false"
4101 (`#170 <https://github.com/fmtlib/fmt/issues/170>`_):
4102
4103 .. code:: c++
4104
4105 fmt::print("{}", true); // prints "true"
4106
4107 To print ``bool`` as a number use numeric format specifier such as ``d``:
4108
4109 .. code:: c++
4110
4111 fmt::print("{:d}", true); // prints "1"
4112
4113 * ``fmt::printf`` and ``fmt::sprintf`` now support formatting of ``bool`` with the
4114 ``%s`` specifier giving textual output, "true" or "false"
4115 (`#223 <https://github.com/fmtlib/fmt/pull/223>`_):
4116
4117 .. code:: c++
4118
4119 fmt::printf("%s", true); // prints "true"
4120
4121 Thanks to `@LarsGullik <https://github.com/LarsGullik>`_.
4122
4123 * [Breaking] ``signed char`` and ``unsigned char`` are now formatted as integers by default
4124 (`#217 <https://github.com/fmtlib/fmt/pull/217>`_).
4125
4126 * [Breaking] Pointers to C strings can now be formatted with the ``p`` specifier
4127 (`#223 <https://github.com/fmtlib/fmt/pull/223>`_):
4128
4129 .. code:: c++
4130
4131 fmt::print("{:p}", "test"); // prints pointer value
4132
4133 Thanks to `@LarsGullik <https://github.com/LarsGullik>`_.
4134
4135 * [Breaking] ``fmt::printf`` and ``fmt::sprintf`` now print null pointers as ``(nil)``
4136 and null strings as ``(null)`` for consistency with glibc
4137 (`#226 <https://github.com/fmtlib/fmt/pull/226>`_).
4138 Thanks to `@LarsGullik <https://github.com/LarsGullik>`_.
4139
4140 * [Breaking] ``fmt::(s)printf`` now supports formatting of objects of user-defined types
4141 that provide an overloaded ``std::ostream`` insertion operator (``operator<<``)
4142 (`#201 <https://github.com/fmtlib/fmt/issues/201>`_):
4143
4144 .. code:: c++
4145
4146 fmt::printf("The date is %s", Date(2012, 12, 9));
4147
4148 * [Breaking] The ``Buffer`` template is now part of the public API and can be used
4149 to implement custom memory buffers
4150 (`#140 <https://github.com/fmtlib/fmt/issues/140>`_).
4151 Thanks to `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_.
4152
4153 * [Breaking] Improved compatibility between ``BasicStringRef`` and
4154 `std::experimental::basic_string_view
4155 <http://en.cppreference.com/w/cpp/experimental/basic_string_view>`_
4156 (`#100 <https://github.com/fmtlib/fmt/issues/100>`_,
4157 `#159 <https://github.com/fmtlib/fmt/issues/159>`_,
4158 `#183 <https://github.com/fmtlib/fmt/issues/183>`_):
4159
4160 - Comparison operators now compare string content, not pointers
4161 - ``BasicStringRef::c_str`` replaced by ``BasicStringRef::data``
4162 - ``BasicStringRef`` is no longer assumed to be null-terminated
4163
4164 References to null-terminated strings are now represented by a new class,
4165 ``BasicCStringRef``.
4166
4167 * Dependency on pthreads introduced by Google Test is now optional
4168 (`#185 <https://github.com/fmtlib/fmt/issues/185>`_).
4169
4170 * New CMake options ``FMT_DOC``, ``FMT_INSTALL`` and ``FMT_TEST`` to control
4171 generation of ``doc``, ``install`` and ``test`` targets respectively, on by default
4172 (`#197 <https://github.com/fmtlib/fmt/issues/197>`_,
4173 `#198 <https://github.com/fmtlib/fmt/issues/198>`_,
4174 `#200 <https://github.com/fmtlib/fmt/issues/200>`_).
4175 Thanks to `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_.
4176
4177 * ``noexcept`` is now used when compiling with MSVC2015
4178 (`#215 <https://github.com/fmtlib/fmt/pull/215>`_).
4179 Thanks to `@dmkrepo (Dmitriy) <https://github.com/dmkrepo>`_.
4180
4181 * Added an option to disable use of ``windows.h`` when ``FMT_USE_WINDOWS_H``
4182 is defined as 0 before including ``format.h``
4183 (`#171 <https://github.com/fmtlib/fmt/issues/171>`_).
4184 Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_.
4185
4186 * [Breaking] ``windows.h`` is now included with ``NOMINMAX`` unless
4187 ``FMT_WIN_MINMAX`` is defined. This is done to prevent breaking code using
4188 ``std::min`` and ``std::max`` and only affects the header-only configuration
4189 (`#152 <https://github.com/fmtlib/fmt/issues/152>`_,
4190 `#153 <https://github.com/fmtlib/fmt/pull/153>`_,
4191 `#154 <https://github.com/fmtlib/fmt/pull/154>`_).
4192 Thanks to `@DevO2012 <https://github.com/DevO2012>`_.
4193
4194 * Improved support for custom character types
4195 (`#171 <https://github.com/fmtlib/fmt/issues/171>`_).
4196 Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_.
4197
4198 * Added an option to disable use of IOStreams when ``FMT_USE_IOSTREAMS``
4199 is defined as 0 before including ``format.h``
4200 (`#205 <https://github.com/fmtlib/fmt/issues/205>`_,
4201 `#208 <https://github.com/fmtlib/fmt/pull/208>`_).
4202 Thanks to `@JodiTheTigger <https://github.com/JodiTheTigger>`_.
4203
4204 * Improved detection of ``isnan``, ``isinf`` and ``signbit``.
4205
4206 Optimization
4207 ~~~~~~~~~~~~
4208
4209 * Made formatting of user-defined types more efficient with a custom stream buffer
4210 (`#92 <https://github.com/fmtlib/fmt/issues/92>`_,
4211 `#230 <https://github.com/fmtlib/fmt/pull/230>`_).
4212 Thanks to `@NotImplemented <https://github.com/NotImplemented>`_.
4213
4214 * Further improved performance of ``fmt::Writer`` on integer formatting
4215 and fixed a minor regression. Now it is ~7% faster than ``karma::generate``
4216 on Karma's benchmark
4217 (`#186 <https://github.com/fmtlib/fmt/issues/186>`_).
4218
4219 * [Breaking] Reduced `compiled code size
4220 <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_
4221 (`#143 <https://github.com/fmtlib/fmt/issues/143>`_,
4222 `#149 <https://github.com/fmtlib/fmt/pull/149>`_).
4223
4224 Distribution
4225 ~~~~~~~~~~~~
4226
4227 * [Breaking] Headers are now installed in
4228 ``${CMAKE_INSTALL_PREFIX}/include/cppformat``
4229 (`#178 <https://github.com/fmtlib/fmt/issues/178>`_).
4230 Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_.
4231
4232 * [Breaking] Changed the library name from ``format`` to ``cppformat``
4233 for consistency with the project name and to avoid potential conflicts
4234 (`#178 <https://github.com/fmtlib/fmt/issues/178>`_).
4235 Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_.
4236
4237 * C++ Format is now available in `Debian <https://www.debian.org/>`_ GNU/Linux
4238 (`stretch <https://packages.debian.org/source/stretch/cppformat>`_,
4239 `sid <https://packages.debian.org/source/sid/cppformat>`_) and
4240 derived distributions such as
4241 `Ubuntu <https://launchpad.net/ubuntu/+source/cppformat>`_ 15.10 and later
4242 (`#155 <https://github.com/fmtlib/fmt/issues/155>`_)::
4243
4244 $ sudo apt-get install libcppformat1-dev
4245
4246 Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_.
4247
4248 * `Packages for Fedora and RHEL <https://admin.fedoraproject.org/pkgdb/package/cppformat/>`_
4249 are now available. Thanks to Dave Johansen.
4250
4251 * C++ Format can now be installed via `Homebrew <http://brew.sh/>`_ on OS X
4252 (`#157 <https://github.com/fmtlib/fmt/issues/157>`_)::
4253
4254 $ brew install cppformat
4255
4256 Thanks to `@ortho <https://github.com/ortho>`_, Anatoliy Bulukin.
4257
4258 Documentation
4259 ~~~~~~~~~~~~~
4260
4261 * Migrated from ReadTheDocs to GitHub Pages for better responsiveness
4262 and reliability
4263 (`#128 <https://github.com/fmtlib/fmt/issues/128>`_).
4264 New documentation address is http://cppformat.github.io/.
4265
4266
4267 * Added `Building the documentation
4268 <https://fmt.dev/2.0.0/usage.html#building-the-documentation>`_
4269 section to the documentation.
4270
4271 * Documentation build script is now compatible with Python 3 and newer pip versions.
4272 (`#189 <https://github.com/fmtlib/fmt/pull/189>`_,
4273 `#209 <https://github.com/fmtlib/fmt/issues/209>`_).
4274 Thanks to `@JodiTheTigger <https://github.com/JodiTheTigger>`_ and
4275 `@xentec <https://github.com/xentec>`_.
4276
4277 * Documentation fixes and improvements
4278 (`#36 <https://github.com/fmtlib/fmt/issues/36>`_,
4279 `#75 <https://github.com/fmtlib/fmt/issues/75>`_,
4280 `#125 <https://github.com/fmtlib/fmt/issues/125>`_,
4281 `#160 <https://github.com/fmtlib/fmt/pull/160>`_,
4282 `#161 <https://github.com/fmtlib/fmt/pull/161>`_,
4283 `#162 <https://github.com/fmtlib/fmt/issues/162>`_,
4284 `#165 <https://github.com/fmtlib/fmt/issues/165>`_,
4285 `#210 <https://github.com/fmtlib/fmt/issues/210>`_).
4286 Thanks to `@syohex (Syohei YOSHIDA) <https://github.com/syohex>`_ and
4287 bug reporters.
4288
4289 * Fixed out-of-tree documentation build
4290 (`#177 <https://github.com/fmtlib/fmt/issues/177>`_).
4291 Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_.
4292
4293 Fixes
4294 ~~~~~
4295
4296 * Fixed ``initializer_list`` detection
4297 (`#136 <https://github.com/fmtlib/fmt/issues/136>`_).
4298 Thanks to `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_.
4299
4300 * [Breaking] Fixed formatting of enums with numeric format specifiers in
4301 ``fmt::(s)printf``
4302 (`#131 <https://github.com/fmtlib/fmt/issues/131>`_,
4303 `#139 <https://github.com/fmtlib/fmt/issues/139>`_):
4304
4305 .. code:: c++
4306
4307 enum { ANSWER = 42 };
4308 fmt::printf("%d", ANSWER);
4309
4310 Thanks to `@Naios <https://github.com/Naios>`_.
4311
4312 * Improved compatibility with old versions of MinGW
4313 (`#129 <https://github.com/fmtlib/fmt/issues/129>`_,
4314 `#130 <https://github.com/fmtlib/fmt/pull/130>`_,
4315 `#132 <https://github.com/fmtlib/fmt/issues/132>`_).
4316 Thanks to `@cstamford (Christopher Stamford) <https://github.com/cstamford>`_.
4317
4318 * Fixed a compile error on MSVC with disabled exceptions
4319 (`#144 <https://github.com/fmtlib/fmt/issues/144>`_).
4320
4321 * Added a workaround for broken implementation of variadic templates in MSVC2012
4322 (`#148 <https://github.com/fmtlib/fmt/issues/148>`_).
4323
4324 * Placed the anonymous namespace within ``fmt`` namespace for the header-only
4325 configuration
4326 (`#171 <https://github.com/fmtlib/fmt/issues/171>`_).
4327 Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_.
4328
4329 * Fixed issues reported by Coverity Scan
4330 (`#187 <https://github.com/fmtlib/fmt/issues/187>`_,
4331 `#192 <https://github.com/fmtlib/fmt/issues/192>`_).
4332
4333 * Implemented a workaround for a name lookup bug in MSVC2010
4334 (`#188 <https://github.com/fmtlib/fmt/issues/188>`_).
4335
4336 * Fixed compiler warnings
4337 (`#95 <https://github.com/fmtlib/fmt/issues/95>`_,
4338 `#96 <https://github.com/fmtlib/fmt/issues/96>`_,
4339 `#114 <https://github.com/fmtlib/fmt/pull/114>`_,
4340 `#135 <https://github.com/fmtlib/fmt/issues/135>`_,
4341 `#142 <https://github.com/fmtlib/fmt/issues/142>`_,
4342 `#145 <https://github.com/fmtlib/fmt/issues/145>`_,
4343 `#146 <https://github.com/fmtlib/fmt/issues/146>`_,
4344 `#158 <https://github.com/fmtlib/fmt/issues/158>`_,
4345 `#163 <https://github.com/fmtlib/fmt/issues/163>`_,
4346 `#175 <https://github.com/fmtlib/fmt/issues/175>`_,
4347 `#190 <https://github.com/fmtlib/fmt/issues/190>`_,
4348 `#191 <https://github.com/fmtlib/fmt/pull/191>`_,
4349 `#194 <https://github.com/fmtlib/fmt/issues/194>`_,
4350 `#196 <https://github.com/fmtlib/fmt/pull/196>`_,
4351 `#216 <https://github.com/fmtlib/fmt/issues/216>`_,
4352 `#218 <https://github.com/fmtlib/fmt/pull/218>`_,
4353 `#220 <https://github.com/fmtlib/fmt/pull/220>`_,
4354 `#229 <https://github.com/fmtlib/fmt/pull/229>`_,
4355 `#233 <https://github.com/fmtlib/fmt/issues/233>`_,
4356 `#234 <https://github.com/fmtlib/fmt/issues/234>`_,
4357 `#236 <https://github.com/fmtlib/fmt/pull/236>`_,
4358 `#281 <https://github.com/fmtlib/fmt/issues/281>`_,
4359 `#289 <https://github.com/fmtlib/fmt/issues/289>`_).
4360 Thanks to `@seanmiddleditch (Sean Middleditch) <https://github.com/seanmiddleditch>`_,
4361 `@dixlorenz (Dix Lorenz) <https://github.com/dixlorenz>`_,
4362 `@CarterLi (李通洲) <https://github.com/CarterLi>`_,
4363 `@Naios <https://github.com/Naios>`_,
4364 `@fmatthew5876 (Matthew Fioravante) <https://github.com/fmatthew5876>`_,
4365 `@LevskiWeng (Levski Weng) <https://github.com/LevskiWeng>`_,
4366 `@rpopescu <https://github.com/rpopescu>`_,
4367 `@gabime (Gabi Melman) <https://github.com/gabime>`_,
4368 `@cubicool (Jeremy Moles) <https://github.com/cubicool>`_,
4369 `@jkflying (Julian Kent) <https://github.com/jkflying>`_,
4370 `@LogicalKnight (Sean L) <https://github.com/LogicalKnight>`_,
4371 `@inguin (Ingo van Lil) <https://github.com/inguin>`_ and
4372 `@Jopie64 (Johan) <https://github.com/Jopie64>`_.
4373
4374 * Fixed portability issues (mostly causing test failures) on ARM, ppc64, ppc64le,
4375 s390x and SunOS 5.11 i386
4376 (`#138 <https://github.com/fmtlib/fmt/issues/138>`_,
4377 `#179 <https://github.com/fmtlib/fmt/issues/179>`_,
4378 `#180 <https://github.com/fmtlib/fmt/issues/180>`_,
4379 `#202 <https://github.com/fmtlib/fmt/issues/202>`_,
4380 `#225 <https://github.com/fmtlib/fmt/issues/225>`_,
4381 `Red Hat Bugzilla Bug 1260297 <https://bugzilla.redhat.com/show_bug.cgi?id=1260297>`_).
4382 Thanks to `@Naios <https://github.com/Naios>`_,
4383 `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_ and Dave Johansen.
4384
4385 * Fixed a name conflict with macro ``free`` defined in
4386 ``crtdbg.h`` when ``_CRTDBG_MAP_ALLOC`` is set
4387 (`#211 <https://github.com/fmtlib/fmt/issues/211>`_).
4388
4389 * Fixed shared library build on OS X
4390 (`#212 <https://github.com/fmtlib/fmt/pull/212>`_).
4391 Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_.
4392
4393 * Fixed an overload conflict on MSVC when ``/Zc:wchar_t-`` option is specified
4394 (`#214 <https://github.com/fmtlib/fmt/pull/214>`_).
4395 Thanks to `@slavanap (Vyacheslav Napadovsky) <https://github.com/slavanap>`_.
4396
4397 * Improved compatibility with MSVC 2008
4398 (`#236 <https://github.com/fmtlib/fmt/pull/236>`_).
4399 Thanks to `@Jopie64 (Johan) <https://github.com/Jopie64>`_.
4400
4401 * Improved compatibility with bcc32
4402 (`#227 <https://github.com/fmtlib/fmt/issues/227>`_).
4403
4404 * Fixed ``static_assert`` detection on Clang
4405 (`#228 <https://github.com/fmtlib/fmt/pull/228>`_).
4406 Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_.
4407
4408 1.1.0 - 2015-03-06
4409 ------------------
4410
4411 * Added ``BasicArrayWriter``, a class template that provides operations for
4412 formatting and writing data into a fixed-size array
4413 (`#105 <https://github.com/fmtlib/fmt/issues/105>`_ and
4414 `#122 <https://github.com/fmtlib/fmt/issues/122>`_):
4415
4416 .. code:: c++
4417
4418 char buffer[100];
4419 fmt::ArrayWriter w(buffer);
4420 w.write("The answer is {}", 42);
4421
4422 * Added `0 A.D. <http://play0ad.com/>`_ and `PenUltima Online (POL)
4423 <http://www.polserver.com/>`_ to the list of notable projects using C++ Format.
4424
4425 * C++ Format now uses MSVC intrinsics for better formatting performance
4426 (`#115 <https://github.com/fmtlib/fmt/pull/115>`_,
4427 `#116 <https://github.com/fmtlib/fmt/pull/116>`_,
4428 `#118 <https://github.com/fmtlib/fmt/pull/118>`_ and
4429 `#121 <https://github.com/fmtlib/fmt/pull/121>`_).
4430 Previously these optimizations where only used on GCC and Clang.
4431 Thanks to `@CarterLi <https://github.com/CarterLi>`_ and
4432 `@objectx <https://github.com/objectx>`_.
4433
4434 * CMake install target (`#119 <https://github.com/fmtlib/fmt/pull/119>`_).
4435 Thanks to `@TrentHouliston <https://github.com/TrentHouliston>`_.
4436
4437 You can now install C++ Format with ``make install`` command.
4438
4439 * Improved `Biicode <http://www.biicode.com/>`_ support
4440 (`#98 <https://github.com/fmtlib/fmt/pull/98>`_ and
4441 `#104 <https://github.com/fmtlib/fmt/pull/104>`_). Thanks to
4442 `@MariadeAnton <https://github.com/MariadeAnton>`_ and
4443 `@franramirez688 <https://github.com/franramirez688>`_.
4444
4445 * Improved support for building with `Android NDK
4446 <https://developer.android.com/tools/sdk/ndk/index.html>`_
4447 (`#107 <https://github.com/fmtlib/fmt/pull/107>`_).
4448 Thanks to `@newnon <https://github.com/newnon>`_.
4449
4450 The `android-ndk-example <https://github.com/fmtlib/android-ndk-example>`_
4451 repository provides and example of using C++ Format with Android NDK:
4452
4453 .. image:: https://raw.githubusercontent.com/fmtlib/android-ndk-example/
4454 master/screenshot.png
4455
4456 * Improved documentation of ``SystemError`` and ``WindowsError``
4457 (`#54 <https://github.com/fmtlib/fmt/issues/54>`_).
4458
4459 * Various code improvements
4460 (`#110 <https://github.com/fmtlib/fmt/pull/110>`_,
4461 `#111 <https://github.com/fmtlib/fmt/pull/111>`_
4462 `#112 <https://github.com/fmtlib/fmt/pull/112>`_).
4463 Thanks to `@CarterLi <https://github.com/CarterLi>`_.
4464
4465 * Improved compile-time errors when formatting wide into narrow strings
4466 (`#117 <https://github.com/fmtlib/fmt/issues/117>`_).
4467
4468 * Fixed ``BasicWriter::write`` without formatting arguments when C++11 support
4469 is disabled (`#109 <https://github.com/fmtlib/fmt/issues/109>`_).
4470
4471 * Fixed header-only build on OS X with GCC 4.9
4472 (`#124 <https://github.com/fmtlib/fmt/issues/124>`_).
4473
4474 * Fixed packaging issues (`#94 <https://github.com/fmtlib/fmt/issues/94>`_).
4475
4476 * Added `changelog <https://github.com/fmtlib/fmt/blob/master/ChangeLog.rst>`_
4477 (`#103 <https://github.com/fmtlib/fmt/issues/103>`_).
4478
4479 1.0.0 - 2015-02-05
4480 ------------------
4481
4482 * Add support for a header-only configuration when ``FMT_HEADER_ONLY`` is
4483 defined before including ``format.h``:
4484
4485 .. code:: c++
4486
4487 #define FMT_HEADER_ONLY
4488 #include "format.h"
4489
4490 * Compute string length in the constructor of ``BasicStringRef``
4491 instead of the ``size`` method
4492 (`#79 <https://github.com/fmtlib/fmt/issues/79>`_).
4493 This eliminates size computation for string literals on reasonable optimizing
4494 compilers.
4495
4496 * Fix formatting of types with overloaded ``operator <<`` for ``std::wostream``
4497 (`#86 <https://github.com/fmtlib/fmt/issues/86>`_):
4498
4499 .. code:: c++
4500
4501 fmt::format(L"The date is {0}", Date(2012, 12, 9));
4502
4503 * Fix linkage of tests on Arch Linux
4504 (`#89 <https://github.com/fmtlib/fmt/issues/89>`_).
4505
4506 * Allow precision specifier for non-float arguments
4507 (`#90 <https://github.com/fmtlib/fmt/issues/90>`_):
4508
4509 .. code:: c++
4510
4511 fmt::print("{:.3}\n", "Carpet"); // prints "Car"
4512
4513 * Fix build on Android NDK
4514 (`#93 <https://github.com/fmtlib/fmt/issues/93>`_)
4515
4516 * Improvements to documentation build procedure.
4517
4518 * Remove ``FMT_SHARED`` CMake variable in favor of standard `BUILD_SHARED_LIBS
4519 <http://www.cmake.org/cmake/help/v3.0/variable/BUILD_SHARED_LIBS.html>`_.
4520
4521 * Fix error handling in ``fmt::fprintf``.
4522
4523 * Fix a number of warnings.
4524
4525 0.12.0 - 2014-10-25
4526 -------------------
4527
4528 * [Breaking] Improved separation between formatting and buffer management.
4529 ``Writer`` is now a base class that cannot be instantiated directly.
4530 The new ``MemoryWriter`` class implements the default buffer management
4531 with small allocations done on stack. So ``fmt::Writer`` should be replaced
4532 with ``fmt::MemoryWriter`` in variable declarations.
4533
4534 Old code:
4535
4536 .. code:: c++
4537
4538 fmt::Writer w;
4539
4540 New code:
4541
4542 .. code:: c++
4543
4544 fmt::MemoryWriter w;
4545
4546 If you pass ``fmt::Writer`` by reference, you can continue to do so:
4547
4548 .. code:: c++
4549
4550 void f(fmt::Writer &w);
4551
4552 This doesn't affect the formatting API.
4553
4554 * Support for custom memory allocators
4555 (`#69 <https://github.com/fmtlib/fmt/issues/69>`_)
4556
4557 * Formatting functions now accept `signed char` and `unsigned char` strings as
4558 arguments (`#73 <https://github.com/fmtlib/fmt/issues/73>`_):
4559
4560 .. code:: c++
4561
4562 auto s = format("GLSL version: {}", glGetString(GL_VERSION));
4563
4564 * Reduced code bloat. According to the new `benchmark results
4565 <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_,
4566 cppformat is close to ``printf`` and by the order of magnitude better than
4567 Boost Format in terms of compiled code size.
4568
4569 * Improved appearance of the documentation on mobile by using the `Sphinx
4570 Bootstrap theme <http://ryan-roemer.github.io/sphinx-bootstrap-theme/>`_:
4571
4572 .. |old| image:: https://cloud.githubusercontent.com/assets/576385/4792130/
4573 cd256436-5de3-11e4-9a62-c077d0c2b003.png
4574
4575 .. |new| image:: https://cloud.githubusercontent.com/assets/576385/4792131/
4576 cd29896c-5de3-11e4-8f59-cac952942bf0.png
4577
4578 +-------+-------+
4579 | Old | New |
4580 +-------+-------+
4581 | |old| | |new| |
4582 +-------+-------+
4583
4584 0.11.0 - 2014-08-21
4585 -------------------
4586
4587 * Safe printf implementation with a POSIX extension for positional arguments:
4588
4589 .. code:: c++
4590
4591 fmt::printf("Elapsed time: %.2f seconds", 1.23);
4592 fmt::printf("%1$s, %3$d %2$s", weekday, month, day);
4593
4594 * Arguments of ``char`` type can now be formatted as integers
4595 (Issue `#55 <https://github.com/fmtlib/fmt/issues/55>`_):
4596
4597 .. code:: c++
4598
4599 fmt::format("0x{0:02X}", 'a');
4600
4601 * Deprecated parts of the API removed.
4602
4603 * The library is now built and tested on MinGW with Appveyor in addition to
4604 existing test platforms Linux/GCC, OS X/Clang, Windows/MSVC.
4605
4606 0.10.0 - 2014-07-01
4607 -------------------
4608
4609 **Improved API**
4610
4611 * All formatting methods are now implemented as variadic functions instead
4612 of using ``operator<<`` for feeding arbitrary arguments into a temporary
4613 formatter object. This works both with C++11 where variadic templates are
4614 used and with older standards where variadic functions are emulated by
4615 providing lightweight wrapper functions defined with the ``FMT_VARIADIC``
4616 macro. You can use this macro for defining your own portable variadic
4617 functions:
4618
4619 .. code:: c++
4620
4621 void report_error(const char *format, const fmt::ArgList &args) {
4622 fmt::print("Error: {}");
4623 fmt::print(format, args);
4624 }
4625 FMT_VARIADIC(void, report_error, const char *)
4626
4627 report_error("file not found: {}", path);
4628
4629 Apart from a more natural syntax, this also improves performance as there
4630 is no need to construct temporary formatter objects and control arguments'
4631 lifetimes. Because the wrapper functions are very lightweight, this doesn't
4632 cause code bloat even in pre-C++11 mode.
4633
4634 * Simplified common case of formatting an ``std::string``. Now it requires a
4635 single function call:
4636
4637 .. code:: c++
4638
4639 std::string s = format("The answer is {}.", 42);
4640
4641 Previously it required 2 function calls:
4642
4643 .. code:: c++
4644
4645 std::string s = str(Format("The answer is {}.") << 42);
4646
4647 Instead of unsafe ``c_str`` function, ``fmt::Writer`` should be used directly
4648 to bypass creation of ``std::string``:
4649
4650 .. code:: c++
4651
4652 fmt::Writer w;
4653 w.write("The answer is {}.", 42);
4654 w.c_str(); // returns a C string
4655
4656 This doesn't do dynamic memory allocation for small strings and is less error
4657 prone as the lifetime of the string is the same as for ``std::string::c_str``
4658 which is well understood (hopefully).
4659
4660 * Improved consistency in naming functions that are a part of the public API.
4661 Now all public functions are lowercase following the standard library
4662 conventions. Previously it was a combination of lowercase and
4663 CapitalizedWords.
4664 Issue `#50 <https://github.com/fmtlib/fmt/issues/50>`_.
4665
4666 * Old functions are marked as deprecated and will be removed in the next
4667 release.
4668
4669 **Other Changes**
4670
4671 * Experimental support for printf format specifications (work in progress):
4672
4673 .. code:: c++
4674
4675 fmt::printf("The answer is %d.", 42);
4676 std::string s = fmt::sprintf("Look, a %s!", "string");
4677
4678 * Support for hexadecimal floating point format specifiers ``a`` and ``A``:
4679
4680 .. code:: c++
4681
4682 print("{:a}", -42.0); // Prints -0x1.5p+5
4683 print("{:A}", -42.0); // Prints -0X1.5P+5
4684
4685 * CMake option ``FMT_SHARED`` that specifies whether to build format as a
4686 shared library (off by default).
4687
4688 0.9.0 - 2014-05-13
4689 ------------------
4690
4691 * More efficient implementation of variadic formatting functions.
4692
4693 * ``Writer::Format`` now has a variadic overload:
4694
4695 .. code:: c++
4696
4697 Writer out;
4698 out.Format("Look, I'm {}!", "variadic");
4699
4700 * For efficiency and consistency with other overloads, variadic overload of
4701 the ``Format`` function now returns ``Writer`` instead of ``std::string``.
4702 Use the ``str`` function to convert it to ``std::string``:
4703
4704 .. code:: c++
4705
4706 std::string s = str(Format("Look, I'm {}!", "variadic"));
4707
4708 * Replaced formatter actions with output sinks: ``NoAction`` -> ``NullSink``,
4709 ``Write`` -> ``FileSink``, ``ColorWriter`` -> ``ANSITerminalSink``.
4710 This improves naming consistency and shouldn't affect client code unless
4711 these classes are used directly which should be rarely needed.
4712
4713 * Added ``ThrowSystemError`` function that formats a message and throws
4714 ``SystemError`` containing the formatted message and system-specific error
4715 description. For example, the following code
4716
4717 .. code:: c++
4718
4719 FILE *f = fopen(filename, "r");
4720 if (!f)
4721 ThrowSystemError(errno, "Failed to open file '{}'") << filename;
4722
4723 will throw ``SystemError`` exception with description
4724 "Failed to open file '<filename>': No such file or directory" if file
4725 doesn't exist.
4726
4727 * Support for AppVeyor continuous integration platform.
4728
4729 * ``Format`` now throws ``SystemError`` in case of I/O errors.
4730
4731 * Improve test infrastructure. Print functions are now tested by redirecting
4732 the output to a pipe.
4733
4734 0.8.0 - 2014-04-14
4735 ------------------
4736
4737 * Initial release
+0
-27
source/misc/embedded_libs/fmt-8.1.1/LICENSE.rst less more
0 Copyright (c) 2012 - present, Victor Zverovich
1
2 Permission is hereby granted, free of charge, to any person obtaining
3 a copy of this software and associated documentation files (the
4 "Software"), to deal in the Software without restriction, including
5 without limitation the rights to use, copy, modify, merge, publish,
6 distribute, sublicense, and/or sell copies of the Software, and to
7 permit persons to whom the Software is furnished to do so, subject to
8 the following conditions:
9
10 The above copyright notice and this permission notice shall be
11 included in all copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
17 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
18 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
19 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
21 --- Optional exception to the license ---
22
23 As an exception, if, as a result of your compiling your source code, portions
24 of this Software are embedded into a machine-executable object form of such
25 source code, you may redistribute such embedded portions in such object form
26 without including the above copyright and permission notices.
+0
-528
source/misc/embedded_libs/fmt-8.1.1/README.rst less more
0 {fmt}
1 =====
2
3 .. image:: https://github.com/fmtlib/fmt/workflows/linux/badge.svg
4 :target: https://github.com/fmtlib/fmt/actions?query=workflow%3Alinux
5
6 .. image:: https://github.com/fmtlib/fmt/workflows/macos/badge.svg
7 :target: https://github.com/fmtlib/fmt/actions?query=workflow%3Amacos
8
9 .. image:: https://github.com/fmtlib/fmt/workflows/windows/badge.svg
10 :target: https://github.com/fmtlib/fmt/actions?query=workflow%3Awindows
11
12 .. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v?svg=true
13 :target: https://ci.appveyor.com/project/vitaut/fmt
14
15 .. image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/fmt.svg
16 :alt: fmt is continuously fuzzed at oss-fuzz
17 :target: https://bugs.chromium.org/p/oss-fuzz/issues/list?\
18 colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\
19 Summary&q=proj%3Dfmt&can=1
20
21 .. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg
22 :alt: Ask questions at StackOverflow with the tag fmt
23 :target: https://stackoverflow.com/questions/tagged/fmt
24
25 **{fmt}** is an open-source formatting library providing a fast and safe
26 alternative to C stdio and C++ iostreams.
27
28 If you like this project, please consider donating to the BYSOL
29 Foundation that helps victims of political repressions in Belarus:
30 https://bysol.org/en/bs/general/.
31
32 `Documentation <https://fmt.dev>`__
33
34 Q&A: ask questions on `StackOverflow with the tag fmt
35 <https://stackoverflow.com/questions/tagged/fmt>`_.
36
37 Try {fmt} in `Compiler Explorer <https://godbolt.org/z/Eq5763>`_.
38
39 Features
40 --------
41
42 * Simple `format API <https://fmt.dev/latest/api.html>`_ with positional arguments
43 for localization
44 * Implementation of `C++20 std::format
45 <https://en.cppreference.com/w/cpp/utility/format>`__
46 * `Format string syntax <https://fmt.dev/latest/syntax.html>`_ similar to Python's
47 `format <https://docs.python.org/3/library/stdtypes.html#str.format>`_
48 * Fast IEEE 754 floating-point formatter with correct rounding, shortness and
49 round-trip guarantees
50 * Safe `printf implementation
51 <https://fmt.dev/latest/api.html#printf-formatting>`_ including the POSIX
52 extension for positional arguments
53 * Extensibility: `support for user-defined types
54 <https://fmt.dev/latest/api.html#formatting-user-defined-types>`_
55 * High performance: faster than common standard library implementations of
56 ``(s)printf``, iostreams, ``to_string`` and ``to_chars``, see `Speed tests`_
57 and `Converting a hundred million integers to strings per second
58 <http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_
59 * Small code size both in terms of source code with the minimum configuration
60 consisting of just three files, ``core.h``, ``format.h`` and ``format-inl.h``,
61 and compiled code; see `Compile time and code bloat`_
62 * Reliability: the library has an extensive set of `tests
63 <https://github.com/fmtlib/fmt/tree/master/test>`_ and is `continuously fuzzed
64 <https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20
65 Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dfmt&can=1>`_
66 * Safety: the library is fully type safe, errors in format strings can be
67 reported at compile time, automatic memory management prevents buffer overflow
68 errors
69 * Ease of use: small self-contained code base, no external dependencies,
70 permissive MIT `license
71 <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_
72 * `Portability <https://fmt.dev/latest/index.html#portability>`_ with
73 consistent output across platforms and support for older compilers
74 * Clean warning-free codebase even on high warning levels such as
75 ``-Wall -Wextra -pedantic``
76 * Locale-independence by default
77 * Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro
78
79 See the `documentation <https://fmt.dev>`_ for more details.
80
81 Examples
82 --------
83
84 **Print to stdout** (`run <https://godbolt.org/z/Tevcjh>`_)
85
86 .. code:: c++
87
88 #include <fmt/core.h>
89
90 int main() {
91 fmt::print("Hello, world!\n");
92 }
93
94 **Format a string** (`run <https://godbolt.org/z/oK8h33>`_)
95
96 .. code:: c++
97
98 std::string s = fmt::format("The answer is {}.", 42);
99 // s == "The answer is 42."
100
101 **Format a string using positional arguments** (`run <https://godbolt.org/z/Yn7Txe>`_)
102
103 .. code:: c++
104
105 std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
106 // s == "I'd rather be happy than right."
107
108 **Print chrono durations** (`run <https://godbolt.org/z/K8s4Mc>`_)
109
110 .. code:: c++
111
112 #include <fmt/chrono.h>
113
114 int main() {
115 using namespace std::literals::chrono_literals;
116 fmt::print("Default format: {} {}\n", 42s, 100ms);
117 fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
118 }
119
120 Output::
121
122 Default format: 42s 100ms
123 strftime-like format: 03:15:30
124
125 **Print a container** (`run <https://godbolt.org/z/MjsY7c>`_)
126
127 .. code:: c++
128
129 #include <vector>
130 #include <fmt/ranges.h>
131
132 int main() {
133 std::vector<int> v = {1, 2, 3};
134 fmt::print("{}\n", v);
135 }
136
137 Output::
138
139 [1, 2, 3]
140
141 **Check a format string at compile time**
142
143 .. code:: c++
144
145 std::string s = fmt::format("{:d}", "I am not a number");
146
147 This gives a compile-time error in C++20 because ``d`` is an invalid format
148 specifier for a string.
149
150 **Write a file from a single thread**
151
152 .. code:: c++
153
154 #include <fmt/os.h>
155
156 int main() {
157 auto out = fmt::output_file("guide.txt");
158 out.print("Don't {}", "Panic");
159 }
160
161 This can be `5 to 9 times faster than fprintf
162 <http://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html>`_.
163
164 **Print with colors and text styles**
165
166 .. code:: c++
167
168 #include <fmt/color.h>
169
170 int main() {
171 fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
172 "Hello, {}!\n", "world");
173 fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
174 fmt::emphasis::underline, "Hello, {}!\n", "мир");
175 fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic,
176 "Hello, {}!\n", "世界");
177 }
178
179 Output on a modern terminal:
180
181 .. image:: https://user-images.githubusercontent.com/
182 576385/88485597-d312f600-cf2b-11ea-9cbe-61f535a86e28.png
183
184 Benchmarks
185 ----------
186
187 Speed tests
188 ~~~~~~~~~~~
189
190 ================= ============= ===========
191 Library Method Run Time, s
192 ================= ============= ===========
193 libc printf 1.04
194 libc++ std::ostream 3.05
195 {fmt} 6.1.1 fmt::print 0.75
196 Boost Format 1.67 boost::format 7.24
197 Folly Format folly::format 2.23
198 ================= ============= ===========
199
200 {fmt} is the fastest of the benchmarked methods, ~35% faster than ``printf``.
201
202 The above results were generated by building ``tinyformat_test.cpp`` on macOS
203 10.14.6 with ``clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT``, and taking the
204 best of three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"``
205 or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for
206 further details refer to the `source
207 <https://github.com/fmtlib/format-benchmark/blob/master/src/tinyformat-test.cc>`_.
208
209 {fmt} is up to 20-30x faster than ``std::ostringstream`` and ``sprintf`` on
210 floating-point formatting (`dtoa-benchmark <https://github.com/fmtlib/dtoa-benchmark>`_)
211 and faster than `double-conversion <https://github.com/google/double-conversion>`_ and
212 `ryu <https://github.com/ulfjack/ryu>`_:
213
214 .. image:: https://user-images.githubusercontent.com/576385/
215 95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png
216 :target: https://fmt.dev/unknown_mac64_clang12.0.html
217
218 Compile time and code bloat
219 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
220
221 The script `bloat-test.py
222 <https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_
223 from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_
224 tests compile time and code bloat for nontrivial projects.
225 It generates 100 translation units and uses ``printf()`` or its alternative
226 five times in each to simulate a medium sized project. The resulting
227 executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42),
228 macOS Sierra, best of three) is shown in the following tables.
229
230 **Optimized build (-O3)**
231
232 ============= =============== ==================== ==================
233 Method Compile Time, s Executable size, KiB Stripped size, KiB
234 ============= =============== ==================== ==================
235 printf 2.6 29 26
236 printf+string 16.4 29 26
237 iostreams 31.1 59 55
238 {fmt} 19.0 37 34
239 Boost Format 91.9 226 203
240 Folly Format 115.7 101 88
241 ============= =============== ==================== ==================
242
243 As you can see, {fmt} has 60% less overhead in terms of resulting binary code
244 size compared to iostreams and comes pretty close to ``printf``. Boost Format
245 and Folly Format have the largest overheads.
246
247 ``printf+string`` is the same as ``printf`` but with extra ``<string>``
248 include to measure the overhead of the latter.
249
250 **Non-optimized build**
251
252 ============= =============== ==================== ==================
253 Method Compile Time, s Executable size, KiB Stripped size, KiB
254 ============= =============== ==================== ==================
255 printf 2.2 33 30
256 printf+string 16.0 33 30
257 iostreams 28.3 56 52
258 {fmt} 18.2 59 50
259 Boost Format 54.1 365 303
260 Folly Format 79.9 445 430
261 ============= =============== ==================== ==================
262
263 ``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to
264 compare formatting function overhead only. Boost Format is a
265 header-only library so it doesn't provide any linkage options.
266
267 Running the tests
268 ~~~~~~~~~~~~~~~~~
269
270 Please refer to `Building the library`__ for the instructions on how to build
271 the library and run the unit tests.
272
273 __ https://fmt.dev/latest/usage.html#building-the-library
274
275 Benchmarks reside in a separate repository,
276 `format-benchmarks <https://github.com/fmtlib/format-benchmark>`_,
277 so to run the benchmarks you first need to clone this repository and
278 generate Makefiles with CMake::
279
280 $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
281 $ cd format-benchmark
282 $ cmake .
283
284 Then you can run the speed test::
285
286 $ make speed-test
287
288 or the bloat test::
289
290 $ make bloat-test
291
292 Migrating code
293 --------------
294
295 `clang-tidy-fmt <https://github.com/mikecrowe/clang-tidy-fmt>`_ provides clang
296 tidy checks for converting occurrences of ``printf`` and ``fprintf`` to
297 ``fmt::print``.
298
299 Projects using this library
300 ---------------------------
301
302 * `0 A.D. <https://play0ad.com/>`_: a free, open-source, cross-platform
303 real-time strategy game
304
305 * `2GIS <https://2gis.ru/>`_: free business listings with a city map
306
307 * `AMPL/MP <https://github.com/ampl/mp>`_:
308 an open-source library for mathematical programming
309
310 * `Aseprite <https://github.com/aseprite/aseprite>`_:
311 animated sprite editor & pixel art tool
312
313 * `AvioBook <https://www.aviobook.aero/en>`_: a comprehensive aircraft
314 operations suite
315
316 * `Blizzard Battle.net <https://battle.net/>`_: an online gaming platform
317
318 * `Celestia <https://celestia.space/>`_: real-time 3D visualization of space
319
320 * `Ceph <https://ceph.com/>`_: a scalable distributed storage system
321
322 * `ccache <https://ccache.dev/>`_: a compiler cache
323
324 * `ClickHouse <https://github.com/ClickHouse/ClickHouse>`_: analytical database
325 management system
326
327 * `CUAUV <https://cuauv.org/>`_: Cornell University's autonomous underwater
328 vehicle
329
330 * `Drake <https://drake.mit.edu/>`_: a planning, control, and analysis toolbox
331 for nonlinear dynamical systems (MIT)
332
333 * `Envoy <https://lyft.github.io/envoy/>`_: C++ L7 proxy and communication bus
334 (Lyft)
335
336 * `FiveM <https://fivem.net/>`_: a modification framework for GTA V
337
338 * `fmtlog <https://github.com/MengRao/fmtlog>`_: a performant fmtlib-style
339 logging library with latency in nanoseconds
340
341 * `Folly <https://github.com/facebook/folly>`_: Facebook open-source library
342
343 * `Grand Mountain Adventure
344 <https://store.steampowered.com/app/1247360/Grand_Mountain_Adventure/>`_:
345 A beautiful open-world ski & snowboarding game
346
347 * `HarpyWar/pvpgn <https://github.com/pvpgn/pvpgn-server>`_:
348 Player vs Player Gaming Network with tweaks
349
350 * `KBEngine <https://github.com/kbengine/kbengine>`_: an open-source MMOG server
351 engine
352
353 * `Keypirinha <https://keypirinha.com/>`_: a semantic launcher for Windows
354
355 * `Kodi <https://kodi.tv/>`_ (formerly xbmc): home theater software
356
357 * `Knuth <https://kth.cash/>`_: high-performance Bitcoin full-node
358
359 * `Microsoft Verona <https://github.com/microsoft/verona>`_:
360 research programming language for concurrent ownership
361
362 * `MongoDB <https://mongodb.com/>`_: distributed document database
363
364 * `MongoDB Smasher <https://github.com/duckie/mongo_smasher>`_: a small tool to
365 generate randomized datasets
366
367 * `OpenSpace <https://openspaceproject.com/>`_: an open-source
368 astrovisualization framework
369
370 * `PenUltima Online (POL) <https://www.polserver.com/>`_:
371 an MMO server, compatible with most Ultima Online clients
372
373 * `PyTorch <https://github.com/pytorch/pytorch>`_: an open-source machine
374 learning library
375
376 * `quasardb <https://www.quasardb.net/>`_: a distributed, high-performance,
377 associative database
378
379 * `Quill <https://github.com/odygrd/quill>`_: asynchronous low-latency logging library
380
381 * `QKW <https://github.com/ravijanjam/qkw>`_: generalizing aliasing to simplify
382 navigation, and executing complex multi-line terminal command sequences
383
384 * `redis-cerberus <https://github.com/HunanTV/redis-cerberus>`_: a Redis cluster
385 proxy
386
387 * `redpanda <https://vectorized.io/redpanda>`_: a 10x faster Kafka® replacement
388 for mission critical systems written in C++
389
390 * `rpclib <http://rpclib.net/>`_: a modern C++ msgpack-RPC server and client
391 library
392
393 * `Salesforce Analytics Cloud
394 <https://www.salesforce.com/analytics-cloud/overview/>`_:
395 business intelligence software
396
397 * `Scylla <https://www.scylladb.com/>`_: a Cassandra-compatible NoSQL data store
398 that can handle 1 million transactions per second on a single server
399
400 * `Seastar <http://www.seastar-project.org/>`_: an advanced, open-source C++
401 framework for high-performance server applications on modern hardware
402
403 * `spdlog <https://github.com/gabime/spdlog>`_: super fast C++ logging library
404
405 * `Stellar <https://www.stellar.org/>`_: financial platform
406
407 * `Touch Surgery <https://www.touchsurgery.com/>`_: surgery simulator
408
409 * `TrinityCore <https://github.com/TrinityCore/TrinityCore>`_: open-source
410 MMORPG framework
411
412 * `Windows Terminal <https://github.com/microsoft/terminal>`_: the new Windows
413 terminal
414
415 `More... <https://github.com/search?q=fmtlib&type=Code>`_
416
417 If you are aware of other projects using this library, please let me know
418 by `email <mailto:victor.zverovich@gmail.com>`_ or by submitting an
419 `issue <https://github.com/fmtlib/fmt/issues>`_.
420
421 Motivation
422 ----------
423
424 So why yet another formatting library?
425
426 There are plenty of methods for doing this task, from standard ones like
427 the printf family of function and iostreams to Boost Format and FastFormat
428 libraries. The reason for creating a new library is that every existing
429 solution that I found either had serious issues or didn't provide
430 all the features I needed.
431
432 printf
433 ~~~~~~
434
435 The good thing about ``printf`` is that it is pretty fast and readily available
436 being a part of the C standard library. The main drawback is that it
437 doesn't support user-defined types. ``printf`` also has safety issues although
438 they are somewhat mitigated with `__attribute__ ((format (printf, ...))
439 <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ in GCC.
440 There is a POSIX extension that adds positional arguments required for
441 `i18n <https://en.wikipedia.org/wiki/Internationalization_and_localization>`_
442 to ``printf`` but it is not a part of C99 and may not be available on some
443 platforms.
444
445 iostreams
446 ~~~~~~~~~
447
448 The main issue with iostreams is best illustrated with an example:
449
450 .. code:: c++
451
452 std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n";
453
454 which is a lot of typing compared to printf:
455
456 .. code:: c++
457
458 printf("%.2f\n", 1.23456);
459
460 Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams
461 don't support positional arguments by design.
462
463 The good part is that iostreams support user-defined types and are safe although
464 error handling is awkward.
465
466 Boost Format
467 ~~~~~~~~~~~~
468
469 This is a very powerful library which supports both ``printf``-like format
470 strings and positional arguments. Its main drawback is performance. According to
471 various benchmarks, it is much slower than other methods considered here. Boost
472 Format also has excessive build times and severe code bloat issues (see
473 `Benchmarks`_).
474
475 FastFormat
476 ~~~~~~~~~~
477
478 This is an interesting library which is fast, safe and has positional arguments.
479 However, it has significant limitations, citing its author:
480
481 Three features that have no hope of being accommodated within the
482 current design are:
483
484 * Leading zeros (or any other non-space padding)
485 * Octal/hexadecimal encoding
486 * Runtime width/alignment specification
487
488 It is also quite big and has a heavy dependency, STLSoft, which might be too
489 restrictive for using it in some projects.
490
491 Boost Spirit.Karma
492 ~~~~~~~~~~~~~~~~~~
493
494 This is not really a formatting library but I decided to include it here for
495 completeness. As iostreams, it suffers from the problem of mixing verbatim text
496 with arguments. The library is pretty fast, but slower on integer formatting
497 than ``fmt::format_to`` with format string compilation on Karma's own benchmark,
498 see `Converting a hundred million integers to strings per second
499 <http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_.
500
501 License
502 -------
503
504 {fmt} is distributed under the MIT `license
505 <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_.
506
507 Documentation License
508 ---------------------
509
510 The `Format String Syntax <https://fmt.dev/latest/syntax.html>`_
511 section in the documentation is based on the one from Python `string module
512 documentation <https://docs.python.org/3/library/string.html#module-string>`_.
513 For this reason the documentation is distributed under the Python Software
514 Foundation license available in `doc/python-license.txt
515 <https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt>`_.
516 It only applies if you distribute the documentation of {fmt}.
517
518 Maintainers
519 -----------
520
521 The {fmt} library is maintained by Victor Zverovich (`vitaut
522 <https://github.com/vitaut>`_) and Jonathan Müller (`foonathan
523 <https://github.com/foonathan>`_) with contributions from many other people.
524 See `Contributors <https://github.com/fmtlib/fmt/graphs/contributors>`_ and
525 `Releases <https://github.com/fmtlib/fmt/releases>`_ for some of the names.
526 Let us know if your contribution is not listed or mentioned incorrectly and
527 we'll make it right.
+0
-17
source/misc/embedded_libs/fmt-8.1.1/doc/CMakeLists.txt less more
0 find_program(DOXYGEN doxygen)
1 if (NOT DOXYGEN)
2 message(STATUS "Target 'doc' disabled (requires doxygen)")
3 return ()
4 endif ()
5
6 find_package(PythonInterp QUIET REQUIRED)
7
8 add_custom_target(doc
9 COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/build.py
10 ${FMT_VERSION}
11 SOURCES api.rst syntax.rst usage.rst build.py conf.py _templates/layout.html)
12
13 include(GNUInstallDirs)
14 install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html/
15 DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/doc/fmt OPTIONAL
16 PATTERN ".doctrees" EXCLUDE)
+0
-7
source/misc/embedded_libs/fmt-8.1.1/doc/_static/bootstrap.min.js less more
0 /*!
1 * Bootstrap v3.3.4 (http://getbootstrap.com)
2 * Copyright 2011-2015 Twitter, Inc.
3 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
4 */
5 if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.4",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.4",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.4",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.4",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.4",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27|32)/.test(b.which)&&!/input|textarea/i.test(b.target.tagName)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g&&27!=b.which||g&&27==b.which)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(b.target);38==b.which&&j>0&&j--,40==b.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="menu"]',g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.4",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in").attr("aria-hidden",!1),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a('<div class="modal-backdrop '+e+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.3.4",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport),this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-m<p.top?"bottom":"right"==h&&k.right+l>p.width?"left":"left"==h&&k.left-l<p.left?"right":h,f.removeClass(n).addClass(h)}var q=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(q,h);var r=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",r).emulateTransitionEnd(c.TRANSITION_DURATION):r()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.4",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.4",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.4",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){
6 var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.4",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a(document.body).height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
+0
-28
source/misc/embedded_libs/fmt-8.1.1/doc/_static/breathe.css less more
0
1 /* -- breathe specific styles ----------------------------------------------- */
2
3 /* So enum value descriptions are displayed inline to the item */
4 .breatheenumvalues li tt + p {
5 display: inline;
6 }
7
8 /* So parameter descriptions are displayed inline to the item */
9 .breatheparameterlist li tt + p {
10 display: inline;
11 }
12
13 .container .breathe-sectiondef {
14 width: inherit;
15 }
16
17 .github-btn {
18 border: 0;
19 overflow: hidden;
20 }
21
22 .jumbotron {
23 background-size: 100% 4px;
24 background-repeat: repeat-y;
25 color: white;
26 text-align: center;
27 }
source/misc/embedded_libs/fmt-8.1.1/doc/_static/fonts/glyphicons-halflings-regular.eot less more
Binary diff not shown
+0
-229
source/misc/embedded_libs/fmt-8.1.1/doc/_static/fonts/glyphicons-halflings-regular.svg less more
0 <?xml version="1.0" standalone="no"?>
1 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
2 <svg xmlns="http://www.w3.org/2000/svg">
3 <metadata></metadata>
4 <defs>
5 <font id="glyphicons_halflingsregular" horiz-adv-x="1200" >
6 <font-face units-per-em="1200" ascent="960" descent="-240" />
7 <missing-glyph horiz-adv-x="500" />
8 <glyph />
9 <glyph />
10 <glyph unicode="&#xd;" />
11 <glyph unicode=" " />
12 <glyph unicode="*" d="M100 500v200h259l-183 183l141 141l183 -183v259h200v-259l183 183l141 -141l-183 -183h259v-200h-259l183 -183l-141 -141l-183 183v-259h-200v259l-183 -183l-141 141l183 183h-259z" />
13 <glyph unicode="+" d="M0 400v300h400v400h300v-400h400v-300h-400v-400h-300v400h-400z" />
14 <glyph unicode="&#xa0;" />
15 <glyph unicode="&#x2000;" horiz-adv-x="652" />
16 <glyph unicode="&#x2001;" horiz-adv-x="1304" />
17 <glyph unicode="&#x2002;" horiz-adv-x="652" />
18 <glyph unicode="&#x2003;" horiz-adv-x="1304" />
19 <glyph unicode="&#x2004;" horiz-adv-x="434" />
20 <glyph unicode="&#x2005;" horiz-adv-x="326" />
21 <glyph unicode="&#x2006;" horiz-adv-x="217" />
22 <glyph unicode="&#x2007;" horiz-adv-x="217" />
23 <glyph unicode="&#x2008;" horiz-adv-x="163" />
24 <glyph unicode="&#x2009;" horiz-adv-x="260" />
25 <glyph unicode="&#x200a;" horiz-adv-x="72" />
26 <glyph unicode="&#x202f;" horiz-adv-x="260" />
27 <glyph unicode="&#x205f;" horiz-adv-x="326" />
28 <glyph unicode="&#x20ac;" d="M100 500l100 100h113q0 47 5 100h-218l100 100h135q37 167 112 257q117 141 297 141q242 0 354 -189q60 -103 66 -209h-181q0 55 -25.5 99t-63.5 68t-75 36.5t-67 12.5q-24 0 -52.5 -10t-62.5 -32t-65.5 -67t-50.5 -107h379l-100 -100h-300q-6 -46 -6 -100h406l-100 -100 h-300q9 -74 33 -132t52.5 -91t62 -54.5t59 -29t46.5 -7.5q29 0 66 13t75 37t63.5 67.5t25.5 96.5h174q-31 -172 -128 -278q-107 -117 -274 -117q-205 0 -324 158q-36 46 -69 131.5t-45 205.5h-217z" />
29 <glyph unicode="&#x2212;" d="M200 400h900v300h-900v-300z" />
30 <glyph unicode="&#x25fc;" horiz-adv-x="500" d="M0 0z" />
31 <glyph unicode="&#x2601;" d="M-14 494q0 -80 56.5 -137t135.5 -57h750q120 0 205 86.5t85 207.5t-85 207t-205 86q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5z" />
32 <glyph unicode="&#x2709;" d="M0 100l400 400l200 -200l200 200l400 -400h-1200zM0 300v600l300 -300zM0 1100l600 -603l600 603h-1200zM900 600l300 300v-600z" />
33 <glyph unicode="&#x270f;" d="M-13 -13l333 112l-223 223zM187 403l214 -214l614 614l-214 214zM887 1103l214 -214l99 92q13 13 13 32.5t-13 33.5l-153 153q-15 13 -33 13t-33 -13z" />
34 <glyph unicode="&#xe001;" d="M0 1200h1200l-500 -550v-550h300v-100h-800v100h300v550z" />
35 <glyph unicode="&#xe002;" d="M14 84q18 -55 86 -75.5t147 5.5q65 21 109 69t44 90v606l600 155v-521q-64 16 -138 -7q-79 -26 -122.5 -83t-25.5 -111q18 -55 86 -75.5t147 4.5q70 23 111.5 63.5t41.5 95.5v881q0 10 -7 15.5t-17 2.5l-752 -193q-10 -3 -17 -12.5t-7 -19.5v-689q-64 17 -138 -7 q-79 -25 -122.5 -82t-25.5 -112z" />
36 <glyph unicode="&#xe003;" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233z" />
37 <glyph unicode="&#xe005;" d="M100 784q0 64 28 123t73 100.5t104.5 64t119 20.5t120 -38.5t104.5 -104.5q48 69 109.5 105t121.5 38t118.5 -20.5t102.5 -64t71 -100.5t27 -123q0 -57 -33.5 -117.5t-94 -124.5t-126.5 -127.5t-150 -152.5t-146 -174q-62 85 -145.5 174t-149.5 152.5t-126.5 127.5 t-94 124.5t-33.5 117.5z" />
38 <glyph unicode="&#xe006;" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1z" />
39 <glyph unicode="&#xe007;" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1zM237 700l196 -142l-73 -226l192 140l195 -141l-74 229l193 140h-235l-77 211l-78 -211h-239z" />
40 <glyph unicode="&#xe008;" d="M0 0v143l400 257v100q-37 0 -68.5 74.5t-31.5 125.5v200q0 124 88 212t212 88t212 -88t88 -212v-200q0 -51 -31.5 -125.5t-68.5 -74.5v-100l400 -257v-143h-1200z" />
41 <glyph unicode="&#xe009;" d="M0 0v1100h1200v-1100h-1200zM100 100h100v100h-100v-100zM100 300h100v100h-100v-100zM100 500h100v100h-100v-100zM100 700h100v100h-100v-100zM100 900h100v100h-100v-100zM300 100h600v400h-600v-400zM300 600h600v400h-600v-400zM1000 100h100v100h-100v-100z M1000 300h100v100h-100v-100zM1000 500h100v100h-100v-100zM1000 700h100v100h-100v-100zM1000 900h100v100h-100v-100z" />
42 <glyph unicode="&#xe010;" d="M0 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM0 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400 q-21 0 -35.5 14.5t-14.5 35.5zM600 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM600 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400 q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5z" />
43 <glyph unicode="&#xe011;" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200 q-21 0 -35.5 14.5t-14.5 35.5zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 450v200q0 21 14.5 35.5t35.5 14.5h200 q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5z" />
44 <glyph unicode="&#xe012;" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v200q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5 t-14.5 -35.5v-200zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5z" />
45 <glyph unicode="&#xe013;" d="M29 454l419 -420l818 820l-212 212l-607 -607l-206 207z" />
46 <glyph unicode="&#xe014;" d="M106 318l282 282l-282 282l212 212l282 -282l282 282l212 -212l-282 -282l282 -282l-212 -212l-282 282l-282 -282z" />
47 <glyph unicode="&#xe015;" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233zM300 600v200h100v100h200v-100h100v-200h-100v-100h-200v100h-100z" />
48 <glyph unicode="&#xe016;" d="M23 694q0 200 142 342t342 142t342 -142t142 -342q0 -141 -78 -262l300 -299q7 -7 7 -18t-7 -18l-109 -109q-8 -8 -18 -8t-18 8l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 694q0 -136 97 -233t234 -97t233.5 97t96.5 233t-96.5 233t-233.5 97t-234 -97 t-97 -233zM300 601h400v200h-400v-200z" />
49 <glyph unicode="&#xe017;" d="M23 600q0 183 105 331t272 210v-166q-103 -55 -165 -155t-62 -220q0 -177 125 -302t302 -125t302 125t125 302q0 120 -62 220t-165 155v166q167 -62 272 -210t105 -331q0 -118 -45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5 zM500 750q0 -21 14.5 -35.5t35.5 -14.5h100q21 0 35.5 14.5t14.5 35.5v400q0 21 -14.5 35.5t-35.5 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-400z" />
50 <glyph unicode="&#xe018;" d="M100 1h200v300h-200v-300zM400 1v500h200v-500h-200zM700 1v800h200v-800h-200zM1000 1v1200h200v-1200h-200z" />
51 <glyph unicode="&#xe019;" d="M26 601q0 -33 6 -74l151 -38l2 -6q14 -49 38 -93l3 -5l-80 -134q45 -59 105 -105l133 81l5 -3q45 -26 94 -39l5 -2l38 -151q40 -5 74 -5q27 0 74 5l38 151l6 2q46 13 93 39l5 3l134 -81q56 44 104 105l-80 134l3 5q24 44 39 93l1 6l152 38q5 40 5 74q0 28 -5 73l-152 38 l-1 6q-16 51 -39 93l-3 5l80 134q-44 58 -104 105l-134 -81l-5 3q-45 25 -93 39l-6 1l-38 152q-40 5 -74 5q-27 0 -74 -5l-38 -152l-5 -1q-50 -14 -94 -39l-5 -3l-133 81q-59 -47 -105 -105l80 -134l-3 -5q-25 -47 -38 -93l-2 -6l-151 -38q-6 -48 -6 -73zM385 601 q0 88 63 151t152 63t152 -63t63 -151q0 -89 -63 -152t-152 -63t-152 63t-63 152z" />
52 <glyph unicode="&#xe020;" d="M100 1025v50q0 10 7.5 17.5t17.5 7.5h275v100q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5v-100h275q10 0 17.5 -7.5t7.5 -17.5v-50q0 -11 -7 -18t-18 -7h-1050q-11 0 -18 7t-7 18zM200 100v800h900v-800q0 -41 -29.5 -71t-70.5 -30h-700q-41 0 -70.5 30 t-29.5 71zM300 100h100v700h-100v-700zM500 100h100v700h-100v-700zM500 1100h300v100h-300v-100zM700 100h100v700h-100v-700zM900 100h100v700h-100v-700z" />
53 <glyph unicode="&#xe021;" d="M1 601l656 644l644 -644h-200v-600h-300v400h-300v-400h-300v600h-200z" />
54 <glyph unicode="&#xe022;" d="M100 25v1150q0 11 7 18t18 7h475v-500h400v-675q0 -11 -7 -18t-18 -7h-850q-11 0 -18 7t-7 18zM700 800v300l300 -300h-300z" />
55 <glyph unicode="&#xe023;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 500v400h100 v-300h200v-100h-300z" />
56 <glyph unicode="&#xe024;" d="M-100 0l431 1200h209l-21 -300h162l-20 300h208l431 -1200h-538l-41 400h-242l-40 -400h-539zM488 500h224l-27 300h-170z" />
57 <glyph unicode="&#xe025;" d="M0 0v400h490l-290 300h200v500h300v-500h200l-290 -300h490v-400h-1100zM813 200h175v100h-175v-100z" />
58 <glyph unicode="&#xe026;" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM188 600q0 -170 121 -291t291 -121t291 121t121 291t-121 291t-291 121 t-291 -121t-121 -291zM350 600h150v300h200v-300h150l-250 -300z" />
59 <glyph unicode="&#xe027;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM350 600l250 300 l250 -300h-150v-300h-200v300h-150z" />
60 <glyph unicode="&#xe028;" d="M0 25v475l200 700h800l199 -700l1 -475q0 -11 -7 -18t-18 -7h-1150q-11 0 -18 7t-7 18zM200 500h200l50 -200h300l50 200h200l-97 500h-606z" />
61 <glyph unicode="&#xe029;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 397v401 l297 -200z" />
62 <glyph unicode="&#xe030;" d="M23 600q0 -118 45.5 -224.5t123 -184t184 -123t224.5 -45.5t224.5 45.5t184 123t123 184t45.5 224.5h-150q0 -177 -125 -302t-302 -125t-302 125t-125 302t125 302t302 125q136 0 246 -81l-146 -146h400v400l-145 -145q-157 122 -355 122q-118 0 -224.5 -45.5t-184 -123 t-123 -184t-45.5 -224.5z" />
63 <glyph unicode="&#xe031;" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5q198 0 355 -122l145 145v-400h-400l147 147q-112 80 -247 80q-177 0 -302 -125t-125 -302h-150zM100 0v400h400l-147 -147q112 -80 247 -80q177 0 302 125t125 302h150q0 -118 -45.5 -224.5t-123 -184t-184 -123 t-224.5 -45.5q-198 0 -355 122z" />
64 <glyph unicode="&#xe032;" d="M100 0h1100v1200h-1100v-1200zM200 100v900h900v-900h-900zM300 200v100h100v-100h-100zM300 400v100h100v-100h-100zM300 600v100h100v-100h-100zM300 800v100h100v-100h-100zM500 200h500v100h-500v-100zM500 400v100h500v-100h-500zM500 600v100h500v-100h-500z M500 800v100h500v-100h-500z" />
65 <glyph unicode="&#xe033;" d="M0 100v600q0 41 29.5 70.5t70.5 29.5h100v200q0 82 59 141t141 59h300q82 0 141 -59t59 -141v-200h100q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-900q-41 0 -70.5 29.5t-29.5 70.5zM400 800h300v150q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-150z" />
66 <glyph unicode="&#xe034;" d="M100 0v1100h100v-1100h-100zM300 400q60 60 127.5 84t127.5 17.5t122 -23t119 -30t110 -11t103 42t91 120.5v500q-40 -81 -101.5 -115.5t-127.5 -29.5t-138 25t-139.5 40t-125.5 25t-103 -29.5t-65 -115.5v-500z" />
67 <glyph unicode="&#xe035;" d="M0 275q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 127 70.5 231.5t184.5 161.5t245 57t245 -57t184.5 -161.5t70.5 -231.5v-300q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 116 -49.5 227t-131 192.5t-192.5 131t-227 49.5t-227 -49.5t-192.5 -131t-131 -192.5 t-49.5 -227v-300zM200 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14zM800 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14z" />
68 <glyph unicode="&#xe036;" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM688 459l141 141l-141 141l71 71l141 -141l141 141l71 -71l-141 -141l141 -141l-71 -71l-141 141l-141 -141z" />
69 <glyph unicode="&#xe037;" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM700 857l69 53q111 -135 111 -310q0 -169 -106 -302l-67 54q86 110 86 248q0 146 -93 257z" />
70 <glyph unicode="&#xe038;" d="M0 401v400h300l300 200v-800l-300 200h-300zM702 858l69 53q111 -135 111 -310q0 -170 -106 -303l-67 55q86 110 86 248q0 145 -93 257zM889 951l7 -8q123 -151 123 -344q0 -189 -119 -339l-7 -8l81 -66l6 8q142 178 142 405q0 230 -144 408l-6 8z" />
71 <glyph unicode="&#xe039;" d="M0 0h500v500h-200v100h-100v-100h-200v-500zM0 600h100v100h400v100h100v100h-100v300h-500v-600zM100 100v300h300v-300h-300zM100 800v300h300v-300h-300zM200 200v100h100v-100h-100zM200 900h100v100h-100v-100zM500 500v100h300v-300h200v-100h-100v-100h-200v100 h-100v100h100v200h-200zM600 0v100h100v-100h-100zM600 1000h100v-300h200v-300h300v200h-200v100h200v500h-600v-200zM800 800v300h300v-300h-300zM900 0v100h300v-100h-300zM900 900v100h100v-100h-100zM1100 200v100h100v-100h-100z" />
72 <glyph unicode="&#xe040;" d="M0 200h100v1000h-100v-1000zM100 0v100h300v-100h-300zM200 200v1000h100v-1000h-100zM500 0v91h100v-91h-100zM500 200v1000h200v-1000h-200zM700 0v91h100v-91h-100zM800 200v1000h100v-1000h-100zM900 0v91h200v-91h-200zM1000 200v1000h200v-1000h-200z" />
73 <glyph unicode="&#xe041;" d="M0 700l1 475q0 10 7.5 17.5t17.5 7.5h474l700 -700l-500 -500zM148 953q0 -42 29 -71q30 -30 71.5 -30t71.5 30q29 29 29 71t-29 71q-30 30 -71.5 30t-71.5 -30q-29 -29 -29 -71z" />
74 <glyph unicode="&#xe042;" d="M1 700l1 475q0 11 7 18t18 7h474l700 -700l-500 -500zM148 953q0 -42 30 -71q29 -30 71 -30t71 30q30 29 30 71t-30 71q-29 30 -71 30t-71 -30q-30 -29 -30 -71zM701 1200h100l700 -700l-500 -500l-50 50l450 450z" />
75 <glyph unicode="&#xe043;" d="M100 0v1025l175 175h925v-1000l-100 -100v1000h-750l-100 -100h750v-1000h-900z" />
76 <glyph unicode="&#xe044;" d="M200 0l450 444l450 -443v1150q0 20 -14.5 35t-35.5 15h-800q-21 0 -35.5 -15t-14.5 -35v-1151z" />
77 <glyph unicode="&#xe045;" d="M0 100v700h200l100 -200h600l100 200h200v-700h-200v200h-800v-200h-200zM253 829l40 -124h592l62 124l-94 346q-2 11 -10 18t-18 7h-450q-10 0 -18 -7t-10 -18zM281 24l38 152q2 10 11.5 17t19.5 7h500q10 0 19.5 -7t11.5 -17l38 -152q2 -10 -3.5 -17t-15.5 -7h-600 q-10 0 -15.5 7t-3.5 17z" />
78 <glyph unicode="&#xe046;" d="M0 200q0 -41 29.5 -70.5t70.5 -29.5h1000q41 0 70.5 29.5t29.5 70.5v600q0 41 -29.5 70.5t-70.5 29.5h-150q-4 8 -11.5 21.5t-33 48t-53 61t-69 48t-83.5 21.5h-200q-41 0 -82 -20.5t-70 -50t-52 -59t-34 -50.5l-12 -20h-150q-41 0 -70.5 -29.5t-29.5 -70.5v-600z M356 500q0 100 72 172t172 72t172 -72t72 -172t-72 -172t-172 -72t-172 72t-72 172zM494 500q0 -44 31 -75t75 -31t75 31t31 75t-31 75t-75 31t-75 -31t-31 -75zM900 700v100h100v-100h-100z" />
79 <glyph unicode="&#xe047;" d="M53 0h365v66q-41 0 -72 11t-49 38t1 71l92 234h391l82 -222q16 -45 -5.5 -88.5t-74.5 -43.5v-66h417v66q-34 1 -74 43q-18 19 -33 42t-21 37l-6 13l-385 998h-93l-399 -1006q-24 -48 -52 -75q-12 -12 -33 -25t-36 -20l-15 -7v-66zM416 521l178 457l46 -140l116 -317h-340 z" />
80 <glyph unicode="&#xe048;" d="M100 0v89q41 7 70.5 32.5t29.5 65.5v827q0 28 -1 39.5t-5.5 26t-15.5 21t-29 14t-49 14.5v71l471 -1q120 0 213 -88t93 -228q0 -55 -11.5 -101.5t-28 -74t-33.5 -47.5t-28 -28l-12 -7q8 -3 21.5 -9t48 -31.5t60.5 -58t47.5 -91.5t21.5 -129q0 -84 -59 -156.5t-142 -111 t-162 -38.5h-500zM400 200h161q89 0 153 48.5t64 132.5q0 90 -62.5 154.5t-156.5 64.5h-159v-400zM400 700h139q76 0 130 61.5t54 138.5q0 82 -84 130.5t-239 48.5v-379z" />
81 <glyph unicode="&#xe049;" d="M200 0v57q77 7 134.5 40.5t65.5 80.5l173 849q10 56 -10 74t-91 37q-6 1 -10.5 2.5t-9.5 2.5v57h425l2 -57q-33 -8 -62 -25.5t-46 -37t-29.5 -38t-17.5 -30.5l-5 -12l-128 -825q-10 -52 14 -82t95 -36v-57h-500z" />
82 <glyph unicode="&#xe050;" d="M-75 200h75v800h-75l125 167l125 -167h-75v-800h75l-125 -167zM300 900v300h150h700h150v-300h-50q0 29 -8 48.5t-18.5 30t-33.5 15t-39.5 5.5t-50.5 1h-200v-850l100 -50v-100h-400v100l100 50v850h-200q-34 0 -50.5 -1t-40 -5.5t-33.5 -15t-18.5 -30t-8.5 -48.5h-49z " />
83 <glyph unicode="&#xe051;" d="M33 51l167 125v-75h800v75l167 -125l-167 -125v75h-800v-75zM100 901v300h150h700h150v-300h-50q0 29 -8 48.5t-18 30t-33.5 15t-40 5.5t-50.5 1h-200v-650l100 -50v-100h-400v100l100 50v650h-200q-34 0 -50.5 -1t-39.5 -5.5t-33.5 -15t-18.5 -30t-8 -48.5h-50z" />
84 <glyph unicode="&#xe052;" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 350q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM0 650q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1000q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 950q0 -20 14.5 -35t35.5 -15h600q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-600q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" />
85 <glyph unicode="&#xe053;" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 650q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM200 350q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM200 950q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" />
86 <glyph unicode="&#xe054;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM100 650v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1000q-21 0 -35.5 15 t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM500 950v100q0 21 14.5 35.5t35.5 14.5h600q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-600 q-21 0 -35.5 15t-14.5 35z" />
87 <glyph unicode="&#xe055;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100 q-21 0 -35.5 15t-14.5 35z" />
88 <glyph unicode="&#xe056;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM300 50v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800 q-21 0 -35.5 15t-14.5 35zM300 650v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 950v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15 h-800q-21 0 -35.5 15t-14.5 35z" />
89 <glyph unicode="&#xe057;" d="M-101 500v100h201v75l166 -125l-166 -125v75h-201zM300 0h100v1100h-100v-1100zM500 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35 v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 650q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100 q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100z" />
90 <glyph unicode="&#xe058;" d="M1 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 650 q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM801 0v1100h100v-1100 h-100zM934 550l167 -125v75h200v100h-200v75z" />
91 <glyph unicode="&#xe059;" d="M0 275v650q0 31 22 53t53 22h750q31 0 53 -22t22 -53v-650q0 -31 -22 -53t-53 -22h-750q-31 0 -53 22t-22 53zM900 600l300 300v-600z" />
92 <glyph unicode="&#xe060;" d="M0 44v1012q0 18 13 31t31 13h1112q19 0 31.5 -13t12.5 -31v-1012q0 -18 -12.5 -31t-31.5 -13h-1112q-18 0 -31 13t-13 31zM100 263l247 182l298 -131l-74 156l293 318l236 -288v500h-1000v-737zM208 750q0 56 39 95t95 39t95 -39t39 -95t-39 -95t-95 -39t-95 39t-39 95z " />
93 <glyph unicode="&#xe062;" d="M148 745q0 124 60.5 231.5t165 172t226.5 64.5q123 0 227 -63t164.5 -169.5t60.5 -229.5t-73 -272q-73 -114 -166.5 -237t-150.5 -189l-57 -66q-10 9 -27 26t-66.5 70.5t-96 109t-104 135.5t-100.5 155q-63 139 -63 262zM342 772q0 -107 75.5 -182.5t181.5 -75.5 q107 0 182.5 75.5t75.5 182.5t-75.5 182t-182.5 75t-182 -75.5t-75 -181.5z" />
94 <glyph unicode="&#xe063;" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM173 600q0 -177 125.5 -302t301.5 -125v854q-176 0 -301.5 -125 t-125.5 -302z" />
95 <glyph unicode="&#xe064;" d="M117 406q0 94 34 186t88.5 172.5t112 159t115 177t87.5 194.5q21 -71 57.5 -142.5t76 -130.5t83 -118.5t82 -117t70 -116t50 -125.5t18.5 -136q0 -89 -39 -165.5t-102 -126.5t-140 -79.5t-156 -33.5q-114 6 -211.5 53t-161.5 139t-64 210zM243 414q14 -82 59.5 -136 t136.5 -80l16 98q-7 6 -18 17t-34 48t-33 77q-15 73 -14 143.5t10 122.5l9 51q-92 -110 -119.5 -185t-12.5 -156z" />
96 <glyph unicode="&#xe065;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5q366 -6 397 -14l-186 -186h-311q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v125l200 200v-225q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM436 341l161 50l412 412l-114 113l-405 -405zM995 1015l113 -113l113 113l-21 85l-92 28z" />
97 <glyph unicode="&#xe066;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h261l2 -80q-133 -32 -218 -120h-145q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5l200 153v-53q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5 zM423 524q30 38 81.5 64t103 35.5t99 14t77.5 3.5l29 -1v-209l360 324l-359 318v-216q-7 0 -19 -1t-48 -8t-69.5 -18.5t-76.5 -37t-76.5 -59t-62 -88t-39.5 -121.5z" />
98 <glyph unicode="&#xe067;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q61 0 127 -23l-178 -177h-349q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v69l200 200v-169q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM342 632l283 -284l567 567l-137 137l-430 -431l-146 147z" />
99 <glyph unicode="&#xe068;" d="M0 603l300 296v-198h200v200h-200l300 300l295 -300h-195v-200h200v198l300 -296l-300 -300v198h-200v-200h195l-295 -300l-300 300h200v200h-200v-198z" />
100 <glyph unicode="&#xe069;" d="M200 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-1100l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" />
101 <glyph unicode="&#xe070;" d="M0 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-487l500 487v-1100l-500 488v-488l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" />
102 <glyph unicode="&#xe071;" d="M136 550l564 550v-487l500 487v-1100l-500 488v-488z" />
103 <glyph unicode="&#xe072;" d="M200 0l900 550l-900 550v-1100z" />
104 <glyph unicode="&#xe073;" d="M200 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5t-14.5 -35.5v-800zM600 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" />
105 <glyph unicode="&#xe074;" d="M200 150q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v800q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" />
106 <glyph unicode="&#xe075;" d="M0 0v1100l500 -487v487l564 -550l-564 -550v488z" />
107 <glyph unicode="&#xe076;" d="M0 0v1100l500 -487v487l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438l-500 -488v488z" />
108 <glyph unicode="&#xe077;" d="M300 0v1100l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438z" />
109 <glyph unicode="&#xe078;" d="M100 250v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5zM100 500h1100l-550 564z" />
110 <glyph unicode="&#xe079;" d="M185 599l592 -592l240 240l-353 353l353 353l-240 240z" />
111 <glyph unicode="&#xe080;" d="M272 194l353 353l-353 353l241 240l572 -571l21 -22l-1 -1v-1l-592 -591z" />
112 <glyph unicode="&#xe081;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM300 500h200v-200h200v200h200v200h-200v200h-200v-200h-200v-200z" />
113 <glyph unicode="&#xe082;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM300 500h600v200h-600v-200z" />
114 <glyph unicode="&#xe083;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM246 459l213 -213l141 142l141 -142l213 213l-142 141l142 141l-213 212l-141 -141l-141 142l-212 -213l141 -141 z" />
115 <glyph unicode="&#xe084;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM270 551l276 -277l411 411l-175 174l-236 -236l-102 102z" />
116 <glyph unicode="&#xe085;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM364 700h143q4 0 11.5 -1t11 -1t6.5 3t3 9t1 11t3.5 8.5t3.5 6t5.5 4t6.5 2.5t9 1.5t9 0.5h11.5h12.5 q19 0 30 -10t11 -26q0 -22 -4 -28t-27 -22q-5 -1 -12.5 -3t-27 -13.5t-34 -27t-26.5 -46t-11 -68.5h200q5 3 14 8t31.5 25.5t39.5 45.5t31 69t14 94q0 51 -17.5 89t-42 58t-58.5 32t-58.5 15t-51.5 3q-50 0 -90.5 -12t-75 -38.5t-53.5 -74.5t-19 -114zM500 300h200v100h-200 v-100z" />
117 <glyph unicode="&#xe086;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM400 300h400v100h-100v300h-300v-100h100v-200h-100v-100zM500 800h200v100h-200v-100z" />
118 <glyph unicode="&#xe087;" d="M0 500v200h195q31 125 98.5 199.5t206.5 100.5v200h200v-200q54 -20 113 -60t112.5 -105.5t71.5 -134.5h203v-200h-203q-25 -102 -116.5 -186t-180.5 -117v-197h-200v197q-140 27 -208 102.5t-98 200.5h-194zM290 500q24 -73 79.5 -127.5t130.5 -78.5v206h200v-206 q149 48 201 206h-201v200h200q-25 74 -75.5 127t-124.5 77v-204h-200v203q-75 -23 -130 -77t-79 -126h209v-200h-210z" />
119 <glyph unicode="&#xe088;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM356 465l135 135 l-135 135l109 109l135 -135l135 135l109 -109l-135 -135l135 -135l-109 -109l-135 135l-135 -135z" />
120 <glyph unicode="&#xe089;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM322 537l141 141 l87 -87l204 205l142 -142l-346 -345z" />
121 <glyph unicode="&#xe090;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -115 62 -215l568 567q-100 62 -216 62q-171 0 -292.5 -121.5t-121.5 -292.5zM391 245q97 -59 209 -59q171 0 292.5 121.5t121.5 292.5 q0 112 -59 209z" />
122 <glyph unicode="&#xe091;" d="M0 547l600 453v-300h600v-300h-600v-301z" />
123 <glyph unicode="&#xe092;" d="M0 400v300h600v300l600 -453l-600 -448v301h-600z" />
124 <glyph unicode="&#xe093;" d="M204 600l450 600l444 -600h-298v-600h-300v600h-296z" />
125 <glyph unicode="&#xe094;" d="M104 600h296v600h300v-600h298l-449 -600z" />
126 <glyph unicode="&#xe095;" d="M0 200q6 132 41 238.5t103.5 193t184 138t271.5 59.5v271l600 -453l-600 -448v301q-95 -2 -183 -20t-170 -52t-147 -92.5t-100 -135.5z" />
127 <glyph unicode="&#xe096;" d="M0 0v400l129 -129l294 294l142 -142l-294 -294l129 -129h-400zM635 777l142 -142l294 294l129 -129v400h-400l129 -129z" />
128 <glyph unicode="&#xe097;" d="M34 176l295 295l-129 129h400v-400l-129 130l-295 -295zM600 600v400l129 -129l295 295l142 -141l-295 -295l129 -130h-400z" />
129 <glyph unicode="&#xe101;" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5t224.5 -45.5t184 -123t123 -184t45.5 -224.5t-45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5zM456 851l58 -302q4 -20 21.5 -34.5t37.5 -14.5h54q20 0 37.5 14.5 t21.5 34.5l58 302q4 20 -8 34.5t-32 14.5h-207q-21 0 -33 -14.5t-8 -34.5zM500 300h200v100h-200v-100z" />
130 <glyph unicode="&#xe102;" d="M0 800h100v-200h400v300h200v-300h400v200h100v100h-111q1 1 1 6.5t-1.5 15t-3.5 17.5l-34 172q-11 39 -41.5 63t-69.5 24q-32 0 -61 -17l-239 -144q-22 -13 -40 -35q-19 24 -40 36l-238 144q-33 18 -62 18q-39 0 -69.5 -23t-40.5 -61l-35 -177q-2 -8 -3 -18t-1 -15v-6 h-111v-100zM100 0h400v400h-400v-400zM200 900q-3 0 14 48t36 96l18 47l213 -191h-281zM700 0v400h400v-400h-400zM731 900l202 197q5 -12 12 -32.5t23 -64t25 -72t7 -28.5h-269z" />
131 <glyph unicode="&#xe103;" d="M0 -22v143l216 193q-9 53 -13 83t-5.5 94t9 113t38.5 114t74 124q47 60 99.5 102.5t103 68t127.5 48t145.5 37.5t184.5 43.5t220 58.5q0 -189 -22 -343t-59 -258t-89 -181.5t-108.5 -120t-122 -68t-125.5 -30t-121.5 -1.5t-107.5 12.5t-87.5 17t-56.5 7.5l-99 -55z M238.5 300.5q19.5 -6.5 86.5 76.5q55 66 367 234q70 38 118.5 69.5t102 79t99 111.5t86.5 148q22 50 24 60t-6 19q-7 5 -17 5t-26.5 -14.5t-33.5 -39.5q-35 -51 -113.5 -108.5t-139.5 -89.5l-61 -32q-369 -197 -458 -401q-48 -111 -28.5 -117.5z" />
132 <glyph unicode="&#xe104;" d="M111 408q0 -33 5 -63q9 -56 44 -119.5t105 -108.5q31 -21 64 -16t62 23.5t57 49.5t48 61.5t35 60.5q32 66 39 184.5t-13 157.5q79 -80 122 -164t26 -184q-5 -33 -20.5 -69.5t-37.5 -80.5q-10 -19 -14.5 -29t-12 -26t-9 -23.5t-3 -19t2.5 -15.5t11 -9.5t19.5 -5t30.5 2.5 t42 8q57 20 91 34t87.5 44.5t87 64t65.5 88.5t47 122q38 172 -44.5 341.5t-246.5 278.5q22 -44 43 -129q39 -159 -32 -154q-15 2 -33 9q-79 33 -120.5 100t-44 175.5t48.5 257.5q-13 -8 -34 -23.5t-72.5 -66.5t-88.5 -105.5t-60 -138t-8 -166.5q2 -12 8 -41.5t8 -43t6 -39.5 t3.5 -39.5t-1 -33.5t-6 -31.5t-13.5 -24t-21 -20.5t-31 -12q-38 -10 -67 13t-40.5 61.5t-15 81.5t10.5 75q-52 -46 -83.5 -101t-39 -107t-7.5 -85z" />
133 <glyph unicode="&#xe105;" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5t145.5 -23.5t132.5 -59t116.5 -83.5t97 -90t74.5 -85.5t49 -63.5t20 -30l26 -40l-26 -40q-6 -10 -20 -30t-49 -63.5t-74.5 -85.5t-97 -90t-116.5 -83.5t-132.5 -59t-145.5 -23.5 t-145.5 23.5t-132.5 59t-116.5 83.5t-97 90t-74.5 85.5t-49 63.5t-20 30zM120 600q7 -10 40.5 -58t56 -78.5t68 -77.5t87.5 -75t103 -49.5t125 -21.5t123.5 20t100.5 45.5t85.5 71.5t66.5 75.5t58 81.5t47 66q-1 1 -28.5 37.5t-42 55t-43.5 53t-57.5 63.5t-58.5 54 q49 -74 49 -163q0 -124 -88 -212t-212 -88t-212 88t-88 212q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l105 105q-37 24 -75 72t-57 84l-20 36z" />
134 <glyph unicode="&#xe106;" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5q61 0 121 -17l37 142h148l-314 -1200h-148l37 143q-82 21 -165 71.5t-140 102t-109.5 112t-72 88.5t-29.5 43zM120 600q210 -282 393 -336l37 141q-107 18 -178.5 101.5t-71.5 193.5 q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l47 47l23 87q-30 28 -59 69t-44 68l-14 26zM780 161l38 145q22 15 44.5 34t46 44t40.5 44t41 50.5t33.5 43.5t33 44t24.5 34q-97 127 -140 175l39 146q67 -54 131.5 -125.5t87.5 -103.5t36 -52l26 -40l-26 -40 q-7 -12 -25.5 -38t-63.5 -79.5t-95.5 -102.5t-124 -100t-146.5 -79z" />
135 <glyph unicode="&#xe107;" d="M-97.5 34q13.5 -34 50.5 -34h1294q37 0 50.5 35.5t-7.5 67.5l-642 1056q-20 34 -48 36.5t-48 -29.5l-642 -1066q-21 -32 -7.5 -66zM155 200l445 723l445 -723h-345v100h-200v-100h-345zM500 600l100 -300l100 300v100h-200v-100z" />
136 <glyph unicode="&#xe108;" d="M100 262v41q0 20 11 44.5t26 38.5l363 325v339q0 62 44 106t106 44t106 -44t44 -106v-339l363 -325q15 -14 26 -38.5t11 -44.5v-41q0 -20 -12 -26.5t-29 5.5l-359 249v-263q100 -91 100 -113v-64q0 -20 -13 -28.5t-32 0.5l-94 78h-222l-94 -78q-19 -9 -32 -0.5t-13 28.5 v64q0 22 100 113v263l-359 -249q-17 -12 -29 -5.5t-12 26.5z" />
137 <glyph unicode="&#xe109;" d="M0 50q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v750h-1100v-750zM0 900h1100v150q0 21 -14.5 35.5t-35.5 14.5h-150v100h-100v-100h-500v100h-100v-100h-150q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 100v100h100v-100h-100zM100 300v100h100v-100h-100z M100 500v100h100v-100h-100zM300 100v100h100v-100h-100zM300 300v100h100v-100h-100zM300 500v100h100v-100h-100zM500 100v100h100v-100h-100zM500 300v100h100v-100h-100zM500 500v100h100v-100h-100zM700 100v100h100v-100h-100zM700 300v100h100v-100h-100zM700 500 v100h100v-100h-100zM900 100v100h100v-100h-100zM900 300v100h100v-100h-100zM900 500v100h100v-100h-100z" />
138 <glyph unicode="&#xe110;" d="M0 200v200h259l600 600h241v198l300 -295l-300 -300v197h-159l-600 -600h-341zM0 800h259l122 -122l141 142l-181 180h-341v-200zM678 381l141 142l122 -123h159v198l300 -295l-300 -300v197h-241z" />
139 <glyph unicode="&#xe111;" d="M0 400v600q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-596l-304 -300v300h-100q-41 0 -70.5 29.5t-29.5 70.5z" />
140 <glyph unicode="&#xe112;" d="M100 600v200h300v-250q0 -113 6 -145q17 -92 102 -117q39 -11 92 -11q37 0 66.5 5.5t50 15.5t36 24t24 31.5t14 37.5t7 42t2.5 45t0 47v25v250h300v-200q0 -42 -3 -83t-15 -104t-31.5 -116t-58 -109.5t-89 -96.5t-129 -65.5t-174.5 -25.5t-174.5 25.5t-129 65.5t-89 96.5 t-58 109.5t-31.5 116t-15 104t-3 83zM100 900v300h300v-300h-300zM800 900v300h300v-300h-300z" />
141 <glyph unicode="&#xe113;" d="M-30 411l227 -227l352 353l353 -353l226 227l-578 579z" />
142 <glyph unicode="&#xe114;" d="M70 797l580 -579l578 579l-226 227l-353 -353l-352 353z" />
143 <glyph unicode="&#xe115;" d="M-198 700l299 283l300 -283h-203v-400h385l215 -200h-800v600h-196zM402 1000l215 -200h381v-400h-198l299 -283l299 283h-200v600h-796z" />
144 <glyph unicode="&#xe116;" d="M18 939q-5 24 10 42q14 19 39 19h896l38 162q5 17 18.5 27.5t30.5 10.5h94q20 0 35 -14.5t15 -35.5t-15 -35.5t-35 -14.5h-54l-201 -961q-2 -4 -6 -10.5t-19 -17.5t-33 -11h-31v-50q0 -20 -14.5 -35t-35.5 -15t-35.5 15t-14.5 35v50h-300v-50q0 -20 -14.5 -35t-35.5 -15 t-35.5 15t-14.5 35v50h-50q-21 0 -35.5 15t-14.5 35q0 21 14.5 35.5t35.5 14.5h535l48 200h-633q-32 0 -54.5 21t-27.5 43z" />
145 <glyph unicode="&#xe117;" d="M0 0v800h1200v-800h-1200zM0 900v100h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-100h-1200z" />
146 <glyph unicode="&#xe118;" d="M1 0l300 700h1200l-300 -700h-1200zM1 400v600h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-200h-1000z" />
147 <glyph unicode="&#xe119;" d="M302 300h198v600h-198l298 300l298 -300h-198v-600h198l-298 -300z" />
148 <glyph unicode="&#xe120;" d="M0 600l300 298v-198h600v198l300 -298l-300 -297v197h-600v-197z" />
149 <glyph unicode="&#xe121;" d="M0 100v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM31 400l172 739q5 22 23 41.5t38 19.5h672q19 0 37.5 -22.5t23.5 -45.5l172 -732h-1138zM800 100h100v100h-100v-100z M1000 100h100v100h-100v-100z" />
150 <glyph unicode="&#xe122;" d="M-101 600v50q0 24 25 49t50 38l25 13v-250l-11 5.5t-24 14t-30 21.5t-24 27.5t-11 31.5zM100 500v250v8v8v7t0.5 7t1.5 5.5t2 5t3 4t4.5 3.5t6 1.5t7.5 0.5h200l675 250v-850l-675 200h-38l47 -276q2 -12 -3 -17.5t-11 -6t-21 -0.5h-8h-83q-20 0 -34.5 14t-18.5 35 q-55 337 -55 351zM1100 200v850q0 21 14.5 35.5t35.5 14.5q20 0 35 -14.5t15 -35.5v-850q0 -20 -15 -35t-35 -15q-21 0 -35.5 15t-14.5 35z" />
151 <glyph unicode="&#xe123;" d="M74 350q0 21 13.5 35.5t33.5 14.5h18l117 173l63 327q15 77 76 140t144 83l-18 32q-6 19 3 32t29 13h94q20 0 29 -10.5t3 -29.5q-18 -36 -18 -37q83 -19 144 -82.5t76 -140.5l63 -327l118 -173h17q20 0 33.5 -14.5t13.5 -35.5q0 -20 -13 -40t-31 -27q-8 -3 -23 -8.5 t-65 -20t-103 -25t-132.5 -19.5t-158.5 -9q-125 0 -245.5 20.5t-178.5 40.5l-58 20q-18 7 -31 27.5t-13 40.5zM497 110q12 -49 40 -79.5t63 -30.5t63 30.5t39 79.5q-48 -6 -102 -6t-103 6z" />
152 <glyph unicode="&#xe124;" d="M21 445l233 -45l-78 -224l224 78l45 -233l155 179l155 -179l45 233l224 -78l-78 224l234 45l-180 155l180 156l-234 44l78 225l-224 -78l-45 233l-155 -180l-155 180l-45 -233l-224 78l78 -225l-233 -44l179 -156z" />
153 <glyph unicode="&#xe125;" d="M0 200h200v600h-200v-600zM300 275q0 -75 100 -75h61q124 -100 139 -100h250q46 0 83 57l238 344q29 31 29 74v100q0 44 -30.5 84.5t-69.5 40.5h-328q28 118 28 125v150q0 44 -30.5 84.5t-69.5 40.5h-50q-27 0 -51 -20t-38 -48l-96 -198l-145 -196q-20 -26 -20 -63v-400z M400 300v375l150 213l100 212h50v-175l-50 -225h450v-125l-250 -375h-214l-136 100h-100z" />
154 <glyph unicode="&#xe126;" d="M0 400v600h200v-600h-200zM300 525v400q0 75 100 75h61q124 100 139 100h250q46 0 83 -57l238 -344q29 -31 29 -74v-100q0 -44 -30.5 -84.5t-69.5 -40.5h-328q28 -118 28 -125v-150q0 -44 -30.5 -84.5t-69.5 -40.5h-50q-27 0 -51 20t-38 48l-96 198l-145 196 q-20 26 -20 63zM400 525l150 -212l100 -213h50v175l-50 225h450v125l-250 375h-214l-136 -100h-100v-375z" />
155 <glyph unicode="&#xe127;" d="M8 200v600h200v-600h-200zM308 275v525q0 17 14 35.5t28 28.5l14 9l362 230q14 6 25 6q17 0 29 -12l109 -112q14 -14 14 -34q0 -18 -11 -32l-85 -121h302q85 0 138.5 -38t53.5 -110t-54.5 -111t-138.5 -39h-107l-130 -339q-7 -22 -20.5 -41.5t-28.5 -19.5h-341 q-7 0 -90 81t-83 94zM408 289l100 -89h293l131 339q6 21 19.5 41t28.5 20h203q16 0 25 15t9 36q0 20 -9 34.5t-25 14.5h-457h-6.5h-7.5t-6.5 0.5t-6 1t-5 1.5t-5.5 2.5t-4 4t-4 5.5q-5 12 -5 20q0 14 10 27l147 183l-86 83l-339 -236v-503z" />
156 <glyph unicode="&#xe128;" d="M-101 651q0 72 54 110t139 38l302 -1l-85 121q-11 16 -11 32q0 21 14 34l109 113q13 12 29 12q11 0 25 -6l365 -230q7 -4 17 -10.5t26.5 -26t16.5 -36.5v-526q0 -13 -86 -93.5t-94 -80.5h-341q-16 0 -29.5 20t-19.5 41l-130 339h-107q-84 0 -139 39t-55 111zM-1 601h222 q15 0 28.5 -20.5t19.5 -40.5l131 -339h293l107 89v502l-343 237l-87 -83l145 -184q10 -11 10 -26q0 -11 -5 -20q-1 -3 -3.5 -5.5l-4 -4t-5 -2.5t-5.5 -1.5t-6.5 -1t-6.5 -0.5h-7.5h-6.5h-476v-100zM1000 201v600h200v-600h-200z" />
157 <glyph unicode="&#xe129;" d="M97 719l230 -363q4 -6 10.5 -15.5t26 -25t36.5 -15.5h525q13 0 94 83t81 90v342q0 15 -20 28.5t-41 19.5l-339 131v106q0 84 -39 139t-111 55t-110 -53.5t-38 -138.5v-302l-121 84q-15 12 -33.5 11.5t-32.5 -13.5l-112 -110q-22 -22 -6 -53zM172 739l83 86l183 -146 q22 -18 47 -5q3 1 5.5 3.5l4 4t2.5 5t1.5 5.5t1 6.5t0.5 6.5v7.5v6.5v456q0 22 25 31t50 -0.5t25 -30.5v-202q0 -16 20 -29.5t41 -19.5l339 -130v-294l-89 -100h-503zM400 0v200h600v-200h-600z" />
158 <glyph unicode="&#xe130;" d="M2 585q-16 -31 6 -53l112 -110q13 -13 32 -13.5t34 10.5l121 85q0 -51 -0.5 -153.5t-0.5 -148.5q0 -84 38.5 -138t110.5 -54t111 55t39 139v106l339 131q20 6 40.5 19.5t20.5 28.5v342q0 7 -81 90t-94 83h-525q-17 0 -35.5 -14t-28.5 -28l-10 -15zM77 565l236 339h503 l89 -100v-294l-340 -130q-20 -6 -40 -20t-20 -29v-202q0 -22 -25 -31t-50 0t-25 31v456v14.5t-1.5 11.5t-5 12t-9.5 7q-24 13 -46 -5l-184 -146zM305 1104v200h600v-200h-600z" />
159 <glyph unicode="&#xe131;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM298 701l2 -201h300l-2 -194l402 294l-402 298v-197h-300z" />
160 <glyph unicode="&#xe132;" d="M0 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t231.5 47.5q122 0 232.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-218 -217.5t-300 -80t-299.5 80t-217.5 217.5t-80 299.5zM200 600l402 -294l-2 194h300l2 201h-300v197z" />
161 <glyph unicode="&#xe133;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600h200v-300h200v300h200l-300 400z" />
162 <glyph unicode="&#xe134;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600l300 -400l300 400h-200v300h-200v-300h-200z" />
163 <glyph unicode="&#xe135;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM254 780q-8 -33 5.5 -92.5t7.5 -87.5q0 -9 17 -44t16 -60 q12 0 23 -5.5t23 -15t20 -13.5q24 -12 108 -42q22 -8 53 -31.5t59.5 -38.5t57.5 -11q8 -18 -15 -55t-20 -57q42 -71 87 -80q0 -6 -3 -15.5t-3.5 -14.5t4.5 -17q104 -3 221 112q30 29 47 47t34.5 49t20.5 62q-14 9 -37 9.5t-36 7.5q-14 7 -49 15t-52 19q-9 0 -39.5 -0.5 t-46.5 -1.5t-39 -6.5t-39 -16.5q-50 -35 -66 -12q-4 2 -3.5 25.5t0.5 25.5q-6 13 -26.5 17t-24.5 7q2 22 -2 41t-16.5 28t-38.5 -20q-23 -25 -42 4q-19 28 -8 58q6 16 22 22q6 -1 26 -1.5t33.5 -4t19.5 -13.5q12 -19 32 -37.5t34 -27.5l14 -8q0 3 9.5 39.5t5.5 57.5 q-4 23 14.5 44.5t22.5 31.5q5 14 10 35t8.5 31t15.5 22.5t34 21.5q-6 18 10 37q8 0 23.5 -1.5t24.5 -1.5t20.5 4.5t20.5 15.5q-10 23 -30.5 42.5t-38 30t-49 26.5t-43.5 23q11 39 2 44q31 -13 58 -14.5t39 3.5l11 4q7 36 -16.5 53.5t-64.5 28.5t-56 23q-19 -3 -37 0 q-15 -12 -36.5 -21t-34.5 -12t-44 -8t-39 -6q-15 -3 -45.5 0.5t-45.5 -2.5q-21 -7 -52 -26.5t-34 -34.5q-3 -11 6.5 -22.5t8.5 -18.5q-3 -34 -27.5 -90.5t-29.5 -79.5zM518 916q3 12 16 30t16 25q10 -10 18.5 -10t14 6t14.5 14.5t16 12.5q0 -24 17 -66.5t17 -43.5 q-9 2 -31 5t-36 5t-32 8t-30 14zM692 1003h1h-1z" />
164 <glyph unicode="&#xe136;" d="M0 164.5q0 21.5 15 37.5l600 599q-33 101 6 201.5t135 154.5q164 92 306 -9l-259 -138l145 -232l251 126q13 -175 -151 -267q-123 -70 -253 -23l-596 -596q-15 -16 -36.5 -16t-36.5 16l-111 110q-15 15 -15 36.5z" />
165 <glyph unicode="&#xe137;" horiz-adv-x="1220" d="M0 196v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 596v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5zM0 996v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM600 596h500v100h-500v-100zM800 196h300v100h-300v-100zM900 996h200v100h-200v-100z" />
166 <glyph unicode="&#xe138;" d="M100 1100v100h1000v-100h-1000zM150 1000h900l-350 -500v-300l-200 -200v500z" />
167 <glyph unicode="&#xe139;" d="M0 200v200h1200v-200q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 500v400q0 41 29.5 70.5t70.5 29.5h300v100q0 41 29.5 70.5t70.5 29.5h200q41 0 70.5 -29.5t29.5 -70.5v-100h300q41 0 70.5 -29.5t29.5 -70.5v-400h-500v100h-200v-100h-500z M500 1000h200v100h-200v-100z" />
168 <glyph unicode="&#xe140;" d="M0 0v400l129 -129l200 200l142 -142l-200 -200l129 -129h-400zM0 800l129 129l200 -200l142 142l-200 200l129 129h-400v-400zM729 329l142 142l200 -200l129 129v-400h-400l129 129zM729 871l200 200l-129 129h400v-400l-129 129l-200 -200z" />
169 <glyph unicode="&#xe141;" d="M0 596q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 596q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM291 655 q0 23 15.5 38.5t38.5 15.5t39 -16t16 -38q0 -23 -16 -39t-39 -16q-22 0 -38 16t-16 39zM400 850q0 22 16 38.5t39 16.5q22 0 38 -16t16 -39t-16 -39t-38 -16q-23 0 -39 16.5t-16 38.5zM514 609q0 32 20.5 56.5t51.5 29.5l122 126l1 1q-9 14 -9 28q0 22 16 38.5t39 16.5 q22 0 38 -16t16 -39t-16 -39t-38 -16q-14 0 -29 10l-55 -145q17 -22 17 -51q0 -36 -25.5 -61.5t-61.5 -25.5t-61.5 25.5t-25.5 61.5zM800 655q0 22 16 38t39 16t38.5 -15.5t15.5 -38.5t-16 -39t-38 -16q-23 0 -39 16t-16 39z" />
170 <glyph unicode="&#xe142;" d="M-40 375q-13 -95 35 -173q35 -57 94 -89t129 -32q63 0 119 28q33 16 65 40.5t52.5 45.5t59.5 64q40 44 57 61l394 394q35 35 47 84t-3 96q-27 87 -117 104q-20 2 -29 2q-46 0 -78.5 -16.5t-67.5 -51.5l-389 -396l-7 -7l69 -67l377 373q20 22 39 38q23 23 50 23 q38 0 53 -36q16 -39 -20 -75l-547 -547q-52 -52 -125 -52q-55 0 -100 33t-54 96q-5 35 2.5 66t31.5 63t42 50t56 54q24 21 44 41l348 348q52 52 82.5 79.5t84 54t107.5 26.5q25 0 48 -4q95 -17 154 -94.5t51 -175.5q-7 -101 -98 -192l-252 -249l-253 -256l7 -7l69 -60 l517 511q67 67 95 157t11 183q-16 87 -67 154t-130 103q-69 33 -152 33q-107 0 -197 -55q-40 -24 -111 -95l-512 -512q-68 -68 -81 -163z" />
171 <glyph unicode="&#xe143;" d="M80 784q0 131 98.5 229.5t230.5 98.5q143 0 241 -129q103 129 246 129q129 0 226 -98.5t97 -229.5q0 -46 -17.5 -91t-61 -99t-77 -89.5t-104.5 -105.5q-197 -191 -293 -322l-17 -23l-16 23q-43 58 -100 122.5t-92 99.5t-101 100q-71 70 -104.5 105.5t-77 89.5t-61 99 t-17.5 91zM250 784q0 -27 30.5 -70t61.5 -75.5t95 -94.5l22 -22q93 -90 190 -201q82 92 195 203l12 12q64 62 97.5 97t64.5 79t31 72q0 71 -48 119.5t-105 48.5q-74 0 -132 -83l-118 -171l-114 174q-51 80 -123 80q-60 0 -109.5 -49.5t-49.5 -118.5z" />
172 <glyph unicode="&#xe144;" d="M57 353q0 -95 66 -159l141 -142q68 -66 159 -66q93 0 159 66l283 283q66 66 66 159t-66 159l-141 141q-8 9 -19 17l-105 -105l212 -212l-389 -389l-247 248l95 95l-18 18q-46 45 -75 101l-55 -55q-66 -66 -66 -159zM269 706q0 -93 66 -159l141 -141q7 -7 19 -17l105 105 l-212 212l389 389l247 -247l-95 -96l18 -17q47 -49 77 -100l29 29q35 35 62.5 88t27.5 96q0 93 -66 159l-141 141q-66 66 -159 66q-95 0 -159 -66l-283 -283q-66 -64 -66 -159z" />
173 <glyph unicode="&#xe145;" d="M200 100v953q0 21 30 46t81 48t129 38t163 15t162 -15t127 -38t79 -48t29 -46v-953q0 -41 -29.5 -70.5t-70.5 -29.5h-600q-41 0 -70.5 29.5t-29.5 70.5zM300 300h600v700h-600v-700zM496 150q0 -43 30.5 -73.5t73.5 -30.5t73.5 30.5t30.5 73.5t-30.5 73.5t-73.5 30.5 t-73.5 -30.5t-30.5 -73.5z" />
174 <glyph unicode="&#xe146;" d="M0 0l303 380l207 208l-210 212h300l267 279l-35 36q-15 14 -15 35t15 35q14 15 35 15t35 -15l283 -282q15 -15 15 -36t-15 -35q-14 -15 -35 -15t-35 15l-36 35l-279 -267v-300l-212 210l-208 -207z" />
175 <glyph unicode="&#xe148;" d="M295 433h139q5 -77 48.5 -126.5t117.5 -64.5v335q-6 1 -15.5 4t-11.5 3q-46 14 -79 26.5t-72 36t-62.5 52t-40 72.5t-16.5 99q0 92 44 159.5t109 101t144 40.5v78h100v-79q38 -4 72.5 -13.5t75.5 -31.5t71 -53.5t51.5 -84t24.5 -118.5h-159q-8 72 -35 109.5t-101 50.5 v-307l64 -14q34 -7 64 -16.5t70 -31.5t67.5 -52t47.5 -80.5t20 -112.5q0 -139 -89 -224t-244 -96v-77h-100v78q-152 17 -237 104q-40 40 -52.5 93.5t-15.5 139.5zM466 889q0 -29 8 -51t16.5 -34t29.5 -22.5t31 -13.5t38 -10q7 -2 11 -3v274q-61 -8 -97.5 -37.5t-36.5 -102.5 zM700 237q170 18 170 151q0 64 -44 99.5t-126 60.5v-311z" />
176 <glyph unicode="&#xe149;" d="M100 600v100h166q-24 49 -44 104q-10 26 -14.5 55.5t-3 72.5t25 90t68.5 87q97 88 263 88q129 0 230 -89t101 -208h-153q0 52 -34 89.5t-74 51.5t-76 14q-37 0 -79 -14.5t-62 -35.5q-41 -44 -41 -101q0 -28 16.5 -69.5t28 -62.5t41.5 -72h241v-100h-197q8 -50 -2.5 -115 t-31.5 -94q-41 -59 -99 -113q35 11 84 18t70 7q33 1 103 -16t103 -17q76 0 136 30l50 -147q-41 -25 -80.5 -36.5t-59 -13t-61.5 -1.5q-23 0 -128 33t-155 29q-39 -4 -82 -17t-66 -25l-24 -11l-55 145l16.5 11t15.5 10t13.5 9.5t14.5 12t14.5 14t17.5 18.5q48 55 54 126.5 t-30 142.5h-221z" />
177 <glyph unicode="&#xe150;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM602 900l298 300l298 -300h-198v-900h-200v900h-198z" />
178 <glyph unicode="&#xe151;" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v200h100v-100h200v-100h-300zM700 400v100h300v-200h-99v-100h-100v100h99v100h-200zM700 700v500h300v-500h-100v100h-100v-100h-100zM801 900h100v200h-100v-200z" />
179 <glyph unicode="&#xe152;" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v500h300v-500h-100v100h-100v-100h-100zM700 700v200h100v-100h200v-100h-300zM700 1100v100h300v-200h-99v-100h-100v100h99v100h-200zM801 200h100v200h-100v-200z" />
180 <glyph unicode="&#xe153;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 100v400h300v-500h-100v100h-200zM800 1100v100h200v-500h-100v400h-100zM901 200h100v200h-100v-200z" />
181 <glyph unicode="&#xe154;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 400v100h200v-500h-100v400h-100zM800 800v400h300v-500h-100v100h-200zM901 900h100v200h-100v-200z" />
182 <glyph unicode="&#xe155;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h500v-200h-500zM700 400v200h400v-200h-400zM700 700v200h300v-200h-300zM700 1000v200h200v-200h-200z" />
183 <glyph unicode="&#xe156;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h200v-200h-200zM700 400v200h300v-200h-300zM700 700v200h400v-200h-400zM700 1000v200h500v-200h-500z" />
184 <glyph unicode="&#xe157;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q162 0 281 -118.5t119 -281.5v-300q0 -165 -118.5 -282.5t-281.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500z" />
185 <glyph unicode="&#xe158;" d="M0 400v300q0 163 119 281.5t281 118.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-163 0 -281.5 117.5t-118.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM400 300l333 250l-333 250v-500z" />
186 <glyph unicode="&#xe159;" d="M0 400v300q0 163 117.5 281.5t282.5 118.5h300q163 0 281.5 -119t118.5 -281v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 700l250 -333l250 333h-500z" />
187 <glyph unicode="&#xe160;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -162 -118.5 -281t-281.5 -119h-300q-165 0 -282.5 118.5t-117.5 281.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 400h500l-250 333z" />
188 <glyph unicode="&#xe161;" d="M0 400v300h300v200l400 -350l-400 -350v200h-300zM500 0v200h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-500v200h400q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-400z" />
189 <glyph unicode="&#xe162;" d="M217 519q8 -19 31 -19h302q-155 -438 -160 -458q-5 -21 4 -32l9 -8h9q14 0 26 15q11 13 274.5 321.5t264.5 308.5q14 19 5 36q-8 17 -31 17l-301 -1q1 4 78 219.5t79 227.5q2 15 -5 27l-9 9h-9q-15 0 -25 -16q-4 -6 -98 -111.5t-228.5 -257t-209.5 -237.5q-16 -19 -6 -41 z" />
190 <glyph unicode="&#xe163;" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q47 0 100 15v185h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h500v185q-14 4 -114 7.5t-193 5.5l-93 2q-165 0 -282.5 -117.5t-117.5 -282.5v-300zM600 400v300h300v200l400 -350l-400 -350v200h-300z " />
191 <glyph unicode="&#xe164;" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q163 0 281.5 117.5t118.5 282.5v98l-78 73l-122 -123v-148q0 -41 -29.5 -70.5t-70.5 -29.5h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h156l118 122l-74 78h-100q-165 0 -282.5 -117.5t-117.5 -282.5 v-300zM496 709l353 342l-149 149h500v-500l-149 149l-342 -353z" />
192 <glyph unicode="&#xe165;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM406 600 q0 80 57 137t137 57t137 -57t57 -137t-57 -137t-137 -57t-137 57t-57 137z" />
193 <glyph unicode="&#xe166;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 800l445 -500l450 500h-295v400h-300v-400h-300zM900 150h100v50h-100v-50z" />
194 <glyph unicode="&#xe167;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 700h300v-300h300v300h295l-445 500zM900 150h100v50h-100v-50z" />
195 <glyph unicode="&#xe168;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 705l305 -305l596 596l-154 155l-442 -442l-150 151zM900 150h100v50h-100v-50z" />
196 <glyph unicode="&#xe169;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 988l97 -98l212 213l-97 97zM200 400l697 1l3 699l-250 -239l-149 149l-212 -212l149 -149zM900 150h100v50h-100v-50z" />
197 <glyph unicode="&#xe170;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM200 612l212 -212l98 97l-213 212zM300 1200l239 -250l-149 -149l212 -212l149 148l249 -237l-1 697zM900 150h100v50h-100v-50z" />
198 <glyph unicode="&#xe171;" d="M23 415l1177 784v-1079l-475 272l-310 -393v416h-392zM494 210l672 938l-672 -712v-226z" />
199 <glyph unicode="&#xe172;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-850q0 -21 -15 -35.5t-35 -14.5h-150v400h-700v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200z" />
200 <glyph unicode="&#xe173;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-218l-276 -275l-120 120l-126 -127h-378v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM581 306l123 123l120 -120l353 352l123 -123l-475 -476zM600 1000h100v200h-100v-200z" />
201 <glyph unicode="&#xe174;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-269l-103 -103l-170 170l-298 -298h-329v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200zM700 133l170 170l-170 170l127 127l170 -170l170 170l127 -128l-170 -169l170 -170 l-127 -127l-170 170l-170 -170z" />
202 <glyph unicode="&#xe175;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-300h-400v-200h-500v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300l300 -300l300 300h-200v300h-200v-300h-200zM600 1000v200h100v-200h-100z" />
203 <glyph unicode="&#xe176;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-402l-200 200l-298 -298h-402v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300h200v-300h200v300h200l-300 300zM600 1000v200h100v-200h-100z" />
204 <glyph unicode="&#xe177;" d="M0 250q0 -21 14.5 -35.5t35.5 -14.5h1100q21 0 35.5 14.5t14.5 35.5v550h-1200v-550zM0 900h1200v150q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 300v200h400v-200h-400z" />
205 <glyph unicode="&#xe178;" d="M0 400l300 298v-198h400v-200h-400v-198zM100 800v200h100v-200h-100zM300 800v200h100v-200h-100zM500 800v200h400v198l300 -298l-300 -298v198h-400zM800 300v200h100v-200h-100zM1000 300h100v200h-100v-200z" />
206 <glyph unicode="&#xe179;" d="M100 700v400l50 100l50 -100v-300h100v300l50 100l50 -100v-300h100v300l50 100l50 -100v-400l-100 -203v-447q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v447zM800 597q0 -29 10.5 -55.5t25 -43t29 -28.5t25.5 -18l10 -5v-397q0 -21 14.5 -35.5 t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v1106q0 31 -18 40.5t-44 -7.5l-276 -116q-25 -17 -43.5 -51.5t-18.5 -65.5v-359z" />
207 <glyph unicode="&#xe180;" d="M100 0h400v56q-75 0 -87.5 6t-12.5 44v394h500v-394q0 -38 -12.5 -44t-87.5 -6v-56h400v56q-4 0 -11 0.5t-24 3t-30 7t-24 15t-11 24.5v888q0 22 25 34.5t50 13.5l25 2v56h-400v-56q75 0 87.5 -6t12.5 -44v-394h-500v394q0 38 12.5 44t87.5 6v56h-400v-56q4 0 11 -0.5 t24 -3t30 -7t24 -15t11 -24.5v-888q0 -22 -25 -34.5t-50 -13.5l-25 -2v-56z" />
208 <glyph unicode="&#xe181;" d="M0 300q0 -41 29.5 -70.5t70.5 -29.5h300q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-300q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM100 100h400l200 200h105l295 98v-298h-425l-100 -100h-375zM100 300v200h300v-200h-300zM100 600v200h300v-200h-300z M100 1000h400l200 -200v-98l295 98h105v200h-425l-100 100h-375zM700 402v163l400 133v-163z" />
209 <glyph unicode="&#xe182;" d="M16.5 974.5q0.5 -21.5 16 -90t46.5 -140t104 -177.5t175 -208q103 -103 207.5 -176t180 -103.5t137 -47t92.5 -16.5l31 1l163 162q17 18 13.5 41t-22.5 37l-192 136q-19 14 -45 12t-42 -19l-118 -118q-142 101 -268 227t-227 268l118 118q17 17 20 41.5t-11 44.5 l-139 194q-14 19 -36.5 22t-40.5 -14l-162 -162q-1 -11 -0.5 -32.5z" />
210 <glyph unicode="&#xe183;" d="M0 50v212q0 20 10.5 45.5t24.5 39.5l365 303v50q0 4 1 10.5t12 22.5t30 28.5t60 23t97 10.5t97 -10t60 -23.5t30 -27.5t12 -24l1 -10v-50l365 -303q14 -14 24.5 -39.5t10.5 -45.5v-212q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-20 0 -35 14.5t-15 35.5zM0 712 q0 -21 14.5 -33.5t34.5 -8.5l202 33q20 4 34.5 21t14.5 38v146q141 24 300 24t300 -24v-146q0 -21 14.5 -38t34.5 -21l202 -33q20 -4 34.5 8.5t14.5 33.5v200q-6 8 -19 20.5t-63 45t-112 57t-171 45t-235 20.5q-92 0 -175 -10.5t-141.5 -27t-108.5 -36.5t-81.5 -40 t-53.5 -36.5t-31 -27.5l-9 -10v-200z" />
211 <glyph unicode="&#xe184;" d="M100 0v100h1100v-100h-1100zM175 200h950l-125 150v250l100 100v400h-100v-200h-100v200h-200v-200h-100v200h-200v-200h-100v200h-100v-400l100 -100v-250z" />
212 <glyph unicode="&#xe185;" d="M100 0h300v400q0 41 -29.5 70.5t-70.5 29.5h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-400zM500 0v1000q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-1000h-300zM900 0v700q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-700h-300z" />
213 <glyph unicode="&#xe186;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" />
214 <glyph unicode="&#xe187;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h100v200h100v-200h100v500h-100v-200h-100v200h-100v-500zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" />
215 <glyph unicode="&#xe188;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v100h-200v300h200v100h-300v-500zM600 300h300v100h-200v300h200v100h-300v-500z" />
216 <glyph unicode="&#xe189;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 550l300 -150v300zM600 400l300 150l-300 150v-300z" />
217 <glyph unicode="&#xe190;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300v500h700v-500h-700zM300 400h130q41 0 68 42t27 107t-28.5 108t-66.5 43h-130v-300zM575 549 q0 -65 27 -107t68 -42h130v300h-130q-38 0 -66.5 -43t-28.5 -108z" />
218 <glyph unicode="&#xe191;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" />
219 <glyph unicode="&#xe192;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v400h-200v100h-100v-500zM301 400v200h100v-200h-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" />
220 <glyph unicode="&#xe193;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 700v100h300v-300h-99v-100h-100v100h99v200h-200zM201 300v100h100v-100h-100zM601 300v100h100v-100h-100z M700 700v100h200v-500h-100v400h-100z" />
221 <glyph unicode="&#xe194;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 500v200 l100 100h300v-100h-300v-200h300v-100h-300z" />
222 <glyph unicode="&#xe195;" d="M0 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 400v400h300 l100 -100v-100h-100v100h-200v-100h200v-100h-200v-100h-100zM700 400v100h100v-100h-100z" />
223 <glyph unicode="&#xe197;" d="M-14 494q0 -80 56.5 -137t135.5 -57h222v300h400v-300h128q120 0 205 86.5t85 207.5t-85 207t-205 86q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200h200v300h200v-300h200 l-300 -300z" />
224 <glyph unicode="&#xe198;" d="M-14 494q0 -80 56.5 -137t135.5 -57h8l414 414l403 -403q94 26 154.5 104.5t60.5 178.5q0 120 -85 206.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200l300 300 l300 -300h-200v-300h-200v300h-200z" />
225 <glyph unicode="&#xe199;" d="M100 200h400v-155l-75 -45h350l-75 45v155h400l-270 300h170l-270 300h170l-300 333l-300 -333h170l-270 -300h170z" />
226 <glyph unicode="&#xe200;" d="M121 700q0 -53 28.5 -97t75.5 -65q-4 -16 -4 -38q0 -74 52.5 -126.5t126.5 -52.5q56 0 100 30v-306l-75 -45h350l-75 45v306q46 -30 100 -30q74 0 126.5 52.5t52.5 126.5q0 24 -9 55q50 32 79.5 83t29.5 112q0 90 -61.5 155.5t-150.5 71.5q-26 89 -99.5 145.5 t-167.5 56.5q-116 0 -197.5 -81.5t-81.5 -197.5q0 -4 1 -11.5t1 -11.5q-14 2 -23 2q-74 0 -126.5 -52.5t-52.5 -126.5z" />
227 </font>
228 </defs></svg>
source/misc/embedded_libs/fmt-8.1.1/doc/_static/fonts/glyphicons-halflings-regular.ttf less more
Binary diff not shown
source/misc/embedded_libs/fmt-8.1.1/doc/_static/fonts/glyphicons-halflings-regular.woff less more
Binary diff not shown
+0
-148
source/misc/embedded_libs/fmt-8.1.1/doc/_templates/layout.html less more
0 {% extends "!layout.html" %}
1
2 {% block extrahead %}
3 <meta name="description" content="Small, safe and fast formatting library">
4 <meta name="keywords" content="C++, formatting, printf, string, library">
5 <meta name="author" content="Victor Zverovich">
6 <link rel="stylesheet" href="_static/fmt.css">
7 {# Google Analytics #}
8 <script async src="https://www.googletagmanager.com/gtag/js?id=UA-20116650-4"></script>
9 <script>
10 window.dataLayer = window.dataLayer || [];
11 function gtag(){dataLayer.push(arguments);}
12 gtag('js', new Date());
13
14 gtag('config', 'UA-20116650-4');
15 </script>
16 {% endblock %}
17
18 {%- macro searchform(classes, button) %}
19 <form class="{{classes}}" role="search" action="{{ pathto('search') }}"
20 method="get">
21 <div class="form-group">
22 <input type="text" name="q" class="form-control"
23 {{ 'placeholder="Search"' if not button }} >
24 </div>
25 <input type="hidden" name="check_keywords" value="yes" />
26 <input type="hidden" name="area" value="default" />
27 {% if button %}
28 <input type="submit" class="btn btn-default" value="search">
29 {% endif %}
30 </form>
31 {%- endmacro %}
32
33 {% block header %}
34 <nav class="navbar navbar-inverse">
35 <div class="tb-container">
36 <div class="row">
37 <div class="navbar-content">
38 {# Brand and toggle get grouped for better mobile display #}
39 <div class="navbar-header">
40 <button type="button" class="navbar-toggle collapsed"
41 data-toggle="collapse" data-target=".navbar-collapse">
42 <span class="sr-only">Toggle navigation</span>
43 <span class="icon-bar"></span>
44 <span class="icon-bar"></span>
45 <span class="icon-bar"></span>
46 </button>
47 <a class="navbar-brand" href="index.html">{fmt}</a>
48 </div>
49
50 {# Collect the nav links, forms, and other content for toggling #}
51 <div class="collapse navbar-collapse">
52 <ul class="nav navbar-nav">
53 <li class="dropdown">
54 <a href="#" class="dropdown-toggle" data-toggle="dropdown"
55 role="button" aria-expanded="false">{{ version }}
56 <span class="caret"></span></a>
57 <ul class="dropdown-menu" role="menu">
58 {% for v in versions.split(',') %}
59 <li><a href="https://fmt.dev/{{v}}">{{v}}</a></li>
60 {% endfor %}
61 </ul>
62 </li>
63 {% for name in ['Contents', 'Usage', 'API', 'Syntax'] %}
64 {% if pagename == name.lower() %}
65 <li class="active"><a href="{{name.lower()}}.html">{{name}}
66 <span class="sr-only">(current)</span></a></li>
67 {%else%}
68 <li><a href="{{name.lower()}}.html">{{name}}</a></li>
69 {%endif%}
70 {% endfor %}
71 </ul>
72 {% if pagename != 'search' %}
73 {{ searchform('navbar-form navbar-right', False) }}
74 {%endif%}
75 </div> {# /.navbar-collapse #}
76 </div> {# /.col-md-offset-2 #}
77 </div> {# /.row #}
78 </div> {# /.tb-container #}
79 </nav>
80 {% if pagename == "index" %}
81 {% set download_url = 'https://github.com/fmtlib/fmt/releases/download' %}
82 <div class="jumbotron">
83 <div class="tb-container">
84 <h1>{fmt}</h1>
85 <p class="lead">A modern formatting library</p>
86 <div class="btn-group" role="group">
87 {% set name = 'fmt' if version.split('.')[0]|int >= 3 else 'cppformat' %}
88 <a class="btn btn-success"
89 href="{{download_url}}/{{version}}/{{name}}-{{version}}.zip">
90 <span class="glyphicon glyphicon-download"></span> Download
91 </a>
92 <button type="button" class="btn btn-success dropdown-toggle"
93 data-toggle="dropdown"><span class="caret"></span></button>
94 <ul class="dropdown-menu">
95 {% for v in versions.split(',') %}
96 {% set name = 'fmt' if v.split('.')[0]|int >= 3 else 'cppformat' %}
97 <li><a href="{{download_url}}/{{v}}/{{name}}-{{v}}.zip">Version {{v}}
98 </a></li>
99 {% endfor %}
100 </ul>
101 </div>
102 </div>
103 </div>
104 {% endif %}
105 {% endblock %}
106
107 {# Disable relbars. #}
108 {% block relbar1 %}
109 {% endblock %}
110 {% block relbar2 %}
111 {% endblock %}
112
113 {% block content %}
114 <div class="tb-container">
115 <div class="row">
116 {# Sidebar is currently disabled.
117 <div class="bs-sidebar">
118 <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
119 <div class="sphinxsidebarwrapper">
120 {%- block sidebarlogo %}
121 {%- if logo %}
122 <p class="logo"><a href="{{ pathto(master_doc) }}">
123 <img class="logo" src="{{ pathto('_static/' + logo, 1) }}"
124 alt="Logo"/>
125 </a></p>
126 {%- endif %}
127 {%- endblock %}
128 {%- for sidebartemplate in sidebars %}
129 {%- include sidebartemplate %}
130 {%- endfor %}
131 </div>
132 </div>
133 </div>
134 #}
135
136 <div class="content">
137 {% block body %} {% endblock %}
138 </div>
139 </div>
140 </div>
141 {% endblock %}
142
143 {% block footer %}
144 {{ super() }}
145 {# Placed at the end of the document so the pages load faster. #}
146 <script src="_static/bootstrap.min.js"></script>
147 {% endblock %}
+0
-55
source/misc/embedded_libs/fmt-8.1.1/doc/_templates/search.html less more
0 {#
1 basic/search.html
2 ~~~~~~~~~~~~~~~~~
3
4 Template for the search page.
5
6 :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
7 :license: BSD, see LICENSE for details.
8 #}
9 {%- extends "layout.html" %}
10 {% set title = _('Search') %}
11 {% set script_files = script_files + ['_static/searchtools.js'] %}
12 {% block extrahead %}
13 <script type="text/javascript">
14 jQuery(function() { Search.loadIndex("{{ pathto('searchindex.js', 1) }}"); });
15 </script>
16 {# this is used when loading the search index using $.ajax fails,
17 such as on Chrome for documents on localhost #}
18 <script type="text/javascript" id="searchindexloader"></script>
19 {{ super() }}
20 {% endblock %}
21 {% block body %}
22 <h1 id="search-documentation">{{ _('Search') }}</h1>
23 <div id="fallback" class="admonition warning">
24 <script type="text/javascript">$('#fallback').hide();</script>
25 <p>
26 {% trans %}Please activate JavaScript to enable the search
27 functionality.{% endtrans %}
28 </p>
29 </div>
30 <p>
31 {% trans %}From here you can search these documents. Enter your search
32 words into the box below and click "search". Note that the search
33 function will automatically search for all of the words. Pages
34 containing fewer words won't appear in the result list.{% endtrans %}
35 </p>
36 {{ searchform('form-inline', True) }}
37 {% if search_performed %}
38 <h2>{{ _('Search Results') }}</h2>
39 {% if not search_results %}
40 <p>{{ _('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.') }}</p>
41 {% endif %}
42 {% endif %}
43 <div id="search-results">
44 {% if search_results %}
45 <ul>
46 {% for href, caption, context in search_results %}
47 <li><a href="{{ pathto(item.href) }}">{{ caption }}</a>
48 <div class="context">{{ context|e }}</div>
49 </li>
50 {% endfor %}
51 </ul>
52 {% endif %}
53 </div>
54 {% endblock %}
+0
-556
source/misc/embedded_libs/fmt-8.1.1/doc/api.rst less more
0 .. _string-formatting-api:
1
2 *************
3 API Reference
4 *************
5
6 The {fmt} library API consists of the following parts:
7
8 * :ref:`fmt/core.h <core-api>`: the core API providing main formatting functions
9 for ``char``/UTF-8 with compile-time checks and minimal dependencies
10 * :ref:`fmt/format.h <format-api>`: the full format API providing additional
11 formatting functions and locale support
12 * :ref:`fmt/ranges.h <ranges-api>`: formatting of ranges and tuples
13 * :ref:`fmt/chrono.h <chrono-api>`: date and time formatting
14 * :ref:`fmt/compile.h <compile-api>`: format string compilation
15 * :ref:`fmt/color.h <color-api>`: terminal color and text style
16 * :ref:`fmt/os.h <os-api>`: system APIs
17 * :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
18 * :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
19 * :ref:`fmt/xchar.h <xchar-api>`: optional ``wchar_t`` support
20
21 All functions and types provided by the library reside in namespace ``fmt`` and
22 macros have prefix ``FMT_``.
23
24 .. _core-api:
25
26 Core API
27 ========
28
29 ``fmt/core.h`` defines the core API which provides main formatting functions for
30 ``char``/UTF-8 with compile-time checks. It has minimal include dependencies for
31 better compile times. This header is only beneficial when using {fmt} as a
32 library and not in the header-only mode.
33
34 The following functions use :ref:`format string syntax <syntax>`
35 similar to that of Python's `str.format
36 <https://docs.python.org/3/library/stdtypes.html#str.format>`_.
37 They take *fmt* and *args* as arguments.
38
39 *fmt* is a format string that contains literal text and replacement fields
40 surrounded by braces ``{}``. The fields are replaced with formatted arguments
41 in the resulting string. `~fmt::format_string` is a format string which can be
42 implicitly constructed from a string literal or a ``constexpr`` string and is
43 checked at compile time in C++20. To pass a runtime format string wrap it in
44 `fmt::runtime`.
45
46 *args* is an argument list representing objects to be formatted.
47
48 .. _format:
49
50 .. doxygenfunction:: format(format_string<T...> fmt, T&&... args) -> std::string
51 .. doxygenfunction:: vformat(string_view fmt, format_args args) -> std::string
52
53 .. doxygenfunction:: format_to(OutputIt out, format_string<T...> fmt, T&&... args) -> OutputIt
54 .. doxygenfunction:: format_to_n(OutputIt out, size_t n, format_string<T...> fmt, T&&... args) -> format_to_n_result<OutputIt>
55 .. doxygenfunction:: formatted_size(format_string<T...> fmt, T&&... args) -> size_t
56
57 .. doxygenstruct:: fmt::format_to_n_result
58 :members:
59
60 .. _print:
61
62 .. doxygenfunction:: fmt::print(format_string<T...> fmt, T&&... args)
63 .. doxygenfunction:: fmt::vprint(string_view fmt, format_args args)
64
65 .. doxygenfunction:: print(std::FILE *f, format_string<T...> fmt, T&&... args)
66 .. doxygenfunction:: vprint(std::FILE *f, string_view fmt, format_args args)
67
68 Compile-time Format String Checks
69 ---------------------------------
70
71 Compile-time checks are enabled when using ``FMT_STRING``. They support built-in
72 and string types as well as user-defined types with ``constexpr`` ``parse``
73 functions in their ``formatter`` specializations.
74 Requires C++14 and is a no-op in C++11.
75
76 .. doxygendefine:: FMT_STRING
77
78 To force the use of compile-time checks, define the preprocessor variable
79 ``FMT_ENFORCE_COMPILE_STRING``. When set, functions accepting ``FMT_STRING``
80 will fail to compile with regular strings. Runtime-checked
81 formatting is still possible using ``fmt::vformat``, ``fmt::vprint``, etc.
82
83 .. doxygenclass:: fmt::basic_format_string
84 :members:
85
86 .. doxygentypedef:: fmt::format_string
87
88 .. doxygenfunction:: fmt::runtime(const S&)
89
90 Named Arguments
91 ---------------
92
93 .. doxygenfunction:: fmt::arg(const S&, const T&)
94
95 Named arguments are not supported in compile-time checks at the moment.
96
97 Argument Lists
98 --------------
99
100 You can create your own formatting function with compile-time checks and small
101 binary footprint, for example (https://godbolt.org/z/oba4Mc):
102
103 .. code:: c++
104
105 #include <fmt/format.h>
106
107 void vlog(const char* file, int line, fmt::string_view format,
108 fmt::format_args args) {
109 fmt::print("{}: {}: ", file, line);
110 fmt::vprint(format, args);
111 }
112
113 template <typename S, typename... Args>
114 void log(const char* file, int line, const S& format, Args&&... args) {
115 vlog(file, line, format,
116 fmt::make_args_checked<Args...>(format, args...));
117 }
118
119 #define MY_LOG(format, ...) \
120 log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__)
121
122 MY_LOG("invalid squishiness: {}", 42);
123
124 Note that ``vlog`` is not parameterized on argument types which improves compile
125 times and reduces binary code size compared to a fully parameterized version.
126
127 .. doxygenfunction:: fmt::make_args_checked(const S&, const remove_reference_t<Args>&...)
128
129 .. doxygenfunction:: fmt::make_format_args(const Args&...)
130
131 .. doxygenclass:: fmt::format_arg_store
132 :members:
133
134 .. doxygenclass:: fmt::dynamic_format_arg_store
135 :members:
136
137 .. doxygenclass:: fmt::basic_format_args
138 :members:
139
140 .. doxygentypedef:: fmt::format_args
141
142 .. doxygenclass:: fmt::basic_format_arg
143 :members:
144
145 .. doxygenclass:: fmt::basic_format_context
146 :members:
147
148 .. doxygentypedef:: fmt::format_context
149
150 Compatibility
151 -------------
152
153 .. doxygenclass:: fmt::basic_string_view
154 :members:
155
156 .. doxygentypedef:: fmt::string_view
157
158 Locale
159 ------
160
161 All formatting is locale-independent by default. Use the ``'L'`` format
162 specifier to insert the appropriate number separator characters from the
163 locale::
164
165 #include <fmt/core.h>
166 #include <locale>
167
168 std::locale::global(std::locale("en_US.UTF-8"));
169 auto s = fmt::format("{:L}", 1000000); // s == "1,000,000"
170
171 .. _format-api:
172
173 Format API
174 ==========
175
176 ``fmt/format.h`` defines the full format API providing additional formatting
177 functions and locale support.
178
179 .. _udt:
180
181 Formatting User-defined Types
182 -----------------------------
183
184 To make a user-defined type formattable, specialize the ``formatter<T>`` struct
185 template and implement ``parse`` and ``format`` methods::
186
187 #include <fmt/format.h>
188
189 struct point {
190 double x, y;
191 };
192
193 template <> struct fmt::formatter<point> {
194 // Presentation format: 'f' - fixed, 'e' - exponential.
195 char presentation = 'f';
196
197 // Parses format specifications of the form ['f' | 'e'].
198 constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
199 // [ctx.begin(), ctx.end()) is a character range that contains a part of
200 // the format string starting from the format specifications to be parsed,
201 // e.g. in
202 //
203 // fmt::format("{:f} - point of interest", point{1, 2});
204 //
205 // the range will contain "f} - point of interest". The formatter should
206 // parse specifiers until '}' or the end of the range. In this example
207 // the formatter should parse the 'f' specifier and return an iterator
208 // pointing to '}'.
209
210 // Parse the presentation format and store it in the formatter:
211 auto it = ctx.begin(), end = ctx.end();
212 if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;
213
214 // Check if reached the end of the range:
215 if (it != end && *it != '}') throw format_error("invalid format");
216
217 // Return an iterator past the end of the parsed range:
218 return it;
219 }
220
221 // Formats the point p using the parsed format specification (presentation)
222 // stored in this formatter.
223 template <typename FormatContext>
224 auto format(const point& p, FormatContext& ctx) -> decltype(ctx.out()) {
225 // ctx.out() is an output iterator to write to.
226 return presentation == 'f'
227 ? format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y)
228 : format_to(ctx.out(), "({:.1e}, {:.1e})", p.x, p.y);
229 }
230 };
231
232 Then you can pass objects of type ``point`` to any formatting function::
233
234 point p = {1, 2};
235 std::string s = fmt::format("{:f}", p);
236 // s == "(1.0, 2.0)"
237
238 You can also reuse existing formatters via inheritance or composition, for
239 example::
240
241 enum class color {red, green, blue};
242
243 template <> struct fmt::formatter<color>: formatter<string_view> {
244 // parse is inherited from formatter<string_view>.
245 template <typename FormatContext>
246 auto format(color c, FormatContext& ctx) {
247 string_view name = "unknown";
248 switch (c) {
249 case color::red: name = "red"; break;
250 case color::green: name = "green"; break;
251 case color::blue: name = "blue"; break;
252 }
253 return formatter<string_view>::format(name, ctx);
254 }
255 };
256
257 Since ``parse`` is inherited from ``formatter<string_view>`` it will recognize
258 all string format specifications, for example
259
260 .. code-block:: c++
261
262 fmt::format("{:>10}", color::blue)
263
264 will return ``" blue"``.
265
266 You can also write a formatter for a hierarchy of classes::
267
268 #include <type_traits>
269 #include <fmt/format.h>
270
271 struct A {
272 virtual ~A() {}
273 virtual std::string name() const { return "A"; }
274 };
275
276 struct B : A {
277 virtual std::string name() const { return "B"; }
278 };
279
280 template <typename T>
281 struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
282 fmt::formatter<std::string> {
283 template <typename FormatCtx>
284 auto format(const A& a, FormatCtx& ctx) {
285 return fmt::formatter<std::string>::format(a.name(), ctx);
286 }
287 };
288
289 int main() {
290 B b;
291 A& a = b;
292 fmt::print("{}", a); // prints "B"
293 }
294
295 If a type provides both a ``formatter`` specialization and an implicit
296 conversion to a formattable type, the specialization takes precedence over the
297 conversion.
298
299 .. doxygenclass:: fmt::basic_format_parse_context
300 :members:
301
302 Literal-based API
303 -----------------
304
305 The following user-defined literals are defined in ``fmt/format.h``.
306
307 .. doxygenfunction:: operator""_format(const char *s, size_t n) -> detail::udl_formatter<char>
308
309 .. doxygenfunction:: operator""_a(const char *s, size_t) -> detail::udl_arg<char>
310
311 Utilities
312 ---------
313
314 .. doxygenfunction:: fmt::ptr(T p) -> const void*
315 .. doxygenfunction:: fmt::ptr(const std::unique_ptr<T> &p) -> const void*
316 .. doxygenfunction:: fmt::ptr(const std::shared_ptr<T> &p) -> const void*
317
318 .. doxygenfunction:: fmt::to_string(const T &value) -> std::string
319
320 .. doxygenfunction:: fmt::to_string_view(const Char *s) -> basic_string_view<Char>
321
322 .. doxygenfunction:: fmt::join(Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>>
323
324 .. doxygenfunction:: fmt::join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel>
325
326 .. doxygenfunction:: fmt::group_digits(T value) -> group_digits_view<T>
327
328 .. doxygenclass:: fmt::detail::buffer
329 :members:
330
331 .. doxygenclass:: fmt::basic_memory_buffer
332 :protected-members:
333 :members:
334
335 System Errors
336 -------------
337
338 {fmt} does not use ``errno`` to communicate errors to the user, but it may call
339 system functions which set ``errno``. Users should not make any assumptions
340 about the value of ``errno`` being preserved by library functions.
341
342 .. doxygenfunction:: fmt::system_error
343
344 .. doxygenfunction:: fmt::format_system_error
345
346 Custom Allocators
347 -----------------
348
349 The {fmt} library supports custom dynamic memory allocators.
350 A custom allocator class can be specified as a template argument to
351 :class:`fmt::basic_memory_buffer`::
352
353 using custom_memory_buffer =
354 fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
355
356 It is also possible to write a formatting function that uses a custom
357 allocator::
358
359 using custom_string =
360 std::basic_string<char, std::char_traits<char>, custom_allocator>;
361
362 custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
363 fmt::format_args args) {
364 auto buf = custom_memory_buffer(alloc);
365 fmt::vformat_to(std::back_inserter(buf), format_str, args);
366 return custom_string(buf.data(), buf.size(), alloc);
367 }
368
369 template <typename ...Args>
370 inline custom_string format(custom_allocator alloc,
371 fmt::string_view format_str,
372 const Args& ... args) {
373 return vformat(alloc, format_str, fmt::make_format_args(args...));
374 }
375
376 The allocator will be used for the output container only. Formatting functions
377 normally don't do any allocations for built-in and string types except for
378 non-default floating-point formatting that occasionally falls back on
379 ``sprintf``.
380
381 .. _ranges-api:
382
383 Ranges and Tuple Formatting
384 ===========================
385
386 The library also supports convenient formatting of ranges and tuples::
387
388 #include <fmt/ranges.h>
389
390 std::tuple<char, int, float> t{'a', 1, 2.0f};
391 // Prints "('a', 1, 2.0)"
392 fmt::print("{}", t);
393
394
395 NOTE: currently, the overload of ``fmt::join`` for iterables exists in the main
396 ``format.h`` header, but expect this to change in the future.
397
398 Using ``fmt::join``, you can separate tuple elements with a custom separator::
399
400 #include <fmt/ranges.h>
401
402 std::tuple<int, char> t = {1, 'a'};
403 // Prints "1, a"
404 fmt::print("{}", fmt::join(t, ", "));
405
406 .. _chrono-api:
407
408 Date and Time Formatting
409 ========================
410
411 ``fmt/chrono.h`` provides formatters for
412
413 * `std::chrono::duration <https://en.cppreference.com/w/cpp/chrono/duration>`_
414 * `std::chrono::time_point
415 <https://en.cppreference.com/w/cpp/chrono/time_point>`_
416 * `std::tm <https://en.cppreference.com/w/cpp/chrono/c/tm>`_
417
418 The format syntax is described in :ref:`chrono-specs`.
419
420 **Example**::
421
422 #include <fmt/chrono.h>
423
424 int main() {
425 std::time_t t = std::time(nullptr);
426
427 // Prints "The date is 2020-11-07." (with the current date):
428 fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
429
430 using namespace std::literals::chrono_literals;
431
432 // Prints "Default format: 42s 100ms":
433 fmt::print("Default format: {} {}\n", 42s, 100ms);
434
435 // Prints "strftime-like format: 03:15:30":
436 fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
437 }
438
439 .. doxygenfunction:: localtime(std::time_t time)
440
441 .. doxygenfunction:: gmtime(std::time_t time)
442
443 .. _compile-api:
444
445 Format string compilation
446 =========================
447
448 ``fmt/compile.h`` provides format string compilation support when using
449 ``FMT_COMPILE``. Format strings are parsed, checked and converted into efficient
450 formatting code at compile-time. This supports arguments of built-in and string
451 types as well as user-defined types with ``constexpr`` ``parse`` functions in
452 their ``formatter`` specializations. Format string compilation can generate more
453 binary code compared to the default API and is only recommended in places where
454 formatting is a performance bottleneck.
455
456 .. doxygendefine:: FMT_COMPILE
457
458 .. _color-api:
459
460 Terminal color and text style
461 =============================
462
463 ``fmt/color.h`` provides support for terminal color and text style output.
464
465 .. doxygenfunction:: print(const text_style &ts, const S &format_str, const Args&... args)
466
467 .. doxygenfunction:: fg(detail::color_type)
468
469 .. doxygenfunction:: bg(detail::color_type)
470
471 .. _os-api:
472
473 System APIs
474 ===========
475
476 .. doxygenclass:: fmt::ostream
477 :members:
478
479 .. doxygenfunction:: fmt::windows_error
480 :members:
481
482 .. _ostream-api:
483
484 ``std::ostream`` Support
485 ========================
486
487 ``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
488 user-defined types that have an overloaded insertion operator (``operator<<``)::
489
490 #include <fmt/ostream.h>
491
492 class date {
493 int year_, month_, day_;
494 public:
495 date(int year, int month, int day): year_(year), month_(month), day_(day) {}
496
497 friend std::ostream& operator<<(std::ostream& os, const date& d) {
498 return os << d.year_ << '-' << d.month_ << '-' << d.day_;
499 }
500 };
501
502 std::string s = fmt::format("The date is {}", date(2012, 12, 9));
503 // s == "The date is 2012-12-9"
504
505 {fmt} only supports insertion operators that are defined in the same namespaces
506 as the types they format and can be found with the argument-dependent lookup.
507
508 .. doxygenfunction:: print(std::basic_ostream<Char> &os, const S &format_str, Args&&... args)
509
510 .. _printf-api:
511
512 ``printf`` Formatting
513 =====================
514
515 The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
516 The following functions use `printf format string syntax
517 <https://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
518 the POSIX extension for positional arguments. Unlike their standard
519 counterparts, the ``fmt`` functions are type-safe and throw an exception if an
520 argument type doesn't match its format specification.
521
522 .. doxygenfunction:: printf(const S &format_str, const T&... args)
523
524 .. doxygenfunction:: fprintf(std::FILE *f, const S &fmt, const T&... args) -> int
525
526 .. doxygenfunction:: sprintf(const S&, const T&...)
527
528 .. _xchar-api:
529
530 ``wchar_t`` Support
531 ===================
532
533 The optional header ``fmt/xchar.h`` provides support for ``wchar_t`` and exotic
534 character types.
535
536 .. doxygenstruct:: fmt::is_char
537
538 .. doxygentypedef:: fmt::wstring_view
539
540 .. doxygentypedef:: fmt::wformat_context
541
542 .. doxygenfunction:: fmt::to_wstring(const T &value)
543
544 Compatibility with C++20 ``std::format``
545 ========================================
546
547 {fmt} implements nearly all of the `C++20 formatting library
548 <https://en.cppreference.com/w/cpp/utility/format>`_ with the following
549 differences:
550
551 * Names are defined in the ``fmt`` namespace instead of ``std`` to avoid
552 collisions with standard library implementations.
553 * Width calculation doesn't use grapheme clusterization. The latter has been
554 implemented in a separate branch but hasn't been integrated yet.
555 * Most C++20 chrono types are not supported yet.
+0
-2
source/misc/embedded_libs/fmt-8.1.1/doc/basic-bootstrap/README less more
0 Sphinx basic theme with Bootstrap support. Modifications are kept to
1 a minimum to simplify integration in case of changes to Sphinx theming.
+0
-208
source/misc/embedded_libs/fmt-8.1.1/doc/basic-bootstrap/layout.html less more
0 {#
1 basic/layout.html
2 ~~~~~~~~~~~~~~~~~
3
4 Master layout template for Sphinx themes.
5
6 :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
7 :license: BSD, see LICENSE for details.
8 #}
9 {%- block doctype -%}
10 <!DOCTYPE html>
11 {%- endblock %}
12 {%- set reldelim1 = reldelim1 is not defined and ' &raquo;' or reldelim1 %}
13 {%- set reldelim2 = reldelim2 is not defined and ' |' or reldelim2 %}
14 {%- set render_sidebar = (not embedded) and (not theme_nosidebar|tobool) and
15 (sidebars != []) %}
16 {%- set url_root = pathto('', 1) %}
17 {# XXX necessary? #}
18 {%- if url_root == '#' %}{% set url_root = '' %}{% endif %}
19 {%- if not embedded and docstitle %}
20 {%- set titlesuffix = " &mdash; "|safe + docstitle|e %}
21 {%- else %}
22 {%- set titlesuffix = "" %}
23 {%- endif %}
24
25 {%- macro relbar() %}
26 <div class="related" role="navigation" aria-label="related navigation">
27 <h3>{{ _('Navigation') }}</h3>
28 <ul>
29 {%- for rellink in rellinks %}
30 <li class="right" {% if loop.first %}style="margin-right: 10px"{% endif %}>
31 <a href="{{ pathto(rellink[0]) }}" title="{{ rellink[1]|striptags|e }}"
32 {{ accesskey(rellink[2]) }}>{{ rellink[3] }}</a>
33 {%- if not loop.first %}{{ reldelim2 }}{% endif %}</li>
34 {%- endfor %}
35 {%- block rootrellink %}
36 <li class="nav-item nav-item-0"><a href="{{ pathto(master_doc) }}">{{ shorttitle|e }}</a>{{ reldelim1 }}</li>
37 {%- endblock %}
38 {%- for parent in parents %}
39 <li class="nav-item nav-item-{{ loop.index }}"><a href="{{ parent.link|e }}" {% if loop.last %}{{ accesskey("U") }}{% endif %}>{{ parent.title }}</a>{{ reldelim1 }}</li>
40 {%- endfor %}
41 {%- block relbaritems %} {% endblock %}
42 </ul>
43 </div>
44 {%- endmacro %}
45
46 {%- macro sidebar() %}
47 {%- if render_sidebar %}
48 <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
49 <div class="sphinxsidebarwrapper">
50 {%- block sidebarlogo %}
51 {%- if logo %}
52 <p class="logo"><a href="{{ pathto(master_doc) }}">
53 <img class="logo" src="{{ pathto('_static/' + logo, 1) }}" alt="Logo"/>
54 </a></p>
55 {%- endif %}
56 {%- endblock %}
57 {%- if sidebars != None %}
58 {#- new style sidebar: explicitly include/exclude templates #}
59 {%- for sidebartemplate in sidebars %}
60 {%- include sidebartemplate %}
61 {%- endfor %}
62 {%- else %}
63 {#- old style sidebars: using blocks -- should be deprecated #}
64 {%- block sidebartoc %}
65 {%- include "localtoc.html" %}
66 {%- endblock %}
67 {%- block sidebarrel %}
68 {%- include "relations.html" %}
69 {%- endblock %}
70 {%- block sidebarsourcelink %}
71 {%- include "sourcelink.html" %}
72 {%- endblock %}
73 {%- if customsidebar %}
74 {%- include customsidebar %}
75 {%- endif %}
76 {%- block sidebarsearch %}
77 {%- include "searchbox.html" %}
78 {%- endblock %}
79 {%- endif %}
80 </div>
81 </div>
82 {%- endif %}
83 {%- endmacro %}
84
85 {%- macro script() %}
86 <script type="text/javascript">
87 var DOCUMENTATION_OPTIONS = {
88 URL_ROOT: '{{ url_root }}',
89 VERSION: '{{ release|e }}',
90 COLLAPSE_INDEX: false,
91 FILE_SUFFIX: '{{ '' if no_search_suffix else file_suffix }}',
92 LINK_SUFFIX: '{{ link_suffix }}',
93 SOURCELINK_SUFFIX: '{{ sourcelink_suffix }}',
94 HAS_SOURCE: {{ has_source|lower }},
95 SOURCELINK_SUFFIX: '{{ sourcelink_suffix }}'
96 };
97 </script>
98 {%- for scriptfile in script_files %}
99 {{ js_tag(scriptfile) }}
100 {%- endfor %}
101 {%- endmacro %}
102
103 {%- macro css() %}
104 <link rel="stylesheet" href="{{ pathto('_static/' + style, 1) }}" type="text/css" />
105 <link rel="stylesheet" href="{{ pathto('_static/pygments.css', 1) }}" type="text/css" />
106 {%- for cssfile in css_files %}
107 <link rel="stylesheet" href="{{ pathto(cssfile, 1) }}" type="text/css" />
108 {%- endfor %}
109 {%- endmacro %}
110
111 <html lang="en">
112 <head>
113 <meta charset="{{ encoding }}">
114 <meta http-equiv="X-UA-Compatible" content="IE=edge">
115 <meta name="viewport" content="width=device-width, initial-scale=1">
116 {# The above 3 meta tags *must* come first in the head; any other head content
117 must come *after* these tags. #}
118 {{ metatags }}
119 {%- block htmltitle %}
120 <title>{{ title|striptags|e }}{{ titlesuffix }}</title>
121 {%- endblock %}
122 {{ css() }}
123 {%- if not embedded %}
124 {{ script() }}
125 {%- if use_opensearch %}
126 <link rel="search" type="application/opensearchdescription+xml"
127 title="{% trans docstitle=docstitle|e %}Search within {{ docstitle }}{% endtrans %}"
128 href="{{ pathto('_static/opensearch.xml', 1) }}"/>
129 {%- endif %}
130 {%- if favicon %}
131 <link rel="shortcut icon" href="{{ pathto('_static/' + favicon, 1) }}"/>
132 {%- endif %}
133 {%- endif %}
134 {%- block linktags %}
135 {%- if hasdoc('about') %}
136 <link rel="author" title="{{ _('About these documents') }}" href="{{ pathto('about') }}" />
137 {%- endif %}
138 {%- if hasdoc('genindex') %}
139 <link rel="index" title="{{ _('Index') }}" href="{{ pathto('genindex') }}" />
140 {%- endif %}
141 {%- if hasdoc('search') %}
142 <link rel="search" title="{{ _('Search') }}" href="{{ pathto('search') }}" />
143 {%- endif %}
144 {%- if hasdoc('copyright') %}
145 <link rel="copyright" title="{{ _('Copyright') }}" href="{{ pathto('copyright') }}" />
146 {%- endif %}
147 {%- if parents %}
148 <link rel="up" title="{{ parents[-1].title|striptags|e }}" href="{{ parents[-1].link|e }}" />
149 {%- endif %}
150 {%- if next %}
151 <link rel="next" title="{{ next.title|striptags|e }}" href="{{ next.link|e }}" />
152 {%- endif %}
153 {%- if prev %}
154 <link rel="prev" title="{{ prev.title|striptags|e }}" href="{{ prev.link|e }}" />
155 {%- endif %}
156 {%- endblock %}
157 {%- block extrahead %} {% endblock %}
158 </head>
159 <body role="document">
160 {%- block header %}{% endblock %}
161
162 {%- block relbar1 %}{{ relbar() }}{% endblock %}
163
164 {%- block content %}
165 {%- block sidebar1 %} {# possible location for sidebar #} {% endblock %}
166
167 <div class="document">
168 {%- block document %}
169 <div class="documentwrapper">
170 {%- if render_sidebar %}
171 <div class="bodywrapper">
172 {%- endif %}
173 <div class="body" role="main">
174 {% block body %} {% endblock %}
175 </div>
176 {%- if render_sidebar %}
177 </div>
178 {%- endif %}
179 </div>
180 {%- endblock %}
181
182 {%- block sidebar2 %}{{ sidebar() }}{% endblock %}
183 <div class="clearer"></div>
184 </div>
185 {%- endblock %}
186
187 {%- block relbar2 %}{{ relbar() }}{% endblock %}
188
189 {%- block footer %}
190 <div class="footer" role="contentinfo">
191 {%- if show_copyright %}
192 {%- if hasdoc('copyright') %}
193 {% trans path=pathto('copyright'), copyright=copyright|e %}&copy; <a href="{{ path }}">Copyright</a> {{ copyright }}.{% endtrans %}
194 {%- else %}
195 {% trans copyright=copyright|e %}&copy; Copyright {{ copyright }}.{% endtrans %}
196 {%- endif %}
197 {%- endif %}
198 {%- if last_updated %}
199 {% trans last_updated=last_updated|e %}Last updated on {{ last_updated }}.{% endtrans %}
200 {%- endif %}
201 {%- if show_sphinx %}
202 {% trans sphinx_version=sphinx_version|e %}Created using <a href="http://sphinx-doc.org/">Sphinx</a> {{ sphinx_version }}.{% endtrans %}
203 {%- endif %}
204 </div>
205 {%- endblock %}
206 </body>
207 </html>
+0
-2
source/misc/embedded_libs/fmt-8.1.1/doc/basic-bootstrap/theme.conf less more
0 [theme]
1 inherit = basic
+0
-73
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/alerts.less less more
0 //
1 // Alerts
2 // --------------------------------------------------
3
4
5 // Base styles
6 // -------------------------
7
8 .alert {
9 padding: @alert-padding;
10 margin-bottom: @line-height-computed;
11 border: 1px solid transparent;
12 border-radius: @alert-border-radius;
13
14 // Headings for larger alerts
15 h4 {
16 margin-top: 0;
17 // Specified for the h4 to prevent conflicts of changing @headings-color
18 color: inherit;
19 }
20
21 // Provide class for links that match alerts
22 .alert-link {
23 font-weight: @alert-link-font-weight;
24 }
25
26 // Improve alignment and spacing of inner content
27 > p,
28 > ul {
29 margin-bottom: 0;
30 }
31
32 > p + p {
33 margin-top: 5px;
34 }
35 }
36
37 // Dismissible alerts
38 //
39 // Expand the right padding and account for the close button's positioning.
40
41 .alert-dismissable, // The misspelled .alert-dismissable was deprecated in 3.2.0.
42 .alert-dismissible {
43 padding-right: (@alert-padding + 20);
44
45 // Adjust close link position
46 .close {
47 position: relative;
48 top: -2px;
49 right: -21px;
50 color: inherit;
51 }
52 }
53
54 // Alternate styles
55 //
56 // Generate contextual modifier classes for colorizing the alert.
57
58 .alert-success {
59 .alert-variant(@alert-success-bg; @alert-success-border; @alert-success-text);
60 }
61
62 .alert-info {
63 .alert-variant(@alert-info-bg; @alert-info-border; @alert-info-text);
64 }
65
66 .alert-warning {
67 .alert-variant(@alert-warning-bg; @alert-warning-border; @alert-warning-text);
68 }
69
70 .alert-danger {
71 .alert-variant(@alert-danger-bg; @alert-danger-border; @alert-danger-text);
72 }
+0
-66
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/badges.less less more
0 //
1 // Badges
2 // --------------------------------------------------
3
4
5 // Base class
6 .badge {
7 display: inline-block;
8 min-width: 10px;
9 padding: 3px 7px;
10 font-size: @font-size-small;
11 font-weight: @badge-font-weight;
12 color: @badge-color;
13 line-height: @badge-line-height;
14 vertical-align: baseline;
15 white-space: nowrap;
16 text-align: center;
17 background-color: @badge-bg;
18 border-radius: @badge-border-radius;
19
20 // Empty badges collapse automatically (not available in IE8)
21 &:empty {
22 display: none;
23 }
24
25 // Quick fix for badges in buttons
26 .btn & {
27 position: relative;
28 top: -1px;
29 }
30
31 .btn-xs &,
32 .btn-group-xs > .btn & {
33 top: 0;
34 padding: 1px 5px;
35 }
36
37 // Hover state, but only for links
38 a& {
39 &:hover,
40 &:focus {
41 color: @badge-link-hover-color;
42 text-decoration: none;
43 cursor: pointer;
44 }
45 }
46
47 // Account for badges in navs
48 .list-group-item.active > &,
49 .nav-pills > .active > a > & {
50 color: @badge-active-color;
51 background-color: @badge-active-bg;
52 }
53
54 .list-group-item > & {
55 float: right;
56 }
57
58 .list-group-item > & + & {
59 margin-right: 5px;
60 }
61
62 .nav-pills > li > a > & {
63 margin-left: 3px;
64 }
65 }
+0
-50
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/bootstrap.less less more
0 // Core variables and mixins
1 @import "variables.less";
2 @import "mixins.less";
3
4 // Reset and dependencies
5 @import "normalize.less";
6 @import "print.less";
7 @import "glyphicons.less";
8
9 // Core CSS
10 @import "scaffolding.less";
11 @import "type.less";
12 @import "code.less";
13 @import "grid.less";
14 @import "tables.less";
15 @import "forms.less";
16 @import "buttons.less";
17
18 // Components
19 @import "component-animations.less";
20 @import "dropdowns.less";
21 @import "button-groups.less";
22 @import "input-groups.less";
23 @import "navs.less";
24 @import "navbar.less";
25 @import "breadcrumbs.less";
26 @import "pagination.less";
27 @import "pager.less";
28 @import "labels.less";
29 @import "badges.less";
30 @import "jumbotron.less";
31 @import "thumbnails.less";
32 @import "alerts.less";
33 @import "progress-bars.less";
34 @import "media.less";
35 @import "list-group.less";
36 @import "panels.less";
37 @import "responsive-embed.less";
38 @import "wells.less";
39 @import "close.less";
40
41 // Components w/ JavaScript
42 @import "modals.less";
43 @import "tooltip.less";
44 @import "popovers.less";
45 @import "carousel.less";
46
47 // Utility classes
48 @import "utilities.less";
49 @import "responsive-utilities.less";
+0
-26
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/breadcrumbs.less less more
0 //
1 // Breadcrumbs
2 // --------------------------------------------------
3
4
5 .breadcrumb {
6 padding: @breadcrumb-padding-vertical @breadcrumb-padding-horizontal;
7 margin-bottom: @line-height-computed;
8 list-style: none;
9 background-color: @breadcrumb-bg;
10 border-radius: @border-radius-base;
11
12 > li {
13 display: inline-block;
14
15 + li:before {
16 content: "@{breadcrumb-separator}\00a0"; // Unicode space added since inline-block means non-collapsing white-space
17 padding: 0 5px;
18 color: @breadcrumb-color;
19 }
20 }
21
22 > .active {
23 color: @breadcrumb-active-color;
24 }
25 }
+0
-243
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/button-groups.less less more
0 //
1 // Button groups
2 // --------------------------------------------------
3
4 // Make the div behave like a button
5 .btn-group,
6 .btn-group-vertical {
7 position: relative;
8 display: inline-block;
9 vertical-align: middle; // match .btn alignment given font-size hack above
10 > .btn {
11 position: relative;
12 float: left;
13 // Bring the "active" button to the front
14 &:hover,
15 &:focus,
16 &:active,
17 &.active {
18 z-index: 2;
19 }
20 }
21 }
22
23 // Prevent double borders when buttons are next to each other
24 .btn-group {
25 .btn + .btn,
26 .btn + .btn-group,
27 .btn-group + .btn,
28 .btn-group + .btn-group {
29 margin-left: -1px;
30 }
31 }
32
33 // Optional: Group multiple button groups together for a toolbar
34 .btn-toolbar {
35 margin-left: -5px; // Offset the first child's margin
36 &:extend(.clearfix all);
37
38 .btn-group,
39 .input-group {
40 float: left;
41 }
42 > .btn,
43 > .btn-group,
44 > .input-group {
45 margin-left: 5px;
46 }
47 }
48
49 .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
50 border-radius: 0;
51 }
52
53 // Set corners individual because sometimes a single button can be in a .btn-group and we need :first-child and :last-child to both match
54 .btn-group > .btn:first-child {
55 margin-left: 0;
56 &:not(:last-child):not(.dropdown-toggle) {
57 .border-right-radius(0);
58 }
59 }
60 // Need .dropdown-toggle since :last-child doesn't apply given a .dropdown-menu immediately after it
61 .btn-group > .btn:last-child:not(:first-child),
62 .btn-group > .dropdown-toggle:not(:first-child) {
63 .border-left-radius(0);
64 }
65
66 // Custom edits for including btn-groups within btn-groups (useful for including dropdown buttons within a btn-group)
67 .btn-group > .btn-group {
68 float: left;
69 }
70 .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
71 border-radius: 0;
72 }
73 .btn-group > .btn-group:first-child:not(:last-child) {
74 > .btn:last-child,
75 > .dropdown-toggle {
76 .border-right-radius(0);
77 }
78 }
79 .btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
80 .border-left-radius(0);
81 }
82
83 // On active and open, don't show outline
84 .btn-group .dropdown-toggle:active,
85 .btn-group.open .dropdown-toggle {
86 outline: 0;
87 }
88
89
90 // Sizing
91 //
92 // Remix the default button sizing classes into new ones for easier manipulation.
93
94 .btn-group-xs > .btn { &:extend(.btn-xs); }
95 .btn-group-sm > .btn { &:extend(.btn-sm); }
96 .btn-group-lg > .btn { &:extend(.btn-lg); }
97
98
99 // Split button dropdowns
100 // ----------------------
101
102 // Give the line between buttons some depth
103 .btn-group > .btn + .dropdown-toggle {
104 padding-left: 8px;
105 padding-right: 8px;
106 }
107 .btn-group > .btn-lg + .dropdown-toggle {
108 padding-left: 12px;
109 padding-right: 12px;
110 }
111
112 // The clickable button for toggling the menu
113 // Remove the gradient and set the same inset shadow as the :active state
114 .btn-group.open .dropdown-toggle {
115 .box-shadow(inset 0 3px 5px rgba(0,0,0,.125));
116
117 // Show no shadow for `.btn-link` since it has no other button styles.
118 &.btn-link {
119 .box-shadow(none);
120 }
121 }
122
123
124 // Reposition the caret
125 .btn .caret {
126 margin-left: 0;
127 }
128 // Carets in other button sizes
129 .btn-lg .caret {
130 border-width: @caret-width-large @caret-width-large 0;
131 border-bottom-width: 0;
132 }
133 // Upside down carets for .dropup
134 .dropup .btn-lg .caret {
135 border-width: 0 @caret-width-large @caret-width-large;
136 }
137
138
139 // Vertical button groups
140 // ----------------------
141
142 .btn-group-vertical {
143 > .btn,
144 > .btn-group,
145 > .btn-group > .btn {
146 display: block;
147 float: none;
148 width: 100%;
149 max-width: 100%;
150 }
151
152 // Clear floats so dropdown menus can be properly placed
153 > .btn-group {
154 &:extend(.clearfix all);
155 > .btn {
156 float: none;
157 }
158 }
159
160 > .btn + .btn,
161 > .btn + .btn-group,
162 > .btn-group + .btn,
163 > .btn-group + .btn-group {
164 margin-top: -1px;
165 margin-left: 0;
166 }
167 }
168
169 .btn-group-vertical > .btn {
170 &:not(:first-child):not(:last-child) {
171 border-radius: 0;
172 }
173 &:first-child:not(:last-child) {
174 border-top-right-radius: @border-radius-base;
175 .border-bottom-radius(0);
176 }
177 &:last-child:not(:first-child) {
178 border-bottom-left-radius: @border-radius-base;
179 .border-top-radius(0);
180 }
181 }
182 .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
183 border-radius: 0;
184 }
185 .btn-group-vertical > .btn-group:first-child:not(:last-child) {
186 > .btn:last-child,
187 > .dropdown-toggle {
188 .border-bottom-radius(0);
189 }
190 }
191 .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
192 .border-top-radius(0);
193 }
194
195
196 // Justified button groups
197 // ----------------------
198
199 .btn-group-justified {
200 display: table;
201 width: 100%;
202 table-layout: fixed;
203 border-collapse: separate;
204 > .btn,
205 > .btn-group {
206 float: none;
207 display: table-cell;
208 width: 1%;
209 }
210 > .btn-group .btn {
211 width: 100%;
212 }
213
214 > .btn-group .dropdown-menu {
215 left: auto;
216 }
217 }
218
219
220 // Checkbox and radio options
221 //
222 // In order to support the browser's form validation feedback, powered by the
223 // `required` attribute, we have to "hide" the inputs via `clip`. We cannot use
224 // `display: none;` or `visibility: hidden;` as that also hides the popover.
225 // Simply visually hiding the inputs via `opacity` would leave them clickable in
226 // certain cases which is prevented by using `clip` and `pointer-events`.
227 // This way, we ensure a DOM element is visible to position the popover from.
228 //
229 // See https://github.com/twbs/bootstrap/pull/12794 and
230 // https://github.com/twbs/bootstrap/pull/14559 for more information.
231
232 [data-toggle="buttons"] {
233 > .btn,
234 > .btn-group > .btn {
235 input[type="radio"],
236 input[type="checkbox"] {
237 position: absolute;
238 clip: rect(0,0,0,0);
239 pointer-events: none;
240 }
241 }
242 }
+0
-160
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/buttons.less less more
0 //
1 // Buttons
2 // --------------------------------------------------
3
4
5 // Base styles
6 // --------------------------------------------------
7
8 .btn {
9 display: inline-block;
10 margin-bottom: 0; // For input.btn
11 font-weight: @btn-font-weight;
12 text-align: center;
13 vertical-align: middle;
14 touch-action: manipulation;
15 cursor: pointer;
16 background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214
17 border: 1px solid transparent;
18 white-space: nowrap;
19 .button-size(@padding-base-vertical; @padding-base-horizontal; @font-size-base; @line-height-base; @border-radius-base);
20 .user-select(none);
21
22 &,
23 &:active,
24 &.active {
25 &:focus,
26 &.focus {
27 .tab-focus();
28 }
29 }
30
31 &:hover,
32 &:focus,
33 &.focus {
34 color: @btn-default-color;
35 text-decoration: none;
36 }
37
38 &:active,
39 &.active {
40 outline: 0;
41 background-image: none;
42 .box-shadow(inset 0 3px 5px rgba(0,0,0,.125));
43 }
44
45 &.disabled,
46 &[disabled],
47 fieldset[disabled] & {
48 cursor: @cursor-disabled;
49 pointer-events: none; // Future-proof disabling of clicks
50 .opacity(.65);
51 .box-shadow(none);
52 }
53 }
54
55
56 // Alternate buttons
57 // --------------------------------------------------
58
59 .btn-default {
60 .button-variant(@btn-default-color; @btn-default-bg; @btn-default-border);
61 }
62 .btn-primary {
63 .button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
64 }
65 // Success appears as green
66 .btn-success {
67 .button-variant(@btn-success-color; @btn-success-bg; @btn-success-border);
68 }
69 // Info appears as blue-green
70 .btn-info {
71 .button-variant(@btn-info-color; @btn-info-bg; @btn-info-border);
72 }
73 // Warning appears as orange
74 .btn-warning {
75 .button-variant(@btn-warning-color; @btn-warning-bg; @btn-warning-border);
76 }
77 // Danger and error appear as red
78 .btn-danger {
79 .button-variant(@btn-danger-color; @btn-danger-bg; @btn-danger-border);
80 }
81
82
83 // Link buttons
84 // -------------------------
85
86 // Make a button look and behave like a link
87 .btn-link {
88 color: @link-color;
89 font-weight: normal;
90 border-radius: 0;
91
92 &,
93 &:active,
94 &.active,
95 &[disabled],
96 fieldset[disabled] & {
97 background-color: transparent;
98 .box-shadow(none);
99 }
100 &,
101 &:hover,
102 &:focus,
103 &:active {
104 border-color: transparent;
105 }
106 &:hover,
107 &:focus {
108 color: @link-hover-color;
109 text-decoration: @link-hover-decoration;
110 background-color: transparent;
111 }
112 &[disabled],
113 fieldset[disabled] & {
114 &:hover,
115 &:focus {
116 color: @btn-link-disabled-color;
117 text-decoration: none;
118 }
119 }
120 }
121
122
123 // Button Sizes
124 // --------------------------------------------------
125
126 .btn-lg {
127 // line-height: ensure even-numbered height of button next to large input
128 .button-size(@padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @border-radius-large);
129 }
130 .btn-sm {
131 // line-height: ensure proper height of button next to small input
132 .button-size(@padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @border-radius-small);
133 }
134 .btn-xs {
135 .button-size(@padding-xs-vertical; @padding-xs-horizontal; @font-size-small; @line-height-small; @border-radius-small);
136 }
137
138
139 // Block button
140 // --------------------------------------------------
141
142 .btn-block {
143 display: block;
144 width: 100%;
145 }
146
147 // Vertically space out multiple block buttons
148 .btn-block + .btn-block {
149 margin-top: 5px;
150 }
151
152 // Specificity overrides
153 input[type="submit"],
154 input[type="reset"],
155 input[type="button"] {
156 &.btn-block {
157 width: 100%;
158 }
159 }
+0
-269
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/carousel.less less more
0 //
1 // Carousel
2 // --------------------------------------------------
3
4
5 // Wrapper for the slide container and indicators
6 .carousel {
7 position: relative;
8 }
9
10 .carousel-inner {
11 position: relative;
12 overflow: hidden;
13 width: 100%;
14
15 > .item {
16 display: none;
17 position: relative;
18 .transition(.6s ease-in-out left);
19
20 // Account for jankitude on images
21 > img,
22 > a > img {
23 &:extend(.img-responsive);
24 line-height: 1;
25 }
26
27 // WebKit CSS3 transforms for supported devices
28 @media all and (transform-3d), (-webkit-transform-3d) {
29 .transition-transform(~'0.6s ease-in-out');
30 .backface-visibility(~'hidden');
31 .perspective(1000);
32
33 &.next,
34 &.active.right {
35 .translate3d(100%, 0, 0);
36 left: 0;
37 }
38 &.prev,
39 &.active.left {
40 .translate3d(-100%, 0, 0);
41 left: 0;
42 }
43 &.next.left,
44 &.prev.right,
45 &.active {
46 .translate3d(0, 0, 0);
47 left: 0;
48 }
49 }
50 }
51
52 > .active,
53 > .next,
54 > .prev {
55 display: block;
56 }
57
58 > .active {
59 left: 0;
60 }
61
62 > .next,
63 > .prev {
64 position: absolute;
65 top: 0;
66 width: 100%;
67 }
68
69 > .next {
70 left: 100%;
71 }
72 > .prev {
73 left: -100%;
74 }
75 > .next.left,
76 > .prev.right {
77 left: 0;
78 }
79
80 > .active.left {
81 left: -100%;
82 }
83 > .active.right {
84 left: 100%;
85 }
86
87 }
88
89 // Left/right controls for nav
90 // ---------------------------
91
92 .carousel-control {
93 position: absolute;
94 top: 0;
95 left: 0;
96 bottom: 0;
97 width: @carousel-control-width;
98 .opacity(@carousel-control-opacity);
99 font-size: @carousel-control-font-size;
100 color: @carousel-control-color;
101 text-align: center;
102 text-shadow: @carousel-text-shadow;
103 // We can't have this transition here because WebKit cancels the carousel
104 // animation if you trip this while in the middle of another animation.
105
106 // Set gradients for backgrounds
107 &.left {
108 #gradient > .horizontal(@start-color: rgba(0,0,0,.5); @end-color: rgba(0,0,0,.0001));
109 }
110 &.right {
111 left: auto;
112 right: 0;
113 #gradient > .horizontal(@start-color: rgba(0,0,0,.0001); @end-color: rgba(0,0,0,.5));
114 }
115
116 // Hover/focus state
117 &:hover,
118 &:focus {
119 outline: 0;
120 color: @carousel-control-color;
121 text-decoration: none;
122 .opacity(.9);
123 }
124
125 // Toggles
126 .icon-prev,
127 .icon-next,
128 .glyphicon-chevron-left,
129 .glyphicon-chevron-right {
130 position: absolute;
131 top: 50%;
132 z-index: 5;
133 display: inline-block;
134 }
135 .icon-prev,
136 .glyphicon-chevron-left {
137 left: 50%;
138 margin-left: -10px;
139 }
140 .icon-next,
141 .glyphicon-chevron-right {
142 right: 50%;
143 margin-right: -10px;
144 }
145 .icon-prev,
146 .icon-next {
147 width: 20px;
148 height: 20px;
149 margin-top: -10px;
150 line-height: 1;
151 font-family: serif;
152 }
153
154
155 .icon-prev {
156 &:before {
157 content: '\2039';// SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039)
158 }
159 }
160 .icon-next {
161 &:before {
162 content: '\203a';// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A)
163 }
164 }
165 }
166
167 // Optional indicator pips
168 //
169 // Add an unordered list with the following class and add a list item for each
170 // slide your carousel holds.
171
172 .carousel-indicators {
173 position: absolute;
174 bottom: 10px;
175 left: 50%;
176 z-index: 15;
177 width: 60%;
178 margin-left: -30%;
179 padding-left: 0;
180 list-style: none;
181 text-align: center;
182
183 li {
184 display: inline-block;
185 width: 10px;
186 height: 10px;
187 margin: 1px;
188 text-indent: -999px;
189 border: 1px solid @carousel-indicator-border-color;
190 border-radius: 10px;
191 cursor: pointer;
192
193 // IE8-9 hack for event handling
194 //
195 // Internet Explorer 8-9 does not support clicks on elements without a set
196 // `background-color`. We cannot use `filter` since that's not viewed as a
197 // background color by the browser. Thus, a hack is needed.
198 // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Internet_Explorer
199 //
200 // For IE8, we set solid black as it doesn't support `rgba()`. For IE9, we
201 // set alpha transparency for the best results possible.
202 background-color: #000 \9; // IE8
203 background-color: rgba(0,0,0,0); // IE9
204 }
205 .active {
206 margin: 0;
207 width: 12px;
208 height: 12px;
209 background-color: @carousel-indicator-active-bg;
210 }
211 }
212
213 // Optional captions
214 // -----------------------------
215 // Hidden by default for smaller viewports
216 .carousel-caption {
217 position: absolute;
218 left: 15%;
219 right: 15%;
220 bottom: 20px;
221 z-index: 10;
222 padding-top: 20px;
223 padding-bottom: 20px;
224 color: @carousel-caption-color;
225 text-align: center;
226 text-shadow: @carousel-text-shadow;
227 & .btn {
228 text-shadow: none; // No shadow for button elements in carousel-caption
229 }
230 }
231
232
233 // Scale up controls for tablets and up
234 @media screen and (min-width: @screen-sm-min) {
235
236 // Scale up the controls a smidge
237 .carousel-control {
238 .glyphicon-chevron-left,
239 .glyphicon-chevron-right,
240 .icon-prev,
241 .icon-next {
242 width: 30px;
243 height: 30px;
244 margin-top: -15px;
245 font-size: 30px;
246 }
247 .glyphicon-chevron-left,
248 .icon-prev {
249 margin-left: -15px;
250 }
251 .glyphicon-chevron-right,
252 .icon-next {
253 margin-right: -15px;
254 }
255 }
256
257 // Show and left align the captions
258 .carousel-caption {
259 left: 20%;
260 right: 20%;
261 padding-bottom: 30px;
262 }
263
264 // Move up the indicators
265 .carousel-indicators {
266 bottom: 20px;
267 }
268 }
+0
-34
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/close.less less more
0 //
1 // Close icons
2 // --------------------------------------------------
3
4
5 .close {
6 float: right;
7 font-size: (@font-size-base * 1.5);
8 font-weight: @close-font-weight;
9 line-height: 1;
10 color: @close-color;
11 text-shadow: @close-text-shadow;
12 .opacity(.2);
13
14 &:hover,
15 &:focus {
16 color: @close-color;
17 text-decoration: none;
18 cursor: pointer;
19 .opacity(.5);
20 }
21
22 // Additional properties for button version
23 // iOS requires the button element instead of an anchor tag.
24 // If you want the anchor version, it requires `href="#"`.
25 // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile
26 button& {
27 padding: 0;
28 cursor: pointer;
29 background: transparent;
30 border: 0;
31 -webkit-appearance: none;
32 }
33 }
+0
-69
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/code.less less more
0 //
1 // Code (inline and block)
2 // --------------------------------------------------
3
4
5 // Inline and block code styles
6 code,
7 kbd,
8 pre,
9 samp {
10 font-family: @font-family-monospace;
11 }
12
13 // Inline code
14 code {
15 padding: 2px 4px;
16 font-size: 90%;
17 color: @code-color;
18 background-color: @code-bg;
19 border-radius: @border-radius-base;
20 }
21
22 // User input typically entered via keyboard
23 kbd {
24 padding: 2px 4px;
25 font-size: 90%;
26 color: @kbd-color;
27 background-color: @kbd-bg;
28 border-radius: @border-radius-small;
29 box-shadow: inset 0 -1px 0 rgba(0,0,0,.25);
30
31 kbd {
32 padding: 0;
33 font-size: 100%;
34 font-weight: bold;
35 box-shadow: none;
36 }
37 }
38
39 // Blocks of code
40 pre {
41 display: block;
42 padding: ((@line-height-computed - 1) / 2);
43 margin: 0 0 (@line-height-computed / 2);
44 font-size: (@font-size-base - 1); // 14px to 13px
45 line-height: @line-height-base;
46 word-break: break-all;
47 word-wrap: break-word;
48 color: @pre-color;
49 background-color: @pre-bg;
50 border: 1px solid @pre-border-color;
51 border-radius: @border-radius-base;
52
53 // Account for some code outputs that place code tags in pre tags
54 code {
55 padding: 0;
56 font-size: inherit;
57 color: inherit;
58 white-space: pre-wrap;
59 background-color: transparent;
60 border-radius: 0;
61 }
62 }
63
64 // Enable scrollable blocks of code
65 .pre-scrollable {
66 max-height: @pre-scrollable-max-height;
67 overflow-y: scroll;
68 }
+0
-33
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/component-animations.less less more
0 //
1 // Component animations
2 // --------------------------------------------------
3
4 // Heads up!
5 //
6 // We don't use the `.opacity()` mixin here since it causes a bug with text
7 // fields in IE7-8. Source: https://github.com/twbs/bootstrap/pull/3552.
8
9 .fade {
10 opacity: 0;
11 .transition(opacity .15s linear);
12 &.in {
13 opacity: 1;
14 }
15 }
16
17 .collapse {
18 display: none;
19
20 &.in { display: block; }
21 tr&.in { display: table-row; }
22 tbody&.in { display: table-row-group; }
23 }
24
25 .collapsing {
26 position: relative;
27 height: 0;
28 overflow: hidden;
29 .transition-property(~"height, visibility");
30 .transition-duration(.35s);
31 .transition-timing-function(ease);
32 }
+0
-214
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/dropdowns.less less more
0 //
1 // Dropdown menus
2 // --------------------------------------------------
3
4
5 // Dropdown arrow/caret
6 .caret {
7 display: inline-block;
8 width: 0;
9 height: 0;
10 margin-left: 2px;
11 vertical-align: middle;
12 border-top: @caret-width-base dashed;
13 border-right: @caret-width-base solid transparent;
14 border-left: @caret-width-base solid transparent;
15 }
16
17 // The dropdown wrapper (div)
18 .dropup,
19 .dropdown {
20 position: relative;
21 }
22
23 // Prevent the focus on the dropdown toggle when closing dropdowns
24 .dropdown-toggle:focus {
25 outline: 0;
26 }
27
28 // The dropdown menu (ul)
29 .dropdown-menu {
30 position: absolute;
31 top: 100%;
32 left: 0;
33 z-index: @zindex-dropdown;
34 display: none; // none by default, but block on "open" of the menu
35 float: left;
36 min-width: 160px;
37 padding: 5px 0;
38 margin: 2px 0 0; // override default ul
39 list-style: none;
40 font-size: @font-size-base;
41 text-align: left; // Ensures proper alignment if parent has it changed (e.g., modal footer)
42 background-color: @dropdown-bg;
43 border: 1px solid @dropdown-fallback-border; // IE8 fallback
44 border: 1px solid @dropdown-border;
45 border-radius: @border-radius-base;
46 .box-shadow(0 6px 12px rgba(0,0,0,.175));
47 background-clip: padding-box;
48
49 // Aligns the dropdown menu to right
50 //
51 // Deprecated as of 3.1.0 in favor of `.dropdown-menu-[dir]`
52 &.pull-right {
53 right: 0;
54 left: auto;
55 }
56
57 // Dividers (basically an hr) within the dropdown
58 .divider {
59 .nav-divider(@dropdown-divider-bg);
60 }
61
62 // Links within the dropdown menu
63 > li > a {
64 display: block;
65 padding: 3px 20px;
66 clear: both;
67 font-weight: normal;
68 line-height: @line-height-base;
69 color: @dropdown-link-color;
70 white-space: nowrap; // prevent links from randomly breaking onto new lines
71 }
72 }
73
74 // Hover/Focus state
75 .dropdown-menu > li > a {
76 &:hover,
77 &:focus {
78 text-decoration: none;
79 color: @dropdown-link-hover-color;
80 background-color: @dropdown-link-hover-bg;
81 }
82 }
83
84 // Active state
85 .dropdown-menu > .active > a {
86 &,
87 &:hover,
88 &:focus {
89 color: @dropdown-link-active-color;
90 text-decoration: none;
91 outline: 0;
92 background-color: @dropdown-link-active-bg;
93 }
94 }
95
96 // Disabled state
97 //
98 // Gray out text and ensure the hover/focus state remains gray
99
100 .dropdown-menu > .disabled > a {
101 &,
102 &:hover,
103 &:focus {
104 color: @dropdown-link-disabled-color;
105 }
106
107 // Nuke hover/focus effects
108 &:hover,
109 &:focus {
110 text-decoration: none;
111 background-color: transparent;
112 background-image: none; // Remove CSS gradient
113 .reset-filter();
114 cursor: @cursor-disabled;
115 }
116 }
117
118 // Open state for the dropdown
119 .open {
120 // Show the menu
121 > .dropdown-menu {
122 display: block;
123 }
124
125 // Remove the outline when :focus is triggered
126 > a {
127 outline: 0;
128 }
129 }
130
131 // Menu positioning
132 //
133 // Add extra class to `.dropdown-menu` to flip the alignment of the dropdown
134 // menu with the parent.
135 .dropdown-menu-right {
136 left: auto; // Reset the default from `.dropdown-menu`
137 right: 0;
138 }
139 // With v3, we enabled auto-flipping if you have a dropdown within a right
140 // aligned nav component. To enable the undoing of that, we provide an override
141 // to restore the default dropdown menu alignment.
142 //
143 // This is only for left-aligning a dropdown menu within a `.navbar-right` or
144 // `.pull-right` nav component.
145 .dropdown-menu-left {
146 left: 0;
147 right: auto;
148 }
149
150 // Dropdown section headers
151 .dropdown-header {
152 display: block;
153 padding: 3px 20px;
154 font-size: @font-size-small;
155 line-height: @line-height-base;
156 color: @dropdown-header-color;
157 white-space: nowrap; // as with > li > a
158 }
159
160 // Backdrop to catch body clicks on mobile, etc.
161 .dropdown-backdrop {
162 position: fixed;
163 left: 0;
164 right: 0;
165 bottom: 0;
166 top: 0;
167 z-index: (@zindex-dropdown - 10);
168 }
169
170 // Right aligned dropdowns
171 .pull-right > .dropdown-menu {
172 right: 0;
173 left: auto;
174 }
175
176 // Allow for dropdowns to go bottom up (aka, dropup-menu)
177 //
178 // Just add .dropup after the standard .dropdown class and you're set, bro.
179 // TODO: abstract this so that the navbar fixed styles are not placed here?
180
181 .dropup,
182 .navbar-fixed-bottom .dropdown {
183 // Reverse the caret
184 .caret {
185 border-top: 0;
186 border-bottom: @caret-width-base solid;
187 content: "";
188 }
189 // Different positioning for bottom up menu
190 .dropdown-menu {
191 top: auto;
192 bottom: 100%;
193 margin-bottom: 2px;
194 }
195 }
196
197
198 // Component alignment
199 //
200 // Reiterate per navbar.less and the modified component alignment there.
201
202 @media (min-width: @grid-float-breakpoint) {
203 .navbar-right {
204 .dropdown-menu {
205 .dropdown-menu-right();
206 }
207 // Necessary for overrides of the default right aligned menu.
208 // Will remove come v4 in all likelihood.
209 .dropdown-menu-left {
210 .dropdown-menu-left();
211 }
212 }
213 }
+0
-574
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/forms.less less more
0 //
1 // Forms
2 // --------------------------------------------------
3
4
5 // Normalize non-controls
6 //
7 // Restyle and baseline non-control form elements.
8
9 fieldset {
10 padding: 0;
11 margin: 0;
12 border: 0;
13 // Chrome and Firefox set a `min-width: min-content;` on fieldsets,
14 // so we reset that to ensure it behaves more like a standard block element.
15 // See https://github.com/twbs/bootstrap/issues/12359.
16 min-width: 0;
17 }
18
19 legend {
20 display: block;
21 width: 100%;
22 padding: 0;
23 margin-bottom: @line-height-computed;
24 font-size: (@font-size-base * 1.5);
25 line-height: inherit;
26 color: @legend-color;
27 border: 0;
28 border-bottom: 1px solid @legend-border-color;
29 }
30
31 label {
32 display: inline-block;
33 max-width: 100%; // Force IE8 to wrap long content (see https://github.com/twbs/bootstrap/issues/13141)
34 margin-bottom: 5px;
35 font-weight: bold;
36 }
37
38
39 // Normalize form controls
40 //
41 // While most of our form styles require extra classes, some basic normalization
42 // is required to ensure optimum display with or without those classes to better
43 // address browser inconsistencies.
44
45 // Override content-box in Normalize (* isn't specific enough)
46 input[type="search"] {
47 .box-sizing(border-box);
48 }
49
50 // Position radios and checkboxes better
51 input[type="radio"],
52 input[type="checkbox"] {
53 margin: 4px 0 0;
54 margin-top: 1px \9; // IE8-9
55 line-height: normal;
56 }
57
58 // Set the height of file controls to match text inputs
59 input[type="file"] {
60 display: block;
61 }
62
63 // Make range inputs behave like textual form controls
64 input[type="range"] {
65 display: block;
66 width: 100%;
67 }
68
69 // Make multiple select elements height not fixed
70 select[multiple],
71 select[size] {
72 height: auto;
73 }
74
75 // Focus for file, radio, and checkbox
76 input[type="file"]:focus,
77 input[type="radio"]:focus,
78 input[type="checkbox"]:focus {
79 .tab-focus();
80 }
81
82 // Adjust output element
83 output {
84 display: block;
85 padding-top: (@padding-base-vertical + 1);
86 font-size: @font-size-base;
87 line-height: @line-height-base;
88 color: @input-color;
89 }
90
91
92 // Common form controls
93 //
94 // Shared size and type resets for form controls. Apply `.form-control` to any
95 // of the following form controls:
96 //
97 // select
98 // textarea
99 // input[type="text"]
100 // input[type="password"]
101 // input[type="datetime"]
102 // input[type="datetime-local"]
103 // input[type="date"]
104 // input[type="month"]
105 // input[type="time"]
106 // input[type="week"]
107 // input[type="number"]
108 // input[type="email"]
109 // input[type="url"]
110 // input[type="search"]
111 // input[type="tel"]
112 // input[type="color"]
113
114 .form-control {
115 display: block;
116 width: 100%;
117 height: @input-height-base; // Make inputs at least the height of their button counterpart (base line-height + padding + border)
118 padding: @padding-base-vertical @padding-base-horizontal;
119 font-size: @font-size-base;
120 line-height: @line-height-base;
121 color: @input-color;
122 background-color: @input-bg;
123 background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214
124 border: 1px solid @input-border;
125 border-radius: @input-border-radius; // Note: This has no effect on <select>s in some browsers, due to the limited stylability of <select>s in CSS.
126 .box-shadow(inset 0 1px 1px rgba(0,0,0,.075));
127 .transition(~"border-color ease-in-out .15s, box-shadow ease-in-out .15s");
128
129 // Customize the `:focus` state to imitate native WebKit styles.
130 .form-control-focus();
131
132 // Placeholder
133 .placeholder();
134
135 // Disabled and read-only inputs
136 //
137 // HTML5 says that controls under a fieldset > legend:first-child won't be
138 // disabled if the fieldset is disabled. Due to implementation difficulty, we
139 // don't honor that edge case; we style them as disabled anyway.
140 &[disabled],
141 &[readonly],
142 fieldset[disabled] & {
143 background-color: @input-bg-disabled;
144 opacity: 1; // iOS fix for unreadable disabled content; see https://github.com/twbs/bootstrap/issues/11655
145 }
146
147 &[disabled],
148 fieldset[disabled] & {
149 cursor: @cursor-disabled;
150 }
151
152 // Reset height for `textarea`s
153 textarea& {
154 height: auto;
155 }
156 }
157
158
159 // Search inputs in iOS
160 //
161 // This overrides the extra rounded corners on search inputs in iOS so that our
162 // `.form-control` class can properly style them. Note that this cannot simply
163 // be added to `.form-control` as it's not specific enough. For details, see
164 // https://github.com/twbs/bootstrap/issues/11586.
165
166 input[type="search"] {
167 -webkit-appearance: none;
168 }
169
170
171 // Special styles for iOS temporal inputs
172 //
173 // In Mobile Safari, setting `display: block` on temporal inputs causes the
174 // text within the input to become vertically misaligned. As a workaround, we
175 // set a pixel line-height that matches the given height of the input, but only
176 // for Safari. See https://bugs.webkit.org/show_bug.cgi?id=139848
177
178 @media screen and (-webkit-min-device-pixel-ratio: 0) {
179 input[type="date"],
180 input[type="time"],
181 input[type="datetime-local"],
182 input[type="month"] {
183 line-height: @input-height-base;
184
185 &.input-sm,
186 .input-group-sm & {
187 line-height: @input-height-small;
188 }
189
190 &.input-lg,
191 .input-group-lg & {
192 line-height: @input-height-large;
193 }
194 }
195 }
196
197
198 // Form groups
199 //
200 // Designed to help with the organization and spacing of vertical forms. For
201 // horizontal forms, use the predefined grid classes.
202
203 .form-group {
204 margin-bottom: @form-group-margin-bottom;
205 }
206
207
208 // Checkboxes and radios
209 //
210 // Indent the labels to position radios/checkboxes as hanging controls.
211
212 .radio,
213 .checkbox {
214 position: relative;
215 display: block;
216 margin-top: 10px;
217 margin-bottom: 10px;
218
219 label {
220 min-height: @line-height-computed; // Ensure the input doesn't jump when there is no text
221 padding-left: 20px;
222 margin-bottom: 0;
223 font-weight: normal;
224 cursor: pointer;
225 }
226 }
227 .radio input[type="radio"],
228 .radio-inline input[type="radio"],
229 .checkbox input[type="checkbox"],
230 .checkbox-inline input[type="checkbox"] {
231 position: absolute;
232 margin-left: -20px;
233 margin-top: 4px \9;
234 }
235
236 .radio + .radio,
237 .checkbox + .checkbox {
238 margin-top: -5px; // Move up sibling radios or checkboxes for tighter spacing
239 }
240
241 // Radios and checkboxes on same line
242 .radio-inline,
243 .checkbox-inline {
244 position: relative;
245 display: inline-block;
246 padding-left: 20px;
247 margin-bottom: 0;
248 vertical-align: middle;
249 font-weight: normal;
250 cursor: pointer;
251 }
252 .radio-inline + .radio-inline,
253 .checkbox-inline + .checkbox-inline {
254 margin-top: 0;
255 margin-left: 10px; // space out consecutive inline controls
256 }
257
258 // Apply same disabled cursor tweak as for inputs
259 // Some special care is needed because <label>s don't inherit their parent's `cursor`.
260 //
261 // Note: Neither radios nor checkboxes can be readonly.
262 input[type="radio"],
263 input[type="checkbox"] {
264 &[disabled],
265 &.disabled,
266 fieldset[disabled] & {
267 cursor: @cursor-disabled;
268 }
269 }
270 // These classes are used directly on <label>s
271 .radio-inline,
272 .checkbox-inline {
273 &.disabled,
274 fieldset[disabled] & {
275 cursor: @cursor-disabled;
276 }
277 }
278 // These classes are used on elements with <label> descendants
279 .radio,
280 .checkbox {
281 &.disabled,
282 fieldset[disabled] & {
283 label {
284 cursor: @cursor-disabled;
285 }
286 }
287 }
288
289
290 // Static form control text
291 //
292 // Apply class to a `p` element to make any string of text align with labels in
293 // a horizontal form layout.
294
295 .form-control-static {
296 // Size it appropriately next to real form controls
297 padding-top: (@padding-base-vertical + 1);
298 padding-bottom: (@padding-base-vertical + 1);
299 // Remove default margin from `p`
300 margin-bottom: 0;
301 min-height: (@line-height-computed + @font-size-base);
302
303 &.input-lg,
304 &.input-sm {
305 padding-left: 0;
306 padding-right: 0;
307 }
308 }
309
310
311 // Form control sizing
312 //
313 // Build on `.form-control` with modifier classes to decrease or increase the
314 // height and font-size of form controls.
315 //
316 // The `.form-group-* form-control` variations are sadly duplicated to avoid the
317 // issue documented in https://github.com/twbs/bootstrap/issues/15074.
318
319 .input-sm {
320 .input-size(@input-height-small; @padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @input-border-radius-small);
321 }
322 .form-group-sm {
323 .form-control {
324 .input-size(@input-height-small; @padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @input-border-radius-small);
325 }
326 .form-control-static {
327 height: @input-height-small;
328 padding: @padding-small-vertical @padding-small-horizontal;
329 font-size: @font-size-small;
330 line-height: @line-height-small;
331 min-height: (@line-height-computed + @font-size-small);
332 }
333 }
334
335 .input-lg {
336 .input-size(@input-height-large; @padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @input-border-radius-large);
337 }
338 .form-group-lg {
339 .form-control {
340 .input-size(@input-height-large; @padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @input-border-radius-large);
341 }
342 .form-control-static {
343 height: @input-height-large;
344 padding: @padding-large-vertical @padding-large-horizontal;
345 font-size: @font-size-large;
346 line-height: @line-height-large;
347 min-height: (@line-height-computed + @font-size-large);
348 }
349 }
350
351
352 // Form control feedback states
353 //
354 // Apply contextual and semantic states to individual form controls.
355
356 .has-feedback {
357 // Enable absolute positioning
358 position: relative;
359
360 // Ensure icons don't overlap text
361 .form-control {
362 padding-right: (@input-height-base * 1.25);
363 }
364 }
365 // Feedback icon (requires .glyphicon classes)
366 .form-control-feedback {
367 position: absolute;
368 top: 0;
369 right: 0;
370 z-index: 2; // Ensure icon is above input groups
371 display: block;
372 width: @input-height-base;
373 height: @input-height-base;
374 line-height: @input-height-base;
375 text-align: center;
376 pointer-events: none;
377 }
378 .input-lg + .form-control-feedback {
379 width: @input-height-large;
380 height: @input-height-large;
381 line-height: @input-height-large;
382 }
383 .input-sm + .form-control-feedback {
384 width: @input-height-small;
385 height: @input-height-small;
386 line-height: @input-height-small;
387 }
388
389 // Feedback states
390 .has-success {
391 .form-control-validation(@state-success-text; @state-success-text; @state-success-bg);
392 }
393 .has-warning {
394 .form-control-validation(@state-warning-text; @state-warning-text; @state-warning-bg);
395 }
396 .has-error {
397 .form-control-validation(@state-danger-text; @state-danger-text; @state-danger-bg);
398 }
399
400 // Reposition feedback icon if input has visible label above
401 .has-feedback label {
402
403 & ~ .form-control-feedback {
404 top: (@line-height-computed + 5); // Height of the `label` and its margin
405 }
406 &.sr-only ~ .form-control-feedback {
407 top: 0;
408 }
409 }
410
411
412 // Help text
413 //
414 // Apply to any element you wish to create light text for placement immediately
415 // below a form control. Use for general help, formatting, or instructional text.
416
417 .help-block {
418 display: block; // account for any element using help-block
419 margin-top: 5px;
420 margin-bottom: 10px;
421 color: lighten(@text-color, 25%); // lighten the text some for contrast
422 }
423
424
425 // Inline forms
426 //
427 // Make forms appear inline(-block) by adding the `.form-inline` class. Inline
428 // forms begin stacked on extra small (mobile) devices and then go inline when
429 // viewports reach <768px.
430 //
431 // Requires wrapping inputs and labels with `.form-group` for proper display of
432 // default HTML form controls and our custom form controls (e.g., input groups).
433 //
434 // Heads up! This is mixin-ed into `.navbar-form` in navbars.less.
435
436 .form-inline {
437
438 // Kick in the inline
439 @media (min-width: @screen-sm-min) {
440 // Inline-block all the things for "inline"
441 .form-group {
442 display: inline-block;
443 margin-bottom: 0;
444 vertical-align: middle;
445 }
446
447 // In navbar-form, allow folks to *not* use `.form-group`
448 .form-control {
449 display: inline-block;
450 width: auto; // Prevent labels from stacking above inputs in `.form-group`
451 vertical-align: middle;
452 }
453
454 // Make static controls behave like regular ones
455 .form-control-static {
456 display: inline-block;
457 }
458
459 .input-group {
460 display: inline-table;
461 vertical-align: middle;
462
463 .input-group-addon,
464 .input-group-btn,
465 .form-control {
466 width: auto;
467 }
468 }
469
470 // Input groups need that 100% width though
471 .input-group > .form-control {
472 width: 100%;
473 }
474
475 .control-label {
476 margin-bottom: 0;
477 vertical-align: middle;
478 }
479
480 // Remove default margin on radios/checkboxes that were used for stacking, and
481 // then undo the floating of radios and checkboxes to match.
482 .radio,
483 .checkbox {
484 display: inline-block;
485 margin-top: 0;
486 margin-bottom: 0;
487 vertical-align: middle;
488
489 label {
490 padding-left: 0;
491 }
492 }
493 .radio input[type="radio"],
494 .checkbox input[type="checkbox"] {
495 position: relative;
496 margin-left: 0;
497 }
498
499 // Re-override the feedback icon.
500 .has-feedback .form-control-feedback {
501 top: 0;
502 }
503 }
504 }
505
506
507 // Horizontal forms
508 //
509 // Horizontal forms are built on grid classes and allow you to create forms with
510 // labels on the left and inputs on the right.
511
512 .form-horizontal {
513
514 // Consistent vertical alignment of radios and checkboxes
515 //
516 // Labels also get some reset styles, but that is scoped to a media query below.
517 .radio,
518 .checkbox,
519 .radio-inline,
520 .checkbox-inline {
521 margin-top: 0;
522 margin-bottom: 0;
523 padding-top: (@padding-base-vertical + 1); // Default padding plus a border
524 }
525 // Account for padding we're adding to ensure the alignment and of help text
526 // and other content below items
527 .radio,
528 .checkbox {
529 min-height: (@line-height-computed + (@padding-base-vertical + 1));
530 }
531
532 // Make form groups behave like rows
533 .form-group {
534 .make-row();
535 }
536
537 // Reset spacing and right align labels, but scope to media queries so that
538 // labels on narrow viewports stack the same as a default form example.
539 @media (min-width: @screen-sm-min) {
540 .control-label {
541 text-align: right;
542 margin-bottom: 0;
543 padding-top: (@padding-base-vertical + 1); // Default padding plus a border
544 }
545 }
546
547 // Validation states
548 //
549 // Reposition the icon because it's now within a grid column and columns have
550 // `position: relative;` on them. Also accounts for the grid gutter padding.
551 .has-feedback .form-control-feedback {
552 right: (@grid-gutter-width / 2);
553 }
554
555 // Form group sizes
556 //
557 // Quick utility class for applying `.input-lg` and `.input-sm` styles to the
558 // inputs and labels within a `.form-group`.
559 .form-group-lg {
560 @media (min-width: @screen-sm-min) {
561 .control-label {
562 padding-top: ((@padding-large-vertical * @line-height-large) + 1);
563 }
564 }
565 }
566 .form-group-sm {
567 @media (min-width: @screen-sm-min) {
568 .control-label {
569 padding-top: (@padding-small-vertical + 1);
570 }
571 }
572 }
573 }
+0
-305
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/glyphicons.less less more
0 //
1 // Glyphicons for Bootstrap
2 //
3 // Since icons are fonts, they can be placed anywhere text is placed and are
4 // thus automatically sized to match the surrounding child. To use, create an
5 // inline element with the appropriate classes, like so:
6 //
7 // <a href="#"><span class="glyphicon glyphicon-star"></span> Star</a>
8
9 // Import the fonts
10 @font-face {
11 font-family: 'Glyphicons Halflings';
12 src: url('@{icon-font-path}@{icon-font-name}.eot');
13 src: url('@{icon-font-path}@{icon-font-name}.eot?#iefix') format('embedded-opentype'),
14 url('@{icon-font-path}@{icon-font-name}.woff2') format('woff2'),
15 url('@{icon-font-path}@{icon-font-name}.woff') format('woff'),
16 url('@{icon-font-path}@{icon-font-name}.ttf') format('truetype'),
17 url('@{icon-font-path}@{icon-font-name}.svg#@{icon-font-svg-id}') format('svg');
18 }
19
20 // Catchall baseclass
21 .glyphicon {
22 position: relative;
23 top: 1px;
24 display: inline-block;
25 font-family: 'Glyphicons Halflings';
26 font-style: normal;
27 font-weight: normal;
28 line-height: 1;
29 -webkit-font-smoothing: antialiased;
30 -moz-osx-font-smoothing: grayscale;
31 }
32
33 // Individual icons
34 .glyphicon-asterisk { &:before { content: "\2a"; } }
35 .glyphicon-plus { &:before { content: "\2b"; } }
36 .glyphicon-euro,
37 .glyphicon-eur { &:before { content: "\20ac"; } }
38 .glyphicon-minus { &:before { content: "\2212"; } }
39 .glyphicon-cloud { &:before { content: "\2601"; } }
40 .glyphicon-envelope { &:before { content: "\2709"; } }
41 .glyphicon-pencil { &:before { content: "\270f"; } }
42 .glyphicon-glass { &:before { content: "\e001"; } }
43 .glyphicon-music { &:before { content: "\e002"; } }
44 .glyphicon-search { &:before { content: "\e003"; } }
45 .glyphicon-heart { &:before { content: "\e005"; } }
46 .glyphicon-star { &:before { content: "\e006"; } }
47 .glyphicon-star-empty { &:before { content: "\e007"; } }
48 .glyphicon-user { &:before { content: "\e008"; } }
49 .glyphicon-film { &:before { content: "\e009"; } }
50 .glyphicon-th-large { &:before { content: "\e010"; } }
51 .glyphicon-th { &:before { content: "\e011"; } }
52 .glyphicon-th-list { &:before { content: "\e012"; } }
53 .glyphicon-ok { &:before { content: "\e013"; } }
54 .glyphicon-remove { &:before { content: "\e014"; } }
55 .glyphicon-zoom-in { &:before { content: "\e015"; } }
56 .glyphicon-zoom-out { &:before { content: "\e016"; } }
57 .glyphicon-off { &:before { content: "\e017"; } }
58 .glyphicon-signal { &:before { content: "\e018"; } }
59 .glyphicon-cog { &:before { content: "\e019"; } }
60 .glyphicon-trash { &:before { content: "\e020"; } }
61 .glyphicon-home { &:before { content: "\e021"; } }
62 .glyphicon-file { &:before { content: "\e022"; } }
63 .glyphicon-time { &:before { content: "\e023"; } }
64 .glyphicon-road { &:before { content: "\e024"; } }
65 .glyphicon-download-alt { &:before { content: "\e025"; } }
66 .glyphicon-download { &:before { content: "\e026"; } }
67 .glyphicon-upload { &:before { content: "\e027"; } }
68 .glyphicon-inbox { &:before { content: "\e028"; } }
69 .glyphicon-play-circle { &:before { content: "\e029"; } }
70 .glyphicon-repeat { &:before { content: "\e030"; } }
71 .glyphicon-refresh { &:before { content: "\e031"; } }
72 .glyphicon-list-alt { &:before { content: "\e032"; } }
73 .glyphicon-lock { &:before { content: "\e033"; } }
74 .glyphicon-flag { &:before { content: "\e034"; } }
75 .glyphicon-headphones { &:before { content: "\e035"; } }
76 .glyphicon-volume-off { &:before { content: "\e036"; } }
77 .glyphicon-volume-down { &:before { content: "\e037"; } }
78 .glyphicon-volume-up { &:before { content: "\e038"; } }
79 .glyphicon-qrcode { &:before { content: "\e039"; } }
80 .glyphicon-barcode { &:before { content: "\e040"; } }
81 .glyphicon-tag { &:before { content: "\e041"; } }
82 .glyphicon-tags { &:before { content: "\e042"; } }
83 .glyphicon-book { &:before { content: "\e043"; } }
84 .glyphicon-bookmark { &:before { content: "\e044"; } }
85 .glyphicon-print { &:before { content: "\e045"; } }
86 .glyphicon-camera { &:before { content: "\e046"; } }
87 .glyphicon-font { &:before { content: "\e047"; } }
88 .glyphicon-bold { &:before { content: "\e048"; } }
89 .glyphicon-italic { &:before { content: "\e049"; } }
90 .glyphicon-text-height { &:before { content: "\e050"; } }
91 .glyphicon-text-width { &:before { content: "\e051"; } }
92 .glyphicon-align-left { &:before { content: "\e052"; } }
93 .glyphicon-align-center { &:before { content: "\e053"; } }
94 .glyphicon-align-right { &:before { content: "\e054"; } }
95 .glyphicon-align-justify { &:before { content: "\e055"; } }
96 .glyphicon-list { &:before { content: "\e056"; } }
97 .glyphicon-indent-left { &:before { content: "\e057"; } }
98 .glyphicon-indent-right { &:before { content: "\e058"; } }
99 .glyphicon-facetime-video { &:before { content: "\e059"; } }
100 .glyphicon-picture { &:before { content: "\e060"; } }
101 .glyphicon-map-marker { &:before { content: "\e062"; } }
102 .glyphicon-adjust { &:before { content: "\e063"; } }
103 .glyphicon-tint { &:before { content: "\e064"; } }
104 .glyphicon-edit { &:before { content: "\e065"; } }
105 .glyphicon-share { &:before { content: "\e066"; } }
106 .glyphicon-check { &:before { content: "\e067"; } }
107 .glyphicon-move { &:before { content: "\e068"; } }
108 .glyphicon-step-backward { &:before { content: "\e069"; } }
109 .glyphicon-fast-backward { &:before { content: "\e070"; } }
110 .glyphicon-backward { &:before { content: "\e071"; } }
111 .glyphicon-play { &:before { content: "\e072"; } }
112 .glyphicon-pause { &:before { content: "\e073"; } }
113 .glyphicon-stop { &:before { content: "\e074"; } }
114 .glyphicon-forward { &:before { content: "\e075"; } }
115 .glyphicon-fast-forward { &:before { content: "\e076"; } }
116 .glyphicon-step-forward { &:before { content: "\e077"; } }
117 .glyphicon-eject { &:before { content: "\e078"; } }
118 .glyphicon-chevron-left { &:before { content: "\e079"; } }
119 .glyphicon-chevron-right { &:before { content: "\e080"; } }
120 .glyphicon-plus-sign { &:before { content: "\e081"; } }
121 .glyphicon-minus-sign { &:before { content: "\e082"; } }
122 .glyphicon-remove-sign { &:before { content: "\e083"; } }
123 .glyphicon-ok-sign { &:before { content: "\e084"; } }
124 .glyphicon-question-sign { &:before { content: "\e085"; } }
125 .glyphicon-info-sign { &:before { content: "\e086"; } }
126 .glyphicon-screenshot { &:before { content: "\e087"; } }
127 .glyphicon-remove-circle { &:before { content: "\e088"; } }
128 .glyphicon-ok-circle { &:before { content: "\e089"; } }
129 .glyphicon-ban-circle { &:before { content: "\e090"; } }
130 .glyphicon-arrow-left { &:before { content: "\e091"; } }
131 .glyphicon-arrow-right { &:before { content: "\e092"; } }
132 .glyphicon-arrow-up { &:before { content: "\e093"; } }
133 .glyphicon-arrow-down { &:before { content: "\e094"; } }
134 .glyphicon-share-alt { &:before { content: "\e095"; } }
135 .glyphicon-resize-full { &:before { content: "\e096"; } }
136 .glyphicon-resize-small { &:before { content: "\e097"; } }
137 .glyphicon-exclamation-sign { &:before { content: "\e101"; } }
138 .glyphicon-gift { &:before { content: "\e102"; } }
139 .glyphicon-leaf { &:before { content: "\e103"; } }
140 .glyphicon-fire { &:before { content: "\e104"; } }
141 .glyphicon-eye-open { &:before { content: "\e105"; } }
142 .glyphicon-eye-close { &:before { content: "\e106"; } }
143 .glyphicon-warning-sign { &:before { content: "\e107"; } }
144 .glyphicon-plane { &:before { content: "\e108"; } }
145 .glyphicon-calendar { &:before { content: "\e109"; } }
146 .glyphicon-random { &:before { content: "\e110"; } }
147 .glyphicon-comment { &:before { content: "\e111"; } }
148 .glyphicon-magnet { &:before { content: "\e112"; } }
149 .glyphicon-chevron-up { &:before { content: "\e113"; } }
150 .glyphicon-chevron-down { &:before { content: "\e114"; } }
151 .glyphicon-retweet { &:before { content: "\e115"; } }
152 .glyphicon-shopping-cart { &:before { content: "\e116"; } }
153 .glyphicon-folder-close { &:before { content: "\e117"; } }
154 .glyphicon-folder-open { &:before { content: "\e118"; } }
155 .glyphicon-resize-vertical { &:before { content: "\e119"; } }
156 .glyphicon-resize-horizontal { &:before { content: "\e120"; } }
157 .glyphicon-hdd { &:before { content: "\e121"; } }
158 .glyphicon-bullhorn { &:before { content: "\e122"; } }
159 .glyphicon-bell { &:before { content: "\e123"; } }
160 .glyphicon-certificate { &:before { content: "\e124"; } }
161 .glyphicon-thumbs-up { &:before { content: "\e125"; } }
162 .glyphicon-thumbs-down { &:before { content: "\e126"; } }
163 .glyphicon-hand-right { &:before { content: "\e127"; } }
164 .glyphicon-hand-left { &:before { content: "\e128"; } }
165 .glyphicon-hand-up { &:before { content: "\e129"; } }
166 .glyphicon-hand-down { &:before { content: "\e130"; } }
167 .glyphicon-circle-arrow-right { &:before { content: "\e131"; } }
168 .glyphicon-circle-arrow-left { &:before { content: "\e132"; } }
169 .glyphicon-circle-arrow-up { &:before { content: "\e133"; } }
170 .glyphicon-circle-arrow-down { &:before { content: "\e134"; } }
171 .glyphicon-globe { &:before { content: "\e135"; } }
172 .glyphicon-wrench { &:before { content: "\e136"; } }
173 .glyphicon-tasks { &:before { content: "\e137"; } }
174 .glyphicon-filter { &:before { content: "\e138"; } }
175 .glyphicon-briefcase { &:before { content: "\e139"; } }
176 .glyphicon-fullscreen { &:before { content: "\e140"; } }
177 .glyphicon-dashboard { &:before { content: "\e141"; } }
178 .glyphicon-paperclip { &:before { content: "\e142"; } }
179 .glyphicon-heart-empty { &:before { content: "\e143"; } }
180 .glyphicon-link { &:before { content: "\e144"; } }
181 .glyphicon-phone { &:before { content: "\e145"; } }
182 .glyphicon-pushpin { &:before { content: "\e146"; } }
183 .glyphicon-usd { &:before { content: "\e148"; } }
184 .glyphicon-gbp { &:before { content: "\e149"; } }
185 .glyphicon-sort { &:before { content: "\e150"; } }
186 .glyphicon-sort-by-alphabet { &:before { content: "\e151"; } }
187 .glyphicon-sort-by-alphabet-alt { &:before { content: "\e152"; } }
188 .glyphicon-sort-by-order { &:before { content: "\e153"; } }
189 .glyphicon-sort-by-order-alt { &:before { content: "\e154"; } }
190 .glyphicon-sort-by-attributes { &:before { content: "\e155"; } }
191 .glyphicon-sort-by-attributes-alt { &:before { content: "\e156"; } }
192 .glyphicon-unchecked { &:before { content: "\e157"; } }
193 .glyphicon-expand { &:before { content: "\e158"; } }
194 .glyphicon-collapse-down { &:before { content: "\e159"; } }
195 .glyphicon-collapse-up { &:before { content: "\e160"; } }
196 .glyphicon-log-in { &:before { content: "\e161"; } }
197 .glyphicon-flash { &:before { content: "\e162"; } }
198 .glyphicon-log-out { &:before { content: "\e163"; } }
199 .glyphicon-new-window { &:before { content: "\e164"; } }
200 .glyphicon-record { &:before { content: "\e165"; } }
201 .glyphicon-save { &:before { content: "\e166"; } }
202 .glyphicon-open { &:before { content: "\e167"; } }
203 .glyphicon-saved { &:before { content: "\e168"; } }
204 .glyphicon-import { &:before { content: "\e169"; } }
205 .glyphicon-export { &:before { content: "\e170"; } }
206 .glyphicon-send { &:before { content: "\e171"; } }
207 .glyphicon-floppy-disk { &:before { content: "\e172"; } }
208 .glyphicon-floppy-saved { &:before { content: "\e173"; } }
209 .glyphicon-floppy-remove { &:before { content: "\e174"; } }
210 .glyphicon-floppy-save { &:before { content: "\e175"; } }
211 .glyphicon-floppy-open { &:before { content: "\e176"; } }
212 .glyphicon-credit-card { &:before { content: "\e177"; } }
213 .glyphicon-transfer { &:before { content: "\e178"; } }
214 .glyphicon-cutlery { &:before { content: "\e179"; } }
215 .glyphicon-header { &:before { content: "\e180"; } }
216 .glyphicon-compressed { &:before { content: "\e181"; } }
217 .glyphicon-earphone { &:before { content: "\e182"; } }
218 .glyphicon-phone-alt { &:before { content: "\e183"; } }
219 .glyphicon-tower { &:before { content: "\e184"; } }
220 .glyphicon-stats { &:before { content: "\e185"; } }
221 .glyphicon-sd-video { &:before { content: "\e186"; } }
222 .glyphicon-hd-video { &:before { content: "\e187"; } }
223 .glyphicon-subtitles { &:before { content: "\e188"; } }
224 .glyphicon-sound-stereo { &:before { content: "\e189"; } }
225 .glyphicon-sound-dolby { &:before { content: "\e190"; } }
226 .glyphicon-sound-5-1 { &:before { content: "\e191"; } }
227 .glyphicon-sound-6-1 { &:before { content: "\e192"; } }
228 .glyphicon-sound-7-1 { &:before { content: "\e193"; } }
229 .glyphicon-copyright-mark { &:before { content: "\e194"; } }
230 .glyphicon-registration-mark { &:before { content: "\e195"; } }
231 .glyphicon-cloud-download { &:before { content: "\e197"; } }
232 .glyphicon-cloud-upload { &:before { content: "\e198"; } }
233 .glyphicon-tree-conifer { &:before { content: "\e199"; } }
234 .glyphicon-tree-deciduous { &:before { content: "\e200"; } }
235 .glyphicon-cd { &:before { content: "\e201"; } }
236 .glyphicon-save-file { &:before { content: "\e202"; } }
237 .glyphicon-open-file { &:before { content: "\e203"; } }
238 .glyphicon-level-up { &:before { content: "\e204"; } }
239 .glyphicon-copy { &:before { content: "\e205"; } }
240 .glyphicon-paste { &:before { content: "\e206"; } }
241 // The following 2 Glyphicons are omitted for the time being because
242 // they currently use Unicode codepoints that are outside the
243 // Basic Multilingual Plane (BMP). Older buggy versions of WebKit can't handle
244 // non-BMP codepoints in CSS string escapes, and thus can't display these two icons.
245 // Notably, the bug affects some older versions of the Android Browser.
246 // More info: https://github.com/twbs/bootstrap/issues/10106
247 // .glyphicon-door { &:before { content: "\1f6aa"; } }
248 // .glyphicon-key { &:before { content: "\1f511"; } }
249 .glyphicon-alert { &:before { content: "\e209"; } }
250 .glyphicon-equalizer { &:before { content: "\e210"; } }
251 .glyphicon-king { &:before { content: "\e211"; } }
252 .glyphicon-queen { &:before { content: "\e212"; } }
253 .glyphicon-pawn { &:before { content: "\e213"; } }
254 .glyphicon-bishop { &:before { content: "\e214"; } }
255 .glyphicon-knight { &:before { content: "\e215"; } }
256 .glyphicon-baby-formula { &:before { content: "\e216"; } }
257 .glyphicon-tent { &:before { content: "\26fa"; } }
258 .glyphicon-blackboard { &:before { content: "\e218"; } }
259 .glyphicon-bed { &:before { content: "\e219"; } }
260 .glyphicon-apple { &:before { content: "\f8ff"; } }
261 .glyphicon-erase { &:before { content: "\e221"; } }
262 .glyphicon-hourglass { &:before { content: "\231b"; } }
263 .glyphicon-lamp { &:before { content: "\e223"; } }
264 .glyphicon-duplicate { &:before { content: "\e224"; } }
265 .glyphicon-piggy-bank { &:before { content: "\e225"; } }
266 .glyphicon-scissors { &:before { content: "\e226"; } }
267 .glyphicon-bitcoin { &:before { content: "\e227"; } }
268 .glyphicon-btc { &:before { content: "\e227"; } }
269 .glyphicon-xbt { &:before { content: "\e227"; } }
270 .glyphicon-yen { &:before { content: "\00a5"; } }
271 .glyphicon-jpy { &:before { content: "\00a5"; } }
272 .glyphicon-ruble { &:before { content: "\20bd"; } }
273 .glyphicon-rub { &:before { content: "\20bd"; } }
274 .glyphicon-scale { &:before { content: "\e230"; } }
275 .glyphicon-ice-lolly { &:before { content: "\e231"; } }
276 .glyphicon-ice-lolly-tasted { &:before { content: "\e232"; } }
277 .glyphicon-education { &:before { content: "\e233"; } }
278 .glyphicon-option-horizontal { &:before { content: "\e234"; } }
279 .glyphicon-option-vertical { &:before { content: "\e235"; } }
280 .glyphicon-menu-hamburger { &:before { content: "\e236"; } }
281 .glyphicon-modal-window { &:before { content: "\e237"; } }
282 .glyphicon-oil { &:before { content: "\e238"; } }
283 .glyphicon-grain { &:before { content: "\e239"; } }
284 .glyphicon-sunglasses { &:before { content: "\e240"; } }
285 .glyphicon-text-size { &:before { content: "\e241"; } }
286 .glyphicon-text-color { &:before { content: "\e242"; } }
287 .glyphicon-text-background { &:before { content: "\e243"; } }
288 .glyphicon-object-align-top { &:before { content: "\e244"; } }
289 .glyphicon-object-align-bottom { &:before { content: "\e245"; } }
290 .glyphicon-object-align-horizontal{ &:before { content: "\e246"; } }
291 .glyphicon-object-align-left { &:before { content: "\e247"; } }
292 .glyphicon-object-align-vertical { &:before { content: "\e248"; } }
293 .glyphicon-object-align-right { &:before { content: "\e249"; } }
294 .glyphicon-triangle-right { &:before { content: "\e250"; } }
295 .glyphicon-triangle-left { &:before { content: "\e251"; } }
296 .glyphicon-triangle-bottom { &:before { content: "\e252"; } }
297 .glyphicon-triangle-top { &:before { content: "\e253"; } }
298 .glyphicon-console { &:before { content: "\e254"; } }
299 .glyphicon-superscript { &:before { content: "\e255"; } }
300 .glyphicon-subscript { &:before { content: "\e256"; } }
301 .glyphicon-menu-left { &:before { content: "\e257"; } }
302 .glyphicon-menu-right { &:before { content: "\e258"; } }
303 .glyphicon-menu-down { &:before { content: "\e259"; } }
304 .glyphicon-menu-up { &:before { content: "\e260"; } }
+0
-84
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/grid.less less more
0 //
1 // Grid system
2 // --------------------------------------------------
3
4
5 // Container widths
6 //
7 // Set the container width, and override it for fixed navbars in media queries.
8
9 .tb-container {
10 .container-fixed();
11
12 @media (min-width: @screen-sm-min) {
13 width: @container-sm;
14 }
15 @media (min-width: @screen-md-min) {
16 width: @container-md;
17 }
18 @media (min-width: @screen-lg-min) {
19 width: @container-lg;
20 }
21 }
22
23
24 // Fluid container
25 //
26 // Utilizes the mixin meant for fixed width containers, but without any defined
27 // width for fluid, full width layouts.
28
29 .container-fluid {
30 .container-fixed();
31 }
32
33
34 // Row
35 //
36 // Rows contain and clear the floats of your columns.
37
38 .row {
39 .make-row();
40 }
41
42
43 // Columns
44 //
45 // Common styles for small and large grid columns
46
47 .make-grid-columns();
48
49
50 // Extra small grid
51 //
52 // Columns, offsets, pushes, and pulls for extra small devices like
53 // smartphones.
54
55 .make-grid(xs);
56
57
58 // Small grid
59 //
60 // Columns, offsets, pushes, and pulls for the small device range, from phones
61 // to tablets.
62
63 @media (min-width: @screen-sm-min) {
64 .make-grid(sm);
65 }
66
67
68 // Medium grid
69 //
70 // Columns, offsets, pushes, and pulls for the desktop device range.
71
72 @media (min-width: @screen-md-min) {
73 .make-grid(md);
74 }
75
76
77 // Large grid
78 //
79 // Columns, offsets, pushes, and pulls for the large desktop device range.
80
81 @media (min-width: @screen-lg-min) {
82 .make-grid(lg);
83 }
+0
-166
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/input-groups.less less more
0 //
1 // Input groups
2 // --------------------------------------------------
3
4 // Base styles
5 // -------------------------
6 .input-group {
7 position: relative; // For dropdowns
8 display: table;
9 border-collapse: separate; // prevent input groups from inheriting border styles from table cells when placed within a table
10
11 // Undo padding and float of grid classes
12 &[class*="col-"] {
13 float: none;
14 padding-left: 0;
15 padding-right: 0;
16 }
17
18 .form-control {
19 // Ensure that the input is always above the *appended* addon button for
20 // proper border colors.
21 position: relative;
22 z-index: 2;
23
24 // IE9 fubars the placeholder attribute in text inputs and the arrows on
25 // select elements in input groups. To fix it, we float the input. Details:
26 // https://github.com/twbs/bootstrap/issues/11561#issuecomment-28936855
27 float: left;
28
29 width: 100%;
30 margin-bottom: 0;
31 }
32 }
33
34 // Sizing options
35 //
36 // Remix the default form control sizing classes into new ones for easier
37 // manipulation.
38
39 .input-group-lg > .form-control,
40 .input-group-lg > .input-group-addon,
41 .input-group-lg > .input-group-btn > .btn {
42 .input-lg();
43 }
44 .input-group-sm > .form-control,
45 .input-group-sm > .input-group-addon,
46 .input-group-sm > .input-group-btn > .btn {
47 .input-sm();
48 }
49
50
51 // Display as table-cell
52 // -------------------------
53 .input-group-addon,
54 .input-group-btn,
55 .input-group .form-control {
56 display: table-cell;
57
58 &:not(:first-child):not(:last-child) {
59 border-radius: 0;
60 }
61 }
62 // Addon and addon wrapper for buttons
63 .input-group-addon,
64 .input-group-btn {
65 width: 1%;
66 white-space: nowrap;
67 vertical-align: middle; // Match the inputs
68 }
69
70 // Text input groups
71 // -------------------------
72 .input-group-addon {
73 padding: @padding-base-vertical @padding-base-horizontal;
74 font-size: @font-size-base;
75 font-weight: normal;
76 line-height: 1;
77 color: @input-color;
78 text-align: center;
79 background-color: @input-group-addon-bg;
80 border: 1px solid @input-group-addon-border-color;
81 border-radius: @border-radius-base;
82
83 // Sizing
84 &.input-sm {
85 padding: @padding-small-vertical @padding-small-horizontal;
86 font-size: @font-size-small;
87 border-radius: @border-radius-small;
88 }
89 &.input-lg {
90 padding: @padding-large-vertical @padding-large-horizontal;
91 font-size: @font-size-large;
92 border-radius: @border-radius-large;
93 }
94
95 // Nuke default margins from checkboxes and radios to vertically center within.
96 input[type="radio"],
97 input[type="checkbox"] {
98 margin-top: 0;
99 }
100 }
101
102 // Reset rounded corners
103 .input-group .form-control:first-child,
104 .input-group-addon:first-child,
105 .input-group-btn:first-child > .btn,
106 .input-group-btn:first-child > .btn-group > .btn,
107 .input-group-btn:first-child > .dropdown-toggle,
108 .input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
109 .input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
110 .border-right-radius(0);
111 }
112 .input-group-addon:first-child {
113 border-right: 0;
114 }
115 .input-group .form-control:last-child,
116 .input-group-addon:last-child,
117 .input-group-btn:last-child > .btn,
118 .input-group-btn:last-child > .btn-group > .btn,
119 .input-group-btn:last-child > .dropdown-toggle,
120 .input-group-btn:first-child > .btn:not(:first-child),
121 .input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
122 .border-left-radius(0);
123 }
124 .input-group-addon:last-child {
125 border-left: 0;
126 }
127
128 // Button input groups
129 // -------------------------
130 .input-group-btn {
131 position: relative;
132 // Jankily prevent input button groups from wrapping with `white-space` and
133 // `font-size` in combination with `inline-block` on buttons.
134 font-size: 0;
135 white-space: nowrap;
136
137 // Negative margin for spacing, position for bringing hovered/focused/actived
138 // element above the siblings.
139 > .btn {
140 position: relative;
141 + .btn {
142 margin-left: -1px;
143 }
144 // Bring the "active" button to the front
145 &:hover,
146 &:focus,
147 &:active {
148 z-index: 2;
149 }
150 }
151
152 // Negative margin to only have a 1px border between the two
153 &:first-child {
154 > .btn,
155 > .btn-group {
156 margin-right: -1px;
157 }
158 }
159 &:last-child {
160 > .btn,
161 > .btn-group {
162 margin-left: -1px;
163 }
164 }
165 }
+0
-50
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/jumbotron.less less more
0 //
1 // Jumbotron
2 // --------------------------------------------------
3
4
5 .jumbotron {
6 padding: @jumbotron-padding (@jumbotron-padding / 2);
7 margin-bottom: @jumbotron-padding;
8 color: @jumbotron-color;
9 background-color: @jumbotron-bg;
10
11 h1,
12 .h1 {
13 color: @jumbotron-heading-color;
14 }
15
16 p {
17 margin-bottom: (@jumbotron-padding / 2);
18 font-size: @jumbotron-font-size;
19 font-weight: 200;
20 }
21
22 > hr {
23 border-top-color: darken(@jumbotron-bg, 10%);
24 }
25
26 .tb-container &,
27 .container-fluid & {
28 border-radius: @border-radius-large; // Only round corners at higher resolutions if contained in a container
29 }
30
31 .tb-container {
32 max-width: 100%;
33 }
34
35 @media screen and (min-width: @screen-sm-min) {
36 padding: (@jumbotron-padding * 1.6) 0;
37
38 .tb-container &,
39 .container-fluid & {
40 padding-left: (@jumbotron-padding * 2);
41 padding-right: (@jumbotron-padding * 2);
42 }
43
44 h1,
45 .h1 {
46 font-size: (@font-size-base * 4.5);
47 }
48 }
49 }
+0
-64
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/labels.less less more
0 //
1 // Labels
2 // --------------------------------------------------
3
4 .label {
5 display: inline;
6 padding: .2em .6em .3em;
7 font-size: 75%;
8 font-weight: bold;
9 line-height: 1;
10 color: @label-color;
11 text-align: center;
12 white-space: nowrap;
13 vertical-align: baseline;
14 border-radius: .25em;
15
16 // Add hover effects, but only for links
17 a& {
18 &:hover,
19 &:focus {
20 color: @label-link-hover-color;
21 text-decoration: none;
22 cursor: pointer;
23 }
24 }
25
26 // Empty labels collapse automatically (not available in IE8)
27 &:empty {
28 display: none;
29 }
30
31 // Quick fix for labels in buttons
32 .btn & {
33 position: relative;
34 top: -1px;
35 }
36 }
37
38 // Colors
39 // Contextual variations (linked labels get darker on :hover)
40
41 .label-default {
42 .label-variant(@label-default-bg);
43 }
44
45 .label-primary {
46 .label-variant(@label-primary-bg);
47 }
48
49 .label-success {
50 .label-variant(@label-success-bg);
51 }
52
53 .label-info {
54 .label-variant(@label-info-bg);
55 }
56
57 .label-warning {
58 .label-variant(@label-warning-bg);
59 }
60
61 .label-danger {
62 .label-variant(@label-danger-bg);
63 }
+0
-124
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/list-group.less less more
0 //
1 // List groups
2 // --------------------------------------------------
3
4
5 // Base class
6 //
7 // Easily usable on <ul>, <ol>, or <div>.
8
9 .list-group {
10 // No need to set list-style: none; since .list-group-item is block level
11 margin-bottom: 20px;
12 padding-left: 0; // reset padding because ul and ol
13 }
14
15
16 // Individual list items
17 //
18 // Use on `li`s or `div`s within the `.list-group` parent.
19
20 .list-group-item {
21 position: relative;
22 display: block;
23 padding: 10px 15px;
24 // Place the border on the list items and negative margin up for better styling
25 margin-bottom: -1px;
26 background-color: @list-group-bg;
27 border: 1px solid @list-group-border;
28
29 // Round the first and last items
30 &:first-child {
31 .border-top-radius(@list-group-border-radius);
32 }
33 &:last-child {
34 margin-bottom: 0;
35 .border-bottom-radius(@list-group-border-radius);
36 }
37 }
38
39
40 // Linked list items
41 //
42 // Use anchor elements instead of `li`s or `div`s to create linked list items.
43 // Includes an extra `.active` modifier class for showing selected items.
44
45 a.list-group-item {
46 color: @list-group-link-color;
47
48 .list-group-item-heading {
49 color: @list-group-link-heading-color;
50 }
51
52 // Hover state
53 &:hover,
54 &:focus {
55 text-decoration: none;
56 color: @list-group-link-hover-color;
57 background-color: @list-group-hover-bg;
58 }
59 }
60
61 .list-group-item {
62 // Disabled state
63 &.disabled,
64 &.disabled:hover,
65 &.disabled:focus {
66 background-color: @list-group-disabled-bg;
67 color: @list-group-disabled-color;
68 cursor: @cursor-disabled;
69
70 // Force color to inherit for custom content
71 .list-group-item-heading {
72 color: inherit;
73 }
74 .list-group-item-text {
75 color: @list-group-disabled-text-color;
76 }
77 }
78
79 // Active class on item itself, not parent
80 &.active,
81 &.active:hover,
82 &.active:focus {
83 z-index: 2; // Place active items above their siblings for proper border styling
84 color: @list-group-active-color;
85 background-color: @list-group-active-bg;
86 border-color: @list-group-active-border;
87
88 // Force color to inherit for custom content
89 .list-group-item-heading,
90 .list-group-item-heading > small,
91 .list-group-item-heading > .small {
92 color: inherit;
93 }
94 .list-group-item-text {
95 color: @list-group-active-text-color;
96 }
97 }
98 }
99
100
101 // Contextual variants
102 //
103 // Add modifier classes to change text and background color on individual items.
104 // Organizationally, this must come after the `:hover` states.
105
106 .list-group-item-variant(success; @state-success-bg; @state-success-text);
107 .list-group-item-variant(info; @state-info-bg; @state-info-text);
108 .list-group-item-variant(warning; @state-warning-bg; @state-warning-text);
109 .list-group-item-variant(danger; @state-danger-bg; @state-danger-text);
110
111
112 // Custom content options
113 //
114 // Extra classes for creating well-formatted content within `.list-group-item`s.
115
116 .list-group-item-heading {
117 margin-top: 0;
118 margin-bottom: 5px;
119 }
120 .list-group-item-text {
121 margin-bottom: 0;
122 line-height: 1.3;
123 }
+0
-61
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/media.less less more
0 .media {
1 // Proper spacing between instances of .media
2 margin-top: 15px;
3
4 &:first-child {
5 margin-top: 0;
6 }
7 }
8
9 .media,
10 .media-body {
11 zoom: 1;
12 overflow: hidden;
13 }
14
15 .media-body {
16 width: 10000px;
17 }
18
19 .media-object {
20 display: block;
21 }
22
23 .media-right,
24 .media > .pull-right {
25 padding-left: 10px;
26 }
27
28 .media-left,
29 .media > .pull-left {
30 padding-right: 10px;
31 }
32
33 .media-left,
34 .media-right,
35 .media-body {
36 display: table-cell;
37 vertical-align: top;
38 }
39
40 .media-middle {
41 vertical-align: middle;
42 }
43
44 .media-bottom {
45 vertical-align: bottom;
46 }
47
48 // Reset margins on headings for tighter default spacing
49 .media-heading {
50 margin-top: 0;
51 margin-bottom: 5px;
52 }
53
54 // Media list variation
55 //
56 // Undo default ul/ol styles
57 .media-list {
58 padding-left: 0;
59 list-style: none;
60 }
+0
-14
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/alerts.less less more
0 // Alerts
1
2 .alert-variant(@background; @border; @text-color) {
3 background-color: @background;
4 border-color: @border;
5 color: @text-color;
6
7 hr {
8 border-top-color: darken(@border, 5%);
9 }
10 .alert-link {
11 color: darken(@text-color, 10%);
12 }
13 }
+0
-8
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/background-variant.less less more
0 // Contextual backgrounds
1
2 .bg-variant(@color) {
3 background-color: @color;
4 a&:hover {
5 background-color: darken(@color, 10%);
6 }
7 }
+0
-18
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/border-radius.less less more
0 // Single side border-radius
1
2 .border-top-radius(@radius) {
3 border-top-right-radius: @radius;
4 border-top-left-radius: @radius;
5 }
6 .border-right-radius(@radius) {
7 border-bottom-right-radius: @radius;
8 border-top-right-radius: @radius;
9 }
10 .border-bottom-radius(@radius) {
11 border-bottom-right-radius: @radius;
12 border-bottom-left-radius: @radius;
13 }
14 .border-left-radius(@radius) {
15 border-bottom-left-radius: @radius;
16 border-top-left-radius: @radius;
17 }
+0
-52
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/buttons.less less more
0 // Button variants
1 //
2 // Easily pump out default styles, as well as :hover, :focus, :active,
3 // and disabled options for all buttons
4
5 .button-variant(@color; @background; @border) {
6 color: @color;
7 background-color: @background;
8 border-color: @border;
9
10 &:hover,
11 &:focus,
12 &.focus,
13 &:active,
14 &.active,
15 .open > .dropdown-toggle& {
16 color: @color;
17 background-color: darken(@background, 10%);
18 border-color: darken(@border, 12%);
19 }
20 &:active,
21 &.active,
22 .open > .dropdown-toggle& {
23 background-image: none;
24 }
25 &.disabled,
26 &[disabled],
27 fieldset[disabled] & {
28 &,
29 &:hover,
30 &:focus,
31 &.focus,
32 &:active,
33 &.active {
34 background-color: @background;
35 border-color: @border;
36 }
37 }
38
39 .badge {
40 color: @background;
41 background-color: @color;
42 }
43 }
44
45 // Button sizes
46 .button-size(@padding-vertical; @padding-horizontal; @font-size; @line-height; @border-radius) {
47 padding: @padding-vertical @padding-horizontal;
48 font-size: @font-size;
49 line-height: @line-height;
50 border-radius: @border-radius;
51 }
+0
-7
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/center-block.less less more
0 // Center-align a block level element
1
2 .center-block() {
3 display: block;
4 margin-left: auto;
5 margin-right: auto;
6 }
+0
-22
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/clearfix.less less more
0 // Clearfix
1 //
2 // For modern browsers
3 // 1. The space content is one way to avoid an Opera bug when the
4 // contenteditable attribute is included anywhere else in the document.
5 // Otherwise it causes space to appear at the top and bottom of elements
6 // that are clearfixed.
7 // 2. The use of `table` rather than `block` is only necessary if using
8 // `:before` to contain the top-margins of child elements.
9 //
10 // Source: http://nicolasgallagher.com/micro-clearfix-hack/
11
12 .clearfix() {
13 &:before,
14 &:after {
15 content: " "; // 1
16 display: table; // 2
17 }
18 &:after {
19 clear: both;
20 }
21 }
+0
-85
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/forms.less less more
0 // Form validation states
1 //
2 // Used in forms.less to generate the form validation CSS for warnings, errors,
3 // and successes.
4
5 .form-control-validation(@text-color: #555; @border-color: #ccc; @background-color: #f5f5f5) {
6 // Color the label and help text
7 .help-block,
8 .control-label,
9 .radio,
10 .checkbox,
11 .radio-inline,
12 .checkbox-inline,
13 &.radio label,
14 &.checkbox label,
15 &.radio-inline label,
16 &.checkbox-inline label {
17 color: @text-color;
18 }
19 // Set the border and box shadow on specific inputs to match
20 .form-control {
21 border-color: @border-color;
22 .box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); // Redeclare so transitions work
23 &:focus {
24 border-color: darken(@border-color, 10%);
25 @shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px lighten(@border-color, 20%);
26 .box-shadow(@shadow);
27 }
28 }
29 // Set validation states also for addons
30 .input-group-addon {
31 color: @text-color;
32 border-color: @border-color;
33 background-color: @background-color;
34 }
35 // Optional feedback icon
36 .form-control-feedback {
37 color: @text-color;
38 }
39 }
40
41
42 // Form control focus state
43 //
44 // Generate a customized focus state and for any input with the specified color,
45 // which defaults to the `@input-border-focus` variable.
46 //
47 // We highly encourage you to not customize the default value, but instead use
48 // this to tweak colors on an as-needed basis. This aesthetic change is based on
49 // WebKit's default styles, but applicable to a wider range of browsers. Its
50 // usability and accessibility should be taken into account with any change.
51 //
52 // Example usage: change the default blue border and shadow to white for better
53 // contrast against a dark gray background.
54 .form-control-focus(@color: @input-border-focus) {
55 @color-rgba: rgba(red(@color), green(@color), blue(@color), .6);
56 &:focus {
57 border-color: @color;
58 outline: 0;
59 .box-shadow(~"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px @{color-rgba}");
60 }
61 }
62
63 // Form control sizing
64 //
65 // Relative text size, padding, and border-radii changes for form controls. For
66 // horizontal sizing, wrap controls in the predefined grid classes. `<select>`
67 // element gets special love because it's special, and that's a fact!
68 .input-size(@input-height; @padding-vertical; @padding-horizontal; @font-size; @line-height; @border-radius) {
69 height: @input-height;
70 padding: @padding-vertical @padding-horizontal;
71 font-size: @font-size;
72 line-height: @line-height;
73 border-radius: @border-radius;
74
75 select& {
76 height: @input-height;
77 line-height: @input-height;
78 }
79
80 textarea&,
81 select[multiple]& {
82 height: auto;
83 }
84 }
+0
-59
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/gradients.less less more
0 // Gradients
1
2 #gradient {
3
4 // Horizontal gradient, from left to right
5 //
6 // Creates two color stops, start and end, by specifying a color and position for each color stop.
7 // Color stops are not available in IE9 and below.
8 .horizontal(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {
9 background-image: -webkit-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+
10 background-image: -o-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Opera 12
11 background-image: linear-gradient(to right, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+
12 background-repeat: repeat-x;
13 filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@start-color),argb(@end-color))); // IE9 and down
14 }
15
16 // Vertical gradient, from top to bottom
17 //
18 // Creates two color stops, start and end, by specifying a color and position for each color stop.
19 // Color stops are not available in IE9 and below.
20 .vertical(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {
21 background-image: -webkit-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+
22 background-image: -o-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Opera 12
23 background-image: linear-gradient(to bottom, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+
24 background-repeat: repeat-x;
25 filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@start-color),argb(@end-color))); // IE9 and down
26 }
27
28 .directional(@start-color: #555; @end-color: #333; @deg: 45deg) {
29 background-repeat: repeat-x;
30 background-image: -webkit-linear-gradient(@deg, @start-color, @end-color); // Safari 5.1-6, Chrome 10+
31 background-image: -o-linear-gradient(@deg, @start-color, @end-color); // Opera 12
32 background-image: linear-gradient(@deg, @start-color, @end-color); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+
33 }
34 .horizontal-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {
35 background-image: -webkit-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);
36 background-image: -o-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);
37 background-image: linear-gradient(to right, @start-color, @mid-color @color-stop, @end-color);
38 background-repeat: no-repeat;
39 filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback
40 }
41 .vertical-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {
42 background-image: -webkit-linear-gradient(@start-color, @mid-color @color-stop, @end-color);
43 background-image: -o-linear-gradient(@start-color, @mid-color @color-stop, @end-color);
44 background-image: linear-gradient(@start-color, @mid-color @color-stop, @end-color);
45 background-repeat: no-repeat;
46 filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback
47 }
48 .radial(@inner-color: #555; @outer-color: #333) {
49 background-image: -webkit-radial-gradient(circle, @inner-color, @outer-color);
50 background-image: radial-gradient(circle, @inner-color, @outer-color);
51 background-repeat: no-repeat;
52 }
53 .striped(@color: rgba(255,255,255,.15); @angle: 45deg) {
54 background-image: -webkit-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);
55 background-image: -o-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);
56 background-image: linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);
57 }
58 }
+0
-91
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/grid-framework.less less more
0 // Framework grid generation
1 //
2 // Used only by Bootstrap to generate the correct number of grid classes given
3 // any value of `@grid-columns`.
4
5 .make-grid-columns() {
6 // Common styles for all sizes of grid columns, widths 1-12
7 .col(@index) { // initial
8 @item: ~".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}";
9 .col((@index + 1), @item);
10 }
11 .col(@index, @list) when (@index =< @grid-columns) { // general; "=<" isn't a typo
12 @item: ~".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}";
13 .col((@index + 1), ~"@{list}, @{item}");
14 }
15 .col(@index, @list) when (@index > @grid-columns) { // terminal
16 @{list} {
17 position: relative;
18 // Prevent columns from collapsing when empty
19 min-height: 1px;
20 // Inner gutter via padding
21 padding-left: (@grid-gutter-width / 2);
22 padding-right: (@grid-gutter-width / 2);
23 }
24 }
25 .col(1); // kickstart it
26 }
27
28 .float-grid-columns(@class) {
29 .col(@index) { // initial
30 @item: ~".col-@{class}-@{index}";
31 .col((@index + 1), @item);
32 }
33 .col(@index, @list) when (@index =< @grid-columns) { // general
34 @item: ~".col-@{class}-@{index}";
35 .col((@index + 1), ~"@{list}, @{item}");
36 }
37 .col(@index, @list) when (@index > @grid-columns) { // terminal
38 @{list} {
39 float: left;
40 }
41 }
42 .col(1); // kickstart it
43 }
44
45 .calc-grid-column(@index, @class, @type) when (@type = width) and (@index > 0) {
46 .col-@{class}-@{index} {
47 width: percentage((@index / @grid-columns));
48 }
49 }
50 .calc-grid-column(@index, @class, @type) when (@type = push) and (@index > 0) {
51 .col-@{class}-push-@{index} {
52 left: percentage((@index / @grid-columns));
53 }
54 }
55 .calc-grid-column(@index, @class, @type) when (@type = push) and (@index = 0) {
56 .col-@{class}-push-0 {
57 left: auto;
58 }
59 }
60 .calc-grid-column(@index, @class, @type) when (@type = pull) and (@index > 0) {
61 .col-@{class}-pull-@{index} {
62 right: percentage((@index / @grid-columns));
63 }
64 }
65 .calc-grid-column(@index, @class, @type) when (@type = pull) and (@index = 0) {
66 .col-@{class}-pull-0 {
67 right: auto;
68 }
69 }
70 .calc-grid-column(@index, @class, @type) when (@type = offset) {
71 .col-@{class}-offset-@{index} {
72 margin-left: percentage((@index / @grid-columns));
73 }
74 }
75
76 // Basic looping in LESS
77 .loop-grid-columns(@index, @class, @type) when (@index >= 0) {
78 .calc-grid-column(@index, @class, @type);
79 // next iteration
80 .loop-grid-columns((@index - 1), @class, @type);
81 }
82
83 // Create grid for specific class
84 .make-grid(@class) {
85 .float-grid-columns(@class);
86 .loop-grid-columns(@grid-columns, @class, width);
87 .loop-grid-columns(@grid-columns, @class, pull);
88 .loop-grid-columns(@grid-columns, @class, push);
89 .loop-grid-columns(@grid-columns, @class, offset);
90 }
+0
-122
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/grid.less less more
0 // Grid system
1 //
2 // Generate semantic grid columns with these mixins.
3
4 // Centered container element
5 .container-fixed(@gutter: @grid-gutter-width) {
6 margin-right: auto;
7 margin-left: auto;
8 padding-left: (@gutter / 2);
9 padding-right: (@gutter / 2);
10 &:extend(.clearfix all);
11 }
12
13 // Creates a wrapper for a series of columns
14 .make-row(@gutter: @grid-gutter-width) {
15 margin-left: (@gutter / -2);
16 margin-right: (@gutter / -2);
17 &:extend(.clearfix all);
18 }
19
20 // Generate the extra small columns
21 .make-xs-column(@columns; @gutter: @grid-gutter-width) {
22 position: relative;
23 float: left;
24 width: percentage((@columns / @grid-columns));
25 min-height: 1px;
26 padding-left: (@gutter / 2);
27 padding-right: (@gutter / 2);
28 }
29 .make-xs-column-offset(@columns) {
30 margin-left: percentage((@columns / @grid-columns));
31 }
32 .make-xs-column-push(@columns) {
33 left: percentage((@columns / @grid-columns));
34 }
35 .make-xs-column-pull(@columns) {
36 right: percentage((@columns / @grid-columns));
37 }
38
39 // Generate the small columns
40 .make-sm-column(@columns; @gutter: @grid-gutter-width) {
41 position: relative;
42 min-height: 1px;
43 padding-left: (@gutter / 2);
44 padding-right: (@gutter / 2);
45
46 @media (min-width: @screen-sm-min) {
47 float: left;
48 width: percentage((@columns / @grid-columns));
49 }
50 }
51 .make-sm-column-offset(@columns) {
52 @media (min-width: @screen-sm-min) {
53 margin-left: percentage((@columns / @grid-columns));
54 }
55 }
56 .make-sm-column-push(@columns) {
57 @media (min-width: @screen-sm-min) {
58 left: percentage((@columns / @grid-columns));
59 }
60 }
61 .make-sm-column-pull(@columns) {
62 @media (min-width: @screen-sm-min) {
63 right: percentage((@columns / @grid-columns));
64 }
65 }
66
67 // Generate the medium columns
68 .make-md-column(@columns; @gutter: @grid-gutter-width) {
69 position: relative;
70 min-height: 1px;
71 padding-left: (@gutter / 2);
72 padding-right: (@gutter / 2);
73
74 @media (min-width: @screen-md-min) {
75 float: left;
76 width: percentage((@columns / @grid-columns));
77 }
78 }
79 .make-md-column-offset(@columns) {
80 @media (min-width: @screen-md-min) {
81 margin-left: percentage((@columns / @grid-columns));
82 }
83 }
84 .make-md-column-push(@columns) {
85 @media (min-width: @screen-md-min) {
86 left: percentage((@columns / @grid-columns));
87 }
88 }
89 .make-md-column-pull(@columns) {
90 @media (min-width: @screen-md-min) {
91 right: percentage((@columns / @grid-columns));
92 }
93 }
94
95 // Generate the large columns
96 .make-lg-column(@columns; @gutter: @grid-gutter-width) {
97 position: relative;
98 min-height: 1px;
99 padding-left: (@gutter / 2);
100 padding-right: (@gutter / 2);
101
102 @media (min-width: @screen-lg-min) {
103 float: left;
104 width: percentage((@columns / @grid-columns));
105 }
106 }
107 .make-lg-column-offset(@columns) {
108 @media (min-width: @screen-lg-min) {
109 margin-left: percentage((@columns / @grid-columns));
110 }
111 }
112 .make-lg-column-push(@columns) {
113 @media (min-width: @screen-lg-min) {
114 left: percentage((@columns / @grid-columns));
115 }
116 }
117 .make-lg-column-pull(@columns) {
118 @media (min-width: @screen-lg-min) {
119 right: percentage((@columns / @grid-columns));
120 }
121 }
+0
-21
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/hide-text.less less more
0 // CSS image replacement
1 //
2 // Heads up! v3 launched with with only `.hide-text()`, but per our pattern for
3 // mixins being reused as classes with the same name, this doesn't hold up. As
4 // of v3.0.1 we have added `.text-hide()` and deprecated `.hide-text()`.
5 //
6 // Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757
7
8 // Deprecated as of v3.0.1 (will be removed in v4)
9 .hide-text() {
10 font: ~"0/0" a;
11 color: transparent;
12 text-shadow: none;
13 background-color: transparent;
14 border: 0;
15 }
16
17 // New mixin to use as of v3.0.1
18 .text-hide() {
19 .hide-text();
20 }
+0
-33
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/image.less less more
0 // Image Mixins
1 // - Responsive image
2 // - Retina image
3
4
5 // Responsive image
6 //
7 // Keep images from scaling beyond the width of their parents.
8 .img-responsive(@display: block) {
9 display: @display;
10 max-width: 100%; // Part 1: Set a maximum relative to the parent
11 height: auto; // Part 2: Scale the height according to the width, otherwise you get stretching
12 }
13
14
15 // Retina image
16 //
17 // Short retina mixin for setting background-image and -size. Note that the
18 // spelling of `min--moz-device-pixel-ratio` is intentional.
19 .img-retina(@file-1x; @file-2x; @width-1x; @height-1x) {
20 background-image: url("@{file-1x}");
21
22 @media
23 only screen and (-webkit-min-device-pixel-ratio: 2),
24 only screen and ( min--moz-device-pixel-ratio: 2),
25 only screen and ( -o-min-device-pixel-ratio: 2/1),
26 only screen and ( min-device-pixel-ratio: 2),
27 only screen and ( min-resolution: 192dpi),
28 only screen and ( min-resolution: 2dppx) {
29 background-image: url("@{file-2x}");
30 background-size: @width-1x @height-1x;
31 }
32 }
+0
-12
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/labels.less less more
0 // Labels
1
2 .label-variant(@color) {
3 background-color: @color;
4
5 &[href] {
6 &:hover,
7 &:focus {
8 background-color: darken(@color, 10%);
9 }
10 }
11 }
+0
-29
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/list-group.less less more
0 // List Groups
1
2 .list-group-item-variant(@state; @background; @color) {
3 .list-group-item-@{state} {
4 color: @color;
5 background-color: @background;
6
7 a& {
8 color: @color;
9
10 .list-group-item-heading {
11 color: inherit;
12 }
13
14 &:hover,
15 &:focus {
16 color: @color;
17 background-color: darken(@background, 5%);
18 }
19 &.active,
20 &.active:hover,
21 &.active:focus {
22 color: #fff;
23 background-color: @color;
24 border-color: @color;
25 }
26 }
27 }
28 }
+0
-10
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/nav-divider.less less more
0 // Horizontal dividers
1 //
2 // Dividers (basically an hr) within dropdowns and nav lists
3
4 .nav-divider(@color: #e5e5e5) {
5 height: 1px;
6 margin: ((@line-height-computed / 2) - 1) 0;
7 overflow: hidden;
8 background-color: @color;
9 }
+0
-9
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/nav-vertical-align.less less more
0 // Navbar vertical align
1 //
2 // Vertically center elements in the navbar.
3 // Example: an element has a height of 30px, so write out `.navbar-vertical-align(30px);` to calculate the appropriate top margin.
4
5 .navbar-vertical-align(@element-height) {
6 margin-top: ((@navbar-height - @element-height) / 2);
7 margin-bottom: ((@navbar-height - @element-height) / 2);
8 }
+0
-8
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/opacity.less less more
0 // Opacity
1
2 .opacity(@opacity) {
3 opacity: @opacity;
4 // IE8 filter
5 @opacity-ie: (@opacity * 100);
6 filter: ~"alpha(opacity=@{opacity-ie})";
7 }
+0
-23
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/pagination.less less more
0 // Pagination
1
2 .pagination-size(@padding-vertical; @padding-horizontal; @font-size; @border-radius) {
3 > li {
4 > a,
5 > span {
6 padding: @padding-vertical @padding-horizontal;
7 font-size: @font-size;
8 }
9 &:first-child {
10 > a,
11 > span {
12 .border-left-radius(@border-radius);
13 }
14 }
15 &:last-child {
16 > a,
17 > span {
18 .border-right-radius(@border-radius);
19 }
20 }
21 }
22 }
+0
-24
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/panels.less less more
0 // Panels
1
2 .panel-variant(@border; @heading-text-color; @heading-bg-color; @heading-border) {
3 border-color: @border;
4
5 & > .panel-heading {
6 color: @heading-text-color;
7 background-color: @heading-bg-color;
8 border-color: @heading-border;
9
10 + .panel-collapse > .panel-body {
11 border-top-color: @border;
12 }
13 .badge {
14 color: @heading-bg-color;
15 background-color: @heading-text-color;
16 }
17 }
18 & > .panel-footer {
19 + .panel-collapse > .panel-body {
20 border-bottom-color: @border;
21 }
22 }
23 }
+0
-10
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/progress-bar.less less more
0 // Progress bars
1
2 .progress-bar-variant(@color) {
3 background-color: @color;
4
5 // Deprecated parent class requirement as of v3.2.0
6 .progress-striped & {
7 #gradient > .striped();
8 }
9 }
+0
-8
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/reset-filter.less less more
0 // Reset filters for IE
1 //
2 // When you need to remove a gradient background, do not forget to use this to reset
3 // the IE filter for IE9 and below.
4
5 .reset-filter() {
6 filter: e(%("progid:DXImageTransform.Microsoft.gradient(enabled = false)"));
7 }
+0
-6
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/resize.less less more
0 // Resize anything
1
2 .resizable(@direction) {
3 resize: @direction; // Options: horizontal, vertical, both
4 overflow: auto; // Per CSS3 UI, `resize` only applies when `overflow` isn't `visible`
5 }
+0
-15
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/responsive-visibility.less less more
0 // Responsive utilities
1
2 //
3 // More easily include all the states for responsive-utilities.less.
4 .responsive-visibility() {
5 display: block !important;
6 table& { display: table; }
7 tr& { display: table-row !important; }
8 th&,
9 td& { display: table-cell !important; }
10 }
11
12 .responsive-invisibility() {
13 display: none !important;
14 }
+0
-10
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/size.less less more
0 // Sizing shortcuts
1
2 .size(@width; @height) {
3 width: @width;
4 height: @height;
5 }
6
7 .square(@size) {
8 .size(@size; @size);
9 }
+0
-9
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/tab-focus.less less more
0 // WebKit-style focus
1
2 .tab-focus() {
3 // Default
4 outline: thin dotted;
5 // WebKit
6 outline: 5px auto -webkit-focus-ring-color;
7 outline-offset: -2px;
8 }
+0
-28
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/table-row.less less more
0 // Tables
1
2 .table-row-variant(@state; @background) {
3 // Exact selectors below required to override `.table-striped` and prevent
4 // inheritance to nested tables.
5 .table > thead > tr,
6 .table > tbody > tr,
7 .table > tfoot > tr {
8 > td.@{state},
9 > th.@{state},
10 &.@{state} > td,
11 &.@{state} > th {
12 background-color: @background;
13 }
14 }
15
16 // Hover states for `.table-hover`
17 // Note: this is not available for cells or rows within `thead` or `tfoot`.
18 .table-hover > tbody > tr {
19 > td.@{state}:hover,
20 > th.@{state}:hover,
21 &.@{state}:hover > td,
22 &:hover > .@{state},
23 &.@{state}:hover > th {
24 background-color: darken(@background, 5%);
25 }
26 }
27 }
+0
-8
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/text-emphasis.less less more
0 // Typography
1
2 .text-emphasis-variant(@color) {
3 color: @color;
4 a&:hover {
5 color: darken(@color, 10%);
6 }
7 }
+0
-8
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/text-overflow.less less more
0 // Text overflow
1 // Requires inline-block or block for proper styling
2
3 .text-overflow() {
4 overflow: hidden;
5 text-overflow: ellipsis;
6 white-space: nowrap;
7 }
+0
-227
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins/vendor-prefixes.less less more
0 // Vendor Prefixes
1 //
2 // All vendor mixins are deprecated as of v3.2.0 due to the introduction of
3 // Autoprefixer in our Gruntfile. They will be removed in v4.
4
5 // - Animations
6 // - Backface visibility
7 // - Box shadow
8 // - Box sizing
9 // - Content columns
10 // - Hyphens
11 // - Placeholder text
12 // - Transformations
13 // - Transitions
14 // - User Select
15
16
17 // Animations
18 .animation(@animation) {
19 -webkit-animation: @animation;
20 -o-animation: @animation;
21 animation: @animation;
22 }
23 .animation-name(@name) {
24 -webkit-animation-name: @name;
25 animation-name: @name;
26 }
27 .animation-duration(@duration) {
28 -webkit-animation-duration: @duration;
29 animation-duration: @duration;
30 }
31 .animation-timing-function(@timing-function) {
32 -webkit-animation-timing-function: @timing-function;
33 animation-timing-function: @timing-function;
34 }
35 .animation-delay(@delay) {
36 -webkit-animation-delay: @delay;
37 animation-delay: @delay;
38 }
39 .animation-iteration-count(@iteration-count) {
40 -webkit-animation-iteration-count: @iteration-count;
41 animation-iteration-count: @iteration-count;
42 }
43 .animation-direction(@direction) {
44 -webkit-animation-direction: @direction;
45 animation-direction: @direction;
46 }
47 .animation-fill-mode(@fill-mode) {
48 -webkit-animation-fill-mode: @fill-mode;
49 animation-fill-mode: @fill-mode;
50 }
51
52 // Backface visibility
53 // Prevent browsers from flickering when using CSS 3D transforms.
54 // Default value is `visible`, but can be changed to `hidden`
55
56 .backface-visibility(@visibility){
57 -webkit-backface-visibility: @visibility;
58 -moz-backface-visibility: @visibility;
59 backface-visibility: @visibility;
60 }
61
62 // Drop shadows
63 //
64 // Note: Deprecated `.box-shadow()` as of v3.1.0 since all of Bootstrap's
65 // supported browsers that have box shadow capabilities now support it.
66
67 .box-shadow(@shadow) {
68 -webkit-box-shadow: @shadow; // iOS <4.3 & Android <4.1
69 box-shadow: @shadow;
70 }
71
72 // Box sizing
73 .box-sizing(@boxmodel) {
74 -webkit-box-sizing: @boxmodel;
75 -moz-box-sizing: @boxmodel;
76 box-sizing: @boxmodel;
77 }
78
79 // CSS3 Content Columns
80 .content-columns(@column-count; @column-gap: @grid-gutter-width) {
81 -webkit-column-count: @column-count;
82 -moz-column-count: @column-count;
83 column-count: @column-count;
84 -webkit-column-gap: @column-gap;
85 -moz-column-gap: @column-gap;
86 column-gap: @column-gap;
87 }
88
89 // Optional hyphenation
90 .hyphens(@mode: auto) {
91 word-wrap: break-word;
92 -webkit-hyphens: @mode;
93 -moz-hyphens: @mode;
94 -ms-hyphens: @mode; // IE10+
95 -o-hyphens: @mode;
96 hyphens: @mode;
97 }
98
99 // Placeholder text
100 .placeholder(@color: @input-color-placeholder) {
101 // Firefox
102 &::-moz-placeholder {
103 color: @color;
104 opacity: 1; // Override Firefox's unusual default opacity; see https://github.com/twbs/bootstrap/pull/11526
105 }
106 &:-ms-input-placeholder { color: @color; } // Internet Explorer 10+
107 &::-webkit-input-placeholder { color: @color; } // Safari and Chrome
108 }
109
110 // Transformations
111 .scale(@ratio) {
112 -webkit-transform: scale(@ratio);
113 -ms-transform: scale(@ratio); // IE9 only
114 -o-transform: scale(@ratio);
115 transform: scale(@ratio);
116 }
117 .scale(@ratioX; @ratioY) {
118 -webkit-transform: scale(@ratioX, @ratioY);
119 -ms-transform: scale(@ratioX, @ratioY); // IE9 only
120 -o-transform: scale(@ratioX, @ratioY);
121 transform: scale(@ratioX, @ratioY);
122 }
123 .scaleX(@ratio) {
124 -webkit-transform: scaleX(@ratio);
125 -ms-transform: scaleX(@ratio); // IE9 only
126 -o-transform: scaleX(@ratio);
127 transform: scaleX(@ratio);
128 }
129 .scaleY(@ratio) {
130 -webkit-transform: scaleY(@ratio);
131 -ms-transform: scaleY(@ratio); // IE9 only
132 -o-transform: scaleY(@ratio);
133 transform: scaleY(@ratio);
134 }
135 .skew(@x; @y) {
136 -webkit-transform: skewX(@x) skewY(@y);
137 -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twbs/bootstrap/issues/4885; IE9+
138 -o-transform: skewX(@x) skewY(@y);
139 transform: skewX(@x) skewY(@y);
140 }
141 .translate(@x; @y) {
142 -webkit-transform: translate(@x, @y);
143 -ms-transform: translate(@x, @y); // IE9 only
144 -o-transform: translate(@x, @y);
145 transform: translate(@x, @y);
146 }
147 .translate3d(@x; @y; @z) {
148 -webkit-transform: translate3d(@x, @y, @z);
149 transform: translate3d(@x, @y, @z);
150 }
151 .rotate(@degrees) {
152 -webkit-transform: rotate(@degrees);
153 -ms-transform: rotate(@degrees); // IE9 only
154 -o-transform: rotate(@degrees);
155 transform: rotate(@degrees);
156 }
157 .rotateX(@degrees) {
158 -webkit-transform: rotateX(@degrees);
159 -ms-transform: rotateX(@degrees); // IE9 only
160 -o-transform: rotateX(@degrees);
161 transform: rotateX(@degrees);
162 }
163 .rotateY(@degrees) {
164 -webkit-transform: rotateY(@degrees);
165 -ms-transform: rotateY(@degrees); // IE9 only
166 -o-transform: rotateY(@degrees);
167 transform: rotateY(@degrees);
168 }
169 .perspective(@perspective) {
170 -webkit-perspective: @perspective;
171 -moz-perspective: @perspective;
172 perspective: @perspective;
173 }
174 .perspective-origin(@perspective) {
175 -webkit-perspective-origin: @perspective;
176 -moz-perspective-origin: @perspective;
177 perspective-origin: @perspective;
178 }
179 .transform-origin(@origin) {
180 -webkit-transform-origin: @origin;
181 -moz-transform-origin: @origin;
182 -ms-transform-origin: @origin; // IE9 only
183 transform-origin: @origin;
184 }
185
186
187 // Transitions
188
189 .transition(@transition) {
190 -webkit-transition: @transition;
191 -o-transition: @transition;
192 transition: @transition;
193 }
194 .transition-property(@transition-property) {
195 -webkit-transition-property: @transition-property;
196 transition-property: @transition-property;
197 }
198 .transition-delay(@transition-delay) {
199 -webkit-transition-delay: @transition-delay;
200 transition-delay: @transition-delay;
201 }
202 .transition-duration(@transition-duration) {
203 -webkit-transition-duration: @transition-duration;
204 transition-duration: @transition-duration;
205 }
206 .transition-timing-function(@timing-function) {
207 -webkit-transition-timing-function: @timing-function;
208 transition-timing-function: @timing-function;
209 }
210 .transition-transform(@transition) {
211 -webkit-transition: -webkit-transform @transition;
212 -moz-transition: -moz-transform @transition;
213 -o-transition: -o-transform @transition;
214 transition: transform @transition;
215 }
216
217
218 // User select
219 // For selecting text on the page
220
221 .user-select(@select) {
222 -webkit-user-select: @select;
223 -moz-user-select: @select;
224 -ms-user-select: @select; // IE10+
225 user-select: @select;
226 }
+0
-39
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/mixins.less less more
0 // Mixins
1 // --------------------------------------------------
2
3 // Utilities
4 @import "mixins/hide-text.less";
5 @import "mixins/opacity.less";
6 @import "mixins/image.less";
7 @import "mixins/labels.less";
8 @import "mixins/reset-filter.less";
9 @import "mixins/resize.less";
10 @import "mixins/responsive-visibility.less";
11 @import "mixins/size.less";
12 @import "mixins/tab-focus.less";
13 @import "mixins/text-emphasis.less";
14 @import "mixins/text-overflow.less";
15 @import "mixins/vendor-prefixes.less";
16
17 // Components
18 @import "mixins/alerts.less";
19 @import "mixins/buttons.less";
20 @import "mixins/panels.less";
21 @import "mixins/pagination.less";
22 @import "mixins/list-group.less";
23 @import "mixins/nav-divider.less";
24 @import "mixins/forms.less";
25 @import "mixins/progress-bar.less";
26 @import "mixins/table-row.less";
27
28 // Skins
29 @import "mixins/background-variant.less";
30 @import "mixins/border-radius.less";
31 @import "mixins/gradients.less";
32
33 // Layout
34 @import "mixins/clearfix.less";
35 @import "mixins/center-block.less";
36 @import "mixins/nav-vertical-align.less";
37 @import "mixins/grid-framework.less";
38 @import "mixins/grid.less";
+0
-150
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/modals.less less more
0 //
1 // Modals
2 // --------------------------------------------------
3
4 // .modal-open - body class for killing the scroll
5 // .modal - container to scroll within
6 // .modal-dialog - positioning shell for the actual modal
7 // .modal-content - actual modal w/ bg and corners and shit
8
9 // Kill the scroll on the body
10 .modal-open {
11 overflow: hidden;
12 }
13
14 // Container that the modal scrolls within
15 .modal {
16 display: none;
17 overflow: hidden;
18 position: fixed;
19 top: 0;
20 right: 0;
21 bottom: 0;
22 left: 0;
23 z-index: @zindex-modal;
24 -webkit-overflow-scrolling: touch;
25
26 // Prevent Chrome on Windows from adding a focus outline. For details, see
27 // https://github.com/twbs/bootstrap/pull/10951.
28 outline: 0;
29
30 // When fading in the modal, animate it to slide down
31 &.fade .modal-dialog {
32 .translate(0, -25%);
33 .transition-transform(~"0.3s ease-out");
34 }
35 &.in .modal-dialog { .translate(0, 0) }
36 }
37 .modal-open .modal {
38 overflow-x: hidden;
39 overflow-y: auto;
40 }
41
42 // Shell div to position the modal with bottom padding
43 .modal-dialog {
44 position: relative;
45 width: auto;
46 margin: 10px;
47 }
48
49 // Actual modal
50 .modal-content {
51 position: relative;
52 background-color: @modal-content-bg;
53 border: 1px solid @modal-content-fallback-border-color; //old browsers fallback (ie8 etc)
54 border: 1px solid @modal-content-border-color;
55 border-radius: @border-radius-large;
56 .box-shadow(0 3px 9px rgba(0,0,0,.5));
57 background-clip: padding-box;
58 // Remove focus outline from opened modal
59 outline: 0;
60 }
61
62 // Modal background
63 .modal-backdrop {
64 position: fixed;
65 top: 0;
66 right: 0;
67 bottom: 0;
68 left: 0;
69 z-index: @zindex-modal-background;
70 background-color: @modal-backdrop-bg;
71 // Fade for backdrop
72 &.fade { .opacity(0); }
73 &.in { .opacity(@modal-backdrop-opacity); }
74 }
75
76 // Modal header
77 // Top section of the modal w/ title and dismiss
78 .modal-header {
79 padding: @modal-title-padding;
80 border-bottom: 1px solid @modal-header-border-color;
81 min-height: (@modal-title-padding + @modal-title-line-height);
82 }
83 // Close icon
84 .modal-header .close {
85 margin-top: -2px;
86 }
87
88 // Title text within header
89 .modal-title {
90 margin: 0;
91 line-height: @modal-title-line-height;
92 }
93
94 // Modal body
95 // Where all modal content resides (sibling of .modal-header and .modal-footer)
96 .modal-body {
97 position: relative;
98 padding: @modal-inner-padding;
99 }
100
101 // Footer (for actions)
102 .modal-footer {
103 padding: @modal-inner-padding;
104 text-align: right; // right align buttons
105 border-top: 1px solid @modal-footer-border-color;
106 &:extend(.clearfix all); // clear it in case folks use .pull-* classes on buttons
107
108 // Properly space out buttons
109 .btn + .btn {
110 margin-left: 5px;
111 margin-bottom: 0; // account for input[type="submit"] which gets the bottom margin like all other inputs
112 }
113 // but override that for button groups
114 .btn-group .btn + .btn {
115 margin-left: -1px;
116 }
117 // and override it for block buttons as well
118 .btn-block + .btn-block {
119 margin-left: 0;
120 }
121 }
122
123 // Measure scrollbar width for padding body during modal show/hide
124 .modal-scrollbar-measure {
125 position: absolute;
126 top: -9999px;
127 width: 50px;
128 height: 50px;
129 overflow: scroll;
130 }
131
132 // Scale up the modal
133 @media (min-width: @screen-sm-min) {
134 // Automatically set modal's width for larger viewports
135 .modal-dialog {
136 width: @modal-md;
137 margin: 30px auto;
138 }
139 .modal-content {
140 .box-shadow(0 5px 15px rgba(0,0,0,.5));
141 }
142
143 // Modal sizes
144 .modal-sm { width: @modal-sm; }
145 }
146
147 @media (min-width: @screen-md-min) {
148 .modal-lg { width: @modal-lg; }
149 }
+0
-660
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/navbar.less less more
0 //
1 // Navbars
2 // --------------------------------------------------
3
4
5 // Wrapper and base class
6 //
7 // Provide a static navbar from which we expand to create full-width, fixed, and
8 // other navbar variations.
9
10 .navbar {
11 position: relative;
12 min-height: @navbar-height; // Ensure a navbar always shows (e.g., without a .navbar-brand in collapsed mode)
13 margin-bottom: @navbar-margin-bottom;
14 border: 1px solid transparent;
15
16 // Prevent floats from breaking the navbar
17 &:extend(.clearfix all);
18
19 @media (min-width: @grid-float-breakpoint) {
20 border-radius: @navbar-border-radius;
21 }
22 }
23
24
25 // Navbar heading
26 //
27 // Groups `.navbar-brand` and `.navbar-toggle` into a single component for easy
28 // styling of responsive aspects.
29
30 .navbar-header {
31 &:extend(.clearfix all);
32
33 @media (min-width: @grid-float-breakpoint) {
34 float: left;
35 }
36 }
37
38
39 // Navbar collapse (body)
40 //
41 // Group your navbar content into this for easy collapsing and expanding across
42 // various device sizes. By default, this content is collapsed when <768px, but
43 // will expand past that for a horizontal display.
44 //
45 // To start (on mobile devices) the navbar links, forms, and buttons are stacked
46 // vertically and include a `max-height` to overflow in case you have too much
47 // content for the user's viewport.
48
49 .navbar-collapse {
50 overflow-x: visible;
51 padding-right: @navbar-padding-horizontal;
52 padding-left: @navbar-padding-horizontal;
53 border-top: 1px solid transparent;
54 box-shadow: inset 0 1px 0 rgba(255,255,255,.1);
55 &:extend(.clearfix all);
56 -webkit-overflow-scrolling: touch;
57
58 &.in {
59 overflow-y: auto;
60 }
61
62 @media (min-width: @grid-float-breakpoint) {
63 width: auto;
64 border-top: 0;
65 box-shadow: none;
66
67 &.collapse {
68 display: block !important;
69 height: auto !important;
70 padding-bottom: 0; // Override default setting
71 overflow: visible !important;
72 }
73
74 &.in {
75 overflow-y: visible;
76 }
77
78 // Undo the collapse side padding for navbars with containers to ensure
79 // alignment of right-aligned contents.
80 .navbar-fixed-top &,
81 .navbar-static-top &,
82 .navbar-fixed-bottom & {
83 padding-left: 0;
84 padding-right: 0;
85 }
86 }
87 }
88
89 .navbar-fixed-top,
90 .navbar-fixed-bottom {
91 .navbar-collapse {
92 max-height: @navbar-collapse-max-height;
93
94 @media (max-device-width: @screen-xs-min) and (orientation: landscape) {
95 max-height: 200px;
96 }
97 }
98 }
99
100
101 // Both navbar header and collapse
102 //
103 // When a container is present, change the behavior of the header and collapse.
104
105 .tb-container,
106 .container-fluid {
107 > .navbar-header,
108 > .navbar-collapse {
109 margin-right: -@navbar-padding-horizontal;
110 margin-left: -@navbar-padding-horizontal;
111
112 @media (min-width: @grid-float-breakpoint) {
113 margin-right: 0;
114 margin-left: 0;
115 }
116 }
117 }
118
119
120 //
121 // Navbar alignment options
122 //
123 // Display the navbar across the entirety of the page or fixed it to the top or
124 // bottom of the page.
125
126 // Static top (unfixed, but 100% wide) navbar
127 .navbar-static-top {
128 z-index: @zindex-navbar;
129 border-width: 0 0 1px;
130
131 @media (min-width: @grid-float-breakpoint) {
132 border-radius: 0;
133 }
134 }
135
136 // Fix the top/bottom navbars when screen real estate supports it
137 .navbar-fixed-top,
138 .navbar-fixed-bottom {
139 position: fixed;
140 right: 0;
141 left: 0;
142 z-index: @zindex-navbar-fixed;
143
144 // Undo the rounded corners
145 @media (min-width: @grid-float-breakpoint) {
146 border-radius: 0;
147 }
148 }
149 .navbar-fixed-top {
150 top: 0;
151 border-width: 0 0 1px;
152 }
153 .navbar-fixed-bottom {
154 bottom: 0;
155 margin-bottom: 0; // override .navbar defaults
156 border-width: 1px 0 0;
157 }
158
159
160 // Brand/project name
161
162 .navbar-brand {
163 float: left;
164 padding: @navbar-padding-vertical @navbar-padding-horizontal;
165 font-size: @font-size-large;
166 line-height: @line-height-computed;
167 height: @navbar-height;
168
169 &:hover,
170 &:focus {
171 text-decoration: none;
172 }
173
174 > img {
175 display: block;
176 }
177
178 @media (min-width: @grid-float-breakpoint) {
179 .navbar > .tb-container &,
180 .navbar > .container-fluid & {
181 margin-left: -@navbar-padding-horizontal;
182 }
183 }
184 }
185
186
187 // Navbar toggle
188 //
189 // Custom button for toggling the `.navbar-collapse`, powered by the collapse
190 // JavaScript plugin.
191
192 .navbar-toggle {
193 position: relative;
194 float: right;
195 margin-right: @navbar-padding-horizontal;
196 padding: 9px 10px;
197 .navbar-vertical-align(34px);
198 background-color: transparent;
199 background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214
200 border: 1px solid transparent;
201 border-radius: @border-radius-base;
202
203 // We remove the `outline` here, but later compensate by attaching `:hover`
204 // styles to `:focus`.
205 &:focus {
206 outline: 0;
207 }
208
209 // Bars
210 .icon-bar {
211 display: block;
212 width: 22px;
213 height: 2px;
214 border-radius: 1px;
215 }
216 .icon-bar + .icon-bar {
217 margin-top: 4px;
218 }
219
220 @media (min-width: @grid-float-breakpoint) {
221 display: none;
222 }
223 }
224
225
226 // Navbar nav links
227 //
228 // Builds on top of the `.nav` components with its own modifier class to make
229 // the nav the full height of the horizontal nav (above 768px).
230
231 .navbar-nav {
232 margin: (@navbar-padding-vertical / 2) -@navbar-padding-horizontal;
233
234 > li > a {
235 padding-top: 10px;
236 padding-bottom: 10px;
237 line-height: @line-height-computed;
238 }
239
240 @media (max-width: @grid-float-breakpoint-max) {
241 // Dropdowns get custom display when collapsed
242 .open .dropdown-menu {
243 position: static;
244 float: none;
245 width: auto;
246 margin-top: 0;
247 background-color: transparent;
248 border: 0;
249 box-shadow: none;
250 > li > a,
251 .dropdown-header {
252 padding: 5px 15px 5px 25px;
253 }
254 > li > a {
255 line-height: @line-height-computed;
256 &:hover,
257 &:focus {
258 background-image: none;
259 }
260 }
261 }
262 }
263
264 // Uncollapse the nav
265 @media (min-width: @grid-float-breakpoint) {
266 float: left;
267 margin: 0;
268
269 > li {
270 float: left;
271 > a {
272 padding-top: @navbar-padding-vertical;
273 padding-bottom: @navbar-padding-vertical;
274 }
275 }
276 }
277 }
278
279
280 // Navbar form
281 //
282 // Extension of the `.form-inline` with some extra flavor for optimum display in
283 // our navbars.
284
285 .navbar-form {
286 margin-left: -@navbar-padding-horizontal;
287 margin-right: -@navbar-padding-horizontal;
288 padding: 10px @navbar-padding-horizontal;
289 border-top: 1px solid transparent;
290 border-bottom: 1px solid transparent;
291 @shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);
292 .box-shadow(@shadow);
293
294 // Mixin behavior for optimum display
295 .form-inline();
296
297 .form-group {
298 @media (max-width: @grid-float-breakpoint-max) {
299 margin-bottom: 5px;
300
301 &:last-child {
302 margin-bottom: 0;
303 }
304 }
305 }
306
307 // Vertically center in expanded, horizontal navbar
308 .navbar-vertical-align(@input-height-base);
309
310 // Undo 100% width for pull classes
311 @media (min-width: @grid-float-breakpoint) {
312 width: auto;
313 border: 0;
314 margin-left: 0;
315 margin-right: 0;
316 padding-top: 0;
317 padding-bottom: 0;
318 .box-shadow(none);
319 }
320 }
321
322
323 // Dropdown menus
324
325 // Menu position and menu carets
326 .navbar-nav > li > .dropdown-menu {
327 margin-top: 0;
328 .border-top-radius(0);
329 }
330 // Menu position and menu caret support for dropups via extra dropup class
331 .navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
332 margin-bottom: 0;
333 .border-top-radius(@navbar-border-radius);
334 .border-bottom-radius(0);
335 }
336
337
338 // Buttons in navbars
339 //
340 // Vertically center a button within a navbar (when *not* in a form).
341
342 .navbar-btn {
343 .navbar-vertical-align(@input-height-base);
344
345 &.btn-sm {
346 .navbar-vertical-align(@input-height-small);
347 }
348 &.btn-xs {
349 .navbar-vertical-align(22);
350 }
351 }
352
353
354 // Text in navbars
355 //
356 // Add a class to make any element properly align itself vertically within the navbars.
357
358 .navbar-text {
359 .navbar-vertical-align(@line-height-computed);
360
361 @media (min-width: @grid-float-breakpoint) {
362 float: left;
363 margin-left: @navbar-padding-horizontal;
364 margin-right: @navbar-padding-horizontal;
365 }
366 }
367
368
369 // Component alignment
370 //
371 // Repurpose the pull utilities as their own navbar utilities to avoid specificity
372 // issues with parents and chaining. Only do this when the navbar is uncollapsed
373 // though so that navbar contents properly stack and align in mobile.
374 //
375 // Declared after the navbar components to ensure more specificity on the margins.
376
377 @media (min-width: @grid-float-breakpoint) {
378 .navbar-left { .pull-left(); }
379 .navbar-right {
380 .pull-right();
381 margin-right: -@navbar-padding-horizontal;
382
383 ~ .navbar-right {
384 margin-right: 0;
385 }
386 }
387 }
388
389
390 // Alternate navbars
391 // --------------------------------------------------
392
393 // Default navbar
394 .navbar-default {
395 background-color: @navbar-default-bg;
396 border-color: @navbar-default-border;
397
398 .navbar-brand {
399 color: @navbar-default-brand-color;
400 &:hover,
401 &:focus {
402 color: @navbar-default-brand-hover-color;
403 background-color: @navbar-default-brand-hover-bg;
404 }
405 }
406
407 .navbar-text {
408 color: @navbar-default-color;
409 }
410
411 .navbar-nav {
412 > li > a {
413 color: @navbar-default-link-color;
414
415 &:hover,
416 &:focus {
417 color: @navbar-default-link-hover-color;
418 background-color: @navbar-default-link-hover-bg;
419 }
420 }
421 > .active > a {
422 &,
423 &:hover,
424 &:focus {
425 color: @navbar-default-link-active-color;
426 background-color: @navbar-default-link-active-bg;
427 }
428 }
429 > .disabled > a {
430 &,
431 &:hover,
432 &:focus {
433 color: @navbar-default-link-disabled-color;
434 background-color: @navbar-default-link-disabled-bg;
435 }
436 }
437 }
438
439 .navbar-toggle {
440 border-color: @navbar-default-toggle-border-color;
441 &:hover,
442 &:focus {
443 background-color: @navbar-default-toggle-hover-bg;
444 }
445 .icon-bar {
446 background-color: @navbar-default-toggle-icon-bar-bg;
447 }
448 }
449
450 .navbar-collapse,
451 .navbar-form {
452 border-color: @navbar-default-border;
453 }
454
455 // Dropdown menu items
456 .navbar-nav {
457 // Remove background color from open dropdown
458 > .open > a {
459 &,
460 &:hover,
461 &:focus {
462 background-color: @navbar-default-link-active-bg;
463 color: @navbar-default-link-active-color;
464 }
465 }
466
467 @media (max-width: @grid-float-breakpoint-max) {
468 // Dropdowns get custom display when collapsed
469 .open .dropdown-menu {
470 > li > a {
471 color: @navbar-default-link-color;
472 &:hover,
473 &:focus {
474 color: @navbar-default-link-hover-color;
475 background-color: @navbar-default-link-hover-bg;
476 }
477 }
478 > .active > a {
479 &,
480 &:hover,
481 &:focus {
482 color: @navbar-default-link-active-color;
483 background-color: @navbar-default-link-active-bg;
484 }
485 }
486 > .disabled > a {
487 &,
488 &:hover,
489 &:focus {
490 color: @navbar-default-link-disabled-color;
491 background-color: @navbar-default-link-disabled-bg;
492 }
493 }
494 }
495 }
496 }
497
498
499 // Links in navbars
500 //
501 // Add a class to ensure links outside the navbar nav are colored correctly.
502
503 .navbar-link {
504 color: @navbar-default-link-color;
505 &:hover {
506 color: @navbar-default-link-hover-color;
507 }
508 }
509
510 .btn-link {
511 color: @navbar-default-link-color;
512 &:hover,
513 &:focus {
514 color: @navbar-default-link-hover-color;
515 }
516 &[disabled],
517 fieldset[disabled] & {
518 &:hover,
519 &:focus {
520 color: @navbar-default-link-disabled-color;
521 }
522 }
523 }
524 }
525
526 // Inverse navbar
527
528 .navbar-inverse {
529 background-color: @navbar-inverse-bg;
530 border-color: @navbar-inverse-border;
531
532 .navbar-brand {
533 color: @navbar-inverse-brand-color;
534 &:hover,
535 &:focus {
536 color: @navbar-inverse-brand-hover-color;
537 background-color: @navbar-inverse-brand-hover-bg;
538 }
539 }
540
541 .navbar-text {
542 color: @navbar-inverse-color;
543 }
544
545 .navbar-nav {
546 > li > a {
547 color: @navbar-inverse-link-color;
548
549 &:hover,
550 &:focus {
551 color: @navbar-inverse-link-hover-color;
552 background-color: @navbar-inverse-link-hover-bg;
553 }
554 }
555 > .active > a {
556 &,
557 &:hover,
558 &:focus {
559 color: @navbar-inverse-link-active-color;
560 background-color: @navbar-inverse-link-active-bg;
561 }
562 }
563 > .disabled > a {
564 &,
565 &:hover,
566 &:focus {
567 color: @navbar-inverse-link-disabled-color;
568 background-color: @navbar-inverse-link-disabled-bg;
569 }
570 }
571 }
572
573 // Darken the responsive nav toggle
574 .navbar-toggle {
575 border-color: @navbar-inverse-toggle-border-color;
576 &:hover,
577 &:focus {
578 background-color: @navbar-inverse-toggle-hover-bg;
579 }
580 .icon-bar {
581 background-color: @navbar-inverse-toggle-icon-bar-bg;
582 }
583 }
584
585 .navbar-collapse,
586 .navbar-form {
587 border-color: darken(@navbar-inverse-bg, 7%);
588 }
589
590 // Dropdowns
591 .navbar-nav {
592 > .open > a {
593 &,
594 &:hover,
595 &:focus {
596 background-color: @navbar-inverse-link-active-bg;
597 color: @navbar-inverse-link-active-color;
598 }
599 }
600
601 @media (max-width: @grid-float-breakpoint-max) {
602 // Dropdowns get custom display
603 .open .dropdown-menu {
604 > .dropdown-header {
605 border-color: @navbar-inverse-border;
606 }
607 .divider {
608 background-color: @navbar-inverse-border;
609 }
610 > li > a {
611 color: @navbar-inverse-link-color;
612 &:hover,
613 &:focus {
614 color: @navbar-inverse-link-hover-color;
615 background-color: @navbar-inverse-link-hover-bg;
616 }
617 }
618 > .active > a {
619 &,
620 &:hover,
621 &:focus {
622 color: @navbar-inverse-link-active-color;
623 background-color: @navbar-inverse-link-active-bg;
624 }
625 }
626 > .disabled > a {
627 &,
628 &:hover,
629 &:focus {
630 color: @navbar-inverse-link-disabled-color;
631 background-color: @navbar-inverse-link-disabled-bg;
632 }
633 }
634 }
635 }
636 }
637
638 .navbar-link {
639 color: @navbar-inverse-link-color;
640 &:hover {
641 color: @navbar-inverse-link-hover-color;
642 }
643 }
644
645 .btn-link {
646 color: @navbar-inverse-link-color;
647 &:hover,
648 &:focus {
649 color: @navbar-inverse-link-hover-color;
650 }
651 &[disabled],
652 fieldset[disabled] & {
653 &:hover,
654 &:focus {
655 color: @navbar-inverse-link-disabled-color;
656 }
657 }
658 }
659 }
+0
-242
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/navs.less less more
0 //
1 // Navs
2 // --------------------------------------------------
3
4
5 // Base class
6 // --------------------------------------------------
7
8 .nav {
9 margin-bottom: 0;
10 padding-left: 0; // Override default ul/ol
11 list-style: none;
12 &:extend(.clearfix all);
13
14 > li {
15 position: relative;
16 display: block;
17
18 > a {
19 position: relative;
20 display: block;
21 padding: @nav-link-padding;
22 &:hover,
23 &:focus {
24 text-decoration: none;
25 background-color: @nav-link-hover-bg;
26 }
27 }
28
29 // Disabled state sets text to gray and nukes hover/tab effects
30 &.disabled > a {
31 color: @nav-disabled-link-color;
32
33 &:hover,
34 &:focus {
35 color: @nav-disabled-link-hover-color;
36 text-decoration: none;
37 background-color: transparent;
38 cursor: @cursor-disabled;
39 }
40 }
41 }
42
43 // Open dropdowns
44 .open > a {
45 &,
46 &:hover,
47 &:focus {
48 background-color: @nav-link-hover-bg;
49 border-color: @link-color;
50 }
51 }
52
53 // Nav dividers (deprecated with v3.0.1)
54 //
55 // This should have been removed in v3 with the dropping of `.nav-list`, but
56 // we missed it. We don't currently support this anywhere, but in the interest
57 // of maintaining backward compatibility in case you use it, it's deprecated.
58 .nav-divider {
59 .nav-divider();
60 }
61
62 // Prevent IE8 from misplacing imgs
63 //
64 // See https://github.com/h5bp/html5-boilerplate/issues/984#issuecomment-3985989
65 > li > a > img {
66 max-width: none;
67 }
68 }
69
70
71 // Tabs
72 // -------------------------
73
74 // Give the tabs something to sit on
75 .nav-tabs {
76 border-bottom: 1px solid @nav-tabs-border-color;
77 > li {
78 float: left;
79 // Make the list-items overlay the bottom border
80 margin-bottom: -1px;
81
82 // Actual tabs (as links)
83 > a {
84 margin-right: 2px;
85 line-height: @line-height-base;
86 border: 1px solid transparent;
87 border-radius: @border-radius-base @border-radius-base 0 0;
88 &:hover {
89 border-color: @nav-tabs-link-hover-border-color @nav-tabs-link-hover-border-color @nav-tabs-border-color;
90 }
91 }
92
93 // Active state, and its :hover to override normal :hover
94 &.active > a {
95 &,
96 &:hover,
97 &:focus {
98 color: @nav-tabs-active-link-hover-color;
99 background-color: @nav-tabs-active-link-hover-bg;
100 border: 1px solid @nav-tabs-active-link-hover-border-color;
101 border-bottom-color: transparent;
102 cursor: default;
103 }
104 }
105 }
106 // pulling this in mainly for less shorthand
107 &.nav-justified {
108 .nav-justified();
109 .nav-tabs-justified();
110 }
111 }
112
113
114 // Pills
115 // -------------------------
116 .nav-pills {
117 > li {
118 float: left;
119
120 // Links rendered as pills
121 > a {
122 border-radius: @nav-pills-border-radius;
123 }
124 + li {
125 margin-left: 2px;
126 }
127
128 // Active state
129 &.active > a {
130 &,
131 &:hover,
132 &:focus {
133 color: @nav-pills-active-link-hover-color;
134 background-color: @nav-pills-active-link-hover-bg;
135 }
136 }
137 }
138 }
139
140
141 // Stacked pills
142 .nav-stacked {
143 > li {
144 float: none;
145 + li {
146 margin-top: 2px;
147 margin-left: 0; // no need for this gap between nav items
148 }
149 }
150 }
151
152
153 // Nav variations
154 // --------------------------------------------------
155
156 // Justified nav links
157 // -------------------------
158
159 .nav-justified {
160 width: 100%;
161
162 > li {
163 float: none;
164 > a {
165 text-align: center;
166 margin-bottom: 5px;
167 }
168 }
169
170 > .dropdown .dropdown-menu {
171 top: auto;
172 left: auto;
173 }
174
175 @media (min-width: @screen-sm-min) {
176 > li {
177 display: table-cell;
178 width: 1%;
179 > a {
180 margin-bottom: 0;
181 }
182 }
183 }
184 }
185
186 // Move borders to anchors instead of bottom of list
187 //
188 // Mixin for adding on top the shared `.nav-justified` styles for our tabs
189 .nav-tabs-justified {
190 border-bottom: 0;
191
192 > li > a {
193 // Override margin from .nav-tabs
194 margin-right: 0;
195 border-radius: @border-radius-base;
196 }
197
198 > .active > a,
199 > .active > a:hover,
200 > .active > a:focus {
201 border: 1px solid @nav-tabs-justified-link-border-color;
202 }
203
204 @media (min-width: @screen-sm-min) {
205 > li > a {
206 border-bottom: 1px solid @nav-tabs-justified-link-border-color;
207 border-radius: @border-radius-base @border-radius-base 0 0;
208 }
209 > .active > a,
210 > .active > a:hover,
211 > .active > a:focus {
212 border-bottom-color: @nav-tabs-justified-active-link-border-color;
213 }
214 }
215 }
216
217
218 // Tabbable tabs
219 // -------------------------
220
221 // Hide tabbable panes to start, show them when `.active`
222 .tab-content {
223 > .tab-pane {
224 display: none;
225 }
226 > .active {
227 display: block;
228 }
229 }
230
231
232 // Dropdowns
233 // -------------------------
234
235 // Specific dropdowns
236 .nav-tabs .dropdown-menu {
237 // make dropdown border overlap tab border
238 margin-top: -1px;
239 // Remove the top rounded corners here since there is a hard edge above the menu
240 .border-top-radius(0);
241 }
+0
-427
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/normalize.less less more
0 /*! normalize.css v3.0.2 | MIT License | git.io/normalize */
1
2 //
3 // 1. Set default font family to sans-serif.
4 // 2. Prevent iOS text size adjust after orientation change, without disabling
5 // user zoom.
6 //
7
8 html {
9 font-family: sans-serif; // 1
10 -ms-text-size-adjust: 100%; // 2
11 -webkit-text-size-adjust: 100%; // 2
12 }
13
14 //
15 // Remove default margin.
16 //
17
18 body {
19 margin: 0;
20 }
21
22 // HTML5 display definitions
23 // ==========================================================================
24
25 //
26 // Correct `block` display not defined for any HTML5 element in IE 8/9.
27 // Correct `block` display not defined for `details` or `summary` in IE 10/11
28 // and Firefox.
29 // Correct `block` display not defined for `main` in IE 11.
30 //
31
32 article,
33 aside,
34 details,
35 figcaption,
36 figure,
37 footer,
38 header,
39 hgroup,
40 main,
41 menu,
42 nav,
43 section,
44 summary {
45 display: block;
46 }
47
48 //
49 // 1. Correct `inline-block` display not defined in IE 8/9.
50 // 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
51 //
52
53 audio,
54 canvas,
55 progress,
56 video {
57 display: inline-block; // 1
58 vertical-align: baseline; // 2
59 }
60
61 //
62 // Prevent modern browsers from displaying `audio` without controls.
63 // Remove excess height in iOS 5 devices.
64 //
65
66 audio:not([controls]) {
67 display: none;
68 height: 0;
69 }
70
71 //
72 // Address `[hidden]` styling not present in IE 8/9/10.
73 // Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.
74 //
75
76 [hidden],
77 template {
78 display: none;
79 }
80
81 // Links
82 // ==========================================================================
83
84 //
85 // Remove the gray background color from active links in IE 10.
86 //
87
88 a {
89 background-color: transparent;
90 }
91
92 //
93 // Improve readability when focused and also mouse hovered in all browsers.
94 //
95
96 a:active,
97 a:hover {
98 outline: 0;
99 }
100
101 // Text-level semantics
102 // ==========================================================================
103
104 //
105 // Address styling not present in IE 8/9/10/11, Safari, and Chrome.
106 //
107
108 abbr[title] {
109 border-bottom: 1px dotted;
110 }
111
112 //
113 // Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
114 //
115
116 b,
117 strong {
118 font-weight: bold;
119 }
120
121 //
122 // Address styling not present in Safari and Chrome.
123 //
124
125 dfn {
126 font-style: italic;
127 }
128
129 //
130 // Address variable `h1` font-size and margin within `section` and `article`
131 // contexts in Firefox 4+, Safari, and Chrome.
132 //
133
134 h1 {
135 font-size: 2em;
136 margin: 0.67em 0;
137 }
138
139 //
140 // Address styling not present in IE 8/9.
141 //
142
143 mark {
144 background: #ff0;
145 color: #000;
146 }
147
148 //
149 // Address inconsistent and variable font size in all browsers.
150 //
151
152 small {
153 font-size: 80%;
154 }
155
156 //
157 // Prevent `sub` and `sup` affecting `line-height` in all browsers.
158 //
159
160 sub,
161 sup {
162 font-size: 75%;
163 line-height: 0;
164 position: relative;
165 vertical-align: baseline;
166 }
167
168 sup {
169 top: -0.5em;
170 }
171
172 sub {
173 bottom: -0.25em;
174 }
175
176 // Embedded content
177 // ==========================================================================
178
179 //
180 // Remove border when inside `a` element in IE 8/9/10.
181 //
182
183 img {
184 border: 0;
185 }
186
187 //
188 // Correct overflow not hidden in IE 9/10/11.
189 //
190
191 svg:not(:root) {
192 overflow: hidden;
193 }
194
195 // Grouping content
196 // ==========================================================================
197
198 //
199 // Address margin not present in IE 8/9 and Safari.
200 //
201
202 figure {
203 margin: 1em 40px;
204 }
205
206 //
207 // Address differences between Firefox and other browsers.
208 //
209
210 hr {
211 -moz-box-sizing: content-box;
212 box-sizing: content-box;
213 height: 0;
214 }
215
216 //
217 // Contain overflow in all browsers.
218 //
219
220 pre {
221 overflow: auto;
222 }
223
224 //
225 // Address odd `em`-unit font size rendering in all browsers.
226 //
227
228 code,
229 kbd,
230 pre,
231 samp {
232 font-family: monospace, monospace;
233 font-size: 1em;
234 }
235
236 // Forms
237 // ==========================================================================
238
239 //
240 // Known limitation: by default, Chrome and Safari on OS X allow very limited
241 // styling of `select`, unless a `border` property is set.
242 //
243
244 //
245 // 1. Correct color not being inherited.
246 // Known issue: affects color of disabled elements.
247 // 2. Correct font properties not being inherited.
248 // 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
249 //
250
251 button,
252 input,
253 optgroup,
254 select,
255 textarea {
256 color: inherit; // 1
257 font: inherit; // 2
258 margin: 0; // 3
259 }
260
261 //
262 // Address `overflow` set to `hidden` in IE 8/9/10/11.
263 //
264
265 button {
266 overflow: visible;
267 }
268
269 //
270 // Address inconsistent `text-transform` inheritance for `button` and `select`.
271 // All other form control elements do not inherit `text-transform` values.
272 // Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
273 // Correct `select` style inheritance in Firefox.
274 //
275
276 button,
277 select {
278 text-transform: none;
279 }
280
281 //
282 // 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
283 // and `video` controls.
284 // 2. Correct inability to style clickable `input` types in iOS.
285 // 3. Improve usability and consistency of cursor style between image-type
286 // `input` and others.
287 //
288
289 button,
290 html input[type="button"], // 1
291 input[type="reset"],
292 input[type="submit"] {
293 -webkit-appearance: button; // 2
294 cursor: pointer; // 3
295 }
296
297 //
298 // Re-set default cursor for disabled elements.
299 //
300
301 button[disabled],
302 html input[disabled] {
303 cursor: default;
304 }
305
306 //
307 // Remove inner padding and border in Firefox 4+.
308 //
309
310 button::-moz-focus-inner,
311 input::-moz-focus-inner {
312 border: 0;
313 padding: 0;
314 }
315
316 //
317 // Address Firefox 4+ setting `line-height` on `input` using `!important` in
318 // the UA stylesheet.
319 //
320
321 input {
322 line-height: normal;
323 }
324
325 //
326 // It's recommended that you don't attempt to style these elements.
327 // Firefox's implementation doesn't respect box-sizing, padding, or width.
328 //
329 // 1. Address box sizing set to `content-box` in IE 8/9/10.
330 // 2. Remove excess padding in IE 8/9/10.
331 //
332
333 input[type="checkbox"],
334 input[type="radio"] {
335 box-sizing: border-box; // 1
336 padding: 0; // 2
337 }
338
339 //
340 // Fix the cursor style for Chrome's increment/decrement buttons. For certain
341 // `font-size` values of the `input`, it causes the cursor style of the
342 // decrement button to change from `default` to `text`.
343 //
344
345 input[type="number"]::-webkit-inner-spin-button,
346 input[type="number"]::-webkit-outer-spin-button {
347 height: auto;
348 }
349
350 //
351 // 1. Address `appearance` set to `searchfield` in Safari and Chrome.
352 // 2. Address `box-sizing` set to `border-box` in Safari and Chrome
353 // (include `-moz` to future-proof).
354 //
355
356 input[type="search"] {
357 -webkit-appearance: textfield; // 1
358 -moz-box-sizing: content-box;
359 -webkit-box-sizing: content-box; // 2
360 box-sizing: content-box;
361 }
362
363 //
364 // Remove inner padding and search cancel button in Safari and Chrome on OS X.
365 // Safari (but not Chrome) clips the cancel button when the search input has
366 // padding (and `textfield` appearance).
367 //
368
369 input[type="search"]::-webkit-search-cancel-button,
370 input[type="search"]::-webkit-search-decoration {
371 -webkit-appearance: none;
372 }
373
374 //
375 // Define consistent border, margin, and padding.
376 //
377
378 fieldset {
379 border: 1px solid #c0c0c0;
380 margin: 0 2px;
381 padding: 0.35em 0.625em 0.75em;
382 }
383
384 //
385 // 1. Correct `color` not being inherited in IE 8/9/10/11.
386 // 2. Remove padding so people aren't caught out if they zero out fieldsets.
387 //
388
389 legend {
390 border: 0; // 1
391 padding: 0; // 2
392 }
393
394 //
395 // Remove default vertical scrollbar in IE 8/9/10/11.
396 //
397
398 textarea {
399 overflow: auto;
400 }
401
402 //
403 // Don't inherit the `font-weight` (applied by a rule above).
404 // NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
405 //
406
407 optgroup {
408 font-weight: bold;
409 }
410
411 // Tables
412 // ==========================================================================
413
414 //
415 // Remove most spacing between table cells.
416 //
417
418 table {
419 border-collapse: collapse;
420 border-spacing: 0;
421 }
422
423 td,
424 th {
425 padding: 0;
426 }
+0
-54
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/pager.less less more
0 //
1 // Pager pagination
2 // --------------------------------------------------
3
4
5 .pager {
6 padding-left: 0;
7 margin: @line-height-computed 0;
8 list-style: none;
9 text-align: center;
10 &:extend(.clearfix all);
11 li {
12 display: inline;
13 > a,
14 > span {
15 display: inline-block;
16 padding: 5px 14px;
17 background-color: @pager-bg;
18 border: 1px solid @pager-border;
19 border-radius: @pager-border-radius;
20 }
21
22 > a:hover,
23 > a:focus {
24 text-decoration: none;
25 background-color: @pager-hover-bg;
26 }
27 }
28
29 .next {
30 > a,
31 > span {
32 float: right;
33 }
34 }
35
36 .previous {
37 > a,
38 > span {
39 float: left;
40 }
41 }
42
43 .disabled {
44 > a,
45 > a:hover,
46 > a:focus,
47 > span {
48 color: @pager-disabled-color;
49 background-color: @pager-bg;
50 cursor: @cursor-disabled;
51 }
52 }
53 }
+0
-88
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/pagination.less less more
0 //
1 // Pagination (multiple pages)
2 // --------------------------------------------------
3 .pagination {
4 display: inline-block;
5 padding-left: 0;
6 margin: @line-height-computed 0;
7 border-radius: @border-radius-base;
8
9 > li {
10 display: inline; // Remove list-style and block-level defaults
11 > a,
12 > span {
13 position: relative;
14 float: left; // Collapse white-space
15 padding: @padding-base-vertical @padding-base-horizontal;
16 line-height: @line-height-base;
17 text-decoration: none;
18 color: @pagination-color;
19 background-color: @pagination-bg;
20 border: 1px solid @pagination-border;
21 margin-left: -1px;
22 }
23 &:first-child {
24 > a,
25 > span {
26 margin-left: 0;
27 .border-left-radius(@border-radius-base);
28 }
29 }
30 &:last-child {
31 > a,
32 > span {
33 .border-right-radius(@border-radius-base);
34 }
35 }
36 }
37
38 > li > a,
39 > li > span {
40 &:hover,
41 &:focus {
42 color: @pagination-hover-color;
43 background-color: @pagination-hover-bg;
44 border-color: @pagination-hover-border;
45 }
46 }
47
48 > .active > a,
49 > .active > span {
50 &,
51 &:hover,
52 &:focus {
53 z-index: 2;
54 color: @pagination-active-color;
55 background-color: @pagination-active-bg;
56 border-color: @pagination-active-border;
57 cursor: default;
58 }
59 }
60
61 > .disabled {
62 > span,
63 > span:hover,
64 > span:focus,
65 > a,
66 > a:hover,
67 > a:focus {
68 color: @pagination-disabled-color;
69 background-color: @pagination-disabled-bg;
70 border-color: @pagination-disabled-border;
71 cursor: @cursor-disabled;
72 }
73 }
74 }
75
76 // Sizing
77 // --------------------------------------------------
78
79 // Large
80 .pagination-lg {
81 .pagination-size(@padding-large-vertical; @padding-large-horizontal; @font-size-large; @border-radius-large);
82 }
83
84 // Small
85 .pagination-sm {
86 .pagination-size(@padding-small-vertical; @padding-small-horizontal; @font-size-small; @border-radius-small);
87 }
+0
-265
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/panels.less less more
0 //
1 // Panels
2 // --------------------------------------------------
3
4
5 // Base class
6 .panel {
7 margin-bottom: @line-height-computed;
8 background-color: @panel-bg;
9 border: 1px solid transparent;
10 border-radius: @panel-border-radius;
11 .box-shadow(0 1px 1px rgba(0,0,0,.05));
12 }
13
14 // Panel contents
15 .panel-body {
16 padding: @panel-body-padding;
17 &:extend(.clearfix all);
18 }
19
20 // Optional heading
21 .panel-heading {
22 padding: @panel-heading-padding;
23 border-bottom: 1px solid transparent;
24 .border-top-radius((@panel-border-radius - 1));
25
26 > .dropdown .dropdown-toggle {
27 color: inherit;
28 }
29 }
30
31 // Within heading, strip any `h*` tag of its default margins for spacing.
32 .panel-title {
33 margin-top: 0;
34 margin-bottom: 0;
35 font-size: ceil((@font-size-base * 1.125));
36 color: inherit;
37
38 > a,
39 > small,
40 > .small,
41 > small > a,
42 > .small > a {
43 color: inherit;
44 }
45 }
46
47 // Optional footer (stays gray in every modifier class)
48 .panel-footer {
49 padding: @panel-footer-padding;
50 background-color: @panel-footer-bg;
51 border-top: 1px solid @panel-inner-border;
52 .border-bottom-radius((@panel-border-radius - 1));
53 }
54
55
56 // List groups in panels
57 //
58 // By default, space out list group content from panel headings to account for
59 // any kind of custom content between the two.
60
61 .panel {
62 > .list-group,
63 > .panel-collapse > .list-group {
64 margin-bottom: 0;
65
66 .list-group-item {
67 border-width: 1px 0;
68 border-radius: 0;
69 }
70
71 // Add border top radius for first one
72 &:first-child {
73 .list-group-item:first-child {
74 border-top: 0;
75 .border-top-radius((@panel-border-radius - 1));
76 }
77 }
78 // Add border bottom radius for last one
79 &:last-child {
80 .list-group-item:last-child {
81 border-bottom: 0;
82 .border-bottom-radius((@panel-border-radius - 1));
83 }
84 }
85 }
86 }
87 // Collapse space between when there's no additional content.
88 .panel-heading + .list-group {
89 .list-group-item:first-child {
90 border-top-width: 0;
91 }
92 }
93 .list-group + .panel-footer {
94 border-top-width: 0;
95 }
96
97 // Tables in panels
98 //
99 // Place a non-bordered `.table` within a panel (not within a `.panel-body`) and
100 // watch it go full width.
101
102 .panel {
103 > .table,
104 > .table-responsive > .table,
105 > .panel-collapse > .table {
106 margin-bottom: 0;
107
108 caption {
109 padding-left: @panel-body-padding;
110 padding-right: @panel-body-padding;
111 }
112 }
113 // Add border top radius for first one
114 > .table:first-child,
115 > .table-responsive:first-child > .table:first-child {
116 .border-top-radius((@panel-border-radius - 1));
117
118 > thead:first-child,
119 > tbody:first-child {
120 > tr:first-child {
121 border-top-left-radius: (@panel-border-radius - 1);
122 border-top-right-radius: (@panel-border-radius - 1);
123
124 td:first-child,
125 th:first-child {
126 border-top-left-radius: (@panel-border-radius - 1);
127 }
128 td:last-child,
129 th:last-child {
130 border-top-right-radius: (@panel-border-radius - 1);
131 }
132 }
133 }
134 }
135 // Add border bottom radius for last one
136 > .table:last-child,
137 > .table-responsive:last-child > .table:last-child {
138 .border-bottom-radius((@panel-border-radius - 1));
139
140 > tbody:last-child,
141 > tfoot:last-child {
142 > tr:last-child {
143 border-bottom-left-radius: (@panel-border-radius - 1);
144 border-bottom-right-radius: (@panel-border-radius - 1);
145
146 td:first-child,
147 th:first-child {
148 border-bottom-left-radius: (@panel-border-radius - 1);
149 }
150 td:last-child,
151 th:last-child {
152 border-bottom-right-radius: (@panel-border-radius - 1);
153 }
154 }
155 }
156 }
157 > .panel-body + .table,
158 > .panel-body + .table-responsive,
159 > .table + .panel-body,
160 > .table-responsive + .panel-body {
161 border-top: 1px solid @table-border-color;
162 }
163 > .table > tbody:first-child > tr:first-child th,
164 > .table > tbody:first-child > tr:first-child td {
165 border-top: 0;
166 }
167 > .table-bordered,
168 > .table-responsive > .table-bordered {
169 border: 0;
170 > thead,
171 > tbody,
172 > tfoot {
173 > tr {
174 > th:first-child,
175 > td:first-child {
176 border-left: 0;
177 }
178 > th:last-child,
179 > td:last-child {
180 border-right: 0;
181 }
182 }
183 }
184 > thead,
185 > tbody {
186 > tr:first-child {
187 > td,
188 > th {
189 border-bottom: 0;
190 }
191 }
192 }
193 > tbody,
194 > tfoot {
195 > tr:last-child {
196 > td,
197 > th {
198 border-bottom: 0;
199 }
200 }
201 }
202 }
203 > .table-responsive {
204 border: 0;
205 margin-bottom: 0;
206 }
207 }
208
209
210 // Collapsable panels (aka, accordion)
211 //
212 // Wrap a series of panels in `.panel-group` to turn them into an accordion with
213 // the help of our collapse JavaScript plugin.
214
215 .panel-group {
216 margin-bottom: @line-height-computed;
217
218 // Tighten up margin so it's only between panels
219 .panel {
220 margin-bottom: 0;
221 border-radius: @panel-border-radius;
222
223 + .panel {
224 margin-top: 5px;
225 }
226 }
227
228 .panel-heading {
229 border-bottom: 0;
230
231 + .panel-collapse > .panel-body,
232 + .panel-collapse > .list-group {
233 border-top: 1px solid @panel-inner-border;
234 }
235 }
236
237 .panel-footer {
238 border-top: 0;
239 + .panel-collapse .panel-body {
240 border-bottom: 1px solid @panel-inner-border;
241 }
242 }
243 }
244
245
246 // Contextual variations
247 .panel-default {
248 .panel-variant(@panel-default-border; @panel-default-text; @panel-default-heading-bg; @panel-default-border);
249 }
250 .panel-primary {
251 .panel-variant(@panel-primary-border; @panel-primary-text; @panel-primary-heading-bg; @panel-primary-border);
252 }
253 .panel-success {
254 .panel-variant(@panel-success-border; @panel-success-text; @panel-success-heading-bg; @panel-success-border);
255 }
256 .panel-info {
257 .panel-variant(@panel-info-border; @panel-info-text; @panel-info-heading-bg; @panel-info-border);
258 }
259 .panel-warning {
260 .panel-variant(@panel-warning-border; @panel-warning-text; @panel-warning-heading-bg; @panel-warning-border);
261 }
262 .panel-danger {
263 .panel-variant(@panel-danger-border; @panel-danger-text; @panel-danger-heading-bg; @panel-danger-border);
264 }
+0
-135
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/popovers.less less more
0 //
1 // Popovers
2 // --------------------------------------------------
3
4
5 .popover {
6 position: absolute;
7 top: 0;
8 left: 0;
9 z-index: @zindex-popover;
10 display: none;
11 max-width: @popover-max-width;
12 padding: 1px;
13 // Reset font and text properties given new insertion method
14 font-family: @font-family-base;
15 font-size: @font-size-base;
16 font-weight: normal;
17 line-height: @line-height-base;
18 text-align: left;
19 background-color: @popover-bg;
20 background-clip: padding-box;
21 border: 1px solid @popover-fallback-border-color;
22 border: 1px solid @popover-border-color;
23 border-radius: @border-radius-large;
24 .box-shadow(0 5px 10px rgba(0,0,0,.2));
25
26 // Overrides for proper insertion
27 white-space: normal;
28
29 // Offset the popover to account for the popover arrow
30 &.top { margin-top: -@popover-arrow-width; }
31 &.right { margin-left: @popover-arrow-width; }
32 &.bottom { margin-top: @popover-arrow-width; }
33 &.left { margin-left: -@popover-arrow-width; }
34 }
35
36 .popover-title {
37 margin: 0; // reset heading margin
38 padding: 8px 14px;
39 font-size: @font-size-base;
40 background-color: @popover-title-bg;
41 border-bottom: 1px solid darken(@popover-title-bg, 5%);
42 border-radius: (@border-radius-large - 1) (@border-radius-large - 1) 0 0;
43 }
44
45 .popover-content {
46 padding: 9px 14px;
47 }
48
49 // Arrows
50 //
51 // .arrow is outer, .arrow:after is inner
52
53 .popover > .arrow {
54 &,
55 &:after {
56 position: absolute;
57 display: block;
58 width: 0;
59 height: 0;
60 border-color: transparent;
61 border-style: solid;
62 }
63 }
64 .popover > .arrow {
65 border-width: @popover-arrow-outer-width;
66 }
67 .popover > .arrow:after {
68 border-width: @popover-arrow-width;
69 content: "";
70 }
71
72 .popover {
73 &.top > .arrow {
74 left: 50%;
75 margin-left: -@popover-arrow-outer-width;
76 border-bottom-width: 0;
77 border-top-color: @popover-arrow-outer-fallback-color; // IE8 fallback
78 border-top-color: @popover-arrow-outer-color;
79 bottom: -@popover-arrow-outer-width;
80 &:after {
81 content: " ";
82 bottom: 1px;
83 margin-left: -@popover-arrow-width;
84 border-bottom-width: 0;
85 border-top-color: @popover-arrow-color;
86 }
87 }
88 &.right > .arrow {
89 top: 50%;
90 left: -@popover-arrow-outer-width;
91 margin-top: -@popover-arrow-outer-width;
92 border-left-width: 0;
93 border-right-color: @popover-arrow-outer-fallback-color; // IE8 fallback
94 border-right-color: @popover-arrow-outer-color;
95 &:after {
96 content: " ";
97 left: 1px;
98 bottom: -@popover-arrow-width;
99 border-left-width: 0;
100 border-right-color: @popover-arrow-color;
101 }
102 }
103 &.bottom > .arrow {
104 left: 50%;
105 margin-left: -@popover-arrow-outer-width;
106 border-top-width: 0;
107 border-bottom-color: @popover-arrow-outer-fallback-color; // IE8 fallback
108 border-bottom-color: @popover-arrow-outer-color;
109 top: -@popover-arrow-outer-width;
110 &:after {
111 content: " ";
112 top: 1px;
113 margin-left: -@popover-arrow-width;
114 border-top-width: 0;
115 border-bottom-color: @popover-arrow-color;
116 }
117 }
118
119 &.left > .arrow {
120 top: 50%;
121 right: -@popover-arrow-outer-width;
122 margin-top: -@popover-arrow-outer-width;
123 border-right-width: 0;
124 border-left-color: @popover-arrow-outer-fallback-color; // IE8 fallback
125 border-left-color: @popover-arrow-outer-color;
126 &:after {
127 content: " ";
128 right: 1px;
129 border-right-width: 0;
130 border-left-color: @popover-arrow-color;
131 bottom: -@popover-arrow-width;
132 }
133 }
134 }
+0
-107
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/print.less less more
0 /*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
1
2 // ==========================================================================
3 // Print styles.
4 // Inlined to avoid the additional HTTP request: h5bp.com/r
5 // ==========================================================================
6
7 @media print {
8 *,
9 *:before,
10 *:after {
11 background: transparent !important;
12 color: #000 !important; // Black prints faster: h5bp.com/s
13 box-shadow: none !important;
14 text-shadow: none !important;
15 }
16
17 a,
18 a:visited {
19 text-decoration: underline;
20 }
21
22 a[href]:after {
23 content: " (" attr(href) ")";
24 }
25
26 abbr[title]:after {
27 content: " (" attr(title) ")";
28 }
29
30 // Don't show links that are fragment identifiers,
31 // or use the `javascript:` pseudo protocol
32 a[href^="#"]:after,
33 a[href^="javascript:"]:after {
34 content: "";
35 }
36
37 pre,
38 blockquote {
39 border: 1px solid #999;
40 page-break-inside: avoid;
41 }
42
43 thead {
44 display: table-header-group; // h5bp.com/t
45 }
46
47 tr,
48 img {
49 page-break-inside: avoid;
50 }
51
52 img {
53 max-width: 100% !important;
54 }
55
56 p,
57 h2,
58 h3 {
59 orphans: 3;
60 widows: 3;
61 }
62
63 h2,
64 h3 {
65 page-break-after: avoid;
66 }
67
68 // Bootstrap specific changes start
69 //
70 // Chrome (OSX) fix for https://github.com/twbs/bootstrap/issues/11245
71 // Once fixed, we can just straight up remove this.
72 select {
73 background: #fff !important;
74 }
75
76 // Bootstrap components
77 .navbar {
78 display: none;
79 }
80 .btn,
81 .dropup > .btn {
82 > .caret {
83 border-top-color: #000 !important;
84 }
85 }
86 .label {
87 border: 1px solid #000;
88 }
89
90 .table {
91 border-collapse: collapse !important;
92
93 td,
94 th {
95 background-color: #fff !important;
96 }
97 }
98 .table-bordered {
99 th,
100 td {
101 border: 1px solid #ddd !important;
102 }
103 }
104
105 // Bootstrap specific changes end
106 }
+0
-87
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/progress-bars.less less more
0 //
1 // Progress bars
2 // --------------------------------------------------
3
4
5 // Bar animations
6 // -------------------------
7
8 // WebKit
9 @-webkit-keyframes progress-bar-stripes {
10 from { background-position: 40px 0; }
11 to { background-position: 0 0; }
12 }
13
14 // Spec and IE10+
15 @keyframes progress-bar-stripes {
16 from { background-position: 40px 0; }
17 to { background-position: 0 0; }
18 }
19
20
21 // Bar itself
22 // -------------------------
23
24 // Outer container
25 .progress {
26 overflow: hidden;
27 height: @line-height-computed;
28 margin-bottom: @line-height-computed;
29 background-color: @progress-bg;
30 border-radius: @progress-border-radius;
31 .box-shadow(inset 0 1px 2px rgba(0,0,0,.1));
32 }
33
34 // Bar of progress
35 .progress-bar {
36 float: left;
37 width: 0%;
38 height: 100%;
39 font-size: @font-size-small;
40 line-height: @line-height-computed;
41 color: @progress-bar-color;
42 text-align: center;
43 background-color: @progress-bar-bg;
44 .box-shadow(inset 0 -1px 0 rgba(0,0,0,.15));
45 .transition(width .6s ease);
46 }
47
48 // Striped bars
49 //
50 // `.progress-striped .progress-bar` is deprecated as of v3.2.0 in favor of the
51 // `.progress-bar-striped` class, which you just add to an existing
52 // `.progress-bar`.
53 .progress-striped .progress-bar,
54 .progress-bar-striped {
55 #gradient > .striped();
56 background-size: 40px 40px;
57 }
58
59 // Call animation for the active one
60 //
61 // `.progress.active .progress-bar` is deprecated as of v3.2.0 in favor of the
62 // `.progress-bar.active` approach.
63 .progress.active .progress-bar,
64 .progress-bar.active {
65 .animation(progress-bar-stripes 2s linear infinite);
66 }
67
68
69 // Variations
70 // -------------------------
71
72 .progress-bar-success {
73 .progress-bar-variant(@progress-bar-success-bg);
74 }
75
76 .progress-bar-info {
77 .progress-bar-variant(@progress-bar-info-bg);
78 }
79
80 .progress-bar-warning {
81 .progress-bar-variant(@progress-bar-warning-bg);
82 }
83
84 .progress-bar-danger {
85 .progress-bar-variant(@progress-bar-danger-bg);
86 }
+0
-35
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/responsive-embed.less less more
0 // Embeds responsive
1 //
2 // Credit: Nicolas Gallagher and SUIT CSS.
3
4 .embed-responsive {
5 position: relative;
6 display: block;
7 height: 0;
8 padding: 0;
9 overflow: hidden;
10
11 .embed-responsive-item,
12 iframe,
13 embed,
14 object,
15 video {
16 position: absolute;
17 top: 0;
18 left: 0;
19 bottom: 0;
20 height: 100%;
21 width: 100%;
22 border: 0;
23 }
24 }
25
26 // Modifier class for 16:9 aspect ratio
27 .embed-responsive-16by9 {
28 padding-bottom: 56.25%;
29 }
30
31 // Modifier class for 4:3 aspect ratio
32 .embed-responsive-4by3 {
33 padding-bottom: 75%;
34 }
+0
-194
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/responsive-utilities.less less more
0 //
1 // Responsive: Utility classes
2 // --------------------------------------------------
3
4
5 // IE10 in Windows (Phone) 8
6 //
7 // Support for responsive views via media queries is kind of borked in IE10, for
8 // Surface/desktop in split view and for Windows Phone 8. This particular fix
9 // must be accompanied by a snippet of JavaScript to sniff the user agent and
10 // apply some conditional CSS to *only* the Surface/desktop Windows 8. Look at
11 // our Getting Started page for more information on this bug.
12 //
13 // For more information, see the following:
14 //
15 // Issue: https://github.com/twbs/bootstrap/issues/10497
16 // Docs: http://getbootstrap.com/getting-started/#support-ie10-width
17 // Source: http://timkadlec.com/2013/01/windows-phone-8-and-device-width/
18 // Source: http://timkadlec.com/2012/10/ie10-snap-mode-and-responsive-design/
19
20 @-ms-viewport {
21 width: device-width;
22 }
23
24
25 // Visibility utilities
26 // Note: Deprecated .visible-xs, .visible-sm, .visible-md, and .visible-lg as of v3.2.0
27 .visible-xs,
28 .visible-sm,
29 .visible-md,
30 .visible-lg {
31 .responsive-invisibility();
32 }
33
34 .visible-xs-block,
35 .visible-xs-inline,
36 .visible-xs-inline-block,
37 .visible-sm-block,
38 .visible-sm-inline,
39 .visible-sm-inline-block,
40 .visible-md-block,
41 .visible-md-inline,
42 .visible-md-inline-block,
43 .visible-lg-block,
44 .visible-lg-inline,
45 .visible-lg-inline-block {
46 display: none !important;
47 }
48
49 .visible-xs {
50 @media (max-width: @screen-xs-max) {
51 .responsive-visibility();
52 }
53 }
54 .visible-xs-block {
55 @media (max-width: @screen-xs-max) {
56 display: block !important;
57 }
58 }
59 .visible-xs-inline {
60 @media (max-width: @screen-xs-max) {
61 display: inline !important;
62 }
63 }
64 .visible-xs-inline-block {
65 @media (max-width: @screen-xs-max) {
66 display: inline-block !important;
67 }
68 }
69
70 .visible-sm {
71 @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {
72 .responsive-visibility();
73 }
74 }
75 .visible-sm-block {
76 @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {
77 display: block !important;
78 }
79 }
80 .visible-sm-inline {
81 @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {
82 display: inline !important;
83 }
84 }
85 .visible-sm-inline-block {
86 @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {
87 display: inline-block !important;
88 }
89 }
90
91 .visible-md {
92 @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {
93 .responsive-visibility();
94 }
95 }
96 .visible-md-block {
97 @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {
98 display: block !important;
99 }
100 }
101 .visible-md-inline {
102 @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {
103 display: inline !important;
104 }
105 }
106 .visible-md-inline-block {
107 @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {
108 display: inline-block !important;
109 }
110 }
111
112 .visible-lg {
113 @media (min-width: @screen-lg-min) {
114 .responsive-visibility();
115 }
116 }
117 .visible-lg-block {
118 @media (min-width: @screen-lg-min) {
119 display: block !important;
120 }
121 }
122 .visible-lg-inline {
123 @media (min-width: @screen-lg-min) {
124 display: inline !important;
125 }
126 }
127 .visible-lg-inline-block {
128 @media (min-width: @screen-lg-min) {
129 display: inline-block !important;
130 }
131 }
132
133 .hidden-xs {
134 @media (max-width: @screen-xs-max) {
135 .responsive-invisibility();
136 }
137 }
138 .hidden-sm {
139 @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {
140 .responsive-invisibility();
141 }
142 }
143 .hidden-md {
144 @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {
145 .responsive-invisibility();
146 }
147 }
148 .hidden-lg {
149 @media (min-width: @screen-lg-min) {
150 .responsive-invisibility();
151 }
152 }
153
154
155 // Print utilities
156 //
157 // Media queries are placed on the inside to be mixin-friendly.
158
159 // Note: Deprecated .visible-print as of v3.2.0
160 .visible-print {
161 .responsive-invisibility();
162
163 @media print {
164 .responsive-visibility();
165 }
166 }
167 .visible-print-block {
168 display: none !important;
169
170 @media print {
171 display: block !important;
172 }
173 }
174 .visible-print-inline {
175 display: none !important;
176
177 @media print {
178 display: inline !important;
179 }
180 }
181 .visible-print-inline-block {
182 display: none !important;
183
184 @media print {
185 display: inline-block !important;
186 }
187 }
188
189 .hidden-print {
190 @media print {
191 .responsive-invisibility();
192 }
193 }
+0
-162
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/scaffolding.less less more
0 //
1 // Scaffolding
2 // --------------------------------------------------
3
4
5 // Reset the box-sizing
6 //
7 // Heads up! This reset may cause conflicts with some third-party widgets.
8 // For recommendations on resolving such conflicts, see
9 // http://getbootstrap.com/getting-started/#third-box-sizing
10 * {
11 .box-sizing(border-box);
12 }
13 *:before,
14 *:after {
15 .box-sizing(border-box);
16 }
17
18
19 // Body reset
20
21 html {
22 font-size: 10px;
23 -webkit-tap-highlight-color: rgba(0,0,0,0);
24 }
25
26 body {
27 font-family: @font-family-base;
28 font-size: @font-size-base;
29 line-height: @line-height-base;
30 color: @text-color;
31 background-color: @body-bg;
32 }
33
34 // Reset fonts for relevant elements
35 input,
36 button,
37 select,
38 textarea {
39 font-family: inherit;
40 font-size: inherit;
41 line-height: inherit;
42 }
43
44
45 // Links
46
47 a {
48 color: @link-color;
49 text-decoration: none;
50
51 &:hover,
52 &:focus {
53 color: @link-hover-color;
54 text-decoration: @link-hover-decoration;
55 }
56
57 &:focus {
58 .tab-focus();
59 }
60 }
61
62
63 // Figures
64 //
65 // We reset this here because previously Normalize had no `figure` margins. This
66 // ensures we don't break anyone's use of the element.
67
68 figure {
69 margin: 0;
70 }
71
72
73 // Images
74
75 img {
76 vertical-align: middle;
77 }
78
79 // Responsive images (ensure images don't scale beyond their parents)
80 .img-responsive {
81 .img-responsive();
82 }
83
84 // Rounded corners
85 .img-rounded {
86 border-radius: @border-radius-large;
87 }
88
89 // Image thumbnails
90 //
91 // Heads up! This is mixin-ed into thumbnails.less for `.thumbnail`.
92 .img-thumbnail {
93 padding: @thumbnail-padding;
94 line-height: @line-height-base;
95 background-color: @thumbnail-bg;
96 border: 1px solid @thumbnail-border;
97 border-radius: @thumbnail-border-radius;
98 .transition(all .2s ease-in-out);
99
100 // Keep them at most 100% wide
101 .img-responsive(inline-block);
102 }
103
104 // Perfect circle
105 .img-circle {
106 border-radius: 50%; // set radius in percents
107 }
108
109
110 // Horizontal rules
111
112 hr {
113 margin-top: @line-height-computed;
114 margin-bottom: @line-height-computed;
115 border: 0;
116 border-top: 1px solid @hr-border;
117 }
118
119
120 // Only display content to screen readers
121 //
122 // See: http://a11yproject.com/posts/how-to-hide-content/
123
124 .sr-only {
125 position: absolute;
126 width: 1px;
127 height: 1px;
128 margin: -1px;
129 padding: 0;
130 overflow: hidden;
131 clip: rect(0,0,0,0);
132 border: 0;
133 }
134
135 // Use in conjunction with .sr-only to only display content when it's focused.
136 // Useful for "Skip to main content" links; see http://www.w3.org/TR/2013/NOTE-WCAG20-TECHS-20130905/G1
137 // Credit: HTML5 Boilerplate
138
139 .sr-only-focusable {
140 &:active,
141 &:focus {
142 position: static;
143 width: auto;
144 height: auto;
145 margin: 0;
146 overflow: visible;
147 clip: auto;
148 }
149 }
150
151
152 // iOS "clickable elements" fix for role="button"
153 //
154 // Fixes "clickability" issue (and more generally, the firing of events such as focus as well)
155 // for traditionally non-focusable elements with role="button"
156 // see https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile
157 // Upstream patch for normalize.css submitted: https://github.com/necolas/normalize.css/pull/379 - remove this fix once that is merged
158
159 [role="button"] {
160 cursor: pointer;
161 }
+0
-234
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/tables.less less more
0 //
1 // Tables
2 // --------------------------------------------------
3
4
5 table {
6 background-color: @table-bg;
7 }
8 caption {
9 padding-top: @table-cell-padding;
10 padding-bottom: @table-cell-padding;
11 color: @text-muted;
12 text-align: left;
13 }
14 th {
15 text-align: left;
16 }
17
18
19 // Baseline styles
20
21 .table {
22 width: 100%;
23 max-width: 100%;
24 margin-bottom: @line-height-computed;
25 // Cells
26 > thead,
27 > tbody,
28 > tfoot {
29 > tr {
30 > th,
31 > td {
32 padding: @table-cell-padding;
33 line-height: @line-height-base;
34 vertical-align: top;
35 border-top: 1px solid @table-border-color;
36 }
37 }
38 }
39 // Bottom align for column headings
40 > thead > tr > th {
41 vertical-align: bottom;
42 border-bottom: 2px solid @table-border-color;
43 }
44 // Remove top border from thead by default
45 > caption + thead,
46 > colgroup + thead,
47 > thead:first-child {
48 > tr:first-child {
49 > th,
50 > td {
51 border-top: 0;
52 }
53 }
54 }
55 // Account for multiple tbody instances
56 > tbody + tbody {
57 border-top: 2px solid @table-border-color;
58 }
59
60 // Nesting
61 .table {
62 background-color: @body-bg;
63 }
64 }
65
66
67 // Condensed table w/ half padding
68
69 .table-condensed {
70 > thead,
71 > tbody,
72 > tfoot {
73 > tr {
74 > th,
75 > td {
76 padding: @table-condensed-cell-padding;
77 }
78 }
79 }
80 }
81
82
83 // Bordered version
84 //
85 // Add borders all around the table and between all the columns.
86
87 .table-bordered {
88 border: 1px solid @table-border-color;
89 > thead,
90 > tbody,
91 > tfoot {
92 > tr {
93 > th,
94 > td {
95 border: 1px solid @table-border-color;
96 }
97 }
98 }
99 > thead > tr {
100 > th,
101 > td {
102 border-bottom-width: 2px;
103 }
104 }
105 }
106
107
108 // Zebra-striping
109 //
110 // Default zebra-stripe styles (alternating gray and transparent backgrounds)
111
112 .table-striped {
113 > tbody > tr:nth-of-type(odd) {
114 background-color: @table-bg-accent;
115 }
116 }
117
118
119 // Hover effect
120 //
121 // Placed here since it has to come after the potential zebra striping
122
123 .table-hover {
124 > tbody > tr:hover {
125 background-color: @table-bg-hover;
126 }
127 }
128
129
130 // Table cell sizing
131 //
132 // Reset default table behavior
133
134 table col[class*="col-"] {
135 position: static; // Prevent border hiding in Firefox and IE9-11 (see https://github.com/twbs/bootstrap/issues/11623)
136 float: none;
137 display: table-column;
138 }
139 table {
140 td,
141 th {
142 &[class*="col-"] {
143 position: static; // Prevent border hiding in Firefox and IE9-11 (see https://github.com/twbs/bootstrap/issues/11623)
144 float: none;
145 display: table-cell;
146 }
147 }
148 }
149
150
151 // Table backgrounds
152 //
153 // Exact selectors below required to override `.table-striped` and prevent
154 // inheritance to nested tables.
155
156 // Generate the contextual variants
157 .table-row-variant(active; @table-bg-active);
158 .table-row-variant(success; @state-success-bg);
159 .table-row-variant(info; @state-info-bg);
160 .table-row-variant(warning; @state-warning-bg);
161 .table-row-variant(danger; @state-danger-bg);
162
163
164 // Responsive tables
165 //
166 // Wrap your tables in `.table-responsive` and we'll make them mobile friendly
167 // by enabling horizontal scrolling. Only applies <768px. Everything above that
168 // will display normally.
169
170 .table-responsive {
171 overflow-x: auto;
172 min-height: 0.01%; // Workaround for IE9 bug (see https://github.com/twbs/bootstrap/issues/14837)
173
174 @media screen and (max-width: @screen-xs-max) {
175 width: 100%;
176 margin-bottom: (@line-height-computed * 0.75);
177 overflow-y: hidden;
178 -ms-overflow-style: -ms-autohiding-scrollbar;
179 border: 1px solid @table-border-color;
180
181 // Tighten up spacing
182 > .table {
183 margin-bottom: 0;
184
185 // Ensure the content doesn't wrap
186 > thead,
187 > tbody,
188 > tfoot {
189 > tr {
190 > th,
191 > td {
192 white-space: nowrap;
193 }
194 }
195 }
196 }
197
198 // Special overrides for the bordered tables
199 > .table-bordered {
200 border: 0;
201
202 // Nuke the appropriate borders so that the parent can handle them
203 > thead,
204 > tbody,
205 > tfoot {
206 > tr {
207 > th:first-child,
208 > td:first-child {
209 border-left: 0;
210 }
211 > th:last-child,
212 > td:last-child {
213 border-right: 0;
214 }
215 }
216 }
217
218 // Only nuke the last row's bottom-border in `tbody` and `tfoot` since
219 // chances are there will be only one `tr` in a `thead` and that would
220 // remove the border altogether.
221 > tbody,
222 > tfoot {
223 > tr:last-child {
224 > th,
225 > td {
226 border-bottom: 0;
227 }
228 }
229 }
230
231 }
232 }
233 }
+0
-273
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/theme.less less more
0
1 //
2 // Load core variables and mixins
3 // --------------------------------------------------
4
5 @import "variables.less";
6 @import "mixins.less";
7
8
9 //
10 // Buttons
11 // --------------------------------------------------
12
13 // Common styles
14 .btn-default,
15 .btn-primary,
16 .btn-success,
17 .btn-info,
18 .btn-warning,
19 .btn-danger {
20 text-shadow: 0 -1px 0 rgba(0,0,0,.2);
21 @shadow: inset 0 1px 0 rgba(255,255,255,.15), 0 1px 1px rgba(0,0,0,.075);
22 .box-shadow(@shadow);
23
24 // Reset the shadow
25 &:active,
26 &.active {
27 .box-shadow(inset 0 3px 5px rgba(0,0,0,.125));
28 }
29
30 .badge {
31 text-shadow: none;
32 }
33 }
34
35 // Mixin for generating new styles
36 .btn-styles(@btn-color: #555) {
37 #gradient > .vertical(@start-color: @btn-color; @end-color: darken(@btn-color, 12%));
38 .reset-filter(); // Disable gradients for IE9 because filter bleeds through rounded corners; see https://github.com/twbs/bootstrap/issues/10620
39 background-repeat: repeat-x;
40 border-color: darken(@btn-color, 14%);
41
42 &:hover,
43 &:focus {
44 background-color: darken(@btn-color, 12%);
45 background-position: 0 -15px;
46 }
47
48 &:active,
49 &.active {
50 background-color: darken(@btn-color, 12%);
51 border-color: darken(@btn-color, 14%);
52 }
53
54 &.disabled,
55 &:disabled,
56 &[disabled] {
57 background-color: darken(@btn-color, 12%);
58 background-image: none;
59 }
60 }
61
62 // Common styles
63 .btn {
64 // Remove the gradient for the pressed/active state
65 &:active,
66 &.active {
67 background-image: none;
68 }
69 }
70
71 // Apply the mixin to the buttons
72 .btn-default { .btn-styles(@btn-default-bg); text-shadow: 0 1px 0 #fff; border-color: #ccc; }
73 .btn-primary { .btn-styles(@btn-primary-bg); }
74 .btn-success { .btn-styles(@btn-success-bg); }
75 .btn-info { .btn-styles(@btn-info-bg); }
76 .btn-warning { .btn-styles(@btn-warning-bg); }
77 .btn-danger { .btn-styles(@btn-danger-bg); }
78
79
80 //
81 // Images
82 // --------------------------------------------------
83
84 .thumbnail,
85 .img-thumbnail {
86 .box-shadow(0 1px 2px rgba(0,0,0,.075));
87 }
88
89
90 //
91 // Dropdowns
92 // --------------------------------------------------
93
94 .dropdown-menu > li > a:hover,
95 .dropdown-menu > li > a:focus {
96 #gradient > .vertical(@start-color: @dropdown-link-hover-bg; @end-color: darken(@dropdown-link-hover-bg, 5%));
97 background-color: darken(@dropdown-link-hover-bg, 5%);
98 }
99 .dropdown-menu > .active > a,
100 .dropdown-menu > .active > a:hover,
101 .dropdown-menu > .active > a:focus {
102 #gradient > .vertical(@start-color: @dropdown-link-active-bg; @end-color: darken(@dropdown-link-active-bg, 5%));
103 background-color: darken(@dropdown-link-active-bg, 5%);
104 }
105
106
107 //
108 // Navbar
109 // --------------------------------------------------
110
111 // Default navbar
112 .navbar-default {
113 #gradient > .vertical(@start-color: lighten(@navbar-default-bg, 10%); @end-color: @navbar-default-bg);
114 .reset-filter(); // Remove gradient in IE<10 to fix bug where dropdowns don't get triggered
115 border-radius: @navbar-border-radius;
116 @shadow: inset 0 1px 0 rgba(255,255,255,.15), 0 1px 5px rgba(0,0,0,.075);
117 .box-shadow(@shadow);
118
119 .navbar-nav > .open > a,
120 .navbar-nav > .active > a {
121 #gradient > .vertical(@start-color: darken(@navbar-default-link-active-bg, 5%); @end-color: darken(@navbar-default-link-active-bg, 2%));
122 .box-shadow(inset 0 3px 9px rgba(0,0,0,.075));
123 }
124 }
125 .navbar-brand,
126 .navbar-nav > li > a {
127 text-shadow: 0 1px 0 rgba(255,255,255,.25);
128 }
129
130 // Inverted navbar
131 .navbar-inverse {
132 #gradient > .vertical(@start-color: lighten(@navbar-inverse-bg, 10%); @end-color: @navbar-inverse-bg);
133 .reset-filter(); // Remove gradient in IE<10 to fix bug where dropdowns don't get triggered; see https://github.com/twbs/bootstrap/issues/10257
134
135 .navbar-nav > .open > a,
136 .navbar-nav > .active > a {
137 #gradient > .vertical(@start-color: @navbar-inverse-link-active-bg; @end-color: lighten(@navbar-inverse-link-active-bg, 2.5%));
138 .box-shadow(inset 0 3px 9px rgba(0,0,0,.25));
139 }
140
141 .navbar-brand,
142 .navbar-nav > li > a {
143 text-shadow: 0 -1px 0 rgba(0,0,0,.25);
144 }
145 }
146
147 // Undo rounded corners in static and fixed navbars
148 .navbar-static-top,
149 .navbar-fixed-top,
150 .navbar-fixed-bottom {
151 border-radius: 0;
152 }
153
154 // Fix active state of dropdown items in collapsed mode
155 @media (max-width: @grid-float-breakpoint-max) {
156 .navbar .navbar-nav .open .dropdown-menu > .active > a {
157 &,
158 &:hover,
159 &:focus {
160 color: #fff;
161 #gradient > .vertical(@start-color: @dropdown-link-active-bg; @end-color: darken(@dropdown-link-active-bg, 5%));
162 }
163 }
164 }
165
166
167 //
168 // Alerts
169 // --------------------------------------------------
170
171 // Common styles
172 .alert {
173 text-shadow: 0 1px 0 rgba(255,255,255,.2);
174 @shadow: inset 0 1px 0 rgba(255,255,255,.25), 0 1px 2px rgba(0,0,0,.05);
175 .box-shadow(@shadow);
176 }
177
178 // Mixin for generating new styles
179 .alert-styles(@color) {
180 #gradient > .vertical(@start-color: @color; @end-color: darken(@color, 7.5%));
181 border-color: darken(@color, 15%);
182 }
183
184 // Apply the mixin to the alerts
185 .alert-success { .alert-styles(@alert-success-bg); }
186 .alert-info { .alert-styles(@alert-info-bg); }
187 .alert-warning { .alert-styles(@alert-warning-bg); }
188 .alert-danger { .alert-styles(@alert-danger-bg); }
189
190
191 //
192 // Progress bars
193 // --------------------------------------------------
194
195 // Give the progress background some depth
196 .progress {
197 #gradient > .vertical(@start-color: darken(@progress-bg, 4%); @end-color: @progress-bg)
198 }
199
200 // Mixin for generating new styles
201 .progress-bar-styles(@color) {
202 #gradient > .vertical(@start-color: @color; @end-color: darken(@color, 10%));
203 }
204
205 // Apply the mixin to the progress bars
206 .progress-bar { .progress-bar-styles(@progress-bar-bg); }
207 .progress-bar-success { .progress-bar-styles(@progress-bar-success-bg); }
208 .progress-bar-info { .progress-bar-styles(@progress-bar-info-bg); }
209 .progress-bar-warning { .progress-bar-styles(@progress-bar-warning-bg); }
210 .progress-bar-danger { .progress-bar-styles(@progress-bar-danger-bg); }
211
212 // Reset the striped class because our mixins don't do multiple gradients and
213 // the above custom styles override the new `.progress-bar-striped` in v3.2.0.
214 .progress-bar-striped {
215 #gradient > .striped();
216 }
217
218
219 //
220 // List groups
221 // --------------------------------------------------
222
223 .list-group {
224 border-radius: @border-radius-base;
225 .box-shadow(0 1px 2px rgba(0,0,0,.075));
226 }
227 .list-group-item.active,
228 .list-group-item.active:hover,
229 .list-group-item.active:focus {
230 text-shadow: 0 -1px 0 darken(@list-group-active-bg, 10%);
231 #gradient > .vertical(@start-color: @list-group-active-bg; @end-color: darken(@list-group-active-bg, 7.5%));
232 border-color: darken(@list-group-active-border, 7.5%);
233
234 .badge {
235 text-shadow: none;
236 }
237 }
238
239
240 //
241 // Panels
242 // --------------------------------------------------
243
244 // Common styles
245 .panel {
246 .box-shadow(0 1px 2px rgba(0,0,0,.05));
247 }
248
249 // Mixin for generating new styles
250 .panel-heading-styles(@color) {
251 #gradient > .vertical(@start-color: @color; @end-color: darken(@color, 5%));
252 }
253
254 // Apply the mixin to the panel headings only
255 .panel-default > .panel-heading { .panel-heading-styles(@panel-default-heading-bg); }
256 .panel-primary > .panel-heading { .panel-heading-styles(@panel-primary-heading-bg); }
257 .panel-success > .panel-heading { .panel-heading-styles(@panel-success-heading-bg); }
258 .panel-info > .panel-heading { .panel-heading-styles(@panel-info-heading-bg); }
259 .panel-warning > .panel-heading { .panel-heading-styles(@panel-warning-heading-bg); }
260 .panel-danger > .panel-heading { .panel-heading-styles(@panel-danger-heading-bg); }
261
262
263 //
264 // Wells
265 // --------------------------------------------------
266
267 .well {
268 #gradient > .vertical(@start-color: darken(@well-bg, 5%); @end-color: @well-bg);
269 border-color: darken(@well-bg, 10%);
270 @shadow: inset 0 1px 3px rgba(0,0,0,.05), 0 1px 0 rgba(255,255,255,.1);
271 .box-shadow(@shadow);
272 }
+0
-36
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/thumbnails.less less more
0 //
1 // Thumbnails
2 // --------------------------------------------------
3
4
5 // Mixin and adjust the regular image class
6 .thumbnail {
7 display: block;
8 padding: @thumbnail-padding;
9 margin-bottom: @line-height-computed;
10 line-height: @line-height-base;
11 background-color: @thumbnail-bg;
12 border: 1px solid @thumbnail-border;
13 border-radius: @thumbnail-border-radius;
14 .transition(border .2s ease-in-out);
15
16 > img,
17 a > img {
18 &:extend(.img-responsive);
19 margin-left: auto;
20 margin-right: auto;
21 }
22
23 // Add a hover state for linked versions only
24 a&:hover,
25 a&:focus,
26 a&.active {
27 border-color: @link-color;
28 }
29
30 // Image captions
31 .caption {
32 padding: @thumbnail-caption-padding;
33 color: @thumbnail-caption-color;
34 }
35 }
+0
-102
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/tooltip.less less more
0 //
1 // Tooltips
2 // --------------------------------------------------
3
4
5 // Base class
6 .tooltip {
7 position: absolute;
8 z-index: @zindex-tooltip;
9 display: block;
10 // Reset font and text properties given new insertion method
11 font-family: @font-family-base;
12 font-size: @font-size-small;
13 font-weight: normal;
14 line-height: 1.4;
15 .opacity(0);
16
17 &.in { .opacity(@tooltip-opacity); }
18 &.top { margin-top: -3px; padding: @tooltip-arrow-width 0; }
19 &.right { margin-left: 3px; padding: 0 @tooltip-arrow-width; }
20 &.bottom { margin-top: 3px; padding: @tooltip-arrow-width 0; }
21 &.left { margin-left: -3px; padding: 0 @tooltip-arrow-width; }
22 }
23
24 // Wrapper for the tooltip content
25 .tooltip-inner {
26 max-width: @tooltip-max-width;
27 padding: 3px 8px;
28 color: @tooltip-color;
29 text-align: center;
30 text-decoration: none;
31 background-color: @tooltip-bg;
32 border-radius: @border-radius-base;
33 }
34
35 // Arrows
36 .tooltip-arrow {
37 position: absolute;
38 width: 0;
39 height: 0;
40 border-color: transparent;
41 border-style: solid;
42 }
43 // Note: Deprecated .top-left, .top-right, .bottom-left, and .bottom-right as of v3.3.1
44 .tooltip {
45 &.top .tooltip-arrow {
46 bottom: 0;
47 left: 50%;
48 margin-left: -@tooltip-arrow-width;
49 border-width: @tooltip-arrow-width @tooltip-arrow-width 0;
50 border-top-color: @tooltip-arrow-color;
51 }
52 &.top-left .tooltip-arrow {
53 bottom: 0;
54 right: @tooltip-arrow-width;
55 margin-bottom: -@tooltip-arrow-width;
56 border-width: @tooltip-arrow-width @tooltip-arrow-width 0;
57 border-top-color: @tooltip-arrow-color;
58 }
59 &.top-right .tooltip-arrow {
60 bottom: 0;
61 left: @tooltip-arrow-width;
62 margin-bottom: -@tooltip-arrow-width;
63 border-width: @tooltip-arrow-width @tooltip-arrow-width 0;
64 border-top-color: @tooltip-arrow-color;
65 }
66 &.right .tooltip-arrow {
67 top: 50%;
68 left: 0;
69 margin-top: -@tooltip-arrow-width;
70 border-width: @tooltip-arrow-width @tooltip-arrow-width @tooltip-arrow-width 0;
71 border-right-color: @tooltip-arrow-color;
72 }
73 &.left .tooltip-arrow {
74 top: 50%;
75 right: 0;
76 margin-top: -@tooltip-arrow-width;
77 border-width: @tooltip-arrow-width 0 @tooltip-arrow-width @tooltip-arrow-width;
78 border-left-color: @tooltip-arrow-color;
79 }
80 &.bottom .tooltip-arrow {
81 top: 0;
82 left: 50%;
83 margin-left: -@tooltip-arrow-width;
84 border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;
85 border-bottom-color: @tooltip-arrow-color;
86 }
87 &.bottom-left .tooltip-arrow {
88 top: 0;
89 right: @tooltip-arrow-width;
90 margin-top: -@tooltip-arrow-width;
91 border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;
92 border-bottom-color: @tooltip-arrow-color;
93 }
94 &.bottom-right .tooltip-arrow {
95 top: 0;
96 left: @tooltip-arrow-width;
97 margin-top: -@tooltip-arrow-width;
98 border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;
99 border-bottom-color: @tooltip-arrow-color;
100 }
101 }
+0
-302
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/type.less less more
0 //
1 // Typography
2 // --------------------------------------------------
3
4
5 // Headings
6 // -------------------------
7
8 h1, h2, h3, h4, h5, h6,
9 .h1, .h2, .h3, .h4, .h5, .h6 {
10 font-family: @headings-font-family;
11 font-weight: @headings-font-weight;
12 line-height: @headings-line-height;
13 color: @headings-color;
14
15 small,
16 .small {
17 font-weight: normal;
18 line-height: 1;
19 color: @headings-small-color;
20 }
21 }
22
23 h1, .h1,
24 h2, .h2,
25 h3, .h3 {
26 margin-top: @line-height-computed;
27 margin-bottom: (@line-height-computed / 2);
28
29 small,
30 .small {
31 font-size: 65%;
32 }
33 }
34 h4, .h4,
35 h5, .h5,
36 h6, .h6 {
37 margin-top: (@line-height-computed / 2);
38 margin-bottom: (@line-height-computed / 2);
39
40 small,
41 .small {
42 font-size: 75%;
43 }
44 }
45
46 h1, .h1 { font-size: @font-size-h1; }
47 h2, .h2 { font-size: @font-size-h2; }
48 h3, .h3 { font-size: @font-size-h3; }
49 h4, .h4 { font-size: @font-size-h4; }
50 h5, .h5 { font-size: @font-size-h5; }
51 h6, .h6 { font-size: @font-size-h6; }
52
53
54 // Body text
55 // -------------------------
56
57 p {
58 margin: 0 0 (@line-height-computed / 2);
59 }
60
61 .lead {
62 margin-bottom: @line-height-computed;
63 font-size: floor((@font-size-base * 1.15));
64 font-weight: 300;
65 line-height: 1.4;
66
67 @media (min-width: @screen-sm-min) {
68 font-size: (@font-size-base * 1.5);
69 }
70 }
71
72
73 // Emphasis & misc
74 // -------------------------
75
76 // Ex: (12px small font / 14px base font) * 100% = about 85%
77 small,
78 .small {
79 font-size: floor((100% * @font-size-small / @font-size-base));
80 }
81
82 mark,
83 .mark {
84 background-color: @state-warning-bg;
85 padding: .2em;
86 }
87
88 // Alignment
89 .text-left { text-align: left; }
90 .text-right { text-align: right; }
91 .text-center { text-align: center; }
92 .text-justify { text-align: justify; }
93 .text-nowrap { white-space: nowrap; }
94
95 // Transformation
96 .text-lowercase { text-transform: lowercase; }
97 .text-uppercase { text-transform: uppercase; }
98 .text-capitalize { text-transform: capitalize; }
99
100 // Contextual colors
101 .text-muted {
102 color: @text-muted;
103 }
104 .text-primary {
105 .text-emphasis-variant(@brand-primary);
106 }
107 .text-success {
108 .text-emphasis-variant(@state-success-text);
109 }
110 .text-info {
111 .text-emphasis-variant(@state-info-text);
112 }
113 .text-warning {
114 .text-emphasis-variant(@state-warning-text);
115 }
116 .text-danger {
117 .text-emphasis-variant(@state-danger-text);
118 }
119
120 // Contextual backgrounds
121 // For now we'll leave these alongside the text classes until v4 when we can
122 // safely shift things around (per SemVer rules).
123 .bg-primary {
124 // Given the contrast here, this is the only class to have its color inverted
125 // automatically.
126 color: #fff;
127 .bg-variant(@brand-primary);
128 }
129 .bg-success {
130 .bg-variant(@state-success-bg);
131 }
132 .bg-info {
133 .bg-variant(@state-info-bg);
134 }
135 .bg-warning {
136 .bg-variant(@state-warning-bg);
137 }
138 .bg-danger {
139 .bg-variant(@state-danger-bg);
140 }
141
142
143 // Page header
144 // -------------------------
145
146 .page-header {
147 padding-bottom: ((@line-height-computed / 2) - 1);
148 margin: (@line-height-computed * 2) 0 @line-height-computed;
149 border-bottom: 1px solid @page-header-border-color;
150 }
151
152
153 // Lists
154 // -------------------------
155
156 // Unordered and Ordered lists
157 ul,
158 ol {
159 margin-top: 0;
160 margin-bottom: (@line-height-computed / 2);
161 ul,
162 ol {
163 margin-bottom: 0;
164 }
165 }
166
167 // List options
168
169 // Unstyled keeps list items block level, just removes default browser padding and list-style
170 .list-unstyled {
171 padding-left: 0;
172 list-style: none;
173 }
174
175 // Inline turns list items into inline-block
176 .list-inline {
177 .list-unstyled();
178 margin-left: -5px;
179
180 > li {
181 display: inline-block;
182 padding-left: 5px;
183 padding-right: 5px;
184 }
185 }
186
187 // Description Lists
188 dl {
189 margin-top: 0; // Remove browser default
190 margin-bottom: @line-height-computed;
191 }
192 dt,
193 dd {
194 line-height: @line-height-base;
195 }
196 dt {
197 font-weight: bold;
198 }
199 dd {
200 margin-left: 0; // Undo browser default
201 }
202
203 // Horizontal description lists
204 //
205 // Defaults to being stacked without any of the below styles applied, until the
206 // grid breakpoint is reached (default of ~768px).
207
208 .dl-horizontal {
209 dd {
210 &:extend(.clearfix all); // Clear the floated `dt` if an empty `dd` is present
211 }
212
213 @media (min-width: @grid-float-breakpoint) {
214 dt {
215 float: left;
216 width: (@dl-horizontal-offset - 20);
217 clear: left;
218 text-align: right;
219 .text-overflow();
220 }
221 dd {
222 margin-left: @dl-horizontal-offset;
223 }
224 }
225 }
226
227
228 // Misc
229 // -------------------------
230
231 // Abbreviations and acronyms
232 abbr[title],
233 // Add data-* attribute to help out our tooltip plugin, per https://github.com/twbs/bootstrap/issues/5257
234 abbr[data-original-title] {
235 cursor: help;
236 border-bottom: 1px dotted @abbr-border-color;
237 }
238 .initialism {
239 font-size: 90%;
240 .text-uppercase();
241 }
242
243 // Blockquotes
244 blockquote {
245 padding: (@line-height-computed / 2) @line-height-computed;
246 margin: 0 0 @line-height-computed;
247 font-size: @blockquote-font-size;
248 border-left: 5px solid @blockquote-border-color;
249
250 p,
251 ul,
252 ol {
253 &:last-child {
254 margin-bottom: 0;
255 }
256 }
257
258 // Note: Deprecated small and .small as of v3.1.0
259 // Context: https://github.com/twbs/bootstrap/issues/11660
260 footer,
261 small,
262 .small {
263 display: block;
264 font-size: 80%; // back to default font-size
265 line-height: @line-height-base;
266 color: @blockquote-small-color;
267
268 &:before {
269 content: '\2014 \00A0'; // em dash, nbsp
270 }
271 }
272 }
273
274 // Opposite alignment of blockquote
275 //
276 // Heads up: `blockquote.pull-right` has been deprecated as of v3.1.0.
277 .blockquote-reverse,
278 blockquote.pull-right {
279 padding-right: 15px;
280 padding-left: 0;
281 border-right: 5px solid @blockquote-border-color;
282 border-left: 0;
283 text-align: right;
284
285 // Account for citation
286 footer,
287 small,
288 .small {
289 &:before { content: ''; }
290 &:after {
291 content: '\00A0 \2014'; // nbsp, em dash
292 }
293 }
294 }
295
296 // Addresses
297 address {
298 margin-bottom: @line-height-computed;
299 font-style: normal;
300 line-height: @line-height-base;
301 }
+0
-55
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/utilities.less less more
0 //
1 // Utility classes
2 // --------------------------------------------------
3
4
5 // Floats
6 // -------------------------
7
8 .clearfix {
9 .clearfix();
10 }
11 .center-block {
12 .center-block();
13 }
14 .pull-right {
15 float: right !important;
16 }
17 .pull-left {
18 float: left !important;
19 }
20
21
22 // Toggling content
23 // -------------------------
24
25 // Note: Deprecated .hide in favor of .hidden or .sr-only (as appropriate) in v3.0.1
26 .hide {
27 display: none !important;
28 }
29 .show {
30 display: block !important;
31 }
32 .invisible {
33 visibility: hidden;
34 }
35 .text-hide {
36 .text-hide();
37 }
38
39
40 // Hide from screenreaders and browsers
41 //
42 // Credit: HTML5 Boilerplate
43
44 .hidden {
45 display: none !important;
46 }
47
48
49 // For Affix plugin
50 // -------------------------
51
52 .affix {
53 position: fixed;
54 }
+0
-861
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/variables.less less more
0 //
1 // Variables
2 // --------------------------------------------------
3
4
5 //== Colors
6 //
7 //## Gray and brand colors for use across Bootstrap.
8
9 @gray-base: #000;
10 @gray-darker: lighten(@gray-base, 13.5%); // #222
11 @gray-dark: lighten(@gray-base, 20%); // #333
12 @gray: lighten(@gray-base, 33.5%); // #555
13 @gray-light: lighten(@gray-base, 46.7%); // #777
14 @gray-lighter: lighten(@gray-base, 93.5%); // #eee
15
16 @brand-primary: darken(#428bca, 6.5%); // #337ab7
17 @brand-success: #5cb85c;
18 @brand-info: #5bc0de;
19 @brand-warning: #f0ad4e;
20 @brand-danger: #d9534f;
21
22
23 //== Scaffolding
24 //
25 //## Settings for some of the most global styles.
26
27 //** Background color for `<body>`.
28 @body-bg: #fff;
29 //** Global text color on `<body>`.
30 @text-color: @gray-dark;
31
32 //** Global textual link color.
33 @link-color: @brand-primary;
34 //** Link hover color set via `darken()` function.
35 @link-hover-color: darken(@link-color, 15%);
36 //** Link hover decoration.
37 @link-hover-decoration: underline;
38
39
40 //== Typography
41 //
42 //## Font, line-height, and color for body text, headings, and more.
43
44 @font-family-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif;
45 @font-family-serif: Georgia, "Times New Roman", Times, serif;
46 //** Default monospace fonts for `<code>`, `<kbd>`, and `<pre>`.
47 @font-family-monospace: Menlo, Monaco, Consolas, "Courier New", monospace;
48 @font-family-base: @font-family-sans-serif;
49
50 @font-size-base: 14px;
51 @font-size-large: ceil((@font-size-base * 1.25)); // ~18px
52 @font-size-small: ceil((@font-size-base * 0.85)); // ~12px
53
54 @font-size-h1: floor((@font-size-base * 2.6)); // ~36px
55 @font-size-h2: floor((@font-size-base * 2.15)); // ~30px
56 @font-size-h3: ceil((@font-size-base * 1.7)); // ~24px
57 @font-size-h4: ceil((@font-size-base * 1.25)); // ~18px
58 @font-size-h5: @font-size-base;
59 @font-size-h6: ceil((@font-size-base * 0.85)); // ~12px
60
61 //** Unit-less `line-height` for use in components like buttons.
62 @line-height-base: 1.428571429; // 20/14
63 //** Computed "line-height" (`font-size` * `line-height`) for use with `margin`, `padding`, etc.
64 @line-height-computed: floor((@font-size-base * @line-height-base)); // ~20px
65
66 //** By default, this inherits from the `<body>`.
67 @headings-font-family: inherit;
68 @headings-font-weight: 500;
69 @headings-line-height: 1.1;
70 @headings-color: inherit;
71
72
73 //== Iconography
74 //
75 //## Specify custom location and filename of the included Glyphicons icon font. Useful for those including Bootstrap via Bower.
76
77 //** Load fonts from this directory.
78 @icon-font-path: "../fonts/";
79 //** File name for all font files.
80 @icon-font-name: "glyphicons-halflings-regular";
81 //** Element ID within SVG icon file.
82 @icon-font-svg-id: "glyphicons_halflingsregular";
83
84
85 //== Components
86 //
87 //## Define common padding and border radius sizes and more. Values based on 14px text and 1.428 line-height (~20px to start).
88
89 @padding-base-vertical: 6px;
90 @padding-base-horizontal: 12px;
91
92 @padding-large-vertical: 10px;
93 @padding-large-horizontal: 16px;
94
95 @padding-small-vertical: 5px;
96 @padding-small-horizontal: 10px;
97
98 @padding-xs-vertical: 1px;
99 @padding-xs-horizontal: 5px;
100
101 @line-height-large: 1.3333333; // extra decimals for Win 8.1 Chrome
102 @line-height-small: 1.5;
103
104 @border-radius-base: 4px;
105 @border-radius-large: 6px;
106 @border-radius-small: 3px;
107
108 //** Global color for active items (e.g., navs or dropdowns).
109 @component-active-color: #fff;
110 //** Global background color for active items (e.g., navs or dropdowns).
111 @component-active-bg: @brand-primary;
112
113 //** Width of the `border` for generating carets that indicator dropdowns.
114 @caret-width-base: 4px;
115 //** Carets increase slightly in size for larger components.
116 @caret-width-large: 5px;
117
118
119 //== Tables
120 //
121 //## Customizes the `.table` component with basic values, each used across all table variations.
122
123 //** Padding for `<th>`s and `<td>`s.
124 @table-cell-padding: 8px;
125 //** Padding for cells in `.table-condensed`.
126 @table-condensed-cell-padding: 5px;
127
128 //** Default background color used for all tables.
129 @table-bg: transparent;
130 //** Background color used for `.table-striped`.
131 @table-bg-accent: #f9f9f9;
132 //** Background color used for `.table-hover`.
133 @table-bg-hover: #f5f5f5;
134 @table-bg-active: @table-bg-hover;
135
136 //** Border color for table and cell borders.
137 @table-border-color: #ddd;
138
139
140 //== Buttons
141 //
142 //## For each of Bootstrap's buttons, define text, background and border color.
143
144 @btn-font-weight: normal;
145
146 @btn-default-color: #333;
147 @btn-default-bg: #fff;
148 @btn-default-border: #ccc;
149
150 @btn-primary-color: #fff;
151 @btn-primary-bg: @brand-primary;
152 @btn-primary-border: darken(@btn-primary-bg, 5%);
153
154 @btn-success-color: #fff;
155 @btn-success-bg: @brand-success;
156 @btn-success-border: darken(@btn-success-bg, 5%);
157
158 @btn-info-color: #fff;
159 @btn-info-bg: @brand-info;
160 @btn-info-border: darken(@btn-info-bg, 5%);
161
162 @btn-warning-color: #fff;
163 @btn-warning-bg: @brand-warning;
164 @btn-warning-border: darken(@btn-warning-bg, 5%);
165
166 @btn-danger-color: #fff;
167 @btn-danger-bg: @brand-danger;
168 @btn-danger-border: darken(@btn-danger-bg, 5%);
169
170 @btn-link-disabled-color: @gray-light;
171
172
173 //== Forms
174 //
175 //##
176
177 //** `<input>` background color
178 @input-bg: #fff;
179 //** `<input disabled>` background color
180 @input-bg-disabled: @gray-lighter;
181
182 //** Text color for `<input>`s
183 @input-color: @gray;
184 //** `<input>` border color
185 @input-border: #ccc;
186
187 // TODO: Rename `@input-border-radius` to `@input-border-radius-base` in v4
188 //** Default `.form-control` border radius
189 // This has no effect on `<select>`s in some browsers, due to the limited stylability of `<select>`s in CSS.
190 @input-border-radius: @border-radius-base;
191 //** Large `.form-control` border radius
192 @input-border-radius-large: @border-radius-large;
193 //** Small `.form-control` border radius
194 @input-border-radius-small: @border-radius-small;
195
196 //** Border color for inputs on focus
197 @input-border-focus: #66afe9;
198
199 //** Placeholder text color
200 @input-color-placeholder: #999;
201
202 //** Default `.form-control` height
203 @input-height-base: (@line-height-computed + (@padding-base-vertical * 2) + 2);
204 //** Large `.form-control` height
205 @input-height-large: (ceil(@font-size-large * @line-height-large) + (@padding-large-vertical * 2) + 2);
206 //** Small `.form-control` height
207 @input-height-small: (floor(@font-size-small * @line-height-small) + (@padding-small-vertical * 2) + 2);
208
209 //** `.form-group` margin
210 @form-group-margin-bottom: 15px;
211
212 @legend-color: @gray-dark;
213 @legend-border-color: #e5e5e5;
214
215 //** Background color for textual input addons
216 @input-group-addon-bg: @gray-lighter;
217 //** Border color for textual input addons
218 @input-group-addon-border-color: @input-border;
219
220 //** Disabled cursor for form controls and buttons.
221 @cursor-disabled: not-allowed;
222
223
224 //== Dropdowns
225 //
226 //## Dropdown menu container and contents.
227
228 //** Background for the dropdown menu.
229 @dropdown-bg: #fff;
230 //** Dropdown menu `border-color`.
231 @dropdown-border: rgba(0,0,0,.15);
232 //** Dropdown menu `border-color` **for IE8**.
233 @dropdown-fallback-border: #ccc;
234 //** Divider color for between dropdown items.
235 @dropdown-divider-bg: #e5e5e5;
236
237 //** Dropdown link text color.
238 @dropdown-link-color: @gray-dark;
239 //** Hover color for dropdown links.
240 @dropdown-link-hover-color: darken(@gray-dark, 5%);
241 //** Hover background for dropdown links.
242 @dropdown-link-hover-bg: #f5f5f5;
243
244 //** Active dropdown menu item text color.
245 @dropdown-link-active-color: @component-active-color;
246 //** Active dropdown menu item background color.
247 @dropdown-link-active-bg: @component-active-bg;
248
249 //** Disabled dropdown menu item background color.
250 @dropdown-link-disabled-color: @gray-light;
251
252 //** Text color for headers within dropdown menus.
253 @dropdown-header-color: @gray-light;
254
255 //** Deprecated `@dropdown-caret-color` as of v3.1.0
256 @dropdown-caret-color: #000;
257
258
259 //-- Z-index master list
260 //
261 // Warning: Avoid customizing these values. They're used for a bird's eye view
262 // of components dependent on the z-axis and are designed to all work together.
263 //
264 // Note: These variables are not generated into the Customizer.
265
266 @zindex-navbar: 1000;
267 @zindex-dropdown: 1000;
268 @zindex-popover: 1060;
269 @zindex-tooltip: 1070;
270 @zindex-navbar-fixed: 1030;
271 @zindex-modal-background: 1040;
272 @zindex-modal: 1050;
273
274
275 //== Media queries breakpoints
276 //
277 //## Define the breakpoints at which your layout will change, adapting to different screen sizes.
278
279 // Extra small screen / phone
280 //** Deprecated `@screen-xs` as of v3.0.1
281 @screen-xs: 480px;
282 //** Deprecated `@screen-xs-min` as of v3.2.0
283 @screen-xs-min: @screen-xs;
284 //** Deprecated `@screen-phone` as of v3.0.1
285 @screen-phone: @screen-xs-min;
286
287 // Small screen / tablet
288 //** Deprecated `@screen-sm` as of v3.0.1
289 @screen-sm: 768px;
290 @screen-sm-min: @screen-sm;
291 //** Deprecated `@screen-tablet` as of v3.0.1
292 @screen-tablet: @screen-sm-min;
293
294 // Medium screen / desktop
295 //** Deprecated `@screen-md` as of v3.0.1
296 @screen-md: 992px;
297 @screen-md-min: @screen-md;
298 //** Deprecated `@screen-desktop` as of v3.0.1
299 @screen-desktop: @screen-md-min;
300
301 // Large screen / wide desktop
302 //** Deprecated `@screen-lg` as of v3.0.1
303 @screen-lg: 1200px;
304 @screen-lg-min: @screen-lg;
305 //** Deprecated `@screen-lg-desktop` as of v3.0.1
306 @screen-lg-desktop: @screen-lg-min;
307
308 // So media queries don't overlap when required, provide a maximum
309 @screen-xs-max: (@screen-sm-min - 1);
310 @screen-sm-max: (@screen-md-min - 1);
311 @screen-md-max: (@screen-lg-min - 1);
312
313
314 //== Grid system
315 //
316 //## Define your custom responsive grid.
317
318 //** Number of columns in the grid.
319 @grid-columns: 12;
320 //** Padding between columns. Gets divided in half for the left and right.
321 @grid-gutter-width: 30px;
322 // Navbar collapse
323 //** Point at which the navbar becomes uncollapsed.
324 @grid-float-breakpoint: @screen-sm-min;
325 //** Point at which the navbar begins collapsing.
326 @grid-float-breakpoint-max: (@grid-float-breakpoint - 1);
327
328
329 //== Container sizes
330 //
331 //## Define the maximum width of `.container` for different screen sizes.
332
333 // Small screen / tablet
334 @container-tablet: (720px + @grid-gutter-width);
335 //** For `@screen-sm-min` and up.
336 @container-sm: @container-tablet;
337
338 // Medium screen / desktop
339 @container-desktop: (940px + @grid-gutter-width);
340 //** For `@screen-md-min` and up.
341 @container-md: @container-desktop;
342
343 // Large screen / wide desktop
344 @container-large-desktop: (1140px + @grid-gutter-width);
345 //** For `@screen-lg-min` and up.
346 @container-lg: @container-large-desktop;
347
348
349 //== Navbar
350 //
351 //##
352
353 // Basics of a navbar
354 @navbar-height: 50px;
355 @navbar-margin-bottom: @line-height-computed;
356 @navbar-border-radius: @border-radius-base;
357 @navbar-padding-horizontal: floor((@grid-gutter-width / 2));
358 @navbar-padding-vertical: ((@navbar-height - @line-height-computed) / 2);
359 @navbar-collapse-max-height: 340px;
360
361 @navbar-default-color: #777;
362 @navbar-default-bg: #f8f8f8;
363 @navbar-default-border: darken(@navbar-default-bg, 6.5%);
364
365 // Navbar links
366 @navbar-default-link-color: #777;
367 @navbar-default-link-hover-color: #333;
368 @navbar-default-link-hover-bg: transparent;
369 @navbar-default-link-active-color: #555;
370 @navbar-default-link-active-bg: darken(@navbar-default-bg, 6.5%);
371 @navbar-default-link-disabled-color: #ccc;
372 @navbar-default-link-disabled-bg: transparent;
373
374 // Navbar brand label
375 @navbar-default-brand-color: @navbar-default-link-color;
376 @navbar-default-brand-hover-color: darken(@navbar-default-brand-color, 10%);
377 @navbar-default-brand-hover-bg: transparent;
378
379 // Navbar toggle
380 @navbar-default-toggle-hover-bg: #ddd;
381 @navbar-default-toggle-icon-bar-bg: #888;
382 @navbar-default-toggle-border-color: #ddd;
383
384
385 // Inverted navbar
386 // Reset inverted navbar basics
387 @navbar-inverse-color: lighten(@gray-light, 15%);
388 @navbar-inverse-bg: #222;
389 @navbar-inverse-border: darken(@navbar-inverse-bg, 10%);
390
391 // Inverted navbar links
392 @navbar-inverse-link-color: lighten(@gray-light, 15%);
393 @navbar-inverse-link-hover-color: #fff;
394 @navbar-inverse-link-hover-bg: transparent;
395 @navbar-inverse-link-active-color: @navbar-inverse-link-hover-color;
396 @navbar-inverse-link-active-bg: darken(@navbar-inverse-bg, 10%);
397 @navbar-inverse-link-disabled-color: #444;
398 @navbar-inverse-link-disabled-bg: transparent;
399
400 // Inverted navbar brand label
401 @navbar-inverse-brand-color: @navbar-inverse-link-color;
402 @navbar-inverse-brand-hover-color: #fff;
403 @navbar-inverse-brand-hover-bg: transparent;
404
405 // Inverted navbar toggle
406 @navbar-inverse-toggle-hover-bg: #333;
407 @navbar-inverse-toggle-icon-bar-bg: #fff;
408 @navbar-inverse-toggle-border-color: #333;
409
410
411 //== Navs
412 //
413 //##
414
415 //=== Shared nav styles
416 @nav-link-padding: 10px 15px;
417 @nav-link-hover-bg: @gray-lighter;
418
419 @nav-disabled-link-color: @gray-light;
420 @nav-disabled-link-hover-color: @gray-light;
421
422 //== Tabs
423 @nav-tabs-border-color: #ddd;
424
425 @nav-tabs-link-hover-border-color: @gray-lighter;
426
427 @nav-tabs-active-link-hover-bg: @body-bg;
428 @nav-tabs-active-link-hover-color: @gray;
429 @nav-tabs-active-link-hover-border-color: #ddd;
430
431 @nav-tabs-justified-link-border-color: #ddd;
432 @nav-tabs-justified-active-link-border-color: @body-bg;
433
434 //== Pills
435 @nav-pills-border-radius: @border-radius-base;
436 @nav-pills-active-link-hover-bg: @component-active-bg;
437 @nav-pills-active-link-hover-color: @component-active-color;
438
439
440 //== Pagination
441 //
442 //##
443
444 @pagination-color: @link-color;
445 @pagination-bg: #fff;
446 @pagination-border: #ddd;
447
448 @pagination-hover-color: @link-hover-color;
449 @pagination-hover-bg: @gray-lighter;
450 @pagination-hover-border: #ddd;
451
452 @pagination-active-color: #fff;
453 @pagination-active-bg: @brand-primary;
454 @pagination-active-border: @brand-primary;
455
456 @pagination-disabled-color: @gray-light;
457 @pagination-disabled-bg: #fff;
458 @pagination-disabled-border: #ddd;
459
460
461 //== Pager
462 //
463 //##
464
465 @pager-bg: @pagination-bg;
466 @pager-border: @pagination-border;
467 @pager-border-radius: 15px;
468
469 @pager-hover-bg: @pagination-hover-bg;
470
471 @pager-active-bg: @pagination-active-bg;
472 @pager-active-color: @pagination-active-color;
473
474 @pager-disabled-color: @pagination-disabled-color;
475
476
477 //== Jumbotron
478 //
479 //##
480
481 @jumbotron-padding: 30px;
482 @jumbotron-color: inherit;
483 @jumbotron-bg: @gray-lighter;
484 @jumbotron-heading-color: inherit;
485 @jumbotron-font-size: ceil((@font-size-base * 1.5));
486
487
488 //== Form states and alerts
489 //
490 //## Define colors for form feedback states and, by default, alerts.
491
492 @state-success-text: #3c763d;
493 @state-success-bg: #dff0d8;
494 @state-success-border: darken(spin(@state-success-bg, -10), 5%);
495
496 @state-info-text: #31708f;
497 @state-info-bg: #d9edf7;
498 @state-info-border: darken(spin(@state-info-bg, -10), 7%);
499
500 @state-warning-text: #8a6d3b;
501 @state-warning-bg: #fcf8e3;
502 @state-warning-border: darken(spin(@state-warning-bg, -10), 5%);
503
504 @state-danger-text: #a94442;
505 @state-danger-bg: #f2dede;
506 @state-danger-border: darken(spin(@state-danger-bg, -10), 5%);
507
508
509 //== Tooltips
510 //
511 //##
512
513 //** Tooltip max width
514 @tooltip-max-width: 200px;
515 //** Tooltip text color
516 @tooltip-color: #fff;
517 //** Tooltip background color
518 @tooltip-bg: #000;
519 @tooltip-opacity: .9;
520
521 //** Tooltip arrow width
522 @tooltip-arrow-width: 5px;
523 //** Tooltip arrow color
524 @tooltip-arrow-color: @tooltip-bg;
525
526
527 //== Popovers
528 //
529 //##
530
531 //** Popover body background color
532 @popover-bg: #fff;
533 //** Popover maximum width
534 @popover-max-width: 276px;
535 //** Popover border color
536 @popover-border-color: rgba(0,0,0,.2);
537 //** Popover fallback border color
538 @popover-fallback-border-color: #ccc;
539
540 //** Popover title background color
541 @popover-title-bg: darken(@popover-bg, 3%);
542
543 //** Popover arrow width
544 @popover-arrow-width: 10px;
545 //** Popover arrow color
546 @popover-arrow-color: @popover-bg;
547
548 //** Popover outer arrow width
549 @popover-arrow-outer-width: (@popover-arrow-width + 1);
550 //** Popover outer arrow color
551 @popover-arrow-outer-color: fadein(@popover-border-color, 5%);
552 //** Popover outer arrow fallback color
553 @popover-arrow-outer-fallback-color: darken(@popover-fallback-border-color, 20%);
554
555
556 //== Labels
557 //
558 //##
559
560 //** Default label background color
561 @label-default-bg: @gray-light;
562 //** Primary label background color
563 @label-primary-bg: @brand-primary;
564 //** Success label background color
565 @label-success-bg: @brand-success;
566 //** Info label background color
567 @label-info-bg: @brand-info;
568 //** Warning label background color
569 @label-warning-bg: @brand-warning;
570 //** Danger label background color
571 @label-danger-bg: @brand-danger;
572
573 //** Default label text color
574 @label-color: #fff;
575 //** Default text color of a linked label
576 @label-link-hover-color: #fff;
577
578
579 //== Modals
580 //
581 //##
582
583 //** Padding applied to the modal body
584 @modal-inner-padding: 15px;
585
586 //** Padding applied to the modal title
587 @modal-title-padding: 15px;
588 //** Modal title line-height
589 @modal-title-line-height: @line-height-base;
590
591 //** Background color of modal content area
592 @modal-content-bg: #fff;
593 //** Modal content border color
594 @modal-content-border-color: rgba(0,0,0,.2);
595 //** Modal content border color **for IE8**
596 @modal-content-fallback-border-color: #999;
597
598 //** Modal backdrop background color
599 @modal-backdrop-bg: #000;
600 //** Modal backdrop opacity
601 @modal-backdrop-opacity: .5;
602 //** Modal header border color
603 @modal-header-border-color: #e5e5e5;
604 //** Modal footer border color
605 @modal-footer-border-color: @modal-header-border-color;
606
607 @modal-lg: 900px;
608 @modal-md: 600px;
609 @modal-sm: 300px;
610
611
612 //== Alerts
613 //
614 //## Define alert colors, border radius, and padding.
615
616 @alert-padding: 15px;
617 @alert-border-radius: @border-radius-base;
618 @alert-link-font-weight: bold;
619
620 @alert-success-bg: @state-success-bg;
621 @alert-success-text: @state-success-text;
622 @alert-success-border: @state-success-border;
623
624 @alert-info-bg: @state-info-bg;
625 @alert-info-text: @state-info-text;
626 @alert-info-border: @state-info-border;
627
628 @alert-warning-bg: @state-warning-bg;
629 @alert-warning-text: @state-warning-text;
630 @alert-warning-border: @state-warning-border;
631
632 @alert-danger-bg: @state-danger-bg;
633 @alert-danger-text: @state-danger-text;
634 @alert-danger-border: @state-danger-border;
635
636
637 //== Progress bars
638 //
639 //##
640
641 //** Background color of the whole progress component
642 @progress-bg: #f5f5f5;
643 //** Progress bar text color
644 @progress-bar-color: #fff;
645 //** Variable for setting rounded corners on progress bar.
646 @progress-border-radius: @border-radius-base;
647
648 //** Default progress bar color
649 @progress-bar-bg: @brand-primary;
650 //** Success progress bar color
651 @progress-bar-success-bg: @brand-success;
652 //** Warning progress bar color
653 @progress-bar-warning-bg: @brand-warning;
654 //** Danger progress bar color
655 @progress-bar-danger-bg: @brand-danger;
656 //** Info progress bar color
657 @progress-bar-info-bg: @brand-info;
658
659
660 //== List group
661 //
662 //##
663
664 //** Background color on `.list-group-item`
665 @list-group-bg: #fff;
666 //** `.list-group-item` border color
667 @list-group-border: #ddd;
668 //** List group border radius
669 @list-group-border-radius: @border-radius-base;
670
671 //** Background color of single list items on hover
672 @list-group-hover-bg: #f5f5f5;
673 //** Text color of active list items
674 @list-group-active-color: @component-active-color;
675 //** Background color of active list items
676 @list-group-active-bg: @component-active-bg;
677 //** Border color of active list elements
678 @list-group-active-border: @list-group-active-bg;
679 //** Text color for content within active list items
680 @list-group-active-text-color: lighten(@list-group-active-bg, 40%);
681
682 //** Text color of disabled list items
683 @list-group-disabled-color: @gray-light;
684 //** Background color of disabled list items
685 @list-group-disabled-bg: @gray-lighter;
686 //** Text color for content within disabled list items
687 @list-group-disabled-text-color: @list-group-disabled-color;
688
689 @list-group-link-color: #555;
690 @list-group-link-hover-color: @list-group-link-color;
691 @list-group-link-heading-color: #333;
692
693
694 //== Panels
695 //
696 //##
697
698 @panel-bg: #fff;
699 @panel-body-padding: 15px;
700 @panel-heading-padding: 10px 15px;
701 @panel-footer-padding: @panel-heading-padding;
702 @panel-border-radius: @border-radius-base;
703
704 //** Border color for elements within panels
705 @panel-inner-border: #ddd;
706 @panel-footer-bg: #f5f5f5;
707
708 @panel-default-text: @gray-dark;
709 @panel-default-border: #ddd;
710 @panel-default-heading-bg: #f5f5f5;
711
712 @panel-primary-text: #fff;
713 @panel-primary-border: @brand-primary;
714 @panel-primary-heading-bg: @brand-primary;
715
716 @panel-success-text: @state-success-text;
717 @panel-success-border: @state-success-border;
718 @panel-success-heading-bg: @state-success-bg;
719
720 @panel-info-text: @state-info-text;
721 @panel-info-border: @state-info-border;
722 @panel-info-heading-bg: @state-info-bg;
723
724 @panel-warning-text: @state-warning-text;
725 @panel-warning-border: @state-warning-border;
726 @panel-warning-heading-bg: @state-warning-bg;
727
728 @panel-danger-text: @state-danger-text;
729 @panel-danger-border: @state-danger-border;
730 @panel-danger-heading-bg: @state-danger-bg;
731
732
733 //== Thumbnails
734 //
735 //##
736
737 //** Padding around the thumbnail image
738 @thumbnail-padding: 4px;
739 //** Thumbnail background color
740 @thumbnail-bg: @body-bg;
741 //** Thumbnail border color
742 @thumbnail-border: #ddd;
743 //** Thumbnail border radius
744 @thumbnail-border-radius: @border-radius-base;
745
746 //** Custom text color for thumbnail captions
747 @thumbnail-caption-color: @text-color;
748 //** Padding around the thumbnail caption
749 @thumbnail-caption-padding: 9px;
750
751
752 //== Wells
753 //
754 //##
755
756 @well-bg: #f5f5f5;
757 @well-border: darken(@well-bg, 7%);
758
759
760 //== Badges
761 //
762 //##
763
764 @badge-color: #fff;
765 //** Linked badge text color on hover
766 @badge-link-hover-color: #fff;
767 @badge-bg: @gray-light;
768
769 //** Badge text color in active nav link
770 @badge-active-color: @link-color;
771 //** Badge background color in active nav link
772 @badge-active-bg: #fff;
773
774 @badge-font-weight: bold;
775 @badge-line-height: 1;
776 @badge-border-radius: 10px;
777
778
779 //== Breadcrumbs
780 //
781 //##
782
783 @breadcrumb-padding-vertical: 8px;
784 @breadcrumb-padding-horizontal: 15px;
785 //** Breadcrumb background color
786 @breadcrumb-bg: #f5f5f5;
787 //** Breadcrumb text color
788 @breadcrumb-color: #ccc;
789 //** Text color of current page in the breadcrumb
790 @breadcrumb-active-color: @gray-light;
791 //** Textual separator for between breadcrumb elements
792 @breadcrumb-separator: "/";
793
794
795 //== Carousel
796 //
797 //##
798
799 @carousel-text-shadow: 0 1px 2px rgba(0,0,0,.6);
800
801 @carousel-control-color: #fff;
802 @carousel-control-width: 15%;
803 @carousel-control-opacity: .5;
804 @carousel-control-font-size: 20px;
805
806 @carousel-indicator-active-bg: #fff;
807 @carousel-indicator-border-color: #fff;
808
809 @carousel-caption-color: #fff;
810
811
812 //== Close
813 //
814 //##
815
816 @close-font-weight: bold;
817 @close-color: #000;
818 @close-text-shadow: 0 1px 0 #fff;
819
820
821 //== Code
822 //
823 //##
824
825 @code-color: #c7254e;
826 @code-bg: #f9f2f4;
827
828 @kbd-color: #fff;
829 @kbd-bg: #333;
830
831 @pre-bg: #f5f5f5;
832 @pre-color: @gray-dark;
833 @pre-border-color: #ccc;
834 @pre-scrollable-max-height: 340px;
835
836
837 //== Type
838 //
839 //##
840
841 //** Horizontal offset for forms and lists.
842 @component-offset-horizontal: 180px;
843 //** Text muted color
844 @text-muted: @gray-light;
845 //** Abbreviations and acronyms border color
846 @abbr-border-color: @gray-light;
847 //** Headings small color
848 @headings-small-color: @gray-light;
849 //** Blockquote small color
850 @blockquote-small-color: @gray-light;
851 //** Blockquote font size
852 @blockquote-font-size: (@font-size-base * 1.25);
853 //** Blockquote border color
854 @blockquote-border-color: @gray-lighter;
855 //** Page header border color
856 @page-header-border-color: @gray-lighter;
857 //** Width of horizontal description list titles
858 @dl-horizontal-offset: @component-offset-horizontal;
859 //** Horizontal line color.
860 @hr-border: @gray-lighter;
+0
-29
source/misc/embedded_libs/fmt-8.1.1/doc/bootstrap/wells.less less more
0 //
1 // Wells
2 // --------------------------------------------------
3
4
5 // Base class
6 .well {
7 min-height: 20px;
8 padding: 19px;
9 margin-bottom: 20px;
10 background-color: @well-bg;
11 border: 1px solid @well-border;
12 border-radius: @border-radius-base;
13 .box-shadow(inset 0 1px 1px rgba(0,0,0,.05));
14 blockquote {
15 border-color: #ddd;
16 border-color: rgba(0,0,0,.15);
17 }
18 }
19
20 // Sizes
21 .well-lg {
22 padding: 24px;
23 border-radius: @border-radius-large;
24 }
25 .well-sm {
26 padding: 9px;
27 border-radius: @border-radius-small;
28 }
+0
-118
source/misc/embedded_libs/fmt-8.1.1/doc/build.py less more
0 #!/usr/bin/env python3
1 # Build the documentation.
2
3 import errno, os, re, sys
4 from subprocess import check_call, CalledProcessError, Popen, PIPE, STDOUT
5
6 versions = ['1.0.0', '1.1.0', '2.0.0', '3.0.2', '4.0.0', '4.1.0', '5.0.0', '5.1.0', '5.2.0', '5.2.1', '5.3.0', '6.0.0', '6.1.0', '6.1.1', '6.1.2', '6.2.0', '6.2.1', '7.0.0', '7.0.1', '7.0.2', '7.0.3', '7.1.0', '7.1.1', '7.1.2', '7.1.3', '8.0.0', '8.0.1', '8.1.0', '8.1.1']
7
8 class Pip:
9 def __init__(self, venv_dir):
10 self.path = os.path.join(venv_dir, 'bin', 'pip')
11
12 def install(self, package, commit=None):
13 "Install package using pip."
14 if commit:
15 package = 'git+https://github.com/{0}.git@{1}'.format(package, commit)
16 print('Installing {0}'.format(package))
17 check_call([self.path, 'install', package])
18
19 def create_build_env(venv_dir='virtualenv'):
20 # Create virtualenv.
21 if not os.path.exists(venv_dir):
22 check_call(['python3', '-m', 'venv', venv_dir])
23 # Install Sphinx and Breathe. Require the exact version of Sphinx which is
24 # compatible with Breathe.
25 pip = Pip(venv_dir)
26 pip.install('wheel')
27 pip.install('six')
28 # See: https://github.com/sphinx-doc/sphinx/issues/9777
29 pip.install('docutils==0.17.1')
30 pip.install('sphinx-doc/sphinx', 'v3.3.0')
31 pip.install('michaeljones/breathe', 'v4.25.0')
32
33 def build_docs(version='dev', **kwargs):
34 doc_dir = kwargs.get('doc_dir', os.path.dirname(os.path.realpath(__file__)))
35 work_dir = kwargs.get('work_dir', '.')
36 include_dir = kwargs.get(
37 'include_dir', os.path.join(os.path.dirname(doc_dir), 'include', 'fmt'))
38 # Build docs.
39 cmd = ['doxygen', '-']
40 p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
41 doxyxml_dir = os.path.join(work_dir, 'doxyxml')
42 out, _ = p.communicate(input=r'''
43 PROJECT_NAME = fmt
44 GENERATE_LATEX = NO
45 GENERATE_MAN = NO
46 GENERATE_RTF = NO
47 CASE_SENSE_NAMES = NO
48 INPUT = {0}/chrono.h {0}/color.h {0}/core.h {0}/compile.h \
49 {0}/format.h {0}/os.h {0}/ostream.h {0}/printf.h \
50 {0}/xchar.h
51 QUIET = YES
52 JAVADOC_AUTOBRIEF = YES
53 AUTOLINK_SUPPORT = NO
54 GENERATE_HTML = NO
55 GENERATE_XML = YES
56 XML_OUTPUT = {1}
57 ALIASES = "rst=\verbatim embed:rst"
58 ALIASES += "endrst=\endverbatim"
59 MACRO_EXPANSION = YES
60 PREDEFINED = _WIN32=1 \
61 __linux__=1 \
62 FMT_ENABLE_IF(...)= \
63 FMT_USE_VARIADIC_TEMPLATES=1 \
64 FMT_USE_RVALUE_REFERENCES=1 \
65 FMT_USE_USER_DEFINED_LITERALS=1 \
66 FMT_USE_ALIAS_TEMPLATES=1 \
67 FMT_API= \
68 "FMT_BEGIN_NAMESPACE=namespace fmt {{" \
69 "FMT_END_NAMESPACE=}}" \
70 "FMT_STRING_ALIAS=1" \
71 "FMT_VARIADIC(...)=" \
72 "FMT_VARIADIC_W(...)=" \
73 "FMT_DOC=1"
74 EXCLUDE_SYMBOLS = fmt::formatter fmt::printf_formatter fmt::arg_join \
75 fmt::basic_format_arg::handle
76 '''.format(include_dir, doxyxml_dir).encode('UTF-8'))
77 out = out.decode('utf-8')
78 internal_symbols = [
79 'fmt::detail::.*',
80 'basic_data<>',
81 'fmt::type_identity',
82 'fmt::dynamic_formatter'
83 ]
84 noisy_warnings = [
85 'warning: (Compound|Member .* of class) (' + '|'.join(internal_symbols) + \
86 ') is not documented.',
87 'warning: Internal inconsistency: .* does not belong to any container!'
88 ]
89 for w in noisy_warnings:
90 out = re.sub('.*' + w + '\n', '', out)
91 print(out)
92 if p.returncode != 0:
93 raise CalledProcessError(p.returncode, cmd)
94
95 html_dir = os.path.join(work_dir, 'html')
96 main_versions = reversed(versions[-3:])
97 check_call([os.path.join(work_dir, 'virtualenv', 'bin', 'sphinx-build'),
98 '-Dbreathe_projects.format=' + os.path.abspath(doxyxml_dir),
99 '-Dversion=' + version, '-Drelease=' + version,
100 '-Aversion=' + version, '-Aversions=' + ','.join(main_versions),
101 '-b', 'html', doc_dir, html_dir])
102 try:
103 check_call(['lessc', '--verbose', '--clean-css',
104 '--include-path=' + os.path.join(doc_dir, 'bootstrap'),
105 os.path.join(doc_dir, 'fmt.less'),
106 os.path.join(html_dir, '_static', 'fmt.css')])
107 except OSError as e:
108 if e.errno != errno.ENOENT:
109 raise
110 print('lessc not found; make sure that Less (http://lesscss.org/) ' +
111 'is installed')
112 sys.exit(1)
113 return html_dir
114
115 if __name__ == '__main__':
116 create_build_env()
117 build_docs(sys.argv[1])
+0
-256
source/misc/embedded_libs/fmt-8.1.1/doc/conf.py less more
0 # -*- coding: utf-8 -*-
1 #
2 # format documentation build configuration file, created by
3 # sphinx-quickstart on Tue Dec 18 06:46:16 2012.
4 #
5 # This file is execfile()d with the current directory set to its containing dir.
6 #
7 # Note that not all possible configuration values are present in this
8 # autogenerated file.
9 #
10 # All configuration values have a default; values that are commented out
11 # serve to show the default.
12
13 import sys, os, re, subprocess
14
15 # If extensions (or modules to document with autodoc) are in another directory,
16 # add these directories to sys.path here. If the directory is relative to the
17 # documentation root, use os.path.abspath to make it absolute, like shown here.
18 #sys.path.insert(0, os.path.abspath('.'))
19
20 # -- General configuration -----------------------------------------------------
21
22 # If your documentation needs a minimal Sphinx version, state it here.
23 needs_sphinx = '1.2'
24
25 if os.environ.get('READTHEDOCS', None) == 'True':
26 subprocess.call('doxygen')
27
28 # Add any Sphinx extension module names here, as strings. They can be extensions
29 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
30 extensions = ['sphinx.ext.ifconfig', 'breathe']
31
32 breathe_default_project = "format"
33 breathe_domain_by_extension = {"h" : "cpp"}
34
35 # Add any paths that contain templates here, relative to this directory.
36 templates_path = ['_templates']
37
38 # The suffix of source filenames.
39 source_suffix = '.rst'
40
41 # The encoding of source files.
42 #source_encoding = 'utf-8-sig'
43
44 # The master toctree document.
45 #master_doc = 'contents'
46
47 # General information about the project.
48 project = u'fmt'
49 copyright = u'2012-present, Victor Zverovich'
50
51 # The version info for the project you're documenting, acts as replacement for
52 # |version| and |release|, also used in various other places throughout the
53 # built documents.
54 #
55 # The short X.Y version.
56
57 # Version and release are passed from CMake.
58 #version = None
59
60 # The full version, including alpha/beta/rc tags.
61 #release = version
62
63 # The language for content autogenerated by Sphinx. Refer to documentation
64 # for a list of supported languages.
65 #language = None
66
67 # There are two options for replacing |today|: either, you set today to some
68 # non-false value, then it is used:
69 #today = ''
70 # Else, today_fmt is used as the format for a strftime call.
71 #today_fmt = '%B %d, %Y'
72
73 # List of patterns, relative to source directory, that match files and
74 # directories to ignore when looking for source files.
75 exclude_patterns = ['virtualenv']
76
77 # The reST default role (used for this markup: `text`) to use for all documents.
78 default_role = 'cpp:any'
79
80 # If true, '()' will be appended to :func: etc. cross-reference text.
81 #add_function_parentheses = True
82
83 # If true, the current module name will be prepended to all description
84 # unit titles (such as .. function::).
85 #add_module_names = True
86
87 # If true, sectionauthor and moduleauthor directives will be shown in the
88 # output. They are ignored by default.
89 #show_authors = False
90
91 # The name of the Pygments (syntax highlighting) style to use.
92 pygments_style = 'sphinx'
93
94 highlight_language = 'c++'
95
96 primary_domain = 'cpp'
97
98 # A list of ignored prefixes for module index sorting.
99 #modindex_common_prefix = []
100
101
102 # -- Options for HTML output ---------------------------------------------------
103
104 # The theme to use for HTML and HTML Help pages. See the documentation for
105 # a list of builtin themes.
106 html_theme = 'basic-bootstrap'
107
108 # Theme options are theme-specific and customize the look and feel of a theme
109 # further. For a list of options available for each theme, see the
110 # documentation.
111 #html_theme_options = {}
112
113 # Add any paths that contain custom themes here, relative to this directory.
114 html_theme_path = ['.']
115
116 # The name for this set of Sphinx documents. If None, it defaults to
117 # "<project> v<release> documentation".
118 #html_title = None
119
120 # A shorter title for the navigation bar. Default is the same as html_title.
121 #html_short_title = None
122
123 # The name of an image file (relative to this directory) to place at the top
124 # of the sidebar.
125 #html_logo = None
126
127 # The name of an image file (within the static path) to use as favicon of the
128 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
129 # pixels large.
130 #html_favicon = None
131
132 # Add any paths that contain custom static files (such as style sheets) here,
133 # relative to this directory. They are copied after the builtin static files,
134 # so a file named "default.css" will overwrite the builtin "default.css".
135 html_static_path = ['_static']
136
137 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
138 # using the given strftime format.
139 #html_last_updated_fmt = '%b %d, %Y'
140
141 # If true, SmartyPants will be used to convert quotes and dashes to
142 # typographically correct entities.
143 #html_use_smartypants = True
144
145 # Custom sidebar templates, maps document names to template names.
146 html_sidebars = {
147 '**': ['localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html']
148 }
149
150 # Additional templates that should be rendered to pages, maps page names to
151 # template names.
152 #html_additional_pages = {}
153
154 # If false, no module index is generated.
155 #html_domain_indices = True
156
157 # If false, no index is generated.
158 #html_use_index = True
159
160 # If true, the index is split into individual pages for each letter.
161 #html_split_index = False
162
163 # If true, links to the reST sources are added to the pages.
164 #html_show_sourcelink = True
165
166 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
167 #html_show_sphinx = True
168
169 # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
170 #html_show_copyright = True
171
172 # If true, an OpenSearch description file will be output, and all pages will
173 # contain a <link> tag referring to it. The value of this option must be the
174 # base URL from which the finished HTML is served.
175 #html_use_opensearch = ''
176
177 # This is the file name suffix for HTML files (e.g. ".xhtml").
178 #html_file_suffix = None
179
180 # Output file base name for HTML help builder.
181 htmlhelp_basename = 'formatdoc'
182
183
184 # -- Options for LaTeX output --------------------------------------------------
185
186 latex_elements = {
187 # The paper size ('letterpaper' or 'a4paper').
188 #'papersize': 'letterpaper',
189
190 # The font size ('10pt', '11pt' or '12pt').
191 #'pointsize': '10pt',
192
193 # Additional stuff for the LaTeX preamble.
194 #'preamble': '',
195 }
196
197 # Grouping the document tree into LaTeX files. List of tuples
198 # (source start file, target name, title, author, documentclass [howto/manual]).
199 latex_documents = [
200 ('index', 'format.tex', u'fmt documentation',
201 u'Victor Zverovich', 'manual'),
202 ]
203
204 # The name of an image file (relative to this directory) to place at the top of
205 # the title page.
206 #latex_logo = None
207
208 # For "manual" documents, if this is true, then toplevel headings are parts,
209 # not chapters.
210 #latex_use_parts = False
211
212 # If true, show page references after internal links.
213 #latex_show_pagerefs = False
214
215 # If true, show URL addresses after external links.
216 #latex_show_urls = False
217
218 # Documents to append as an appendix to all manuals.
219 #latex_appendices = []
220
221 # If false, no module index is generated.
222 #latex_domain_indices = True
223
224
225 # -- Options for manual page output --------------------------------------------
226
227 # One entry per manual page. List of tuples
228 # (source start file, name, description, authors, manual section).
229 man_pages = [
230 ('index', 'fmt', u'fmt documentation', [u'Victor Zverovich'], 1)
231 ]
232
233 # If true, show URL addresses after external links.
234 #man_show_urls = False
235
236
237 # -- Options for Texinfo output ------------------------------------------------
238
239 # Grouping the document tree into Texinfo files. List of tuples
240 # (source start file, target name, title, author,
241 # dir menu entry, description, category)
242 texinfo_documents = [
243 ('index', 'fmt', u'fmt documentation',
244 u'Victor Zverovich', 'fmt', 'One line description of project.',
245 'Miscellaneous'),
246 ]
247
248 # Documents to append as an appendix to all manuals.
249 #texinfo_appendices = []
250
251 # If false, no module index is generated.
252 #texinfo_domain_indices = True
253
254 # How to display URL addresses: 'footnote', 'no', or 'inline'.
255 #texinfo_show_urls = 'footnote'
+0
-10
source/misc/embedded_libs/fmt-8.1.1/doc/contents.rst less more
0 ########
1 Contents
2 ########
3
4 .. toctree::
5 :maxdepth: 2
6
7 usage
8 api
9 syntax
+0
-71
source/misc/embedded_libs/fmt-8.1.1/doc/fmt.less less more
0 @import 'bootstrap.less';
1
2 @header-bg: #094d75;
3 @icon-font-path: "fonts/";
4
5 html {
6 overflow-y: scroll;
7 }
8
9 .navbar {
10 border-radius: 0;
11 margin-bottom: 0;
12 background-color: darken(@header-bg, 10%);
13 }
14
15 .jumbotron {
16 #gradient > .vertical(@header-bg; darken(@header-bg, 2%); 50%; 50%);
17 background-size: 100% 4px;
18 background-color: @header-bg;
19 background-repeat: repeat-y;
20 color: white;
21 text-align: center;
22 }
23
24 div.sphinxsidebar {
25 margin-left: 0;
26 }
27
28 // Keep content not too wide for better readability.
29 .navbar-content, .content {
30 .make-md-column-offset(1);
31 .make-md-column(10);
32 .make-lg-column-offset(2);
33 .make-lg-column(8);
34 }
35
36 .footer {
37 padding-top: 20px;
38 padding-bottom: 20px;
39 border-top: 1px solid @gray-lighter;
40 text-align: center;
41 }
42
43 // Indent descriptions of classes, functions and macros.
44 .class dd, .function dd, .macro dd {
45 margin-left: 20px;
46 }
47
48 // Remove Bootstrap padding for Sphinx containers.
49 .breathe-sectiondef.container {
50 padding: 0;
51 }
52
53 // Remove Bootstrap padding for Sphinx code elements in API signatures.
54 .descclassname, .descname {
55 padding: 0;
56 }
57
58 // Override center alignment in tables.
59 td {
60 text-align: left;
61 }
62
63 p.rubric {
64 margin-top: 10px;
65 }
66
67 .github-btn {
68 border: 0;
69 overflow: hidden;
70 }
+0
-198
source/misc/embedded_libs/fmt-8.1.1/doc/index.rst less more
0 Overview
1 ========
2
3 **{fmt}** is an open-source formatting library providing a fast and safe
4 alternative to C stdio and C++ iostreams.
5
6 .. raw:: html
7
8 <div class="panel panel-default">
9 <div class="panel-heading">What users say:</div>
10 <div class="panel-body">
11 Thanks for creating this library. It’s been a hole in C++ for
12 a long time. I’ve used both <code>boost::format</code> and
13 <code>loki::SPrintf</code>, and neither felt like the right answer.
14 This does.
15 </div>
16 </div>
17
18 .. _format-api-intro:
19
20 Format API
21 ----------
22
23 The format API is similar in spirit to the C ``printf`` family of function but
24 is safer, simpler and several times `faster
25 <https://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_
26 than common standard library implementations.
27 The `format string syntax <syntax.html>`_ is similar to the one used by
28 `str.format <https://docs.python.org/3/library/stdtypes.html#str.format>`_ in
29 Python:
30
31 .. code:: c++
32
33 std::string s = fmt::format("The answer is {}.", 42);
34
35 The ``fmt::format`` function returns a string "The answer is 42.". You can use
36 ``fmt::memory_buffer`` to avoid constructing ``std::string``:
37
38 .. code:: c++
39
40 auto out = fmt::memory_buffer();
41 format_to(std::back_inserter(out),
42 "For a moment, {} happened.", "nothing");
43 auto data = out.data(); // pointer to the formatted data
44 auto size = out.size(); // size of the formatted data
45
46 The ``fmt::print`` function performs formatting and writes the result to a stream:
47
48 .. code:: c++
49
50 fmt::print(stderr, "System error code = {}\n", errno);
51
52 If you omit the file argument the function will print to ``stdout``:
53
54 .. code:: c++
55
56 fmt::print("Don't {}\n", "panic");
57
58 The format API also supports positional arguments useful for localization:
59
60 .. code:: c++
61
62 fmt::print("I'd rather be {1} than {0}.", "right", "happy");
63
64 You can pass named arguments with ``fmt::arg``:
65
66 .. code:: c++
67
68 fmt::print("Hello, {name}! The answer is {number}. Goodbye, {name}.",
69 fmt::arg("name", "World"), fmt::arg("number", 42));
70
71 If your compiler supports C++11 user-defined literals, the suffix ``_a`` offers
72 an alternative, slightly terser syntax for named arguments:
73
74 .. code:: c++
75
76 using namespace fmt::literals;
77 fmt::print("Hello, {name}! The answer is {number}. Goodbye, {name}.",
78 "name"_a="World", "number"_a=42);
79
80 .. _safety:
81
82 Safety
83 ------
84
85 The library is fully type safe, automatic memory management prevents buffer
86 overflow, errors in format strings are reported using exceptions or at compile
87 time. For example, the code
88
89 .. code:: c++
90
91 fmt::format("The answer is {:d}", "forty-two");
92
93 throws the ``format_error`` exception because the argument ``"forty-two"`` is a
94 string while the format code ``d`` only applies to integers.
95
96 The code
97
98 .. code:: c++
99
100 format(FMT_STRING("The answer is {:d}"), "forty-two");
101
102 reports a compile-time error on compilers that support relaxed ``constexpr``.
103 See `here <api.html#c.fmt>`_ for details.
104
105 The following code
106
107 .. code:: c++
108
109 fmt::format("Cyrillic letter {}", L'\x42e');
110
111 produces a compile-time error because wide character ``L'\x42e'`` cannot be
112 formatted into a narrow string. For comparison, writing a wide character to
113 ``std::ostream`` results in its numeric value being written to the stream
114 (i.e. 1070 instead of letter 'ю' which is represented by ``L'\x42e'`` if we
115 use Unicode) which is rarely desirable.
116
117 Compact Binary Code
118 -------------------
119
120 The library produces compact per-call compiled code. For example
121 (`godbolt <https://godbolt.org/g/TZU4KF>`_),
122
123 .. code:: c++
124
125 #include <fmt/core.h>
126
127 int main() {
128 fmt::print("The answer is {}.", 42);
129 }
130
131 compiles to just
132
133 .. code:: asm
134
135 main: # @main
136 sub rsp, 24
137 mov qword ptr [rsp], 42
138 mov rcx, rsp
139 mov edi, offset .L.str
140 mov esi, 17
141 mov edx, 1
142 call fmt::v7::vprint(fmt::v7::basic_string_view<char>, fmt::v7::format_args)
143 xor eax, eax
144 add rsp, 24
145 ret
146 .L.str:
147 .asciz "The answer is {}."
148
149 .. _portability:
150
151 Portability
152 -----------
153
154 The library is highly portable and relies only on a small set of C++11 features:
155
156 * variadic templates
157 * type traits
158 * rvalue references
159 * decltype
160 * trailing return types
161 * deleted functions
162 * alias templates
163
164 These are available in GCC 4.8, Clang 3.4, MSVC 19.0 (2015) and more recent
165 compiler version. For older compilers use {fmt} `version 4.x
166 <https://github.com/fmtlib/fmt/releases/tag/4.1.0>`_ which is maintained and
167 only requires C++98.
168
169 The output of all formatting functions is consistent across platforms.
170 For example,
171
172 .. code::
173
174 fmt::print("{}", std::numeric_limits<double>::infinity());
175
176 always prints ``inf`` while the output of ``printf`` is platform-dependent.
177
178 .. _ease-of-use:
179
180 Ease of Use
181 -----------
182
183 {fmt} has a small self-contained code base with the core library consisting of
184 just three header files and no external dependencies.
185 A permissive MIT `license <https://github.com/fmtlib/fmt#license>`_ allows
186 using the library both in open-source and commercial projects.
187
188 `Learn more... <contents.html>`_
189
190 .. raw:: html
191
192 <a class="btn btn-success" href="https://github.com/fmtlib/fmt">GitHub Repository</a>
193
194 <div class="section footer">
195 <iframe src="https://ghbtns.com/github-btn.html?user=fmtlib&amp;repo=fmt&amp;type=watch&amp;count=true"
196 class="github-btn" width="100" height="20"></iframe>
197 </div>
+0
-290
source/misc/embedded_libs/fmt-8.1.1/doc/python-license.txt less more
0 A. HISTORY OF THE SOFTWARE
1 ==========================
2
3 Python was created in the early 1990s by Guido van Rossum at Stichting
4 Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
5 as a successor of a language called ABC. Guido remains Python's
6 principal author, although it includes many contributions from others.
7
8 In 1995, Guido continued his work on Python at the Corporation for
9 National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
10 in Reston, Virginia where he released several versions of the
11 software.
12
13 In May 2000, Guido and the Python core development team moved to
14 BeOpen.com to form the BeOpen PythonLabs team. In October of the same
15 year, the PythonLabs team moved to Digital Creations (now Zope
16 Corporation, see http://www.zope.com). In 2001, the Python Software
17 Foundation (PSF, see http://www.python.org/psf/) was formed, a
18 non-profit organization created specifically to own Python-related
19 Intellectual Property. Zope Corporation is a sponsoring member of
20 the PSF.
21
22 All Python releases are Open Source (see http://www.opensource.org for
23 the Open Source Definition). Historically, most, but not all, Python
24 releases have also been GPL-compatible; the table below summarizes
25 the various releases.
26
27 Release Derived Year Owner GPL-
28 from compatible? (1)
29
30 0.9.0 thru 1.2 1991-1995 CWI yes
31 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
32 1.6 1.5.2 2000 CNRI no
33 2.0 1.6 2000 BeOpen.com no
34 1.6.1 1.6 2001 CNRI yes (2)
35 2.1 2.0+1.6.1 2001 PSF no
36 2.0.1 2.0+1.6.1 2001 PSF yes
37 2.1.1 2.1+2.0.1 2001 PSF yes
38 2.2 2.1.1 2001 PSF yes
39 2.1.2 2.1.1 2002 PSF yes
40 2.1.3 2.1.2 2002 PSF yes
41 2.2.1 2.2 2002 PSF yes
42 2.2.2 2.2.1 2002 PSF yes
43 2.2.3 2.2.2 2003 PSF yes
44 2.3 2.2.2 2002-2003 PSF yes
45 2.3.1 2.3 2002-2003 PSF yes
46 2.3.2 2.3.1 2002-2003 PSF yes
47 2.3.3 2.3.2 2002-2003 PSF yes
48 2.3.4 2.3.3 2004 PSF yes
49 2.3.5 2.3.4 2005 PSF yes
50 2.4 2.3 2004 PSF yes
51 2.4.1 2.4 2005 PSF yes
52 2.4.2 2.4.1 2005 PSF yes
53 2.4.3 2.4.2 2006 PSF yes
54 2.4.4 2.4.3 2006 PSF yes
55 2.5 2.4 2006 PSF yes
56 2.5.1 2.5 2007 PSF yes
57 2.5.2 2.5.1 2008 PSF yes
58 2.5.3 2.5.2 2008 PSF yes
59 2.6 2.5 2008 PSF yes
60 2.6.1 2.6 2008 PSF yes
61 2.6.2 2.6.1 2009 PSF yes
62 2.6.3 2.6.2 2009 PSF yes
63 2.6.4 2.6.3 2009 PSF yes
64 2.6.5 2.6.4 2010 PSF yes
65 3.0 2.6 2008 PSF yes
66 3.0.1 3.0 2009 PSF yes
67 3.1 3.0.1 2009 PSF yes
68 3.1.1 3.1 2009 PSF yes
69 3.1.2 3.1.1 2010 PSF yes
70 3.1.3 3.1.2 2010 PSF yes
71 3.1.4 3.1.3 2011 PSF yes
72 3.2 3.1 2011 PSF yes
73 3.2.1 3.2 2011 PSF yes
74 3.2.2 3.2.1 2011 PSF yes
75 3.2.3 3.2.2 2012 PSF yes
76 3.3.0 3.2 2012 PSF yes
77
78 Footnotes:
79
80 (1) GPL-compatible doesn't mean that we're distributing Python under
81 the GPL. All Python licenses, unlike the GPL, let you distribute
82 a modified version without making your changes open source. The
83 GPL-compatible licenses make it possible to combine Python with
84 other software that is released under the GPL; the others don't.
85
86 (2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
87 because its license has a choice of law clause. According to
88 CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
89 is "not incompatible" with the GPL.
90
91 Thanks to the many outside volunteers who have worked under Guido's
92 direction to make these releases possible.
93
94
95 B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
96 ===============================================================
97
98 PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
99 --------------------------------------------
100
101 1. This LICENSE AGREEMENT is between the Python Software Foundation
102 ("PSF"), and the Individual or Organization ("Licensee") accessing and
103 otherwise using this software ("Python") in source or binary form and
104 its associated documentation.
105
106 2. Subject to the terms and conditions of this License Agreement, PSF hereby
107 grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
108 analyze, test, perform and/or display publicly, prepare derivative works,
109 distribute, and otherwise use Python alone or in any derivative version,
110 provided, however, that PSF's License Agreement and PSF's notice of copyright,
111 i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
112 2011, 2012 Python Software Foundation; All Rights Reserved" are retained in Python
113 alone or in any derivative version prepared by Licensee.
114
115 3. In the event Licensee prepares a derivative work that is based on
116 or incorporates Python or any part thereof, and wants to make
117 the derivative work available to others as provided herein, then
118 Licensee hereby agrees to include in any such work a brief summary of
119 the changes made to Python.
120
121 4. PSF is making Python available to Licensee on an "AS IS"
122 basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
123 IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
124 DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
125 FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
126 INFRINGE ANY THIRD PARTY RIGHTS.
127
128 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
129 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
130 A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
131 OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
132
133 6. This License Agreement will automatically terminate upon a material
134 breach of its terms and conditions.
135
136 7. Nothing in this License Agreement shall be deemed to create any
137 relationship of agency, partnership, or joint venture between PSF and
138 Licensee. This License Agreement does not grant permission to use PSF
139 trademarks or trade name in a trademark sense to endorse or promote
140 products or services of Licensee, or any third party.
141
142 8. By copying, installing or otherwise using Python, Licensee
143 agrees to be bound by the terms and conditions of this License
144 Agreement.
145
146
147 BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
148 -------------------------------------------
149
150 BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
151
152 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
153 office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
154 Individual or Organization ("Licensee") accessing and otherwise using
155 this software in source or binary form and its associated
156 documentation ("the Software").
157
158 2. Subject to the terms and conditions of this BeOpen Python License
159 Agreement, BeOpen hereby grants Licensee a non-exclusive,
160 royalty-free, world-wide license to reproduce, analyze, test, perform
161 and/or display publicly, prepare derivative works, distribute, and
162 otherwise use the Software alone or in any derivative version,
163 provided, however, that the BeOpen Python License is retained in the
164 Software, alone or in any derivative version prepared by Licensee.
165
166 3. BeOpen is making the Software available to Licensee on an "AS IS"
167 basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
168 IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
169 DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
170 FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
171 INFRINGE ANY THIRD PARTY RIGHTS.
172
173 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
174 SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
175 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
176 DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
177
178 5. This License Agreement will automatically terminate upon a material
179 breach of its terms and conditions.
180
181 6. This License Agreement shall be governed by and interpreted in all
182 respects by the law of the State of California, excluding conflict of
183 law provisions. Nothing in this License Agreement shall be deemed to
184 create any relationship of agency, partnership, or joint venture
185 between BeOpen and Licensee. This License Agreement does not grant
186 permission to use BeOpen trademarks or trade names in a trademark
187 sense to endorse or promote products or services of Licensee, or any
188 third party. As an exception, the "BeOpen Python" logos available at
189 http://www.pythonlabs.com/logos.html may be used according to the
190 permissions granted on that web page.
191
192 7. By copying, installing or otherwise using the software, Licensee
193 agrees to be bound by the terms and conditions of this License
194 Agreement.
195
196
197 CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
198 ---------------------------------------
199
200 1. This LICENSE AGREEMENT is between the Corporation for National
201 Research Initiatives, having an office at 1895 Preston White Drive,
202 Reston, VA 20191 ("CNRI"), and the Individual or Organization
203 ("Licensee") accessing and otherwise using Python 1.6.1 software in
204 source or binary form and its associated documentation.
205
206 2. Subject to the terms and conditions of this License Agreement, CNRI
207 hereby grants Licensee a nonexclusive, royalty-free, world-wide
208 license to reproduce, analyze, test, perform and/or display publicly,
209 prepare derivative works, distribute, and otherwise use Python 1.6.1
210 alone or in any derivative version, provided, however, that CNRI's
211 License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
212 1995-2001 Corporation for National Research Initiatives; All Rights
213 Reserved" are retained in Python 1.6.1 alone or in any derivative
214 version prepared by Licensee. Alternately, in lieu of CNRI's License
215 Agreement, Licensee may substitute the following text (omitting the
216 quotes): "Python 1.6.1 is made available subject to the terms and
217 conditions in CNRI's License Agreement. This Agreement together with
218 Python 1.6.1 may be located on the Internet using the following
219 unique, persistent identifier (known as a handle): 1895.22/1013. This
220 Agreement may also be obtained from a proxy server on the Internet
221 using the following URL: http://hdl.handle.net/1895.22/1013".
222
223 3. In the event Licensee prepares a derivative work that is based on
224 or incorporates Python 1.6.1 or any part thereof, and wants to make
225 the derivative work available to others as provided herein, then
226 Licensee hereby agrees to include in any such work a brief summary of
227 the changes made to Python 1.6.1.
228
229 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
230 basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
231 IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
232 DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
233 FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
234 INFRINGE ANY THIRD PARTY RIGHTS.
235
236 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
237 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
238 A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
239 OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
240
241 6. This License Agreement will automatically terminate upon a material
242 breach of its terms and conditions.
243
244 7. This License Agreement shall be governed by the federal
245 intellectual property law of the United States, including without
246 limitation the federal copyright law, and, to the extent such
247 U.S. federal law does not apply, by the law of the Commonwealth of
248 Virginia, excluding Virginia's conflict of law provisions.
249 Notwithstanding the foregoing, with regard to derivative works based
250 on Python 1.6.1 that incorporate non-separable material that was
251 previously distributed under the GNU General Public License (GPL), the
252 law of the Commonwealth of Virginia shall govern this License
253 Agreement only as to issues arising under or with respect to
254 Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
255 License Agreement shall be deemed to create any relationship of
256 agency, partnership, or joint venture between CNRI and Licensee. This
257 License Agreement does not grant permission to use CNRI trademarks or
258 trade name in a trademark sense to endorse or promote products or
259 services of Licensee, or any third party.
260
261 8. By clicking on the "ACCEPT" button where indicated, or by copying,
262 installing or otherwise using Python 1.6.1, Licensee agrees to be
263 bound by the terms and conditions of this License Agreement.
264
265 ACCEPT
266
267
268 CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
269 --------------------------------------------------
270
271 Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
272 The Netherlands. All rights reserved.
273
274 Permission to use, copy, modify, and distribute this software and its
275 documentation for any purpose and without fee is hereby granted,
276 provided that the above copyright notice appear in all copies and that
277 both that copyright notice and this permission notice appear in
278 supporting documentation, and that the name of Stichting Mathematisch
279 Centrum or CWI not be used in advertising or publicity pertaining to
280 distribution of the software without specific, written prior
281 permission.
282
283 STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
284 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
285 FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
286 FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
287 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
288 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
289 OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+0
-487
source/misc/embedded_libs/fmt-8.1.1/doc/syntax.rst less more
0 .. _syntax:
1
2 ********************
3 Format String Syntax
4 ********************
5
6 Formatting functions such as :ref:`fmt::format() <format>` and
7 :ref:`fmt::print() <print>` use the same format string syntax described in this
8 section.
9
10 Format strings contain "replacement fields" surrounded by curly braces ``{}``.
11 Anything that is not contained in braces is considered literal text, which is
12 copied unchanged to the output. If you need to include a brace character in the
13 literal text, it can be escaped by doubling: ``{{`` and ``}}``.
14
15 The grammar for a replacement field is as follows:
16
17 .. productionlist:: sf
18 replacement_field: "{" [`arg_id`] [":" (`format_spec` | `chrono_format_spec`)] "}"
19 arg_id: `integer` | `identifier`
20 integer: `digit`+
21 digit: "0"..."9"
22 identifier: `id_start` `id_continue`*
23 id_start: "a"..."z" | "A"..."Z" | "_"
24 id_continue: `id_start` | `digit`
25
26 In less formal terms, the replacement field can start with an *arg_id*
27 that specifies the argument whose value is to be formatted and inserted into
28 the output instead of the replacement field.
29 The *arg_id* is optionally followed by a *format_spec*, which is preceded by a
30 colon ``':'``. These specify a non-default format for the replacement value.
31
32 See also the :ref:`formatspec` section.
33
34 If the numerical arg_ids in a format string are 0, 1, 2, ... in sequence,
35 they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be
36 automatically inserted in that order.
37
38 Named arguments can be referred to by their names or indices.
39
40 Some simple format string examples::
41
42 "First, thou shalt count to {0}" // References the first argument
43 "Bring me a {}" // Implicitly references the first argument
44 "From {} to {}" // Same as "From {0} to {1}"
45
46 The *format_spec* field contains a specification of how the value should be
47 presented, including such details as field width, alignment, padding, decimal
48 precision and so on. Each value type can define its own "formatting
49 mini-language" or interpretation of the *format_spec*.
50
51 Most built-in types support a common formatting mini-language, which is
52 described in the next section.
53
54 A *format_spec* field can also include nested replacement fields in certain
55 positions within it. These nested replacement fields can contain only an
56 argument id; format specifications are not allowed. This allows the formatting
57 of a value to be dynamically specified.
58
59 See the :ref:`formatexamples` section for some examples.
60
61 .. _formatspec:
62
63 Format Specification Mini-Language
64 ==================================
65
66 "Format specifications" are used within replacement fields contained within a
67 format string to define how individual values are presented (see
68 :ref:`syntax`). Each formattable type may define how the format
69 specification is to be interpreted.
70
71 Most built-in types implement the following options for format specifications,
72 although some of the formatting options are only supported by the numeric types.
73
74 The general form of a *standard format specifier* is:
75
76 .. productionlist:: sf
77 format_spec: [[`fill`]`align`][`sign`]["#"]["0"][`width`]["." `precision`]["L"][`type`]
78 fill: <a character other than '{' or '}'>
79 align: "<" | ">" | "^"
80 sign: "+" | "-" | " "
81 width: `integer` | "{" [`arg_id`] "}"
82 precision: `integer` | "{" [`arg_id`] "}"
83 type: "a" | "A" | "b" | "B" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" |
84 : "o" | "p" | "s" | "x" | "X"
85
86 The *fill* character can be any Unicode code point other than ``'{'`` or
87 ``'}'``. The presence of a fill character is signaled by the character following
88 it, which must be one of the alignment options. If the second character of
89 *format_spec* is not a valid alignment option, then it is assumed that both the
90 fill character and the alignment option are absent.
91
92 The meaning of the various alignment options is as follows:
93
94 +---------+----------------------------------------------------------+
95 | Option | Meaning |
96 +=========+==========================================================+
97 | ``'<'`` | Forces the field to be left-aligned within the available |
98 | | space (this is the default for most objects). |
99 +---------+----------------------------------------------------------+
100 | ``'>'`` | Forces the field to be right-aligned within the |
101 | | available space (this is the default for numbers). |
102 +---------+----------------------------------------------------------+
103 | ``'^'`` | Forces the field to be centered within the available |
104 | | space. |
105 +---------+----------------------------------------------------------+
106
107 Note that unless a minimum field width is defined, the field width will always
108 be the same size as the data to fill it, so that the alignment option has no
109 meaning in this case.
110
111 The *sign* option is only valid for number types, and can be one of the
112 following:
113
114 +---------+------------------------------------------------------------+
115 | Option | Meaning |
116 +=========+============================================================+
117 | ``'+'`` | indicates that a sign should be used for both |
118 | | nonnegative as well as negative numbers. |
119 +---------+------------------------------------------------------------+
120 | ``'-'`` | indicates that a sign should be used only for negative |
121 | | numbers (this is the default behavior). |
122 +---------+------------------------------------------------------------+
123 | space | indicates that a leading space should be used on |
124 | | nonnegative numbers, and a minus sign on negative numbers. |
125 +---------+------------------------------------------------------------+
126
127 The ``'#'`` option causes the "alternate form" to be used for the
128 conversion. The alternate form is defined differently for different
129 types. This option is only valid for integer and floating-point types.
130 For integers, when binary, octal, or hexadecimal output is used, this
131 option adds the prefix respective ``"0b"`` (``"0B"``), ``"0"``, or
132 ``"0x"`` (``"0X"``) to the output value. Whether the prefix is
133 lower-case or upper-case is determined by the case of the type
134 specifier, for example, the prefix ``"0x"`` is used for the type ``'x'``
135 and ``"0X"`` is used for ``'X'``. For floating-point numbers the
136 alternate form causes the result of the conversion to always contain a
137 decimal-point character, even if no digits follow it. Normally, a
138 decimal-point character appears in the result of these conversions
139 only if a digit follows it. In addition, for ``'g'`` and ``'G'``
140 conversions, trailing zeros are not removed from the result.
141
142 .. ifconfig:: False
143
144 The ``','`` option signals the use of a comma for a thousands separator.
145 For a locale aware separator, use the ``'L'`` integer presentation type
146 instead.
147
148 *width* is a decimal integer defining the minimum field width. If not
149 specified, then the field width will be determined by the content.
150
151 Preceding the *width* field by a zero (``'0'``) character enables sign-aware
152 zero-padding for numeric types. It forces the padding to be placed after the
153 sign or base (if any) but before the digits. This is used for printing fields in
154 the form '+000000120'. This option is only valid for numeric types and it has no
155 effect on formatting of infinity and NaN.
156
157 The *precision* is a decimal number indicating how many digits should be
158 displayed after the decimal point for a floating-point value formatted with
159 ``'f'`` and ``'F'``, or before and after the decimal point for a floating-point
160 value formatted with ``'g'`` or ``'G'``. For non-number types the field
161 indicates the maximum field size - in other words, how many characters will be
162 used from the field content. The *precision* is not allowed for integer,
163 character, Boolean, and pointer values. Note that a C string must be
164 null-terminated even if precision is specified.
165
166 The ``'L'`` option uses the current locale setting to insert the appropriate
167 number separator characters. This option is only valid for numeric types.
168
169 Finally, the *type* determines how the data should be presented.
170
171 The available string presentation types are:
172
173 +---------+----------------------------------------------------------+
174 | Type | Meaning |
175 +=========+==========================================================+
176 | ``'s'`` | String format. This is the default type for strings and |
177 | | may be omitted. |
178 +---------+----------------------------------------------------------+
179 | none | The same as ``'s'``. |
180 +---------+----------------------------------------------------------+
181
182 The available character presentation types are:
183
184 +---------+----------------------------------------------------------+
185 | Type | Meaning |
186 +=========+==========================================================+
187 | ``'c'`` | Character format. This is the default type for |
188 | | characters and may be omitted. |
189 +---------+----------------------------------------------------------+
190 | none | The same as ``'c'``. |
191 +---------+----------------------------------------------------------+
192
193 The available integer presentation types are:
194
195 +---------+----------------------------------------------------------+
196 | Type | Meaning |
197 +=========+==========================================================+
198 | ``'b'`` | Binary format. Outputs the number in base 2. Using the |
199 | | ``'#'`` option with this type adds the prefix ``"0b"`` |
200 | | to the output value. |
201 +---------+----------------------------------------------------------+
202 | ``'B'`` | Binary format. Outputs the number in base 2. Using the |
203 | | ``'#'`` option with this type adds the prefix ``"0B"`` |
204 | | to the output value. |
205 +---------+----------------------------------------------------------+
206 | ``'c'`` | Character format. Outputs the number as a character. |
207 +---------+----------------------------------------------------------+
208 | ``'d'`` | Decimal integer. Outputs the number in base 10. |
209 +---------+----------------------------------------------------------+
210 | ``'o'`` | Octal format. Outputs the number in base 8. |
211 +---------+----------------------------------------------------------+
212 | ``'x'`` | Hex format. Outputs the number in base 16, using |
213 | | lower-case letters for the digits above 9. Using the |
214 | | ``'#'`` option with this type adds the prefix ``"0x"`` |
215 | | to the output value. |
216 +---------+----------------------------------------------------------+
217 | ``'X'`` | Hex format. Outputs the number in base 16, using |
218 | | upper-case letters for the digits above 9. Using the |
219 | | ``'#'`` option with this type adds the prefix ``"0X"`` |
220 | | to the output value. |
221 +---------+----------------------------------------------------------+
222 | none | The same as ``'d'``. |
223 +---------+----------------------------------------------------------+
224
225 Integer presentation types can also be used with character and Boolean values.
226 Boolean values are formatted using textual representation, either ``true`` or
227 ``false``, if the presentation type is not specified.
228
229 The available presentation types for floating-point values are:
230
231 +---------+----------------------------------------------------------+
232 | Type | Meaning |
233 +=========+==========================================================+
234 | ``'a'`` | Hexadecimal floating point format. Prints the number in |
235 | | base 16 with prefix ``"0x"`` and lower-case letters for |
236 | | digits above 9. Uses ``'p'`` to indicate the exponent. |
237 +---------+----------------------------------------------------------+
238 | ``'A'`` | Same as ``'a'`` except it uses upper-case letters for |
239 | | the prefix, digits above 9 and to indicate the exponent. |
240 +---------+----------------------------------------------------------+
241 | ``'e'`` | Exponent notation. Prints the number in scientific |
242 | | notation using the letter 'e' to indicate the exponent. |
243 +---------+----------------------------------------------------------+
244 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
245 | | upper-case ``'E'`` as the separator character. |
246 +---------+----------------------------------------------------------+
247 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
248 | | number. |
249 +---------+----------------------------------------------------------+
250 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
251 | | ``NAN`` and ``inf`` to ``INF``. |
252 +---------+----------------------------------------------------------+
253 | ``'g'`` | General format. For a given precision ``p >= 1``, |
254 | | this rounds the number to ``p`` significant digits and |
255 | | then formats the result in either fixed-point format |
256 | | or in scientific notation, depending on its magnitude. |
257 | | |
258 | | A precision of ``0`` is treated as equivalent to a |
259 | | precision of ``1``. |
260 +---------+----------------------------------------------------------+
261 | ``'G'`` | General format. Same as ``'g'`` except switches to |
262 | | ``'E'`` if the number gets too large. The |
263 | | representations of infinity and NaN are uppercased, too. |
264 +---------+----------------------------------------------------------+
265 | none | Similar to ``'g'``, except that the default precision is |
266 | | as high as needed to represent the particular value. |
267 +---------+----------------------------------------------------------+
268
269 .. ifconfig:: False
270
271 +---------+----------------------------------------------------------+
272 | | The precise rules are as follows: suppose that the |
273 | | result formatted with presentation type ``'e'`` and |
274 | | precision ``p-1`` would have exponent ``exp``. Then |
275 | | if ``-4 <= exp < p``, the number is formatted |
276 | | with presentation type ``'f'`` and precision |
277 | | ``p-1-exp``. Otherwise, the number is formatted |
278 | | with presentation type ``'e'`` and precision ``p-1``. |
279 | | In both cases insignificant trailing zeros are removed |
280 | | from the significand, and the decimal point is also |
281 | | removed if there are no remaining digits following it. |
282 | | |
283 | | Positive and negative infinity, positive and negative |
284 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
285 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
286 | | the precision. |
287 | | |
288 +---------+----------------------------------------------------------+
289
290 The available presentation types for pointers are:
291
292 +---------+----------------------------------------------------------+
293 | Type | Meaning |
294 +=========+==========================================================+
295 | ``'p'`` | Pointer format. This is the default type for |
296 | | pointers and may be omitted. |
297 +---------+----------------------------------------------------------+
298 | none | The same as ``'p'``. |
299 +---------+----------------------------------------------------------+
300
301 .. _chrono-specs:
302
303 Chrono Format Specifications
304 ============================
305
306 Format specifications for chrono types have the following syntax:
307
308 .. productionlist:: sf
309 chrono_format_spec: [[`fill`]`align`][`width`]["." `precision`][`chrono_specs`]
310 chrono_specs: [`chrono_specs`] `conversion_spec` | `chrono_specs` `literal_char`
311 conversion_spec: "%" [`modifier`] `chrono_type`
312 literal_char: <a character other than '{', '}' or '%'>
313 modifier: "E" | "O"
314 chrono_type: "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" | "F" |
315 : "g" | "G" | "h" | "H" | "I" | "j" | "m" | "M" | "n" | "p" |
316 : "q" | "Q" | "r" | "R" | "S" | "t" | "T" | "u" | "U" | "V" |
317 : "w" | "W" | "x" | "X" | "y" | "Y" | "z" | "Z" | "%"
318
319 Literal chars are copied unchanged to the output. Precision is valid only for
320 ``std::chrono::duration`` types with a floating-point representation type.
321
322 The available presentation types (*chrono_type*) for chrono durations and time
323 points are:
324
325 +---------+--------------------------------------------------------------------+
326 | Type | Meaning |
327 +=========+====================================================================+
328 | ``'H'`` | The hour (24-hour clock) as a decimal number. If the result is a |
329 | | single digit, it is prefixed with 0. The modified command ``%OH`` |
330 | | produces the locale's alternative representation. |
331 +---------+--------------------------------------------------------------------+
332 | ``'M'`` | The minute as a decimal number. If the result is a single digit, |
333 | | it is prefixed with 0. The modified command ``%OM`` produces the |
334 | | locale's alternative representation. |
335 +---------+--------------------------------------------------------------------+
336 | ``'S'`` | Seconds as a decimal number. If the number of seconds is less than |
337 | | 10, the result is prefixed with 0. If the precision of the input |
338 | | cannot be exactly represented with seconds, then the format is a |
339 | | decimal floating-point number with a fixed format and a precision |
340 | | matching that of the precision of the input (or to a microseconds |
341 | | precision if the conversion to floating-point decimal seconds |
342 | | cannot be made within 18 fractional digits). The character for the |
343 | | decimal point is localized according to the locale. The modified |
344 | | command ``%OS`` produces the locale's alternative representation. |
345 +---------+--------------------------------------------------------------------+
346
347 Specifiers that have a calendaric component such as `'d'` (the day of month)
348 are valid only for ``std::tm`` and not durations or time points.
349
350 ``std::tm`` uses the system's `strftime
351 <https://en.cppreference.com/w/cpp/chrono/c/strftime>`_ so refer to its
352 documentation for details on supported conversion specifiers.
353
354 .. _formatexamples:
355
356 Format Examples
357 ===============
358
359 This section contains examples of the format syntax and comparison with
360 the printf formatting.
361
362 In most of the cases the syntax is similar to the printf formatting, with the
363 addition of the ``{}`` and with ``:`` used instead of ``%``.
364 For example, ``"%03.2f"`` can be translated to ``"{:03.2f}"``.
365
366 The new format syntax also supports new and different options, shown in the
367 following examples.
368
369 Accessing arguments by position::
370
371 fmt::format("{0}, {1}, {2}", 'a', 'b', 'c');
372 // Result: "a, b, c"
373 fmt::format("{}, {}, {}", 'a', 'b', 'c');
374 // Result: "a, b, c"
375 fmt::format("{2}, {1}, {0}", 'a', 'b', 'c');
376 // Result: "c, b, a"
377 fmt::format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated
378 // Result: "abracadabra"
379
380 Aligning the text and specifying a width::
381
382 fmt::format("{:<30}", "left aligned");
383 // Result: "left aligned "
384 fmt::format("{:>30}", "right aligned");
385 // Result: " right aligned"
386 fmt::format("{:^30}", "centered");
387 // Result: " centered "
388 fmt::format("{:*^30}", "centered"); // use '*' as a fill char
389 // Result: "***********centered***********"
390
391 Dynamic width::
392
393 fmt::format("{:<{}}", "left aligned", 30);
394 // Result: "left aligned "
395
396 Dynamic precision::
397
398 fmt::format("{:.{}f}", 3.14, 1);
399 // Result: "3.1"
400
401 Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
402
403 fmt::format("{:+f}; {:+f}", 3.14, -3.14); // show it always
404 // Result: "+3.140000; -3.140000"
405 fmt::format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers
406 // Result: " 3.140000; -3.140000"
407 fmt::format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}'
408 // Result: "3.140000; -3.140000"
409
410 Replacing ``%x`` and ``%o`` and converting the value to different bases::
411
412 fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
413 // Result: "int: 42; hex: 2a; oct: 52; bin: 101010"
414 // with 0x or 0 or 0b as prefix:
415 fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42);
416 // Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010"
417
418 Padded hex byte with prefix and always prints both hex characters::
419
420 fmt::format("{:#04x}", 0);
421 // Result: "0x00"
422
423 Box drawing using Unicode fill::
424
425 fmt::print(
426 "┌{0:─^{2}}┐\n"
427 "│{1: ^{2}}│\n"
428 "└{0:─^{2}}┘\n", "", "Hello, world!", 20);
429
430 prints::
431
432 ┌────────────────────┐
433 │ Hello, world! │
434 └────────────────────┘
435
436 Using type-specific formatting::
437
438 #include <fmt/chrono.h>
439
440 auto t = tm();
441 t.tm_year = 2010 - 1900;
442 t.tm_mon = 7;
443 t.tm_mday = 4;
444 t.tm_hour = 12;
445 t.tm_min = 15;
446 t.tm_sec = 58;
447 fmt::print("{:%Y-%m-%d %H:%M:%S}", t);
448 // Prints: 2010-08-04 12:15:58
449
450 Using the comma as a thousands separator::
451
452 #include <fmt/format.h>
453
454 auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890);
455 // s == "1,234,567,890"
456
457 .. ifconfig:: False
458
459 Nesting arguments and more complex examples::
460
461 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
462 ... '{0:{fill}{align}16}") << text, fill=align, align=align)
463 ...
464 'left<<<<<<<<<<<<'
465 '^^^^^center^^^^^'
466 '>>>>>>>>>>>right'
467 >>>
468 >>> octets = [192, 168, 0, 1]
469 Format("{:02X}{:02X}{:02X}{:02X}") << *octets)
470 'C0A80001'
471 >>> int(_, 16)
472 3232235521
473 >>>
474 >>> width = 5
475 >>> for num in range(5,12):
476 ... for base in 'dXob':
477 ... print('{0:{width}{base}}") << num, base=base, width=width), end=' ')
478 ... print()
479 ...
480 5 5 5 101
481 6 6 6 110
482 7 7 7 111
483 8 8 10 1000
484 9 9 11 1001
485 10 A 12 1010
486 11 B 13 1011
+0
-212
source/misc/embedded_libs/fmt-8.1.1/doc/usage.rst less more
0 *****
1 Usage
2 *****
3
4 To use the {fmt} library, add :file:`fmt/core.h`, :file:`fmt/format.h`,
5 :file:`fmt/format-inl.h`, :file:`src/format.cc` and optionally other headers
6 from a `release archive <https://github.com/fmtlib/fmt/releases/latest>`_ or
7 the `Git repository <https://github.com/fmtlib/fmt>`_ to your project.
8 Alternatively, you can :ref:`build the library with CMake <building>`.
9
10 .. _building:
11
12 Building the Library
13 ====================
14
15 The included `CMake build script`__ can be used to build the fmt
16 library on a wide range of platforms. CMake is freely available for
17 download from https://www.cmake.org/download/.
18
19 __ https://github.com/fmtlib/fmt/blob/master/CMakeLists.txt
20
21 CMake works by generating native makefiles or project files that can
22 be used in the compiler environment of your choice. The typical
23 workflow starts with::
24
25 mkdir build # Create a directory to hold the build output.
26 cd build
27 cmake .. # Generate native build scripts.
28
29 where :file:`{<path/to/fmt>}` is a path to the ``fmt`` repository.
30
31 If you are on a \*nix system, you should now see a Makefile in the
32 current directory. Now you can build the library by running :command:`make`.
33
34 Once the library has been built you can invoke :command:`make test` to run
35 the tests.
36
37 You can control generation of the make ``test`` target with the ``FMT_TEST``
38 CMake option. This can be useful if you include fmt as a subdirectory in
39 your project but don't want to add fmt's tests to your ``test`` target.
40
41 If you use Windows and have Visual Studio installed, a :file:`FMT.sln`
42 file and several :file:`.vcproj` files will be created. You can then build them
43 using Visual Studio or msbuild.
44
45 On Mac OS X with Xcode installed, an :file:`.xcodeproj` file will be generated.
46
47 To build a `shared library`__ set the ``BUILD_SHARED_LIBS`` CMake variable to
48 ``TRUE``::
49
50 cmake -DBUILD_SHARED_LIBS=TRUE ...
51
52 __ https://en.wikipedia.org/wiki/Library_%28computing%29#Shared_libraries
53
54
55 To build a `static library` with position independent code (required if the main
56 consumer of the fmt library is a shared library i.e. a Python extension) set the
57 ``CMAKE_POSITION_INDEPENDENT_CODE`` CMake variable to ``TRUE``::
58
59 cmake -DCMAKE_POSITION_INDEPENDENT_CODE=TRUE ...
60
61
62 Installing the Library
63 ======================
64
65 After building the library you can install it on a Unix-like system by running
66 :command:`sudo make install`.
67
68 Usage with CMake
69 ================
70
71 You can add the ``fmt`` library directory into your project and include it in
72 your ``CMakeLists.txt`` file::
73
74 add_subdirectory(fmt)
75
76 or
77
78 ::
79
80 add_subdirectory(fmt EXCLUDE_FROM_ALL)
81
82 to exclude it from ``make``, ``make all``, or ``cmake --build .``.
83
84 You can detect and use an installed version of {fmt} as follows::
85
86 find_package(fmt)
87 target_link_libraries(<your-target> fmt::fmt)
88
89 Setting up your target to use a header-only version of ``fmt`` is equally easy::
90
91 target_link_libraries(<your-target> PRIVATE fmt::fmt-header-only)
92
93 Usage with build2
94 =================
95
96 You can use `build2 <https://build2.org>`_, a dependency manager and a
97 build-system combined, to use ``fmt``.
98
99 Currently this package is available in these package repositories:
100
101 - **https://cppget.org/fmt/** for released and published versions.
102 - `The git repository with the sources of the build2 package of fmt <https://github.com/build2-packaging/fmt.git>`_
103 for unreleased or custom revisions of ``fmt``.
104
105 **Usage:**
106
107 - ``build2`` package name: ``fmt``
108 - Library target name : ``lib{fmt}``
109
110 For example, to make your ``build2`` project depend on ``fmt``:
111
112 - Add one of the repositories to your configurations, or in your
113 ``repositories.manifest``, if not already there::
114
115 :
116 role: prerequisite
117 location: https://pkg.cppget.org/1/stable
118
119 - Add this package as a dependency to your ``./manifest`` file
120 (example for ``v7.0.x``)::
121
122 depends: fmt ~7.0.0
123
124 - Import the target and use it as a prerequisite to your own target
125 using `fmt` in the appropriate ``buildfile``::
126
127 import fmt = fmt%lib{fmt}
128 lib{mylib} : cxx{**} ... $fmt
129
130 Then build your project as usual with `b` or `bdep update`.
131
132 For ``build2`` newcomers or to get more details and use cases, you can read the
133 ``build2``
134 `toolchain introduction <https://build2.org/build2-toolchain/doc/build2-toolchain-intro.xhtml>`_.
135
136 Building the Documentation
137 ==========================
138
139 To build the documentation you need the following software installed on your
140 system:
141
142 * `Python <https://www.python.org/>`_ with pip and virtualenv
143 * `Doxygen <http://www.stack.nl/~dimitri/doxygen/>`_
144 * `Less <http://lesscss.org/>`_ with ``less-plugin-clean-css``.
145 Ubuntu doesn't package the ``clean-css`` plugin so you should use ``npm``
146 instead of ``apt`` to install both ``less`` and the plugin::
147
148 sudo npm install -g less less-plugin-clean-css.
149
150 First generate makefiles or project files using CMake as described in
151 the previous section. Then compile the ``doc`` target/project, for example::
152
153 make doc
154
155 This will generate the HTML documentation in ``doc/html``.
156
157 Conda
158 =====
159
160 fmt can be installed on Linux, macOS and Windows with
161 `Conda <https://docs.conda.io/en/latest/>`__, using its
162 `conda-forge <https://conda-forge.org>`__
163 `package <https://github.com/conda-forge/fmt-feedstock>`__, as follows::
164
165 conda install -c conda-forge fmt
166
167 Vcpkg
168 =====
169
170 You can download and install fmt using the `vcpkg
171 <https://github.com/Microsoft/vcpkg>`__ dependency manager::
172
173 git clone https://github.com/Microsoft/vcpkg.git
174 cd vcpkg
175 ./bootstrap-vcpkg.sh
176 ./vcpkg integrate install
177 ./vcpkg install fmt
178
179 The fmt port in vcpkg is kept up to date by Microsoft team members and community
180 contributors. If the version is out of date, please `create an issue or pull
181 request <https://github.com/Microsoft/vcpkg>`__ on the vcpkg repository.
182
183 LHelper
184 =======
185
186 You can download and install fmt using
187 `lhelper <https://github.com/franko/lhelper>`__ dependency manager::
188
189 lhelper activate <some-environment>
190 lhelper install fmt
191
192 All the recipes for lhelper are kept in the
193 `lhelper's recipe <https://github.com/franko/lhelper-recipes>`__ repository.
194
195 Android NDK
196 ===========
197
198 fmt provides `Android.mk file`__ that can be used to build the library
199 with `Android NDK <https://developer.android.com/tools/sdk/ndk/index.html>`_.
200 For an example of using fmt with Android NDK, see the
201 `android-ndk-example <https://github.com/fmtlib/android-ndk-example>`_
202 repository.
203
204 __ https://github.com/fmtlib/fmt/blob/master/support/Android.mk
205
206 Homebrew
207 ========
208
209 fmt can be installed on OS X using `Homebrew <https://brew.sh/>`_::
210
211 brew install fmt
+0
-234
source/misc/embedded_libs/fmt-8.1.1/include/fmt/args.h less more
0 // Formatting library for C++ - dynamic format arguments
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_ARGS_H_
8 #define FMT_ARGS_H_
9
10 #include <functional> // std::reference_wrapper
11 #include <memory> // std::unique_ptr
12 #include <vector>
13
14 #include "core.h"
15
16 FMT_BEGIN_NAMESPACE
17
18 namespace detail {
19
20 template <typename T> struct is_reference_wrapper : std::false_type {};
21 template <typename T>
22 struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {};
23
24 template <typename T> const T& unwrap(const T& v) { return v; }
25 template <typename T> const T& unwrap(const std::reference_wrapper<T>& v) {
26 return static_cast<const T&>(v);
27 }
28
29 class dynamic_arg_list {
30 // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for
31 // templates it doesn't complain about inability to deduce single translation
32 // unit for placing vtable. So storage_node_base is made a fake template.
33 template <typename = void> struct node {
34 virtual ~node() = default;
35 std::unique_ptr<node<>> next;
36 };
37
38 template <typename T> struct typed_node : node<> {
39 T value;
40
41 template <typename Arg>
42 FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {}
43
44 template <typename Char>
45 FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg)
46 : value(arg.data(), arg.size()) {}
47 };
48
49 std::unique_ptr<node<>> head_;
50
51 public:
52 template <typename T, typename Arg> const T& push(const Arg& arg) {
53 auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg));
54 auto& value = new_node->value;
55 new_node->next = std::move(head_);
56 head_ = std::move(new_node);
57 return value;
58 }
59 };
60 } // namespace detail
61
62 /**
63 \rst
64 A dynamic version of `fmt::format_arg_store`.
65 It's equipped with a storage to potentially temporary objects which lifetimes
66 could be shorter than the format arguments object.
67
68 It can be implicitly converted into `~fmt::basic_format_args` for passing
69 into type-erased formatting functions such as `~fmt::vformat`.
70 \endrst
71 */
72 template <typename Context>
73 class dynamic_format_arg_store
74 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
75 // Workaround a GCC template argument substitution bug.
76 : public basic_format_args<Context>
77 #endif
78 {
79 private:
80 using char_type = typename Context::char_type;
81
82 template <typename T> struct need_copy {
83 static constexpr detail::type mapped_type =
84 detail::mapped_type_constant<T, Context>::value;
85
86 enum {
87 value = !(detail::is_reference_wrapper<T>::value ||
88 std::is_same<T, basic_string_view<char_type>>::value ||
89 std::is_same<T, detail::std_string_view<char_type>>::value ||
90 (mapped_type != detail::type::cstring_type &&
91 mapped_type != detail::type::string_type &&
92 mapped_type != detail::type::custom_type))
93 };
94 };
95
96 template <typename T>
97 using stored_type = conditional_t<detail::is_string<T>::value &&
98 !has_formatter<T, Context>::value &&
99 !detail::is_reference_wrapper<T>::value,
100 std::basic_string<char_type>, T>;
101
102 // Storage of basic_format_arg must be contiguous.
103 std::vector<basic_format_arg<Context>> data_;
104 std::vector<detail::named_arg_info<char_type>> named_info_;
105
106 // Storage of arguments not fitting into basic_format_arg must grow
107 // without relocation because items in data_ refer to it.
108 detail::dynamic_arg_list dynamic_args_;
109
110 friend class basic_format_args<Context>;
111
112 unsigned long long get_types() const {
113 return detail::is_unpacked_bit | data_.size() |
114 (named_info_.empty()
115 ? 0ULL
116 : static_cast<unsigned long long>(detail::has_named_args_bit));
117 }
118
119 const basic_format_arg<Context>* data() const {
120 return named_info_.empty() ? data_.data() : data_.data() + 1;
121 }
122
123 template <typename T> void emplace_arg(const T& arg) {
124 data_.emplace_back(detail::make_arg<Context>(arg));
125 }
126
127 template <typename T>
128 void emplace_arg(const detail::named_arg<char_type, T>& arg) {
129 if (named_info_.empty()) {
130 constexpr const detail::named_arg_info<char_type>* zero_ptr{nullptr};
131 data_.insert(data_.begin(), {zero_ptr, 0});
132 }
133 data_.emplace_back(detail::make_arg<Context>(detail::unwrap(arg.value)));
134 auto pop_one = [](std::vector<basic_format_arg<Context>>* data) {
135 data->pop_back();
136 };
137 std::unique_ptr<std::vector<basic_format_arg<Context>>, decltype(pop_one)>
138 guard{&data_, pop_one};
139 named_info_.push_back({arg.name, static_cast<int>(data_.size() - 2u)});
140 data_[0].value_.named_args = {named_info_.data(), named_info_.size()};
141 guard.release();
142 }
143
144 public:
145 constexpr dynamic_format_arg_store() = default;
146
147 /**
148 \rst
149 Adds an argument into the dynamic store for later passing to a formatting
150 function.
151
152 Note that custom types and string types (but not string views) are copied
153 into the store dynamically allocating memory if necessary.
154
155 **Example**::
156
157 fmt::dynamic_format_arg_store<fmt::format_context> store;
158 store.push_back(42);
159 store.push_back("abc");
160 store.push_back(1.5f);
161 std::string result = fmt::vformat("{} and {} and {}", store);
162 \endrst
163 */
164 template <typename T> void push_back(const T& arg) {
165 if (detail::const_check(need_copy<T>::value))
166 emplace_arg(dynamic_args_.push<stored_type<T>>(arg));
167 else
168 emplace_arg(detail::unwrap(arg));
169 }
170
171 /**
172 \rst
173 Adds a reference to the argument into the dynamic store for later passing to
174 a formatting function.
175
176 **Example**::
177
178 fmt::dynamic_format_arg_store<fmt::format_context> store;
179 char band[] = "Rolling Stones";
180 store.push_back(std::cref(band));
181 band[9] = 'c'; // Changing str affects the output.
182 std::string result = fmt::vformat("{}", store);
183 // result == "Rolling Scones"
184 \endrst
185 */
186 template <typename T> void push_back(std::reference_wrapper<T> arg) {
187 static_assert(
188 need_copy<T>::value,
189 "objects of built-in types and string views are always copied");
190 emplace_arg(arg.get());
191 }
192
193 /**
194 Adds named argument into the dynamic store for later passing to a formatting
195 function. ``std::reference_wrapper`` is supported to avoid copying of the
196 argument. The name is always copied into the store.
197 */
198 template <typename T>
199 void push_back(const detail::named_arg<char_type, T>& arg) {
200 const char_type* arg_name =
201 dynamic_args_.push<std::basic_string<char_type>>(arg.name).c_str();
202 if (detail::const_check(need_copy<T>::value)) {
203 emplace_arg(
204 fmt::arg(arg_name, dynamic_args_.push<stored_type<T>>(arg.value)));
205 } else {
206 emplace_arg(fmt::arg(arg_name, arg.value));
207 }
208 }
209
210 /** Erase all elements from the store */
211 void clear() {
212 data_.clear();
213 named_info_.clear();
214 dynamic_args_ = detail::dynamic_arg_list();
215 }
216
217 /**
218 \rst
219 Reserves space to store at least *new_cap* arguments including
220 *new_cap_named* named arguments.
221 \endrst
222 */
223 void reserve(size_t new_cap, size_t new_cap_named) {
224 FMT_ASSERT(new_cap >= new_cap_named,
225 "Set of arguments includes set of named arguments");
226 data_.reserve(new_cap);
227 named_info_.reserve(new_cap_named);
228 }
229 };
230
231 FMT_END_NAMESPACE
232
233 #endif // FMT_ARGS_H_
+0
-2067
source/misc/embedded_libs/fmt-8.1.1/include/fmt/chrono.h less more
0 // Formatting library for C++ - chrono support
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_CHRONO_H_
8 #define FMT_CHRONO_H_
9
10 #include <algorithm>
11 #include <chrono>
12 #include <ctime>
13 #include <iterator>
14 #include <locale>
15 #include <ostream>
16 #include <type_traits>
17
18 #include "format.h"
19
20 FMT_BEGIN_NAMESPACE
21
22 // Enable tzset.
23 #ifndef FMT_USE_TZSET
24 // UWP doesn't provide _tzset.
25 # if FMT_HAS_INCLUDE("winapifamily.h")
26 # include <winapifamily.h>
27 # endif
28 # if defined(_WIN32) && (!defined(WINAPI_FAMILY) || \
29 (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
30 # define FMT_USE_TZSET 1
31 # else
32 # define FMT_USE_TZSET 0
33 # endif
34 #endif
35
36 // Enable safe chrono durations, unless explicitly disabled.
37 #ifndef FMT_SAFE_DURATION_CAST
38 # define FMT_SAFE_DURATION_CAST 1
39 #endif
40 #if FMT_SAFE_DURATION_CAST
41
42 // For conversion between std::chrono::durations without undefined
43 // behaviour or erroneous results.
44 // This is a stripped down version of duration_cast, for inclusion in fmt.
45 // See https://github.com/pauldreik/safe_duration_cast
46 //
47 // Copyright Paul Dreik 2019
48 namespace safe_duration_cast {
49
50 template <typename To, typename From,
51 FMT_ENABLE_IF(!std::is_same<From, To>::value &&
52 std::numeric_limits<From>::is_signed ==
53 std::numeric_limits<To>::is_signed)>
54 FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
55 ec = 0;
56 using F = std::numeric_limits<From>;
57 using T = std::numeric_limits<To>;
58 static_assert(F::is_integer, "From must be integral");
59 static_assert(T::is_integer, "To must be integral");
60
61 // A and B are both signed, or both unsigned.
62 if (detail::const_check(F::digits <= T::digits)) {
63 // From fits in To without any problem.
64 } else {
65 // From does not always fit in To, resort to a dynamic check.
66 if (from < (T::min)() || from > (T::max)()) {
67 // outside range.
68 ec = 1;
69 return {};
70 }
71 }
72 return static_cast<To>(from);
73 }
74
75 /**
76 * converts From to To, without loss. If the dynamic value of from
77 * can't be converted to To without loss, ec is set.
78 */
79 template <typename To, typename From,
80 FMT_ENABLE_IF(!std::is_same<From, To>::value &&
81 std::numeric_limits<From>::is_signed !=
82 std::numeric_limits<To>::is_signed)>
83 FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
84 ec = 0;
85 using F = std::numeric_limits<From>;
86 using T = std::numeric_limits<To>;
87 static_assert(F::is_integer, "From must be integral");
88 static_assert(T::is_integer, "To must be integral");
89
90 if (detail::const_check(F::is_signed && !T::is_signed)) {
91 // From may be negative, not allowed!
92 if (fmt::detail::is_negative(from)) {
93 ec = 1;
94 return {};
95 }
96 // From is positive. Can it always fit in To?
97 if (detail::const_check(F::digits > T::digits) &&
98 from > static_cast<From>(detail::max_value<To>())) {
99 ec = 1;
100 return {};
101 }
102 }
103
104 if (detail::const_check(!F::is_signed && T::is_signed &&
105 F::digits >= T::digits) &&
106 from > static_cast<From>(detail::max_value<To>())) {
107 ec = 1;
108 return {};
109 }
110 return static_cast<To>(from); // Lossless conversion.
111 }
112
113 template <typename To, typename From,
114 FMT_ENABLE_IF(std::is_same<From, To>::value)>
115 FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
116 ec = 0;
117 return from;
118 } // function
119
120 // clang-format off
121 /**
122 * converts From to To if possible, otherwise ec is set.
123 *
124 * input | output
125 * ---------------------------------|---------------
126 * NaN | NaN
127 * Inf | Inf
128 * normal, fits in output | converted (possibly lossy)
129 * normal, does not fit in output | ec is set
130 * subnormal | best effort
131 * -Inf | -Inf
132 */
133 // clang-format on
134 template <typename To, typename From,
135 FMT_ENABLE_IF(!std::is_same<From, To>::value)>
136 FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
137 ec = 0;
138 using T = std::numeric_limits<To>;
139 static_assert(std::is_floating_point<From>::value, "From must be floating");
140 static_assert(std::is_floating_point<To>::value, "To must be floating");
141
142 // catch the only happy case
143 if (std::isfinite(from)) {
144 if (from >= T::lowest() && from <= (T::max)()) {
145 return static_cast<To>(from);
146 }
147 // not within range.
148 ec = 1;
149 return {};
150 }
151
152 // nan and inf will be preserved
153 return static_cast<To>(from);
154 } // function
155
156 template <typename To, typename From,
157 FMT_ENABLE_IF(std::is_same<From, To>::value)>
158 FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
159 ec = 0;
160 static_assert(std::is_floating_point<From>::value, "From must be floating");
161 return from;
162 }
163
164 /**
165 * safe duration cast between integral durations
166 */
167 template <typename To, typename FromRep, typename FromPeriod,
168 FMT_ENABLE_IF(std::is_integral<FromRep>::value),
169 FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)>
170 To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
171 int& ec) {
172 using From = std::chrono::duration<FromRep, FromPeriod>;
173 ec = 0;
174 // the basic idea is that we need to convert from count() in the from type
175 // to count() in the To type, by multiplying it with this:
176 struct Factor
177 : std::ratio_divide<typename From::period, typename To::period> {};
178
179 static_assert(Factor::num > 0, "num must be positive");
180 static_assert(Factor::den > 0, "den must be positive");
181
182 // the conversion is like this: multiply from.count() with Factor::num
183 // /Factor::den and convert it to To::rep, all this without
184 // overflow/underflow. let's start by finding a suitable type that can hold
185 // both To, From and Factor::num
186 using IntermediateRep =
187 typename std::common_type<typename From::rep, typename To::rep,
188 decltype(Factor::num)>::type;
189
190 // safe conversion to IntermediateRep
191 IntermediateRep count =
192 lossless_integral_conversion<IntermediateRep>(from.count(), ec);
193 if (ec) return {};
194 // multiply with Factor::num without overflow or underflow
195 if (detail::const_check(Factor::num != 1)) {
196 const auto max1 = detail::max_value<IntermediateRep>() / Factor::num;
197 if (count > max1) {
198 ec = 1;
199 return {};
200 }
201 const auto min1 =
202 (std::numeric_limits<IntermediateRep>::min)() / Factor::num;
203 if (count < min1) {
204 ec = 1;
205 return {};
206 }
207 count *= Factor::num;
208 }
209
210 if (detail::const_check(Factor::den != 1)) count /= Factor::den;
211 auto tocount = lossless_integral_conversion<typename To::rep>(count, ec);
212 return ec ? To() : To(tocount);
213 }
214
215 /**
216 * safe duration_cast between floating point durations
217 */
218 template <typename To, typename FromRep, typename FromPeriod,
219 FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
220 FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
221 To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
222 int& ec) {
223 using From = std::chrono::duration<FromRep, FromPeriod>;
224 ec = 0;
225 if (std::isnan(from.count())) {
226 // nan in, gives nan out. easy.
227 return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
228 }
229 // maybe we should also check if from is denormal, and decide what to do about
230 // it.
231
232 // +-inf should be preserved.
233 if (std::isinf(from.count())) {
234 return To{from.count()};
235 }
236
237 // the basic idea is that we need to convert from count() in the from type
238 // to count() in the To type, by multiplying it with this:
239 struct Factor
240 : std::ratio_divide<typename From::period, typename To::period> {};
241
242 static_assert(Factor::num > 0, "num must be positive");
243 static_assert(Factor::den > 0, "den must be positive");
244
245 // the conversion is like this: multiply from.count() with Factor::num
246 // /Factor::den and convert it to To::rep, all this without
247 // overflow/underflow. let's start by finding a suitable type that can hold
248 // both To, From and Factor::num
249 using IntermediateRep =
250 typename std::common_type<typename From::rep, typename To::rep,
251 decltype(Factor::num)>::type;
252
253 // force conversion of From::rep -> IntermediateRep to be safe,
254 // even if it will never happen be narrowing in this context.
255 IntermediateRep count =
256 safe_float_conversion<IntermediateRep>(from.count(), ec);
257 if (ec) {
258 return {};
259 }
260
261 // multiply with Factor::num without overflow or underflow
262 if (detail::const_check(Factor::num != 1)) {
263 constexpr auto max1 = detail::max_value<IntermediateRep>() /
264 static_cast<IntermediateRep>(Factor::num);
265 if (count > max1) {
266 ec = 1;
267 return {};
268 }
269 constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
270 static_cast<IntermediateRep>(Factor::num);
271 if (count < min1) {
272 ec = 1;
273 return {};
274 }
275 count *= static_cast<IntermediateRep>(Factor::num);
276 }
277
278 // this can't go wrong, right? den>0 is checked earlier.
279 if (detail::const_check(Factor::den != 1)) {
280 using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
281 count /= static_cast<common_t>(Factor::den);
282 }
283
284 // convert to the to type, safely
285 using ToRep = typename To::rep;
286
287 const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
288 if (ec) {
289 return {};
290 }
291 return To{tocount};
292 }
293 } // namespace safe_duration_cast
294 #endif
295
296 // Prevents expansion of a preceding token as a function-style macro.
297 // Usage: f FMT_NOMACRO()
298 #define FMT_NOMACRO
299
300 namespace detail {
301 template <typename T = void> struct null {};
302 inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
303 inline null<> localtime_s(...) { return null<>(); }
304 inline null<> gmtime_r(...) { return null<>(); }
305 inline null<> gmtime_s(...) { return null<>(); }
306
307 inline const std::locale& get_classic_locale() {
308 static const auto& locale = std::locale::classic();
309 return locale;
310 }
311
312 template <typename CodeUnit> struct codecvt_result {
313 static constexpr const size_t max_size = 32;
314 CodeUnit buf[max_size];
315 CodeUnit* end;
316 };
317 template <typename CodeUnit>
318 constexpr const size_t codecvt_result<CodeUnit>::max_size;
319
320 template <typename CodeUnit>
321 void write_codecvt(codecvt_result<CodeUnit>& out, string_view in_buf,
322 const std::locale& loc) {
323 using codecvt = std::codecvt<CodeUnit, char, std::mbstate_t>;
324 #if FMT_CLANG_VERSION
325 # pragma clang diagnostic push
326 # pragma clang diagnostic ignored "-Wdeprecated"
327 auto& f = std::use_facet<codecvt>(loc);
328 # pragma clang diagnostic pop
329 #else
330 auto& f = std::use_facet<codecvt>(loc);
331 #endif
332 auto mb = std::mbstate_t();
333 const char* from_next = nullptr;
334 auto result = f.in(mb, in_buf.begin(), in_buf.end(), from_next,
335 std::begin(out.buf), std::end(out.buf), out.end);
336 if (result != std::codecvt_base::ok)
337 FMT_THROW(format_error("failed to format time"));
338 }
339
340 template <typename OutputIt>
341 auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc)
342 -> OutputIt {
343 if (detail::is_utf8() && loc != get_classic_locale()) {
344 // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and
345 // gcc-4.
346 #if FMT_MSC_VER != 0 || \
347 (defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI))
348 // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5
349 // and newer.
350 using code_unit = wchar_t;
351 #else
352 using code_unit = char32_t;
353 #endif
354
355 using unit_t = codecvt_result<code_unit>;
356 unit_t unit;
357 write_codecvt(unit, in, loc);
358 // In UTF-8 is used one to four one-byte code units.
359 auto&& buf = basic_memory_buffer<char, unit_t::max_size * 4>();
360 for (code_unit* p = unit.buf; p != unit.end; ++p) {
361 uint32_t c = static_cast<uint32_t>(*p);
362 if (sizeof(code_unit) == 2 && c >= 0xd800 && c <= 0xdfff) {
363 // surrogate pair
364 ++p;
365 if (p == unit.end || (c & 0xfc00) != 0xd800 ||
366 (*p & 0xfc00) != 0xdc00) {
367 FMT_THROW(format_error("failed to format time"));
368 }
369 c = (c << 10) + static_cast<uint32_t>(*p) - 0x35fdc00;
370 }
371 if (c < 0x80) {
372 buf.push_back(static_cast<char>(c));
373 } else if (c < 0x800) {
374 buf.push_back(static_cast<char>(0xc0 | (c >> 6)));
375 buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
376 } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) {
377 buf.push_back(static_cast<char>(0xe0 | (c >> 12)));
378 buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
379 buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
380 } else if (c >= 0x10000 && c <= 0x10ffff) {
381 buf.push_back(static_cast<char>(0xf0 | (c >> 18)));
382 buf.push_back(static_cast<char>(0x80 | ((c & 0x3ffff) >> 12)));
383 buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
384 buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
385 } else {
386 FMT_THROW(format_error("failed to format time"));
387 }
388 }
389 return copy_str<char>(buf.data(), buf.data() + buf.size(), out);
390 }
391 return copy_str<char>(in.data(), in.data() + in.size(), out);
392 }
393
394 template <typename Char, typename OutputIt,
395 FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
396 auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
397 -> OutputIt {
398 codecvt_result<Char> unit;
399 write_codecvt(unit, sv, loc);
400 return copy_str<Char>(unit.buf, unit.end, out);
401 }
402
403 template <typename Char, typename OutputIt,
404 FMT_ENABLE_IF(std::is_same<Char, char>::value)>
405 auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
406 -> OutputIt {
407 return write_encoded_tm_str(out, sv, loc);
408 }
409
410 template <typename Char>
411 inline void do_write(buffer<Char>& buf, const std::tm& time,
412 const std::locale& loc, char format, char modifier) {
413 auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);
414 auto&& os = std::basic_ostream<Char>(&format_buf);
415 os.imbue(loc);
416 using iterator = std::ostreambuf_iterator<Char>;
417 const auto& facet = std::use_facet<std::time_put<Char, iterator>>(loc);
418 auto end = facet.put(os, os, Char(' '), &time, format, modifier);
419 if (end.failed()) FMT_THROW(format_error("failed to format time"));
420 }
421
422 template <typename Char, typename OutputIt,
423 FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
424 auto write(OutputIt out, const std::tm& time, const std::locale& loc,
425 char format, char modifier = 0) -> OutputIt {
426 auto&& buf = get_buffer<Char>(out);
427 do_write<Char>(buf, time, loc, format, modifier);
428 return buf.out();
429 }
430
431 template <typename Char, typename OutputIt,
432 FMT_ENABLE_IF(std::is_same<Char, char>::value)>
433 auto write(OutputIt out, const std::tm& time, const std::locale& loc,
434 char format, char modifier = 0) -> OutputIt {
435 auto&& buf = basic_memory_buffer<Char>();
436 do_write<char>(buf, time, loc, format, modifier);
437 return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc);
438 }
439
440 } // namespace detail
441
442 FMT_MODULE_EXPORT_BEGIN
443
444 /**
445 Converts given time since epoch as ``std::time_t`` value into calendar time,
446 expressed in local time. Unlike ``std::localtime``, this function is
447 thread-safe on most platforms.
448 */
449 inline std::tm localtime(std::time_t time) {
450 struct dispatcher {
451 std::time_t time_;
452 std::tm tm_;
453
454 dispatcher(std::time_t t) : time_(t) {}
455
456 bool run() {
457 using namespace fmt::detail;
458 return handle(localtime_r(&time_, &tm_));
459 }
460
461 bool handle(std::tm* tm) { return tm != nullptr; }
462
463 bool handle(detail::null<>) {
464 using namespace fmt::detail;
465 return fallback(localtime_s(&tm_, &time_));
466 }
467
468 bool fallback(int res) { return res == 0; }
469
470 #if !FMT_MSC_VER
471 bool fallback(detail::null<>) {
472 using namespace fmt::detail;
473 std::tm* tm = std::localtime(&time_);
474 if (tm) tm_ = *tm;
475 return tm != nullptr;
476 }
477 #endif
478 };
479 dispatcher lt(time);
480 // Too big time values may be unsupported.
481 if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
482 return lt.tm_;
483 }
484
485 inline std::tm localtime(
486 std::chrono::time_point<std::chrono::system_clock> time_point) {
487 return localtime(std::chrono::system_clock::to_time_t(time_point));
488 }
489
490 /**
491 Converts given time since epoch as ``std::time_t`` value into calendar time,
492 expressed in Coordinated Universal Time (UTC). Unlike ``std::gmtime``, this
493 function is thread-safe on most platforms.
494 */
495 inline std::tm gmtime(std::time_t time) {
496 struct dispatcher {
497 std::time_t time_;
498 std::tm tm_;
499
500 dispatcher(std::time_t t) : time_(t) {}
501
502 bool run() {
503 using namespace fmt::detail;
504 return handle(gmtime_r(&time_, &tm_));
505 }
506
507 bool handle(std::tm* tm) { return tm != nullptr; }
508
509 bool handle(detail::null<>) {
510 using namespace fmt::detail;
511 return fallback(gmtime_s(&tm_, &time_));
512 }
513
514 bool fallback(int res) { return res == 0; }
515
516 #if !FMT_MSC_VER
517 bool fallback(detail::null<>) {
518 std::tm* tm = std::gmtime(&time_);
519 if (tm) tm_ = *tm;
520 return tm != nullptr;
521 }
522 #endif
523 };
524 dispatcher gt(time);
525 // Too big time values may be unsupported.
526 if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
527 return gt.tm_;
528 }
529
530 inline std::tm gmtime(
531 std::chrono::time_point<std::chrono::system_clock> time_point) {
532 return gmtime(std::chrono::system_clock::to_time_t(time_point));
533 }
534
535 FMT_BEGIN_DETAIL_NAMESPACE
536
537 // Writes two-digit numbers a, b and c separated by sep to buf.
538 // The method by Pavel Novikov based on
539 // https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/.
540 inline void write_digit2_separated(char* buf, unsigned a, unsigned b,
541 unsigned c, char sep) {
542 unsigned long long digits =
543 a | (b << 24) | (static_cast<unsigned long long>(c) << 48);
544 // Convert each value to BCD.
545 // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b.
546 // The difference is
547 // y - x = a * 6
548 // a can be found from x:
549 // a = floor(x / 10)
550 // then
551 // y = x + a * 6 = x + floor(x / 10) * 6
552 // floor(x / 10) is (x * 205) >> 11 (needs 16 bits).
553 digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6;
554 // Put low nibbles to high bytes and high nibbles to low bytes.
555 digits = ((digits & 0x00f00000f00000f0) >> 4) |
556 ((digits & 0x000f00000f00000f) << 8);
557 auto usep = static_cast<unsigned long long>(sep);
558 // Add ASCII '0' to each digit byte and insert separators.
559 digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);
560
561 constexpr const size_t len = 8;
562 if (const_check(is_big_endian())) {
563 char tmp[len];
564 memcpy(tmp, &digits, len);
565 std::reverse_copy(tmp, tmp + len, buf);
566 } else {
567 memcpy(buf, &digits, len);
568 }
569 }
570
571 template <typename Period> FMT_CONSTEXPR inline const char* get_units() {
572 if (std::is_same<Period, std::atto>::value) return "as";
573 if (std::is_same<Period, std::femto>::value) return "fs";
574 if (std::is_same<Period, std::pico>::value) return "ps";
575 if (std::is_same<Period, std::nano>::value) return "ns";
576 if (std::is_same<Period, std::micro>::value) return "µs";
577 if (std::is_same<Period, std::milli>::value) return "ms";
578 if (std::is_same<Period, std::centi>::value) return "cs";
579 if (std::is_same<Period, std::deci>::value) return "ds";
580 if (std::is_same<Period, std::ratio<1>>::value) return "s";
581 if (std::is_same<Period, std::deca>::value) return "das";
582 if (std::is_same<Period, std::hecto>::value) return "hs";
583 if (std::is_same<Period, std::kilo>::value) return "ks";
584 if (std::is_same<Period, std::mega>::value) return "Ms";
585 if (std::is_same<Period, std::giga>::value) return "Gs";
586 if (std::is_same<Period, std::tera>::value) return "Ts";
587 if (std::is_same<Period, std::peta>::value) return "Ps";
588 if (std::is_same<Period, std::exa>::value) return "Es";
589 if (std::is_same<Period, std::ratio<60>>::value) return "m";
590 if (std::is_same<Period, std::ratio<3600>>::value) return "h";
591 return nullptr;
592 }
593
594 enum class numeric_system {
595 standard,
596 // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
597 alternative
598 };
599
600 // Parses a put_time-like format string and invokes handler actions.
601 template <typename Char, typename Handler>
602 FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin,
603 const Char* end,
604 Handler&& handler) {
605 auto ptr = begin;
606 while (ptr != end) {
607 auto c = *ptr;
608 if (c == '}') break;
609 if (c != '%') {
610 ++ptr;
611 continue;
612 }
613 if (begin != ptr) handler.on_text(begin, ptr);
614 ++ptr; // consume '%'
615 if (ptr == end) FMT_THROW(format_error("invalid format"));
616 c = *ptr++;
617 switch (c) {
618 case '%':
619 handler.on_text(ptr - 1, ptr);
620 break;
621 case 'n': {
622 const Char newline[] = {'\n'};
623 handler.on_text(newline, newline + 1);
624 break;
625 }
626 case 't': {
627 const Char tab[] = {'\t'};
628 handler.on_text(tab, tab + 1);
629 break;
630 }
631 // Year:
632 case 'Y':
633 handler.on_year(numeric_system::standard);
634 break;
635 case 'y':
636 handler.on_short_year(numeric_system::standard);
637 break;
638 case 'C':
639 handler.on_century(numeric_system::standard);
640 break;
641 case 'G':
642 handler.on_iso_week_based_year();
643 break;
644 case 'g':
645 handler.on_iso_week_based_short_year();
646 break;
647 // Day of the week:
648 case 'a':
649 handler.on_abbr_weekday();
650 break;
651 case 'A':
652 handler.on_full_weekday();
653 break;
654 case 'w':
655 handler.on_dec0_weekday(numeric_system::standard);
656 break;
657 case 'u':
658 handler.on_dec1_weekday(numeric_system::standard);
659 break;
660 // Month:
661 case 'b':
662 case 'h':
663 handler.on_abbr_month();
664 break;
665 case 'B':
666 handler.on_full_month();
667 break;
668 case 'm':
669 handler.on_dec_month(numeric_system::standard);
670 break;
671 // Day of the year/month:
672 case 'U':
673 handler.on_dec0_week_of_year(numeric_system::standard);
674 break;
675 case 'W':
676 handler.on_dec1_week_of_year(numeric_system::standard);
677 break;
678 case 'V':
679 handler.on_iso_week_of_year(numeric_system::standard);
680 break;
681 case 'j':
682 handler.on_day_of_year();
683 break;
684 case 'd':
685 handler.on_day_of_month(numeric_system::standard);
686 break;
687 case 'e':
688 handler.on_day_of_month_space(numeric_system::standard);
689 break;
690 // Hour, minute, second:
691 case 'H':
692 handler.on_24_hour(numeric_system::standard);
693 break;
694 case 'I':
695 handler.on_12_hour(numeric_system::standard);
696 break;
697 case 'M':
698 handler.on_minute(numeric_system::standard);
699 break;
700 case 'S':
701 handler.on_second(numeric_system::standard);
702 break;
703 // Other:
704 case 'c':
705 handler.on_datetime(numeric_system::standard);
706 break;
707 case 'x':
708 handler.on_loc_date(numeric_system::standard);
709 break;
710 case 'X':
711 handler.on_loc_time(numeric_system::standard);
712 break;
713 case 'D':
714 handler.on_us_date();
715 break;
716 case 'F':
717 handler.on_iso_date();
718 break;
719 case 'r':
720 handler.on_12_hour_time();
721 break;
722 case 'R':
723 handler.on_24_hour_time();
724 break;
725 case 'T':
726 handler.on_iso_time();
727 break;
728 case 'p':
729 handler.on_am_pm();
730 break;
731 case 'Q':
732 handler.on_duration_value();
733 break;
734 case 'q':
735 handler.on_duration_unit();
736 break;
737 case 'z':
738 handler.on_utc_offset();
739 break;
740 case 'Z':
741 handler.on_tz_name();
742 break;
743 // Alternative representation:
744 case 'E': {
745 if (ptr == end) FMT_THROW(format_error("invalid format"));
746 c = *ptr++;
747 switch (c) {
748 case 'Y':
749 handler.on_year(numeric_system::alternative);
750 break;
751 case 'y':
752 handler.on_offset_year();
753 break;
754 case 'C':
755 handler.on_century(numeric_system::alternative);
756 break;
757 case 'c':
758 handler.on_datetime(numeric_system::alternative);
759 break;
760 case 'x':
761 handler.on_loc_date(numeric_system::alternative);
762 break;
763 case 'X':
764 handler.on_loc_time(numeric_system::alternative);
765 break;
766 default:
767 FMT_THROW(format_error("invalid format"));
768 }
769 break;
770 }
771 case 'O':
772 if (ptr == end) FMT_THROW(format_error("invalid format"));
773 c = *ptr++;
774 switch (c) {
775 case 'y':
776 handler.on_short_year(numeric_system::alternative);
777 break;
778 case 'm':
779 handler.on_dec_month(numeric_system::alternative);
780 break;
781 case 'U':
782 handler.on_dec0_week_of_year(numeric_system::alternative);
783 break;
784 case 'W':
785 handler.on_dec1_week_of_year(numeric_system::alternative);
786 break;
787 case 'V':
788 handler.on_iso_week_of_year(numeric_system::alternative);
789 break;
790 case 'd':
791 handler.on_day_of_month(numeric_system::alternative);
792 break;
793 case 'e':
794 handler.on_day_of_month_space(numeric_system::alternative);
795 break;
796 case 'w':
797 handler.on_dec0_weekday(numeric_system::alternative);
798 break;
799 case 'u':
800 handler.on_dec1_weekday(numeric_system::alternative);
801 break;
802 case 'H':
803 handler.on_24_hour(numeric_system::alternative);
804 break;
805 case 'I':
806 handler.on_12_hour(numeric_system::alternative);
807 break;
808 case 'M':
809 handler.on_minute(numeric_system::alternative);
810 break;
811 case 'S':
812 handler.on_second(numeric_system::alternative);
813 break;
814 default:
815 FMT_THROW(format_error("invalid format"));
816 }
817 break;
818 default:
819 FMT_THROW(format_error("invalid format"));
820 }
821 begin = ptr;
822 }
823 if (begin != ptr) handler.on_text(begin, ptr);
824 return ptr;
825 }
826
827 template <typename Derived> struct null_chrono_spec_handler {
828 FMT_CONSTEXPR void unsupported() {
829 static_cast<Derived*>(this)->unsupported();
830 }
831 FMT_CONSTEXPR void on_year(numeric_system) { unsupported(); }
832 FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); }
833 FMT_CONSTEXPR void on_offset_year() { unsupported(); }
834 FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); }
835 FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); }
836 FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); }
837 FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); }
838 FMT_CONSTEXPR void on_full_weekday() { unsupported(); }
839 FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); }
840 FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); }
841 FMT_CONSTEXPR void on_abbr_month() { unsupported(); }
842 FMT_CONSTEXPR void on_full_month() { unsupported(); }
843 FMT_CONSTEXPR void on_dec_month(numeric_system) { unsupported(); }
844 FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) { unsupported(); }
845 FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) { unsupported(); }
846 FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) { unsupported(); }
847 FMT_CONSTEXPR void on_day_of_year() { unsupported(); }
848 FMT_CONSTEXPR void on_day_of_month(numeric_system) { unsupported(); }
849 FMT_CONSTEXPR void on_day_of_month_space(numeric_system) { unsupported(); }
850 FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); }
851 FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); }
852 FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); }
853 FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); }
854 FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); }
855 FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); }
856 FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); }
857 FMT_CONSTEXPR void on_us_date() { unsupported(); }
858 FMT_CONSTEXPR void on_iso_date() { unsupported(); }
859 FMT_CONSTEXPR void on_12_hour_time() { unsupported(); }
860 FMT_CONSTEXPR void on_24_hour_time() { unsupported(); }
861 FMT_CONSTEXPR void on_iso_time() { unsupported(); }
862 FMT_CONSTEXPR void on_am_pm() { unsupported(); }
863 FMT_CONSTEXPR void on_duration_value() { unsupported(); }
864 FMT_CONSTEXPR void on_duration_unit() { unsupported(); }
865 FMT_CONSTEXPR void on_utc_offset() { unsupported(); }
866 FMT_CONSTEXPR void on_tz_name() { unsupported(); }
867 };
868
869 struct tm_format_checker : null_chrono_spec_handler<tm_format_checker> {
870 FMT_NORETURN void unsupported() { FMT_THROW(format_error("no format")); }
871
872 template <typename Char>
873 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
874 FMT_CONSTEXPR void on_year(numeric_system) {}
875 FMT_CONSTEXPR void on_short_year(numeric_system) {}
876 FMT_CONSTEXPR void on_offset_year() {}
877 FMT_CONSTEXPR void on_century(numeric_system) {}
878 FMT_CONSTEXPR void on_iso_week_based_year() {}
879 FMT_CONSTEXPR void on_iso_week_based_short_year() {}
880 FMT_CONSTEXPR void on_abbr_weekday() {}
881 FMT_CONSTEXPR void on_full_weekday() {}
882 FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {}
883 FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {}
884 FMT_CONSTEXPR void on_abbr_month() {}
885 FMT_CONSTEXPR void on_full_month() {}
886 FMT_CONSTEXPR void on_dec_month(numeric_system) {}
887 FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) {}
888 FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) {}
889 FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) {}
890 FMT_CONSTEXPR void on_day_of_year() {}
891 FMT_CONSTEXPR void on_day_of_month(numeric_system) {}
892 FMT_CONSTEXPR void on_day_of_month_space(numeric_system) {}
893 FMT_CONSTEXPR void on_24_hour(numeric_system) {}
894 FMT_CONSTEXPR void on_12_hour(numeric_system) {}
895 FMT_CONSTEXPR void on_minute(numeric_system) {}
896 FMT_CONSTEXPR void on_second(numeric_system) {}
897 FMT_CONSTEXPR void on_datetime(numeric_system) {}
898 FMT_CONSTEXPR void on_loc_date(numeric_system) {}
899 FMT_CONSTEXPR void on_loc_time(numeric_system) {}
900 FMT_CONSTEXPR void on_us_date() {}
901 FMT_CONSTEXPR void on_iso_date() {}
902 FMT_CONSTEXPR void on_12_hour_time() {}
903 FMT_CONSTEXPR void on_24_hour_time() {}
904 FMT_CONSTEXPR void on_iso_time() {}
905 FMT_CONSTEXPR void on_am_pm() {}
906 FMT_CONSTEXPR void on_utc_offset() {}
907 FMT_CONSTEXPR void on_tz_name() {}
908 };
909
910 inline const char* tm_wday_full_name(int wday) {
911 static constexpr const char* full_name_list[] = {
912 "Sunday", "Monday", "Tuesday", "Wednesday",
913 "Thursday", "Friday", "Saturday"};
914 return wday >= 0 && wday <= 6 ? full_name_list[wday] : "?";
915 }
916 inline const char* tm_wday_short_name(int wday) {
917 static constexpr const char* short_name_list[] = {"Sun", "Mon", "Tue", "Wed",
918 "Thu", "Fri", "Sat"};
919 return wday >= 0 && wday <= 6 ? short_name_list[wday] : "???";
920 }
921
922 inline const char* tm_mon_full_name(int mon) {
923 static constexpr const char* full_name_list[] = {
924 "January", "February", "March", "April", "May", "June",
925 "July", "August", "September", "October", "November", "December"};
926 return mon >= 0 && mon <= 11 ? full_name_list[mon] : "?";
927 }
928 inline const char* tm_mon_short_name(int mon) {
929 static constexpr const char* short_name_list[] = {
930 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
931 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
932 };
933 return mon >= 0 && mon <= 11 ? short_name_list[mon] : "???";
934 }
935
936 template <typename T, typename = void>
937 struct has_member_data_tm_gmtoff : std::false_type {};
938 template <typename T>
939 struct has_member_data_tm_gmtoff<T, void_t<decltype(T::tm_gmtoff)>>
940 : std::true_type {};
941
942 template <typename T, typename = void>
943 struct has_member_data_tm_zone : std::false_type {};
944 template <typename T>
945 struct has_member_data_tm_zone<T, void_t<decltype(T::tm_zone)>>
946 : std::true_type {};
947
948 #if FMT_USE_TZSET
949 inline void tzset_once() {
950 static bool init = []() -> bool {
951 _tzset();
952 return true;
953 }();
954 ignore_unused(init);
955 }
956 #endif
957
958 template <typename OutputIt, typename Char> class tm_writer {
959 private:
960 static constexpr int days_per_week = 7;
961
962 const std::locale& loc_;
963 const bool is_classic_;
964 OutputIt out_;
965 const std::tm& tm_;
966
967 auto tm_sec() const noexcept -> int {
968 FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, "");
969 return tm_.tm_sec;
970 }
971 auto tm_min() const noexcept -> int {
972 FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, "");
973 return tm_.tm_min;
974 }
975 auto tm_hour() const noexcept -> int {
976 FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, "");
977 return tm_.tm_hour;
978 }
979 auto tm_mday() const noexcept -> int {
980 FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, "");
981 return tm_.tm_mday;
982 }
983 auto tm_mon() const noexcept -> int {
984 FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, "");
985 return tm_.tm_mon;
986 }
987 auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; }
988 auto tm_wday() const noexcept -> int {
989 FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, "");
990 return tm_.tm_wday;
991 }
992 auto tm_yday() const noexcept -> int {
993 FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, "");
994 return tm_.tm_yday;
995 }
996
997 auto tm_hour12() const noexcept -> int {
998 const auto h = tm_hour();
999 const auto z = h < 12 ? h : h - 12;
1000 return z == 0 ? 12 : z;
1001 }
1002
1003 // POSIX and the C Standard are unclear or inconsistent about what %C and %y
1004 // do if the year is negative or exceeds 9999. Use the convention that %C
1005 // concatenated with %y yields the same output as %Y, and that %Y contains at
1006 // least 4 characters, with more only if necessary.
1007 auto split_year_lower(long long year) const noexcept -> int {
1008 auto l = year % 100;
1009 if (l < 0) l = -l; // l in [0, 99]
1010 return static_cast<int>(l);
1011 }
1012
1013 // Algorithm:
1014 // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_the_week_number_from_a_month_and_day_of_the_month_or_ordinal_date
1015 auto iso_year_weeks(long long curr_year) const noexcept -> int {
1016 const auto prev_year = curr_year - 1;
1017 const auto curr_p =
1018 (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) %
1019 days_per_week;
1020 const auto prev_p =
1021 (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) %
1022 days_per_week;
1023 return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0);
1024 }
1025 auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int {
1026 return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) /
1027 days_per_week;
1028 }
1029 auto tm_iso_week_year() const noexcept -> long long {
1030 const auto year = tm_year();
1031 const auto w = iso_week_num(tm_yday(), tm_wday());
1032 if (w < 1) return year - 1;
1033 if (w > iso_year_weeks(year)) return year + 1;
1034 return year;
1035 }
1036 auto tm_iso_week_of_year() const noexcept -> int {
1037 const auto year = tm_year();
1038 const auto w = iso_week_num(tm_yday(), tm_wday());
1039 if (w < 1) return iso_year_weeks(year - 1);
1040 if (w > iso_year_weeks(year)) return 1;
1041 return w;
1042 }
1043
1044 void write1(int value) {
1045 *out_++ = static_cast<char>('0' + to_unsigned(value) % 10);
1046 }
1047 void write2(int value) {
1048 const char* d = digits2(to_unsigned(value) % 100);
1049 *out_++ = *d++;
1050 *out_++ = *d;
1051 }
1052
1053 void write_year_extended(long long year) {
1054 // At least 4 characters.
1055 int width = 4;
1056 if (year < 0) {
1057 *out_++ = '-';
1058 year = 0 - year;
1059 --width;
1060 }
1061 uint32_or_64_or_128_t<long long> n = to_unsigned(year);
1062 const int num_digits = count_digits(n);
1063 if (width > num_digits) out_ = std::fill_n(out_, width - num_digits, '0');
1064 out_ = format_decimal<Char>(out_, n, num_digits).end;
1065 }
1066 void write_year(long long year) {
1067 if (year >= 0 && year < 10000) {
1068 write2(static_cast<int>(year / 100));
1069 write2(static_cast<int>(year % 100));
1070 } else {
1071 write_year_extended(year);
1072 }
1073 }
1074
1075 void write_utc_offset(long offset) {
1076 if (offset < 0) {
1077 *out_++ = '-';
1078 offset = -offset;
1079 } else {
1080 *out_++ = '+';
1081 }
1082 offset /= 60;
1083 write2(static_cast<int>(offset / 60));
1084 write2(static_cast<int>(offset % 60));
1085 }
1086 template <typename T, FMT_ENABLE_IF(has_member_data_tm_gmtoff<T>::value)>
1087 void format_utc_offset_impl(const T& tm) {
1088 write_utc_offset(tm.tm_gmtoff);
1089 }
1090 template <typename T, FMT_ENABLE_IF(!has_member_data_tm_gmtoff<T>::value)>
1091 void format_utc_offset_impl(const T& tm) {
1092 #if defined(_WIN32) && defined(_UCRT)
1093 # if FMT_USE_TZSET
1094 tzset_once();
1095 # endif
1096 long offset = 0;
1097 _get_timezone(&offset);
1098 if (tm.tm_isdst) {
1099 long dstbias = 0;
1100 _get_dstbias(&dstbias);
1101 offset += dstbias;
1102 }
1103 write_utc_offset(-offset);
1104 #else
1105 ignore_unused(tm);
1106 format_localized('z');
1107 #endif
1108 }
1109
1110 template <typename T, FMT_ENABLE_IF(has_member_data_tm_zone<T>::value)>
1111 void format_tz_name_impl(const T& tm) {
1112 if (is_classic_)
1113 out_ = write_tm_str<Char>(out_, tm.tm_zone, loc_);
1114 else
1115 format_localized('Z');
1116 }
1117 template <typename T, FMT_ENABLE_IF(!has_member_data_tm_zone<T>::value)>
1118 void format_tz_name_impl(const T&) {
1119 format_localized('Z');
1120 }
1121
1122 void format_localized(char format, char modifier = 0) {
1123 out_ = write<Char>(out_, tm_, loc_, format, modifier);
1124 }
1125
1126 public:
1127 tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm)
1128 : loc_(loc),
1129 is_classic_(loc_ == get_classic_locale()),
1130 out_(out),
1131 tm_(tm) {}
1132
1133 OutputIt out() const { return out_; }
1134
1135 FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
1136 out_ = copy_str<Char>(begin, end, out_);
1137 }
1138
1139 void on_abbr_weekday() {
1140 if (is_classic_)
1141 out_ = write(out_, tm_wday_short_name(tm_wday()));
1142 else
1143 format_localized('a');
1144 }
1145 void on_full_weekday() {
1146 if (is_classic_)
1147 out_ = write(out_, tm_wday_full_name(tm_wday()));
1148 else
1149 format_localized('A');
1150 }
1151 void on_dec0_weekday(numeric_system ns) {
1152 if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday());
1153 format_localized('w', 'O');
1154 }
1155 void on_dec1_weekday(numeric_system ns) {
1156 if (is_classic_ || ns == numeric_system::standard) {
1157 auto wday = tm_wday();
1158 write1(wday == 0 ? days_per_week : wday);
1159 } else {
1160 format_localized('u', 'O');
1161 }
1162 }
1163
1164 void on_abbr_month() {
1165 if (is_classic_)
1166 out_ = write(out_, tm_mon_short_name(tm_mon()));
1167 else
1168 format_localized('b');
1169 }
1170 void on_full_month() {
1171 if (is_classic_)
1172 out_ = write(out_, tm_mon_full_name(tm_mon()));
1173 else
1174 format_localized('B');
1175 }
1176
1177 void on_datetime(numeric_system ns) {
1178 if (is_classic_) {
1179 on_abbr_weekday();
1180 *out_++ = ' ';
1181 on_abbr_month();
1182 *out_++ = ' ';
1183 on_day_of_month_space(numeric_system::standard);
1184 *out_++ = ' ';
1185 on_iso_time();
1186 *out_++ = ' ';
1187 on_year(numeric_system::standard);
1188 } else {
1189 format_localized('c', ns == numeric_system::standard ? '\0' : 'E');
1190 }
1191 }
1192 void on_loc_date(numeric_system ns) {
1193 if (is_classic_)
1194 on_us_date();
1195 else
1196 format_localized('x', ns == numeric_system::standard ? '\0' : 'E');
1197 }
1198 void on_loc_time(numeric_system ns) {
1199 if (is_classic_)
1200 on_iso_time();
1201 else
1202 format_localized('X', ns == numeric_system::standard ? '\0' : 'E');
1203 }
1204 void on_us_date() {
1205 char buf[8];
1206 write_digit2_separated(buf, to_unsigned(tm_mon() + 1),
1207 to_unsigned(tm_mday()),
1208 to_unsigned(split_year_lower(tm_year())), '/');
1209 out_ = copy_str<Char>(std::begin(buf), std::end(buf), out_);
1210 }
1211 void on_iso_date() {
1212 auto year = tm_year();
1213 char buf[10];
1214 size_t offset = 0;
1215 if (year >= 0 && year < 10000) {
1216 copy2(buf, digits2(to_unsigned(year / 100)));
1217 } else {
1218 offset = 4;
1219 write_year_extended(year);
1220 year = 0;
1221 }
1222 write_digit2_separated(buf + 2, static_cast<unsigned>(year % 100),
1223 to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()),
1224 '-');
1225 out_ = copy_str<Char>(std::begin(buf) + offset, std::end(buf), out_);
1226 }
1227
1228 void on_utc_offset() { format_utc_offset_impl(tm_); }
1229 void on_tz_name() { format_tz_name_impl(tm_); }
1230
1231 void on_year(numeric_system ns) {
1232 if (is_classic_ || ns == numeric_system::standard)
1233 return write_year(tm_year());
1234 format_localized('Y', 'E');
1235 }
1236 void on_short_year(numeric_system ns) {
1237 if (is_classic_ || ns == numeric_system::standard)
1238 return write2(split_year_lower(tm_year()));
1239 format_localized('y', 'O');
1240 }
1241 void on_offset_year() {
1242 if (is_classic_) return write2(split_year_lower(tm_year()));
1243 format_localized('y', 'E');
1244 }
1245
1246 void on_century(numeric_system ns) {
1247 if (is_classic_ || ns == numeric_system::standard) {
1248 auto year = tm_year();
1249 auto upper = year / 100;
1250 if (year >= -99 && year < 0) {
1251 // Zero upper on negative year.
1252 *out_++ = '-';
1253 *out_++ = '0';
1254 } else if (upper >= 0 && upper < 100) {
1255 write2(static_cast<int>(upper));
1256 } else {
1257 out_ = write<Char>(out_, upper);
1258 }
1259 } else {
1260 format_localized('C', 'E');
1261 }
1262 }
1263
1264 void on_dec_month(numeric_system ns) {
1265 if (is_classic_ || ns == numeric_system::standard)
1266 return write2(tm_mon() + 1);
1267 format_localized('m', 'O');
1268 }
1269
1270 void on_dec0_week_of_year(numeric_system ns) {
1271 if (is_classic_ || ns == numeric_system::standard)
1272 return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week);
1273 format_localized('U', 'O');
1274 }
1275 void on_dec1_week_of_year(numeric_system ns) {
1276 if (is_classic_ || ns == numeric_system::standard) {
1277 auto wday = tm_wday();
1278 write2((tm_yday() + days_per_week -
1279 (wday == 0 ? (days_per_week - 1) : (wday - 1))) /
1280 days_per_week);
1281 } else {
1282 format_localized('W', 'O');
1283 }
1284 }
1285 void on_iso_week_of_year(numeric_system ns) {
1286 if (is_classic_ || ns == numeric_system::standard)
1287 return write2(tm_iso_week_of_year());
1288 format_localized('V', 'O');
1289 }
1290
1291 void on_iso_week_based_year() { write_year(tm_iso_week_year()); }
1292 void on_iso_week_based_short_year() {
1293 write2(split_year_lower(tm_iso_week_year()));
1294 }
1295
1296 void on_day_of_year() {
1297 auto yday = tm_yday() + 1;
1298 write1(yday / 100);
1299 write2(yday % 100);
1300 }
1301 void on_day_of_month(numeric_system ns) {
1302 if (is_classic_ || ns == numeric_system::standard) return write2(tm_mday());
1303 format_localized('d', 'O');
1304 }
1305 void on_day_of_month_space(numeric_system ns) {
1306 if (is_classic_ || ns == numeric_system::standard) {
1307 auto mday = to_unsigned(tm_mday()) % 100;
1308 const char* d2 = digits2(mday);
1309 *out_++ = mday < 10 ? ' ' : d2[0];
1310 *out_++ = d2[1];
1311 } else {
1312 format_localized('e', 'O');
1313 }
1314 }
1315
1316 void on_24_hour(numeric_system ns) {
1317 if (is_classic_ || ns == numeric_system::standard) return write2(tm_hour());
1318 format_localized('H', 'O');
1319 }
1320 void on_12_hour(numeric_system ns) {
1321 if (is_classic_ || ns == numeric_system::standard)
1322 return write2(tm_hour12());
1323 format_localized('I', 'O');
1324 }
1325 void on_minute(numeric_system ns) {
1326 if (is_classic_ || ns == numeric_system::standard) return write2(tm_min());
1327 format_localized('M', 'O');
1328 }
1329 void on_second(numeric_system ns) {
1330 if (is_classic_ || ns == numeric_system::standard) return write2(tm_sec());
1331 format_localized('S', 'O');
1332 }
1333
1334 void on_12_hour_time() {
1335 if (is_classic_) {
1336 char buf[8];
1337 write_digit2_separated(buf, to_unsigned(tm_hour12()),
1338 to_unsigned(tm_min()), to_unsigned(tm_sec()), ':');
1339 out_ = copy_str<Char>(std::begin(buf), std::end(buf), out_);
1340 *out_++ = ' ';
1341 on_am_pm();
1342 } else {
1343 format_localized('r');
1344 }
1345 }
1346 void on_24_hour_time() {
1347 write2(tm_hour());
1348 *out_++ = ':';
1349 write2(tm_min());
1350 }
1351 void on_iso_time() {
1352 char buf[8];
1353 write_digit2_separated(buf, to_unsigned(tm_hour()), to_unsigned(tm_min()),
1354 to_unsigned(tm_sec()), ':');
1355 out_ = copy_str<Char>(std::begin(buf), std::end(buf), out_);
1356 }
1357
1358 void on_am_pm() {
1359 if (is_classic_) {
1360 *out_++ = tm_hour() < 12 ? 'A' : 'P';
1361 *out_++ = 'M';
1362 } else {
1363 format_localized('p');
1364 }
1365 }
1366
1367 // These apply to chrono durations but not tm.
1368 void on_duration_value() {}
1369 void on_duration_unit() {}
1370 };
1371
1372 struct chrono_format_checker : null_chrono_spec_handler<chrono_format_checker> {
1373 FMT_NORETURN void unsupported() { FMT_THROW(format_error("no date")); }
1374
1375 template <typename Char>
1376 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
1377 FMT_CONSTEXPR void on_24_hour(numeric_system) {}
1378 FMT_CONSTEXPR void on_12_hour(numeric_system) {}
1379 FMT_CONSTEXPR void on_minute(numeric_system) {}
1380 FMT_CONSTEXPR void on_second(numeric_system) {}
1381 FMT_CONSTEXPR void on_12_hour_time() {}
1382 FMT_CONSTEXPR void on_24_hour_time() {}
1383 FMT_CONSTEXPR void on_iso_time() {}
1384 FMT_CONSTEXPR void on_am_pm() {}
1385 FMT_CONSTEXPR void on_duration_value() {}
1386 FMT_CONSTEXPR void on_duration_unit() {}
1387 };
1388
1389 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
1390 inline bool isnan(T) {
1391 return false;
1392 }
1393 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1394 inline bool isnan(T value) {
1395 return std::isnan(value);
1396 }
1397
1398 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
1399 inline bool isfinite(T) {
1400 return true;
1401 }
1402
1403 // Converts value to Int and checks that it's in the range [0, upper).
1404 template <typename T, typename Int, FMT_ENABLE_IF(std::is_integral<T>::value)>
1405 inline Int to_nonnegative_int(T value, Int upper) {
1406 FMT_ASSERT(value >= 0 && to_unsigned(value) <= to_unsigned(upper),
1407 "invalid value");
1408 (void)upper;
1409 return static_cast<Int>(value);
1410 }
1411 template <typename T, typename Int, FMT_ENABLE_IF(!std::is_integral<T>::value)>
1412 inline Int to_nonnegative_int(T value, Int upper) {
1413 if (value < 0 || value > static_cast<T>(upper))
1414 FMT_THROW(format_error("invalid value"));
1415 return static_cast<Int>(value);
1416 }
1417
1418 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
1419 inline T mod(T x, int y) {
1420 return x % static_cast<T>(y);
1421 }
1422 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1423 inline T mod(T x, int y) {
1424 return std::fmod(x, static_cast<T>(y));
1425 }
1426
1427 // If T is an integral type, maps T to its unsigned counterpart, otherwise
1428 // leaves it unchanged (unlike std::make_unsigned).
1429 template <typename T, bool INTEGRAL = std::is_integral<T>::value>
1430 struct make_unsigned_or_unchanged {
1431 using type = T;
1432 };
1433
1434 template <typename T> struct make_unsigned_or_unchanged<T, true> {
1435 using type = typename std::make_unsigned<T>::type;
1436 };
1437
1438 #if FMT_SAFE_DURATION_CAST
1439 // throwing version of safe_duration_cast
1440 template <typename To, typename FromRep, typename FromPeriod>
1441 To fmt_safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) {
1442 int ec;
1443 To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
1444 if (ec) FMT_THROW(format_error("cannot format duration"));
1445 return to;
1446 }
1447 #endif
1448
1449 template <typename Rep, typename Period,
1450 FMT_ENABLE_IF(std::is_integral<Rep>::value)>
1451 inline std::chrono::duration<Rep, std::milli> get_milliseconds(
1452 std::chrono::duration<Rep, Period> d) {
1453 // this may overflow and/or the result may not fit in the
1454 // target type.
1455 #if FMT_SAFE_DURATION_CAST
1456 using CommonSecondsType =
1457 typename std::common_type<decltype(d), std::chrono::seconds>::type;
1458 const auto d_as_common = fmt_safe_duration_cast<CommonSecondsType>(d);
1459 const auto d_as_whole_seconds =
1460 fmt_safe_duration_cast<std::chrono::seconds>(d_as_common);
1461 // this conversion should be nonproblematic
1462 const auto diff = d_as_common - d_as_whole_seconds;
1463 const auto ms =
1464 fmt_safe_duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
1465 return ms;
1466 #else
1467 auto s = std::chrono::duration_cast<std::chrono::seconds>(d);
1468 return std::chrono::duration_cast<std::chrono::milliseconds>(d - s);
1469 #endif
1470 }
1471
1472 // Returns the number of fractional digits in the range [0, 18] according to the
1473 // C++20 spec. If more than 18 fractional digits are required then returns 6 for
1474 // microseconds precision.
1475 constexpr int count_fractional_digits(long long num, long long den, int n = 0) {
1476 return num % den == 0
1477 ? n
1478 : (n > 18 ? 6 : count_fractional_digits(num * 10, den, n + 1));
1479 }
1480
1481 constexpr long long pow10(std::uint32_t n) {
1482 return n == 0 ? 1 : 10 * pow10(n - 1);
1483 }
1484
1485 template <class Rep, class Period,
1486 FMT_ENABLE_IF(std::numeric_limits<Rep>::is_signed)>
1487 constexpr std::chrono::duration<Rep, Period> abs(
1488 std::chrono::duration<Rep, Period> d) {
1489 // We need to compare the duration using the count() method directly
1490 // due to a compiler bug in clang-11 regarding the spaceship operator,
1491 // when -Wzero-as-null-pointer-constant is enabled.
1492 // In clang-12 the bug has been fixed. See
1493 // https://bugs.llvm.org/show_bug.cgi?id=46235 and the reproducible example:
1494 // https://www.godbolt.org/z/Knbb5joYx.
1495 return d.count() >= d.zero().count() ? d : -d;
1496 }
1497
1498 template <class Rep, class Period,
1499 FMT_ENABLE_IF(!std::numeric_limits<Rep>::is_signed)>
1500 constexpr std::chrono::duration<Rep, Period> abs(
1501 std::chrono::duration<Rep, Period> d) {
1502 return d;
1503 }
1504
1505 template <typename Char, typename Rep, typename OutputIt,
1506 FMT_ENABLE_IF(std::is_integral<Rep>::value)>
1507 OutputIt format_duration_value(OutputIt out, Rep val, int) {
1508 return write<Char>(out, val);
1509 }
1510
1511 template <typename Char, typename Rep, typename OutputIt,
1512 FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
1513 OutputIt format_duration_value(OutputIt out, Rep val, int precision) {
1514 auto specs = basic_format_specs<Char>();
1515 specs.precision = precision;
1516 specs.type = precision >= 0 ? presentation_type::fixed_lower
1517 : presentation_type::general_lower;
1518 return write<Char>(out, val, specs);
1519 }
1520
1521 template <typename Char, typename OutputIt>
1522 OutputIt copy_unit(string_view unit, OutputIt out, Char) {
1523 return std::copy(unit.begin(), unit.end(), out);
1524 }
1525
1526 template <typename OutputIt>
1527 OutputIt copy_unit(string_view unit, OutputIt out, wchar_t) {
1528 // This works when wchar_t is UTF-32 because units only contain characters
1529 // that have the same representation in UTF-16 and UTF-32.
1530 utf8_to_utf16 u(unit);
1531 return std::copy(u.c_str(), u.c_str() + u.size(), out);
1532 }
1533
1534 template <typename Char, typename Period, typename OutputIt>
1535 OutputIt format_duration_unit(OutputIt out) {
1536 if (const char* unit = get_units<Period>())
1537 return copy_unit(string_view(unit), out, Char());
1538 *out++ = '[';
1539 out = write<Char>(out, Period::num);
1540 if (const_check(Period::den != 1)) {
1541 *out++ = '/';
1542 out = write<Char>(out, Period::den);
1543 }
1544 *out++ = ']';
1545 *out++ = 's';
1546 return out;
1547 }
1548
1549 class get_locale {
1550 private:
1551 union {
1552 std::locale locale_;
1553 };
1554 bool has_locale_ = false;
1555
1556 public:
1557 get_locale(bool localized, locale_ref loc) : has_locale_(localized) {
1558 if (localized)
1559 ::new (&locale_) std::locale(loc.template get<std::locale>());
1560 }
1561 ~get_locale() {
1562 if (has_locale_) locale_.~locale();
1563 }
1564 operator const std::locale&() const {
1565 return has_locale_ ? locale_ : get_classic_locale();
1566 }
1567 };
1568
1569 template <typename FormatContext, typename OutputIt, typename Rep,
1570 typename Period>
1571 struct chrono_formatter {
1572 FormatContext& context;
1573 OutputIt out;
1574 int precision;
1575 bool localized = false;
1576 // rep is unsigned to avoid overflow.
1577 using rep =
1578 conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
1579 unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
1580 rep val;
1581 using seconds = std::chrono::duration<rep>;
1582 seconds s;
1583 using milliseconds = std::chrono::duration<rep, std::milli>;
1584 bool negative;
1585
1586 using char_type = typename FormatContext::char_type;
1587 using tm_writer_type = tm_writer<OutputIt, char_type>;
1588
1589 chrono_formatter(FormatContext& ctx, OutputIt o,
1590 std::chrono::duration<Rep, Period> d)
1591 : context(ctx),
1592 out(o),
1593 val(static_cast<rep>(d.count())),
1594 negative(false) {
1595 if (d.count() < 0) {
1596 val = 0 - val;
1597 negative = true;
1598 }
1599
1600 // this may overflow and/or the result may not fit in the
1601 // target type.
1602 #if FMT_SAFE_DURATION_CAST
1603 // might need checked conversion (rep!=Rep)
1604 auto tmpval = std::chrono::duration<rep, Period>(val);
1605 s = fmt_safe_duration_cast<seconds>(tmpval);
1606 #else
1607 s = std::chrono::duration_cast<seconds>(
1608 std::chrono::duration<rep, Period>(val));
1609 #endif
1610 }
1611
1612 // returns true if nan or inf, writes to out.
1613 bool handle_nan_inf() {
1614 if (isfinite(val)) {
1615 return false;
1616 }
1617 if (isnan(val)) {
1618 write_nan();
1619 return true;
1620 }
1621 // must be +-inf
1622 if (val > 0) {
1623 write_pinf();
1624 } else {
1625 write_ninf();
1626 }
1627 return true;
1628 }
1629
1630 Rep hour() const { return static_cast<Rep>(mod((s.count() / 3600), 24)); }
1631
1632 Rep hour12() const {
1633 Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
1634 return hour <= 0 ? 12 : hour;
1635 }
1636
1637 Rep minute() const { return static_cast<Rep>(mod((s.count() / 60), 60)); }
1638 Rep second() const { return static_cast<Rep>(mod(s.count(), 60)); }
1639
1640 std::tm time() const {
1641 auto time = std::tm();
1642 time.tm_hour = to_nonnegative_int(hour(), 24);
1643 time.tm_min = to_nonnegative_int(minute(), 60);
1644 time.tm_sec = to_nonnegative_int(second(), 60);
1645 return time;
1646 }
1647
1648 void write_sign() {
1649 if (negative) {
1650 *out++ = '-';
1651 negative = false;
1652 }
1653 }
1654
1655 void write(Rep value, int width) {
1656 write_sign();
1657 if (isnan(value)) return write_nan();
1658 uint32_or_64_or_128_t<int> n =
1659 to_unsigned(to_nonnegative_int(value, max_value<int>()));
1660 int num_digits = detail::count_digits(n);
1661 if (width > num_digits) out = std::fill_n(out, width - num_digits, '0');
1662 out = format_decimal<char_type>(out, n, num_digits).end;
1663 }
1664
1665 template <class Duration> void write_fractional_seconds(Duration d) {
1666 constexpr auto num_fractional_digits =
1667 count_fractional_digits(Duration::period::num, Duration::period::den);
1668
1669 using subsecond_precision = std::chrono::duration<
1670 typename std::common_type<typename Duration::rep,
1671 std::chrono::seconds::rep>::type,
1672 std::ratio<1, detail::pow10(num_fractional_digits)>>;
1673 if (std::ratio_less<typename subsecond_precision::period,
1674 std::chrono::seconds::period>::value) {
1675 *out++ = '.';
1676 // Don't convert long double to integer seconds to avoid overflow.
1677 using sec = conditional_t<
1678 std::is_same<typename Duration::rep, long double>::value,
1679 std::chrono::duration<long double>, std::chrono::seconds>;
1680 auto fractional = detail::abs(d) - std::chrono::duration_cast<sec>(d);
1681 const auto subseconds =
1682 std::chrono::treat_as_floating_point<
1683 typename subsecond_precision::rep>::value
1684 ? fractional.count()
1685 : std::chrono::duration_cast<subsecond_precision>(fractional)
1686 .count();
1687 uint32_or_64_or_128_t<long long> n =
1688 to_unsigned(to_nonnegative_int(subseconds, max_value<long long>()));
1689 int num_digits = detail::count_digits(n);
1690 if (num_fractional_digits > num_digits)
1691 out = std::fill_n(out, num_fractional_digits - num_digits, '0');
1692 out = format_decimal<char_type>(out, n, num_digits).end;
1693 }
1694 }
1695
1696 void write_nan() { std::copy_n("nan", 3, out); }
1697 void write_pinf() { std::copy_n("inf", 3, out); }
1698 void write_ninf() { std::copy_n("-inf", 4, out); }
1699
1700 template <typename Callback, typename... Args>
1701 void format_tm(const tm& time, Callback cb, Args... args) {
1702 if (isnan(val)) return write_nan();
1703 get_locale loc(localized, context.locale());
1704 auto w = tm_writer_type(loc, out, time);
1705 (w.*cb)(args...);
1706 out = w.out();
1707 }
1708
1709 void on_text(const char_type* begin, const char_type* end) {
1710 std::copy(begin, end, out);
1711 }
1712
1713 // These are not implemented because durations don't have date information.
1714 void on_abbr_weekday() {}
1715 void on_full_weekday() {}
1716 void on_dec0_weekday(numeric_system) {}
1717 void on_dec1_weekday(numeric_system) {}
1718 void on_abbr_month() {}
1719 void on_full_month() {}
1720 void on_datetime(numeric_system) {}
1721 void on_loc_date(numeric_system) {}
1722 void on_loc_time(numeric_system) {}
1723 void on_us_date() {}
1724 void on_iso_date() {}
1725 void on_utc_offset() {}
1726 void on_tz_name() {}
1727 void on_year(numeric_system) {}
1728 void on_short_year(numeric_system) {}
1729 void on_offset_year() {}
1730 void on_century(numeric_system) {}
1731 void on_iso_week_based_year() {}
1732 void on_iso_week_based_short_year() {}
1733 void on_dec_month(numeric_system) {}
1734 void on_dec0_week_of_year(numeric_system) {}
1735 void on_dec1_week_of_year(numeric_system) {}
1736 void on_iso_week_of_year(numeric_system) {}
1737 void on_day_of_year() {}
1738 void on_day_of_month(numeric_system) {}
1739 void on_day_of_month_space(numeric_system) {}
1740
1741 void on_24_hour(numeric_system ns) {
1742 if (handle_nan_inf()) return;
1743
1744 if (ns == numeric_system::standard) return write(hour(), 2);
1745 auto time = tm();
1746 time.tm_hour = to_nonnegative_int(hour(), 24);
1747 format_tm(time, &tm_writer_type::on_24_hour, ns);
1748 }
1749
1750 void on_12_hour(numeric_system ns) {
1751 if (handle_nan_inf()) return;
1752
1753 if (ns == numeric_system::standard) return write(hour12(), 2);
1754 auto time = tm();
1755 time.tm_hour = to_nonnegative_int(hour12(), 12);
1756 format_tm(time, &tm_writer_type::on_12_hour, ns);
1757 }
1758
1759 void on_minute(numeric_system ns) {
1760 if (handle_nan_inf()) return;
1761
1762 if (ns == numeric_system::standard) return write(minute(), 2);
1763 auto time = tm();
1764 time.tm_min = to_nonnegative_int(minute(), 60);
1765 format_tm(time, &tm_writer_type::on_minute, ns);
1766 }
1767
1768 void on_second(numeric_system ns) {
1769 if (handle_nan_inf()) return;
1770
1771 if (ns == numeric_system::standard) {
1772 write(second(), 2);
1773 write_fractional_seconds(std::chrono::duration<rep, Period>{val});
1774 return;
1775 }
1776 auto time = tm();
1777 time.tm_sec = to_nonnegative_int(second(), 60);
1778 format_tm(time, &tm_writer_type::on_second, ns);
1779 }
1780
1781 void on_12_hour_time() {
1782 if (handle_nan_inf()) return;
1783 format_tm(time(), &tm_writer_type::on_12_hour_time);
1784 }
1785
1786 void on_24_hour_time() {
1787 if (handle_nan_inf()) {
1788 *out++ = ':';
1789 handle_nan_inf();
1790 return;
1791 }
1792
1793 write(hour(), 2);
1794 *out++ = ':';
1795 write(minute(), 2);
1796 }
1797
1798 void on_iso_time() {
1799 on_24_hour_time();
1800 *out++ = ':';
1801 if (handle_nan_inf()) return;
1802 on_second(numeric_system::standard);
1803 }
1804
1805 void on_am_pm() {
1806 if (handle_nan_inf()) return;
1807 format_tm(time(), &tm_writer_type::on_am_pm);
1808 }
1809
1810 void on_duration_value() {
1811 if (handle_nan_inf()) return;
1812 write_sign();
1813 out = format_duration_value<char_type>(out, val, precision);
1814 }
1815
1816 void on_duration_unit() {
1817 out = format_duration_unit<char_type, Period>(out);
1818 }
1819 };
1820
1821 FMT_END_DETAIL_NAMESPACE
1822
1823 #if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907
1824 using weekday = std::chrono::weekday;
1825 #else
1826 // A fallback version of weekday.
1827 class weekday {
1828 private:
1829 unsigned char value;
1830
1831 public:
1832 weekday() = default;
1833 explicit constexpr weekday(unsigned wd) noexcept
1834 : value(static_cast<unsigned char>(wd != 7 ? wd : 0)) {}
1835 constexpr unsigned c_encoding() const noexcept { return value; }
1836 };
1837
1838 class year_month_day {};
1839 #endif
1840
1841 // A rudimentary weekday formatter.
1842 template <typename Char> struct formatter<weekday, Char> {
1843 private:
1844 bool localized = false;
1845
1846 public:
1847 FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
1848 -> decltype(ctx.begin()) {
1849 auto begin = ctx.begin(), end = ctx.end();
1850 if (begin != end && *begin == 'L') {
1851 ++begin;
1852 localized = true;
1853 }
1854 return begin;
1855 }
1856
1857 template <typename FormatContext>
1858 auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) {
1859 auto time = std::tm();
1860 time.tm_wday = static_cast<int>(wd.c_encoding());
1861 detail::get_locale loc(localized, ctx.locale());
1862 auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
1863 w.on_abbr_weekday();
1864 return w.out();
1865 }
1866 };
1867
1868 template <typename Rep, typename Period, typename Char>
1869 struct formatter<std::chrono::duration<Rep, Period>, Char> {
1870 private:
1871 basic_format_specs<Char> specs;
1872 int precision = -1;
1873 using arg_ref_type = detail::arg_ref<Char>;
1874 arg_ref_type width_ref;
1875 arg_ref_type precision_ref;
1876 bool localized = false;
1877 basic_string_view<Char> format_str;
1878 using duration = std::chrono::duration<Rep, Period>;
1879
1880 struct spec_handler {
1881 formatter& f;
1882 basic_format_parse_context<Char>& context;
1883 basic_string_view<Char> format_str;
1884
1885 template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
1886 context.check_arg_id(arg_id);
1887 return arg_ref_type(arg_id);
1888 }
1889
1890 FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<Char> arg_id) {
1891 context.check_arg_id(arg_id);
1892 return arg_ref_type(arg_id);
1893 }
1894
1895 FMT_CONSTEXPR arg_ref_type make_arg_ref(detail::auto_id) {
1896 return arg_ref_type(context.next_arg_id());
1897 }
1898
1899 void on_error(const char* msg) { FMT_THROW(format_error(msg)); }
1900 FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) {
1901 f.specs.fill = fill;
1902 }
1903 FMT_CONSTEXPR void on_align(align_t align) { f.specs.align = align; }
1904 FMT_CONSTEXPR void on_width(int width) { f.specs.width = width; }
1905 FMT_CONSTEXPR void on_precision(int _precision) {
1906 f.precision = _precision;
1907 }
1908 FMT_CONSTEXPR void end_precision() {}
1909
1910 template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
1911 f.width_ref = make_arg_ref(arg_id);
1912 }
1913
1914 template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
1915 f.precision_ref = make_arg_ref(arg_id);
1916 }
1917 };
1918
1919 using iterator = typename basic_format_parse_context<Char>::iterator;
1920 struct parse_range {
1921 iterator begin;
1922 iterator end;
1923 };
1924
1925 FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context<Char>& ctx) {
1926 auto begin = ctx.begin(), end = ctx.end();
1927 if (begin == end || *begin == '}') return {begin, begin};
1928 spec_handler handler{*this, ctx, format_str};
1929 begin = detail::parse_align(begin, end, handler);
1930 if (begin == end) return {begin, begin};
1931 begin = detail::parse_width(begin, end, handler);
1932 if (begin == end) return {begin, begin};
1933 if (*begin == '.') {
1934 if (std::is_floating_point<Rep>::value)
1935 begin = detail::parse_precision(begin, end, handler);
1936 else
1937 handler.on_error("precision not allowed for this argument type");
1938 }
1939 if (begin != end && *begin == 'L') {
1940 ++begin;
1941 localized = true;
1942 }
1943 end = detail::parse_chrono_format(begin, end,
1944 detail::chrono_format_checker());
1945 return {begin, end};
1946 }
1947
1948 public:
1949 FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
1950 -> decltype(ctx.begin()) {
1951 auto range = do_parse(ctx);
1952 format_str = basic_string_view<Char>(
1953 &*range.begin, detail::to_unsigned(range.end - range.begin));
1954 return range.end;
1955 }
1956
1957 template <typename FormatContext>
1958 auto format(const duration& d, FormatContext& ctx) const
1959 -> decltype(ctx.out()) {
1960 auto specs_copy = specs;
1961 auto precision_copy = precision;
1962 auto begin = format_str.begin(), end = format_str.end();
1963 // As a possible future optimization, we could avoid extra copying if width
1964 // is not specified.
1965 basic_memory_buffer<Char> buf;
1966 auto out = std::back_inserter(buf);
1967 detail::handle_dynamic_spec<detail::width_checker>(specs_copy.width,
1968 width_ref, ctx);
1969 detail::handle_dynamic_spec<detail::precision_checker>(precision_copy,
1970 precision_ref, ctx);
1971 if (begin == end || *begin == '}') {
1972 out = detail::format_duration_value<Char>(out, d.count(), precision_copy);
1973 detail::format_duration_unit<Char, Period>(out);
1974 } else {
1975 detail::chrono_formatter<FormatContext, decltype(out), Rep, Period> f(
1976 ctx, out, d);
1977 f.precision = precision_copy;
1978 f.localized = localized;
1979 detail::parse_chrono_format(begin, end, f);
1980 }
1981 return detail::write(
1982 ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs_copy);
1983 }
1984 };
1985
1986 template <typename Char, typename Duration>
1987 struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
1988 Char> : formatter<std::tm, Char> {
1989 FMT_CONSTEXPR formatter() {
1990 this->do_parse(default_specs,
1991 default_specs + sizeof(default_specs) / sizeof(Char));
1992 }
1993
1994 template <typename ParseContext>
1995 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
1996 return this->do_parse(ctx.begin(), ctx.end(), true);
1997 }
1998
1999 template <typename FormatContext>
2000 auto format(std::chrono::time_point<std::chrono::system_clock> val,
2001 FormatContext& ctx) const -> decltype(ctx.out()) {
2002 return formatter<std::tm, Char>::format(localtime(val), ctx);
2003 }
2004
2005 static constexpr const Char default_specs[] = {'%', 'F', ' ', '%', 'T'};
2006 };
2007
2008 template <typename Char, typename Duration>
2009 constexpr const Char
2010 formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
2011 Char>::default_specs[];
2012
2013 template <typename Char> struct formatter<std::tm, Char> {
2014 private:
2015 enum class spec {
2016 unknown,
2017 year_month_day,
2018 hh_mm_ss,
2019 };
2020 spec spec_ = spec::unknown;
2021 basic_string_view<Char> specs;
2022
2023 protected:
2024 template <typename It>
2025 FMT_CONSTEXPR auto do_parse(It begin, It end, bool with_default = false)
2026 -> It {
2027 if (begin != end && *begin == ':') ++begin;
2028 end = detail::parse_chrono_format(begin, end, detail::tm_format_checker());
2029 if (!with_default || end != begin)
2030 specs = {begin, detail::to_unsigned(end - begin)};
2031 // basic_string_view<>::compare isn't constexpr before C++17.
2032 if (specs.size() == 2 && specs[0] == Char('%')) {
2033 if (specs[1] == Char('F'))
2034 spec_ = spec::year_month_day;
2035 else if (specs[1] == Char('T'))
2036 spec_ = spec::hh_mm_ss;
2037 }
2038 return end;
2039 }
2040
2041 public:
2042 template <typename ParseContext>
2043 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
2044 return this->do_parse(ctx.begin(), ctx.end());
2045 }
2046
2047 template <typename FormatContext>
2048 auto format(const std::tm& tm, FormatContext& ctx) const
2049 -> decltype(ctx.out()) {
2050 const auto loc_ref = ctx.locale();
2051 detail::get_locale loc(static_cast<bool>(loc_ref), loc_ref);
2052 auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), tm);
2053 if (spec_ == spec::year_month_day)
2054 w.on_iso_date();
2055 else if (spec_ == spec::hh_mm_ss)
2056 w.on_iso_time();
2057 else
2058 detail::parse_chrono_format(specs.begin(), specs.end(), w);
2059 return w.out();
2060 }
2061 };
2062
2063 FMT_MODULE_EXPORT_END
2064 FMT_END_NAMESPACE
2065
2066 #endif // FMT_CHRONO_H_
+0
-638
source/misc/embedded_libs/fmt-8.1.1/include/fmt/color.h less more
0 // Formatting library for C++ - color support
1 //
2 // Copyright (c) 2018 - present, Victor Zverovich and fmt contributors
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_COLOR_H_
8 #define FMT_COLOR_H_
9
10 #include "format.h"
11
12 // __declspec(deprecated) is broken in some MSVC versions.
13 #if FMT_MSC_VER
14 # define FMT_DEPRECATED_NONMSVC
15 #else
16 # define FMT_DEPRECATED_NONMSVC FMT_DEPRECATED
17 #endif
18
19 FMT_BEGIN_NAMESPACE
20 FMT_MODULE_EXPORT_BEGIN
21
22 enum class color : uint32_t {
23 alice_blue = 0xF0F8FF, // rgb(240,248,255)
24 antique_white = 0xFAEBD7, // rgb(250,235,215)
25 aqua = 0x00FFFF, // rgb(0,255,255)
26 aquamarine = 0x7FFFD4, // rgb(127,255,212)
27 azure = 0xF0FFFF, // rgb(240,255,255)
28 beige = 0xF5F5DC, // rgb(245,245,220)
29 bisque = 0xFFE4C4, // rgb(255,228,196)
30 black = 0x000000, // rgb(0,0,0)
31 blanched_almond = 0xFFEBCD, // rgb(255,235,205)
32 blue = 0x0000FF, // rgb(0,0,255)
33 blue_violet = 0x8A2BE2, // rgb(138,43,226)
34 brown = 0xA52A2A, // rgb(165,42,42)
35 burly_wood = 0xDEB887, // rgb(222,184,135)
36 cadet_blue = 0x5F9EA0, // rgb(95,158,160)
37 chartreuse = 0x7FFF00, // rgb(127,255,0)
38 chocolate = 0xD2691E, // rgb(210,105,30)
39 coral = 0xFF7F50, // rgb(255,127,80)
40 cornflower_blue = 0x6495ED, // rgb(100,149,237)
41 cornsilk = 0xFFF8DC, // rgb(255,248,220)
42 crimson = 0xDC143C, // rgb(220,20,60)
43 cyan = 0x00FFFF, // rgb(0,255,255)
44 dark_blue = 0x00008B, // rgb(0,0,139)
45 dark_cyan = 0x008B8B, // rgb(0,139,139)
46 dark_golden_rod = 0xB8860B, // rgb(184,134,11)
47 dark_gray = 0xA9A9A9, // rgb(169,169,169)
48 dark_green = 0x006400, // rgb(0,100,0)
49 dark_khaki = 0xBDB76B, // rgb(189,183,107)
50 dark_magenta = 0x8B008B, // rgb(139,0,139)
51 dark_olive_green = 0x556B2F, // rgb(85,107,47)
52 dark_orange = 0xFF8C00, // rgb(255,140,0)
53 dark_orchid = 0x9932CC, // rgb(153,50,204)
54 dark_red = 0x8B0000, // rgb(139,0,0)
55 dark_salmon = 0xE9967A, // rgb(233,150,122)
56 dark_sea_green = 0x8FBC8F, // rgb(143,188,143)
57 dark_slate_blue = 0x483D8B, // rgb(72,61,139)
58 dark_slate_gray = 0x2F4F4F, // rgb(47,79,79)
59 dark_turquoise = 0x00CED1, // rgb(0,206,209)
60 dark_violet = 0x9400D3, // rgb(148,0,211)
61 deep_pink = 0xFF1493, // rgb(255,20,147)
62 deep_sky_blue = 0x00BFFF, // rgb(0,191,255)
63 dim_gray = 0x696969, // rgb(105,105,105)
64 dodger_blue = 0x1E90FF, // rgb(30,144,255)
65 fire_brick = 0xB22222, // rgb(178,34,34)
66 floral_white = 0xFFFAF0, // rgb(255,250,240)
67 forest_green = 0x228B22, // rgb(34,139,34)
68 fuchsia = 0xFF00FF, // rgb(255,0,255)
69 gainsboro = 0xDCDCDC, // rgb(220,220,220)
70 ghost_white = 0xF8F8FF, // rgb(248,248,255)
71 gold = 0xFFD700, // rgb(255,215,0)
72 golden_rod = 0xDAA520, // rgb(218,165,32)
73 gray = 0x808080, // rgb(128,128,128)
74 green = 0x008000, // rgb(0,128,0)
75 green_yellow = 0xADFF2F, // rgb(173,255,47)
76 honey_dew = 0xF0FFF0, // rgb(240,255,240)
77 hot_pink = 0xFF69B4, // rgb(255,105,180)
78 indian_red = 0xCD5C5C, // rgb(205,92,92)
79 indigo = 0x4B0082, // rgb(75,0,130)
80 ivory = 0xFFFFF0, // rgb(255,255,240)
81 khaki = 0xF0E68C, // rgb(240,230,140)
82 lavender = 0xE6E6FA, // rgb(230,230,250)
83 lavender_blush = 0xFFF0F5, // rgb(255,240,245)
84 lawn_green = 0x7CFC00, // rgb(124,252,0)
85 lemon_chiffon = 0xFFFACD, // rgb(255,250,205)
86 light_blue = 0xADD8E6, // rgb(173,216,230)
87 light_coral = 0xF08080, // rgb(240,128,128)
88 light_cyan = 0xE0FFFF, // rgb(224,255,255)
89 light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210)
90 light_gray = 0xD3D3D3, // rgb(211,211,211)
91 light_green = 0x90EE90, // rgb(144,238,144)
92 light_pink = 0xFFB6C1, // rgb(255,182,193)
93 light_salmon = 0xFFA07A, // rgb(255,160,122)
94 light_sea_green = 0x20B2AA, // rgb(32,178,170)
95 light_sky_blue = 0x87CEFA, // rgb(135,206,250)
96 light_slate_gray = 0x778899, // rgb(119,136,153)
97 light_steel_blue = 0xB0C4DE, // rgb(176,196,222)
98 light_yellow = 0xFFFFE0, // rgb(255,255,224)
99 lime = 0x00FF00, // rgb(0,255,0)
100 lime_green = 0x32CD32, // rgb(50,205,50)
101 linen = 0xFAF0E6, // rgb(250,240,230)
102 magenta = 0xFF00FF, // rgb(255,0,255)
103 maroon = 0x800000, // rgb(128,0,0)
104 medium_aquamarine = 0x66CDAA, // rgb(102,205,170)
105 medium_blue = 0x0000CD, // rgb(0,0,205)
106 medium_orchid = 0xBA55D3, // rgb(186,85,211)
107 medium_purple = 0x9370DB, // rgb(147,112,219)
108 medium_sea_green = 0x3CB371, // rgb(60,179,113)
109 medium_slate_blue = 0x7B68EE, // rgb(123,104,238)
110 medium_spring_green = 0x00FA9A, // rgb(0,250,154)
111 medium_turquoise = 0x48D1CC, // rgb(72,209,204)
112 medium_violet_red = 0xC71585, // rgb(199,21,133)
113 midnight_blue = 0x191970, // rgb(25,25,112)
114 mint_cream = 0xF5FFFA, // rgb(245,255,250)
115 misty_rose = 0xFFE4E1, // rgb(255,228,225)
116 moccasin = 0xFFE4B5, // rgb(255,228,181)
117 navajo_white = 0xFFDEAD, // rgb(255,222,173)
118 navy = 0x000080, // rgb(0,0,128)
119 old_lace = 0xFDF5E6, // rgb(253,245,230)
120 olive = 0x808000, // rgb(128,128,0)
121 olive_drab = 0x6B8E23, // rgb(107,142,35)
122 orange = 0xFFA500, // rgb(255,165,0)
123 orange_red = 0xFF4500, // rgb(255,69,0)
124 orchid = 0xDA70D6, // rgb(218,112,214)
125 pale_golden_rod = 0xEEE8AA, // rgb(238,232,170)
126 pale_green = 0x98FB98, // rgb(152,251,152)
127 pale_turquoise = 0xAFEEEE, // rgb(175,238,238)
128 pale_violet_red = 0xDB7093, // rgb(219,112,147)
129 papaya_whip = 0xFFEFD5, // rgb(255,239,213)
130 peach_puff = 0xFFDAB9, // rgb(255,218,185)
131 peru = 0xCD853F, // rgb(205,133,63)
132 pink = 0xFFC0CB, // rgb(255,192,203)
133 plum = 0xDDA0DD, // rgb(221,160,221)
134 powder_blue = 0xB0E0E6, // rgb(176,224,230)
135 purple = 0x800080, // rgb(128,0,128)
136 rebecca_purple = 0x663399, // rgb(102,51,153)
137 red = 0xFF0000, // rgb(255,0,0)
138 rosy_brown = 0xBC8F8F, // rgb(188,143,143)
139 royal_blue = 0x4169E1, // rgb(65,105,225)
140 saddle_brown = 0x8B4513, // rgb(139,69,19)
141 salmon = 0xFA8072, // rgb(250,128,114)
142 sandy_brown = 0xF4A460, // rgb(244,164,96)
143 sea_green = 0x2E8B57, // rgb(46,139,87)
144 sea_shell = 0xFFF5EE, // rgb(255,245,238)
145 sienna = 0xA0522D, // rgb(160,82,45)
146 silver = 0xC0C0C0, // rgb(192,192,192)
147 sky_blue = 0x87CEEB, // rgb(135,206,235)
148 slate_blue = 0x6A5ACD, // rgb(106,90,205)
149 slate_gray = 0x708090, // rgb(112,128,144)
150 snow = 0xFFFAFA, // rgb(255,250,250)
151 spring_green = 0x00FF7F, // rgb(0,255,127)
152 steel_blue = 0x4682B4, // rgb(70,130,180)
153 tan = 0xD2B48C, // rgb(210,180,140)
154 teal = 0x008080, // rgb(0,128,128)
155 thistle = 0xD8BFD8, // rgb(216,191,216)
156 tomato = 0xFF6347, // rgb(255,99,71)
157 turquoise = 0x40E0D0, // rgb(64,224,208)
158 violet = 0xEE82EE, // rgb(238,130,238)
159 wheat = 0xF5DEB3, // rgb(245,222,179)
160 white = 0xFFFFFF, // rgb(255,255,255)
161 white_smoke = 0xF5F5F5, // rgb(245,245,245)
162 yellow = 0xFFFF00, // rgb(255,255,0)
163 yellow_green = 0x9ACD32 // rgb(154,205,50)
164 }; // enum class color
165
166 enum class terminal_color : uint8_t {
167 black = 30,
168 red,
169 green,
170 yellow,
171 blue,
172 magenta,
173 cyan,
174 white,
175 bright_black = 90,
176 bright_red,
177 bright_green,
178 bright_yellow,
179 bright_blue,
180 bright_magenta,
181 bright_cyan,
182 bright_white
183 };
184
185 enum class emphasis : uint8_t {
186 bold = 1,
187 faint = 1 << 1,
188 italic = 1 << 2,
189 underline = 1 << 3,
190 blink = 1 << 4,
191 reverse = 1 << 5,
192 conceal = 1 << 6,
193 strikethrough = 1 << 7,
194 };
195
196 // rgb is a struct for red, green and blue colors.
197 // Using the name "rgb" makes some editors show the color in a tooltip.
198 struct rgb {
199 FMT_CONSTEXPR rgb() : r(0), g(0), b(0) {}
200 FMT_CONSTEXPR rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {}
201 FMT_CONSTEXPR rgb(uint32_t hex)
202 : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {}
203 FMT_CONSTEXPR rgb(color hex)
204 : r((uint32_t(hex) >> 16) & 0xFF),
205 g((uint32_t(hex) >> 8) & 0xFF),
206 b(uint32_t(hex) & 0xFF) {}
207 uint8_t r;
208 uint8_t g;
209 uint8_t b;
210 };
211
212 FMT_BEGIN_DETAIL_NAMESPACE
213
214 // color is a struct of either a rgb color or a terminal color.
215 struct color_type {
216 FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {}
217 FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true),
218 value{} {
219 value.rgb_color = static_cast<uint32_t>(rgb_color);
220 }
221 FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} {
222 value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) |
223 (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
224 }
225 FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(),
226 value{} {
227 value.term_color = static_cast<uint8_t>(term_color);
228 }
229 bool is_rgb;
230 union color_union {
231 uint8_t term_color;
232 uint32_t rgb_color;
233 } value;
234 };
235
236 FMT_END_DETAIL_NAMESPACE
237
238 /** A text style consisting of foreground and background colors and emphasis. */
239 class text_style {
240 public:
241 FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT
242 : set_foreground_color(),
243 set_background_color(),
244 ems(em) {}
245
246 FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) {
247 if (!set_foreground_color) {
248 set_foreground_color = rhs.set_foreground_color;
249 foreground_color = rhs.foreground_color;
250 } else if (rhs.set_foreground_color) {
251 if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb)
252 FMT_THROW(format_error("can't OR a terminal color"));
253 foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color;
254 }
255
256 if (!set_background_color) {
257 set_background_color = rhs.set_background_color;
258 background_color = rhs.background_color;
259 } else if (rhs.set_background_color) {
260 if (!background_color.is_rgb || !rhs.background_color.is_rgb)
261 FMT_THROW(format_error("can't OR a terminal color"));
262 background_color.value.rgb_color |= rhs.background_color.value.rgb_color;
263 }
264
265 ems = static_cast<emphasis>(static_cast<uint8_t>(ems) |
266 static_cast<uint8_t>(rhs.ems));
267 return *this;
268 }
269
270 friend FMT_CONSTEXPR text_style operator|(text_style lhs,
271 const text_style& rhs) {
272 return lhs |= rhs;
273 }
274
275 FMT_DEPRECATED_NONMSVC FMT_CONSTEXPR text_style& operator&=(
276 const text_style& rhs) {
277 return and_assign(rhs);
278 }
279
280 FMT_DEPRECATED_NONMSVC friend FMT_CONSTEXPR text_style
281 operator&(text_style lhs, const text_style& rhs) {
282 return lhs.and_assign(rhs);
283 }
284
285 FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT {
286 return set_foreground_color;
287 }
288 FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT {
289 return set_background_color;
290 }
291 FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT {
292 return static_cast<uint8_t>(ems) != 0;
293 }
294 FMT_CONSTEXPR detail::color_type get_foreground() const FMT_NOEXCEPT {
295 FMT_ASSERT(has_foreground(), "no foreground specified for this style");
296 return foreground_color;
297 }
298 FMT_CONSTEXPR detail::color_type get_background() const FMT_NOEXCEPT {
299 FMT_ASSERT(has_background(), "no background specified for this style");
300 return background_color;
301 }
302 FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT {
303 FMT_ASSERT(has_emphasis(), "no emphasis specified for this style");
304 return ems;
305 }
306
307 private:
308 FMT_CONSTEXPR text_style(bool is_foreground,
309 detail::color_type text_color) FMT_NOEXCEPT
310 : set_foreground_color(),
311 set_background_color(),
312 ems() {
313 if (is_foreground) {
314 foreground_color = text_color;
315 set_foreground_color = true;
316 } else {
317 background_color = text_color;
318 set_background_color = true;
319 }
320 }
321
322 // DEPRECATED!
323 FMT_CONSTEXPR text_style& and_assign(const text_style& rhs) {
324 if (!set_foreground_color) {
325 set_foreground_color = rhs.set_foreground_color;
326 foreground_color = rhs.foreground_color;
327 } else if (rhs.set_foreground_color) {
328 if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb)
329 FMT_THROW(format_error("can't AND a terminal color"));
330 foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color;
331 }
332
333 if (!set_background_color) {
334 set_background_color = rhs.set_background_color;
335 background_color = rhs.background_color;
336 } else if (rhs.set_background_color) {
337 if (!background_color.is_rgb || !rhs.background_color.is_rgb)
338 FMT_THROW(format_error("can't AND a terminal color"));
339 background_color.value.rgb_color &= rhs.background_color.value.rgb_color;
340 }
341
342 ems = static_cast<emphasis>(static_cast<uint8_t>(ems) &
343 static_cast<uint8_t>(rhs.ems));
344 return *this;
345 }
346
347 friend FMT_CONSTEXPR_DECL text_style fg(detail::color_type foreground)
348 FMT_NOEXCEPT;
349
350 friend FMT_CONSTEXPR_DECL text_style bg(detail::color_type background)
351 FMT_NOEXCEPT;
352
353 detail::color_type foreground_color;
354 detail::color_type background_color;
355 bool set_foreground_color;
356 bool set_background_color;
357 emphasis ems;
358 };
359
360 /** Creates a text style from the foreground (text) color. */
361 FMT_CONSTEXPR inline text_style fg(detail::color_type foreground) FMT_NOEXCEPT {
362 return text_style(true, foreground);
363 }
364
365 /** Creates a text style from the background color. */
366 FMT_CONSTEXPR inline text_style bg(detail::color_type background) FMT_NOEXCEPT {
367 return text_style(false, background);
368 }
369
370 FMT_CONSTEXPR inline text_style operator|(emphasis lhs,
371 emphasis rhs) FMT_NOEXCEPT {
372 return text_style(lhs) | rhs;
373 }
374
375 FMT_BEGIN_DETAIL_NAMESPACE
376
377 template <typename Char> struct ansi_color_escape {
378 FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color,
379 const char* esc) FMT_NOEXCEPT {
380 // If we have a terminal color, we need to output another escape code
381 // sequence.
382 if (!text_color.is_rgb) {
383 bool is_background = esc == string_view("\x1b[48;2;");
384 uint32_t value = text_color.value.term_color;
385 // Background ASCII codes are the same as the foreground ones but with
386 // 10 more.
387 if (is_background) value += 10u;
388
389 size_t index = 0;
390 buffer[index++] = static_cast<Char>('\x1b');
391 buffer[index++] = static_cast<Char>('[');
392
393 if (value >= 100u) {
394 buffer[index++] = static_cast<Char>('1');
395 value %= 100u;
396 }
397 buffer[index++] = static_cast<Char>('0' + value / 10u);
398 buffer[index++] = static_cast<Char>('0' + value % 10u);
399
400 buffer[index++] = static_cast<Char>('m');
401 buffer[index++] = static_cast<Char>('\0');
402 return;
403 }
404
405 for (int i = 0; i < 7; i++) {
406 buffer[i] = static_cast<Char>(esc[i]);
407 }
408 rgb color(text_color.value.rgb_color);
409 to_esc(color.r, buffer + 7, ';');
410 to_esc(color.g, buffer + 11, ';');
411 to_esc(color.b, buffer + 15, 'm');
412 buffer[19] = static_cast<Char>(0);
413 }
414 FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT {
415 uint8_t em_codes[num_emphases] = {};
416 if (has_emphasis(em, emphasis::bold)) em_codes[0] = 1;
417 if (has_emphasis(em, emphasis::faint)) em_codes[1] = 2;
418 if (has_emphasis(em, emphasis::italic)) em_codes[2] = 3;
419 if (has_emphasis(em, emphasis::underline)) em_codes[3] = 4;
420 if (has_emphasis(em, emphasis::blink)) em_codes[4] = 5;
421 if (has_emphasis(em, emphasis::reverse)) em_codes[5] = 7;
422 if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8;
423 if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9;
424
425 size_t index = 0;
426 for (size_t i = 0; i < num_emphases; ++i) {
427 if (!em_codes[i]) continue;
428 buffer[index++] = static_cast<Char>('\x1b');
429 buffer[index++] = static_cast<Char>('[');
430 buffer[index++] = static_cast<Char>('0' + em_codes[i]);
431 buffer[index++] = static_cast<Char>('m');
432 }
433 buffer[index++] = static_cast<Char>(0);
434 }
435 FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; }
436
437 FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; }
438 FMT_CONSTEXPR_CHAR_TRAITS const Char* end() const FMT_NOEXCEPT {
439 return buffer + std::char_traits<Char>::length(buffer);
440 }
441
442 private:
443 static constexpr size_t num_emphases = 8;
444 Char buffer[7u + 3u * num_emphases + 1u];
445
446 static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
447 char delimiter) FMT_NOEXCEPT {
448 out[0] = static_cast<Char>('0' + c / 100);
449 out[1] = static_cast<Char>('0' + c / 10 % 10);
450 out[2] = static_cast<Char>('0' + c % 10);
451 out[3] = static_cast<Char>(delimiter);
452 }
453 static FMT_CONSTEXPR bool has_emphasis(emphasis em,
454 emphasis mask) FMT_NOEXCEPT {
455 return static_cast<uint8_t>(em) & static_cast<uint8_t>(mask);
456 }
457 };
458
459 template <typename Char>
460 FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color(
461 detail::color_type foreground) FMT_NOEXCEPT {
462 return ansi_color_escape<Char>(foreground, "\x1b[38;2;");
463 }
464
465 template <typename Char>
466 FMT_CONSTEXPR ansi_color_escape<Char> make_background_color(
467 detail::color_type background) FMT_NOEXCEPT {
468 return ansi_color_escape<Char>(background, "\x1b[48;2;");
469 }
470
471 template <typename Char>
472 FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT {
473 return ansi_color_escape<Char>(em);
474 }
475
476 template <typename Char>
477 inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT {
478 std::fputs(chars, stream);
479 }
480
481 template <>
482 inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT {
483 std::fputws(chars, stream);
484 }
485
486 template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT {
487 fputs("\x1b[0m", stream);
488 }
489
490 template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT {
491 fputs(L"\x1b[0m", stream);
492 }
493
494 template <typename Char>
495 inline void reset_color(buffer<Char>& buffer) FMT_NOEXCEPT {
496 auto reset_color = string_view("\x1b[0m");
497 buffer.append(reset_color.begin(), reset_color.end());
498 }
499
500 template <typename Char>
501 void vformat_to(buffer<Char>& buf, const text_style& ts,
502 basic_string_view<Char> format_str,
503 basic_format_args<buffer_context<type_identity_t<Char>>> args) {
504 bool has_style = false;
505 if (ts.has_emphasis()) {
506 has_style = true;
507 auto emphasis = detail::make_emphasis<Char>(ts.get_emphasis());
508 buf.append(emphasis.begin(), emphasis.end());
509 }
510 if (ts.has_foreground()) {
511 has_style = true;
512 auto foreground = detail::make_foreground_color<Char>(ts.get_foreground());
513 buf.append(foreground.begin(), foreground.end());
514 }
515 if (ts.has_background()) {
516 has_style = true;
517 auto background = detail::make_background_color<Char>(ts.get_background());
518 buf.append(background.begin(), background.end());
519 }
520 detail::vformat_to(buf, format_str, args, {});
521 if (has_style) detail::reset_color<Char>(buf);
522 }
523
524 FMT_END_DETAIL_NAMESPACE
525
526 template <typename S, typename Char = char_t<S>>
527 void vprint(std::FILE* f, const text_style& ts, const S& format,
528 basic_format_args<buffer_context<type_identity_t<Char>>> args) {
529 basic_memory_buffer<Char> buf;
530 detail::vformat_to(buf, ts, to_string_view(format), args);
531 buf.push_back(Char(0));
532 detail::fputs(buf.data(), f);
533 }
534
535 /**
536 \rst
537 Formats a string and prints it to the specified file stream using ANSI
538 escape sequences to specify text formatting.
539
540 **Example**::
541
542 fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
543 "Elapsed time: {0:.2f} seconds", 1.23);
544 \endrst
545 */
546 template <typename S, typename... Args,
547 FMT_ENABLE_IF(detail::is_string<S>::value)>
548 void print(std::FILE* f, const text_style& ts, const S& format_str,
549 const Args&... args) {
550 vprint(f, ts, format_str,
551 fmt::make_args_checked<Args...>(format_str, args...));
552 }
553
554 /**
555 \rst
556 Formats a string and prints it to stdout using ANSI escape sequences to
557 specify text formatting.
558
559 **Example**::
560
561 fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
562 "Elapsed time: {0:.2f} seconds", 1.23);
563 \endrst
564 */
565 template <typename S, typename... Args,
566 FMT_ENABLE_IF(detail::is_string<S>::value)>
567 void print(const text_style& ts, const S& format_str, const Args&... args) {
568 return print(stdout, ts, format_str, args...);
569 }
570
571 template <typename S, typename Char = char_t<S>>
572 inline std::basic_string<Char> vformat(
573 const text_style& ts, const S& format_str,
574 basic_format_args<buffer_context<type_identity_t<Char>>> args) {
575 basic_memory_buffer<Char> buf;
576 detail::vformat_to(buf, ts, to_string_view(format_str), args);
577 return fmt::to_string(buf);
578 }
579
580 /**
581 \rst
582 Formats arguments and returns the result as a string using ANSI
583 escape sequences to specify text formatting.
584
585 **Example**::
586
587 #include <fmt/color.h>
588 std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),
589 "The answer is {}", 42);
590 \endrst
591 */
592 template <typename S, typename... Args, typename Char = char_t<S>>
593 inline std::basic_string<Char> format(const text_style& ts, const S& format_str,
594 const Args&... args) {
595 return fmt::vformat(ts, to_string_view(format_str),
596 fmt::make_args_checked<Args...>(format_str, args...));
597 }
598
599 /**
600 Formats a string with the given text_style and writes the output to ``out``.
601 */
602 template <typename OutputIt, typename Char,
603 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)>
604 OutputIt vformat_to(
605 OutputIt out, const text_style& ts, basic_string_view<Char> format_str,
606 basic_format_args<buffer_context<type_identity_t<Char>>> args) {
607 auto&& buf = detail::get_buffer<Char>(out);
608 detail::vformat_to(buf, ts, format_str, args);
609 return detail::get_iterator(buf);
610 }
611
612 /**
613 \rst
614 Formats arguments with the given text_style, writes the result to the output
615 iterator ``out`` and returns the iterator past the end of the output range.
616
617 **Example**::
618
619 std::vector<char> out;
620 fmt::format_to(std::back_inserter(out),
621 fmt::emphasis::bold | fg(fmt::color::red), "{}", 42);
622 \endrst
623 */
624 template <typename OutputIt, typename S, typename... Args,
625 bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value&&
626 detail::is_string<S>::value>
627 inline auto format_to(OutputIt out, const text_style& ts, const S& format_str,
628 Args&&... args) ->
629 typename std::enable_if<enable, OutputIt>::type {
630 return vformat_to(out, ts, to_string_view(format_str),
631 fmt::make_args_checked<Args...>(format_str, args...));
632 }
633
634 FMT_MODULE_EXPORT_END
635 FMT_END_NAMESPACE
636
637 #endif // FMT_COLOR_H_
+0
-642
source/misc/embedded_libs/fmt-8.1.1/include/fmt/compile.h less more
0 // Formatting library for C++ - experimental format string compilation
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich and fmt contributors
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_COMPILE_H_
8 #define FMT_COMPILE_H_
9
10 #include "format.h"
11
12 FMT_BEGIN_NAMESPACE
13 namespace detail {
14
15 // An output iterator that counts the number of objects written to it and
16 // discards them.
17 class counting_iterator {
18 private:
19 size_t count_;
20
21 public:
22 using iterator_category = std::output_iterator_tag;
23 using difference_type = std::ptrdiff_t;
24 using pointer = void;
25 using reference = void;
26 using _Unchecked_type = counting_iterator; // Mark iterator as checked.
27
28 struct value_type {
29 template <typename T> void operator=(const T&) {}
30 };
31
32 counting_iterator() : count_(0) {}
33
34 size_t count() const { return count_; }
35
36 counting_iterator& operator++() {
37 ++count_;
38 return *this;
39 }
40 counting_iterator operator++(int) {
41 auto it = *this;
42 ++*this;
43 return it;
44 }
45
46 friend counting_iterator operator+(counting_iterator it, difference_type n) {
47 it.count_ += static_cast<size_t>(n);
48 return it;
49 }
50
51 value_type operator*() const { return {}; }
52 };
53
54 template <typename Char, typename InputIt>
55 inline counting_iterator copy_str(InputIt begin, InputIt end,
56 counting_iterator it) {
57 return it + (end - begin);
58 }
59
60 template <typename OutputIt> class truncating_iterator_base {
61 protected:
62 OutputIt out_;
63 size_t limit_;
64 size_t count_ = 0;
65
66 truncating_iterator_base() : out_(), limit_(0) {}
67
68 truncating_iterator_base(OutputIt out, size_t limit)
69 : out_(out), limit_(limit) {}
70
71 public:
72 using iterator_category = std::output_iterator_tag;
73 using value_type = typename std::iterator_traits<OutputIt>::value_type;
74 using difference_type = std::ptrdiff_t;
75 using pointer = void;
76 using reference = void;
77 using _Unchecked_type =
78 truncating_iterator_base; // Mark iterator as checked.
79
80 OutputIt base() const { return out_; }
81 size_t count() const { return count_; }
82 };
83
84 // An output iterator that truncates the output and counts the number of objects
85 // written to it.
86 template <typename OutputIt,
87 typename Enable = typename std::is_void<
88 typename std::iterator_traits<OutputIt>::value_type>::type>
89 class truncating_iterator;
90
91 template <typename OutputIt>
92 class truncating_iterator<OutputIt, std::false_type>
93 : public truncating_iterator_base<OutputIt> {
94 mutable typename truncating_iterator_base<OutputIt>::value_type blackhole_;
95
96 public:
97 using value_type = typename truncating_iterator_base<OutputIt>::value_type;
98
99 truncating_iterator() = default;
100
101 truncating_iterator(OutputIt out, size_t limit)
102 : truncating_iterator_base<OutputIt>(out, limit) {}
103
104 truncating_iterator& operator++() {
105 if (this->count_++ < this->limit_) ++this->out_;
106 return *this;
107 }
108
109 truncating_iterator operator++(int) {
110 auto it = *this;
111 ++*this;
112 return it;
113 }
114
115 value_type& operator*() const {
116 return this->count_ < this->limit_ ? *this->out_ : blackhole_;
117 }
118 };
119
120 template <typename OutputIt>
121 class truncating_iterator<OutputIt, std::true_type>
122 : public truncating_iterator_base<OutputIt> {
123 public:
124 truncating_iterator() = default;
125
126 truncating_iterator(OutputIt out, size_t limit)
127 : truncating_iterator_base<OutputIt>(out, limit) {}
128
129 template <typename T> truncating_iterator& operator=(T val) {
130 if (this->count_++ < this->limit_) *this->out_++ = val;
131 return *this;
132 }
133
134 truncating_iterator& operator++() { return *this; }
135 truncating_iterator& operator++(int) { return *this; }
136 truncating_iterator& operator*() { return *this; }
137 };
138
139 // A compile-time string which is compiled into fast formatting code.
140 class compiled_string {};
141
142 template <typename S>
143 struct is_compiled_string : std::is_base_of<compiled_string, S> {};
144
145 /**
146 \rst
147 Converts a string literal *s* into a format string that will be parsed at
148 compile time and converted into efficient formatting code. Requires C++17
149 ``constexpr if`` compiler support.
150
151 **Example**::
152
153 // Converts 42 into std::string using the most efficient method and no
154 // runtime format string processing.
155 std::string s = fmt::format(FMT_COMPILE("{}"), 42);
156 \endrst
157 */
158 #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
159 # define FMT_COMPILE(s) \
160 FMT_STRING_IMPL(s, fmt::detail::compiled_string, explicit)
161 #else
162 # define FMT_COMPILE(s) FMT_STRING(s)
163 #endif
164
165 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
166 template <typename Char, size_t N,
167 fmt::detail_exported::fixed_string<Char, N> Str>
168 struct udl_compiled_string : compiled_string {
169 using char_type = Char;
170 constexpr operator basic_string_view<char_type>() const {
171 return {Str.data, N - 1};
172 }
173 };
174 #endif
175
176 template <typename T, typename... Tail>
177 const T& first(const T& value, const Tail&...) {
178 return value;
179 }
180
181 #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
182 template <typename... Args> struct type_list {};
183
184 // Returns a reference to the argument at index N from [first, rest...].
185 template <int N, typename T, typename... Args>
186 constexpr const auto& get([[maybe_unused]] const T& first,
187 [[maybe_unused]] const Args&... rest) {
188 static_assert(N < 1 + sizeof...(Args), "index is out of bounds");
189 if constexpr (N == 0)
190 return first;
191 else
192 return detail::get<N - 1>(rest...);
193 }
194
195 template <typename Char, typename... Args>
196 constexpr int get_arg_index_by_name(basic_string_view<Char> name,
197 type_list<Args...>) {
198 return get_arg_index_by_name<Args...>(name);
199 }
200
201 template <int N, typename> struct get_type_impl;
202
203 template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {
204 using type =
205 remove_cvref_t<decltype(detail::get<N>(std::declval<Args>()...))>;
206 };
207
208 template <int N, typename T>
209 using get_type = typename get_type_impl<N, T>::type;
210
211 template <typename T> struct is_compiled_format : std::false_type {};
212
213 template <typename Char> struct text {
214 basic_string_view<Char> data;
215 using char_type = Char;
216
217 template <typename OutputIt, typename... Args>
218 constexpr OutputIt format(OutputIt out, const Args&...) const {
219 return write<Char>(out, data);
220 }
221 };
222
223 template <typename Char>
224 struct is_compiled_format<text<Char>> : std::true_type {};
225
226 template <typename Char>
227 constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos,
228 size_t size) {
229 return {{&s[pos], size}};
230 }
231
232 template <typename Char> struct code_unit {
233 Char value;
234 using char_type = Char;
235
236 template <typename OutputIt, typename... Args>
237 constexpr OutputIt format(OutputIt out, const Args&...) const {
238 return write<Char>(out, value);
239 }
240 };
241
242 // This ensures that the argument type is convertible to `const T&`.
243 template <typename T, int N, typename... Args>
244 constexpr const T& get_arg_checked(const Args&... args) {
245 const auto& arg = detail::get<N>(args...);
246 if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) {
247 return arg.value;
248 } else {
249 return arg;
250 }
251 }
252
253 template <typename Char>
254 struct is_compiled_format<code_unit<Char>> : std::true_type {};
255
256 // A replacement field that refers to argument N.
257 template <typename Char, typename T, int N> struct field {
258 using char_type = Char;
259
260 template <typename OutputIt, typename... Args>
261 constexpr OutputIt format(OutputIt out, const Args&... args) const {
262 return write<Char>(out, get_arg_checked<T, N>(args...));
263 }
264 };
265
266 template <typename Char, typename T, int N>
267 struct is_compiled_format<field<Char, T, N>> : std::true_type {};
268
269 // A replacement field that refers to argument with name.
270 template <typename Char> struct runtime_named_field {
271 using char_type = Char;
272 basic_string_view<Char> name;
273
274 template <typename OutputIt, typename T>
275 constexpr static bool try_format_argument(
276 OutputIt& out,
277 // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9
278 [[maybe_unused]] basic_string_view<Char> arg_name, const T& arg) {
279 if constexpr (is_named_arg<typename std::remove_cv<T>::type>::value) {
280 if (arg_name == arg.name) {
281 out = write<Char>(out, arg.value);
282 return true;
283 }
284 }
285 return false;
286 }
287
288 template <typename OutputIt, typename... Args>
289 constexpr OutputIt format(OutputIt out, const Args&... args) const {
290 bool found = (try_format_argument(out, name, args) || ...);
291 if (!found) {
292 FMT_THROW(format_error("argument with specified name is not found"));
293 }
294 return out;
295 }
296 };
297
298 template <typename Char>
299 struct is_compiled_format<runtime_named_field<Char>> : std::true_type {};
300
301 // A replacement field that refers to argument N and has format specifiers.
302 template <typename Char, typename T, int N> struct spec_field {
303 using char_type = Char;
304 formatter<T, Char> fmt;
305
306 template <typename OutputIt, typename... Args>
307 constexpr FMT_INLINE OutputIt format(OutputIt out,
308 const Args&... args) const {
309 const auto& vargs =
310 fmt::make_format_args<basic_format_context<OutputIt, Char>>(args...);
311 basic_format_context<OutputIt, Char> ctx(out, vargs);
312 return fmt.format(get_arg_checked<T, N>(args...), ctx);
313 }
314 };
315
316 template <typename Char, typename T, int N>
317 struct is_compiled_format<spec_field<Char, T, N>> : std::true_type {};
318
319 template <typename L, typename R> struct concat {
320 L lhs;
321 R rhs;
322 using char_type = typename L::char_type;
323
324 template <typename OutputIt, typename... Args>
325 constexpr OutputIt format(OutputIt out, const Args&... args) const {
326 out = lhs.format(out, args...);
327 return rhs.format(out, args...);
328 }
329 };
330
331 template <typename L, typename R>
332 struct is_compiled_format<concat<L, R>> : std::true_type {};
333
334 template <typename L, typename R>
335 constexpr concat<L, R> make_concat(L lhs, R rhs) {
336 return {lhs, rhs};
337 }
338
339 struct unknown_format {};
340
341 template <typename Char>
342 constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) {
343 for (size_t size = str.size(); pos != size; ++pos) {
344 if (str[pos] == '{' || str[pos] == '}') break;
345 }
346 return pos;
347 }
348
349 template <typename Args, size_t POS, int ID, typename S>
350 constexpr auto compile_format_string(S format_str);
351
352 template <typename Args, size_t POS, int ID, typename T, typename S>
353 constexpr auto parse_tail(T head, S format_str) {
354 if constexpr (POS !=
355 basic_string_view<typename S::char_type>(format_str).size()) {
356 constexpr auto tail = compile_format_string<Args, POS, ID>(format_str);
357 if constexpr (std::is_same<remove_cvref_t<decltype(tail)>,
358 unknown_format>())
359 return tail;
360 else
361 return make_concat(head, tail);
362 } else {
363 return head;
364 }
365 }
366
367 template <typename T, typename Char> struct parse_specs_result {
368 formatter<T, Char> fmt;
369 size_t end;
370 int next_arg_id;
371 };
372
373 constexpr int manual_indexing_id = -1;
374
375 template <typename T, typename Char>
376 constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str,
377 size_t pos, int next_arg_id) {
378 str.remove_prefix(pos);
379 auto ctx = basic_format_parse_context<Char>(str, {}, next_arg_id);
380 auto f = formatter<T, Char>();
381 auto end = f.parse(ctx);
382 return {f, pos + fmt::detail::to_unsigned(end - str.data()) + 1,
383 next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()};
384 }
385
386 template <typename Char> struct arg_id_handler {
387 arg_ref<Char> arg_id;
388
389 constexpr int operator()() {
390 FMT_ASSERT(false, "handler cannot be used with automatic indexing");
391 return 0;
392 }
393 constexpr int operator()(int id) {
394 arg_id = arg_ref<Char>(id);
395 return 0;
396 }
397 constexpr int operator()(basic_string_view<Char> id) {
398 arg_id = arg_ref<Char>(id);
399 return 0;
400 }
401
402 constexpr void on_error(const char* message) {
403 FMT_THROW(format_error(message));
404 }
405 };
406
407 template <typename Char> struct parse_arg_id_result {
408 arg_ref<Char> arg_id;
409 const Char* arg_id_end;
410 };
411
412 template <int ID, typename Char>
413 constexpr auto parse_arg_id(const Char* begin, const Char* end) {
414 auto handler = arg_id_handler<Char>{arg_ref<Char>{}};
415 auto arg_id_end = parse_arg_id(begin, end, handler);
416 return parse_arg_id_result<Char>{handler.arg_id, arg_id_end};
417 }
418
419 template <typename T, typename Enable = void> struct field_type {
420 using type = remove_cvref_t<T>;
421 };
422
423 template <typename T>
424 struct field_type<T, enable_if_t<detail::is_named_arg<T>::value>> {
425 using type = remove_cvref_t<decltype(T::value)>;
426 };
427
428 template <typename T, typename Args, size_t END_POS, int ARG_INDEX, int NEXT_ID,
429 typename S>
430 constexpr auto parse_replacement_field_then_tail(S format_str) {
431 using char_type = typename S::char_type;
432 constexpr auto str = basic_string_view<char_type>(format_str);
433 constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type();
434 if constexpr (c == '}') {
435 return parse_tail<Args, END_POS + 1, NEXT_ID>(
436 field<char_type, typename field_type<T>::type, ARG_INDEX>(),
437 format_str);
438 } else if constexpr (c == ':') {
439 constexpr auto result = parse_specs<typename field_type<T>::type>(
440 str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID);
441 return parse_tail<Args, result.end, result.next_arg_id>(
442 spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
443 result.fmt},
444 format_str);
445 }
446 }
447
448 // Compiles a non-empty format string and returns the compiled representation
449 // or unknown_format() on unrecognized input.
450 template <typename Args, size_t POS, int ID, typename S>
451 constexpr auto compile_format_string(S format_str) {
452 using char_type = typename S::char_type;
453 constexpr auto str = basic_string_view<char_type>(format_str);
454 if constexpr (str[POS] == '{') {
455 if constexpr (POS + 1 == str.size())
456 FMT_THROW(format_error("unmatched '{' in format string"));
457 if constexpr (str[POS + 1] == '{') {
458 return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
459 } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') {
460 static_assert(ID != manual_indexing_id,
461 "cannot switch from manual to automatic argument indexing");
462 constexpr auto next_id =
463 ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
464 return parse_replacement_field_then_tail<get_type<ID, Args>, Args,
465 POS + 1, ID, next_id>(
466 format_str);
467 } else {
468 constexpr auto arg_id_result =
469 parse_arg_id<ID>(str.data() + POS + 1, str.data() + str.size());
470 constexpr auto arg_id_end_pos = arg_id_result.arg_id_end - str.data();
471 constexpr char_type c =
472 arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type();
473 static_assert(c == '}' || c == ':', "missing '}' in format string");
474 if constexpr (arg_id_result.arg_id.kind == arg_id_kind::index) {
475 static_assert(
476 ID == manual_indexing_id || ID == 0,
477 "cannot switch from automatic to manual argument indexing");
478 constexpr auto arg_index = arg_id_result.arg_id.val.index;
479 return parse_replacement_field_then_tail<get_type<arg_index, Args>,
480 Args, arg_id_end_pos,
481 arg_index, manual_indexing_id>(
482 format_str);
483 } else if constexpr (arg_id_result.arg_id.kind == arg_id_kind::name) {
484 constexpr auto arg_index =
485 get_arg_index_by_name(arg_id_result.arg_id.val.name, Args{});
486 if constexpr (arg_index != invalid_arg_index) {
487 constexpr auto next_id =
488 ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
489 return parse_replacement_field_then_tail<
490 decltype(get_type<arg_index, Args>::value), Args, arg_id_end_pos,
491 arg_index, next_id>(format_str);
492 } else {
493 if constexpr (c == '}') {
494 return parse_tail<Args, arg_id_end_pos + 1, ID>(
495 runtime_named_field<char_type>{arg_id_result.arg_id.val.name},
496 format_str);
497 } else if constexpr (c == ':') {
498 return unknown_format(); // no type info for specs parsing
499 }
500 }
501 }
502 }
503 } else if constexpr (str[POS] == '}') {
504 if constexpr (POS + 1 == str.size())
505 FMT_THROW(format_error("unmatched '}' in format string"));
506 return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
507 } else {
508 constexpr auto end = parse_text(str, POS + 1);
509 if constexpr (end - POS > 1) {
510 return parse_tail<Args, end, ID>(make_text(str, POS, end - POS),
511 format_str);
512 } else {
513 return parse_tail<Args, end, ID>(code_unit<char_type>{str[POS]},
514 format_str);
515 }
516 }
517 }
518
519 template <typename... Args, typename S,
520 FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
521 constexpr auto compile(S format_str) {
522 constexpr auto str = basic_string_view<typename S::char_type>(format_str);
523 if constexpr (str.size() == 0) {
524 return detail::make_text(str, 0, 0);
525 } else {
526 constexpr auto result =
527 detail::compile_format_string<detail::type_list<Args...>, 0, 0>(
528 format_str);
529 return result;
530 }
531 }
532 #endif // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
533 } // namespace detail
534
535 FMT_MODULE_EXPORT_BEGIN
536
537 #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
538
539 template <typename CompiledFormat, typename... Args,
540 typename Char = typename CompiledFormat::char_type,
541 FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
542 FMT_INLINE std::basic_string<Char> format(const CompiledFormat& cf,
543 const Args&... args) {
544 auto s = std::basic_string<Char>();
545 cf.format(std::back_inserter(s), args...);
546 return s;
547 }
548
549 template <typename OutputIt, typename CompiledFormat, typename... Args,
550 FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
551 constexpr FMT_INLINE OutputIt format_to(OutputIt out, const CompiledFormat& cf,
552 const Args&... args) {
553 return cf.format(out, args...);
554 }
555
556 template <typename S, typename... Args,
557 FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
558 FMT_INLINE std::basic_string<typename S::char_type> format(const S&,
559 Args&&... args) {
560 if constexpr (std::is_same<typename S::char_type, char>::value) {
561 constexpr auto str = basic_string_view<typename S::char_type>(S());
562 if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') {
563 const auto& first = detail::first(args...);
564 if constexpr (detail::is_named_arg<
565 remove_cvref_t<decltype(first)>>::value) {
566 return fmt::to_string(first.value);
567 } else {
568 return fmt::to_string(first);
569 }
570 }
571 }
572 constexpr auto compiled = detail::compile<Args...>(S());
573 if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
574 detail::unknown_format>()) {
575 return format(static_cast<basic_string_view<typename S::char_type>>(S()),
576 std::forward<Args>(args)...);
577 } else {
578 return format(compiled, std::forward<Args>(args)...);
579 }
580 }
581
582 template <typename OutputIt, typename S, typename... Args,
583 FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
584 FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) {
585 constexpr auto compiled = detail::compile<Args...>(S());
586 if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
587 detail::unknown_format>()) {
588 return format_to(out,
589 static_cast<basic_string_view<typename S::char_type>>(S()),
590 std::forward<Args>(args)...);
591 } else {
592 return format_to(out, compiled, std::forward<Args>(args)...);
593 }
594 }
595 #endif
596
597 template <typename OutputIt, typename S, typename... Args,
598 FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
599 format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n,
600 const S& format_str, Args&&... args) {
601 auto it = format_to(detail::truncating_iterator<OutputIt>(out, n), format_str,
602 std::forward<Args>(args)...);
603 return {it.base(), it.count()};
604 }
605
606 template <typename S, typename... Args,
607 FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
608 size_t formatted_size(const S& format_str, const Args&... args) {
609 return format_to(detail::counting_iterator(), format_str, args...).count();
610 }
611
612 template <typename S, typename... Args,
613 FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
614 void print(std::FILE* f, const S& format_str, const Args&... args) {
615 memory_buffer buffer;
616 format_to(std::back_inserter(buffer), format_str, args...);
617 detail::print(f, {buffer.data(), buffer.size()});
618 }
619
620 template <typename S, typename... Args,
621 FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
622 void print(const S& format_str, const Args&... args) {
623 print(stdout, format_str, args...);
624 }
625
626 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
627 inline namespace literals {
628 template <detail_exported::fixed_string Str>
629 constexpr detail::udl_compiled_string<
630 remove_cvref_t<decltype(Str.data[0])>,
631 sizeof(Str.data) / sizeof(decltype(Str.data[0])), Str>
632 operator""_cf() {
633 return {};
634 }
635 } // namespace literals
636 #endif
637
638 FMT_MODULE_EXPORT_END
639 FMT_END_NAMESPACE
640
641 #endif // FMT_COMPILE_H_
+0
-3236
source/misc/embedded_libs/fmt-8.1.1/include/fmt/core.h less more
0 // Formatting library for C++ - the core API for char/UTF-8
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_CORE_H_
8 #define FMT_CORE_H_
9
10 #include <cstddef> // std::byte
11 #include <cstdio> // std::FILE
12 #include <cstring>
13 #include <iterator>
14 #include <limits>
15 #include <string>
16 #include <type_traits>
17
18 // The fmt library version in the form major * 10000 + minor * 100 + patch.
19 #define FMT_VERSION 80101
20
21 #if defined(__clang__) && !defined(__ibmxl__)
22 # define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
23 #else
24 # define FMT_CLANG_VERSION 0
25 #endif
26
27 #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && \
28 !defined(__NVCOMPILER)
29 # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
30 #else
31 # define FMT_GCC_VERSION 0
32 #endif
33
34 #ifndef FMT_GCC_PRAGMA
35 // Workaround _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884.
36 # if FMT_GCC_VERSION >= 504
37 # define FMT_GCC_PRAGMA(arg) _Pragma(arg)
38 # else
39 # define FMT_GCC_PRAGMA(arg)
40 # endif
41 #endif
42
43 #ifdef __ICL
44 # define FMT_ICC_VERSION __ICL
45 #elif defined(__INTEL_COMPILER)
46 # define FMT_ICC_VERSION __INTEL_COMPILER
47 #else
48 # define FMT_ICC_VERSION 0
49 #endif
50
51 #ifdef __NVCC__
52 # define FMT_NVCC __NVCC__
53 #else
54 # define FMT_NVCC 0
55 #endif
56
57 #ifdef _MSC_VER
58 # define FMT_MSC_VER _MSC_VER
59 # define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
60 #else
61 # define FMT_MSC_VER 0
62 # define FMT_MSC_WARNING(...)
63 #endif
64
65 #ifdef __has_feature
66 # define FMT_HAS_FEATURE(x) __has_feature(x)
67 #else
68 # define FMT_HAS_FEATURE(x) 0
69 #endif
70
71 #if defined(__has_include) && \
72 (!defined(__INTELLISENSE__) || FMT_MSC_VER > 1900) && \
73 (!FMT_ICC_VERSION || FMT_ICC_VERSION >= 1600)
74 # define FMT_HAS_INCLUDE(x) __has_include(x)
75 #else
76 # define FMT_HAS_INCLUDE(x) 0
77 #endif
78
79 #ifdef __has_cpp_attribute
80 # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
81 #else
82 # define FMT_HAS_CPP_ATTRIBUTE(x) 0
83 #endif
84
85 #ifdef _MSVC_LANG
86 # define FMT_CPLUSPLUS _MSVC_LANG
87 #else
88 # define FMT_CPLUSPLUS __cplusplus
89 #endif
90
91 #define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
92 (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
93
94 #define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
95 (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
96
97 // Check if relaxed C++14 constexpr is supported.
98 // GCC doesn't allow throw in constexpr until version 6 (bug 67371).
99 #ifndef FMT_USE_CONSTEXPR
100 # define FMT_USE_CONSTEXPR \
101 (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1912 || \
102 (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) && \
103 !FMT_NVCC && !FMT_ICC_VERSION
104 #endif
105 #if FMT_USE_CONSTEXPR
106 # define FMT_CONSTEXPR constexpr
107 # define FMT_CONSTEXPR_DECL constexpr
108 #else
109 # define FMT_CONSTEXPR
110 # define FMT_CONSTEXPR_DECL
111 #endif
112
113 #if ((__cplusplus >= 202002L) && \
114 (!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE > 9)) || \
115 (__cplusplus >= 201709L && FMT_GCC_VERSION >= 1002)
116 # define FMT_CONSTEXPR20 constexpr
117 #else
118 # define FMT_CONSTEXPR20
119 #endif
120
121 // Check if constexpr std::char_traits<>::compare,length is supported.
122 #if defined(__GLIBCXX__)
123 # if __cplusplus >= 201703L && defined(_GLIBCXX_RELEASE) && \
124 _GLIBCXX_RELEASE >= 7 // GCC 7+ libstdc++ has _GLIBCXX_RELEASE.
125 # define FMT_CONSTEXPR_CHAR_TRAITS constexpr
126 # endif
127 #elif defined(_LIBCPP_VERSION) && __cplusplus >= 201703L && \
128 _LIBCPP_VERSION >= 4000
129 # define FMT_CONSTEXPR_CHAR_TRAITS constexpr
130 #elif FMT_MSC_VER >= 1914 && _MSVC_LANG >= 201703L
131 # define FMT_CONSTEXPR_CHAR_TRAITS constexpr
132 #endif
133 #ifndef FMT_CONSTEXPR_CHAR_TRAITS
134 # define FMT_CONSTEXPR_CHAR_TRAITS
135 #endif
136
137 // Check if exceptions are disabled.
138 #ifndef FMT_EXCEPTIONS
139 # if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
140 FMT_MSC_VER && !_HAS_EXCEPTIONS
141 # define FMT_EXCEPTIONS 0
142 # else
143 # define FMT_EXCEPTIONS 1
144 # endif
145 #endif
146
147 // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
148 #ifndef FMT_USE_NOEXCEPT
149 # define FMT_USE_NOEXCEPT 0
150 #endif
151
152 #if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
153 FMT_GCC_VERSION >= 408 || FMT_MSC_VER >= 1900
154 # define FMT_DETECTED_NOEXCEPT noexcept
155 # define FMT_HAS_CXX11_NOEXCEPT 1
156 #else
157 # define FMT_DETECTED_NOEXCEPT throw()
158 # define FMT_HAS_CXX11_NOEXCEPT 0
159 #endif
160
161 #ifndef FMT_NOEXCEPT
162 # if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
163 # define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
164 # else
165 # define FMT_NOEXCEPT
166 # endif
167 #endif
168
169 // [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code
170 // warnings.
171 #if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \
172 !FMT_NVCC
173 # define FMT_NORETURN [[noreturn]]
174 #else
175 # define FMT_NORETURN
176 #endif
177
178 #if __cplusplus == 201103L || __cplusplus == 201402L
179 # if defined(__INTEL_COMPILER) || defined(__PGI)
180 # define FMT_FALLTHROUGH
181 # elif defined(__clang__)
182 # define FMT_FALLTHROUGH [[clang::fallthrough]]
183 # elif FMT_GCC_VERSION >= 700 && \
184 (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
185 # define FMT_FALLTHROUGH [[gnu::fallthrough]]
186 # else
187 # define FMT_FALLTHROUGH
188 # endif
189 #elif FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
190 # define FMT_FALLTHROUGH [[fallthrough]]
191 #else
192 # define FMT_FALLTHROUGH
193 #endif
194
195 #ifndef FMT_NODISCARD
196 # if FMT_HAS_CPP17_ATTRIBUTE(nodiscard)
197 # define FMT_NODISCARD [[nodiscard]]
198 # else
199 # define FMT_NODISCARD
200 # endif
201 #endif
202
203 #ifndef FMT_USE_FLOAT
204 # define FMT_USE_FLOAT 1
205 #endif
206 #ifndef FMT_USE_DOUBLE
207 # define FMT_USE_DOUBLE 1
208 #endif
209 #ifndef FMT_USE_LONG_DOUBLE
210 # define FMT_USE_LONG_DOUBLE 1
211 #endif
212
213 #ifndef FMT_INLINE
214 # if FMT_GCC_VERSION || FMT_CLANG_VERSION
215 # define FMT_INLINE inline __attribute__((always_inline))
216 # else
217 # define FMT_INLINE inline
218 # endif
219 #endif
220
221 #ifndef FMT_DEPRECATED
222 # if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900
223 # define FMT_DEPRECATED [[deprecated]]
224 # else
225 # if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
226 # define FMT_DEPRECATED __attribute__((deprecated))
227 # elif FMT_MSC_VER
228 # define FMT_DEPRECATED __declspec(deprecated)
229 # else
230 # define FMT_DEPRECATED /* deprecated */
231 # endif
232 # endif
233 #endif
234
235 #ifndef FMT_BEGIN_NAMESPACE
236 # define FMT_BEGIN_NAMESPACE \
237 namespace fmt { \
238 inline namespace v8 {
239 # define FMT_END_NAMESPACE \
240 } \
241 }
242 #endif
243
244 #ifndef FMT_MODULE_EXPORT
245 # define FMT_MODULE_EXPORT
246 # define FMT_MODULE_EXPORT_BEGIN
247 # define FMT_MODULE_EXPORT_END
248 # define FMT_BEGIN_DETAIL_NAMESPACE namespace detail {
249 # define FMT_END_DETAIL_NAMESPACE }
250 #endif
251
252 #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
253 # define FMT_CLASS_API FMT_MSC_WARNING(suppress : 4275)
254 # ifdef FMT_EXPORT
255 # define FMT_API __declspec(dllexport)
256 # elif defined(FMT_SHARED)
257 # define FMT_API __declspec(dllimport)
258 # endif
259 #else
260 # define FMT_CLASS_API
261 # if defined(FMT_EXPORT) || defined(FMT_SHARED)
262 # if defined(__GNUC__) || defined(__clang__)
263 # define FMT_API __attribute__((visibility("default")))
264 # endif
265 # endif
266 #endif
267 #ifndef FMT_API
268 # define FMT_API
269 #endif
270
271 // libc++ supports string_view in pre-c++17.
272 #if (FMT_HAS_INCLUDE(<string_view>) && \
273 (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \
274 (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
275 # include <string_view>
276 # define FMT_USE_STRING_VIEW
277 #elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L
278 # include <experimental/string_view>
279 # define FMT_USE_EXPERIMENTAL_STRING_VIEW
280 #endif
281
282 #ifndef FMT_UNICODE
283 # define FMT_UNICODE !FMT_MSC_VER
284 #endif
285
286 #ifndef FMT_CONSTEVAL
287 # if ((FMT_GCC_VERSION >= 1000 || FMT_CLANG_VERSION >= 1101) && \
288 __cplusplus > 201703L && !defined(__apple_build_version__)) || \
289 (defined(__cpp_consteval) && \
290 (!FMT_MSC_VER || _MSC_FULL_VER >= 193030704))
291 // consteval is broken in MSVC before VS2022 and Apple clang 13.
292 # define FMT_CONSTEVAL consteval
293 # define FMT_HAS_CONSTEVAL
294 # else
295 # define FMT_CONSTEVAL
296 # endif
297 #endif
298
299 #ifndef FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
300 # if defined(__cpp_nontype_template_args) && \
301 ((FMT_GCC_VERSION >= 903 && __cplusplus >= 201709L) || \
302 __cpp_nontype_template_args >= 201911L)
303 # define FMT_USE_NONTYPE_TEMPLATE_PARAMETERS 1
304 # else
305 # define FMT_USE_NONTYPE_TEMPLATE_PARAMETERS 0
306 # endif
307 #endif
308
309 // Enable minimal optimizations for more compact code in debug mode.
310 FMT_GCC_PRAGMA("GCC push_options")
311 #ifndef __OPTIMIZE__
312 FMT_GCC_PRAGMA("GCC optimize(\"Og\")")
313 #endif
314
315 FMT_BEGIN_NAMESPACE
316 FMT_MODULE_EXPORT_BEGIN
317
318 // Implementations of enable_if_t and other metafunctions for older systems.
319 template <bool B, typename T = void>
320 using enable_if_t = typename std::enable_if<B, T>::type;
321 template <bool B, typename T, typename F>
322 using conditional_t = typename std::conditional<B, T, F>::type;
323 template <bool B> using bool_constant = std::integral_constant<bool, B>;
324 template <typename T>
325 using remove_reference_t = typename std::remove_reference<T>::type;
326 template <typename T>
327 using remove_const_t = typename std::remove_const<T>::type;
328 template <typename T>
329 using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
330 template <typename T> struct type_identity { using type = T; };
331 template <typename T> using type_identity_t = typename type_identity<T>::type;
332
333 struct monostate {
334 constexpr monostate() {}
335 };
336
337 // An enable_if helper to be used in template parameters which results in much
338 // shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
339 // to workaround a bug in MSVC 2019 (see #1140 and #1186).
340 #ifdef FMT_DOC
341 # define FMT_ENABLE_IF(...)
342 #else
343 # define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0
344 #endif
345
346 FMT_BEGIN_DETAIL_NAMESPACE
347
348 // Suppress "unused variable" warnings with the method described in
349 // https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
350 // (void)var does not work on many Intel compilers.
351 template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
352
353 constexpr FMT_INLINE auto is_constant_evaluated(bool default_value = false)
354 FMT_NOEXCEPT -> bool {
355 #ifdef __cpp_lib_is_constant_evaluated
356 ignore_unused(default_value);
357 return std::is_constant_evaluated();
358 #else
359 return default_value;
360 #endif
361 }
362
363 // A function to suppress "conditional expression is constant" warnings.
364 template <typename T> constexpr FMT_INLINE auto const_check(T value) -> T {
365 return value;
366 }
367
368 FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
369 const char* message);
370
371 #ifndef FMT_ASSERT
372 # ifdef NDEBUG
373 // FMT_ASSERT is not empty to avoid -Werror=empty-body.
374 # define FMT_ASSERT(condition, message) \
375 ::fmt::detail::ignore_unused((condition), (message))
376 # else
377 # define FMT_ASSERT(condition, message) \
378 ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
379 ? (void)0 \
380 : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
381 # endif
382 #endif
383
384 #ifdef __cpp_lib_byte
385 using byte = std::byte;
386 #else
387 enum class byte : unsigned char {};
388 #endif
389
390 #if defined(FMT_USE_STRING_VIEW)
391 template <typename Char> using std_string_view = std::basic_string_view<Char>;
392 #elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
393 template <typename Char>
394 using std_string_view = std::experimental::basic_string_view<Char>;
395 #else
396 template <typename T> struct std_string_view {};
397 #endif
398
399 #ifdef FMT_USE_INT128
400 // Do nothing.
401 #elif defined(__SIZEOF_INT128__) && !FMT_NVCC && \
402 !(FMT_CLANG_VERSION && FMT_MSC_VER)
403 # define FMT_USE_INT128 1
404 using int128_t = __int128_t;
405 using uint128_t = __uint128_t;
406 template <typename T> inline auto convert_for_visit(T value) -> T {
407 return value;
408 }
409 #else
410 # define FMT_USE_INT128 0
411 #endif
412 #if !FMT_USE_INT128
413 enum class int128_t {};
414 enum class uint128_t {};
415 // Reduce template instantiations.
416 template <typename T> inline auto convert_for_visit(T) -> monostate {
417 return {};
418 }
419 #endif
420
421 // Casts a nonnegative integer to unsigned.
422 template <typename Int>
423 FMT_CONSTEXPR auto to_unsigned(Int value) ->
424 typename std::make_unsigned<Int>::type {
425 FMT_ASSERT(value >= 0, "negative value");
426 return static_cast<typename std::make_unsigned<Int>::type>(value);
427 }
428
429 FMT_MSC_WARNING(suppress : 4566) constexpr unsigned char micro[] = "\u00B5";
430
431 constexpr auto is_utf8() -> bool {
432 // Avoid buggy sign extensions in MSVC's constant evaluation mode.
433 // https://developercommunity.visualstudio.com/t/C-difference-in-behavior-for-unsigned/1233612
434 using uchar = unsigned char;
435 return FMT_UNICODE || (sizeof(micro) == 3 && uchar(micro[0]) == 0xC2 &&
436 uchar(micro[1]) == 0xB5);
437 }
438 FMT_END_DETAIL_NAMESPACE
439
440 /**
441 An implementation of ``std::basic_string_view`` for pre-C++17. It provides a
442 subset of the API. ``fmt::basic_string_view`` is used for format strings even
443 if ``std::string_view`` is available to prevent issues when a library is
444 compiled with a different ``-std`` option than the client code (which is not
445 recommended).
446 */
447 template <typename Char> class basic_string_view {
448 private:
449 const Char* data_;
450 size_t size_;
451
452 public:
453 using value_type = Char;
454 using iterator = const Char*;
455
456 constexpr basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {}
457
458 /** Constructs a string reference object from a C string and a size. */
459 constexpr basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT
460 : data_(s),
461 size_(count) {}
462
463 /**
464 \rst
465 Constructs a string reference object from a C string computing
466 the size with ``std::char_traits<Char>::length``.
467 \endrst
468 */
469 FMT_CONSTEXPR_CHAR_TRAITS
470 FMT_INLINE
471 basic_string_view(const Char* s)
472 : data_(s),
473 size_(detail::const_check(std::is_same<Char, char>::value &&
474 !detail::is_constant_evaluated(true))
475 ? std::strlen(reinterpret_cast<const char*>(s))
476 : std::char_traits<Char>::length(s)) {}
477
478 /** Constructs a string reference from a ``std::basic_string`` object. */
479 template <typename Traits, typename Alloc>
480 FMT_CONSTEXPR basic_string_view(
481 const std::basic_string<Char, Traits, Alloc>& s) FMT_NOEXCEPT
482 : data_(s.data()),
483 size_(s.size()) {}
484
485 template <typename S, FMT_ENABLE_IF(std::is_same<
486 S, detail::std_string_view<Char>>::value)>
487 FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()),
488 size_(s.size()) {}
489
490 /** Returns a pointer to the string data. */
491 constexpr auto data() const FMT_NOEXCEPT -> const Char* { return data_; }
492
493 /** Returns the string size. */
494 constexpr auto size() const FMT_NOEXCEPT -> size_t { return size_; }
495
496 constexpr auto begin() const FMT_NOEXCEPT -> iterator { return data_; }
497 constexpr auto end() const FMT_NOEXCEPT -> iterator { return data_ + size_; }
498
499 constexpr auto operator[](size_t pos) const FMT_NOEXCEPT -> const Char& {
500 return data_[pos];
501 }
502
503 FMT_CONSTEXPR void remove_prefix(size_t n) FMT_NOEXCEPT {
504 data_ += n;
505 size_ -= n;
506 }
507
508 // Lexicographically compare this string reference to other.
509 FMT_CONSTEXPR_CHAR_TRAITS auto compare(basic_string_view other) const -> int {
510 size_t str_size = size_ < other.size_ ? size_ : other.size_;
511 int result = std::char_traits<Char>::compare(data_, other.data_, str_size);
512 if (result == 0)
513 result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
514 return result;
515 }
516
517 FMT_CONSTEXPR_CHAR_TRAITS friend auto operator==(basic_string_view lhs,
518 basic_string_view rhs)
519 -> bool {
520 return lhs.compare(rhs) == 0;
521 }
522 friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {
523 return lhs.compare(rhs) != 0;
524 }
525 friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {
526 return lhs.compare(rhs) < 0;
527 }
528 friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {
529 return lhs.compare(rhs) <= 0;
530 }
531 friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {
532 return lhs.compare(rhs) > 0;
533 }
534 friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {
535 return lhs.compare(rhs) >= 0;
536 }
537 };
538
539 using string_view = basic_string_view<char>;
540
541 /** Specifies if ``T`` is a character type. Can be specialized by users. */
542 template <typename T> struct is_char : std::false_type {};
543 template <> struct is_char<char> : std::true_type {};
544
545 // Returns a string view of `s`.
546 template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
547 FMT_INLINE auto to_string_view(const Char* s) -> basic_string_view<Char> {
548 return s;
549 }
550 template <typename Char, typename Traits, typename Alloc>
551 inline auto to_string_view(const std::basic_string<Char, Traits, Alloc>& s)
552 -> basic_string_view<Char> {
553 return s;
554 }
555 template <typename Char>
556 constexpr auto to_string_view(basic_string_view<Char> s)
557 -> basic_string_view<Char> {
558 return s;
559 }
560 template <typename Char,
561 FMT_ENABLE_IF(!std::is_empty<detail::std_string_view<Char>>::value)>
562 inline auto to_string_view(detail::std_string_view<Char> s)
563 -> basic_string_view<Char> {
564 return s;
565 }
566
567 // A base class for compile-time strings. It is defined in the fmt namespace to
568 // make formatting functions visible via ADL, e.g. format(FMT_STRING("{}"), 42).
569 struct compile_string {};
570
571 template <typename S>
572 struct is_compile_string : std::is_base_of<compile_string, S> {};
573
574 template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
575 constexpr auto to_string_view(const S& s)
576 -> basic_string_view<typename S::char_type> {
577 return basic_string_view<typename S::char_type>(s);
578 }
579
580 FMT_BEGIN_DETAIL_NAMESPACE
581
582 void to_string_view(...);
583 using fmt::to_string_view;
584
585 // Specifies whether S is a string type convertible to fmt::basic_string_view.
586 // It should be a constexpr function but MSVC 2017 fails to compile it in
587 // enable_if and MSVC 2015 fails to compile it as an alias template.
588 template <typename S>
589 struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
590 };
591
592 template <typename S, typename = void> struct char_t_impl {};
593 template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
594 using result = decltype(to_string_view(std::declval<S>()));
595 using type = typename result::value_type;
596 };
597
598 // Reports a compile-time error if S is not a valid format string.
599 template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
600 FMT_INLINE void check_format_string(const S&) {
601 #ifdef FMT_ENFORCE_COMPILE_STRING
602 static_assert(is_compile_string<S>::value,
603 "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
604 "FMT_STRING.");
605 #endif
606 }
607 template <typename..., typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
608 void check_format_string(S);
609
610 FMT_NORETURN FMT_API void throw_format_error(const char* message);
611
612 struct error_handler {
613 constexpr error_handler() = default;
614 constexpr error_handler(const error_handler&) = default;
615
616 // This function is intentionally not constexpr to give a compile-time error.
617 FMT_NORETURN FMT_API void on_error(const char* message);
618 };
619 FMT_END_DETAIL_NAMESPACE
620
621 /** String's character type. */
622 template <typename S> using char_t = typename detail::char_t_impl<S>::type;
623
624 /**
625 \rst
626 Parsing context consisting of a format string range being parsed and an
627 argument counter for automatic indexing.
628 You can use the ``format_parse_context`` type alias for ``char`` instead.
629 \endrst
630 */
631 template <typename Char, typename ErrorHandler = detail::error_handler>
632 class basic_format_parse_context : private ErrorHandler {
633 private:
634 basic_string_view<Char> format_str_;
635 int next_arg_id_;
636
637 public:
638 using char_type = Char;
639 using iterator = typename basic_string_view<Char>::iterator;
640
641 explicit constexpr basic_format_parse_context(
642 basic_string_view<Char> format_str, ErrorHandler eh = {},
643 int next_arg_id = 0)
644 : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {}
645
646 /**
647 Returns an iterator to the beginning of the format string range being
648 parsed.
649 */
650 constexpr auto begin() const FMT_NOEXCEPT -> iterator {
651 return format_str_.begin();
652 }
653
654 /**
655 Returns an iterator past the end of the format string range being parsed.
656 */
657 constexpr auto end() const FMT_NOEXCEPT -> iterator {
658 return format_str_.end();
659 }
660
661 /** Advances the begin iterator to ``it``. */
662 FMT_CONSTEXPR void advance_to(iterator it) {
663 format_str_.remove_prefix(detail::to_unsigned(it - begin()));
664 }
665
666 /**
667 Reports an error if using the manual argument indexing; otherwise returns
668 the next argument index and switches to the automatic indexing.
669 */
670 FMT_CONSTEXPR auto next_arg_id() -> int {
671 // Don't check if the argument id is valid to avoid overhead and because it
672 // will be checked during formatting anyway.
673 if (next_arg_id_ >= 0) return next_arg_id_++;
674 on_error("cannot switch from manual to automatic argument indexing");
675 return 0;
676 }
677
678 /**
679 Reports an error if using the automatic argument indexing; otherwise
680 switches to the manual indexing.
681 */
682 FMT_CONSTEXPR void check_arg_id(int) {
683 if (next_arg_id_ > 0)
684 on_error("cannot switch from automatic to manual argument indexing");
685 else
686 next_arg_id_ = -1;
687 }
688
689 FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
690
691 FMT_CONSTEXPR void on_error(const char* message) {
692 ErrorHandler::on_error(message);
693 }
694
695 constexpr auto error_handler() const -> ErrorHandler { return *this; }
696 };
697
698 using format_parse_context = basic_format_parse_context<char>;
699
700 template <typename Context> class basic_format_arg;
701 template <typename Context> class basic_format_args;
702 template <typename Context> class dynamic_format_arg_store;
703
704 // A formatter for objects of type T.
705 template <typename T, typename Char = char, typename Enable = void>
706 struct formatter {
707 // A deleted default constructor indicates a disabled formatter.
708 formatter() = delete;
709 };
710
711 // Specifies if T has an enabled formatter specialization. A type can be
712 // formattable even if it doesn't have a formatter e.g. via a conversion.
713 template <typename T, typename Context>
714 using has_formatter =
715 std::is_constructible<typename Context::template formatter_type<T>>;
716
717 // Checks whether T is a container with contiguous storage.
718 template <typename T> struct is_contiguous : std::false_type {};
719 template <typename Char>
720 struct is_contiguous<std::basic_string<Char>> : std::true_type {};
721
722 class appender;
723
724 FMT_BEGIN_DETAIL_NAMESPACE
725
726 template <typename Context, typename T>
727 constexpr auto has_const_formatter_impl(T*)
728 -> decltype(typename Context::template formatter_type<T>().format(
729 std::declval<const T&>(), std::declval<Context&>()),
730 true) {
731 return true;
732 }
733 template <typename Context>
734 constexpr auto has_const_formatter_impl(...) -> bool {
735 return false;
736 }
737 template <typename T, typename Context>
738 constexpr auto has_const_formatter() -> bool {
739 return has_const_formatter_impl<Context>(static_cast<T*>(nullptr));
740 }
741
742 // Extracts a reference to the container from back_insert_iterator.
743 template <typename Container>
744 inline auto get_container(std::back_insert_iterator<Container> it)
745 -> Container& {
746 using bi_iterator = std::back_insert_iterator<Container>;
747 struct accessor : bi_iterator {
748 accessor(bi_iterator iter) : bi_iterator(iter) {}
749 using bi_iterator::container;
750 };
751 return *accessor(it).container;
752 }
753
754 template <typename Char, typename InputIt, typename OutputIt>
755 FMT_CONSTEXPR auto copy_str(InputIt begin, InputIt end, OutputIt out)
756 -> OutputIt {
757 while (begin != end) *out++ = static_cast<Char>(*begin++);
758 return out;
759 }
760
761 template <typename Char, typename T, typename U,
762 FMT_ENABLE_IF(
763 std::is_same<remove_const_t<T>, U>::value&& is_char<U>::value)>
764 FMT_CONSTEXPR auto copy_str(T* begin, T* end, U* out) -> U* {
765 if (is_constant_evaluated()) return copy_str<Char, T*, U*>(begin, end, out);
766 auto size = to_unsigned(end - begin);
767 memcpy(out, begin, size * sizeof(U));
768 return out + size;
769 }
770
771 /**
772 \rst
773 A contiguous memory buffer with an optional growing ability. It is an internal
774 class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`.
775 \endrst
776 */
777 template <typename T> class buffer {
778 private:
779 T* ptr_;
780 size_t size_;
781 size_t capacity_;
782
783 protected:
784 // Don't initialize ptr_ since it is not accessed to save a few cycles.
785 FMT_MSC_WARNING(suppress : 26495)
786 buffer(size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {}
787
788 FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0,
789 size_t cap = 0) FMT_NOEXCEPT : ptr_(p),
790 size_(sz),
791 capacity_(cap) {}
792
793 FMT_CONSTEXPR20 ~buffer() = default;
794 buffer(buffer&&) = default;
795
796 /** Sets the buffer data and capacity. */
797 FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) FMT_NOEXCEPT {
798 ptr_ = buf_data;
799 capacity_ = buf_capacity;
800 }
801
802 /** Increases the buffer capacity to hold at least *capacity* elements. */
803 virtual FMT_CONSTEXPR20 void grow(size_t capacity) = 0;
804
805 public:
806 using value_type = T;
807 using const_reference = const T&;
808
809 buffer(const buffer&) = delete;
810 void operator=(const buffer&) = delete;
811
812 auto begin() FMT_NOEXCEPT -> T* { return ptr_; }
813 auto end() FMT_NOEXCEPT -> T* { return ptr_ + size_; }
814
815 auto begin() const FMT_NOEXCEPT -> const T* { return ptr_; }
816 auto end() const FMT_NOEXCEPT -> const T* { return ptr_ + size_; }
817
818 /** Returns the size of this buffer. */
819 constexpr auto size() const FMT_NOEXCEPT -> size_t { return size_; }
820
821 /** Returns the capacity of this buffer. */
822 constexpr auto capacity() const FMT_NOEXCEPT -> size_t { return capacity_; }
823
824 /** Returns a pointer to the buffer data. */
825 FMT_CONSTEXPR auto data() FMT_NOEXCEPT -> T* { return ptr_; }
826
827 /** Returns a pointer to the buffer data. */
828 FMT_CONSTEXPR auto data() const FMT_NOEXCEPT -> const T* { return ptr_; }
829
830 /** Clears this buffer. */
831 void clear() { size_ = 0; }
832
833 // Tries resizing the buffer to contain *count* elements. If T is a POD type
834 // the new elements may not be initialized.
835 FMT_CONSTEXPR20 void try_resize(size_t count) {
836 try_reserve(count);
837 size_ = count <= capacity_ ? count : capacity_;
838 }
839
840 // Tries increasing the buffer capacity to *new_capacity*. It can increase the
841 // capacity by a smaller amount than requested but guarantees there is space
842 // for at least one additional element either by increasing the capacity or by
843 // flushing the buffer if it is full.
844 FMT_CONSTEXPR20 void try_reserve(size_t new_capacity) {
845 if (new_capacity > capacity_) grow(new_capacity);
846 }
847
848 FMT_CONSTEXPR20 void push_back(const T& value) {
849 try_reserve(size_ + 1);
850 ptr_[size_++] = value;
851 }
852
853 /** Appends data to the end of the buffer. */
854 template <typename U> void append(const U* begin, const U* end);
855
856 template <typename I> FMT_CONSTEXPR auto operator[](I index) -> T& {
857 return ptr_[index];
858 }
859 template <typename I>
860 FMT_CONSTEXPR auto operator[](I index) const -> const T& {
861 return ptr_[index];
862 }
863 };
864
865 struct buffer_traits {
866 explicit buffer_traits(size_t) {}
867 auto count() const -> size_t { return 0; }
868 auto limit(size_t size) -> size_t { return size; }
869 };
870
871 class fixed_buffer_traits {
872 private:
873 size_t count_ = 0;
874 size_t limit_;
875
876 public:
877 explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
878 auto count() const -> size_t { return count_; }
879 auto limit(size_t size) -> size_t {
880 size_t n = limit_ > count_ ? limit_ - count_ : 0;
881 count_ += size;
882 return size < n ? size : n;
883 }
884 };
885
886 // A buffer that writes to an output iterator when flushed.
887 template <typename OutputIt, typename T, typename Traits = buffer_traits>
888 class iterator_buffer final : public Traits, public buffer<T> {
889 private:
890 OutputIt out_;
891 enum { buffer_size = 256 };
892 T data_[buffer_size];
893
894 protected:
895 FMT_CONSTEXPR20 void grow(size_t) override {
896 if (this->size() == buffer_size) flush();
897 }
898
899 void flush() {
900 auto size = this->size();
901 this->clear();
902 out_ = copy_str<T>(data_, data_ + this->limit(size), out_);
903 }
904
905 public:
906 explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
907 : Traits(n), buffer<T>(data_, 0, buffer_size), out_(out) {}
908 iterator_buffer(iterator_buffer&& other)
909 : Traits(other), buffer<T>(data_, 0, buffer_size), out_(other.out_) {}
910 ~iterator_buffer() { flush(); }
911
912 auto out() -> OutputIt {
913 flush();
914 return out_;
915 }
916 auto count() const -> size_t { return Traits::count() + this->size(); }
917 };
918
919 template <typename T>
920 class iterator_buffer<T*, T, fixed_buffer_traits> final
921 : public fixed_buffer_traits,
922 public buffer<T> {
923 private:
924 T* out_;
925 enum { buffer_size = 256 };
926 T data_[buffer_size];
927
928 protected:
929 FMT_CONSTEXPR20 void grow(size_t) override {
930 if (this->size() == this->capacity()) flush();
931 }
932
933 void flush() {
934 size_t n = this->limit(this->size());
935 if (this->data() == out_) {
936 out_ += n;
937 this->set(data_, buffer_size);
938 }
939 this->clear();
940 }
941
942 public:
943 explicit iterator_buffer(T* out, size_t n = buffer_size)
944 : fixed_buffer_traits(n), buffer<T>(out, 0, n), out_(out) {}
945 iterator_buffer(iterator_buffer&& other)
946 : fixed_buffer_traits(other),
947 buffer<T>(std::move(other)),
948 out_(other.out_) {
949 if (this->data() != out_) {
950 this->set(data_, buffer_size);
951 this->clear();
952 }
953 }
954 ~iterator_buffer() { flush(); }
955
956 auto out() -> T* {
957 flush();
958 return out_;
959 }
960 auto count() const -> size_t {
961 return fixed_buffer_traits::count() + this->size();
962 }
963 };
964
965 template <typename T> class iterator_buffer<T*, T> final : public buffer<T> {
966 protected:
967 FMT_CONSTEXPR20 void grow(size_t) override {}
968
969 public:
970 explicit iterator_buffer(T* out, size_t = 0) : buffer<T>(out, 0, ~size_t()) {}
971
972 auto out() -> T* { return &*this->end(); }
973 };
974
975 // A buffer that writes to a container with the contiguous storage.
976 template <typename Container>
977 class iterator_buffer<std::back_insert_iterator<Container>,
978 enable_if_t<is_contiguous<Container>::value,
979 typename Container::value_type>>
980 final : public buffer<typename Container::value_type> {
981 private:
982 Container& container_;
983
984 protected:
985 FMT_CONSTEXPR20 void grow(size_t capacity) override {
986 container_.resize(capacity);
987 this->set(&container_[0], capacity);
988 }
989
990 public:
991 explicit iterator_buffer(Container& c)
992 : buffer<typename Container::value_type>(c.size()), container_(c) {}
993 explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0)
994 : iterator_buffer(get_container(out)) {}
995 auto out() -> std::back_insert_iterator<Container> {
996 return std::back_inserter(container_);
997 }
998 };
999
1000 // A buffer that counts the number of code units written discarding the output.
1001 template <typename T = char> class counting_buffer final : public buffer<T> {
1002 private:
1003 enum { buffer_size = 256 };
1004 T data_[buffer_size];
1005 size_t count_ = 0;
1006
1007 protected:
1008 FMT_CONSTEXPR20 void grow(size_t) override {
1009 if (this->size() != buffer_size) return;
1010 count_ += this->size();
1011 this->clear();
1012 }
1013
1014 public:
1015 counting_buffer() : buffer<T>(data_, 0, buffer_size) {}
1016
1017 auto count() -> size_t { return count_ + this->size(); }
1018 };
1019
1020 template <typename T>
1021 using buffer_appender = conditional_t<std::is_same<T, char>::value, appender,
1022 std::back_insert_iterator<buffer<T>>>;
1023
1024 // Maps an output iterator to a buffer.
1025 template <typename T, typename OutputIt>
1026 auto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {
1027 return iterator_buffer<OutputIt, T>(out);
1028 }
1029
1030 template <typename Buffer>
1031 auto get_iterator(Buffer& buf) -> decltype(buf.out()) {
1032 return buf.out();
1033 }
1034 template <typename T> auto get_iterator(buffer<T>& buf) -> buffer_appender<T> {
1035 return buffer_appender<T>(buf);
1036 }
1037
1038 template <typename T, typename Char = char, typename Enable = void>
1039 struct fallback_formatter {
1040 fallback_formatter() = delete;
1041 };
1042
1043 // Specifies if T has an enabled fallback_formatter specialization.
1044 template <typename T, typename Char>
1045 using has_fallback_formatter =
1046 std::is_constructible<fallback_formatter<T, Char>>;
1047
1048 struct view {};
1049
1050 template <typename Char, typename T> struct named_arg : view {
1051 const Char* name;
1052 const T& value;
1053 named_arg(const Char* n, const T& v) : name(n), value(v) {}
1054 };
1055
1056 template <typename Char> struct named_arg_info {
1057 const Char* name;
1058 int id;
1059 };
1060
1061 template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
1062 struct arg_data {
1063 // args_[0].named_args points to named_args_ to avoid bloating format_args.
1064 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1065 T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)];
1066 named_arg_info<Char> named_args_[NUM_NAMED_ARGS];
1067
1068 template <typename... U>
1069 arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {}
1070 arg_data(const arg_data& other) = delete;
1071 auto args() const -> const T* { return args_ + 1; }
1072 auto named_args() -> named_arg_info<Char>* { return named_args_; }
1073 };
1074
1075 template <typename T, typename Char, size_t NUM_ARGS>
1076 struct arg_data<T, Char, NUM_ARGS, 0> {
1077 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1078 T args_[NUM_ARGS != 0 ? NUM_ARGS : +1];
1079
1080 template <typename... U>
1081 FMT_CONSTEXPR FMT_INLINE arg_data(const U&... init) : args_{init...} {}
1082 FMT_CONSTEXPR FMT_INLINE auto args() const -> const T* { return args_; }
1083 FMT_CONSTEXPR FMT_INLINE auto named_args() -> std::nullptr_t {
1084 return nullptr;
1085 }
1086 };
1087
1088 template <typename Char>
1089 inline void init_named_args(named_arg_info<Char>*, int, int) {}
1090
1091 template <typename T> struct is_named_arg : std::false_type {};
1092 template <typename T> struct is_statically_named_arg : std::false_type {};
1093
1094 template <typename T, typename Char>
1095 struct is_named_arg<named_arg<Char, T>> : std::true_type {};
1096
1097 template <typename Char, typename T, typename... Tail,
1098 FMT_ENABLE_IF(!is_named_arg<T>::value)>
1099 void init_named_args(named_arg_info<Char>* named_args, int arg_count,
1100 int named_arg_count, const T&, const Tail&... args) {
1101 init_named_args(named_args, arg_count + 1, named_arg_count, args...);
1102 }
1103
1104 template <typename Char, typename T, typename... Tail,
1105 FMT_ENABLE_IF(is_named_arg<T>::value)>
1106 void init_named_args(named_arg_info<Char>* named_args, int arg_count,
1107 int named_arg_count, const T& arg, const Tail&... args) {
1108 named_args[named_arg_count++] = {arg.name, arg_count};
1109 init_named_args(named_args, arg_count + 1, named_arg_count, args...);
1110 }
1111
1112 template <typename... Args>
1113 FMT_CONSTEXPR FMT_INLINE void init_named_args(std::nullptr_t, int, int,
1114 const Args&...) {}
1115
1116 template <bool B = false> constexpr auto count() -> size_t { return B ? 1 : 0; }
1117 template <bool B1, bool B2, bool... Tail> constexpr auto count() -> size_t {
1118 return (B1 ? 1 : 0) + count<B2, Tail...>();
1119 }
1120
1121 template <typename... Args> constexpr auto count_named_args() -> size_t {
1122 return count<is_named_arg<Args>::value...>();
1123 }
1124
1125 template <typename... Args>
1126 constexpr auto count_statically_named_args() -> size_t {
1127 return count<is_statically_named_arg<Args>::value...>();
1128 }
1129
1130 enum class type {
1131 none_type,
1132 // Integer types should go first,
1133 int_type,
1134 uint_type,
1135 long_long_type,
1136 ulong_long_type,
1137 int128_type,
1138 uint128_type,
1139 bool_type,
1140 char_type,
1141 last_integer_type = char_type,
1142 // followed by floating-point types.
1143 float_type,
1144 double_type,
1145 long_double_type,
1146 last_numeric_type = long_double_type,
1147 cstring_type,
1148 string_type,
1149 pointer_type,
1150 custom_type
1151 };
1152
1153 // Maps core type T to the corresponding type enum constant.
1154 template <typename T, typename Char>
1155 struct type_constant : std::integral_constant<type, type::custom_type> {};
1156
1157 #define FMT_TYPE_CONSTANT(Type, constant) \
1158 template <typename Char> \
1159 struct type_constant<Type, Char> \
1160 : std::integral_constant<type, type::constant> {}
1161
1162 FMT_TYPE_CONSTANT(int, int_type);
1163 FMT_TYPE_CONSTANT(unsigned, uint_type);
1164 FMT_TYPE_CONSTANT(long long, long_long_type);
1165 FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
1166 FMT_TYPE_CONSTANT(int128_t, int128_type);
1167 FMT_TYPE_CONSTANT(uint128_t, uint128_type);
1168 FMT_TYPE_CONSTANT(bool, bool_type);
1169 FMT_TYPE_CONSTANT(Char, char_type);
1170 FMT_TYPE_CONSTANT(float, float_type);
1171 FMT_TYPE_CONSTANT(double, double_type);
1172 FMT_TYPE_CONSTANT(long double, long_double_type);
1173 FMT_TYPE_CONSTANT(const Char*, cstring_type);
1174 FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
1175 FMT_TYPE_CONSTANT(const void*, pointer_type);
1176
1177 constexpr bool is_integral_type(type t) {
1178 return t > type::none_type && t <= type::last_integer_type;
1179 }
1180
1181 constexpr bool is_arithmetic_type(type t) {
1182 return t > type::none_type && t <= type::last_numeric_type;
1183 }
1184
1185 struct unformattable {};
1186 struct unformattable_char : unformattable {};
1187 struct unformattable_const : unformattable {};
1188 struct unformattable_pointer : unformattable {};
1189
1190 template <typename Char> struct string_value {
1191 const Char* data;
1192 size_t size;
1193 };
1194
1195 template <typename Char> struct named_arg_value {
1196 const named_arg_info<Char>* data;
1197 size_t size;
1198 };
1199
1200 template <typename Context> struct custom_value {
1201 using parse_context = typename Context::parse_context_type;
1202 void* value;
1203 void (*format)(void* arg, parse_context& parse_ctx, Context& ctx);
1204 };
1205
1206 // A formatting argument value.
1207 template <typename Context> class value {
1208 public:
1209 using char_type = typename Context::char_type;
1210
1211 union {
1212 monostate no_value;
1213 int int_value;
1214 unsigned uint_value;
1215 long long long_long_value;
1216 unsigned long long ulong_long_value;
1217 int128_t int128_value;
1218 uint128_t uint128_value;
1219 bool bool_value;
1220 char_type char_value;
1221 float float_value;
1222 double double_value;
1223 long double long_double_value;
1224 const void* pointer;
1225 string_value<char_type> string;
1226 custom_value<Context> custom;
1227 named_arg_value<char_type> named_args;
1228 };
1229
1230 constexpr FMT_INLINE value() : no_value() {}
1231 constexpr FMT_INLINE value(int val) : int_value(val) {}
1232 constexpr FMT_INLINE value(unsigned val) : uint_value(val) {}
1233 constexpr FMT_INLINE value(long long val) : long_long_value(val) {}
1234 constexpr FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {}
1235 FMT_INLINE value(int128_t val) : int128_value(val) {}
1236 FMT_INLINE value(uint128_t val) : uint128_value(val) {}
1237 constexpr FMT_INLINE value(float val) : float_value(val) {}
1238 constexpr FMT_INLINE value(double val) : double_value(val) {}
1239 FMT_INLINE value(long double val) : long_double_value(val) {}
1240 constexpr FMT_INLINE value(bool val) : bool_value(val) {}
1241 constexpr FMT_INLINE value(char_type val) : char_value(val) {}
1242 FMT_CONSTEXPR FMT_INLINE value(const char_type* val) {
1243 string.data = val;
1244 if (is_constant_evaluated()) string.size = {};
1245 }
1246 FMT_CONSTEXPR FMT_INLINE value(basic_string_view<char_type> val) {
1247 string.data = val.data();
1248 string.size = val.size();
1249 }
1250 FMT_INLINE value(const void* val) : pointer(val) {}
1251 FMT_INLINE value(const named_arg_info<char_type>* args, size_t size)
1252 : named_args{args, size} {}
1253
1254 template <typename T> FMT_CONSTEXPR FMT_INLINE value(T& val) {
1255 using value_type = remove_cvref_t<T>;
1256 custom.value = const_cast<value_type*>(&val);
1257 // Get the formatter type through the context to allow different contexts
1258 // have different extension points, e.g. `formatter<T>` for `format` and
1259 // `printf_formatter<T>` for `printf`.
1260 custom.format = format_custom_arg<
1261 value_type,
1262 conditional_t<has_formatter<value_type, Context>::value,
1263 typename Context::template formatter_type<value_type>,
1264 fallback_formatter<value_type, char_type>>>;
1265 }
1266 value(unformattable);
1267 value(unformattable_char);
1268 value(unformattable_const);
1269 value(unformattable_pointer);
1270
1271 private:
1272 // Formats an argument of a custom type, such as a user-defined class.
1273 template <typename T, typename Formatter>
1274 static void format_custom_arg(void* arg,
1275 typename Context::parse_context_type& parse_ctx,
1276 Context& ctx) {
1277 auto f = Formatter();
1278 parse_ctx.advance_to(f.parse(parse_ctx));
1279 using qualified_type =
1280 conditional_t<has_const_formatter<T, Context>(), const T, T>;
1281 ctx.advance_to(f.format(*static_cast<qualified_type*>(arg), ctx));
1282 }
1283 };
1284
1285 template <typename Context, typename T>
1286 FMT_CONSTEXPR auto make_arg(const T& value) -> basic_format_arg<Context>;
1287
1288 // To minimize the number of types we need to deal with, long is translated
1289 // either to int or to long long depending on its size.
1290 enum { long_short = sizeof(long) == sizeof(int) };
1291 using long_type = conditional_t<long_short, int, long long>;
1292 using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
1293
1294 // Maps formatting arguments to core types.
1295 // arg_mapper reports errors by returning unformattable instead of using
1296 // static_assert because it's used in the is_formattable trait.
1297 template <typename Context> struct arg_mapper {
1298 using char_type = typename Context::char_type;
1299
1300 FMT_CONSTEXPR FMT_INLINE auto map(signed char val) -> int { return val; }
1301 FMT_CONSTEXPR FMT_INLINE auto map(unsigned char val) -> unsigned {
1302 return val;
1303 }
1304 FMT_CONSTEXPR FMT_INLINE auto map(short val) -> int { return val; }
1305 FMT_CONSTEXPR FMT_INLINE auto map(unsigned short val) -> unsigned {
1306 return val;
1307 }
1308 FMT_CONSTEXPR FMT_INLINE auto map(int val) -> int { return val; }
1309 FMT_CONSTEXPR FMT_INLINE auto map(unsigned val) -> unsigned { return val; }
1310 FMT_CONSTEXPR FMT_INLINE auto map(long val) -> long_type { return val; }
1311 FMT_CONSTEXPR FMT_INLINE auto map(unsigned long val) -> ulong_type {
1312 return val;
1313 }
1314 FMT_CONSTEXPR FMT_INLINE auto map(long long val) -> long long { return val; }
1315 FMT_CONSTEXPR FMT_INLINE auto map(unsigned long long val)
1316 -> unsigned long long {
1317 return val;
1318 }
1319 FMT_CONSTEXPR FMT_INLINE auto map(int128_t val) -> int128_t { return val; }
1320 FMT_CONSTEXPR FMT_INLINE auto map(uint128_t val) -> uint128_t { return val; }
1321 FMT_CONSTEXPR FMT_INLINE auto map(bool val) -> bool { return val; }
1322
1323 template <typename T, FMT_ENABLE_IF(std::is_same<T, char>::value ||
1324 std::is_same<T, char_type>::value)>
1325 FMT_CONSTEXPR FMT_INLINE auto map(T val) -> char_type {
1326 return val;
1327 }
1328 template <typename T, enable_if_t<(std::is_same<T, wchar_t>::value ||
1329 #ifdef __cpp_char8_t
1330 std::is_same<T, char8_t>::value ||
1331 #endif
1332 std::is_same<T, char16_t>::value ||
1333 std::is_same<T, char32_t>::value) &&
1334 !std::is_same<T, char_type>::value,
1335 int> = 0>
1336 FMT_CONSTEXPR FMT_INLINE auto map(T) -> unformattable_char {
1337 return {};
1338 }
1339
1340 FMT_CONSTEXPR FMT_INLINE auto map(float val) -> float { return val; }
1341 FMT_CONSTEXPR FMT_INLINE auto map(double val) -> double { return val; }
1342 FMT_CONSTEXPR FMT_INLINE auto map(long double val) -> long double {
1343 return val;
1344 }
1345
1346 FMT_CONSTEXPR FMT_INLINE auto map(char_type* val) -> const char_type* {
1347 return val;
1348 }
1349 FMT_CONSTEXPR FMT_INLINE auto map(const char_type* val) -> const char_type* {
1350 return val;
1351 }
1352 template <typename T,
1353 FMT_ENABLE_IF(is_string<T>::value && !std::is_pointer<T>::value &&
1354 std::is_same<char_type, char_t<T>>::value)>
1355 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1356 -> basic_string_view<char_type> {
1357 return to_string_view(val);
1358 }
1359 template <typename T,
1360 FMT_ENABLE_IF(is_string<T>::value && !std::is_pointer<T>::value &&
1361 !std::is_same<char_type, char_t<T>>::value)>
1362 FMT_CONSTEXPR FMT_INLINE auto map(const T&) -> unformattable_char {
1363 return {};
1364 }
1365 template <typename T,
1366 FMT_ENABLE_IF(
1367 std::is_constructible<basic_string_view<char_type>, T>::value &&
1368 !is_string<T>::value && !has_formatter<T, Context>::value &&
1369 !has_fallback_formatter<T, char_type>::value)>
1370 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1371 -> basic_string_view<char_type> {
1372 return basic_string_view<char_type>(val);
1373 }
1374 template <
1375 typename T,
1376 FMT_ENABLE_IF(
1377 std::is_constructible<std_string_view<char_type>, T>::value &&
1378 !std::is_constructible<basic_string_view<char_type>, T>::value &&
1379 !is_string<T>::value && !has_formatter<T, Context>::value &&
1380 !has_fallback_formatter<T, char_type>::value)>
1381 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1382 -> basic_string_view<char_type> {
1383 return std_string_view<char_type>(val);
1384 }
1385
1386 using cstring_result = conditional_t<std::is_same<char_type, char>::value,
1387 const char*, unformattable_pointer>;
1388
1389 FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(const signed char* val)
1390 -> cstring_result {
1391 return map(reinterpret_cast<const char*>(val));
1392 }
1393 FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(const unsigned char* val)
1394 -> cstring_result {
1395 return map(reinterpret_cast<const char*>(val));
1396 }
1397 FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(signed char* val)
1398 -> cstring_result {
1399 return map(reinterpret_cast<const char*>(val));
1400 }
1401 FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(unsigned char* val)
1402 -> cstring_result {
1403 return map(reinterpret_cast<const char*>(val));
1404 }
1405
1406 FMT_CONSTEXPR FMT_INLINE auto map(void* val) -> const void* { return val; }
1407 FMT_CONSTEXPR FMT_INLINE auto map(const void* val) -> const void* {
1408 return val;
1409 }
1410 FMT_CONSTEXPR FMT_INLINE auto map(std::nullptr_t val) -> const void* {
1411 return val;
1412 }
1413
1414 // We use SFINAE instead of a const T* parameter to avoid conflicting with
1415 // the C array overload.
1416 template <
1417 typename T,
1418 FMT_ENABLE_IF(
1419 std::is_member_pointer<T>::value ||
1420 std::is_function<typename std::remove_pointer<T>::type>::value ||
1421 (std::is_convertible<const T&, const void*>::value &&
1422 !std::is_convertible<const T&, const char_type*>::value))>
1423 FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer {
1424 return {};
1425 }
1426
1427 template <typename T, std::size_t N,
1428 FMT_ENABLE_IF(!std::is_same<T, wchar_t>::value)>
1429 FMT_CONSTEXPR FMT_INLINE auto map(const T (&values)[N]) -> const T (&)[N] {
1430 return values;
1431 }
1432
1433 template <typename T,
1434 FMT_ENABLE_IF(
1435 std::is_enum<T>::value&& std::is_convertible<T, int>::value &&
1436 !has_formatter<T, Context>::value &&
1437 !has_fallback_formatter<T, char_type>::value)>
1438 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1439 -> decltype(std::declval<arg_mapper>().map(
1440 static_cast<typename std::underlying_type<T>::type>(val))) {
1441 return map(static_cast<typename std::underlying_type<T>::type>(val));
1442 }
1443
1444 FMT_CONSTEXPR FMT_INLINE auto map(detail::byte val) -> unsigned {
1445 return map(static_cast<unsigned char>(val));
1446 }
1447
1448 template <typename T, typename U = remove_cvref_t<T>>
1449 struct formattable
1450 : bool_constant<has_const_formatter<U, Context>() ||
1451 !std::is_const<remove_reference_t<T>>::value ||
1452 has_fallback_formatter<U, char_type>::value> {};
1453
1454 #if FMT_MSC_VER != 0 && FMT_MSC_VER < 1910
1455 // Workaround a bug in MSVC.
1456 template <typename T> FMT_CONSTEXPR FMT_INLINE auto do_map(T&& val) -> T& {
1457 return val;
1458 }
1459 #else
1460 template <typename T, FMT_ENABLE_IF(formattable<T>::value)>
1461 FMT_CONSTEXPR FMT_INLINE auto do_map(T&& val) -> T& {
1462 return val;
1463 }
1464 template <typename T, FMT_ENABLE_IF(!formattable<T>::value)>
1465 FMT_CONSTEXPR FMT_INLINE auto do_map(T&&) -> unformattable_const {
1466 return {};
1467 }
1468 #endif
1469
1470 template <typename T, typename U = remove_cvref_t<T>,
1471 FMT_ENABLE_IF(!is_string<U>::value && !is_char<U>::value &&
1472 !std::is_array<U>::value &&
1473 (has_formatter<U, Context>::value ||
1474 has_fallback_formatter<U, char_type>::value))>
1475 FMT_CONSTEXPR FMT_INLINE auto map(T&& val)
1476 -> decltype(this->do_map(std::forward<T>(val))) {
1477 return do_map(std::forward<T>(val));
1478 }
1479
1480 template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
1481 FMT_CONSTEXPR FMT_INLINE auto map(const T& named_arg)
1482 -> decltype(std::declval<arg_mapper>().map(named_arg.value)) {
1483 return map(named_arg.value);
1484 }
1485
1486 auto map(...) -> unformattable { return {}; }
1487 };
1488
1489 // A type constant after applying arg_mapper<Context>.
1490 template <typename T, typename Context>
1491 using mapped_type_constant =
1492 type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
1493 typename Context::char_type>;
1494
1495 enum { packed_arg_bits = 4 };
1496 // Maximum number of arguments with packed types.
1497 enum { max_packed_args = 62 / packed_arg_bits };
1498 enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
1499 enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
1500
1501 FMT_END_DETAIL_NAMESPACE
1502
1503 // An output iterator that appends to a buffer.
1504 // It is used to reduce symbol sizes for the common case.
1505 class appender : public std::back_insert_iterator<detail::buffer<char>> {
1506 using base = std::back_insert_iterator<detail::buffer<char>>;
1507
1508 template <typename T>
1509 friend auto get_buffer(appender out) -> detail::buffer<char>& {
1510 return detail::get_container(out);
1511 }
1512
1513 public:
1514 using std::back_insert_iterator<detail::buffer<char>>::back_insert_iterator;
1515 appender(base it) FMT_NOEXCEPT : base(it) {}
1516 using _Unchecked_type = appender; // Mark iterator as checked.
1517
1518 auto operator++() FMT_NOEXCEPT -> appender& { return *this; }
1519
1520 auto operator++(int) FMT_NOEXCEPT -> appender { return *this; }
1521 };
1522
1523 // A formatting argument. It is a trivially copyable/constructible type to
1524 // allow storage in basic_memory_buffer.
1525 template <typename Context> class basic_format_arg {
1526 private:
1527 detail::value<Context> value_;
1528 detail::type type_;
1529
1530 template <typename ContextType, typename T>
1531 friend FMT_CONSTEXPR auto detail::make_arg(const T& value)
1532 -> basic_format_arg<ContextType>;
1533
1534 template <typename Visitor, typename Ctx>
1535 friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
1536 const basic_format_arg<Ctx>& arg)
1537 -> decltype(vis(0));
1538
1539 friend class basic_format_args<Context>;
1540 friend class dynamic_format_arg_store<Context>;
1541
1542 using char_type = typename Context::char_type;
1543
1544 template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
1545 friend struct detail::arg_data;
1546
1547 basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
1548 : value_(args, size) {}
1549
1550 public:
1551 class handle {
1552 public:
1553 explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
1554
1555 void format(typename Context::parse_context_type& parse_ctx,
1556 Context& ctx) const {
1557 custom_.format(custom_.value, parse_ctx, ctx);
1558 }
1559
1560 private:
1561 detail::custom_value<Context> custom_;
1562 };
1563
1564 constexpr basic_format_arg() : type_(detail::type::none_type) {}
1565
1566 constexpr explicit operator bool() const FMT_NOEXCEPT {
1567 return type_ != detail::type::none_type;
1568 }
1569
1570 auto type() const -> detail::type { return type_; }
1571
1572 auto is_integral() const -> bool { return detail::is_integral_type(type_); }
1573 auto is_arithmetic() const -> bool {
1574 return detail::is_arithmetic_type(type_);
1575 }
1576 };
1577
1578 /**
1579 \rst
1580 Visits an argument dispatching to the appropriate visit method based on
1581 the argument type. For example, if the argument type is ``double`` then
1582 ``vis(value)`` will be called with the value of type ``double``.
1583 \endrst
1584 */
1585 template <typename Visitor, typename Context>
1586 FMT_CONSTEXPR FMT_INLINE auto visit_format_arg(
1587 Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
1588 switch (arg.type_) {
1589 case detail::type::none_type:
1590 break;
1591 case detail::type::int_type:
1592 return vis(arg.value_.int_value);
1593 case detail::type::uint_type:
1594 return vis(arg.value_.uint_value);
1595 case detail::type::long_long_type:
1596 return vis(arg.value_.long_long_value);
1597 case detail::type::ulong_long_type:
1598 return vis(arg.value_.ulong_long_value);
1599 case detail::type::int128_type:
1600 return vis(detail::convert_for_visit(arg.value_.int128_value));
1601 case detail::type::uint128_type:
1602 return vis(detail::convert_for_visit(arg.value_.uint128_value));
1603 case detail::type::bool_type:
1604 return vis(arg.value_.bool_value);
1605 case detail::type::char_type:
1606 return vis(arg.value_.char_value);
1607 case detail::type::float_type:
1608 return vis(arg.value_.float_value);
1609 case detail::type::double_type:
1610 return vis(arg.value_.double_value);
1611 case detail::type::long_double_type:
1612 return vis(arg.value_.long_double_value);
1613 case detail::type::cstring_type:
1614 return vis(arg.value_.string.data);
1615 case detail::type::string_type:
1616 using sv = basic_string_view<typename Context::char_type>;
1617 return vis(sv(arg.value_.string.data, arg.value_.string.size));
1618 case detail::type::pointer_type:
1619 return vis(arg.value_.pointer);
1620 case detail::type::custom_type:
1621 return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
1622 }
1623 return vis(monostate());
1624 }
1625
1626 FMT_BEGIN_DETAIL_NAMESPACE
1627
1628 template <typename Char, typename InputIt>
1629 auto copy_str(InputIt begin, InputIt end, appender out) -> appender {
1630 get_container(out).append(begin, end);
1631 return out;
1632 }
1633
1634 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
1635 // A workaround for gcc 4.8 to make void_t work in a SFINAE context.
1636 template <typename... Ts> struct void_t_impl { using type = void; };
1637 template <typename... Ts>
1638 using void_t = typename detail::void_t_impl<Ts...>::type;
1639 #else
1640 template <typename...> using void_t = void;
1641 #endif
1642
1643 template <typename It, typename T, typename Enable = void>
1644 struct is_output_iterator : std::false_type {};
1645
1646 template <typename It, typename T>
1647 struct is_output_iterator<
1648 It, T,
1649 void_t<typename std::iterator_traits<It>::iterator_category,
1650 decltype(*std::declval<It>() = std::declval<T>())>>
1651 : std::true_type {};
1652
1653 template <typename OutputIt>
1654 struct is_back_insert_iterator : std::false_type {};
1655 template <typename Container>
1656 struct is_back_insert_iterator<std::back_insert_iterator<Container>>
1657 : std::true_type {};
1658
1659 template <typename OutputIt>
1660 struct is_contiguous_back_insert_iterator : std::false_type {};
1661 template <typename Container>
1662 struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
1663 : is_contiguous<Container> {};
1664 template <>
1665 struct is_contiguous_back_insert_iterator<appender> : std::true_type {};
1666
1667 // A type-erased reference to an std::locale to avoid heavy <locale> include.
1668 class locale_ref {
1669 private:
1670 const void* locale_; // A type-erased pointer to std::locale.
1671
1672 public:
1673 constexpr locale_ref() : locale_(nullptr) {}
1674 template <typename Locale> explicit locale_ref(const Locale& loc);
1675
1676 explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; }
1677
1678 template <typename Locale> auto get() const -> Locale;
1679 };
1680
1681 template <typename> constexpr auto encode_types() -> unsigned long long {
1682 return 0;
1683 }
1684
1685 template <typename Context, typename Arg, typename... Args>
1686 constexpr auto encode_types() -> unsigned long long {
1687 return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
1688 (encode_types<Context, Args...>() << packed_arg_bits);
1689 }
1690
1691 template <typename Context, typename T>
1692 FMT_CONSTEXPR auto make_arg(const T& value) -> basic_format_arg<Context> {
1693 basic_format_arg<Context> arg;
1694 arg.type_ = mapped_type_constant<T, Context>::value;
1695 arg.value_ = arg_mapper<Context>().map(value);
1696 return arg;
1697 }
1698
1699 // The type template parameter is there to avoid an ODR violation when using
1700 // a fallback formatter in one translation unit and an implicit conversion in
1701 // another (not recommended).
1702 template <bool IS_PACKED, typename Context, type, typename T,
1703 FMT_ENABLE_IF(IS_PACKED)>
1704 FMT_CONSTEXPR FMT_INLINE auto make_arg(T&& val) -> value<Context> {
1705 const auto& arg = arg_mapper<Context>().map(std::forward<T>(val));
1706
1707 constexpr bool formattable_char =
1708 !std::is_same<decltype(arg), const unformattable_char&>::value;
1709 static_assert(formattable_char, "Mixing character types is disallowed.");
1710
1711 constexpr bool formattable_const =
1712 !std::is_same<decltype(arg), const unformattable_const&>::value;
1713 static_assert(formattable_const, "Cannot format a const argument.");
1714
1715 // Formatting of arbitrary pointers is disallowed. If you want to output
1716 // a pointer cast it to "void *" or "const void *". In particular, this
1717 // forbids formatting of "[const] volatile char *" which is printed as bool
1718 // by iostreams.
1719 constexpr bool formattable_pointer =
1720 !std::is_same<decltype(arg), const unformattable_pointer&>::value;
1721 static_assert(formattable_pointer,
1722 "Formatting of non-void pointers is disallowed.");
1723
1724 constexpr bool formattable =
1725 !std::is_same<decltype(arg), const unformattable&>::value;
1726 static_assert(
1727 formattable,
1728 "Cannot format an argument. To make type T formattable provide a "
1729 "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
1730 return {arg};
1731 }
1732
1733 template <bool IS_PACKED, typename Context, type, typename T,
1734 FMT_ENABLE_IF(!IS_PACKED)>
1735 inline auto make_arg(const T& value) -> basic_format_arg<Context> {
1736 return make_arg<Context>(value);
1737 }
1738 FMT_END_DETAIL_NAMESPACE
1739
1740 // Formatting context.
1741 template <typename OutputIt, typename Char> class basic_format_context {
1742 public:
1743 /** The character type for the output. */
1744 using char_type = Char;
1745
1746 private:
1747 OutputIt out_;
1748 basic_format_args<basic_format_context> args_;
1749 detail::locale_ref loc_;
1750
1751 public:
1752 using iterator = OutputIt;
1753 using format_arg = basic_format_arg<basic_format_context>;
1754 using parse_context_type = basic_format_parse_context<Char>;
1755 template <typename T> using formatter_type = formatter<T, char_type>;
1756
1757 basic_format_context(basic_format_context&&) = default;
1758 basic_format_context(const basic_format_context&) = delete;
1759 void operator=(const basic_format_context&) = delete;
1760 /**
1761 Constructs a ``basic_format_context`` object. References to the arguments are
1762 stored in the object so make sure they have appropriate lifetimes.
1763 */
1764 constexpr basic_format_context(
1765 OutputIt out, basic_format_args<basic_format_context> ctx_args,
1766 detail::locale_ref loc = detail::locale_ref())
1767 : out_(out), args_(ctx_args), loc_(loc) {}
1768
1769 constexpr auto arg(int id) const -> format_arg { return args_.get(id); }
1770 FMT_CONSTEXPR auto arg(basic_string_view<char_type> name) -> format_arg {
1771 return args_.get(name);
1772 }
1773 FMT_CONSTEXPR auto arg_id(basic_string_view<char_type> name) -> int {
1774 return args_.get_id(name);
1775 }
1776 auto args() const -> const basic_format_args<basic_format_context>& {
1777 return args_;
1778 }
1779
1780 FMT_CONSTEXPR auto error_handler() -> detail::error_handler { return {}; }
1781 void on_error(const char* message) { error_handler().on_error(message); }
1782
1783 // Returns an iterator to the beginning of the output range.
1784 FMT_CONSTEXPR auto out() -> iterator { return out_; }
1785
1786 // Advances the begin iterator to ``it``.
1787 void advance_to(iterator it) {
1788 if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
1789 }
1790
1791 FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; }
1792 };
1793
1794 template <typename Char>
1795 using buffer_context =
1796 basic_format_context<detail::buffer_appender<Char>, Char>;
1797 using format_context = buffer_context<char>;
1798
1799 // Workaround an alias issue: https://stackoverflow.com/q/62767544/471164.
1800 #define FMT_BUFFER_CONTEXT(Char) \
1801 basic_format_context<detail::buffer_appender<Char>, Char>
1802
1803 template <typename T, typename Char = char>
1804 using is_formattable = bool_constant<
1805 !std::is_base_of<detail::unformattable,
1806 decltype(detail::arg_mapper<buffer_context<Char>>().map(
1807 std::declval<T>()))>::value &&
1808 !detail::has_fallback_formatter<T, Char>::value>;
1809
1810 /**
1811 \rst
1812 An array of references to arguments. It can be implicitly converted into
1813 `~fmt::basic_format_args` for passing into type-erased formatting functions
1814 such as `~fmt::vformat`.
1815 \endrst
1816 */
1817 template <typename Context, typename... Args>
1818 class format_arg_store
1819 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
1820 // Workaround a GCC template argument substitution bug.
1821 : public basic_format_args<Context>
1822 #endif
1823 {
1824 private:
1825 static const size_t num_args = sizeof...(Args);
1826 static const size_t num_named_args = detail::count_named_args<Args...>();
1827 static const bool is_packed = num_args <= detail::max_packed_args;
1828
1829 using value_type = conditional_t<is_packed, detail::value<Context>,
1830 basic_format_arg<Context>>;
1831
1832 detail::arg_data<value_type, typename Context::char_type, num_args,
1833 num_named_args>
1834 data_;
1835
1836 friend class basic_format_args<Context>;
1837
1838 static constexpr unsigned long long desc =
1839 (is_packed ? detail::encode_types<Context, Args...>()
1840 : detail::is_unpacked_bit | num_args) |
1841 (num_named_args != 0
1842 ? static_cast<unsigned long long>(detail::has_named_args_bit)
1843 : 0);
1844
1845 public:
1846 template <typename... T>
1847 FMT_CONSTEXPR FMT_INLINE format_arg_store(T&&... args)
1848 :
1849 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
1850 basic_format_args<Context>(*this),
1851 #endif
1852 data_{detail::make_arg<
1853 is_packed, Context,
1854 detail::mapped_type_constant<remove_cvref_t<T>, Context>::value>(
1855 std::forward<T>(args))...} {
1856 detail::init_named_args(data_.named_args(), 0, 0, args...);
1857 }
1858 };
1859
1860 /**
1861 \rst
1862 Constructs a `~fmt::format_arg_store` object that contains references to
1863 arguments and can be implicitly converted to `~fmt::format_args`. `Context`
1864 can be omitted in which case it defaults to `~fmt::context`.
1865 See `~fmt::arg` for lifetime considerations.
1866 \endrst
1867 */
1868 template <typename Context = format_context, typename... Args>
1869 constexpr auto make_format_args(Args&&... args)
1870 -> format_arg_store<Context, remove_cvref_t<Args>...> {
1871 return {std::forward<Args>(args)...};
1872 }
1873
1874 /**
1875 \rst
1876 Returns a named argument to be used in a formatting function.
1877 It should only be used in a call to a formatting function or
1878 `dynamic_format_arg_store::push_back`.
1879
1880 **Example**::
1881
1882 fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
1883 \endrst
1884 */
1885 template <typename Char, typename T>
1886 inline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {
1887 static_assert(!detail::is_named_arg<T>(), "nested named arguments");
1888 return {name, arg};
1889 }
1890
1891 /**
1892 \rst
1893 A view of a collection of formatting arguments. To avoid lifetime issues it
1894 should only be used as a parameter type in type-erased functions such as
1895 ``vformat``::
1896
1897 void vlog(string_view format_str, format_args args); // OK
1898 format_args args = make_format_args(42); // Error: dangling reference
1899 \endrst
1900 */
1901 template <typename Context> class basic_format_args {
1902 public:
1903 using size_type = int;
1904 using format_arg = basic_format_arg<Context>;
1905
1906 private:
1907 // A descriptor that contains information about formatting arguments.
1908 // If the number of arguments is less or equal to max_packed_args then
1909 // argument types are passed in the descriptor. This reduces binary code size
1910 // per formatting function call.
1911 unsigned long long desc_;
1912 union {
1913 // If is_packed() returns true then argument values are stored in values_;
1914 // otherwise they are stored in args_. This is done to improve cache
1915 // locality and reduce compiled code size since storing larger objects
1916 // may require more code (at least on x86-64) even if the same amount of
1917 // data is actually copied to stack. It saves ~10% on the bloat test.
1918 const detail::value<Context>* values_;
1919 const format_arg* args_;
1920 };
1921
1922 constexpr auto is_packed() const -> bool {
1923 return (desc_ & detail::is_unpacked_bit) == 0;
1924 }
1925 auto has_named_args() const -> bool {
1926 return (desc_ & detail::has_named_args_bit) != 0;
1927 }
1928
1929 FMT_CONSTEXPR auto type(int index) const -> detail::type {
1930 int shift = index * detail::packed_arg_bits;
1931 unsigned int mask = (1 << detail::packed_arg_bits) - 1;
1932 return static_cast<detail::type>((desc_ >> shift) & mask);
1933 }
1934
1935 constexpr FMT_INLINE basic_format_args(unsigned long long desc,
1936 const detail::value<Context>* values)
1937 : desc_(desc), values_(values) {}
1938 constexpr basic_format_args(unsigned long long desc, const format_arg* args)
1939 : desc_(desc), args_(args) {}
1940
1941 public:
1942 constexpr basic_format_args() : desc_(0), args_(nullptr) {}
1943
1944 /**
1945 \rst
1946 Constructs a `basic_format_args` object from `~fmt::format_arg_store`.
1947 \endrst
1948 */
1949 template <typename... Args>
1950 constexpr FMT_INLINE basic_format_args(
1951 const format_arg_store<Context, Args...>& store)
1952 : basic_format_args(format_arg_store<Context, Args...>::desc,
1953 store.data_.args()) {}
1954
1955 /**
1956 \rst
1957 Constructs a `basic_format_args` object from
1958 `~fmt::dynamic_format_arg_store`.
1959 \endrst
1960 */
1961 constexpr FMT_INLINE basic_format_args(
1962 const dynamic_format_arg_store<Context>& store)
1963 : basic_format_args(store.get_types(), store.data()) {}
1964
1965 /**
1966 \rst
1967 Constructs a `basic_format_args` object from a dynamic set of arguments.
1968 \endrst
1969 */
1970 constexpr basic_format_args(const format_arg* args, int count)
1971 : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count),
1972 args) {}
1973
1974 /** Returns the argument with the specified id. */
1975 FMT_CONSTEXPR auto get(int id) const -> format_arg {
1976 format_arg arg;
1977 if (!is_packed()) {
1978 if (id < max_size()) arg = args_[id];
1979 return arg;
1980 }
1981 if (id >= detail::max_packed_args) return arg;
1982 arg.type_ = type(id);
1983 if (arg.type_ == detail::type::none_type) return arg;
1984 arg.value_ = values_[id];
1985 return arg;
1986 }
1987
1988 template <typename Char>
1989 auto get(basic_string_view<Char> name) const -> format_arg {
1990 int id = get_id(name);
1991 return id >= 0 ? get(id) : format_arg();
1992 }
1993
1994 template <typename Char>
1995 auto get_id(basic_string_view<Char> name) const -> int {
1996 if (!has_named_args()) return -1;
1997 const auto& named_args =
1998 (is_packed() ? values_[-1] : args_[-1].value_).named_args;
1999 for (size_t i = 0; i < named_args.size; ++i) {
2000 if (named_args.data[i].name == name) return named_args.data[i].id;
2001 }
2002 return -1;
2003 }
2004
2005 auto max_size() const -> int {
2006 unsigned long long max_packed = detail::max_packed_args;
2007 return static_cast<int>(is_packed() ? max_packed
2008 : desc_ & ~detail::is_unpacked_bit);
2009 }
2010 };
2011
2012 /** An alias to ``basic_format_args<format_context>``. */
2013 // A separate type would result in shorter symbols but break ABI compatibility
2014 // between clang and gcc on ARM (#1919).
2015 using format_args = basic_format_args<format_context>;
2016
2017 // We cannot use enum classes as bit fields because of a gcc bug
2018 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414.
2019 namespace align {
2020 enum type { none, left, right, center, numeric };
2021 }
2022 using align_t = align::type;
2023 namespace sign {
2024 enum type { none, minus, plus, space };
2025 }
2026 using sign_t = sign::type;
2027
2028 FMT_BEGIN_DETAIL_NAMESPACE
2029
2030 // Workaround an array initialization issue in gcc 4.8.
2031 template <typename Char> struct fill_t {
2032 private:
2033 enum { max_size = 4 };
2034 Char data_[max_size] = {Char(' '), Char(0), Char(0), Char(0)};
2035 unsigned char size_ = 1;
2036
2037 public:
2038 FMT_CONSTEXPR void operator=(basic_string_view<Char> s) {
2039 auto size = s.size();
2040 if (size > max_size) return throw_format_error("invalid fill");
2041 for (size_t i = 0; i < size; ++i) data_[i] = s[i];
2042 size_ = static_cast<unsigned char>(size);
2043 }
2044
2045 constexpr auto size() const -> size_t { return size_; }
2046 constexpr auto data() const -> const Char* { return data_; }
2047
2048 FMT_CONSTEXPR auto operator[](size_t index) -> Char& { return data_[index]; }
2049 FMT_CONSTEXPR auto operator[](size_t index) const -> const Char& {
2050 return data_[index];
2051 }
2052 };
2053 FMT_END_DETAIL_NAMESPACE
2054
2055 enum class presentation_type : unsigned char {
2056 none,
2057 // Integer types should go first,
2058 dec, // 'd'
2059 oct, // 'o'
2060 hex_lower, // 'x'
2061 hex_upper, // 'X'
2062 bin_lower, // 'b'
2063 bin_upper, // 'B'
2064 hexfloat_lower, // 'a'
2065 hexfloat_upper, // 'A'
2066 exp_lower, // 'e'
2067 exp_upper, // 'E'
2068 fixed_lower, // 'f'
2069 fixed_upper, // 'F'
2070 general_lower, // 'g'
2071 general_upper, // 'G'
2072 chr, // 'c'
2073 string, // 's'
2074 pointer // 'p'
2075 };
2076
2077 // Format specifiers for built-in and string types.
2078 template <typename Char> struct basic_format_specs {
2079 int width;
2080 int precision;
2081 presentation_type type;
2082 align_t align : 4;
2083 sign_t sign : 3;
2084 bool alt : 1; // Alternate form ('#').
2085 bool localized : 1;
2086 detail::fill_t<Char> fill;
2087
2088 constexpr basic_format_specs()
2089 : width(0),
2090 precision(-1),
2091 type(presentation_type::none),
2092 align(align::none),
2093 sign(sign::none),
2094 alt(false),
2095 localized(false) {}
2096 };
2097
2098 using format_specs = basic_format_specs<char>;
2099
2100 FMT_BEGIN_DETAIL_NAMESPACE
2101
2102 enum class arg_id_kind { none, index, name };
2103
2104 // An argument reference.
2105 template <typename Char> struct arg_ref {
2106 FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
2107
2108 FMT_CONSTEXPR explicit arg_ref(int index)
2109 : kind(arg_id_kind::index), val(index) {}
2110 FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name)
2111 : kind(arg_id_kind::name), val(name) {}
2112
2113 FMT_CONSTEXPR auto operator=(int idx) -> arg_ref& {
2114 kind = arg_id_kind::index;
2115 val.index = idx;
2116 return *this;
2117 }
2118
2119 arg_id_kind kind;
2120 union value {
2121 FMT_CONSTEXPR value(int id = 0) : index{id} {}
2122 FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {}
2123
2124 int index;
2125 basic_string_view<Char> name;
2126 } val;
2127 };
2128
2129 // Format specifiers with width and precision resolved at formatting rather
2130 // than parsing time to allow re-using the same parsed specifiers with
2131 // different sets of arguments (precompilation of format strings).
2132 template <typename Char>
2133 struct dynamic_format_specs : basic_format_specs<Char> {
2134 arg_ref<Char> width_ref;
2135 arg_ref<Char> precision_ref;
2136 };
2137
2138 struct auto_id {};
2139
2140 // A format specifier handler that sets fields in basic_format_specs.
2141 template <typename Char> class specs_setter {
2142 protected:
2143 basic_format_specs<Char>& specs_;
2144
2145 public:
2146 explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs)
2147 : specs_(specs) {}
2148
2149 FMT_CONSTEXPR specs_setter(const specs_setter& other)
2150 : specs_(other.specs_) {}
2151
2152 FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; }
2153 FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) {
2154 specs_.fill = fill;
2155 }
2156 FMT_CONSTEXPR void on_sign(sign_t s) { specs_.sign = s; }
2157 FMT_CONSTEXPR void on_hash() { specs_.alt = true; }
2158 FMT_CONSTEXPR void on_localized() { specs_.localized = true; }
2159
2160 FMT_CONSTEXPR void on_zero() {
2161 if (specs_.align == align::none) specs_.align = align::numeric;
2162 specs_.fill[0] = Char('0');
2163 }
2164
2165 FMT_CONSTEXPR void on_width(int width) { specs_.width = width; }
2166 FMT_CONSTEXPR void on_precision(int precision) {
2167 specs_.precision = precision;
2168 }
2169 FMT_CONSTEXPR void end_precision() {}
2170
2171 FMT_CONSTEXPR void on_type(presentation_type type) { specs_.type = type; }
2172 };
2173
2174 // Format spec handler that saves references to arguments representing dynamic
2175 // width and precision to be resolved at formatting time.
2176 template <typename ParseContext>
2177 class dynamic_specs_handler
2178 : public specs_setter<typename ParseContext::char_type> {
2179 public:
2180 using char_type = typename ParseContext::char_type;
2181
2182 FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs,
2183 ParseContext& ctx)
2184 : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {}
2185
2186 FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other)
2187 : specs_setter<char_type>(other),
2188 specs_(other.specs_),
2189 context_(other.context_) {}
2190
2191 template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
2192 specs_.width_ref = make_arg_ref(arg_id);
2193 }
2194
2195 template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
2196 specs_.precision_ref = make_arg_ref(arg_id);
2197 }
2198
2199 FMT_CONSTEXPR void on_error(const char* message) {
2200 context_.on_error(message);
2201 }
2202
2203 private:
2204 dynamic_format_specs<char_type>& specs_;
2205 ParseContext& context_;
2206
2207 using arg_ref_type = arg_ref<char_type>;
2208
2209 FMT_CONSTEXPR auto make_arg_ref(int arg_id) -> arg_ref_type {
2210 context_.check_arg_id(arg_id);
2211 return arg_ref_type(arg_id);
2212 }
2213
2214 FMT_CONSTEXPR auto make_arg_ref(auto_id) -> arg_ref_type {
2215 return arg_ref_type(context_.next_arg_id());
2216 }
2217
2218 FMT_CONSTEXPR auto make_arg_ref(basic_string_view<char_type> arg_id)
2219 -> arg_ref_type {
2220 context_.check_arg_id(arg_id);
2221 basic_string_view<char_type> format_str(
2222 context_.begin(), to_unsigned(context_.end() - context_.begin()));
2223 return arg_ref_type(arg_id);
2224 }
2225 };
2226
2227 template <typename Char> constexpr bool is_ascii_letter(Char c) {
2228 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
2229 }
2230
2231 // Converts a character to ASCII. Returns a number > 127 on conversion failure.
2232 template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
2233 constexpr auto to_ascii(Char value) -> Char {
2234 return value;
2235 }
2236 template <typename Char, FMT_ENABLE_IF(std::is_enum<Char>::value)>
2237 constexpr auto to_ascii(Char value) ->
2238 typename std::underlying_type<Char>::type {
2239 return value;
2240 }
2241
2242 template <typename Char>
2243 FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
2244 if (const_check(sizeof(Char) != 1)) return 1;
2245 auto lengths =
2246 "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4";
2247 int len = lengths[static_cast<unsigned char>(*begin) >> 3];
2248
2249 // Compute the pointer to the next character early so that the next
2250 // iteration can start working on the next character. Neither Clang
2251 // nor GCC figure out this reordering on their own.
2252 return len + !len;
2253 }
2254
2255 // Return the result via the out param to workaround gcc bug 77539.
2256 template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
2257 FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {
2258 for (out = first; out != last; ++out) {
2259 if (*out == value) return true;
2260 }
2261 return false;
2262 }
2263
2264 template <>
2265 inline auto find<false, char>(const char* first, const char* last, char value,
2266 const char*& out) -> bool {
2267 out = static_cast<const char*>(
2268 std::memchr(first, value, to_unsigned(last - first)));
2269 return out != nullptr;
2270 }
2271
2272 // Parses the range [begin, end) as an unsigned integer. This function assumes
2273 // that the range is non-empty and the first character is a digit.
2274 template <typename Char>
2275 FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,
2276 int error_value) noexcept -> int {
2277 FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
2278 unsigned value = 0, prev = 0;
2279 auto p = begin;
2280 do {
2281 prev = value;
2282 value = value * 10 + unsigned(*p - '0');
2283 ++p;
2284 } while (p != end && '0' <= *p && *p <= '9');
2285 auto num_digits = p - begin;
2286 begin = p;
2287 if (num_digits <= std::numeric_limits<int>::digits10)
2288 return static_cast<int>(value);
2289 // Check for overflow.
2290 const unsigned max = to_unsigned((std::numeric_limits<int>::max)());
2291 return num_digits == std::numeric_limits<int>::digits10 + 1 &&
2292 prev * 10ull + unsigned(p[-1] - '0') <= max
2293 ? static_cast<int>(value)
2294 : error_value;
2295 }
2296
2297 // Parses fill and alignment.
2298 template <typename Char, typename Handler>
2299 FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end,
2300 Handler&& handler) -> const Char* {
2301 FMT_ASSERT(begin != end, "");
2302 auto align = align::none;
2303 auto p = begin + code_point_length(begin);
2304 if (p >= end) p = begin;
2305 for (;;) {
2306 switch (to_ascii(*p)) {
2307 case '<':
2308 align = align::left;
2309 break;
2310 case '>':
2311 align = align::right;
2312 break;
2313 case '^':
2314 align = align::center;
2315 break;
2316 default:
2317 break;
2318 }
2319 if (align != align::none) {
2320 if (p != begin) {
2321 auto c = *begin;
2322 if (c == '{')
2323 return handler.on_error("invalid fill character '{'"), begin;
2324 handler.on_fill(basic_string_view<Char>(begin, to_unsigned(p - begin)));
2325 begin = p + 1;
2326 } else
2327 ++begin;
2328 handler.on_align(align);
2329 break;
2330 } else if (p == begin) {
2331 break;
2332 }
2333 p = begin;
2334 }
2335 return begin;
2336 }
2337
2338 template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) {
2339 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
2340 }
2341
2342 template <typename Char, typename IDHandler>
2343 FMT_CONSTEXPR auto do_parse_arg_id(const Char* begin, const Char* end,
2344 IDHandler&& handler) -> const Char* {
2345 FMT_ASSERT(begin != end, "");
2346 Char c = *begin;
2347 if (c >= '0' && c <= '9') {
2348 int index = 0;
2349 if (c != '0')
2350 index =
2351 parse_nonnegative_int(begin, end, (std::numeric_limits<int>::max)());
2352 else
2353 ++begin;
2354 if (begin == end || (*begin != '}' && *begin != ':'))
2355 handler.on_error("invalid format string");
2356 else
2357 handler(index);
2358 return begin;
2359 }
2360 if (!is_name_start(c)) {
2361 handler.on_error("invalid format string");
2362 return begin;
2363 }
2364 auto it = begin;
2365 do {
2366 ++it;
2367 } while (it != end && (is_name_start(c = *it) || ('0' <= c && c <= '9')));
2368 handler(basic_string_view<Char>(begin, to_unsigned(it - begin)));
2369 return it;
2370 }
2371
2372 template <typename Char, typename IDHandler>
2373 FMT_CONSTEXPR FMT_INLINE auto parse_arg_id(const Char* begin, const Char* end,
2374 IDHandler&& handler) -> const Char* {
2375 Char c = *begin;
2376 if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler);
2377 handler();
2378 return begin;
2379 }
2380
2381 template <typename Char, typename Handler>
2382 FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end,
2383 Handler&& handler) -> const Char* {
2384 using detail::auto_id;
2385 struct width_adapter {
2386 Handler& handler;
2387
2388 FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); }
2389 FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); }
2390 FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
2391 handler.on_dynamic_width(id);
2392 }
2393 FMT_CONSTEXPR void on_error(const char* message) {
2394 if (message) handler.on_error(message);
2395 }
2396 };
2397
2398 FMT_ASSERT(begin != end, "");
2399 if ('0' <= *begin && *begin <= '9') {
2400 int width = parse_nonnegative_int(begin, end, -1);
2401 if (width != -1)
2402 handler.on_width(width);
2403 else
2404 handler.on_error("number is too big");
2405 } else if (*begin == '{') {
2406 ++begin;
2407 if (begin != end) begin = parse_arg_id(begin, end, width_adapter{handler});
2408 if (begin == end || *begin != '}')
2409 return handler.on_error("invalid format string"), begin;
2410 ++begin;
2411 }
2412 return begin;
2413 }
2414
2415 template <typename Char, typename Handler>
2416 FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,
2417 Handler&& handler) -> const Char* {
2418 using detail::auto_id;
2419 struct precision_adapter {
2420 Handler& handler;
2421
2422 FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); }
2423 FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); }
2424 FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
2425 handler.on_dynamic_precision(id);
2426 }
2427 FMT_CONSTEXPR void on_error(const char* message) {
2428 if (message) handler.on_error(message);
2429 }
2430 };
2431
2432 ++begin;
2433 auto c = begin != end ? *begin : Char();
2434 if ('0' <= c && c <= '9') {
2435 auto precision = parse_nonnegative_int(begin, end, -1);
2436 if (precision != -1)
2437 handler.on_precision(precision);
2438 else
2439 handler.on_error("number is too big");
2440 } else if (c == '{') {
2441 ++begin;
2442 if (begin != end)
2443 begin = parse_arg_id(begin, end, precision_adapter{handler});
2444 if (begin == end || *begin++ != '}')
2445 return handler.on_error("invalid format string"), begin;
2446 } else {
2447 return handler.on_error("missing precision specifier"), begin;
2448 }
2449 handler.end_precision();
2450 return begin;
2451 }
2452
2453 template <typename Char>
2454 FMT_CONSTEXPR auto parse_presentation_type(Char type) -> presentation_type {
2455 switch (to_ascii(type)) {
2456 case 'd':
2457 return presentation_type::dec;
2458 case 'o':
2459 return presentation_type::oct;
2460 case 'x':
2461 return presentation_type::hex_lower;
2462 case 'X':
2463 return presentation_type::hex_upper;
2464 case 'b':
2465 return presentation_type::bin_lower;
2466 case 'B':
2467 return presentation_type::bin_upper;
2468 case 'a':
2469 return presentation_type::hexfloat_lower;
2470 case 'A':
2471 return presentation_type::hexfloat_upper;
2472 case 'e':
2473 return presentation_type::exp_lower;
2474 case 'E':
2475 return presentation_type::exp_upper;
2476 case 'f':
2477 return presentation_type::fixed_lower;
2478 case 'F':
2479 return presentation_type::fixed_upper;
2480 case 'g':
2481 return presentation_type::general_lower;
2482 case 'G':
2483 return presentation_type::general_upper;
2484 case 'c':
2485 return presentation_type::chr;
2486 case 's':
2487 return presentation_type::string;
2488 case 'p':
2489 return presentation_type::pointer;
2490 default:
2491 return presentation_type::none;
2492 }
2493 }
2494
2495 // Parses standard format specifiers and sends notifications about parsed
2496 // components to handler.
2497 template <typename Char, typename SpecHandler>
2498 FMT_CONSTEXPR FMT_INLINE auto parse_format_specs(const Char* begin,
2499 const Char* end,
2500 SpecHandler&& handler)
2501 -> const Char* {
2502 if (1 < end - begin && begin[1] == '}' && is_ascii_letter(*begin) &&
2503 *begin != 'L') {
2504 presentation_type type = parse_presentation_type(*begin++);
2505 if (type == presentation_type::none)
2506 handler.on_error("invalid type specifier");
2507 handler.on_type(type);
2508 return begin;
2509 }
2510
2511 if (begin == end) return begin;
2512
2513 begin = parse_align(begin, end, handler);
2514 if (begin == end) return begin;
2515
2516 // Parse sign.
2517 switch (to_ascii(*begin)) {
2518 case '+':
2519 handler.on_sign(sign::plus);
2520 ++begin;
2521 break;
2522 case '-':
2523 handler.on_sign(sign::minus);
2524 ++begin;
2525 break;
2526 case ' ':
2527 handler.on_sign(sign::space);
2528 ++begin;
2529 break;
2530 default:
2531 break;
2532 }
2533 if (begin == end) return begin;
2534
2535 if (*begin == '#') {
2536 handler.on_hash();
2537 if (++begin == end) return begin;
2538 }
2539
2540 // Parse zero flag.
2541 if (*begin == '0') {
2542 handler.on_zero();
2543 if (++begin == end) return begin;
2544 }
2545
2546 begin = parse_width(begin, end, handler);
2547 if (begin == end) return begin;
2548
2549 // Parse precision.
2550 if (*begin == '.') {
2551 begin = parse_precision(begin, end, handler);
2552 if (begin == end) return begin;
2553 }
2554
2555 if (*begin == 'L') {
2556 handler.on_localized();
2557 ++begin;
2558 }
2559
2560 // Parse type.
2561 if (begin != end && *begin != '}') {
2562 presentation_type type = parse_presentation_type(*begin++);
2563 if (type == presentation_type::none)
2564 handler.on_error("invalid type specifier");
2565 handler.on_type(type);
2566 }
2567 return begin;
2568 }
2569
2570 template <typename Char, typename Handler>
2571 FMT_CONSTEXPR auto parse_replacement_field(const Char* begin, const Char* end,
2572 Handler&& handler) -> const Char* {
2573 struct id_adapter {
2574 Handler& handler;
2575 int arg_id;
2576
2577 FMT_CONSTEXPR void operator()() { arg_id = handler.on_arg_id(); }
2578 FMT_CONSTEXPR void operator()(int id) { arg_id = handler.on_arg_id(id); }
2579 FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
2580 arg_id = handler.on_arg_id(id);
2581 }
2582 FMT_CONSTEXPR void on_error(const char* message) {
2583 if (message) handler.on_error(message);
2584 }
2585 };
2586
2587 ++begin;
2588 if (begin == end) return handler.on_error("invalid format string"), end;
2589 if (*begin == '}') {
2590 handler.on_replacement_field(handler.on_arg_id(), begin);
2591 } else if (*begin == '{') {
2592 handler.on_text(begin, begin + 1);
2593 } else {
2594 auto adapter = id_adapter{handler, 0};
2595 begin = parse_arg_id(begin, end, adapter);
2596 Char c = begin != end ? *begin : Char();
2597 if (c == '}') {
2598 handler.on_replacement_field(adapter.arg_id, begin);
2599 } else if (c == ':') {
2600 begin = handler.on_format_specs(adapter.arg_id, begin + 1, end);
2601 if (begin == end || *begin != '}')
2602 return handler.on_error("unknown format specifier"), end;
2603 } else {
2604 return handler.on_error("missing '}' in format string"), end;
2605 }
2606 }
2607 return begin + 1;
2608 }
2609
2610 template <bool IS_CONSTEXPR, typename Char, typename Handler>
2611 FMT_CONSTEXPR FMT_INLINE void parse_format_string(
2612 basic_string_view<Char> format_str, Handler&& handler) {
2613 // Workaround a name-lookup bug in MSVC's modules implementation.
2614 using detail::find;
2615
2616 auto begin = format_str.data();
2617 auto end = begin + format_str.size();
2618 if (end - begin < 32) {
2619 // Use a simple loop instead of memchr for small strings.
2620 const Char* p = begin;
2621 while (p != end) {
2622 auto c = *p++;
2623 if (c == '{') {
2624 handler.on_text(begin, p - 1);
2625 begin = p = parse_replacement_field(p - 1, end, handler);
2626 } else if (c == '}') {
2627 if (p == end || *p != '}')
2628 return handler.on_error("unmatched '}' in format string");
2629 handler.on_text(begin, p);
2630 begin = ++p;
2631 }
2632 }
2633 handler.on_text(begin, end);
2634 return;
2635 }
2636 struct writer {
2637 FMT_CONSTEXPR void operator()(const Char* pbegin, const Char* pend) {
2638 if (pbegin == pend) return;
2639 for (;;) {
2640 const Char* p = nullptr;
2641 if (!find<IS_CONSTEXPR>(pbegin, pend, Char('}'), p))
2642 return handler_.on_text(pbegin, pend);
2643 ++p;
2644 if (p == pend || *p != '}')
2645 return handler_.on_error("unmatched '}' in format string");
2646 handler_.on_text(pbegin, p);
2647 pbegin = p + 1;
2648 }
2649 }
2650 Handler& handler_;
2651 } write{handler};
2652 while (begin != end) {
2653 // Doing two passes with memchr (one for '{' and another for '}') is up to
2654 // 2.5x faster than the naive one-pass implementation on big format strings.
2655 const Char* p = begin;
2656 if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, Char('{'), p))
2657 return write(begin, end);
2658 write(begin, p);
2659 begin = parse_replacement_field(p, end, handler);
2660 }
2661 }
2662
2663 template <typename T, typename ParseContext>
2664 FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx)
2665 -> decltype(ctx.begin()) {
2666 using char_type = typename ParseContext::char_type;
2667 using context = buffer_context<char_type>;
2668 using mapped_type = conditional_t<
2669 mapped_type_constant<T, context>::value != type::custom_type,
2670 decltype(arg_mapper<context>().map(std::declval<const T&>())), T>;
2671 auto f = conditional_t<has_formatter<mapped_type, context>::value,
2672 formatter<mapped_type, char_type>,
2673 fallback_formatter<T, char_type>>();
2674 return f.parse(ctx);
2675 }
2676
2677 // A parse context with extra argument id checks. It is only used at compile
2678 // time because adding checks at runtime would introduce substantial overhead
2679 // and would be redundant since argument ids are checked when arguments are
2680 // retrieved anyway.
2681 template <typename Char, typename ErrorHandler = error_handler>
2682 class compile_parse_context
2683 : public basic_format_parse_context<Char, ErrorHandler> {
2684 private:
2685 int num_args_;
2686 using base = basic_format_parse_context<Char, ErrorHandler>;
2687
2688 public:
2689 explicit FMT_CONSTEXPR compile_parse_context(
2690 basic_string_view<Char> format_str,
2691 int num_args = (std::numeric_limits<int>::max)(), ErrorHandler eh = {})
2692 : base(format_str, eh), num_args_(num_args) {}
2693
2694 FMT_CONSTEXPR auto next_arg_id() -> int {
2695 int id = base::next_arg_id();
2696 if (id >= num_args_) this->on_error("argument not found");
2697 return id;
2698 }
2699
2700 FMT_CONSTEXPR void check_arg_id(int id) {
2701 base::check_arg_id(id);
2702 if (id >= num_args_) this->on_error("argument not found");
2703 }
2704 using base::check_arg_id;
2705 };
2706
2707 template <typename ErrorHandler>
2708 FMT_CONSTEXPR void check_int_type_spec(presentation_type type,
2709 ErrorHandler&& eh) {
2710 if (type > presentation_type::bin_upper && type != presentation_type::chr)
2711 eh.on_error("invalid type specifier");
2712 }
2713
2714 // Checks char specs and returns true if the type spec is char (and not int).
2715 template <typename Char, typename ErrorHandler = error_handler>
2716 FMT_CONSTEXPR auto check_char_specs(const basic_format_specs<Char>& specs,
2717 ErrorHandler&& eh = {}) -> bool {
2718 if (specs.type != presentation_type::none &&
2719 specs.type != presentation_type::chr) {
2720 check_int_type_spec(specs.type, eh);
2721 return false;
2722 }
2723 if (specs.align == align::numeric || specs.sign != sign::none || specs.alt)
2724 eh.on_error("invalid format specifier for char");
2725 return true;
2726 }
2727
2728 // A floating-point presentation format.
2729 enum class float_format : unsigned char {
2730 general, // General: exponent notation or fixed point based on magnitude.
2731 exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3.
2732 fixed, // Fixed point with the default precision of 6, e.g. 0.0012.
2733 hex
2734 };
2735
2736 struct float_specs {
2737 int precision;
2738 float_format format : 8;
2739 sign_t sign : 8;
2740 bool upper : 1;
2741 bool locale : 1;
2742 bool binary32 : 1;
2743 bool fallback : 1;
2744 bool showpoint : 1;
2745 };
2746
2747 template <typename ErrorHandler = error_handler, typename Char>
2748 FMT_CONSTEXPR auto parse_float_type_spec(const basic_format_specs<Char>& specs,
2749 ErrorHandler&& eh = {})
2750 -> float_specs {
2751 auto result = float_specs();
2752 result.showpoint = specs.alt;
2753 result.locale = specs.localized;
2754 switch (specs.type) {
2755 case presentation_type::none:
2756 result.format = float_format::general;
2757 break;
2758 case presentation_type::general_upper:
2759 result.upper = true;
2760 FMT_FALLTHROUGH;
2761 case presentation_type::general_lower:
2762 result.format = float_format::general;
2763 break;
2764 case presentation_type::exp_upper:
2765 result.upper = true;
2766 FMT_FALLTHROUGH;
2767 case presentation_type::exp_lower:
2768 result.format = float_format::exp;
2769 result.showpoint |= specs.precision != 0;
2770 break;
2771 case presentation_type::fixed_upper:
2772 result.upper = true;
2773 FMT_FALLTHROUGH;
2774 case presentation_type::fixed_lower:
2775 result.format = float_format::fixed;
2776 result.showpoint |= specs.precision != 0;
2777 break;
2778 case presentation_type::hexfloat_upper:
2779 result.upper = true;
2780 FMT_FALLTHROUGH;
2781 case presentation_type::hexfloat_lower:
2782 result.format = float_format::hex;
2783 break;
2784 default:
2785 eh.on_error("invalid type specifier");
2786 break;
2787 }
2788 return result;
2789 }
2790
2791 template <typename ErrorHandler = error_handler>
2792 FMT_CONSTEXPR auto check_cstring_type_spec(presentation_type type,
2793 ErrorHandler&& eh = {}) -> bool {
2794 if (type == presentation_type::none || type == presentation_type::string)
2795 return true;
2796 if (type != presentation_type::pointer) eh.on_error("invalid type specifier");
2797 return false;
2798 }
2799
2800 template <typename ErrorHandler = error_handler>
2801 FMT_CONSTEXPR void check_string_type_spec(presentation_type type,
2802 ErrorHandler&& eh = {}) {
2803 if (type != presentation_type::none && type != presentation_type::string)
2804 eh.on_error("invalid type specifier");
2805 }
2806
2807 template <typename ErrorHandler>
2808 FMT_CONSTEXPR void check_pointer_type_spec(presentation_type type,
2809 ErrorHandler&& eh) {
2810 if (type != presentation_type::none && type != presentation_type::pointer)
2811 eh.on_error("invalid type specifier");
2812 }
2813
2814 // A parse_format_specs handler that checks if specifiers are consistent with
2815 // the argument type.
2816 template <typename Handler> class specs_checker : public Handler {
2817 private:
2818 detail::type arg_type_;
2819
2820 FMT_CONSTEXPR void require_numeric_argument() {
2821 if (!is_arithmetic_type(arg_type_))
2822 this->on_error("format specifier requires numeric argument");
2823 }
2824
2825 public:
2826 FMT_CONSTEXPR specs_checker(const Handler& handler, detail::type arg_type)
2827 : Handler(handler), arg_type_(arg_type) {}
2828
2829 FMT_CONSTEXPR void on_align(align_t align) {
2830 if (align == align::numeric) require_numeric_argument();
2831 Handler::on_align(align);
2832 }
2833
2834 FMT_CONSTEXPR void on_sign(sign_t s) {
2835 require_numeric_argument();
2836 if (is_integral_type(arg_type_) && arg_type_ != type::int_type &&
2837 arg_type_ != type::long_long_type && arg_type_ != type::char_type) {
2838 this->on_error("format specifier requires signed argument");
2839 }
2840 Handler::on_sign(s);
2841 }
2842
2843 FMT_CONSTEXPR void on_hash() {
2844 require_numeric_argument();
2845 Handler::on_hash();
2846 }
2847
2848 FMT_CONSTEXPR void on_localized() {
2849 require_numeric_argument();
2850 Handler::on_localized();
2851 }
2852
2853 FMT_CONSTEXPR void on_zero() {
2854 require_numeric_argument();
2855 Handler::on_zero();
2856 }
2857
2858 FMT_CONSTEXPR void end_precision() {
2859 if (is_integral_type(arg_type_) || arg_type_ == type::pointer_type)
2860 this->on_error("precision not allowed for this argument type");
2861 }
2862 };
2863
2864 constexpr int invalid_arg_index = -1;
2865
2866 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
2867 template <int N, typename T, typename... Args, typename Char>
2868 constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2869 if constexpr (detail::is_statically_named_arg<T>()) {
2870 if (name == T::name) return N;
2871 }
2872 if constexpr (sizeof...(Args) > 0)
2873 return get_arg_index_by_name<N + 1, Args...>(name);
2874 (void)name; // Workaround an MSVC bug about "unused" parameter.
2875 return invalid_arg_index;
2876 }
2877 #endif
2878
2879 template <typename... Args, typename Char>
2880 FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2881 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
2882 if constexpr (sizeof...(Args) > 0)
2883 return get_arg_index_by_name<0, Args...>(name);
2884 #endif
2885 (void)name;
2886 return invalid_arg_index;
2887 }
2888
2889 template <typename Char, typename ErrorHandler, typename... Args>
2890 class format_string_checker {
2891 private:
2892 using parse_context_type = compile_parse_context<Char, ErrorHandler>;
2893 enum { num_args = sizeof...(Args) };
2894
2895 // Format specifier parsing function.
2896 using parse_func = const Char* (*)(parse_context_type&);
2897
2898 parse_context_type context_;
2899 parse_func parse_funcs_[num_args > 0 ? num_args : 1];
2900
2901 public:
2902 explicit FMT_CONSTEXPR format_string_checker(
2903 basic_string_view<Char> format_str, ErrorHandler eh)
2904 : context_(format_str, num_args, eh),
2905 parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
2906
2907 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
2908
2909 FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }
2910 FMT_CONSTEXPR auto on_arg_id(int id) -> int {
2911 return context_.check_arg_id(id), id;
2912 }
2913 FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
2914 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
2915 auto index = get_arg_index_by_name<Args...>(id);
2916 if (index == invalid_arg_index) on_error("named argument is not found");
2917 return context_.check_arg_id(index), index;
2918 #else
2919 (void)id;
2920 on_error("compile-time checks for named arguments require C++20 support");
2921 return 0;
2922 #endif
2923 }
2924
2925 FMT_CONSTEXPR void on_replacement_field(int, const Char*) {}
2926
2927 FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char*)
2928 -> const Char* {
2929 context_.advance_to(context_.begin() + (begin - &*context_.begin()));
2930 // id >= 0 check is a workaround for gcc 10 bug (#2065).
2931 return id >= 0 && id < num_args ? parse_funcs_[id](context_) : begin;
2932 }
2933
2934 FMT_CONSTEXPR void on_error(const char* message) {
2935 context_.on_error(message);
2936 }
2937 };
2938
2939 template <typename... Args, typename S,
2940 enable_if_t<(is_compile_string<S>::value), int>>
2941 void check_format_string(S format_str) {
2942 FMT_CONSTEXPR auto s = to_string_view(format_str);
2943 using checker = format_string_checker<typename S::char_type, error_handler,
2944 remove_cvref_t<Args>...>;
2945 FMT_CONSTEXPR bool invalid_format =
2946 (parse_format_string<true>(s, checker(s, {})), true);
2947 ignore_unused(invalid_format);
2948 }
2949
2950 template <typename Char>
2951 void vformat_to(
2952 buffer<Char>& buf, basic_string_view<Char> fmt,
2953 basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
2954 locale_ref loc = {});
2955
2956 FMT_API void vprint_mojibake(std::FILE*, string_view, format_args);
2957 #ifndef _WIN32
2958 inline void vprint_mojibake(std::FILE*, string_view, format_args) {}
2959 #endif
2960 FMT_END_DETAIL_NAMESPACE
2961
2962 // A formatter specialization for the core types corresponding to detail::type
2963 // constants.
2964 template <typename T, typename Char>
2965 struct formatter<T, Char,
2966 enable_if_t<detail::type_constant<T, Char>::value !=
2967 detail::type::custom_type>> {
2968 private:
2969 detail::dynamic_format_specs<Char> specs_;
2970
2971 public:
2972 // Parses format specifiers stopping either at the end of the range or at the
2973 // terminating '}'.
2974 template <typename ParseContext>
2975 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
2976 auto begin = ctx.begin(), end = ctx.end();
2977 if (begin == end) return begin;
2978 using handler_type = detail::dynamic_specs_handler<ParseContext>;
2979 auto type = detail::type_constant<T, Char>::value;
2980 auto checker =
2981 detail::specs_checker<handler_type>(handler_type(specs_, ctx), type);
2982 auto it = detail::parse_format_specs(begin, end, checker);
2983 auto eh = ctx.error_handler();
2984 switch (type) {
2985 case detail::type::none_type:
2986 FMT_ASSERT(false, "invalid argument type");
2987 break;
2988 case detail::type::bool_type:
2989 if (specs_.type == presentation_type::none ||
2990 specs_.type == presentation_type::string) {
2991 break;
2992 }
2993 FMT_FALLTHROUGH;
2994 case detail::type::int_type:
2995 case detail::type::uint_type:
2996 case detail::type::long_long_type:
2997 case detail::type::ulong_long_type:
2998 case detail::type::int128_type:
2999 case detail::type::uint128_type:
3000 detail::check_int_type_spec(specs_.type, eh);
3001 break;
3002 case detail::type::char_type:
3003 detail::check_char_specs(specs_, eh);
3004 break;
3005 case detail::type::float_type:
3006 if (detail::const_check(FMT_USE_FLOAT))
3007 detail::parse_float_type_spec(specs_, eh);
3008 else
3009 FMT_ASSERT(false, "float support disabled");
3010 break;
3011 case detail::type::double_type:
3012 if (detail::const_check(FMT_USE_DOUBLE))
3013 detail::parse_float_type_spec(specs_, eh);
3014 else
3015 FMT_ASSERT(false, "double support disabled");
3016 break;
3017 case detail::type::long_double_type:
3018 if (detail::const_check(FMT_USE_LONG_DOUBLE))
3019 detail::parse_float_type_spec(specs_, eh);
3020 else
3021 FMT_ASSERT(false, "long double support disabled");
3022 break;
3023 case detail::type::cstring_type:
3024 detail::check_cstring_type_spec(specs_.type, eh);
3025 break;
3026 case detail::type::string_type:
3027 detail::check_string_type_spec(specs_.type, eh);
3028 break;
3029 case detail::type::pointer_type:
3030 detail::check_pointer_type_spec(specs_.type, eh);
3031 break;
3032 case detail::type::custom_type:
3033 // Custom format specifiers are checked in parse functions of
3034 // formatter specializations.
3035 break;
3036 }
3037 return it;
3038 }
3039
3040 template <typename FormatContext>
3041 FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
3042 -> decltype(ctx.out());
3043 };
3044
3045 template <typename Char> struct basic_runtime { basic_string_view<Char> str; };
3046
3047 /** A compile-time format string. */
3048 template <typename Char, typename... Args> class basic_format_string {
3049 private:
3050 basic_string_view<Char> str_;
3051
3052 public:
3053 template <typename S,
3054 FMT_ENABLE_IF(
3055 std::is_convertible<const S&, basic_string_view<Char>>::value)>
3056 FMT_CONSTEVAL FMT_INLINE basic_format_string(const S& s) : str_(s) {
3057 static_assert(
3058 detail::count<
3059 (std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
3060 std::is_reference<Args>::value)...>() == 0,
3061 "passing views as lvalues is disallowed");
3062 #ifdef FMT_HAS_CONSTEVAL
3063 if constexpr (detail::count_named_args<Args...>() ==
3064 detail::count_statically_named_args<Args...>()) {
3065 using checker = detail::format_string_checker<Char, detail::error_handler,
3066 remove_cvref_t<Args>...>;
3067 detail::parse_format_string<true>(str_, checker(s, {}));
3068 }
3069 #else
3070 detail::check_format_string<Args...>(s);
3071 #endif
3072 }
3073 basic_format_string(basic_runtime<Char> r) : str_(r.str) {}
3074
3075 FMT_INLINE operator basic_string_view<Char>() const { return str_; }
3076 };
3077
3078 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
3079 // Workaround broken conversion on older gcc.
3080 template <typename... Args> using format_string = string_view;
3081 template <typename S> auto runtime(const S& s) -> basic_string_view<char_t<S>> {
3082 return s;
3083 }
3084 #else
3085 template <typename... Args>
3086 using format_string = basic_format_string<char, type_identity_t<Args>...>;
3087 /**
3088 \rst
3089 Creates a runtime format string.
3090
3091 **Example**::
3092
3093 // Check format string at runtime instead of compile-time.
3094 fmt::print(fmt::runtime("{:d}"), "I am not a number");
3095 \endrst
3096 */
3097 template <typename S> auto runtime(const S& s) -> basic_runtime<char_t<S>> {
3098 return {{s}};
3099 }
3100 #endif
3101
3102 FMT_API auto vformat(string_view fmt, format_args args) -> std::string;
3103
3104 /**
3105 \rst
3106 Formats ``args`` according to specifications in ``fmt`` and returns the result
3107 as a string.
3108
3109 **Example**::
3110
3111 #include <fmt/core.h>
3112 std::string message = fmt::format("The answer is {}.", 42);
3113 \endrst
3114 */
3115 template <typename... T>
3116 FMT_NODISCARD FMT_INLINE auto format(format_string<T...> fmt, T&&... args)
3117 -> std::string {
3118 return vformat(fmt, fmt::make_format_args(args...));
3119 }
3120
3121 /** Formats a string and writes the output to ``out``. */
3122 template <typename OutputIt,
3123 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3124 auto vformat_to(OutputIt out, string_view fmt, format_args args) -> OutputIt {
3125 using detail::get_buffer;
3126 auto&& buf = get_buffer<char>(out);
3127 detail::vformat_to(buf, fmt, args, {});
3128 return detail::get_iterator(buf);
3129 }
3130
3131 /**
3132 \rst
3133 Formats ``args`` according to specifications in ``fmt``, writes the result to
3134 the output iterator ``out`` and returns the iterator past the end of the output
3135 range. `format_to` does not append a terminating null character.
3136
3137 **Example**::
3138
3139 auto out = std::vector<char>();
3140 fmt::format_to(std::back_inserter(out), "{}", 42);
3141 \endrst
3142 */
3143 template <typename OutputIt, typename... T,
3144 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3145 FMT_INLINE auto format_to(OutputIt out, format_string<T...> fmt, T&&... args)
3146 -> OutputIt {
3147 return vformat_to(out, fmt, fmt::make_format_args(args...));
3148 }
3149
3150 template <typename OutputIt> struct format_to_n_result {
3151 /** Iterator past the end of the output range. */
3152 OutputIt out;
3153 /** Total (not truncated) output size. */
3154 size_t size;
3155 };
3156
3157 template <typename OutputIt, typename... T,
3158 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3159 auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)
3160 -> format_to_n_result<OutputIt> {
3161 using traits = detail::fixed_buffer_traits;
3162 auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
3163 detail::vformat_to(buf, fmt, args, {});
3164 return {buf.out(), buf.count()};
3165 }
3166
3167 /**
3168 \rst
3169 Formats ``args`` according to specifications in ``fmt``, writes up to ``n``
3170 characters of the result to the output iterator ``out`` and returns the total
3171 (not truncated) output size and the iterator past the end of the output range.
3172 `format_to_n` does not append a terminating null character.
3173 \endrst
3174 */
3175 template <typename OutputIt, typename... T,
3176 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3177 FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,
3178 T&&... args) -> format_to_n_result<OutputIt> {
3179 return vformat_to_n(out, n, fmt, fmt::make_format_args(args...));
3180 }
3181
3182 /** Returns the number of chars in the output of ``format(fmt, args...)``. */
3183 template <typename... T>
3184 FMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,
3185 T&&... args) -> size_t {
3186 auto buf = detail::counting_buffer<>();
3187 detail::vformat_to(buf, string_view(fmt), fmt::make_format_args(args...), {});
3188 return buf.count();
3189 }
3190
3191 FMT_API void vprint(string_view fmt, format_args args);
3192 FMT_API void vprint(std::FILE* f, string_view fmt, format_args args);
3193
3194 /**
3195 \rst
3196 Formats ``args`` according to specifications in ``fmt`` and writes the output
3197 to ``stdout``.
3198
3199 **Example**::
3200
3201 fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
3202 \endrst
3203 */
3204 template <typename... T>
3205 FMT_INLINE void print(format_string<T...> fmt, T&&... args) {
3206 const auto& vargs = fmt::make_format_args(args...);
3207 return detail::is_utf8() ? vprint(fmt, vargs)
3208 : detail::vprint_mojibake(stdout, fmt, vargs);
3209 }
3210
3211 /**
3212 \rst
3213 Formats ``args`` according to specifications in ``fmt`` and writes the
3214 output to the file ``f``.
3215
3216 **Example**::
3217
3218 fmt::print(stderr, "Don't {}!", "panic");
3219 \endrst
3220 */
3221 template <typename... T>
3222 FMT_INLINE void print(std::FILE* f, format_string<T...> fmt, T&&... args) {
3223 const auto& vargs = fmt::make_format_args(args...);
3224 return detail::is_utf8() ? vprint(f, fmt, vargs)
3225 : detail::vprint_mojibake(f, fmt, vargs);
3226 }
3227
3228 FMT_MODULE_EXPORT_END
3229 FMT_GCC_PRAGMA("GCC pop_options")
3230 FMT_END_NAMESPACE
3231
3232 #ifdef FMT_HEADER_ONLY
3233 # include "format.h"
3234 #endif
3235 #endif // FMT_CORE_H_
+0
-2643
source/misc/embedded_libs/fmt-8.1.1/include/fmt/format-inl.h less more
0 // Formatting library for C++ - implementation
1 //
2 // Copyright (c) 2012 - 2016, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_FORMAT_INL_H_
8 #define FMT_FORMAT_INL_H_
9
10 #include <algorithm>
11 #include <cctype>
12 #include <cerrno> // errno
13 #include <climits>
14 #include <cmath>
15 #include <cstdarg>
16 #include <cstring> // std::memmove
17 #include <cwchar>
18 #include <exception>
19
20 #ifndef FMT_STATIC_THOUSANDS_SEPARATOR
21 # include <locale>
22 #endif
23
24 #ifdef _WIN32
25 # include <io.h> // _isatty
26 #endif
27
28 #include "format.h"
29
30 FMT_BEGIN_NAMESPACE
31 namespace detail {
32
33 FMT_FUNC void assert_fail(const char* file, int line, const char* message) {
34 // Use unchecked std::fprintf to avoid triggering another assertion when
35 // writing to stderr fails
36 std::fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message);
37 // Chosen instead of std::abort to satisfy Clang in CUDA mode during device
38 // code pass.
39 std::terminate();
40 }
41
42 FMT_FUNC void throw_format_error(const char* message) {
43 FMT_THROW(format_error(message));
44 }
45
46 #ifndef _MSC_VER
47 # define FMT_SNPRINTF snprintf
48 #else // _MSC_VER
49 inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) {
50 va_list args;
51 va_start(args, format);
52 int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args);
53 va_end(args);
54 return result;
55 }
56 # define FMT_SNPRINTF fmt_snprintf
57 #endif // _MSC_VER
58
59 FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code,
60 string_view message) FMT_NOEXCEPT {
61 // Report error code making sure that the output fits into
62 // inline_buffer_size to avoid dynamic memory allocation and potential
63 // bad_alloc.
64 out.try_resize(0);
65 static const char SEP[] = ": ";
66 static const char ERROR_STR[] = "error ";
67 // Subtract 2 to account for terminating null characters in SEP and ERROR_STR.
68 size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2;
69 auto abs_value = static_cast<uint32_or_64_or_128_t<int>>(error_code);
70 if (detail::is_negative(error_code)) {
71 abs_value = 0 - abs_value;
72 ++error_code_size;
73 }
74 error_code_size += detail::to_unsigned(detail::count_digits(abs_value));
75 auto it = buffer_appender<char>(out);
76 if (message.size() <= inline_buffer_size - error_code_size)
77 format_to(it, FMT_STRING("{}{}"), message, SEP);
78 format_to(it, FMT_STRING("{}{}"), ERROR_STR, error_code);
79 FMT_ASSERT(out.size() <= inline_buffer_size, "");
80 }
81
82 FMT_FUNC void report_error(format_func func, int error_code,
83 const char* message) FMT_NOEXCEPT {
84 memory_buffer full_message;
85 func(full_message, error_code, message);
86 // Don't use fwrite_fully because the latter may throw.
87 if (std::fwrite(full_message.data(), full_message.size(), 1, stderr) > 0)
88 std::fputc('\n', stderr);
89 }
90
91 // A wrapper around fwrite that throws on error.
92 inline void fwrite_fully(const void* ptr, size_t size, size_t count,
93 FILE* stream) {
94 size_t written = std::fwrite(ptr, size, count, stream);
95 if (written < count) FMT_THROW(system_error(errno, "cannot write to file"));
96 }
97
98 #ifndef FMT_STATIC_THOUSANDS_SEPARATOR
99 template <typename Locale>
100 locale_ref::locale_ref(const Locale& loc) : locale_(&loc) {
101 static_assert(std::is_same<Locale, std::locale>::value, "");
102 }
103
104 template <typename Locale> Locale locale_ref::get() const {
105 static_assert(std::is_same<Locale, std::locale>::value, "");
106 return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale();
107 }
108
109 template <typename Char>
110 FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char> {
111 auto& facet = std::use_facet<std::numpunct<Char>>(loc.get<std::locale>());
112 auto grouping = facet.grouping();
113 auto thousands_sep = grouping.empty() ? Char() : facet.thousands_sep();
114 return {std::move(grouping), thousands_sep};
115 }
116 template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref loc) {
117 return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>())
118 .decimal_point();
119 }
120 #else
121 template <typename Char>
122 FMT_FUNC auto thousands_sep_impl(locale_ref) -> thousands_sep_result<Char> {
123 return {"\03", FMT_STATIC_THOUSANDS_SEPARATOR};
124 }
125 template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref) {
126 return '.';
127 }
128 #endif
129 } // namespace detail
130
131 #if !FMT_MSC_VER
132 FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default;
133 #endif
134
135 FMT_FUNC std::system_error vsystem_error(int error_code, string_view format_str,
136 format_args args) {
137 auto ec = std::error_code(error_code, std::generic_category());
138 return std::system_error(ec, vformat(format_str, args));
139 }
140
141 namespace detail {
142
143 template <> FMT_FUNC int count_digits<4>(detail::fallback_uintptr n) {
144 // fallback_uintptr is always stored in little endian.
145 int i = static_cast<int>(sizeof(void*)) - 1;
146 while (i > 0 && n.value[i] == 0) --i;
147 auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
148 return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1;
149 }
150
151 // log10(2) = 0x0.4d104d427de7fbcc...
152 static constexpr uint64_t log10_2_significand = 0x4d104d427de7fbcc;
153
154 template <typename T = void> struct basic_impl_data {
155 // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
156 // These are generated by support/compute-powers.py.
157 static constexpr uint64_t pow10_significands[87] = {
158 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
159 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
160 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
161 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
162 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
163 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
164 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
165 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
166 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
167 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
168 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
169 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
170 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
171 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
172 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
173 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
174 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
175 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
176 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
177 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
178 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
179 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
180 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
181 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
182 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
183 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
184 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
185 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
186 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
187 };
188
189 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
190 # pragma GCC diagnostic push
191 # pragma GCC diagnostic ignored "-Wnarrowing"
192 #endif
193 // Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
194 // to significands above.
195 static constexpr int16_t pow10_exponents[87] = {
196 -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
197 -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661,
198 -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
199 -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77,
200 -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
201 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
202 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
203 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066};
204 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
205 # pragma GCC diagnostic pop
206 #endif
207
208 static constexpr uint64_t power_of_10_64[20] = {
209 1, FMT_POWERS_OF_10(1ULL), FMT_POWERS_OF_10(1000000000ULL),
210 10000000000000000000ULL};
211 };
212
213 // This is a struct rather than an alias to avoid shadowing warnings in gcc.
214 struct impl_data : basic_impl_data<> {};
215
216 #if __cplusplus < 201703L
217 template <typename T>
218 constexpr uint64_t basic_impl_data<T>::pow10_significands[];
219 template <typename T> constexpr int16_t basic_impl_data<T>::pow10_exponents[];
220 template <typename T> constexpr uint64_t basic_impl_data<T>::power_of_10_64[];
221 #endif
222
223 template <typename T> struct bits {
224 static FMT_CONSTEXPR_DECL const int value =
225 static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits);
226 };
227
228 // Returns the number of significand bits in Float excluding the implicit bit.
229 template <typename Float> constexpr int num_significand_bits() {
230 // Subtract 1 to account for an implicit most significant bit in the
231 // normalized form.
232 return std::numeric_limits<Float>::digits - 1;
233 }
234
235 // A floating-point number f * pow(2, e).
236 struct fp {
237 uint64_t f;
238 int e;
239
240 static constexpr const int num_significand_bits = bits<decltype(f)>::value;
241
242 constexpr fp() : f(0), e(0) {}
243 constexpr fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
244
245 // Constructs fp from an IEEE754 floating-point number. It is a template to
246 // prevent compile errors on systems where n is not IEEE754.
247 template <typename Float> explicit FMT_CONSTEXPR fp(Float n) { assign(n); }
248
249 template <typename Float>
250 using is_supported = bool_constant<sizeof(Float) == sizeof(uint64_t) ||
251 sizeof(Float) == sizeof(uint32_t)>;
252
253 // Assigns d to this and return true iff predecessor is closer than successor.
254 template <typename Float, FMT_ENABLE_IF(is_supported<Float>::value)>
255 FMT_CONSTEXPR bool assign(Float n) {
256 // Assume float is in the format [sign][exponent][significand].
257 const int num_float_significand_bits =
258 detail::num_significand_bits<Float>();
259 const uint64_t implicit_bit = 1ULL << num_float_significand_bits;
260 const uint64_t significand_mask = implicit_bit - 1;
261 constexpr bool is_double = sizeof(Float) == sizeof(uint64_t);
262 auto u = bit_cast<conditional_t<is_double, uint64_t, uint32_t>>(n);
263 f = u & significand_mask;
264 const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask;
265 int biased_e =
266 static_cast<int>((u & exponent_mask) >> num_float_significand_bits);
267 // The predecessor is closer if n is a normalized power of 2 (f == 0) other
268 // than the smallest normalized number (biased_e > 1).
269 bool is_predecessor_closer = f == 0 && biased_e > 1;
270 if (biased_e != 0)
271 f += implicit_bit;
272 else
273 biased_e = 1; // Subnormals use biased exponent 1 (min exponent).
274 const int exponent_bias = std::numeric_limits<Float>::max_exponent - 1;
275 e = biased_e - exponent_bias - num_float_significand_bits;
276 return is_predecessor_closer;
277 }
278
279 template <typename Float, FMT_ENABLE_IF(!is_supported<Float>::value)>
280 bool assign(Float) {
281 FMT_ASSERT(false, "");
282 return false;
283 }
284 };
285
286 // Normalizes the value converted from double and multiplied by (1 << SHIFT).
287 template <int SHIFT = 0> FMT_CONSTEXPR fp normalize(fp value) {
288 // Handle subnormals.
289 const uint64_t implicit_bit = 1ULL << num_significand_bits<double>();
290 const auto shifted_implicit_bit = implicit_bit << SHIFT;
291 while ((value.f & shifted_implicit_bit) == 0) {
292 value.f <<= 1;
293 --value.e;
294 }
295 // Subtract 1 to account for hidden bit.
296 const auto offset =
297 fp::num_significand_bits - num_significand_bits<double>() - SHIFT - 1;
298 value.f <<= offset;
299 value.e -= offset;
300 return value;
301 }
302
303 inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; }
304
305 // Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.
306 FMT_CONSTEXPR inline uint64_t multiply(uint64_t lhs, uint64_t rhs) {
307 #if FMT_USE_INT128
308 auto product = static_cast<__uint128_t>(lhs) * rhs;
309 auto f = static_cast<uint64_t>(product >> 64);
310 return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;
311 #else
312 // Multiply 32-bit parts of significands.
313 uint64_t mask = (1ULL << 32) - 1;
314 uint64_t a = lhs >> 32, b = lhs & mask;
315 uint64_t c = rhs >> 32, d = rhs & mask;
316 uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
317 // Compute mid 64-bit of result and round.
318 uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
319 return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);
320 #endif
321 }
322
323 FMT_CONSTEXPR inline fp operator*(fp x, fp y) {
324 return {multiply(x.f, y.f), x.e + y.e + 64};
325 }
326
327 // Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its
328 // (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`.
329 FMT_CONSTEXPR inline fp get_cached_power(int min_exponent,
330 int& pow10_exponent) {
331 const int shift = 32;
332 const auto significand = static_cast<int64_t>(log10_2_significand);
333 int index = static_cast<int>(
334 ((min_exponent + fp::num_significand_bits - 1) * (significand >> shift) +
335 ((int64_t(1) << shift) - 1)) // ceil
336 >> 32 // arithmetic shift
337 );
338 // Decimal exponent of the first (smallest) cached power of 10.
339 const int first_dec_exp = -348;
340 // Difference between 2 consecutive decimal exponents in cached powers of 10.
341 const int dec_exp_step = 8;
342 index = (index - first_dec_exp - 1) / dec_exp_step + 1;
343 pow10_exponent = first_dec_exp + index * dec_exp_step;
344 return {impl_data::pow10_significands[index],
345 impl_data::pow10_exponents[index]};
346 }
347
348 // A simple accumulator to hold the sums of terms in bigint::square if uint128_t
349 // is not available.
350 struct accumulator {
351 uint64_t lower;
352 uint64_t upper;
353
354 constexpr accumulator() : lower(0), upper(0) {}
355 constexpr explicit operator uint32_t() const {
356 return static_cast<uint32_t>(lower);
357 }
358
359 FMT_CONSTEXPR void operator+=(uint64_t n) {
360 lower += n;
361 if (lower < n) ++upper;
362 }
363 FMT_CONSTEXPR void operator>>=(int shift) {
364 FMT_ASSERT(shift == 32, "");
365 (void)shift;
366 lower = (upper << 32) | (lower >> 32);
367 upper >>= 32;
368 }
369 };
370
371 class bigint {
372 private:
373 // A bigint is stored as an array of bigits (big digits), with bigit at index
374 // 0 being the least significant one.
375 using bigit = uint32_t;
376 using double_bigit = uint64_t;
377 enum { bigits_capacity = 32 };
378 basic_memory_buffer<bigit, bigits_capacity> bigits_;
379 int exp_;
380
381 FMT_CONSTEXPR20 bigit operator[](int index) const {
382 return bigits_[to_unsigned(index)];
383 }
384 FMT_CONSTEXPR20 bigit& operator[](int index) {
385 return bigits_[to_unsigned(index)];
386 }
387
388 static FMT_CONSTEXPR_DECL const int bigit_bits = bits<bigit>::value;
389
390 friend struct formatter<bigint>;
391
392 FMT_CONSTEXPR20 void subtract_bigits(int index, bigit other, bigit& borrow) {
393 auto result = static_cast<double_bigit>((*this)[index]) - other - borrow;
394 (*this)[index] = static_cast<bigit>(result);
395 borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));
396 }
397
398 FMT_CONSTEXPR20 void remove_leading_zeros() {
399 int num_bigits = static_cast<int>(bigits_.size()) - 1;
400 while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits;
401 bigits_.resize(to_unsigned(num_bigits + 1));
402 }
403
404 // Computes *this -= other assuming aligned bigints and *this >= other.
405 FMT_CONSTEXPR20 void subtract_aligned(const bigint& other) {
406 FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints");
407 FMT_ASSERT(compare(*this, other) >= 0, "");
408 bigit borrow = 0;
409 int i = other.exp_ - exp_;
410 for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)
411 subtract_bigits(i, other.bigits_[j], borrow);
412 while (borrow > 0) subtract_bigits(i, 0, borrow);
413 remove_leading_zeros();
414 }
415
416 FMT_CONSTEXPR20 void multiply(uint32_t value) {
417 const double_bigit wide_value = value;
418 bigit carry = 0;
419 for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
420 double_bigit result = bigits_[i] * wide_value + carry;
421 bigits_[i] = static_cast<bigit>(result);
422 carry = static_cast<bigit>(result >> bigit_bits);
423 }
424 if (carry != 0) bigits_.push_back(carry);
425 }
426
427 FMT_CONSTEXPR20 void multiply(uint64_t value) {
428 const bigit mask = ~bigit(0);
429 const double_bigit lower = value & mask;
430 const double_bigit upper = value >> bigit_bits;
431 double_bigit carry = 0;
432 for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
433 double_bigit result = bigits_[i] * lower + (carry & mask);
434 carry =
435 bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits);
436 bigits_[i] = static_cast<bigit>(result);
437 }
438 while (carry != 0) {
439 bigits_.push_back(carry & mask);
440 carry >>= bigit_bits;
441 }
442 }
443
444 public:
445 FMT_CONSTEXPR20 bigint() : exp_(0) {}
446 explicit bigint(uint64_t n) { assign(n); }
447 FMT_CONSTEXPR20 ~bigint() {
448 FMT_ASSERT(bigits_.capacity() <= bigits_capacity, "");
449 }
450
451 bigint(const bigint&) = delete;
452 void operator=(const bigint&) = delete;
453
454 FMT_CONSTEXPR20 void assign(const bigint& other) {
455 auto size = other.bigits_.size();
456 bigits_.resize(size);
457 auto data = other.bigits_.data();
458 std::copy(data, data + size, make_checked(bigits_.data(), size));
459 exp_ = other.exp_;
460 }
461
462 FMT_CONSTEXPR20 void assign(uint64_t n) {
463 size_t num_bigits = 0;
464 do {
465 bigits_[num_bigits++] = n & ~bigit(0);
466 n >>= bigit_bits;
467 } while (n != 0);
468 bigits_.resize(num_bigits);
469 exp_ = 0;
470 }
471
472 FMT_CONSTEXPR20 int num_bigits() const {
473 return static_cast<int>(bigits_.size()) + exp_;
474 }
475
476 FMT_NOINLINE FMT_CONSTEXPR20 bigint& operator<<=(int shift) {
477 FMT_ASSERT(shift >= 0, "");
478 exp_ += shift / bigit_bits;
479 shift %= bigit_bits;
480 if (shift == 0) return *this;
481 bigit carry = 0;
482 for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
483 bigit c = bigits_[i] >> (bigit_bits - shift);
484 bigits_[i] = (bigits_[i] << shift) + carry;
485 carry = c;
486 }
487 if (carry != 0) bigits_.push_back(carry);
488 return *this;
489 }
490
491 template <typename Int> FMT_CONSTEXPR20 bigint& operator*=(Int value) {
492 FMT_ASSERT(value > 0, "");
493 multiply(uint32_or_64_or_128_t<Int>(value));
494 return *this;
495 }
496
497 friend FMT_CONSTEXPR20 int compare(const bigint& lhs, const bigint& rhs) {
498 int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits();
499 if (num_lhs_bigits != num_rhs_bigits)
500 return num_lhs_bigits > num_rhs_bigits ? 1 : -1;
501 int i = static_cast<int>(lhs.bigits_.size()) - 1;
502 int j = static_cast<int>(rhs.bigits_.size()) - 1;
503 int end = i - j;
504 if (end < 0) end = 0;
505 for (; i >= end; --i, --j) {
506 bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j];
507 if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1;
508 }
509 if (i != j) return i > j ? 1 : -1;
510 return 0;
511 }
512
513 // Returns compare(lhs1 + lhs2, rhs).
514 friend FMT_CONSTEXPR20 int add_compare(const bigint& lhs1, const bigint& lhs2,
515 const bigint& rhs) {
516 int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits());
517 int num_rhs_bigits = rhs.num_bigits();
518 if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;
519 if (max_lhs_bigits > num_rhs_bigits) return 1;
520 auto get_bigit = [](const bigint& n, int i) -> bigit {
521 return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0;
522 };
523 double_bigit borrow = 0;
524 int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_);
525 for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {
526 double_bigit sum =
527 static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i);
528 bigit rhs_bigit = get_bigit(rhs, i);
529 if (sum > rhs_bigit + borrow) return 1;
530 borrow = rhs_bigit + borrow - sum;
531 if (borrow > 1) return -1;
532 borrow <<= bigit_bits;
533 }
534 return borrow != 0 ? -1 : 0;
535 }
536
537 // Assigns pow(10, exp) to this bigint.
538 FMT_CONSTEXPR20 void assign_pow10(int exp) {
539 FMT_ASSERT(exp >= 0, "");
540 if (exp == 0) return assign(1);
541 // Find the top bit.
542 int bitmask = 1;
543 while (exp >= bitmask) bitmask <<= 1;
544 bitmask >>= 1;
545 // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by
546 // repeated squaring and multiplication.
547 assign(5);
548 bitmask >>= 1;
549 while (bitmask != 0) {
550 square();
551 if ((exp & bitmask) != 0) *this *= 5;
552 bitmask >>= 1;
553 }
554 *this <<= exp; // Multiply by pow(2, exp) by shifting.
555 }
556
557 FMT_CONSTEXPR20 void square() {
558 int num_bigits = static_cast<int>(bigits_.size());
559 int num_result_bigits = 2 * num_bigits;
560 basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));
561 bigits_.resize(to_unsigned(num_result_bigits));
562 using accumulator_t = conditional_t<FMT_USE_INT128, uint128_t, accumulator>;
563 auto sum = accumulator_t();
564 for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {
565 // Compute bigit at position bigit_index of the result by adding
566 // cross-product terms n[i] * n[j] such that i + j == bigit_index.
567 for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {
568 // Most terms are multiplied twice which can be optimized in the future.
569 sum += static_cast<double_bigit>(n[i]) * n[j];
570 }
571 (*this)[bigit_index] = static_cast<bigit>(sum);
572 sum >>= bits<bigit>::value; // Compute the carry.
573 }
574 // Do the same for the top half.
575 for (int bigit_index = num_bigits; bigit_index < num_result_bigits;
576 ++bigit_index) {
577 for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)
578 sum += static_cast<double_bigit>(n[i++]) * n[j--];
579 (*this)[bigit_index] = static_cast<bigit>(sum);
580 sum >>= bits<bigit>::value;
581 }
582 remove_leading_zeros();
583 exp_ *= 2;
584 }
585
586 // If this bigint has a bigger exponent than other, adds trailing zero to make
587 // exponents equal. This simplifies some operations such as subtraction.
588 FMT_CONSTEXPR20 void align(const bigint& other) {
589 int exp_difference = exp_ - other.exp_;
590 if (exp_difference <= 0) return;
591 int num_bigits = static_cast<int>(bigits_.size());
592 bigits_.resize(to_unsigned(num_bigits + exp_difference));
593 for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)
594 bigits_[j] = bigits_[i];
595 std::uninitialized_fill_n(bigits_.data(), exp_difference, 0);
596 exp_ -= exp_difference;
597 }
598
599 // Divides this bignum by divisor, assigning the remainder to this and
600 // returning the quotient.
601 FMT_CONSTEXPR20 int divmod_assign(const bigint& divisor) {
602 FMT_ASSERT(this != &divisor, "");
603 if (compare(*this, divisor) < 0) return 0;
604 FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, "");
605 align(divisor);
606 int quotient = 0;
607 do {
608 subtract_aligned(divisor);
609 ++quotient;
610 } while (compare(*this, divisor) >= 0);
611 return quotient;
612 }
613 };
614
615 enum class round_direction { unknown, up, down };
616
617 // Given the divisor (normally a power of 10), the remainder = v % divisor for
618 // some number v and the error, returns whether v should be rounded up, down, or
619 // whether the rounding direction can't be determined due to error.
620 // error should be less than divisor / 2.
621 FMT_CONSTEXPR inline round_direction get_round_direction(uint64_t divisor,
622 uint64_t remainder,
623 uint64_t error) {
624 FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow.
625 FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow.
626 FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow.
627 // Round down if (remainder + error) * 2 <= divisor.
628 if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2)
629 return round_direction::down;
630 // Round up if (remainder - error) * 2 >= divisor.
631 if (remainder >= error &&
632 remainder - error >= divisor - (remainder - error)) {
633 return round_direction::up;
634 }
635 return round_direction::unknown;
636 }
637
638 namespace digits {
639 enum result {
640 more, // Generate more digits.
641 done, // Done generating digits.
642 error // Digit generation cancelled due to an error.
643 };
644 }
645
646 struct gen_digits_handler {
647 char* buf;
648 int size;
649 int precision;
650 int exp10;
651 bool fixed;
652
653 FMT_CONSTEXPR digits::result on_digit(char digit, uint64_t divisor,
654 uint64_t remainder, uint64_t error,
655 bool integral) {
656 FMT_ASSERT(remainder < divisor, "");
657 buf[size++] = digit;
658 if (!integral && error >= remainder) return digits::error;
659 if (size < precision) return digits::more;
660 if (!integral) {
661 // Check if error * 2 < divisor with overflow prevention.
662 // The check is not needed for the integral part because error = 1
663 // and divisor > (1 << 32) there.
664 if (error >= divisor || error >= divisor - error) return digits::error;
665 } else {
666 FMT_ASSERT(error == 1 && divisor > 2, "");
667 }
668 auto dir = get_round_direction(divisor, remainder, error);
669 if (dir != round_direction::up)
670 return dir == round_direction::down ? digits::done : digits::error;
671 ++buf[size - 1];
672 for (int i = size - 1; i > 0 && buf[i] > '9'; --i) {
673 buf[i] = '0';
674 ++buf[i - 1];
675 }
676 if (buf[0] > '9') {
677 buf[0] = '1';
678 if (fixed)
679 buf[size++] = '0';
680 else
681 ++exp10;
682 }
683 return digits::done;
684 }
685 };
686
687 // Generates output using the Grisu digit-gen algorithm.
688 // error: the size of the region (lower, upper) outside of which numbers
689 // definitely do not round to value (Delta in Grisu3).
690 FMT_INLINE FMT_CONSTEXPR20 digits::result grisu_gen_digits(
691 fp value, uint64_t error, int& exp, gen_digits_handler& handler) {
692 const fp one(1ULL << -value.e, value.e);
693 // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be
694 // zero because it contains a product of two 64-bit numbers with MSB set (due
695 // to normalization) - 1, shifted right by at most 60 bits.
696 auto integral = static_cast<uint32_t>(value.f >> -one.e);
697 FMT_ASSERT(integral != 0, "");
698 FMT_ASSERT(integral == value.f >> -one.e, "");
699 // The fractional part of scaled value (p2 in Grisu) c = value % one.
700 uint64_t fractional = value.f & (one.f - 1);
701 exp = count_digits(integral); // kappa in Grisu.
702 // Non-fixed formats require at least one digit and no precision adjustment.
703 if (handler.fixed) {
704 // Adjust fixed precision by exponent because it is relative to decimal
705 // point.
706 int precision_offset = exp + handler.exp10;
707 if (precision_offset > 0 &&
708 handler.precision > max_value<int>() - precision_offset) {
709 FMT_THROW(format_error("number is too big"));
710 }
711 handler.precision += precision_offset;
712 // Check if precision is satisfied just by leading zeros, e.g.
713 // format("{:.2f}", 0.001) gives "0.00" without generating any digits.
714 if (handler.precision <= 0) {
715 if (handler.precision < 0) return digits::done;
716 // Divide by 10 to prevent overflow.
717 uint64_t divisor = impl_data::power_of_10_64[exp - 1] << -one.e;
718 auto dir = get_round_direction(divisor, value.f / 10, error * 10);
719 if (dir == round_direction::unknown) return digits::error;
720 handler.buf[handler.size++] = dir == round_direction::up ? '1' : '0';
721 return digits::done;
722 }
723 }
724 // Generate digits for the integral part. This can produce up to 10 digits.
725 do {
726 uint32_t digit = 0;
727 auto divmod_integral = [&](uint32_t divisor) {
728 digit = integral / divisor;
729 integral %= divisor;
730 };
731 // This optimization by Milo Yip reduces the number of integer divisions by
732 // one per iteration.
733 switch (exp) {
734 case 10:
735 divmod_integral(1000000000);
736 break;
737 case 9:
738 divmod_integral(100000000);
739 break;
740 case 8:
741 divmod_integral(10000000);
742 break;
743 case 7:
744 divmod_integral(1000000);
745 break;
746 case 6:
747 divmod_integral(100000);
748 break;
749 case 5:
750 divmod_integral(10000);
751 break;
752 case 4:
753 divmod_integral(1000);
754 break;
755 case 3:
756 divmod_integral(100);
757 break;
758 case 2:
759 divmod_integral(10);
760 break;
761 case 1:
762 digit = integral;
763 integral = 0;
764 break;
765 default:
766 FMT_ASSERT(false, "invalid number of digits");
767 }
768 --exp;
769 auto remainder = (static_cast<uint64_t>(integral) << -one.e) + fractional;
770 auto result = handler.on_digit(static_cast<char>('0' + digit),
771 impl_data::power_of_10_64[exp] << -one.e,
772 remainder, error, true);
773 if (result != digits::more) return result;
774 } while (exp > 0);
775 // Generate digits for the fractional part.
776 for (;;) {
777 fractional *= 10;
778 error *= 10;
779 char digit = static_cast<char>('0' + (fractional >> -one.e));
780 fractional &= one.f - 1;
781 --exp;
782 auto result = handler.on_digit(digit, one.f, fractional, error, false);
783 if (result != digits::more) return result;
784 }
785 }
786
787 // A 128-bit integer type used internally,
788 struct uint128_wrapper {
789 uint128_wrapper() = default;
790
791 #if FMT_USE_INT128
792 uint128_t internal_;
793
794 constexpr uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT
795 : internal_{static_cast<uint128_t>(low) |
796 (static_cast<uint128_t>(high) << 64)} {}
797
798 constexpr uint128_wrapper(uint128_t u) : internal_{u} {}
799
800 constexpr uint64_t high() const FMT_NOEXCEPT {
801 return uint64_t(internal_ >> 64);
802 }
803 constexpr uint64_t low() const FMT_NOEXCEPT { return uint64_t(internal_); }
804
805 uint128_wrapper& operator+=(uint64_t n) FMT_NOEXCEPT {
806 internal_ += n;
807 return *this;
808 }
809 #else
810 uint64_t high_;
811 uint64_t low_;
812
813 constexpr uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT
814 : high_{high},
815 low_{low} {}
816
817 constexpr uint64_t high() const FMT_NOEXCEPT { return high_; }
818 constexpr uint64_t low() const FMT_NOEXCEPT { return low_; }
819
820 uint128_wrapper& operator+=(uint64_t n) FMT_NOEXCEPT {
821 # if defined(_MSC_VER) && defined(_M_X64)
822 unsigned char carry = _addcarry_u64(0, low_, n, &low_);
823 _addcarry_u64(carry, high_, 0, &high_);
824 return *this;
825 # else
826 uint64_t sum = low_ + n;
827 high_ += (sum < low_ ? 1 : 0);
828 low_ = sum;
829 return *this;
830 # endif
831 }
832 #endif
833 };
834
835 // Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox.
836 namespace dragonbox {
837 // Computes 128-bit result of multiplication of two 64-bit unsigned integers.
838 inline uint128_wrapper umul128(uint64_t x, uint64_t y) FMT_NOEXCEPT {
839 #if FMT_USE_INT128
840 return static_cast<uint128_t>(x) * static_cast<uint128_t>(y);
841 #elif defined(_MSC_VER) && defined(_M_X64)
842 uint128_wrapper result;
843 result.low_ = _umul128(x, y, &result.high_);
844 return result;
845 #else
846 const uint64_t mask = (uint64_t(1) << 32) - uint64_t(1);
847
848 uint64_t a = x >> 32;
849 uint64_t b = x & mask;
850 uint64_t c = y >> 32;
851 uint64_t d = y & mask;
852
853 uint64_t ac = a * c;
854 uint64_t bc = b * c;
855 uint64_t ad = a * d;
856 uint64_t bd = b * d;
857
858 uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask);
859
860 return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32),
861 (intermediate << 32) + (bd & mask)};
862 #endif
863 }
864
865 // Computes upper 64 bits of multiplication of two 64-bit unsigned integers.
866 inline uint64_t umul128_upper64(uint64_t x, uint64_t y) FMT_NOEXCEPT {
867 #if FMT_USE_INT128
868 auto p = static_cast<uint128_t>(x) * static_cast<uint128_t>(y);
869 return static_cast<uint64_t>(p >> 64);
870 #elif defined(_MSC_VER) && defined(_M_X64)
871 return __umulh(x, y);
872 #else
873 return umul128(x, y).high();
874 #endif
875 }
876
877 // Computes upper 64 bits of multiplication of a 64-bit unsigned integer and a
878 // 128-bit unsigned integer.
879 inline uint64_t umul192_upper64(uint64_t x, uint128_wrapper y) FMT_NOEXCEPT {
880 uint128_wrapper g0 = umul128(x, y.high());
881 g0 += umul128_upper64(x, y.low());
882 return g0.high();
883 }
884
885 // Computes upper 32 bits of multiplication of a 32-bit unsigned integer and a
886 // 64-bit unsigned integer.
887 inline uint32_t umul96_upper32(uint32_t x, uint64_t y) FMT_NOEXCEPT {
888 return static_cast<uint32_t>(umul128_upper64(x, y));
889 }
890
891 // Computes middle 64 bits of multiplication of a 64-bit unsigned integer and a
892 // 128-bit unsigned integer.
893 inline uint64_t umul192_middle64(uint64_t x, uint128_wrapper y) FMT_NOEXCEPT {
894 uint64_t g01 = x * y.high();
895 uint64_t g10 = umul128_upper64(x, y.low());
896 return g01 + g10;
897 }
898
899 // Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a
900 // 64-bit unsigned integer.
901 inline uint64_t umul96_lower64(uint32_t x, uint64_t y) FMT_NOEXCEPT {
902 return x * y;
903 }
904
905 // Computes floor(log10(pow(2, e))) for e in [-1700, 1700] using the method from
906 // https://fmt.dev/papers/Grisu-Exact.pdf#page=5, section 3.4.
907 inline int floor_log10_pow2(int e) FMT_NOEXCEPT {
908 FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent");
909 const int shift = 22;
910 return (e * static_cast<int>(log10_2_significand >> (64 - shift))) >> shift;
911 }
912
913 // Various fast log computations.
914 inline int floor_log2_pow10(int e) FMT_NOEXCEPT {
915 FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent");
916 const uint64_t log2_10_integer_part = 3;
917 const uint64_t log2_10_fractional_digits = 0x5269e12f346e2bf9;
918 const int shift_amount = 19;
919 return (e * static_cast<int>(
920 (log2_10_integer_part << shift_amount) |
921 (log2_10_fractional_digits >> (64 - shift_amount)))) >>
922 shift_amount;
923 }
924 inline int floor_log10_pow2_minus_log10_4_over_3(int e) FMT_NOEXCEPT {
925 FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent");
926 const uint64_t log10_4_over_3_fractional_digits = 0x1ffbfc2bbc780375;
927 const int shift_amount = 22;
928 return (e * static_cast<int>(log10_2_significand >> (64 - shift_amount)) -
929 static_cast<int>(log10_4_over_3_fractional_digits >>
930 (64 - shift_amount))) >>
931 shift_amount;
932 }
933
934 // Returns true iff x is divisible by pow(2, exp).
935 inline bool divisible_by_power_of_2(uint32_t x, int exp) FMT_NOEXCEPT {
936 FMT_ASSERT(exp >= 1, "");
937 FMT_ASSERT(x != 0, "");
938 #ifdef FMT_BUILTIN_CTZ
939 return FMT_BUILTIN_CTZ(x) >= exp;
940 #else
941 return exp < num_bits<uint32_t>() && x == ((x >> exp) << exp);
942 #endif
943 }
944 inline bool divisible_by_power_of_2(uint64_t x, int exp) FMT_NOEXCEPT {
945 FMT_ASSERT(exp >= 1, "");
946 FMT_ASSERT(x != 0, "");
947 #ifdef FMT_BUILTIN_CTZLL
948 return FMT_BUILTIN_CTZLL(x) >= exp;
949 #else
950 return exp < num_bits<uint64_t>() && x == ((x >> exp) << exp);
951 #endif
952 }
953
954 // Table entry type for divisibility test.
955 template <typename T> struct divtest_table_entry {
956 T mod_inv;
957 T max_quotient;
958 };
959
960 // Returns true iff x is divisible by pow(5, exp).
961 inline bool divisible_by_power_of_5(uint32_t x, int exp) FMT_NOEXCEPT {
962 FMT_ASSERT(exp <= 10, "too large exponent");
963 static constexpr const divtest_table_entry<uint32_t> divtest_table[] = {
964 {0x00000001, 0xffffffff}, {0xcccccccd, 0x33333333},
965 {0xc28f5c29, 0x0a3d70a3}, {0x26e978d5, 0x020c49ba},
966 {0x3afb7e91, 0x0068db8b}, {0x0bcbe61d, 0x0014f8b5},
967 {0x68c26139, 0x000431bd}, {0xae8d46a5, 0x0000d6bf},
968 {0x22e90e21, 0x00002af3}, {0x3a2e9c6d, 0x00000897},
969 {0x3ed61f49, 0x000001b7}};
970 return x * divtest_table[exp].mod_inv <= divtest_table[exp].max_quotient;
971 }
972 inline bool divisible_by_power_of_5(uint64_t x, int exp) FMT_NOEXCEPT {
973 FMT_ASSERT(exp <= 23, "too large exponent");
974 static constexpr const divtest_table_entry<uint64_t> divtest_table[] = {
975 {0x0000000000000001, 0xffffffffffffffff},
976 {0xcccccccccccccccd, 0x3333333333333333},
977 {0x8f5c28f5c28f5c29, 0x0a3d70a3d70a3d70},
978 {0x1cac083126e978d5, 0x020c49ba5e353f7c},
979 {0xd288ce703afb7e91, 0x0068db8bac710cb2},
980 {0x5d4e8fb00bcbe61d, 0x0014f8b588e368f0},
981 {0x790fb65668c26139, 0x000431bde82d7b63},
982 {0xe5032477ae8d46a5, 0x0000d6bf94d5e57a},
983 {0xc767074b22e90e21, 0x00002af31dc46118},
984 {0x8e47ce423a2e9c6d, 0x0000089705f4136b},
985 {0x4fa7f60d3ed61f49, 0x000001b7cdfd9d7b},
986 {0x0fee64690c913975, 0x00000057f5ff85e5},
987 {0x3662e0e1cf503eb1, 0x000000119799812d},
988 {0xa47a2cf9f6433fbd, 0x0000000384b84d09},
989 {0x54186f653140a659, 0x00000000b424dc35},
990 {0x7738164770402145, 0x0000000024075f3d},
991 {0xe4a4d1417cd9a041, 0x000000000734aca5},
992 {0xc75429d9e5c5200d, 0x000000000170ef54},
993 {0xc1773b91fac10669, 0x000000000049c977},
994 {0x26b172506559ce15, 0x00000000000ec1e4},
995 {0xd489e3a9addec2d1, 0x000000000002f394},
996 {0x90e860bb892c8d5d, 0x000000000000971d},
997 {0x502e79bf1b6f4f79, 0x0000000000001e39},
998 {0xdcd618596be30fe5, 0x000000000000060b}};
999 return x * divtest_table[exp].mod_inv <= divtest_table[exp].max_quotient;
1000 }
1001
1002 // Replaces n by floor(n / pow(5, N)) returning true if and only if n is
1003 // divisible by pow(5, N).
1004 // Precondition: n <= 2 * pow(5, N + 1).
1005 template <int N>
1006 bool check_divisibility_and_divide_by_pow5(uint32_t& n) FMT_NOEXCEPT {
1007 static constexpr struct {
1008 uint32_t magic_number;
1009 int bits_for_comparison;
1010 uint32_t threshold;
1011 int shift_amount;
1012 } infos[] = {{0xcccd, 16, 0x3333, 18}, {0xa429, 8, 0x0a, 20}};
1013 constexpr auto info = infos[N - 1];
1014 n *= info.magic_number;
1015 const uint32_t comparison_mask = (1u << info.bits_for_comparison) - 1;
1016 bool result = (n & comparison_mask) <= info.threshold;
1017 n >>= info.shift_amount;
1018 return result;
1019 }
1020
1021 // Computes floor(n / pow(10, N)) for small n and N.
1022 // Precondition: n <= pow(10, N + 1).
1023 template <int N> uint32_t small_division_by_pow10(uint32_t n) FMT_NOEXCEPT {
1024 static constexpr struct {
1025 uint32_t magic_number;
1026 int shift_amount;
1027 uint32_t divisor_times_10;
1028 } infos[] = {{0xcccd, 19, 100}, {0xa3d8, 22, 1000}};
1029 constexpr auto info = infos[N - 1];
1030 FMT_ASSERT(n <= info.divisor_times_10, "n is too large");
1031 return n * info.magic_number >> info.shift_amount;
1032 }
1033
1034 // Computes floor(n / 10^(kappa + 1)) (float)
1035 inline uint32_t divide_by_10_to_kappa_plus_1(uint32_t n) FMT_NOEXCEPT {
1036 return n / float_info<float>::big_divisor;
1037 }
1038 // Computes floor(n / 10^(kappa + 1)) (double)
1039 inline uint64_t divide_by_10_to_kappa_plus_1(uint64_t n) FMT_NOEXCEPT {
1040 return umul128_upper64(n, 0x83126e978d4fdf3c) >> 9;
1041 }
1042
1043 // Various subroutines using pow10 cache
1044 template <class T> struct cache_accessor;
1045
1046 template <> struct cache_accessor<float> {
1047 using carrier_uint = float_info<float>::carrier_uint;
1048 using cache_entry_type = uint64_t;
1049
1050 static uint64_t get_cached_power(int k) FMT_NOEXCEPT {
1051 FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k,
1052 "k is out of range");
1053 static constexpr const uint64_t pow10_significands[] = {
1054 0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f,
1055 0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb,
1056 0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28,
1057 0xf1c90080baf72cb2, 0x971da05074da7bef, 0xbce5086492111aeb,
1058 0xec1e4a7db69561a6, 0x9392ee8e921d5d08, 0xb877aa3236a4b44a,
1059 0xe69594bec44de15c, 0x901d7cf73ab0acda, 0xb424dc35095cd810,
1060 0xe12e13424bb40e14, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff,
1061 0xdbe6fecebdedd5bf, 0x89705f4136b4a598, 0xabcc77118461cefd,
1062 0xd6bf94d5e57a42bd, 0x8637bd05af6c69b6, 0xa7c5ac471b478424,
1063 0xd1b71758e219652c, 0x83126e978d4fdf3c, 0xa3d70a3d70a3d70b,
1064 0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000,
1065 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000,
1066 0xc350000000000000, 0xf424000000000000, 0x9896800000000000,
1067 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000,
1068 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000,
1069 0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000,
1070 0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000,
1071 0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000,
1072 0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0,
1073 0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940984,
1074 0xa18f07d736b90be5, 0xc9f2c9cd04674ede, 0xfc6f7c4045812296,
1075 0x9dc5ada82b70b59d, 0xc5371912364ce305, 0xf684df56c3e01bc6,
1076 0x9a130b963a6c115c, 0xc097ce7bc90715b3, 0xf0bdc21abb48db20,
1077 0x96769950b50d88f4, 0xbc143fa4e250eb31, 0xeb194f8e1ae525fd,
1078 0x92efd1b8d0cf37be, 0xb7abc627050305ad, 0xe596b7b0c643c719,
1079 0x8f7e32ce7bea5c6f, 0xb35dbf821ae4f38b, 0xe0352f62a19e306e};
1080 return pow10_significands[k - float_info<float>::min_k];
1081 }
1082
1083 static carrier_uint compute_mul(carrier_uint u,
1084 const cache_entry_type& cache) FMT_NOEXCEPT {
1085 return umul96_upper32(u, cache);
1086 }
1087
1088 static uint32_t compute_delta(const cache_entry_type& cache,
1089 int beta_minus_1) FMT_NOEXCEPT {
1090 return static_cast<uint32_t>(cache >> (64 - 1 - beta_minus_1));
1091 }
1092
1093 static bool compute_mul_parity(carrier_uint two_f,
1094 const cache_entry_type& cache,
1095 int beta_minus_1) FMT_NOEXCEPT {
1096 FMT_ASSERT(beta_minus_1 >= 1, "");
1097 FMT_ASSERT(beta_minus_1 < 64, "");
1098
1099 return ((umul96_lower64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0;
1100 }
1101
1102 static carrier_uint compute_left_endpoint_for_shorter_interval_case(
1103 const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
1104 return static_cast<carrier_uint>(
1105 (cache - (cache >> (float_info<float>::significand_bits + 2))) >>
1106 (64 - float_info<float>::significand_bits - 1 - beta_minus_1));
1107 }
1108
1109 static carrier_uint compute_right_endpoint_for_shorter_interval_case(
1110 const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
1111 return static_cast<carrier_uint>(
1112 (cache + (cache >> (float_info<float>::significand_bits + 1))) >>
1113 (64 - float_info<float>::significand_bits - 1 - beta_minus_1));
1114 }
1115
1116 static carrier_uint compute_round_up_for_shorter_interval_case(
1117 const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
1118 return (static_cast<carrier_uint>(
1119 cache >>
1120 (64 - float_info<float>::significand_bits - 2 - beta_minus_1)) +
1121 1) /
1122 2;
1123 }
1124 };
1125
1126 template <> struct cache_accessor<double> {
1127 using carrier_uint = float_info<double>::carrier_uint;
1128 using cache_entry_type = uint128_wrapper;
1129
1130 static uint128_wrapper get_cached_power(int k) FMT_NOEXCEPT {
1131 FMT_ASSERT(k >= float_info<double>::min_k && k <= float_info<double>::max_k,
1132 "k is out of range");
1133
1134 static constexpr const uint128_wrapper pow10_significands[] = {
1135 #if FMT_USE_FULL_CACHE_DRAGONBOX
1136 {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
1137 {0x9faacf3df73609b1, 0x77b191618c54e9ad},
1138 {0xc795830d75038c1d, 0xd59df5b9ef6a2418},
1139 {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e},
1140 {0x9becce62836ac577, 0x4ee367f9430aec33},
1141 {0xc2e801fb244576d5, 0x229c41f793cda740},
1142 {0xf3a20279ed56d48a, 0x6b43527578c11110},
1143 {0x9845418c345644d6, 0x830a13896b78aaaa},
1144 {0xbe5691ef416bd60c, 0x23cc986bc656d554},
1145 {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9},
1146 {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa},
1147 {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54},
1148 {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69},
1149 {0x91376c36d99995be, 0x23100809b9c21fa2},
1150 {0xb58547448ffffb2d, 0xabd40a0c2832a78b},
1151 {0xe2e69915b3fff9f9, 0x16c90c8f323f516d},
1152 {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4},
1153 {0xb1442798f49ffb4a, 0x99cd11cfdf41779d},
1154 {0xdd95317f31c7fa1d, 0x40405643d711d584},
1155 {0x8a7d3eef7f1cfc52, 0x482835ea666b2573},
1156 {0xad1c8eab5ee43b66, 0xda3243650005eed0},
1157 {0xd863b256369d4a40, 0x90bed43e40076a83},
1158 {0x873e4f75e2224e68, 0x5a7744a6e804a292},
1159 {0xa90de3535aaae202, 0x711515d0a205cb37},
1160 {0xd3515c2831559a83, 0x0d5a5b44ca873e04},
1161 {0x8412d9991ed58091, 0xe858790afe9486c3},
1162 {0xa5178fff668ae0b6, 0x626e974dbe39a873},
1163 {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},
1164 {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a},
1165 {0xa139029f6a239f72, 0x1c1fffc1ebc44e81},
1166 {0xc987434744ac874e, 0xa327ffb266b56221},
1167 {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9},
1168 {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa},
1169 {0xc4ce17b399107c22, 0xcb550fb4384d21d4},
1170 {0xf6019da07f549b2b, 0x7e2a53a146606a49},
1171 {0x99c102844f94e0fb, 0x2eda7444cbfc426e},
1172 {0xc0314325637a1939, 0xfa911155fefb5309},
1173 {0xf03d93eebc589f88, 0x793555ab7eba27cb},
1174 {0x96267c7535b763b5, 0x4bc1558b2f3458df},
1175 {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17},
1176 {0xea9c227723ee8bcb, 0x465e15a979c1cadd},
1177 {0x92a1958a7675175f, 0x0bfacd89ec191eca},
1178 {0xb749faed14125d36, 0xcef980ec671f667c},
1179 {0xe51c79a85916f484, 0x82b7e12780e7401b},
1180 {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811},
1181 {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16},
1182 {0xdfbdcece67006ac9, 0x67a791e093e1d49b},
1183 {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1},
1184 {0xaecc49914078536d, 0x58fae9f773886e19},
1185 {0xda7f5bf590966848, 0xaf39a475506a899f},
1186 {0x888f99797a5e012d, 0x6d8406c952429604},
1187 {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84},
1188 {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65},
1189 {0x855c3be0a17fcd26, 0x5cf2eea09a550680},
1190 {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},
1191 {0xd0601d8efc57b08b, 0xf13b94daf124da27},
1192 {0x823c12795db6ce57, 0x76c53d08d6b70859},
1193 {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f},
1194 {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a},
1195 {0xfe5d54150b090b02, 0xd3f93b35435d7c4d},
1196 {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0},
1197 {0xc6b8e9b0709f109a, 0x359ab6419ca1091c},
1198 {0xf867241c8cc6d4c0, 0xc30163d203c94b63},
1199 {0x9b407691d7fc44f8, 0x79e0de63425dcf1e},
1200 {0xc21094364dfb5636, 0x985915fc12f542e5},
1201 {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e},
1202 {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43},
1203 {0xbd8430bd08277231, 0x50c6ff782a838354},
1204 {0xece53cec4a314ebd, 0xa4f8bf5635246429},
1205 {0x940f4613ae5ed136, 0x871b7795e136be9a},
1206 {0xb913179899f68584, 0x28e2557b59846e40},
1207 {0xe757dd7ec07426e5, 0x331aeada2fe589d0},
1208 {0x9096ea6f3848984f, 0x3ff0d2c85def7622},
1209 {0xb4bca50b065abe63, 0x0fed077a756b53aa},
1210 {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895},
1211 {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d},
1212 {0xb080392cc4349dec, 0xbd8d794d96aacfb4},
1213 {0xdca04777f541c567, 0xecf0d7a0fc5583a1},
1214 {0x89e42caaf9491b60, 0xf41686c49db57245},
1215 {0xac5d37d5b79b6239, 0x311c2875c522ced6},
1216 {0xd77485cb25823ac7, 0x7d633293366b828c},
1217 {0x86a8d39ef77164bc, 0xae5dff9c02033198},
1218 {0xa8530886b54dbdeb, 0xd9f57f830283fdfd},
1219 {0xd267caa862a12d66, 0xd072df63c324fd7c},
1220 {0x8380dea93da4bc60, 0x4247cb9e59f71e6e},
1221 {0xa46116538d0deb78, 0x52d9be85f074e609},
1222 {0xcd795be870516656, 0x67902e276c921f8c},
1223 {0x806bd9714632dff6, 0x00ba1cd8a3db53b7},
1224 {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5},
1225 {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce},
1226 {0xfad2a4b13d1b5d6c, 0x796b805720085f82},
1227 {0x9cc3a6eec6311a63, 0xcbe3303674053bb1},
1228 {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d},
1229 {0xf4f1b4d515acb93b, 0xee92fb5515482d45},
1230 {0x991711052d8bf3c5, 0x751bdd152d4d1c4b},
1231 {0xbf5cd54678eef0b6, 0xd262d45a78a0635e},
1232 {0xef340a98172aace4, 0x86fb897116c87c35},
1233 {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1},
1234 {0xbae0a846d2195712, 0x8974836059cca10a},
1235 {0xe998d258869facd7, 0x2bd1a438703fc94c},
1236 {0x91ff83775423cc06, 0x7b6306a34627ddd0},
1237 {0xb67f6455292cbf08, 0x1a3bc84c17b1d543},
1238 {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94},
1239 {0x8e938662882af53e, 0x547eb47b7282ee9d},
1240 {0xb23867fb2a35b28d, 0xe99e619a4f23aa44},
1241 {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5},
1242 {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05},
1243 {0xae0b158b4738705e, 0x9624ab50b148d446},
1244 {0xd98ddaee19068c76, 0x3badd624dd9b0958},
1245 {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7},
1246 {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d},
1247 {0xd47487cc8470652b, 0x7647c32000696720},
1248 {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074},
1249 {0xa5fb0a17c777cf09, 0xf468107100525891},
1250 {0xcf79cc9db955c2cc, 0x7182148d4066eeb5},
1251 {0x81ac1fe293d599bf, 0xc6f14cd848405531},
1252 {0xa21727db38cb002f, 0xb8ada00e5a506a7d},
1253 {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d},
1254 {0xfd442e4688bd304a, 0x908f4a166d1da664},
1255 {0x9e4a9cec15763e2e, 0x9a598e4e043287ff},
1256 {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe},
1257 {0xf7549530e188c128, 0xd12bee59e68ef47d},
1258 {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf},
1259 {0xc13a148e3032d6e7, 0xe36a52363c1faf02},
1260 {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2},
1261 {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba},
1262 {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8},
1263 {0xebdf661791d60f56, 0x111b495b3464ad22},
1264 {0x936b9fcebb25c995, 0xcab10dd900beec35},
1265 {0xb84687c269ef3bfb, 0x3d5d514f40eea743},
1266 {0xe65829b3046b0afa, 0x0cb4a5a3112a5113},
1267 {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac},
1268 {0xb3f4e093db73a093, 0x59ed216765690f57},
1269 {0xe0f218b8d25088b8, 0x306869c13ec3532d},
1270 {0x8c974f7383725573, 0x1e414218c73a13fc},
1271 {0xafbd2350644eeacf, 0xe5d1929ef90898fb},
1272 {0xdbac6c247d62a583, 0xdf45f746b74abf3a},
1273 {0x894bc396ce5da772, 0x6b8bba8c328eb784},
1274 {0xab9eb47c81f5114f, 0x066ea92f3f326565},
1275 {0xd686619ba27255a2, 0xc80a537b0efefebe},
1276 {0x8613fd0145877585, 0xbd06742ce95f5f37},
1277 {0xa798fc4196e952e7, 0x2c48113823b73705},
1278 {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6},
1279 {0x82ef85133de648c4, 0x9a984d73dbe722fc},
1280 {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb},
1281 {0xcc963fee10b7d1b3, 0x318df905079926a9},
1282 {0xffbbcfe994e5c61f, 0xfdf17746497f7053},
1283 {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634},
1284 {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1},
1285 {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1},
1286 {0x9c1661a651213e2d, 0x06bea10ca65c084f},
1287 {0xc31bfa0fe5698db8, 0x486e494fcff30a63},
1288 {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb},
1289 {0x986ddb5c6b3a76b7, 0xf89629465a75e01d},
1290 {0xbe89523386091465, 0xf6bbb397f1135824},
1291 {0xee2ba6c0678b597f, 0x746aa07ded582e2d},
1292 {0x94db483840b717ef, 0xa8c2a44eb4571cdd},
1293 {0xba121a4650e4ddeb, 0x92f34d62616ce414},
1294 {0xe896a0d7e51e1566, 0x77b020baf9c81d18},
1295 {0x915e2486ef32cd60, 0x0ace1474dc1d122f},
1296 {0xb5b5ada8aaff80b8, 0x0d819992132456bb},
1297 {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a},
1298 {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},
1299 {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3},
1300 {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf},
1301 {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c},
1302 {0xad4ab7112eb3929d, 0x86c16c98d2c953c7},
1303 {0xd89d64d57a607744, 0xe871c7bf077ba8b8},
1304 {0x87625f056c7c4a8b, 0x11471cd764ad4973},
1305 {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0},
1306 {0xd389b47879823479, 0x4aff1d108d4ec2c4},
1307 {0x843610cb4bf160cb, 0xcedf722a585139bb},
1308 {0xa54394fe1eedb8fe, 0xc2974eb4ee658829},
1309 {0xce947a3da6a9273e, 0x733d226229feea33},
1310 {0x811ccc668829b887, 0x0806357d5a3f5260},
1311 {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8},
1312 {0xc9bcff6034c13052, 0xfc89b393dd02f0b6},
1313 {0xfc2c3f3841f17c67, 0xbbac2078d443ace3},
1314 {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e},
1315 {0xc5029163f384a931, 0x0a9e795e65d4df12},
1316 {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6},
1317 {0x99ea0196163fa42e, 0x504bced1bf8e4e46},
1318 {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7},
1319 {0xf07da27a82c37088, 0x5d767327bb4e5a4d},
1320 {0x964e858c91ba2655, 0x3a6a07f8d510f870},
1321 {0xbbe226efb628afea, 0x890489f70a55368c},
1322 {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f},
1323 {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e},
1324 {0xb77ada0617e3bbcb, 0x09ce6ebb40173745},
1325 {0xe55990879ddcaabd, 0xcc420a6a101d0516},
1326 {0x8f57fa54c2a9eab6, 0x9fa946824a12232e},
1327 {0xb32df8e9f3546564, 0x47939822dc96abfa},
1328 {0xdff9772470297ebd, 0x59787e2b93bc56f8},
1329 {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b},
1330 {0xaefae51477a06b03, 0xede622920b6b23f2},
1331 {0xdab99e59958885c4, 0xe95fab368e45ecee},
1332 {0x88b402f7fd75539b, 0x11dbcb0218ebb415},
1333 {0xaae103b5fcd2a881, 0xd652bdc29f26a11a},
1334 {0xd59944a37c0752a2, 0x4be76d3346f04960},
1335 {0x857fcae62d8493a5, 0x6f70a4400c562ddc},
1336 {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953},
1337 {0xd097ad07a71f26b2, 0x7e2000a41346a7a8},
1338 {0x825ecc24c873782f, 0x8ed400668c0c28c9},
1339 {0xa2f67f2dfa90563b, 0x728900802f0f32fb},
1340 {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba},
1341 {0xfea126b7d78186bc, 0xe2f610c84987bfa9},
1342 {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca},
1343 {0xc6ede63fa05d3143, 0x91503d1c79720dbc},
1344 {0xf8a95fcf88747d94, 0x75a44c6397ce912b},
1345 {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb},
1346 {0xc24452da229b021b, 0xfbe85badce996169},
1347 {0xf2d56790ab41c2a2, 0xfae27299423fb9c4},
1348 {0x97c560ba6b0919a5, 0xdccd879fc967d41b},
1349 {0xbdb6b8e905cb600f, 0x5400e987bbc1c921},
1350 {0xed246723473e3813, 0x290123e9aab23b69},
1351 {0x9436c0760c86e30b, 0xf9a0b6720aaf6522},
1352 {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},
1353 {0xe7958cb87392c2c2, 0xb60b1d1230b20e05},
1354 {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3},
1355 {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4},
1356 {0xe2280b6c20dd5232, 0x25c6da63c38de1b1},
1357 {0x8d590723948a535f, 0x579c487e5a38ad0f},
1358 {0xb0af48ec79ace837, 0x2d835a9df0c6d852},
1359 {0xdcdb1b2798182244, 0xf8e431456cf88e66},
1360 {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900},
1361 {0xac8b2d36eed2dac5, 0xe272467e3d222f40},
1362 {0xd7adf884aa879177, 0x5b0ed81dcc6abb10},
1363 {0x86ccbb52ea94baea, 0x98e947129fc2b4ea},
1364 {0xa87fea27a539e9a5, 0x3f2398d747b36225},
1365 {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae},
1366 {0x83a3eeeef9153e89, 0x1953cf68300424ad},
1367 {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8},
1368 {0xcdb02555653131b6, 0x3792f412cb06794e},
1369 {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1},
1370 {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5},
1371 {0xc8de047564d20a8b, 0xf245825a5a445276},
1372 {0xfb158592be068d2e, 0xeed6e2f0f0d56713},
1373 {0x9ced737bb6c4183d, 0x55464dd69685606c},
1374 {0xc428d05aa4751e4c, 0xaa97e14c3c26b887},
1375 {0xf53304714d9265df, 0xd53dd99f4b3066a9},
1376 {0x993fe2c6d07b7fab, 0xe546a8038efe402a},
1377 {0xbf8fdb78849a5f96, 0xde98520472bdd034},
1378 {0xef73d256a5c0f77c, 0x963e66858f6d4441},
1379 {0x95a8637627989aad, 0xdde7001379a44aa9},
1380 {0xbb127c53b17ec159, 0x5560c018580d5d53},
1381 {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7},
1382 {0x9226712162ab070d, 0xcab3961304ca70e9},
1383 {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23},
1384 {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b},
1385 {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243},
1386 {0xb267ed1940f1c61c, 0x55f038b237591ed4},
1387 {0xdf01e85f912e37a3, 0x6b6c46dec52f6689},
1388 {0x8b61313bbabce2c6, 0x2323ac4b3b3da016},
1389 {0xae397d8aa96c1b77, 0xabec975e0a0d081b},
1390 {0xd9c7dced53c72255, 0x96e7bd358c904a22},
1391 {0x881cea14545c7575, 0x7e50d64177da2e55},
1392 {0xaa242499697392d2, 0xdde50bd1d5d0b9ea},
1393 {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865},
1394 {0x84ec3c97da624ab4, 0xbd5af13bef0b113f},
1395 {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f},
1396 {0xcfb11ead453994ba, 0x67de18eda5814af3},
1397 {0x81ceb32c4b43fcf4, 0x80eacf948770ced8},
1398 {0xa2425ff75e14fc31, 0xa1258379a94d028e},
1399 {0xcad2f7f5359a3b3e, 0x096ee45813a04331},
1400 {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd},
1401 {0x9e74d1b791e07e48, 0x775ea264cf55347e},
1402 {0xc612062576589dda, 0x95364afe032a819e},
1403 {0xf79687aed3eec551, 0x3a83ddbd83f52205},
1404 {0x9abe14cd44753b52, 0xc4926a9672793543},
1405 {0xc16d9a0095928a27, 0x75b7053c0f178294},
1406 {0xf1c90080baf72cb1, 0x5324c68b12dd6339},
1407 {0x971da05074da7bee, 0xd3f6fc16ebca5e04},
1408 {0xbce5086492111aea, 0x88f4bb1ca6bcf585},
1409 {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6},
1410 {0x9392ee8e921d5d07, 0x3aff322e62439fd0},
1411 {0xb877aa3236a4b449, 0x09befeb9fad487c3},
1412 {0xe69594bec44de15b, 0x4c2ebe687989a9b4},
1413 {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11},
1414 {0xb424dc35095cd80f, 0x538484c19ef38c95},
1415 {0xe12e13424bb40e13, 0x2865a5f206b06fba},
1416 {0x8cbccc096f5088cb, 0xf93f87b7442e45d4},
1417 {0xafebff0bcb24aafe, 0xf78f69a51539d749},
1418 {0xdbe6fecebdedd5be, 0xb573440e5a884d1c},
1419 {0x89705f4136b4a597, 0x31680a88f8953031},
1420 {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e},
1421 {0xd6bf94d5e57a42bc, 0x3d32907604691b4d},
1422 {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110},
1423 {0xa7c5ac471b478423, 0x0fcf80dc33721d54},
1424 {0xd1b71758e219652b, 0xd3c36113404ea4a9},
1425 {0x83126e978d4fdf3b, 0x645a1cac083126ea},
1426 {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4},
1427 {0xcccccccccccccccc, 0xcccccccccccccccd},
1428 {0x8000000000000000, 0x0000000000000000},
1429 {0xa000000000000000, 0x0000000000000000},
1430 {0xc800000000000000, 0x0000000000000000},
1431 {0xfa00000000000000, 0x0000000000000000},
1432 {0x9c40000000000000, 0x0000000000000000},
1433 {0xc350000000000000, 0x0000000000000000},
1434 {0xf424000000000000, 0x0000000000000000},
1435 {0x9896800000000000, 0x0000000000000000},
1436 {0xbebc200000000000, 0x0000000000000000},
1437 {0xee6b280000000000, 0x0000000000000000},
1438 {0x9502f90000000000, 0x0000000000000000},
1439 {0xba43b74000000000, 0x0000000000000000},
1440 {0xe8d4a51000000000, 0x0000000000000000},
1441 {0x9184e72a00000000, 0x0000000000000000},
1442 {0xb5e620f480000000, 0x0000000000000000},
1443 {0xe35fa931a0000000, 0x0000000000000000},
1444 {0x8e1bc9bf04000000, 0x0000000000000000},
1445 {0xb1a2bc2ec5000000, 0x0000000000000000},
1446 {0xde0b6b3a76400000, 0x0000000000000000},
1447 {0x8ac7230489e80000, 0x0000000000000000},
1448 {0xad78ebc5ac620000, 0x0000000000000000},
1449 {0xd8d726b7177a8000, 0x0000000000000000},
1450 {0x878678326eac9000, 0x0000000000000000},
1451 {0xa968163f0a57b400, 0x0000000000000000},
1452 {0xd3c21bcecceda100, 0x0000000000000000},
1453 {0x84595161401484a0, 0x0000000000000000},
1454 {0xa56fa5b99019a5c8, 0x0000000000000000},
1455 {0xcecb8f27f4200f3a, 0x0000000000000000},
1456 {0x813f3978f8940984, 0x4000000000000000},
1457 {0xa18f07d736b90be5, 0x5000000000000000},
1458 {0xc9f2c9cd04674ede, 0xa400000000000000},
1459 {0xfc6f7c4045812296, 0x4d00000000000000},
1460 {0x9dc5ada82b70b59d, 0xf020000000000000},
1461 {0xc5371912364ce305, 0x6c28000000000000},
1462 {0xf684df56c3e01bc6, 0xc732000000000000},
1463 {0x9a130b963a6c115c, 0x3c7f400000000000},
1464 {0xc097ce7bc90715b3, 0x4b9f100000000000},
1465 {0xf0bdc21abb48db20, 0x1e86d40000000000},
1466 {0x96769950b50d88f4, 0x1314448000000000},
1467 {0xbc143fa4e250eb31, 0x17d955a000000000},
1468 {0xeb194f8e1ae525fd, 0x5dcfab0800000000},
1469 {0x92efd1b8d0cf37be, 0x5aa1cae500000000},
1470 {0xb7abc627050305ad, 0xf14a3d9e40000000},
1471 {0xe596b7b0c643c719, 0x6d9ccd05d0000000},
1472 {0x8f7e32ce7bea5c6f, 0xe4820023a2000000},
1473 {0xb35dbf821ae4f38b, 0xdda2802c8a800000},
1474 {0xe0352f62a19e306e, 0xd50b2037ad200000},
1475 {0x8c213d9da502de45, 0x4526f422cc340000},
1476 {0xaf298d050e4395d6, 0x9670b12b7f410000},
1477 {0xdaf3f04651d47b4c, 0x3c0cdd765f114000},
1478 {0x88d8762bf324cd0f, 0xa5880a69fb6ac800},
1479 {0xab0e93b6efee0053, 0x8eea0d047a457a00},
1480 {0xd5d238a4abe98068, 0x72a4904598d6d880},
1481 {0x85a36366eb71f041, 0x47a6da2b7f864750},
1482 {0xa70c3c40a64e6c51, 0x999090b65f67d924},
1483 {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d},
1484 {0x82818f1281ed449f, 0xbff8f10e7a8921a4},
1485 {0xa321f2d7226895c7, 0xaff72d52192b6a0d},
1486 {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490},
1487 {0xfee50b7025c36a08, 0x02f236d04753d5b4},
1488 {0x9f4f2726179a2245, 0x01d762422c946590},
1489 {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5},
1490 {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2},
1491 {0x9b934c3b330c8577, 0x63cc55f49f88eb2f},
1492 {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb},
1493 {0xf316271c7fc3908a, 0x8bef464e3945ef7a},
1494 {0x97edd871cfda3a56, 0x97758bf0e3cbb5ac},
1495 {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317},
1496 {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd},
1497 {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a},
1498 {0xb975d6b6ee39e436, 0xb3e2fd538e122b44},
1499 {0xe7d34c64a9c85d44, 0x60dbbca87196b616},
1500 {0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd},
1501 {0xb51d13aea4a488dd, 0x6babab6398bdbe41},
1502 {0xe264589a4dcdab14, 0xc696963c7eed2dd1},
1503 {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2},
1504 {0xb0de65388cc8ada8, 0x3b25a55f43294bcb},
1505 {0xdd15fe86affad912, 0x49ef0eb713f39ebe},
1506 {0x8a2dbf142dfcc7ab, 0x6e3569326c784337},
1507 {0xacb92ed9397bf996, 0x49c2c37f07965404},
1508 {0xd7e77a8f87daf7fb, 0xdc33745ec97be906},
1509 {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3},
1510 {0xa8acd7c0222311bc, 0xc40832ea0d68ce0c},
1511 {0xd2d80db02aabd62b, 0xf50a3fa490c30190},
1512 {0x83c7088e1aab65db, 0x792667c6da79e0fa},
1513 {0xa4b8cab1a1563f52, 0x577001b891185938},
1514 {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86},
1515 {0x80b05e5ac60b6178, 0x544f8158315b05b4},
1516 {0xa0dc75f1778e39d6, 0x696361ae3db1c721},
1517 {0xc913936dd571c84c, 0x03bc3a19cd1e38e9},
1518 {0xfb5878494ace3a5f, 0x04ab48a04065c723},
1519 {0x9d174b2dcec0e47b, 0x62eb0d64283f9c76},
1520 {0xc45d1df942711d9a, 0x3ba5d0bd324f8394},
1521 {0xf5746577930d6500, 0xca8f44ec7ee36479},
1522 {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb},
1523 {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e},
1524 {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e},
1525 {0x95d04aee3b80ece5, 0xbba1f1d158724a12},
1526 {0xbb445da9ca61281f, 0x2a8a6e45ae8edc97},
1527 {0xea1575143cf97226, 0xf52d09d71a3293bd},
1528 {0x924d692ca61be758, 0x593c2626705f9c56},
1529 {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c},
1530 {0xe498f455c38b997a, 0x0b6dfb9c0f956447},
1531 {0x8edf98b59a373fec, 0x4724bd4189bd5eac},
1532 {0xb2977ee300c50fe7, 0x58edec91ec2cb657},
1533 {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed},
1534 {0x8b865b215899f46c, 0xbd79e0d20082ee74},
1535 {0xae67f1e9aec07187, 0xecd8590680a3aa11},
1536 {0xda01ee641a708de9, 0xe80e6f4820cc9495},
1537 {0x884134fe908658b2, 0x3109058d147fdcdd},
1538 {0xaa51823e34a7eede, 0xbd4b46f0599fd415},
1539 {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a},
1540 {0x850fadc09923329e, 0x03e2cf6bc604ddb0},
1541 {0xa6539930bf6bff45, 0x84db8346b786151c},
1542 {0xcfe87f7cef46ff16, 0xe612641865679a63},
1543 {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e},
1544 {0xa26da3999aef7749, 0xe3be5e330f38f09d},
1545 {0xcb090c8001ab551c, 0x5cadf5bfd3072cc5},
1546 {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6},
1547 {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa},
1548 {0xc646d63501a1511d, 0xb281e1fd541501b8},
1549 {0xf7d88bc24209a565, 0x1f225a7ca91a4226},
1550 {0x9ae757596946075f, 0x3375788de9b06958},
1551 {0xc1a12d2fc3978937, 0x0052d6b1641c83ae},
1552 {0xf209787bb47d6b84, 0xc0678c5dbd23a49a},
1553 {0x9745eb4d50ce6332, 0xf840b7ba963646e0},
1554 {0xbd176620a501fbff, 0xb650e5a93bc3d898},
1555 {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe},
1556 {0x93ba47c980e98cdf, 0xc66f336c36b10137},
1557 {0xb8a8d9bbe123f017, 0xb80b0047445d4184},
1558 {0xe6d3102ad96cec1d, 0xa60dc059157491e5},
1559 {0x9043ea1ac7e41392, 0x87c89837ad68db2f},
1560 {0xb454e4a179dd1877, 0x29babe4598c311fb},
1561 {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a},
1562 {0x8ce2529e2734bb1d, 0x1899e4a65f58660c},
1563 {0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f},
1564 {0xdc21a1171d42645d, 0x76707543f4fa1f73},
1565 {0x899504ae72497eba, 0x6a06494a791c53a8},
1566 {0xabfa45da0edbde69, 0x0487db9d17636892},
1567 {0xd6f8d7509292d603, 0x45a9d2845d3c42b6},
1568 {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2},
1569 {0xa7f26836f282b732, 0x8e6cac7768d7141e},
1570 {0xd1ef0244af2364ff, 0x3207d795430cd926},
1571 {0x8335616aed761f1f, 0x7f44e6bd49e807b8},
1572 {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6},
1573 {0xcd036837130890a1, 0x36dba887c37a8c0f},
1574 {0x802221226be55a64, 0xc2494954da2c9789},
1575 {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c},
1576 {0xc83553c5c8965d3d, 0x6f92829494e5acc7},
1577 {0xfa42a8b73abbf48c, 0xcb772339ba1f17f9},
1578 {0x9c69a97284b578d7, 0xff2a760414536efb},
1579 {0xc38413cf25e2d70d, 0xfef5138519684aba},
1580 {0xf46518c2ef5b8cd1, 0x7eb258665fc25d69},
1581 {0x98bf2f79d5993802, 0xef2f773ffbd97a61},
1582 {0xbeeefb584aff8603, 0xaafb550ffacfd8fa},
1583 {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38},
1584 {0x952ab45cfa97a0b2, 0xdd945a747bf26183},
1585 {0xba756174393d88df, 0x94f971119aeef9e4},
1586 {0xe912b9d1478ceb17, 0x7a37cd5601aab85d},
1587 {0x91abb422ccb812ee, 0xac62e055c10ab33a},
1588 {0xb616a12b7fe617aa, 0x577b986b314d6009},
1589 {0xe39c49765fdf9d94, 0xed5a7e85fda0b80b},
1590 {0x8e41ade9fbebc27d, 0x14588f13be847307},
1591 {0xb1d219647ae6b31c, 0x596eb2d8ae258fc8},
1592 {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb},
1593 {0x8aec23d680043bee, 0x25de7bb9480d5854},
1594 {0xada72ccc20054ae9, 0xaf561aa79a10ae6a},
1595 {0xd910f7ff28069da4, 0x1b2ba1518094da04},
1596 {0x87aa9aff79042286, 0x90fb44d2f05d0842},
1597 {0xa99541bf57452b28, 0x353a1607ac744a53},
1598 {0xd3fa922f2d1675f2, 0x42889b8997915ce8},
1599 {0x847c9b5d7c2e09b7, 0x69956135febada11},
1600 {0xa59bc234db398c25, 0x43fab9837e699095},
1601 {0xcf02b2c21207ef2e, 0x94f967e45e03f4bb},
1602 {0x8161afb94b44f57d, 0x1d1be0eebac278f5},
1603 {0xa1ba1ba79e1632dc, 0x6462d92a69731732},
1604 {0xca28a291859bbf93, 0x7d7b8f7503cfdcfe},
1605 {0xfcb2cb35e702af78, 0x5cda735244c3d43e},
1606 {0x9defbf01b061adab, 0x3a0888136afa64a7},
1607 {0xc56baec21c7a1916, 0x088aaa1845b8fdd0},
1608 {0xf6c69a72a3989f5b, 0x8aad549e57273d45},
1609 {0x9a3c2087a63f6399, 0x36ac54e2f678864b},
1610 {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd},
1611 {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5},
1612 {0x969eb7c47859e743, 0x9f644ae5a4b1b325},
1613 {0xbc4665b596706114, 0x873d5d9f0dde1fee},
1614 {0xeb57ff22fc0c7959, 0xa90cb506d155a7ea},
1615 {0x9316ff75dd87cbd8, 0x09a7f12442d588f2},
1616 {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb2f},
1617 {0xe5d3ef282a242e81, 0x8f1668c8a86da5fa},
1618 {0x8fa475791a569d10, 0xf96e017d694487bc},
1619 {0xb38d92d760ec4455, 0x37c981dcc395a9ac},
1620 {0xe070f78d3927556a, 0x85bbe253f47b1417},
1621 {0x8c469ab843b89562, 0x93956d7478ccec8e},
1622 {0xaf58416654a6babb, 0x387ac8d1970027b2},
1623 {0xdb2e51bfe9d0696a, 0x06997b05fcc0319e},
1624 {0x88fcf317f22241e2, 0x441fece3bdf81f03},
1625 {0xab3c2fddeeaad25a, 0xd527e81cad7626c3},
1626 {0xd60b3bd56a5586f1, 0x8a71e223d8d3b074},
1627 {0x85c7056562757456, 0xf6872d5667844e49},
1628 {0xa738c6bebb12d16c, 0xb428f8ac016561db},
1629 {0xd106f86e69d785c7, 0xe13336d701beba52},
1630 {0x82a45b450226b39c, 0xecc0024661173473},
1631 {0xa34d721642b06084, 0x27f002d7f95d0190},
1632 {0xcc20ce9bd35c78a5, 0x31ec038df7b441f4},
1633 {0xff290242c83396ce, 0x7e67047175a15271},
1634 {0x9f79a169bd203e41, 0x0f0062c6e984d386},
1635 {0xc75809c42c684dd1, 0x52c07b78a3e60868},
1636 {0xf92e0c3537826145, 0xa7709a56ccdf8a82},
1637 {0x9bbcc7a142b17ccb, 0x88a66076400bb691},
1638 {0xc2abf989935ddbfe, 0x6acff893d00ea435},
1639 {0xf356f7ebf83552fe, 0x0583f6b8c4124d43},
1640 {0x98165af37b2153de, 0xc3727a337a8b704a},
1641 {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c},
1642 {0xeda2ee1c7064130c, 0x1162def06f79df73},
1643 {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8},
1644 {0xb9a74a0637ce2ee1, 0x6d953e2bd7173692},
1645 {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437},
1646 {0x910ab1d4db9914a0, 0x1d9c9892400a22a2},
1647 {0xb54d5e4a127f59c8, 0x2503beb6d00cab4b},
1648 {0xe2a0b5dc971f303a, 0x2e44ae64840fd61d},
1649 {0x8da471a9de737e24, 0x5ceaecfed289e5d2},
1650 {0xb10d8e1456105dad, 0x7425a83e872c5f47},
1651 {0xdd50f1996b947518, 0xd12f124e28f77719},
1652 {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f},
1653 {0xace73cbfdc0bfb7b, 0x636cc64d1001550b},
1654 {0xd8210befd30efa5a, 0x3c47f7e05401aa4e},
1655 {0x8714a775e3e95c78, 0x65acfaec34810a71},
1656 {0xa8d9d1535ce3b396, 0x7f1839a741a14d0d},
1657 {0xd31045a8341ca07c, 0x1ede48111209a050},
1658 {0x83ea2b892091e44d, 0x934aed0aab460432},
1659 {0xa4e4b66b68b65d60, 0xf81da84d5617853f},
1660 {0xce1de40642e3f4b9, 0x36251260ab9d668e},
1661 {0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019},
1662 {0xa1075a24e4421730, 0xb24cf65b8612f81f},
1663 {0xc94930ae1d529cfc, 0xdee033f26797b627},
1664 {0xfb9b7cd9a4a7443c, 0x169840ef017da3b1},
1665 {0x9d412e0806e88aa5, 0x8e1f289560ee864e},
1666 {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2},
1667 {0xf5b5d7ec8acb58a2, 0xae10af696774b1db},
1668 {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29},
1669 {0xbff610b0cc6edd3f, 0x17fd090a58d32af3},
1670 {0xeff394dcff8a948e, 0xddfc4b4cef07f5b0},
1671 {0x95f83d0a1fb69cd9, 0x4abdaf101564f98e},
1672 {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1},
1673 {0xea53df5fd18d5513, 0x84c86189216dc5ed},
1674 {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4},
1675 {0xb7118682dbb66a77, 0x3fbc8c33221dc2a1},
1676 {0xe4d5e82392a40515, 0x0fabaf3feaa5334a},
1677 {0x8f05b1163ba6832d, 0x29cb4d87f2a7400e},
1678 {0xb2c71d5bca9023f8, 0x743e20e9ef511012},
1679 {0xdf78e4b2bd342cf6, 0x914da9246b255416},
1680 {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e},
1681 {0xae9672aba3d0c320, 0xa184ac2473b529b1},
1682 {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e},
1683 {0x8865899617fb1871, 0x7e2fa67c7a658892},
1684 {0xaa7eebfb9df9de8d, 0xddbb901b98feeab7},
1685 {0xd51ea6fa85785631, 0x552a74227f3ea565},
1686 {0x8533285c936b35de, 0xd53a88958f87275f},
1687 {0xa67ff273b8460356, 0x8a892abaf368f137},
1688 {0xd01fef10a657842c, 0x2d2b7569b0432d85},
1689 {0x8213f56a67f6b29b, 0x9c3b29620e29fc73},
1690 {0xa298f2c501f45f42, 0x8349f3ba91b47b8f},
1691 {0xcb3f2f7642717713, 0x241c70a936219a73},
1692 {0xfe0efb53d30dd4d7, 0xed238cd383aa0110},
1693 {0x9ec95d1463e8a506, 0xf4363804324a40aa},
1694 {0xc67bb4597ce2ce48, 0xb143c6053edcd0d5},
1695 {0xf81aa16fdc1b81da, 0xdd94b7868e94050a},
1696 {0x9b10a4e5e9913128, 0xca7cf2b4191c8326},
1697 {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0},
1698 {0xf24a01a73cf2dccf, 0xbc633b39673c8cec},
1699 {0x976e41088617ca01, 0xd5be0503e085d813},
1700 {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18},
1701 {0xec9c459d51852ba2, 0xddf8e7d60ed1219e},
1702 {0x93e1ab8252f33b45, 0xcabb90e5c942b503},
1703 {0xb8da1662e7b00a17, 0x3d6a751f3b936243},
1704 {0xe7109bfba19c0c9d, 0x0cc512670a783ad4},
1705 {0x906a617d450187e2, 0x27fb2b80668b24c5},
1706 {0xb484f9dc9641e9da, 0xb1f9f660802dedf6},
1707 {0xe1a63853bbd26451, 0x5e7873f8a0396973},
1708 {0x8d07e33455637eb2, 0xdb0b487b6423e1e8},
1709 {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62},
1710 {0xdc5c5301c56b75f7, 0x7641a140cc7810fb},
1711 {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d},
1712 {0xac2820d9623bf429, 0x546345fa9fbdcd44},
1713 {0xd732290fbacaf133, 0xa97c177947ad4095},
1714 {0x867f59a9d4bed6c0, 0x49ed8eabcccc485d},
1715 {0xa81f301449ee8c70, 0x5c68f256bfff5a74},
1716 {0xd226fc195c6a2f8c, 0x73832eec6fff3111},
1717 {0x83585d8fd9c25db7, 0xc831fd53c5ff7eab},
1718 {0xa42e74f3d032f525, 0xba3e7ca8b77f5e55},
1719 {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb},
1720 {0x80444b5e7aa7cf85, 0x7980d163cf5b81b3},
1721 {0xa0555e361951c366, 0xd7e105bcc332621f},
1722 {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7},
1723 {0xfa856334878fc150, 0xb14f98f6f0feb951},
1724 {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3},
1725 {0xc3b8358109e84f07, 0x0a862f80ec4700c8},
1726 {0xf4a642e14c6262c8, 0xcd27bb612758c0fa},
1727 {0x98e7e9cccfbd7dbd, 0x8038d51cb897789c},
1728 {0xbf21e44003acdd2c, 0xe0470a63e6bd56c3},
1729 {0xeeea5d5004981478, 0x1858ccfce06cac74},
1730 {0x95527a5202df0ccb, 0x0f37801e0c43ebc8},
1731 {0xbaa718e68396cffd, 0xd30560258f54e6ba},
1732 {0xe950df20247c83fd, 0x47c6b82ef32a2069},
1733 {0x91d28b7416cdd27e, 0x4cdc331d57fa5441},
1734 {0xb6472e511c81471d, 0xe0133fe4adf8e952},
1735 {0xe3d8f9e563a198e5, 0x58180fddd97723a6},
1736 {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648},
1737 {0xb201833b35d63f73, 0x2cd2cc6551e513da},
1738 {0xde81e40a034bcf4f, 0xf8077f7ea65e58d1},
1739 {0x8b112e86420f6191, 0xfb04afaf27faf782},
1740 {0xadd57a27d29339f6, 0x79c5db9af1f9b563},
1741 {0xd94ad8b1c7380874, 0x18375281ae7822bc},
1742 {0x87cec76f1c830548, 0x8f2293910d0b15b5},
1743 {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb22},
1744 {0xd433179d9c8cb841, 0x5fa60692a46151eb},
1745 {0x849feec281d7f328, 0xdbc7c41ba6bcd333},
1746 {0xa5c7ea73224deff3, 0x12b9b522906c0800},
1747 {0xcf39e50feae16bef, 0xd768226b34870a00},
1748 {0x81842f29f2cce375, 0xe6a1158300d46640},
1749 {0xa1e53af46f801c53, 0x60495ae3c1097fd0},
1750 {0xca5e89b18b602368, 0x385bb19cb14bdfc4},
1751 {0xfcf62c1dee382c42, 0x46729e03dd9ed7b5},
1752 {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d1},
1753 {0xc5a05277621be293, 0xc7098b7305241885},
1754 { 0xf70867153aa2db38,
1755 0xb8cbee4fc66d1ea7 }
1756 #else
1757 {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
1758 {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},
1759 {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},
1760 {0x86a8d39ef77164bc, 0xae5dff9c02033198},
1761 {0xd98ddaee19068c76, 0x3badd624dd9b0958},
1762 {0xafbd2350644eeacf, 0xe5d1929ef90898fb},
1763 {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},
1764 {0xe55990879ddcaabd, 0xcc420a6a101d0516},
1765 {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},
1766 {0x95a8637627989aad, 0xdde7001379a44aa9},
1767 {0xf1c90080baf72cb1, 0x5324c68b12dd6339},
1768 {0xc350000000000000, 0x0000000000000000},
1769 {0x9dc5ada82b70b59d, 0xf020000000000000},
1770 {0xfee50b7025c36a08, 0x02f236d04753d5b4},
1771 {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86},
1772 {0xa6539930bf6bff45, 0x84db8346b786151c},
1773 {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2},
1774 {0xd910f7ff28069da4, 0x1b2ba1518094da04},
1775 {0xaf58416654a6babb, 0x387ac8d1970027b2},
1776 {0x8da471a9de737e24, 0x5ceaecfed289e5d2},
1777 {0xe4d5e82392a40515, 0x0fabaf3feaa5334a},
1778 {0xb8da1662e7b00a17, 0x3d6a751f3b936243},
1779 { 0x95527a5202df0ccb,
1780 0x0f37801e0c43ebc8 }
1781 #endif
1782 };
1783
1784 #if FMT_USE_FULL_CACHE_DRAGONBOX
1785 return pow10_significands[k - float_info<double>::min_k];
1786 #else
1787 static constexpr const uint64_t powers_of_5_64[] = {
1788 0x0000000000000001, 0x0000000000000005, 0x0000000000000019,
1789 0x000000000000007d, 0x0000000000000271, 0x0000000000000c35,
1790 0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1,
1791 0x00000000001dcd65, 0x00000000009502f9, 0x0000000002e90edd,
1792 0x000000000e8d4a51, 0x0000000048c27395, 0x000000016bcc41e9,
1793 0x000000071afd498d, 0x0000002386f26fc1, 0x000000b1a2bc2ec5,
1794 0x000003782dace9d9, 0x00001158e460913d, 0x000056bc75e2d631,
1795 0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed,
1796 0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9};
1797
1798 static constexpr const uint32_t pow10_recovery_errors[] = {
1799 0x50001400, 0x54044100, 0x54014555, 0x55954415, 0x54115555, 0x00000001,
1800 0x50000000, 0x00104000, 0x54010004, 0x05004001, 0x55555544, 0x41545555,
1801 0x54040551, 0x15445545, 0x51555514, 0x10000015, 0x00101100, 0x01100015,
1802 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04450514, 0x45414110,
1803 0x55555145, 0x50544050, 0x15040155, 0x11054140, 0x50111514, 0x11451454,
1804 0x00400541, 0x00000000, 0x55555450, 0x10056551, 0x10054011, 0x55551014,
1805 0x69514555, 0x05151109, 0x00155555};
1806
1807 static const int compression_ratio = 27;
1808
1809 // Compute base index.
1810 int cache_index = (k - float_info<double>::min_k) / compression_ratio;
1811 int kb = cache_index * compression_ratio + float_info<double>::min_k;
1812 int offset = k - kb;
1813
1814 // Get base cache.
1815 uint128_wrapper base_cache = pow10_significands[cache_index];
1816 if (offset == 0) return base_cache;
1817
1818 // Compute the required amount of bit-shift.
1819 int alpha = floor_log2_pow10(kb + offset) - floor_log2_pow10(kb) - offset;
1820 FMT_ASSERT(alpha > 0 && alpha < 64, "shifting error detected");
1821
1822 // Try to recover the real cache.
1823 uint64_t pow5 = powers_of_5_64[offset];
1824 uint128_wrapper recovered_cache = umul128(base_cache.high(), pow5);
1825 uint128_wrapper middle_low =
1826 umul128(base_cache.low() - (kb < 0 ? 1u : 0u), pow5);
1827
1828 recovered_cache += middle_low.high();
1829
1830 uint64_t high_to_middle = recovered_cache.high() << (64 - alpha);
1831 uint64_t middle_to_low = recovered_cache.low() << (64 - alpha);
1832
1833 recovered_cache =
1834 uint128_wrapper{(recovered_cache.low() >> alpha) | high_to_middle,
1835 ((middle_low.low() >> alpha) | middle_to_low)};
1836
1837 if (kb < 0) recovered_cache += 1;
1838
1839 // Get error.
1840 int error_idx = (k - float_info<double>::min_k) / 16;
1841 uint32_t error = (pow10_recovery_errors[error_idx] >>
1842 ((k - float_info<double>::min_k) % 16) * 2) &
1843 0x3;
1844
1845 // Add the error back.
1846 FMT_ASSERT(recovered_cache.low() + error >= recovered_cache.low(), "");
1847 return {recovered_cache.high(), recovered_cache.low() + error};
1848 #endif
1849 }
1850
1851 static carrier_uint compute_mul(carrier_uint u,
1852 const cache_entry_type& cache) FMT_NOEXCEPT {
1853 return umul192_upper64(u, cache);
1854 }
1855
1856 static uint32_t compute_delta(cache_entry_type const& cache,
1857 int beta_minus_1) FMT_NOEXCEPT {
1858 return static_cast<uint32_t>(cache.high() >> (64 - 1 - beta_minus_1));
1859 }
1860
1861 static bool compute_mul_parity(carrier_uint two_f,
1862 const cache_entry_type& cache,
1863 int beta_minus_1) FMT_NOEXCEPT {
1864 FMT_ASSERT(beta_minus_1 >= 1, "");
1865 FMT_ASSERT(beta_minus_1 < 64, "");
1866
1867 return ((umul192_middle64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0;
1868 }
1869
1870 static carrier_uint compute_left_endpoint_for_shorter_interval_case(
1871 const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
1872 return (cache.high() -
1873 (cache.high() >> (float_info<double>::significand_bits + 2))) >>
1874 (64 - float_info<double>::significand_bits - 1 - beta_minus_1);
1875 }
1876
1877 static carrier_uint compute_right_endpoint_for_shorter_interval_case(
1878 const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
1879 return (cache.high() +
1880 (cache.high() >> (float_info<double>::significand_bits + 1))) >>
1881 (64 - float_info<double>::significand_bits - 1 - beta_minus_1);
1882 }
1883
1884 static carrier_uint compute_round_up_for_shorter_interval_case(
1885 const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
1886 return ((cache.high() >>
1887 (64 - float_info<double>::significand_bits - 2 - beta_minus_1)) +
1888 1) /
1889 2;
1890 }
1891 };
1892
1893 // Various integer checks
1894 template <class T>
1895 bool is_left_endpoint_integer_shorter_interval(int exponent) FMT_NOEXCEPT {
1896 return exponent >=
1897 float_info<
1898 T>::case_shorter_interval_left_endpoint_lower_threshold &&
1899 exponent <=
1900 float_info<T>::case_shorter_interval_left_endpoint_upper_threshold;
1901 }
1902 template <class T>
1903 bool is_endpoint_integer(typename float_info<T>::carrier_uint two_f,
1904 int exponent, int minus_k) FMT_NOEXCEPT {
1905 if (exponent < float_info<T>::case_fc_pm_half_lower_threshold) return false;
1906 // For k >= 0.
1907 if (exponent <= float_info<T>::case_fc_pm_half_upper_threshold) return true;
1908 // For k < 0.
1909 if (exponent > float_info<T>::divisibility_check_by_5_threshold) return false;
1910 return divisible_by_power_of_5(two_f, minus_k);
1911 }
1912
1913 template <class T>
1914 bool is_center_integer(typename float_info<T>::carrier_uint two_f, int exponent,
1915 int minus_k) FMT_NOEXCEPT {
1916 // Exponent for 5 is negative.
1917 if (exponent > float_info<T>::divisibility_check_by_5_threshold) return false;
1918 if (exponent > float_info<T>::case_fc_upper_threshold)
1919 return divisible_by_power_of_5(two_f, minus_k);
1920 // Both exponents are nonnegative.
1921 if (exponent >= float_info<T>::case_fc_lower_threshold) return true;
1922 // Exponent for 2 is negative.
1923 return divisible_by_power_of_2(two_f, minus_k - exponent + 1);
1924 }
1925
1926 // Remove trailing zeros from n and return the number of zeros removed (float)
1927 FMT_INLINE int remove_trailing_zeros(uint32_t& n) FMT_NOEXCEPT {
1928 #ifdef FMT_BUILTIN_CTZ
1929 int t = FMT_BUILTIN_CTZ(n);
1930 #else
1931 int t = ctz(n);
1932 #endif
1933 if (t > float_info<float>::max_trailing_zeros)
1934 t = float_info<float>::max_trailing_zeros;
1935
1936 const uint32_t mod_inv1 = 0xcccccccd;
1937 const uint32_t max_quotient1 = 0x33333333;
1938 const uint32_t mod_inv2 = 0xc28f5c29;
1939 const uint32_t max_quotient2 = 0x0a3d70a3;
1940
1941 int s = 0;
1942 for (; s < t - 1; s += 2) {
1943 if (n * mod_inv2 > max_quotient2) break;
1944 n *= mod_inv2;
1945 }
1946 if (s < t && n * mod_inv1 <= max_quotient1) {
1947 n *= mod_inv1;
1948 ++s;
1949 }
1950 n >>= s;
1951 return s;
1952 }
1953
1954 // Removes trailing zeros and returns the number of zeros removed (double)
1955 FMT_INLINE int remove_trailing_zeros(uint64_t& n) FMT_NOEXCEPT {
1956 #ifdef FMT_BUILTIN_CTZLL
1957 int t = FMT_BUILTIN_CTZLL(n);
1958 #else
1959 int t = ctzll(n);
1960 #endif
1961 if (t > float_info<double>::max_trailing_zeros)
1962 t = float_info<double>::max_trailing_zeros;
1963 // Divide by 10^8 and reduce to 32-bits
1964 // Since ret_value.significand <= (2^64 - 1) / 1000 < 10^17,
1965 // both of the quotient and the r should fit in 32-bits
1966
1967 const uint32_t mod_inv1 = 0xcccccccd;
1968 const uint32_t max_quotient1 = 0x33333333;
1969 const uint64_t mod_inv8 = 0xc767074b22e90e21;
1970 const uint64_t max_quotient8 = 0x00002af31dc46118;
1971
1972 // If the number is divisible by 1'0000'0000, work with the quotient
1973 if (t >= 8) {
1974 auto quotient_candidate = n * mod_inv8;
1975
1976 if (quotient_candidate <= max_quotient8) {
1977 auto quotient = static_cast<uint32_t>(quotient_candidate >> 8);
1978
1979 int s = 8;
1980 for (; s < t; ++s) {
1981 if (quotient * mod_inv1 > max_quotient1) break;
1982 quotient *= mod_inv1;
1983 }
1984 quotient >>= (s - 8);
1985 n = quotient;
1986 return s;
1987 }
1988 }
1989
1990 // Otherwise, work with the remainder
1991 auto quotient = static_cast<uint32_t>(n / 100000000);
1992 auto remainder = static_cast<uint32_t>(n - 100000000 * quotient);
1993
1994 if (t == 0 || remainder * mod_inv1 > max_quotient1) {
1995 return 0;
1996 }
1997 remainder *= mod_inv1;
1998
1999 if (t == 1 || remainder * mod_inv1 > max_quotient1) {
2000 n = (remainder >> 1) + quotient * 10000000ull;
2001 return 1;
2002 }
2003 remainder *= mod_inv1;
2004
2005 if (t == 2 || remainder * mod_inv1 > max_quotient1) {
2006 n = (remainder >> 2) + quotient * 1000000ull;
2007 return 2;
2008 }
2009 remainder *= mod_inv1;
2010
2011 if (t == 3 || remainder * mod_inv1 > max_quotient1) {
2012 n = (remainder >> 3) + quotient * 100000ull;
2013 return 3;
2014 }
2015 remainder *= mod_inv1;
2016
2017 if (t == 4 || remainder * mod_inv1 > max_quotient1) {
2018 n = (remainder >> 4) + quotient * 10000ull;
2019 return 4;
2020 }
2021 remainder *= mod_inv1;
2022
2023 if (t == 5 || remainder * mod_inv1 > max_quotient1) {
2024 n = (remainder >> 5) + quotient * 1000ull;
2025 return 5;
2026 }
2027 remainder *= mod_inv1;
2028
2029 if (t == 6 || remainder * mod_inv1 > max_quotient1) {
2030 n = (remainder >> 6) + quotient * 100ull;
2031 return 6;
2032 }
2033 remainder *= mod_inv1;
2034
2035 n = (remainder >> 7) + quotient * 10ull;
2036 return 7;
2037 }
2038
2039 // The main algorithm for shorter interval case
2040 template <class T>
2041 FMT_INLINE decimal_fp<T> shorter_interval_case(int exponent) FMT_NOEXCEPT {
2042 decimal_fp<T> ret_value;
2043 // Compute k and beta
2044 const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent);
2045 const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k);
2046
2047 // Compute xi and zi
2048 using cache_entry_type = typename cache_accessor<T>::cache_entry_type;
2049 const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
2050
2051 auto xi = cache_accessor<T>::compute_left_endpoint_for_shorter_interval_case(
2052 cache, beta_minus_1);
2053 auto zi = cache_accessor<T>::compute_right_endpoint_for_shorter_interval_case(
2054 cache, beta_minus_1);
2055
2056 // If the left endpoint is not an integer, increase it
2057 if (!is_left_endpoint_integer_shorter_interval<T>(exponent)) ++xi;
2058
2059 // Try bigger divisor
2060 ret_value.significand = zi / 10;
2061
2062 // If succeed, remove trailing zeros if necessary and return
2063 if (ret_value.significand * 10 >= xi) {
2064 ret_value.exponent = minus_k + 1;
2065 ret_value.exponent += remove_trailing_zeros(ret_value.significand);
2066 return ret_value;
2067 }
2068
2069 // Otherwise, compute the round-up of y
2070 ret_value.significand =
2071 cache_accessor<T>::compute_round_up_for_shorter_interval_case(
2072 cache, beta_minus_1);
2073 ret_value.exponent = minus_k;
2074
2075 // When tie occurs, choose one of them according to the rule
2076 if (exponent >= float_info<T>::shorter_interval_tie_lower_threshold &&
2077 exponent <= float_info<T>::shorter_interval_tie_upper_threshold) {
2078 ret_value.significand = ret_value.significand % 2 == 0
2079 ? ret_value.significand
2080 : ret_value.significand - 1;
2081 } else if (ret_value.significand < xi) {
2082 ++ret_value.significand;
2083 }
2084 return ret_value;
2085 }
2086
2087 template <typename T> decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT {
2088 // Step 1: integer promotion & Schubfach multiplier calculation.
2089
2090 using carrier_uint = typename float_info<T>::carrier_uint;
2091 using cache_entry_type = typename cache_accessor<T>::cache_entry_type;
2092 auto br = bit_cast<carrier_uint>(x);
2093
2094 // Extract significand bits and exponent bits.
2095 const carrier_uint significand_mask =
2096 (static_cast<carrier_uint>(1) << float_info<T>::significand_bits) - 1;
2097 carrier_uint significand = (br & significand_mask);
2098 int exponent = static_cast<int>((br & exponent_mask<T>()) >>
2099 float_info<T>::significand_bits);
2100
2101 if (exponent != 0) { // Check if normal.
2102 exponent += float_info<T>::exponent_bias - float_info<T>::significand_bits;
2103
2104 // Shorter interval case; proceed like Schubfach.
2105 if (significand == 0) return shorter_interval_case<T>(exponent);
2106
2107 significand |=
2108 (static_cast<carrier_uint>(1) << float_info<T>::significand_bits);
2109 } else {
2110 // Subnormal case; the interval is always regular.
2111 if (significand == 0) return {0, 0};
2112 exponent = float_info<T>::min_exponent - float_info<T>::significand_bits;
2113 }
2114
2115 const bool include_left_endpoint = (significand % 2 == 0);
2116 const bool include_right_endpoint = include_left_endpoint;
2117
2118 // Compute k and beta.
2119 const int minus_k = floor_log10_pow2(exponent) - float_info<T>::kappa;
2120 const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
2121 const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k);
2122
2123 // Compute zi and deltai
2124 // 10^kappa <= deltai < 10^(kappa + 1)
2125 const uint32_t deltai = cache_accessor<T>::compute_delta(cache, beta_minus_1);
2126 const carrier_uint two_fc = significand << 1;
2127 const carrier_uint two_fr = two_fc | 1;
2128 const carrier_uint zi =
2129 cache_accessor<T>::compute_mul(two_fr << beta_minus_1, cache);
2130
2131 // Step 2: Try larger divisor; remove trailing zeros if necessary
2132
2133 // Using an upper bound on zi, we might be able to optimize the division
2134 // better than the compiler; we are computing zi / big_divisor here
2135 decimal_fp<T> ret_value;
2136 ret_value.significand = divide_by_10_to_kappa_plus_1(zi);
2137 uint32_t r = static_cast<uint32_t>(zi - float_info<T>::big_divisor *
2138 ret_value.significand);
2139
2140 if (r > deltai) {
2141 goto small_divisor_case_label;
2142 } else if (r < deltai) {
2143 // Exclude the right endpoint if necessary
2144 if (r == 0 && !include_right_endpoint &&
2145 is_endpoint_integer<T>(two_fr, exponent, minus_k)) {
2146 --ret_value.significand;
2147 r = float_info<T>::big_divisor;
2148 goto small_divisor_case_label;
2149 }
2150 } else {
2151 // r == deltai; compare fractional parts
2152 // Check conditions in the order different from the paper
2153 // to take advantage of short-circuiting
2154 const carrier_uint two_fl = two_fc - 1;
2155 if ((!include_left_endpoint ||
2156 !is_endpoint_integer<T>(two_fl, exponent, minus_k)) &&
2157 !cache_accessor<T>::compute_mul_parity(two_fl, cache, beta_minus_1)) {
2158 goto small_divisor_case_label;
2159 }
2160 }
2161 ret_value.exponent = minus_k + float_info<T>::kappa + 1;
2162
2163 // We may need to remove trailing zeros
2164 ret_value.exponent += remove_trailing_zeros(ret_value.significand);
2165 return ret_value;
2166
2167 // Step 3: Find the significand with the smaller divisor
2168
2169 small_divisor_case_label:
2170 ret_value.significand *= 10;
2171 ret_value.exponent = minus_k + float_info<T>::kappa;
2172
2173 const uint32_t mask = (1u << float_info<T>::kappa) - 1;
2174 auto dist = r - (deltai / 2) + (float_info<T>::small_divisor / 2);
2175
2176 // Is dist divisible by 2^kappa?
2177 if ((dist & mask) == 0) {
2178 const bool approx_y_parity =
2179 ((dist ^ (float_info<T>::small_divisor / 2)) & 1) != 0;
2180 dist >>= float_info<T>::kappa;
2181
2182 // Is dist divisible by 5^kappa?
2183 if (check_divisibility_and_divide_by_pow5<float_info<T>::kappa>(dist)) {
2184 ret_value.significand += dist;
2185
2186 // Check z^(f) >= epsilon^(f)
2187 // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1,
2188 // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f)
2189 // Since there are only 2 possibilities, we only need to care about the
2190 // parity. Also, zi and r should have the same parity since the divisor
2191 // is an even number
2192 if (cache_accessor<T>::compute_mul_parity(two_fc, cache, beta_minus_1) !=
2193 approx_y_parity) {
2194 --ret_value.significand;
2195 } else {
2196 // If z^(f) >= epsilon^(f), we might have a tie
2197 // when z^(f) == epsilon^(f), or equivalently, when y is an integer
2198 if (is_center_integer<T>(two_fc, exponent, minus_k)) {
2199 ret_value.significand = ret_value.significand % 2 == 0
2200 ? ret_value.significand
2201 : ret_value.significand - 1;
2202 }
2203 }
2204 }
2205 // Is dist not divisible by 5^kappa?
2206 else {
2207 ret_value.significand += dist;
2208 }
2209 }
2210 // Is dist not divisible by 2^kappa?
2211 else {
2212 // Since we know dist is small, we might be able to optimize the division
2213 // better than the compiler; we are computing dist / small_divisor here
2214 ret_value.significand +=
2215 small_division_by_pow10<float_info<T>::kappa>(dist);
2216 }
2217 return ret_value;
2218 }
2219 } // namespace dragonbox
2220
2221 // Formats a floating-point number using a variation of the Fixed-Precision
2222 // Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White:
2223 // https://fmt.dev/papers/p372-steele.pdf.
2224 FMT_CONSTEXPR20 inline void format_dragon(fp value, bool is_predecessor_closer,
2225 int num_digits, buffer<char>& buf,
2226 int& exp10) {
2227 bigint numerator; // 2 * R in (FPP)^2.
2228 bigint denominator; // 2 * S in (FPP)^2.
2229 // lower and upper are differences between value and corresponding boundaries.
2230 bigint lower; // (M^- in (FPP)^2).
2231 bigint upper_store; // upper's value if different from lower.
2232 bigint* upper = nullptr; // (M^+ in (FPP)^2).
2233 // Shift numerator and denominator by an extra bit or two (if lower boundary
2234 // is closer) to make lower and upper integers. This eliminates multiplication
2235 // by 2 during later computations.
2236 int shift = is_predecessor_closer ? 2 : 1;
2237 uint64_t significand = value.f << shift;
2238 if (value.e >= 0) {
2239 numerator.assign(significand);
2240 numerator <<= value.e;
2241 lower.assign(1);
2242 lower <<= value.e;
2243 if (shift != 1) {
2244 upper_store.assign(1);
2245 upper_store <<= value.e + 1;
2246 upper = &upper_store;
2247 }
2248 denominator.assign_pow10(exp10);
2249 denominator <<= shift;
2250 } else if (exp10 < 0) {
2251 numerator.assign_pow10(-exp10);
2252 lower.assign(numerator);
2253 if (shift != 1) {
2254 upper_store.assign(numerator);
2255 upper_store <<= 1;
2256 upper = &upper_store;
2257 }
2258 numerator *= significand;
2259 denominator.assign(1);
2260 denominator <<= shift - value.e;
2261 } else {
2262 numerator.assign(significand);
2263 denominator.assign_pow10(exp10);
2264 denominator <<= shift - value.e;
2265 lower.assign(1);
2266 if (shift != 1) {
2267 upper_store.assign(1ULL << 1);
2268 upper = &upper_store;
2269 }
2270 }
2271 // Invariant: value == (numerator / denominator) * pow(10, exp10).
2272 if (num_digits < 0) {
2273 // Generate the shortest representation.
2274 if (!upper) upper = &lower;
2275 bool even = (value.f & 1) == 0;
2276 num_digits = 0;
2277 char* data = buf.data();
2278 for (;;) {
2279 int digit = numerator.divmod_assign(denominator);
2280 bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower.
2281 // numerator + upper >[=] pow10:
2282 bool high = add_compare(numerator, *upper, denominator) + even > 0;
2283 data[num_digits++] = static_cast<char>('0' + digit);
2284 if (low || high) {
2285 if (!low) {
2286 ++data[num_digits - 1];
2287 } else if (high) {
2288 int result = add_compare(numerator, numerator, denominator);
2289 // Round half to even.
2290 if (result > 0 || (result == 0 && (digit % 2) != 0))
2291 ++data[num_digits - 1];
2292 }
2293 buf.try_resize(to_unsigned(num_digits));
2294 exp10 -= num_digits - 1;
2295 return;
2296 }
2297 numerator *= 10;
2298 lower *= 10;
2299 if (upper != &lower) *upper *= 10;
2300 }
2301 }
2302 // Generate the given number of digits.
2303 exp10 -= num_digits - 1;
2304 if (num_digits == 0) {
2305 denominator *= 10;
2306 auto digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';
2307 buf.push_back(digit);
2308 return;
2309 }
2310 buf.try_resize(to_unsigned(num_digits));
2311 for (int i = 0; i < num_digits - 1; ++i) {
2312 int digit = numerator.divmod_assign(denominator);
2313 buf[i] = static_cast<char>('0' + digit);
2314 numerator *= 10;
2315 }
2316 int digit = numerator.divmod_assign(denominator);
2317 auto result = add_compare(numerator, numerator, denominator);
2318 if (result > 0 || (result == 0 && (digit % 2) != 0)) {
2319 if (digit == 9) {
2320 const auto overflow = '0' + 10;
2321 buf[num_digits - 1] = overflow;
2322 // Propagate the carry.
2323 for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {
2324 buf[i] = '0';
2325 ++buf[i - 1];
2326 }
2327 if (buf[0] == overflow) {
2328 buf[0] = '1';
2329 ++exp10;
2330 }
2331 return;
2332 }
2333 ++digit;
2334 }
2335 buf[num_digits - 1] = static_cast<char>('0' + digit);
2336 }
2337
2338 template <typename Float>
2339 FMT_HEADER_ONLY_CONSTEXPR20 int format_float(Float value, int precision,
2340 float_specs specs,
2341 buffer<char>& buf) {
2342 // float is passed as double to reduce the number of instantiations.
2343 static_assert(!std::is_same<Float, float>::value, "");
2344 FMT_ASSERT(value >= 0, "value is negative");
2345
2346 const bool fixed = specs.format == float_format::fixed;
2347 if (value <= 0) { // <= instead of == to silence a warning.
2348 if (precision <= 0 || !fixed) {
2349 buf.push_back('0');
2350 return 0;
2351 }
2352 buf.try_resize(to_unsigned(precision));
2353 fill_n(buf.data(), precision, '0');
2354 return -precision;
2355 }
2356
2357 if (specs.fallback) return snprintf_float(value, precision, specs, buf);
2358
2359 if (!is_constant_evaluated() && precision < 0) {
2360 // Use Dragonbox for the shortest format.
2361 if (specs.binary32) {
2362 auto dec = dragonbox::to_decimal(static_cast<float>(value));
2363 write<char>(buffer_appender<char>(buf), dec.significand);
2364 return dec.exponent;
2365 }
2366 auto dec = dragonbox::to_decimal(static_cast<double>(value));
2367 write<char>(buffer_appender<char>(buf), dec.significand);
2368 return dec.exponent;
2369 }
2370
2371 int exp = 0;
2372 bool use_dragon = true;
2373 if (is_fast_float<Float>()) {
2374 // Use Grisu + Dragon4 for the given precision:
2375 // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf.
2376 const int min_exp = -60; // alpha in Grisu.
2377 int cached_exp10 = 0; // K in Grisu.
2378 fp normalized = normalize(fp(value));
2379 const auto cached_pow = get_cached_power(
2380 min_exp - (normalized.e + fp::num_significand_bits), cached_exp10);
2381 normalized = normalized * cached_pow;
2382 gen_digits_handler handler{buf.data(), 0, precision, -cached_exp10, fixed};
2383 if (grisu_gen_digits(normalized, 1, exp, handler) != digits::error &&
2384 !is_constant_evaluated()) {
2385 exp += handler.exp10;
2386 buf.try_resize(to_unsigned(handler.size));
2387 use_dragon = false;
2388 } else {
2389 exp += handler.size - cached_exp10 - 1;
2390 precision = handler.precision;
2391 }
2392 }
2393 if (use_dragon) {
2394 auto f = fp();
2395 bool is_predecessor_closer =
2396 specs.binary32 ? f.assign(static_cast<float>(value)) : f.assign(value);
2397 // Limit precision to the maximum possible number of significant digits in
2398 // an IEEE754 double because we don't need to generate zeros.
2399 const int max_double_digits = 767;
2400 if (precision > max_double_digits) precision = max_double_digits;
2401 format_dragon(f, is_predecessor_closer, precision, buf, exp);
2402 }
2403 if (!fixed && !specs.showpoint) {
2404 // Remove trailing zeros.
2405 auto num_digits = buf.size();
2406 while (num_digits > 0 && buf[num_digits - 1] == '0') {
2407 --num_digits;
2408 ++exp;
2409 }
2410 buf.try_resize(num_digits);
2411 }
2412 return exp;
2413 }
2414
2415 template <typename T>
2416 int snprintf_float(T value, int precision, float_specs specs,
2417 buffer<char>& buf) {
2418 // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
2419 FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer");
2420 static_assert(!std::is_same<T, float>::value, "");
2421
2422 // Subtract 1 to account for the difference in precision since we use %e for
2423 // both general and exponent format.
2424 if (specs.format == float_format::general ||
2425 specs.format == float_format::exp)
2426 precision = (precision >= 0 ? precision : 6) - 1;
2427
2428 // Build the format string.
2429 enum { max_format_size = 7 }; // The longest format is "%#.*Le".
2430 char format[max_format_size];
2431 char* format_ptr = format;
2432 *format_ptr++ = '%';
2433 if (specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#';
2434 if (precision >= 0) {
2435 *format_ptr++ = '.';
2436 *format_ptr++ = '*';
2437 }
2438 if (std::is_same<T, long double>()) *format_ptr++ = 'L';
2439 *format_ptr++ = specs.format != float_format::hex
2440 ? (specs.format == float_format::fixed ? 'f' : 'e')
2441 : (specs.upper ? 'A' : 'a');
2442 *format_ptr = '\0';
2443
2444 // Format using snprintf.
2445 auto offset = buf.size();
2446 for (;;) {
2447 auto begin = buf.data() + offset;
2448 auto capacity = buf.capacity() - offset;
2449 #ifdef FMT_FUZZ
2450 if (precision > 100000)
2451 throw std::runtime_error(
2452 "fuzz mode - avoid large allocation inside snprintf");
2453 #endif
2454 // Suppress the warning about a nonliteral format string.
2455 // Cannot use auto because of a bug in MinGW (#1532).
2456 int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF;
2457 int result = precision >= 0
2458 ? snprintf_ptr(begin, capacity, format, precision, value)
2459 : snprintf_ptr(begin, capacity, format, value);
2460 if (result < 0) {
2461 // The buffer will grow exponentially.
2462 buf.try_reserve(buf.capacity() + 1);
2463 continue;
2464 }
2465 auto size = to_unsigned(result);
2466 // Size equal to capacity means that the last character was truncated.
2467 if (size >= capacity) {
2468 buf.try_reserve(size + offset + 1); // Add 1 for the terminating '\0'.
2469 continue;
2470 }
2471 auto is_digit = [](char c) { return c >= '0' && c <= '9'; };
2472 if (specs.format == float_format::fixed) {
2473 if (precision == 0) {
2474 buf.try_resize(size);
2475 return 0;
2476 }
2477 // Find and remove the decimal point.
2478 auto end = begin + size, p = end;
2479 do {
2480 --p;
2481 } while (is_digit(*p));
2482 int fraction_size = static_cast<int>(end - p - 1);
2483 std::memmove(p, p + 1, to_unsigned(fraction_size));
2484 buf.try_resize(size - 1);
2485 return -fraction_size;
2486 }
2487 if (specs.format == float_format::hex) {
2488 buf.try_resize(size + offset);
2489 return 0;
2490 }
2491 // Find and parse the exponent.
2492 auto end = begin + size, exp_pos = end;
2493 do {
2494 --exp_pos;
2495 } while (*exp_pos != 'e');
2496 char sign = exp_pos[1];
2497 FMT_ASSERT(sign == '+' || sign == '-', "");
2498 int exp = 0;
2499 auto p = exp_pos + 2; // Skip 'e' and sign.
2500 do {
2501 FMT_ASSERT(is_digit(*p), "");
2502 exp = exp * 10 + (*p++ - '0');
2503 } while (p != end);
2504 if (sign == '-') exp = -exp;
2505 int fraction_size = 0;
2506 if (exp_pos != begin + 1) {
2507 // Remove trailing zeros.
2508 auto fraction_end = exp_pos - 1;
2509 while (*fraction_end == '0') --fraction_end;
2510 // Move the fractional part left to get rid of the decimal point.
2511 fraction_size = static_cast<int>(fraction_end - begin - 1);
2512 std::memmove(begin + 1, begin + 2, to_unsigned(fraction_size));
2513 }
2514 buf.try_resize(to_unsigned(fraction_size) + offset + 1);
2515 return exp - fraction_size;
2516 }
2517 }
2518 } // namespace detail
2519
2520 template <> struct formatter<detail::bigint> {
2521 FMT_CONSTEXPR format_parse_context::iterator parse(
2522 format_parse_context& ctx) {
2523 return ctx.begin();
2524 }
2525
2526 format_context::iterator format(const detail::bigint& n,
2527 format_context& ctx) {
2528 auto out = ctx.out();
2529 bool first = true;
2530 for (auto i = n.bigits_.size(); i > 0; --i) {
2531 auto value = n.bigits_[i - 1u];
2532 if (first) {
2533 out = format_to(out, FMT_STRING("{:x}"), value);
2534 first = false;
2535 continue;
2536 }
2537 out = format_to(out, FMT_STRING("{:08x}"), value);
2538 }
2539 if (n.exp_ > 0)
2540 out = format_to(out, FMT_STRING("p{}"),
2541 n.exp_ * detail::bigint::bigit_bits);
2542 return out;
2543 }
2544 };
2545
2546 FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) {
2547 for_each_codepoint(s, [this](uint32_t cp, string_view) {
2548 if (cp == invalid_code_point) FMT_THROW(std::runtime_error("invalid utf8"));
2549 if (cp <= 0xFFFF) {
2550 buffer_.push_back(static_cast<wchar_t>(cp));
2551 } else {
2552 cp -= 0x10000;
2553 buffer_.push_back(static_cast<wchar_t>(0xD800 + (cp >> 10)));
2554 buffer_.push_back(static_cast<wchar_t>(0xDC00 + (cp & 0x3FF)));
2555 }
2556 return true;
2557 });
2558 buffer_.push_back(0);
2559 }
2560
2561 FMT_FUNC void format_system_error(detail::buffer<char>& out, int error_code,
2562 const char* message) FMT_NOEXCEPT {
2563 FMT_TRY {
2564 auto ec = std::error_code(error_code, std::generic_category());
2565 write(std::back_inserter(out), std::system_error(ec, message).what());
2566 return;
2567 }
2568 FMT_CATCH(...) {}
2569 format_error_code(out, error_code, message);
2570 }
2571
2572 FMT_FUNC void report_system_error(int error_code,
2573 const char* message) FMT_NOEXCEPT {
2574 report_error(format_system_error, error_code, message);
2575 }
2576
2577 // DEPRECATED!
2578 // This function is defined here and not inline for ABI compatiblity.
2579 FMT_FUNC void detail::error_handler::on_error(const char* message) {
2580 throw_format_error(message);
2581 }
2582
2583 FMT_FUNC std::string vformat(string_view fmt, format_args args) {
2584 // Don't optimize the "{}" case to keep the binary size small and because it
2585 // can be better optimized in fmt::format anyway.
2586 auto buffer = memory_buffer();
2587 detail::vformat_to(buffer, fmt, args);
2588 return to_string(buffer);
2589 }
2590
2591 #ifdef _WIN32
2592 namespace detail {
2593 using dword = conditional_t<sizeof(long) == 4, unsigned long, unsigned>;
2594 extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( //
2595 void*, const void*, dword, dword*, void*);
2596 } // namespace detail
2597 #endif
2598
2599 namespace detail {
2600 FMT_FUNC void print(std::FILE* f, string_view text) {
2601 #ifdef _WIN32
2602 auto fd = _fileno(f);
2603 if (_isatty(fd)) {
2604 detail::utf8_to_utf16 u16(string_view(text.data(), text.size()));
2605 auto written = detail::dword();
2606 if (detail::WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fd)),
2607 u16.c_str(), static_cast<uint32_t>(u16.size()),
2608 &written, nullptr)) {
2609 return;
2610 }
2611 // Fallback to fwrite on failure. It can happen if the output has been
2612 // redirected to NUL.
2613 }
2614 #endif
2615 detail::fwrite_fully(text.data(), 1, text.size(), f);
2616 }
2617 } // namespace detail
2618
2619 FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) {
2620 memory_buffer buffer;
2621 detail::vformat_to(buffer, format_str, args);
2622 detail::print(f, {buffer.data(), buffer.size()});
2623 }
2624
2625 #ifdef _WIN32
2626 // Print assuming legacy (non-Unicode) encoding.
2627 FMT_FUNC void detail::vprint_mojibake(std::FILE* f, string_view format_str,
2628 format_args args) {
2629 memory_buffer buffer;
2630 detail::vformat_to(buffer, format_str,
2631 basic_format_args<buffer_context<char>>(args));
2632 fwrite_fully(buffer.data(), 1, buffer.size(), f);
2633 }
2634 #endif
2635
2636 FMT_FUNC void vprint(string_view format_str, format_args args) {
2637 vprint(stdout, format_str, args);
2638 }
2639
2640 FMT_END_NAMESPACE
2641
2642 #endif // FMT_FORMAT_INL_H_
+0
-3104
source/misc/embedded_libs/fmt-8.1.1/include/fmt/format.h less more
0 /*
1 Formatting library for C++
2
3 Copyright (c) 2012 - present, Victor Zverovich
4
5 Permission is hereby granted, free of charge, to any person obtaining
6 a copy of this software and associated documentation files (the
7 "Software"), to deal in the Software without restriction, including
8 without limitation the rights to use, copy, modify, merge, publish,
9 distribute, sublicense, and/or sell copies of the Software, and to
10 permit persons to whom the Software is furnished to do so, subject to
11 the following conditions:
12
13 The above copyright notice and this permission notice shall be
14 included in all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
24 --- Optional exception to the license ---
25
26 As an exception, if, as a result of your compiling your source code, portions
27 of this Software are embedded into a machine-executable object form of such
28 source code, you may redistribute such embedded portions in such object form
29 without including the above copyright and permission notices.
30 */
31
32 #ifndef FMT_FORMAT_H_
33 #define FMT_FORMAT_H_
34
35 #include <cmath> // std::signbit
36 #include <cstdint> // uint32_t
37 #include <limits> // std::numeric_limits
38 #include <memory> // std::uninitialized_copy
39 #include <stdexcept> // std::runtime_error
40 #include <system_error> // std::system_error
41 #include <utility> // std::swap
42
43 #ifdef __cpp_lib_bit_cast
44 # include <bit> // std::bitcast
45 #endif
46
47 #include "core.h"
48
49 #if FMT_GCC_VERSION
50 # define FMT_GCC_VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
51 #else
52 # define FMT_GCC_VISIBILITY_HIDDEN
53 #endif
54
55 #ifdef __NVCC__
56 # define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__)
57 #else
58 # define FMT_CUDA_VERSION 0
59 #endif
60
61 #ifdef __has_builtin
62 # define FMT_HAS_BUILTIN(x) __has_builtin(x)
63 #else
64 # define FMT_HAS_BUILTIN(x) 0
65 #endif
66
67 #if FMT_GCC_VERSION || FMT_CLANG_VERSION
68 # define FMT_NOINLINE __attribute__((noinline))
69 #else
70 # define FMT_NOINLINE
71 #endif
72
73 #if FMT_MSC_VER
74 # define FMT_MSC_DEFAULT = default
75 #else
76 # define FMT_MSC_DEFAULT
77 #endif
78
79 #ifndef FMT_THROW
80 # if FMT_EXCEPTIONS
81 # if FMT_MSC_VER || FMT_NVCC
82 FMT_BEGIN_NAMESPACE
83 namespace detail {
84 template <typename Exception> inline void do_throw(const Exception& x) {
85 // Silence unreachable code warnings in MSVC and NVCC because these
86 // are nearly impossible to fix in a generic code.
87 volatile bool b = true;
88 if (b) throw x;
89 }
90 } // namespace detail
91 FMT_END_NAMESPACE
92 # define FMT_THROW(x) detail::do_throw(x)
93 # else
94 # define FMT_THROW(x) throw x
95 # endif
96 # else
97 # define FMT_THROW(x) \
98 do { \
99 FMT_ASSERT(false, (x).what()); \
100 } while (false)
101 # endif
102 #endif
103
104 #if FMT_EXCEPTIONS
105 # define FMT_TRY try
106 # define FMT_CATCH(x) catch (x)
107 #else
108 # define FMT_TRY if (true)
109 # define FMT_CATCH(x) if (false)
110 #endif
111
112 #ifndef FMT_MAYBE_UNUSED
113 # if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused)
114 # define FMT_MAYBE_UNUSED [[maybe_unused]]
115 # else
116 # define FMT_MAYBE_UNUSED
117 # endif
118 #endif
119
120 // Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers.
121 #if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC
122 # define FMT_DEPRECATED_ALIAS
123 #else
124 # define FMT_DEPRECATED_ALIAS FMT_DEPRECATED
125 #endif
126
127 #ifndef FMT_USE_USER_DEFINED_LITERALS
128 // EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs.
129 # if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \
130 FMT_MSC_VER >= 1900) && \
131 (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480)
132 # define FMT_USE_USER_DEFINED_LITERALS 1
133 # else
134 # define FMT_USE_USER_DEFINED_LITERALS 0
135 # endif
136 #endif
137
138 // Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of
139 // integer formatter template instantiations to just one by only using the
140 // largest integer type. This results in a reduction in binary size but will
141 // cause a decrease in integer formatting performance.
142 #if !defined(FMT_REDUCE_INT_INSTANTIATIONS)
143 # define FMT_REDUCE_INT_INSTANTIATIONS 0
144 #endif
145
146 // __builtin_clz is broken in clang with Microsoft CodeGen:
147 // https://github.com/fmtlib/fmt/issues/519.
148 #if !FMT_MSC_VER
149 # if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION
150 # define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
151 # endif
152 # if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
153 # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
154 # endif
155 #endif
156
157 // __builtin_ctz is broken in Intel Compiler Classic on Windows:
158 // https://github.com/fmtlib/fmt/issues/2510.
159 #ifndef __ICL
160 # if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION
161 # define FMT_BUILTIN_CTZ(n) __builtin_ctz(n)
162 # endif
163 # if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
164 # define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n)
165 # endif
166 #endif
167
168 #if FMT_MSC_VER
169 # include <intrin.h> // _BitScanReverse[64], _BitScanForward[64], _umul128
170 #endif
171
172 // Some compilers masquerade as both MSVC and GCC-likes or otherwise support
173 // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
174 // MSVC intrinsics if the clz and clzll builtins are not available.
175 #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(FMT_BUILTIN_CTZLL)
176 FMT_BEGIN_NAMESPACE
177 namespace detail {
178 // Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
179 # if !defined(__clang__)
180 # pragma intrinsic(_BitScanForward)
181 # pragma intrinsic(_BitScanReverse)
182 # if defined(_WIN64)
183 # pragma intrinsic(_BitScanForward64)
184 # pragma intrinsic(_BitScanReverse64)
185 # endif
186 # endif
187
188 inline auto clz(uint32_t x) -> int {
189 unsigned long r = 0;
190 _BitScanReverse(&r, x);
191 FMT_ASSERT(x != 0, "");
192 // Static analysis complains about using uninitialized data
193 // "r", but the only way that can happen is if "x" is 0,
194 // which the callers guarantee to not happen.
195 FMT_MSC_WARNING(suppress : 6102)
196 return 31 ^ static_cast<int>(r);
197 }
198 # define FMT_BUILTIN_CLZ(n) detail::clz(n)
199
200 inline auto clzll(uint64_t x) -> int {
201 unsigned long r = 0;
202 # ifdef _WIN64
203 _BitScanReverse64(&r, x);
204 # else
205 // Scan the high 32 bits.
206 if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 ^ (r + 32);
207 // Scan the low 32 bits.
208 _BitScanReverse(&r, static_cast<uint32_t>(x));
209 # endif
210 FMT_ASSERT(x != 0, "");
211 FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
212 return 63 ^ static_cast<int>(r);
213 }
214 # define FMT_BUILTIN_CLZLL(n) detail::clzll(n)
215
216 inline auto ctz(uint32_t x) -> int {
217 unsigned long r = 0;
218 _BitScanForward(&r, x);
219 FMT_ASSERT(x != 0, "");
220 FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
221 return static_cast<int>(r);
222 }
223 # define FMT_BUILTIN_CTZ(n) detail::ctz(n)
224
225 inline auto ctzll(uint64_t x) -> int {
226 unsigned long r = 0;
227 FMT_ASSERT(x != 0, "");
228 FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
229 # ifdef _WIN64
230 _BitScanForward64(&r, x);
231 # else
232 // Scan the low 32 bits.
233 if (_BitScanForward(&r, static_cast<uint32_t>(x))) return static_cast<int>(r);
234 // Scan the high 32 bits.
235 _BitScanForward(&r, static_cast<uint32_t>(x >> 32));
236 r += 32;
237 # endif
238 return static_cast<int>(r);
239 }
240 # define FMT_BUILTIN_CTZLL(n) detail::ctzll(n)
241 } // namespace detail
242 FMT_END_NAMESPACE
243 #endif
244
245 #ifdef FMT_HEADER_ONLY
246 # define FMT_HEADER_ONLY_CONSTEXPR20 FMT_CONSTEXPR20
247 #else
248 # define FMT_HEADER_ONLY_CONSTEXPR20
249 #endif
250
251 FMT_BEGIN_NAMESPACE
252 namespace detail {
253
254 template <typename Streambuf> class formatbuf : public Streambuf {
255 private:
256 using char_type = typename Streambuf::char_type;
257 using streamsize = decltype(std::declval<Streambuf>().sputn(nullptr, 0));
258 using int_type = typename Streambuf::int_type;
259 using traits_type = typename Streambuf::traits_type;
260
261 buffer<char_type>& buffer_;
262
263 public:
264 explicit formatbuf(buffer<char_type>& buf) : buffer_(buf) {}
265
266 protected:
267 // The put area is always empty. This makes the implementation simpler and has
268 // the advantage that the streambuf and the buffer are always in sync and
269 // sputc never writes into uninitialized memory. A disadvantage is that each
270 // call to sputc always results in a (virtual) call to overflow. There is no
271 // disadvantage here for sputn since this always results in a call to xsputn.
272
273 auto overflow(int_type ch) -> int_type override {
274 if (!traits_type::eq_int_type(ch, traits_type::eof()))
275 buffer_.push_back(static_cast<char_type>(ch));
276 return ch;
277 }
278
279 auto xsputn(const char_type* s, streamsize count) -> streamsize override {
280 buffer_.append(s, s + count);
281 return count;
282 }
283 };
284
285 // Implementation of std::bit_cast for pre-C++20.
286 template <typename To, typename From>
287 FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
288 static_assert(sizeof(To) == sizeof(From), "size mismatch");
289 #ifdef __cpp_lib_bit_cast
290 if (is_constant_evaluated()) return std::bit_cast<To>(from);
291 #endif
292 auto to = To();
293 std::memcpy(&to, &from, sizeof(to));
294 return to;
295 }
296
297 inline auto is_big_endian() -> bool {
298 #ifdef _WIN32
299 return false;
300 #elif defined(__BIG_ENDIAN__)
301 return true;
302 #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
303 return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
304 #else
305 struct bytes {
306 char data[sizeof(int)];
307 };
308 return bit_cast<bytes>(1).data[0] == 0;
309 #endif
310 }
311
312 // A fallback implementation of uintptr_t for systems that lack it.
313 struct fallback_uintptr {
314 unsigned char value[sizeof(void*)];
315
316 fallback_uintptr() = default;
317 explicit fallback_uintptr(const void* p) {
318 *this = bit_cast<fallback_uintptr>(p);
319 if (const_check(is_big_endian())) {
320 for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j)
321 std::swap(value[i], value[j]);
322 }
323 }
324 };
325 #ifdef UINTPTR_MAX
326 using uintptr_t = ::uintptr_t;
327 inline auto to_uintptr(const void* p) -> uintptr_t {
328 return bit_cast<uintptr_t>(p);
329 }
330 #else
331 using uintptr_t = fallback_uintptr;
332 inline auto to_uintptr(const void* p) -> fallback_uintptr {
333 return fallback_uintptr(p);
334 }
335 #endif
336
337 // Returns the largest possible value for type T. Same as
338 // std::numeric_limits<T>::max() but shorter and not affected by the max macro.
339 template <typename T> constexpr auto max_value() -> T {
340 return (std::numeric_limits<T>::max)();
341 }
342 template <typename T> constexpr auto num_bits() -> int {
343 return std::numeric_limits<T>::digits;
344 }
345 // std::numeric_limits<T>::digits may return 0 for 128-bit ints.
346 template <> constexpr auto num_bits<int128_t>() -> int { return 128; }
347 template <> constexpr auto num_bits<uint128_t>() -> int { return 128; }
348 template <> constexpr auto num_bits<fallback_uintptr>() -> int {
349 return static_cast<int>(sizeof(void*) *
350 std::numeric_limits<unsigned char>::digits);
351 }
352
353 FMT_INLINE void assume(bool condition) {
354 (void)condition;
355 #if FMT_HAS_BUILTIN(__builtin_assume)
356 __builtin_assume(condition);
357 #endif
358 }
359
360 // An approximation of iterator_t for pre-C++20 systems.
361 template <typename T>
362 using iterator_t = decltype(std::begin(std::declval<T&>()));
363 template <typename T> using sentinel_t = decltype(std::end(std::declval<T&>()));
364
365 // A workaround for std::string not having mutable data() until C++17.
366 template <typename Char>
367 inline auto get_data(std::basic_string<Char>& s) -> Char* {
368 return &s[0];
369 }
370 template <typename Container>
371 inline auto get_data(Container& c) -> typename Container::value_type* {
372 return c.data();
373 }
374
375 #if defined(_SECURE_SCL) && _SECURE_SCL
376 // Make a checked iterator to avoid MSVC warnings.
377 template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>;
378 template <typename T>
379 constexpr auto make_checked(T* p, size_t size) -> checked_ptr<T> {
380 return {p, size};
381 }
382 #else
383 template <typename T> using checked_ptr = T*;
384 template <typename T> constexpr auto make_checked(T* p, size_t) -> T* {
385 return p;
386 }
387 #endif
388
389 // Attempts to reserve space for n extra characters in the output range.
390 // Returns a pointer to the reserved range or a reference to it.
391 template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
392 #if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION
393 __attribute__((no_sanitize("undefined")))
394 #endif
395 inline auto
396 reserve(std::back_insert_iterator<Container> it, size_t n)
397 -> checked_ptr<typename Container::value_type> {
398 Container& c = get_container(it);
399 size_t size = c.size();
400 c.resize(size + n);
401 return make_checked(get_data(c) + size, n);
402 }
403
404 template <typename T>
405 inline auto reserve(buffer_appender<T> it, size_t n) -> buffer_appender<T> {
406 buffer<T>& buf = get_container(it);
407 buf.try_reserve(buf.size() + n);
408 return it;
409 }
410
411 template <typename Iterator>
412 constexpr auto reserve(Iterator& it, size_t) -> Iterator& {
413 return it;
414 }
415
416 template <typename OutputIt>
417 using reserve_iterator =
418 remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>;
419
420 template <typename T, typename OutputIt>
421 constexpr auto to_pointer(OutputIt, size_t) -> T* {
422 return nullptr;
423 }
424 template <typename T> auto to_pointer(buffer_appender<T> it, size_t n) -> T* {
425 buffer<T>& buf = get_container(it);
426 auto size = buf.size();
427 if (buf.capacity() < size + n) return nullptr;
428 buf.try_resize(size + n);
429 return buf.data() + size;
430 }
431
432 template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
433 inline auto base_iterator(std::back_insert_iterator<Container>& it,
434 checked_ptr<typename Container::value_type>)
435 -> std::back_insert_iterator<Container> {
436 return it;
437 }
438
439 template <typename Iterator>
440 constexpr auto base_iterator(Iterator, Iterator it) -> Iterator {
441 return it;
442 }
443
444 // <algorithm> is spectacularly slow to compile in C++20 so use a simple fill_n
445 // instead (#1998).
446 template <typename OutputIt, typename Size, typename T>
447 FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value)
448 -> OutputIt {
449 for (Size i = 0; i < count; ++i) *out++ = value;
450 return out;
451 }
452 template <typename T, typename Size>
453 FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* {
454 if (is_constant_evaluated()) {
455 return fill_n<T*, Size, T>(out, count, value);
456 }
457 std::memset(out, value, to_unsigned(count));
458 return out + count;
459 }
460
461 #ifdef __cpp_char8_t
462 using char8_type = char8_t;
463 #else
464 enum char8_type : unsigned char {};
465 #endif
466
467 template <typename OutChar, typename InputIt, typename OutputIt>
468 FMT_CONSTEXPR FMT_NOINLINE auto copy_str_noinline(InputIt begin, InputIt end,
469 OutputIt out) -> OutputIt {
470 return copy_str<OutChar>(begin, end, out);
471 }
472
473 // A public domain branchless UTF-8 decoder by Christopher Wellons:
474 // https://github.com/skeeto/branchless-utf8
475 /* Decode the next character, c, from s, reporting errors in e.
476 *
477 * Since this is a branchless decoder, four bytes will be read from the
478 * buffer regardless of the actual length of the next character. This
479 * means the buffer _must_ have at least three bytes of zero padding
480 * following the end of the data stream.
481 *
482 * Errors are reported in e, which will be non-zero if the parsed
483 * character was somehow invalid: invalid byte sequence, non-canonical
484 * encoding, or a surrogate half.
485 *
486 * The function returns a pointer to the next character. When an error
487 * occurs, this pointer will be a guess that depends on the particular
488 * error, but it will always advance at least one byte.
489 */
490 FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e)
491 -> const char* {
492 constexpr const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07};
493 constexpr const uint32_t mins[] = {4194304, 0, 128, 2048, 65536};
494 constexpr const int shiftc[] = {0, 18, 12, 6, 0};
495 constexpr const int shifte[] = {0, 6, 4, 2, 0};
496
497 int len = code_point_length(s);
498 const char* next = s + len;
499
500 // Assume a four-byte character and load four bytes. Unused bits are
501 // shifted out.
502 *c = uint32_t(s[0] & masks[len]) << 18;
503 *c |= uint32_t(s[1] & 0x3f) << 12;
504 *c |= uint32_t(s[2] & 0x3f) << 6;
505 *c |= uint32_t(s[3] & 0x3f) << 0;
506 *c >>= shiftc[len];
507
508 // Accumulate the various error conditions.
509 using uchar = unsigned char;
510 *e = (*c < mins[len]) << 6; // non-canonical encoding
511 *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half?
512 *e |= (*c > 0x10FFFF) << 8; // out of range?
513 *e |= (uchar(s[1]) & 0xc0) >> 2;
514 *e |= (uchar(s[2]) & 0xc0) >> 4;
515 *e |= uchar(s[3]) >> 6;
516 *e ^= 0x2a; // top two bits of each tail byte correct?
517 *e >>= shifte[len];
518
519 return next;
520 }
521
522 constexpr uint32_t invalid_code_point = ~uint32_t();
523
524 // Invokes f(cp, sv) for every code point cp in s with sv being the string view
525 // corresponding to the code point. cp is invalid_code_point on error.
526 template <typename F>
527 FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) {
528 auto decode = [f](const char* buf_ptr, const char* ptr) {
529 auto cp = uint32_t();
530 auto error = 0;
531 auto end = utf8_decode(buf_ptr, &cp, &error);
532 bool result = f(error ? invalid_code_point : cp,
533 string_view(ptr, to_unsigned(end - buf_ptr)));
534 return result ? end : nullptr;
535 };
536 auto p = s.data();
537 const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars.
538 if (s.size() >= block_size) {
539 for (auto end = p + s.size() - block_size + 1; p < end;) {
540 p = decode(p, p);
541 if (!p) return;
542 }
543 }
544 if (auto num_chars_left = s.data() + s.size() - p) {
545 char buf[2 * block_size - 1] = {};
546 copy_str<char>(p, p + num_chars_left, buf);
547 const char* buf_ptr = buf;
548 do {
549 auto end = decode(buf_ptr, p);
550 if (!end) return;
551 p += end - buf_ptr;
552 buf_ptr = end;
553 } while (buf_ptr - buf < num_chars_left);
554 }
555 }
556
557 template <typename Char>
558 inline auto compute_width(basic_string_view<Char> s) -> size_t {
559 return s.size();
560 }
561
562 // Computes approximate display width of a UTF-8 string.
563 FMT_CONSTEXPR inline size_t compute_width(string_view s) {
564 size_t num_code_points = 0;
565 // It is not a lambda for compatibility with C++14.
566 struct count_code_points {
567 size_t* count;
568 FMT_CONSTEXPR auto operator()(uint32_t cp, string_view) const -> bool {
569 *count += detail::to_unsigned(
570 1 +
571 (cp >= 0x1100 &&
572 (cp <= 0x115f || // Hangul Jamo init. consonants
573 cp == 0x2329 || // LEFT-POINTING ANGLE BRACKET
574 cp == 0x232a || // RIGHT-POINTING ANGLE BRACKET
575 // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE:
576 (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||
577 (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables
578 (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs
579 (cp >= 0xfe10 && cp <= 0xfe19) || // Vertical Forms
580 (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK Compatibility Forms
581 (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth Forms
582 (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth Forms
583 (cp >= 0x20000 && cp <= 0x2fffd) || // CJK
584 (cp >= 0x30000 && cp <= 0x3fffd) ||
585 // Miscellaneous Symbols and Pictographs + Emoticons:
586 (cp >= 0x1f300 && cp <= 0x1f64f) ||
587 // Supplemental Symbols and Pictographs:
588 (cp >= 0x1f900 && cp <= 0x1f9ff))));
589 return true;
590 }
591 };
592 for_each_codepoint(s, count_code_points{&num_code_points});
593 return num_code_points;
594 }
595
596 inline auto compute_width(basic_string_view<char8_type> s) -> size_t {
597 return compute_width(basic_string_view<char>(
598 reinterpret_cast<const char*>(s.data()), s.size()));
599 }
600
601 template <typename Char>
602 inline auto code_point_index(basic_string_view<Char> s, size_t n) -> size_t {
603 size_t size = s.size();
604 return n < size ? n : size;
605 }
606
607 // Calculates the index of the nth code point in a UTF-8 string.
608 inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
609 -> size_t {
610 const char8_type* data = s.data();
611 size_t num_code_points = 0;
612 for (size_t i = 0, size = s.size(); i != size; ++i) {
613 if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) return i;
614 }
615 return s.size();
616 }
617
618 template <typename T, bool = std::is_floating_point<T>::value>
619 struct is_fast_float : bool_constant<std::numeric_limits<T>::is_iec559 &&
620 sizeof(T) <= sizeof(double)> {};
621 template <typename T> struct is_fast_float<T, false> : std::false_type {};
622
623 #ifndef FMT_USE_FULL_CACHE_DRAGONBOX
624 # define FMT_USE_FULL_CACHE_DRAGONBOX 0
625 #endif
626
627 template <typename T>
628 template <typename U>
629 void buffer<T>::append(const U* begin, const U* end) {
630 while (begin != end) {
631 auto count = to_unsigned(end - begin);
632 try_reserve(size_ + count);
633 auto free_cap = capacity_ - size_;
634 if (free_cap < count) count = free_cap;
635 std::uninitialized_copy_n(begin, count, make_checked(ptr_ + size_, count));
636 size_ += count;
637 begin += count;
638 }
639 }
640
641 template <typename T, typename Enable = void>
642 struct is_locale : std::false_type {};
643 template <typename T>
644 struct is_locale<T, void_t<decltype(T::classic())>> : std::true_type {};
645 } // namespace detail
646
647 FMT_MODULE_EXPORT_BEGIN
648
649 // The number of characters to store in the basic_memory_buffer object itself
650 // to avoid dynamic memory allocation.
651 enum { inline_buffer_size = 500 };
652
653 /**
654 \rst
655 A dynamically growing memory buffer for trivially copyable/constructible types
656 with the first ``SIZE`` elements stored in the object itself.
657
658 You can use the ``memory_buffer`` type alias for ``char`` instead.
659
660 **Example**::
661
662 auto out = fmt::memory_buffer();
663 format_to(std::back_inserter(out), "The answer is {}.", 42);
664
665 This will append the following output to the ``out`` object:
666
667 .. code-block:: none
668
669 The answer is 42.
670
671 The output can be converted to an ``std::string`` with ``to_string(out)``.
672 \endrst
673 */
674 template <typename T, size_t SIZE = inline_buffer_size,
675 typename Allocator = std::allocator<T>>
676 class basic_memory_buffer final : public detail::buffer<T> {
677 private:
678 T store_[SIZE];
679
680 // Don't inherit from Allocator avoid generating type_info for it.
681 Allocator alloc_;
682
683 // Deallocate memory allocated by the buffer.
684 FMT_CONSTEXPR20 void deallocate() {
685 T* data = this->data();
686 if (data != store_) alloc_.deallocate(data, this->capacity());
687 }
688
689 protected:
690 FMT_CONSTEXPR20 void grow(size_t size) override;
691
692 public:
693 using value_type = T;
694 using const_reference = const T&;
695
696 FMT_CONSTEXPR20 explicit basic_memory_buffer(
697 const Allocator& alloc = Allocator())
698 : alloc_(alloc) {
699 this->set(store_, SIZE);
700 if (detail::is_constant_evaluated()) {
701 detail::fill_n(store_, SIZE, T{});
702 }
703 }
704 FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); }
705
706 private:
707 // Move data from other to this buffer.
708 FMT_CONSTEXPR20 void move(basic_memory_buffer& other) {
709 alloc_ = std::move(other.alloc_);
710 T* data = other.data();
711 size_t size = other.size(), capacity = other.capacity();
712 if (data == other.store_) {
713 this->set(store_, capacity);
714 if (detail::is_constant_evaluated()) {
715 detail::copy_str<T>(other.store_, other.store_ + size,
716 detail::make_checked(store_, capacity));
717 } else {
718 std::uninitialized_copy(other.store_, other.store_ + size,
719 detail::make_checked(store_, capacity));
720 }
721 } else {
722 this->set(data, capacity);
723 // Set pointer to the inline array so that delete is not called
724 // when deallocating.
725 other.set(other.store_, 0);
726 }
727 this->resize(size);
728 }
729
730 public:
731 /**
732 \rst
733 Constructs a :class:`fmt::basic_memory_buffer` object moving the content
734 of the other object to it.
735 \endrst
736 */
737 FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other)
738 FMT_NOEXCEPT {
739 move(other);
740 }
741
742 /**
743 \rst
744 Moves the content of the other ``basic_memory_buffer`` object to this one.
745 \endrst
746 */
747 auto operator=(basic_memory_buffer&& other) FMT_NOEXCEPT
748 -> basic_memory_buffer& {
749 FMT_ASSERT(this != &other, "");
750 deallocate();
751 move(other);
752 return *this;
753 }
754
755 // Returns a copy of the allocator associated with this buffer.
756 auto get_allocator() const -> Allocator { return alloc_; }
757
758 /**
759 Resizes the buffer to contain *count* elements. If T is a POD type new
760 elements may not be initialized.
761 */
762 FMT_CONSTEXPR20 void resize(size_t count) { this->try_resize(count); }
763
764 /** Increases the buffer capacity to *new_capacity*. */
765 void reserve(size_t new_capacity) { this->try_reserve(new_capacity); }
766
767 // Directly append data into the buffer
768 using detail::buffer<T>::append;
769 template <typename ContiguousRange>
770 void append(const ContiguousRange& range) {
771 append(range.data(), range.data() + range.size());
772 }
773 };
774
775 template <typename T, size_t SIZE, typename Allocator>
776 FMT_CONSTEXPR20 void basic_memory_buffer<T, SIZE, Allocator>::grow(
777 size_t size) {
778 #ifdef FMT_FUZZ
779 if (size > 5000) throw std::runtime_error("fuzz mode - won't grow that much");
780 #endif
781 const size_t max_size = std::allocator_traits<Allocator>::max_size(alloc_);
782 size_t old_capacity = this->capacity();
783 size_t new_capacity = old_capacity + old_capacity / 2;
784 if (size > new_capacity)
785 new_capacity = size;
786 else if (new_capacity > max_size)
787 new_capacity = size > max_size ? size : max_size;
788 T* old_data = this->data();
789 T* new_data =
790 std::allocator_traits<Allocator>::allocate(alloc_, new_capacity);
791 // The following code doesn't throw, so the raw pointer above doesn't leak.
792 std::uninitialized_copy(old_data, old_data + this->size(),
793 detail::make_checked(new_data, new_capacity));
794 this->set(new_data, new_capacity);
795 // deallocate must not throw according to the standard, but even if it does,
796 // the buffer already uses the new storage and will deallocate it in
797 // destructor.
798 if (old_data != store_) alloc_.deallocate(old_data, old_capacity);
799 }
800
801 using memory_buffer = basic_memory_buffer<char>;
802
803 template <typename T, size_t SIZE, typename Allocator>
804 struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {
805 };
806
807 namespace detail {
808 FMT_API void print(std::FILE*, string_view);
809 }
810
811 /** A formatting error such as invalid format string. */
812 FMT_CLASS_API
813 class FMT_API format_error : public std::runtime_error {
814 public:
815 explicit format_error(const char* message) : std::runtime_error(message) {}
816 explicit format_error(const std::string& message)
817 : std::runtime_error(message) {}
818 format_error(const format_error&) = default;
819 format_error& operator=(const format_error&) = default;
820 format_error(format_error&&) = default;
821 format_error& operator=(format_error&&) = default;
822 ~format_error() FMT_NOEXCEPT override FMT_MSC_DEFAULT;
823 };
824
825 /**
826 \rst
827 Constructs a `~fmt::format_arg_store` object that contains references
828 to arguments and can be implicitly converted to `~fmt::format_args`.
829 If ``fmt`` is a compile-time string then `make_args_checked` checks
830 its validity at compile time.
831 \endrst
832 */
833 template <typename... Args, typename S, typename Char = char_t<S>>
834 FMT_INLINE auto make_args_checked(const S& fmt,
835 const remove_reference_t<Args>&... args)
836 -> format_arg_store<buffer_context<Char>, remove_reference_t<Args>...> {
837 static_assert(
838 detail::count<(
839 std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
840 std::is_reference<Args>::value)...>() == 0,
841 "passing views as lvalues is disallowed");
842 detail::check_format_string<Args...>(fmt);
843 return {args...};
844 }
845
846 // compile-time support
847 namespace detail_exported {
848 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
849 template <typename Char, size_t N> struct fixed_string {
850 constexpr fixed_string(const Char (&str)[N]) {
851 detail::copy_str<Char, const Char*, Char*>(static_cast<const Char*>(str),
852 str + N, data);
853 }
854 Char data[N]{};
855 };
856 #endif
857
858 // Converts a compile-time string to basic_string_view.
859 template <typename Char, size_t N>
860 constexpr auto compile_string_to_view(const Char (&s)[N])
861 -> basic_string_view<Char> {
862 // Remove trailing NUL character if needed. Won't be present if this is used
863 // with a raw character array (i.e. not defined as a string).
864 return {s, N - (std::char_traits<Char>::to_int_type(s[N - 1]) == 0 ? 1 : 0)};
865 }
866 template <typename Char>
867 constexpr auto compile_string_to_view(detail::std_string_view<Char> s)
868 -> basic_string_view<Char> {
869 return {s.data(), s.size()};
870 }
871 } // namespace detail_exported
872
873 FMT_BEGIN_DETAIL_NAMESPACE
874
875 template <typename T> struct is_integral : std::is_integral<T> {};
876 template <> struct is_integral<int128_t> : std::true_type {};
877 template <> struct is_integral<uint128_t> : std::true_type {};
878
879 template <typename T>
880 using is_signed =
881 std::integral_constant<bool, std::numeric_limits<T>::is_signed ||
882 std::is_same<T, int128_t>::value>;
883
884 // Returns true if value is negative, false otherwise.
885 // Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
886 template <typename T, FMT_ENABLE_IF(is_signed<T>::value)>
887 FMT_CONSTEXPR auto is_negative(T value) -> bool {
888 return value < 0;
889 }
890 template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>
891 FMT_CONSTEXPR auto is_negative(T) -> bool {
892 return false;
893 }
894
895 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
896 FMT_CONSTEXPR auto is_supported_floating_point(T) -> uint16_t {
897 return (std::is_same<T, float>::value && FMT_USE_FLOAT) ||
898 (std::is_same<T, double>::value && FMT_USE_DOUBLE) ||
899 (std::is_same<T, long double>::value && FMT_USE_LONG_DOUBLE);
900 }
901
902 // Smallest of uint32_t, uint64_t, uint128_t that is large enough to
903 // represent all values of an integral type T.
904 template <typename T>
905 using uint32_or_64_or_128_t =
906 conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS,
907 uint32_t,
908 conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>;
909 template <typename T>
910 using uint64_or_128_t = conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>;
911
912 #define FMT_POWERS_OF_10(factor) \
913 factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \
914 (factor)*1000000, (factor)*10000000, (factor)*100000000, \
915 (factor)*1000000000
916
917 // Converts value in the range [0, 100) to a string.
918 constexpr const char* digits2(size_t value) {
919 // GCC generates slightly better code when value is pointer-size.
920 return &"0001020304050607080910111213141516171819"
921 "2021222324252627282930313233343536373839"
922 "4041424344454647484950515253545556575859"
923 "6061626364656667686970717273747576777879"
924 "8081828384858687888990919293949596979899"[value * 2];
925 }
926
927 // Sign is a template parameter to workaround a bug in gcc 4.8.
928 template <typename Char, typename Sign> constexpr Char sign(Sign s) {
929 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 604
930 static_assert(std::is_same<Sign, sign_t>::value, "");
931 #endif
932 return static_cast<Char>("\0-+ "[s]);
933 }
934
935 template <typename T> FMT_CONSTEXPR auto count_digits_fallback(T n) -> int {
936 int count = 1;
937 for (;;) {
938 // Integer division is slow so do it for a group of four digits instead
939 // of for every digit. The idea comes from the talk by Alexandrescu
940 // "Three Optimization Tips for C++". See speed-test for a comparison.
941 if (n < 10) return count;
942 if (n < 100) return count + 1;
943 if (n < 1000) return count + 2;
944 if (n < 10000) return count + 3;
945 n /= 10000u;
946 count += 4;
947 }
948 }
949 #if FMT_USE_INT128
950 FMT_CONSTEXPR inline auto count_digits(uint128_t n) -> int {
951 return count_digits_fallback(n);
952 }
953 #endif
954
955 #ifdef FMT_BUILTIN_CLZLL
956 // It is a separate function rather than a part of count_digits to workaround
957 // the lack of static constexpr in constexpr functions.
958 inline auto do_count_digits(uint64_t n) -> int {
959 // This has comparable performance to the version by Kendall Willets
960 // (https://github.com/fmtlib/format-benchmark/blob/master/digits10)
961 // but uses smaller tables.
962 // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)).
963 static constexpr uint8_t bsr2log10[] = {
964 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
965 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10,
966 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15,
967 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20};
968 auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63];
969 static constexpr const uint64_t zero_or_powers_of_10[] = {
970 0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL),
971 10000000000000000000ULL};
972 return t - (n < zero_or_powers_of_10[t]);
973 }
974 #endif
975
976 // Returns the number of decimal digits in n. Leading zeros are not counted
977 // except for n == 0 in which case count_digits returns 1.
978 FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int {
979 #ifdef FMT_BUILTIN_CLZLL
980 if (!is_constant_evaluated()) {
981 return do_count_digits(n);
982 }
983 #endif
984 return count_digits_fallback(n);
985 }
986
987 // Counts the number of digits in n. BITS = log2(radix).
988 template <int BITS, typename UInt>
989 FMT_CONSTEXPR auto count_digits(UInt n) -> int {
990 #ifdef FMT_BUILTIN_CLZ
991 if (num_bits<UInt>() == 32)
992 return (FMT_BUILTIN_CLZ(static_cast<uint32_t>(n) | 1) ^ 31) / BITS + 1;
993 #endif
994 // Lambda avoids unreachable code warnings from NVHPC.
995 return [](UInt m) {
996 int num_digits = 0;
997 do {
998 ++num_digits;
999 } while ((m >>= BITS) != 0);
1000 return num_digits;
1001 }(n);
1002 }
1003
1004 template <> auto count_digits<4>(detail::fallback_uintptr n) -> int;
1005
1006 #ifdef FMT_BUILTIN_CLZ
1007 // It is a separate function rather than a part of count_digits to workaround
1008 // the lack of static constexpr in constexpr functions.
1009 FMT_INLINE auto do_count_digits(uint32_t n) -> int {
1010 // An optimization by Kendall Willets from https://bit.ly/3uOIQrB.
1011 // This increments the upper 32 bits (log10(T) - 1) when >= T is added.
1012 # define FMT_INC(T) (((sizeof(# T) - 1ull) << 32) - T)
1013 static constexpr uint64_t table[] = {
1014 FMT_INC(0), FMT_INC(0), FMT_INC(0), // 8
1015 FMT_INC(10), FMT_INC(10), FMT_INC(10), // 64
1016 FMT_INC(100), FMT_INC(100), FMT_INC(100), // 512
1017 FMT_INC(1000), FMT_INC(1000), FMT_INC(1000), // 4096
1018 FMT_INC(10000), FMT_INC(10000), FMT_INC(10000), // 32k
1019 FMT_INC(100000), FMT_INC(100000), FMT_INC(100000), // 256k
1020 FMT_INC(1000000), FMT_INC(1000000), FMT_INC(1000000), // 2048k
1021 FMT_INC(10000000), FMT_INC(10000000), FMT_INC(10000000), // 16M
1022 FMT_INC(100000000), FMT_INC(100000000), FMT_INC(100000000), // 128M
1023 FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000), // 1024M
1024 FMT_INC(1000000000), FMT_INC(1000000000) // 4B
1025 };
1026 auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31];
1027 return static_cast<int>((n + inc) >> 32);
1028 }
1029 #endif
1030
1031 // Optional version of count_digits for better performance on 32-bit platforms.
1032 FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int {
1033 #ifdef FMT_BUILTIN_CLZ
1034 if (!is_constant_evaluated()) {
1035 return do_count_digits(n);
1036 }
1037 #endif
1038 return count_digits_fallback(n);
1039 }
1040
1041 template <typename Int> constexpr auto digits10() FMT_NOEXCEPT -> int {
1042 return std::numeric_limits<Int>::digits10;
1043 }
1044 template <> constexpr auto digits10<int128_t>() FMT_NOEXCEPT -> int {
1045 return 38;
1046 }
1047 template <> constexpr auto digits10<uint128_t>() FMT_NOEXCEPT -> int {
1048 return 38;
1049 }
1050
1051 template <typename Char> struct thousands_sep_result {
1052 std::string grouping;
1053 Char thousands_sep;
1054 };
1055
1056 template <typename Char>
1057 FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char>;
1058 template <typename Char>
1059 inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<Char> {
1060 auto result = thousands_sep_impl<char>(loc);
1061 return {result.grouping, Char(result.thousands_sep)};
1062 }
1063 template <>
1064 inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<wchar_t> {
1065 return thousands_sep_impl<wchar_t>(loc);
1066 }
1067
1068 template <typename Char>
1069 FMT_API auto decimal_point_impl(locale_ref loc) -> Char;
1070 template <typename Char> inline auto decimal_point(locale_ref loc) -> Char {
1071 return Char(decimal_point_impl<char>(loc));
1072 }
1073 template <> inline auto decimal_point(locale_ref loc) -> wchar_t {
1074 return decimal_point_impl<wchar_t>(loc);
1075 }
1076
1077 // Compares two characters for equality.
1078 template <typename Char> auto equal2(const Char* lhs, const char* rhs) -> bool {
1079 return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]);
1080 }
1081 inline auto equal2(const char* lhs, const char* rhs) -> bool {
1082 return memcmp(lhs, rhs, 2) == 0;
1083 }
1084
1085 // Copies two characters from src to dst.
1086 template <typename Char>
1087 FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) {
1088 if (!is_constant_evaluated() && sizeof(Char) == sizeof(char)) {
1089 memcpy(dst, src, 2);
1090 return;
1091 }
1092 *dst++ = static_cast<Char>(*src++);
1093 *dst = static_cast<Char>(*src);
1094 }
1095
1096 template <typename Iterator> struct format_decimal_result {
1097 Iterator begin;
1098 Iterator end;
1099 };
1100
1101 // Formats a decimal unsigned integer value writing into out pointing to a
1102 // buffer of specified size. The caller must ensure that the buffer is large
1103 // enough.
1104 template <typename Char, typename UInt>
1105 FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size)
1106 -> format_decimal_result<Char*> {
1107 FMT_ASSERT(size >= count_digits(value), "invalid digit count");
1108 out += size;
1109 Char* end = out;
1110 while (value >= 100) {
1111 // Integer division is slow so do it for a group of two digits instead
1112 // of for every digit. The idea comes from the talk by Alexandrescu
1113 // "Three Optimization Tips for C++". See speed-test for a comparison.
1114 out -= 2;
1115 copy2(out, digits2(static_cast<size_t>(value % 100)));
1116 value /= 100;
1117 }
1118 if (value < 10) {
1119 *--out = static_cast<Char>('0' + value);
1120 return {out, end};
1121 }
1122 out -= 2;
1123 copy2(out, digits2(static_cast<size_t>(value)));
1124 return {out, end};
1125 }
1126
1127 template <typename Char, typename UInt, typename Iterator,
1128 FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<Iterator>>::value)>
1129 inline auto format_decimal(Iterator out, UInt value, int size)
1130 -> format_decimal_result<Iterator> {
1131 // Buffer is large enough to hold all digits (digits10 + 1).
1132 Char buffer[digits10<UInt>() + 1];
1133 auto end = format_decimal(buffer, value, size).end;
1134 return {out, detail::copy_str_noinline<Char>(buffer, end, out)};
1135 }
1136
1137 template <unsigned BASE_BITS, typename Char, typename UInt>
1138 FMT_CONSTEXPR auto format_uint(Char* buffer, UInt value, int num_digits,
1139 bool upper = false) -> Char* {
1140 buffer += num_digits;
1141 Char* end = buffer;
1142 do {
1143 const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
1144 unsigned digit = (value & ((1 << BASE_BITS) - 1));
1145 *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
1146 : digits[digit]);
1147 } while ((value >>= BASE_BITS) != 0);
1148 return end;
1149 }
1150
1151 template <unsigned BASE_BITS, typename Char>
1152 auto format_uint(Char* buffer, detail::fallback_uintptr n, int num_digits,
1153 bool = false) -> Char* {
1154 auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
1155 int start = (num_digits + char_digits - 1) / char_digits - 1;
1156 if (int start_digits = num_digits % char_digits) {
1157 unsigned value = n.value[start--];
1158 buffer = format_uint<BASE_BITS>(buffer, value, start_digits);
1159 }
1160 for (; start >= 0; --start) {
1161 unsigned value = n.value[start];
1162 buffer += char_digits;
1163 auto p = buffer;
1164 for (int i = 0; i < char_digits; ++i) {
1165 unsigned digit = (value & ((1 << BASE_BITS) - 1));
1166 *--p = static_cast<Char>("0123456789abcdef"[digit]);
1167 value >>= BASE_BITS;
1168 }
1169 }
1170 return buffer;
1171 }
1172
1173 template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
1174 inline auto format_uint(It out, UInt value, int num_digits, bool upper = false)
1175 -> It {
1176 if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {
1177 format_uint<BASE_BITS>(ptr, value, num_digits, upper);
1178 return out;
1179 }
1180 // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1).
1181 char buffer[num_bits<UInt>() / BASE_BITS + 1];
1182 format_uint<BASE_BITS>(buffer, value, num_digits, upper);
1183 return detail::copy_str_noinline<Char>(buffer, buffer + num_digits, out);
1184 }
1185
1186 // A converter from UTF-8 to UTF-16.
1187 class utf8_to_utf16 {
1188 private:
1189 basic_memory_buffer<wchar_t> buffer_;
1190
1191 public:
1192 FMT_API explicit utf8_to_utf16(string_view s);
1193 operator basic_string_view<wchar_t>() const { return {&buffer_[0], size()}; }
1194 auto size() const -> size_t { return buffer_.size() - 1; }
1195 auto c_str() const -> const wchar_t* { return &buffer_[0]; }
1196 auto str() const -> std::wstring { return {&buffer_[0], size()}; }
1197 };
1198
1199 namespace dragonbox {
1200
1201 // Type-specific information that Dragonbox uses.
1202 template <class T> struct float_info;
1203
1204 template <> struct float_info<float> {
1205 using carrier_uint = uint32_t;
1206 static const int significand_bits = 23;
1207 static const int exponent_bits = 8;
1208 static const int min_exponent = -126;
1209 static const int max_exponent = 127;
1210 static const int exponent_bias = -127;
1211 static const int decimal_digits = 9;
1212 static const int kappa = 1;
1213 static const int big_divisor = 100;
1214 static const int small_divisor = 10;
1215 static const int min_k = -31;
1216 static const int max_k = 46;
1217 static const int cache_bits = 64;
1218 static const int divisibility_check_by_5_threshold = 39;
1219 static const int case_fc_pm_half_lower_threshold = -1;
1220 static const int case_fc_pm_half_upper_threshold = 6;
1221 static const int case_fc_lower_threshold = -2;
1222 static const int case_fc_upper_threshold = 6;
1223 static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
1224 static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
1225 static const int shorter_interval_tie_lower_threshold = -35;
1226 static const int shorter_interval_tie_upper_threshold = -35;
1227 static const int max_trailing_zeros = 7;
1228 };
1229
1230 template <> struct float_info<double> {
1231 using carrier_uint = uint64_t;
1232 static const int significand_bits = 52;
1233 static const int exponent_bits = 11;
1234 static const int min_exponent = -1022;
1235 static const int max_exponent = 1023;
1236 static const int exponent_bias = -1023;
1237 static const int decimal_digits = 17;
1238 static const int kappa = 2;
1239 static const int big_divisor = 1000;
1240 static const int small_divisor = 100;
1241 static const int min_k = -292;
1242 static const int max_k = 326;
1243 static const int cache_bits = 128;
1244 static const int divisibility_check_by_5_threshold = 86;
1245 static const int case_fc_pm_half_lower_threshold = -2;
1246 static const int case_fc_pm_half_upper_threshold = 9;
1247 static const int case_fc_lower_threshold = -4;
1248 static const int case_fc_upper_threshold = 9;
1249 static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
1250 static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
1251 static const int shorter_interval_tie_lower_threshold = -77;
1252 static const int shorter_interval_tie_upper_threshold = -77;
1253 static const int max_trailing_zeros = 16;
1254 };
1255
1256 template <typename T> struct decimal_fp {
1257 using significand_type = typename float_info<T>::carrier_uint;
1258 significand_type significand;
1259 int exponent;
1260 };
1261
1262 template <typename T>
1263 FMT_API auto to_decimal(T x) FMT_NOEXCEPT -> decimal_fp<T>;
1264 } // namespace dragonbox
1265
1266 template <typename T>
1267 constexpr auto exponent_mask() ->
1268 typename dragonbox::float_info<T>::carrier_uint {
1269 using uint = typename dragonbox::float_info<T>::carrier_uint;
1270 return ((uint(1) << dragonbox::float_info<T>::exponent_bits) - 1)
1271 << dragonbox::float_info<T>::significand_bits;
1272 }
1273
1274 // Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
1275 template <typename Char, typename It>
1276 FMT_CONSTEXPR auto write_exponent(int exp, It it) -> It {
1277 FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range");
1278 if (exp < 0) {
1279 *it++ = static_cast<Char>('-');
1280 exp = -exp;
1281 } else {
1282 *it++ = static_cast<Char>('+');
1283 }
1284 if (exp >= 100) {
1285 const char* top = digits2(to_unsigned(exp / 100));
1286 if (exp >= 1000) *it++ = static_cast<Char>(top[0]);
1287 *it++ = static_cast<Char>(top[1]);
1288 exp %= 100;
1289 }
1290 const char* d = digits2(to_unsigned(exp));
1291 *it++ = static_cast<Char>(d[0]);
1292 *it++ = static_cast<Char>(d[1]);
1293 return it;
1294 }
1295
1296 template <typename T>
1297 FMT_HEADER_ONLY_CONSTEXPR20 auto format_float(T value, int precision,
1298 float_specs specs,
1299 buffer<char>& buf) -> int;
1300
1301 // Formats a floating-point number with snprintf.
1302 template <typename T>
1303 auto snprintf_float(T value, int precision, float_specs specs,
1304 buffer<char>& buf) -> int;
1305
1306 template <typename T> constexpr auto promote_float(T value) -> T {
1307 return value;
1308 }
1309 constexpr auto promote_float(float value) -> double {
1310 return static_cast<double>(value);
1311 }
1312
1313 template <typename OutputIt, typename Char>
1314 FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n,
1315 const fill_t<Char>& fill) -> OutputIt {
1316 auto fill_size = fill.size();
1317 if (fill_size == 1) return detail::fill_n(it, n, fill[0]);
1318 auto data = fill.data();
1319 for (size_t i = 0; i < n; ++i)
1320 it = copy_str<Char>(data, data + fill_size, it);
1321 return it;
1322 }
1323
1324 // Writes the output of f, padded according to format specifications in specs.
1325 // size: output size in code units.
1326 // width: output display width in (terminal) column positions.
1327 template <align::type align = align::left, typename OutputIt, typename Char,
1328 typename F>
1329 FMT_CONSTEXPR auto write_padded(OutputIt out,
1330 const basic_format_specs<Char>& specs,
1331 size_t size, size_t width, F&& f) -> OutputIt {
1332 static_assert(align == align::left || align == align::right, "");
1333 unsigned spec_width = to_unsigned(specs.width);
1334 size_t padding = spec_width > width ? spec_width - width : 0;
1335 // Shifts are encoded as string literals because static constexpr is not
1336 // supported in constexpr functions.
1337 auto* shifts = align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01";
1338 size_t left_padding = padding >> shifts[specs.align];
1339 size_t right_padding = padding - left_padding;
1340 auto it = reserve(out, size + padding * specs.fill.size());
1341 if (left_padding != 0) it = fill(it, left_padding, specs.fill);
1342 it = f(it);
1343 if (right_padding != 0) it = fill(it, right_padding, specs.fill);
1344 return base_iterator(out, it);
1345 }
1346
1347 template <align::type align = align::left, typename OutputIt, typename Char,
1348 typename F>
1349 constexpr auto write_padded(OutputIt out, const basic_format_specs<Char>& specs,
1350 size_t size, F&& f) -> OutputIt {
1351 return write_padded<align>(out, specs, size, size, f);
1352 }
1353
1354 template <align::type align = align::left, typename Char, typename OutputIt>
1355 FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes,
1356 const basic_format_specs<Char>& specs)
1357 -> OutputIt {
1358 return write_padded<align>(
1359 out, specs, bytes.size(), [bytes](reserve_iterator<OutputIt> it) {
1360 const char* data = bytes.data();
1361 return copy_str<Char>(data, data + bytes.size(), it);
1362 });
1363 }
1364
1365 template <typename Char, typename OutputIt, typename UIntPtr>
1366 auto write_ptr(OutputIt out, UIntPtr value,
1367 const basic_format_specs<Char>* specs) -> OutputIt {
1368 int num_digits = count_digits<4>(value);
1369 auto size = to_unsigned(num_digits) + size_t(2);
1370 auto write = [=](reserve_iterator<OutputIt> it) {
1371 *it++ = static_cast<Char>('0');
1372 *it++ = static_cast<Char>('x');
1373 return format_uint<4, Char>(it, value, num_digits);
1374 };
1375 return specs ? write_padded<align::right>(out, *specs, size, write)
1376 : base_iterator(out, write(reserve(out, size)));
1377 }
1378
1379 template <typename Char, typename OutputIt>
1380 FMT_CONSTEXPR auto write_char(OutputIt out, Char value,
1381 const basic_format_specs<Char>& specs)
1382 -> OutputIt {
1383 return write_padded(out, specs, 1, [=](reserve_iterator<OutputIt> it) {
1384 *it++ = value;
1385 return it;
1386 });
1387 }
1388 template <typename Char, typename OutputIt>
1389 FMT_CONSTEXPR auto write(OutputIt out, Char value,
1390 const basic_format_specs<Char>& specs,
1391 locale_ref loc = {}) -> OutputIt {
1392 return check_char_specs(specs)
1393 ? write_char(out, value, specs)
1394 : write(out, static_cast<int>(value), specs, loc);
1395 }
1396
1397 // Data for write_int that doesn't depend on output iterator type. It is used to
1398 // avoid template code bloat.
1399 template <typename Char> struct write_int_data {
1400 size_t size;
1401 size_t padding;
1402
1403 FMT_CONSTEXPR write_int_data(int num_digits, unsigned prefix,
1404 const basic_format_specs<Char>& specs)
1405 : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) {
1406 if (specs.align == align::numeric) {
1407 auto width = to_unsigned(specs.width);
1408 if (width > size) {
1409 padding = width - size;
1410 size = width;
1411 }
1412 } else if (specs.precision > num_digits) {
1413 size = (prefix >> 24) + to_unsigned(specs.precision);
1414 padding = to_unsigned(specs.precision - num_digits);
1415 }
1416 }
1417 };
1418
1419 // Writes an integer in the format
1420 // <left-padding><prefix><numeric-padding><digits><right-padding>
1421 // where <digits> are written by write_digits(it).
1422 // prefix contains chars in three lower bytes and the size in the fourth byte.
1423 template <typename OutputIt, typename Char, typename W>
1424 FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, int num_digits,
1425 unsigned prefix,
1426 const basic_format_specs<Char>& specs,
1427 W write_digits) -> OutputIt {
1428 // Slightly faster check for specs.width == 0 && specs.precision == -1.
1429 if ((specs.width | (specs.precision + 1)) == 0) {
1430 auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24));
1431 if (prefix != 0) {
1432 for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
1433 *it++ = static_cast<Char>(p & 0xff);
1434 }
1435 return base_iterator(out, write_digits(it));
1436 }
1437 auto data = write_int_data<Char>(num_digits, prefix, specs);
1438 return write_padded<align::right>(
1439 out, specs, data.size, [=](reserve_iterator<OutputIt> it) {
1440 for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
1441 *it++ = static_cast<Char>(p & 0xff);
1442 it = detail::fill_n(it, data.padding, static_cast<Char>('0'));
1443 return write_digits(it);
1444 });
1445 }
1446
1447 template <typename Char> class digit_grouping {
1448 private:
1449 thousands_sep_result<Char> sep_;
1450
1451 struct next_state {
1452 std::string::const_iterator group;
1453 int pos;
1454 };
1455 next_state initial_state() const { return {sep_.grouping.begin(), 0}; }
1456
1457 // Returns the next digit group separator position.
1458 int next(next_state& state) const {
1459 if (!sep_.thousands_sep) return max_value<int>();
1460 if (state.group == sep_.grouping.end())
1461 return state.pos += sep_.grouping.back();
1462 if (*state.group <= 0 || *state.group == max_value<char>())
1463 return max_value<int>();
1464 state.pos += *state.group++;
1465 return state.pos;
1466 }
1467
1468 public:
1469 explicit digit_grouping(locale_ref loc, bool localized = true) {
1470 if (localized)
1471 sep_ = thousands_sep<Char>(loc);
1472 else
1473 sep_.thousands_sep = Char();
1474 }
1475 explicit digit_grouping(thousands_sep_result<Char> sep) : sep_(sep) {}
1476
1477 Char separator() const { return sep_.thousands_sep; }
1478
1479 int count_separators(int num_digits) const {
1480 int count = 0;
1481 auto state = initial_state();
1482 while (num_digits > next(state)) ++count;
1483 return count;
1484 }
1485
1486 // Applies grouping to digits and write the output to out.
1487 template <typename Out, typename C>
1488 Out apply(Out out, basic_string_view<C> digits) const {
1489 auto num_digits = static_cast<int>(digits.size());
1490 auto separators = basic_memory_buffer<int>();
1491 separators.push_back(0);
1492 auto state = initial_state();
1493 while (int i = next(state)) {
1494 if (i >= num_digits) break;
1495 separators.push_back(i);
1496 }
1497 for (int i = 0, sep_index = static_cast<int>(separators.size() - 1);
1498 i < num_digits; ++i) {
1499 if (num_digits - i == separators[sep_index]) {
1500 *out++ = separator();
1501 --sep_index;
1502 }
1503 *out++ = static_cast<Char>(digits[to_unsigned(i)]);
1504 }
1505 return out;
1506 }
1507 };
1508
1509 template <typename OutputIt, typename UInt, typename Char>
1510 auto write_int_localized(OutputIt out, UInt value, unsigned prefix,
1511 const basic_format_specs<Char>& specs,
1512 const digit_grouping<Char>& grouping) -> OutputIt {
1513 static_assert(std::is_same<uint64_or_128_t<UInt>, UInt>::value, "");
1514 int num_digits = count_digits(value);
1515 char digits[40];
1516 format_decimal(digits, value, num_digits);
1517 unsigned size = to_unsigned((prefix != 0 ? 1 : 0) + num_digits +
1518 grouping.count_separators(num_digits));
1519 return write_padded<align::right>(
1520 out, specs, size, size, [&](reserve_iterator<OutputIt> it) {
1521 if (prefix != 0) *it++ = static_cast<Char>(prefix);
1522 return grouping.apply(it, string_view(digits, to_unsigned(num_digits)));
1523 });
1524 }
1525
1526 template <typename OutputIt, typename UInt, typename Char>
1527 auto write_int_localized(OutputIt& out, UInt value, unsigned prefix,
1528 const basic_format_specs<Char>& specs, locale_ref loc)
1529 -> bool {
1530 auto grouping = digit_grouping<Char>(loc);
1531 out = write_int_localized(out, value, prefix, specs, grouping);
1532 return true;
1533 }
1534
1535 FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) {
1536 prefix |= prefix != 0 ? value << 8 : value;
1537 prefix += (1u + (value > 0xff ? 1 : 0)) << 24;
1538 }
1539
1540 template <typename UInt> struct write_int_arg {
1541 UInt abs_value;
1542 unsigned prefix;
1543 };
1544
1545 template <typename T>
1546 FMT_CONSTEXPR auto make_write_int_arg(T value, sign_t sign)
1547 -> write_int_arg<uint32_or_64_or_128_t<T>> {
1548 auto prefix = 0u;
1549 auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
1550 if (is_negative(value)) {
1551 prefix = 0x01000000 | '-';
1552 abs_value = 0 - abs_value;
1553 } else {
1554 constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+',
1555 0x1000000u | ' '};
1556 prefix = prefixes[sign];
1557 }
1558 return {abs_value, prefix};
1559 }
1560
1561 template <typename Char, typename OutputIt, typename T>
1562 FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg<T> arg,
1563 const basic_format_specs<Char>& specs,
1564 locale_ref loc) -> OutputIt {
1565 static_assert(std::is_same<T, uint32_or_64_or_128_t<T>>::value, "");
1566 auto abs_value = arg.abs_value;
1567 auto prefix = arg.prefix;
1568 switch (specs.type) {
1569 case presentation_type::none:
1570 case presentation_type::dec: {
1571 if (specs.localized &&
1572 write_int_localized(out, static_cast<uint64_or_128_t<T>>(abs_value),
1573 prefix, specs, loc)) {
1574 return out;
1575 }
1576 auto num_digits = count_digits(abs_value);
1577 return write_int(
1578 out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
1579 return format_decimal<Char>(it, abs_value, num_digits).end;
1580 });
1581 }
1582 case presentation_type::hex_lower:
1583 case presentation_type::hex_upper: {
1584 bool upper = specs.type == presentation_type::hex_upper;
1585 if (specs.alt)
1586 prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0');
1587 int num_digits = count_digits<4>(abs_value);
1588 return write_int(
1589 out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
1590 return format_uint<4, Char>(it, abs_value, num_digits, upper);
1591 });
1592 }
1593 case presentation_type::bin_lower:
1594 case presentation_type::bin_upper: {
1595 bool upper = specs.type == presentation_type::bin_upper;
1596 if (specs.alt)
1597 prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0');
1598 int num_digits = count_digits<1>(abs_value);
1599 return write_int(out, num_digits, prefix, specs,
1600 [=](reserve_iterator<OutputIt> it) {
1601 return format_uint<1, Char>(it, abs_value, num_digits);
1602 });
1603 }
1604 case presentation_type::oct: {
1605 int num_digits = count_digits<3>(abs_value);
1606 // Octal prefix '0' is counted as a digit, so only add it if precision
1607 // is not greater than the number of digits.
1608 if (specs.alt && specs.precision <= num_digits && abs_value != 0)
1609 prefix_append(prefix, '0');
1610 return write_int(out, num_digits, prefix, specs,
1611 [=](reserve_iterator<OutputIt> it) {
1612 return format_uint<3, Char>(it, abs_value, num_digits);
1613 });
1614 }
1615 case presentation_type::chr:
1616 return write_char(out, static_cast<Char>(abs_value), specs);
1617 default:
1618 throw_format_error("invalid type specifier");
1619 }
1620 return out;
1621 }
1622 template <typename Char, typename OutputIt, typename T>
1623 FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(
1624 OutputIt out, write_int_arg<T> arg, const basic_format_specs<Char>& specs,
1625 locale_ref loc) -> OutputIt {
1626 return write_int(out, arg, specs, loc);
1627 }
1628 template <typename Char, typename OutputIt, typename T,
1629 FMT_ENABLE_IF(is_integral<T>::value &&
1630 !std::is_same<T, bool>::value &&
1631 std::is_same<OutputIt, buffer_appender<Char>>::value)>
1632 FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
1633 const basic_format_specs<Char>& specs,
1634 locale_ref loc) -> OutputIt {
1635 return write_int_noinline(out, make_write_int_arg(value, specs.sign), specs,
1636 loc);
1637 }
1638 // An inlined version of write used in format string compilation.
1639 template <typename Char, typename OutputIt, typename T,
1640 FMT_ENABLE_IF(is_integral<T>::value &&
1641 !std::is_same<T, bool>::value &&
1642 !std::is_same<OutputIt, buffer_appender<Char>>::value)>
1643 FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
1644 const basic_format_specs<Char>& specs,
1645 locale_ref loc) -> OutputIt {
1646 return write_int(out, make_write_int_arg(value, specs.sign), specs, loc);
1647 }
1648
1649 template <typename Char, typename OutputIt>
1650 FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
1651 const basic_format_specs<Char>& specs) -> OutputIt {
1652 auto data = s.data();
1653 auto size = s.size();
1654 if (specs.precision >= 0 && to_unsigned(specs.precision) < size)
1655 size = code_point_index(s, to_unsigned(specs.precision));
1656 auto width =
1657 specs.width != 0 ? compute_width(basic_string_view<Char>(data, size)) : 0;
1658 return write_padded(out, specs, size, width,
1659 [=](reserve_iterator<OutputIt> it) {
1660 return copy_str<Char>(data, data + size, it);
1661 });
1662 }
1663 template <typename Char, typename OutputIt>
1664 FMT_CONSTEXPR auto write(OutputIt out,
1665 basic_string_view<type_identity_t<Char>> s,
1666 const basic_format_specs<Char>& specs, locale_ref)
1667 -> OutputIt {
1668 check_string_type_spec(specs.type);
1669 return write(out, s, specs);
1670 }
1671 template <typename Char, typename OutputIt>
1672 FMT_CONSTEXPR auto write(OutputIt out, const Char* s,
1673 const basic_format_specs<Char>& specs, locale_ref)
1674 -> OutputIt {
1675 return check_cstring_type_spec(specs.type)
1676 ? write(out, basic_string_view<Char>(s), specs, {})
1677 : write_ptr<Char>(out, to_uintptr(s), &specs);
1678 }
1679
1680 template <typename Char, typename OutputIt>
1681 FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isinf,
1682 basic_format_specs<Char> specs,
1683 const float_specs& fspecs) -> OutputIt {
1684 auto str =
1685 isinf ? (fspecs.upper ? "INF" : "inf") : (fspecs.upper ? "NAN" : "nan");
1686 constexpr size_t str_size = 3;
1687 auto sign = fspecs.sign;
1688 auto size = str_size + (sign ? 1 : 0);
1689 // Replace '0'-padding with space for non-finite values.
1690 const bool is_zero_fill =
1691 specs.fill.size() == 1 && *specs.fill.data() == static_cast<Char>('0');
1692 if (is_zero_fill) specs.fill[0] = static_cast<Char>(' ');
1693 return write_padded(out, specs, size, [=](reserve_iterator<OutputIt> it) {
1694 if (sign) *it++ = detail::sign<Char>(sign);
1695 return copy_str<Char>(str, str + str_size, it);
1696 });
1697 }
1698
1699 // A decimal floating-point number significand * pow(10, exp).
1700 struct big_decimal_fp {
1701 const char* significand;
1702 int significand_size;
1703 int exponent;
1704 };
1705
1706 constexpr auto get_significand_size(const big_decimal_fp& fp) -> int {
1707 return fp.significand_size;
1708 }
1709 template <typename T>
1710 inline auto get_significand_size(const dragonbox::decimal_fp<T>& fp) -> int {
1711 return count_digits(fp.significand);
1712 }
1713
1714 template <typename Char, typename OutputIt>
1715 constexpr auto write_significand(OutputIt out, const char* significand,
1716 int significand_size) -> OutputIt {
1717 return copy_str<Char>(significand, significand + significand_size, out);
1718 }
1719 template <typename Char, typename OutputIt, typename UInt>
1720 inline auto write_significand(OutputIt out, UInt significand,
1721 int significand_size) -> OutputIt {
1722 return format_decimal<Char>(out, significand, significand_size).end;
1723 }
1724 template <typename Char, typename OutputIt, typename T, typename Grouping>
1725 FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
1726 int significand_size, int exponent,
1727 const Grouping& grouping) -> OutputIt {
1728 if (!grouping.separator()) {
1729 out = write_significand<Char>(out, significand, significand_size);
1730 return detail::fill_n(out, exponent, static_cast<Char>('0'));
1731 }
1732 auto buffer = memory_buffer();
1733 write_significand<char>(appender(buffer), significand, significand_size);
1734 detail::fill_n(appender(buffer), exponent, '0');
1735 return grouping.apply(out, string_view(buffer.data(), buffer.size()));
1736 }
1737
1738 template <typename Char, typename UInt,
1739 FMT_ENABLE_IF(std::is_integral<UInt>::value)>
1740 inline auto write_significand(Char* out, UInt significand, int significand_size,
1741 int integral_size, Char decimal_point) -> Char* {
1742 if (!decimal_point)
1743 return format_decimal(out, significand, significand_size).end;
1744 out += significand_size + 1;
1745 Char* end = out;
1746 int floating_size = significand_size - integral_size;
1747 for (int i = floating_size / 2; i > 0; --i) {
1748 out -= 2;
1749 copy2(out, digits2(significand % 100));
1750 significand /= 100;
1751 }
1752 if (floating_size % 2 != 0) {
1753 *--out = static_cast<Char>('0' + significand % 10);
1754 significand /= 10;
1755 }
1756 *--out = decimal_point;
1757 format_decimal(out - integral_size, significand, integral_size);
1758 return end;
1759 }
1760
1761 template <typename OutputIt, typename UInt, typename Char,
1762 FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>
1763 inline auto write_significand(OutputIt out, UInt significand,
1764 int significand_size, int integral_size,
1765 Char decimal_point) -> OutputIt {
1766 // Buffer is large enough to hold digits (digits10 + 1) and a decimal point.
1767 Char buffer[digits10<UInt>() + 2];
1768 auto end = write_significand(buffer, significand, significand_size,
1769 integral_size, decimal_point);
1770 return detail::copy_str_noinline<Char>(buffer, end, out);
1771 }
1772
1773 template <typename OutputIt, typename Char>
1774 FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand,
1775 int significand_size, int integral_size,
1776 Char decimal_point) -> OutputIt {
1777 out = detail::copy_str_noinline<Char>(significand,
1778 significand + integral_size, out);
1779 if (!decimal_point) return out;
1780 *out++ = decimal_point;
1781 return detail::copy_str_noinline<Char>(significand + integral_size,
1782 significand + significand_size, out);
1783 }
1784
1785 template <typename OutputIt, typename Char, typename T, typename Grouping>
1786 FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
1787 int significand_size, int integral_size,
1788 Char decimal_point,
1789 const Grouping& grouping) -> OutputIt {
1790 if (!grouping.separator()) {
1791 return write_significand(out, significand, significand_size, integral_size,
1792 decimal_point);
1793 }
1794 auto buffer = basic_memory_buffer<Char>();
1795 write_significand(buffer_appender<Char>(buffer), significand,
1796 significand_size, integral_size, decimal_point);
1797 grouping.apply(
1798 out, basic_string_view<Char>(buffer.data(), to_unsigned(integral_size)));
1799 return detail::copy_str_noinline<Char>(buffer.data() + integral_size,
1800 buffer.end(), out);
1801 }
1802
1803 template <typename OutputIt, typename DecimalFP, typename Char,
1804 typename Grouping = digit_grouping<Char>>
1805 FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& fp,
1806 const basic_format_specs<Char>& specs,
1807 float_specs fspecs, locale_ref loc)
1808 -> OutputIt {
1809 auto significand = fp.significand;
1810 int significand_size = get_significand_size(fp);
1811 constexpr Char zero = static_cast<Char>('0');
1812 auto sign = fspecs.sign;
1813 size_t size = to_unsigned(significand_size) + (sign ? 1 : 0);
1814 using iterator = reserve_iterator<OutputIt>;
1815
1816 Char decimal_point =
1817 fspecs.locale ? detail::decimal_point<Char>(loc) : static_cast<Char>('.');
1818
1819 int output_exp = fp.exponent + significand_size - 1;
1820 auto use_exp_format = [=]() {
1821 if (fspecs.format == float_format::exp) return true;
1822 if (fspecs.format != float_format::general) return false;
1823 // Use the fixed notation if the exponent is in [exp_lower, exp_upper),
1824 // e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation.
1825 const int exp_lower = -4, exp_upper = 16;
1826 return output_exp < exp_lower ||
1827 output_exp >= (fspecs.precision > 0 ? fspecs.precision : exp_upper);
1828 };
1829 if (use_exp_format()) {
1830 int num_zeros = 0;
1831 if (fspecs.showpoint) {
1832 num_zeros = fspecs.precision - significand_size;
1833 if (num_zeros < 0) num_zeros = 0;
1834 size += to_unsigned(num_zeros);
1835 } else if (significand_size == 1) {
1836 decimal_point = Char();
1837 }
1838 auto abs_output_exp = output_exp >= 0 ? output_exp : -output_exp;
1839 int exp_digits = 2;
1840 if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3;
1841
1842 size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits);
1843 char exp_char = fspecs.upper ? 'E' : 'e';
1844 auto write = [=](iterator it) {
1845 if (sign) *it++ = detail::sign<Char>(sign);
1846 // Insert a decimal point after the first digit and add an exponent.
1847 it = write_significand(it, significand, significand_size, 1,
1848 decimal_point);
1849 if (num_zeros > 0) it = detail::fill_n(it, num_zeros, zero);
1850 *it++ = static_cast<Char>(exp_char);
1851 return write_exponent<Char>(output_exp, it);
1852 };
1853 return specs.width > 0 ? write_padded<align::right>(out, specs, size, write)
1854 : base_iterator(out, write(reserve(out, size)));
1855 }
1856
1857 int exp = fp.exponent + significand_size;
1858 if (fp.exponent >= 0) {
1859 // 1234e5 -> 123400000[.0+]
1860 size += to_unsigned(fp.exponent);
1861 int num_zeros = fspecs.precision - exp;
1862 #ifdef FMT_FUZZ
1863 if (num_zeros > 5000)
1864 throw std::runtime_error("fuzz mode - avoiding excessive cpu use");
1865 #endif
1866 if (fspecs.showpoint) {
1867 if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 1;
1868 if (num_zeros > 0) size += to_unsigned(num_zeros) + 1;
1869 }
1870 auto grouping = Grouping(loc, fspecs.locale);
1871 size += to_unsigned(grouping.count_separators(significand_size));
1872 return write_padded<align::right>(out, specs, size, [&](iterator it) {
1873 if (sign) *it++ = detail::sign<Char>(sign);
1874 it = write_significand<Char>(it, significand, significand_size,
1875 fp.exponent, grouping);
1876 if (!fspecs.showpoint) return it;
1877 *it++ = decimal_point;
1878 return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
1879 });
1880 } else if (exp > 0) {
1881 // 1234e-2 -> 12.34[0+]
1882 int num_zeros = fspecs.showpoint ? fspecs.precision - significand_size : 0;
1883 size += 1 + to_unsigned(num_zeros > 0 ? num_zeros : 0);
1884 auto grouping = Grouping(loc, fspecs.locale);
1885 size += to_unsigned(grouping.count_separators(significand_size));
1886 return write_padded<align::right>(out, specs, size, [&](iterator it) {
1887 if (sign) *it++ = detail::sign<Char>(sign);
1888 it = write_significand(it, significand, significand_size, exp,
1889 decimal_point, grouping);
1890 return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
1891 });
1892 }
1893 // 1234e-6 -> 0.001234
1894 int num_zeros = -exp;
1895 if (significand_size == 0 && fspecs.precision >= 0 &&
1896 fspecs.precision < num_zeros) {
1897 num_zeros = fspecs.precision;
1898 }
1899 bool pointy = num_zeros != 0 || significand_size != 0 || fspecs.showpoint;
1900 size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros);
1901 return write_padded<align::right>(out, specs, size, [&](iterator it) {
1902 if (sign) *it++ = detail::sign<Char>(sign);
1903 *it++ = zero;
1904 if (!pointy) return it;
1905 *it++ = decimal_point;
1906 it = detail::fill_n(it, num_zeros, zero);
1907 return write_significand<Char>(it, significand, significand_size);
1908 });
1909 }
1910
1911 template <typename Char> class fallback_digit_grouping {
1912 public:
1913 constexpr fallback_digit_grouping(locale_ref, bool) {}
1914
1915 constexpr Char separator() const { return Char(); }
1916
1917 constexpr int count_separators(int) const { return 0; }
1918
1919 template <typename Out, typename C>
1920 constexpr Out apply(Out out, basic_string_view<C>) const {
1921 return out;
1922 }
1923 };
1924
1925 template <typename OutputIt, typename DecimalFP, typename Char>
1926 FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& fp,
1927 const basic_format_specs<Char>& specs,
1928 float_specs fspecs, locale_ref loc)
1929 -> OutputIt {
1930 if (is_constant_evaluated()) {
1931 return do_write_float<OutputIt, DecimalFP, Char,
1932 fallback_digit_grouping<Char>>(out, fp, specs, fspecs,
1933 loc);
1934 } else {
1935 return do_write_float(out, fp, specs, fspecs, loc);
1936 }
1937 }
1938
1939 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1940 FMT_CONSTEXPR20 bool isinf(T value) {
1941 if (is_constant_evaluated()) {
1942 #if defined(__cpp_if_constexpr)
1943 if constexpr (std::numeric_limits<double>::is_iec559) {
1944 auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
1945 constexpr auto significand_bits =
1946 dragonbox::float_info<double>::significand_bits;
1947 return (bits & exponent_mask<double>()) &&
1948 !(bits & ((uint64_t(1) << significand_bits) - 1));
1949 }
1950 #endif
1951 }
1952 return std::isinf(value);
1953 }
1954
1955 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1956 FMT_CONSTEXPR20 bool isfinite(T value) {
1957 if (is_constant_evaluated()) {
1958 #if defined(__cpp_if_constexpr)
1959 if constexpr (std::numeric_limits<double>::is_iec559) {
1960 auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
1961 return (bits & exponent_mask<double>()) != exponent_mask<double>();
1962 }
1963 #endif
1964 }
1965 return std::isfinite(value);
1966 }
1967
1968 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1969 FMT_INLINE FMT_CONSTEXPR bool signbit(T value) {
1970 if (is_constant_evaluated()) {
1971 #ifdef __cpp_if_constexpr
1972 if constexpr (std::numeric_limits<double>::is_iec559) {
1973 auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
1974 return (bits & (uint64_t(1) << (num_bits<uint64_t>() - 1))) != 0;
1975 }
1976 #endif
1977 }
1978 return std::signbit(value);
1979 }
1980
1981 template <typename Char, typename OutputIt, typename T,
1982 FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1983 FMT_CONSTEXPR20 auto write(OutputIt out, T value,
1984 basic_format_specs<Char> specs, locale_ref loc = {})
1985 -> OutputIt {
1986 if (const_check(!is_supported_floating_point(value))) return out;
1987 float_specs fspecs = parse_float_type_spec(specs);
1988 fspecs.sign = specs.sign;
1989 if (detail::signbit(value)) { // value < 0 is false for NaN so use signbit.
1990 fspecs.sign = sign::minus;
1991 value = -value;
1992 } else if (fspecs.sign == sign::minus) {
1993 fspecs.sign = sign::none;
1994 }
1995
1996 if (!detail::isfinite(value))
1997 return write_nonfinite(out, detail::isinf(value), specs, fspecs);
1998
1999 if (specs.align == align::numeric && fspecs.sign) {
2000 auto it = reserve(out, 1);
2001 *it++ = detail::sign<Char>(fspecs.sign);
2002 out = base_iterator(out, it);
2003 fspecs.sign = sign::none;
2004 if (specs.width != 0) --specs.width;
2005 }
2006
2007 memory_buffer buffer;
2008 if (fspecs.format == float_format::hex) {
2009 if (fspecs.sign) buffer.push_back(detail::sign<char>(fspecs.sign));
2010 snprintf_float(promote_float(value), specs.precision, fspecs, buffer);
2011 return write_bytes<align::right>(out, {buffer.data(), buffer.size()},
2012 specs);
2013 }
2014 int precision = specs.precision >= 0 || specs.type == presentation_type::none
2015 ? specs.precision
2016 : 6;
2017 if (fspecs.format == float_format::exp) {
2018 if (precision == max_value<int>())
2019 throw_format_error("number is too big");
2020 else
2021 ++precision;
2022 }
2023 if (const_check(std::is_same<T, float>())) fspecs.binary32 = true;
2024 if (!is_fast_float<T>()) fspecs.fallback = true;
2025 int exp = format_float(promote_float(value), precision, fspecs, buffer);
2026 fspecs.precision = precision;
2027 auto fp = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
2028 return write_float(out, fp, specs, fspecs, loc);
2029 }
2030
2031 template <typename Char, typename OutputIt, typename T,
2032 FMT_ENABLE_IF(is_fast_float<T>::value)>
2033 FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {
2034 if (is_constant_evaluated()) {
2035 return write(out, value, basic_format_specs<Char>());
2036 }
2037
2038 if (const_check(!is_supported_floating_point(value))) return out;
2039
2040 using floaty = conditional_t<std::is_same<T, long double>::value, double, T>;
2041 using uint = typename dragonbox::float_info<floaty>::carrier_uint;
2042 auto bits = bit_cast<uint>(value);
2043
2044 auto fspecs = float_specs();
2045 if (detail::signbit(value)) {
2046 fspecs.sign = sign::minus;
2047 value = -value;
2048 }
2049
2050 constexpr auto specs = basic_format_specs<Char>();
2051 uint mask = exponent_mask<floaty>();
2052 if ((bits & mask) == mask)
2053 return write_nonfinite(out, std::isinf(value), specs, fspecs);
2054
2055 auto dec = dragonbox::to_decimal(static_cast<floaty>(value));
2056 return write_float(out, dec, specs, fspecs, {});
2057 }
2058
2059 template <typename Char, typename OutputIt, typename T,
2060 FMT_ENABLE_IF(std::is_floating_point<T>::value &&
2061 !is_fast_float<T>::value)>
2062 inline auto write(OutputIt out, T value) -> OutputIt {
2063 return write(out, value, basic_format_specs<Char>());
2064 }
2065
2066 template <typename Char, typename OutputIt>
2067 auto write(OutputIt out, monostate, basic_format_specs<Char> = {},
2068 locale_ref = {}) -> OutputIt {
2069 FMT_ASSERT(false, "");
2070 return out;
2071 }
2072
2073 template <typename Char, typename OutputIt>
2074 FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> value)
2075 -> OutputIt {
2076 auto it = reserve(out, value.size());
2077 it = copy_str_noinline<Char>(value.begin(), value.end(), it);
2078 return base_iterator(out, it);
2079 }
2080
2081 template <typename Char, typename OutputIt, typename T,
2082 FMT_ENABLE_IF(is_string<T>::value)>
2083 constexpr auto write(OutputIt out, const T& value) -> OutputIt {
2084 return write<Char>(out, to_string_view(value));
2085 }
2086
2087 template <typename Char, typename OutputIt, typename T,
2088 FMT_ENABLE_IF(is_integral<T>::value &&
2089 !std::is_same<T, bool>::value &&
2090 !std::is_same<T, Char>::value)>
2091 FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
2092 auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
2093 bool negative = is_negative(value);
2094 // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
2095 if (negative) abs_value = ~abs_value + 1;
2096 int num_digits = count_digits(abs_value);
2097 auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
2098 auto it = reserve(out, size);
2099 if (auto ptr = to_pointer<Char>(it, size)) {
2100 if (negative) *ptr++ = static_cast<Char>('-');
2101 format_decimal<Char>(ptr, abs_value, num_digits);
2102 return out;
2103 }
2104 if (negative) *it++ = static_cast<Char>('-');
2105 it = format_decimal<Char>(it, abs_value, num_digits).end;
2106 return base_iterator(out, it);
2107 }
2108
2109 // FMT_ENABLE_IF() condition separated to workaround an MSVC bug.
2110 template <
2111 typename Char, typename OutputIt, typename T,
2112 bool check =
2113 std::is_enum<T>::value && !std::is_same<T, Char>::value &&
2114 mapped_type_constant<T, basic_format_context<OutputIt, Char>>::value !=
2115 type::custom_type,
2116 FMT_ENABLE_IF(check)>
2117 FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
2118 return write<Char>(
2119 out, static_cast<typename std::underlying_type<T>::type>(value));
2120 }
2121
2122 template <typename Char, typename OutputIt, typename T,
2123 FMT_ENABLE_IF(std::is_same<T, bool>::value)>
2124 FMT_CONSTEXPR auto write(OutputIt out, T value,
2125 const basic_format_specs<Char>& specs = {},
2126 locale_ref = {}) -> OutputIt {
2127 return specs.type != presentation_type::none &&
2128 specs.type != presentation_type::string
2129 ? write(out, value ? 1 : 0, specs, {})
2130 : write_bytes(out, value ? "true" : "false", specs);
2131 }
2132
2133 template <typename Char, typename OutputIt>
2134 FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt {
2135 auto it = reserve(out, 1);
2136 *it++ = value;
2137 return base_iterator(out, it);
2138 }
2139
2140 template <typename Char, typename OutputIt>
2141 FMT_CONSTEXPR_CHAR_TRAITS auto write(OutputIt out, const Char* value)
2142 -> OutputIt {
2143 if (!value) {
2144 throw_format_error("string pointer is null");
2145 } else {
2146 out = write(out, basic_string_view<Char>(value));
2147 }
2148 return out;
2149 }
2150
2151 template <typename Char, typename OutputIt, typename T,
2152 FMT_ENABLE_IF(std::is_same<T, void>::value)>
2153 auto write(OutputIt out, const T* value,
2154 const basic_format_specs<Char>& specs = {}, locale_ref = {})
2155 -> OutputIt {
2156 check_pointer_type_spec(specs.type, error_handler());
2157 return write_ptr<Char>(out, to_uintptr(value), &specs);
2158 }
2159
2160 // A write overload that handles implicit conversions.
2161 template <typename Char, typename OutputIt, typename T,
2162 typename Context = basic_format_context<OutputIt, Char>>
2163 FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> enable_if_t<
2164 std::is_class<T>::value && !is_string<T>::value &&
2165 !std::is_same<T, Char>::value &&
2166 !std::is_same<const T&,
2167 decltype(arg_mapper<Context>().map(value))>::value,
2168 OutputIt> {
2169 return write<Char>(out, arg_mapper<Context>().map(value));
2170 }
2171
2172 template <typename Char, typename OutputIt, typename T,
2173 typename Context = basic_format_context<OutputIt, Char>>
2174 FMT_CONSTEXPR auto write(OutputIt out, const T& value)
2175 -> enable_if_t<mapped_type_constant<T, Context>::value == type::custom_type,
2176 OutputIt> {
2177 using formatter_type =
2178 conditional_t<has_formatter<T, Context>::value,
2179 typename Context::template formatter_type<T>,
2180 fallback_formatter<T, Char>>;
2181 auto ctx = Context(out, {}, {});
2182 return formatter_type().format(value, ctx);
2183 }
2184
2185 // An argument visitor that formats the argument and writes it via the output
2186 // iterator. It's a class and not a generic lambda for compatibility with C++11.
2187 template <typename Char> struct default_arg_formatter {
2188 using iterator = buffer_appender<Char>;
2189 using context = buffer_context<Char>;
2190
2191 iterator out;
2192 basic_format_args<context> args;
2193 locale_ref loc;
2194
2195 template <typename T> auto operator()(T value) -> iterator {
2196 return write<Char>(out, value);
2197 }
2198 auto operator()(typename basic_format_arg<context>::handle h) -> iterator {
2199 basic_format_parse_context<Char> parse_ctx({});
2200 context format_ctx(out, args, loc);
2201 h.format(parse_ctx, format_ctx);
2202 return format_ctx.out();
2203 }
2204 };
2205
2206 template <typename Char> struct arg_formatter {
2207 using iterator = buffer_appender<Char>;
2208 using context = buffer_context<Char>;
2209
2210 iterator out;
2211 const basic_format_specs<Char>& specs;
2212 locale_ref locale;
2213
2214 template <typename T>
2215 FMT_CONSTEXPR FMT_INLINE auto operator()(T value) -> iterator {
2216 return detail::write(out, value, specs, locale);
2217 }
2218 auto operator()(typename basic_format_arg<context>::handle) -> iterator {
2219 // User-defined types are handled separately because they require access
2220 // to the parse context.
2221 return out;
2222 }
2223 };
2224
2225 template <typename Char> struct custom_formatter {
2226 basic_format_parse_context<Char>& parse_ctx;
2227 buffer_context<Char>& ctx;
2228
2229 void operator()(
2230 typename basic_format_arg<buffer_context<Char>>::handle h) const {
2231 h.format(parse_ctx, ctx);
2232 }
2233 template <typename T> void operator()(T) const {}
2234 };
2235
2236 template <typename T>
2237 using is_integer =
2238 bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&
2239 !std::is_same<T, char>::value &&
2240 !std::is_same<T, wchar_t>::value>;
2241
2242 template <typename ErrorHandler> class width_checker {
2243 public:
2244 explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {}
2245
2246 template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
2247 FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
2248 if (is_negative(value)) handler_.on_error("negative width");
2249 return static_cast<unsigned long long>(value);
2250 }
2251
2252 template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
2253 FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
2254 handler_.on_error("width is not integer");
2255 return 0;
2256 }
2257
2258 private:
2259 ErrorHandler& handler_;
2260 };
2261
2262 template <typename ErrorHandler> class precision_checker {
2263 public:
2264 explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {}
2265
2266 template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
2267 FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
2268 if (is_negative(value)) handler_.on_error("negative precision");
2269 return static_cast<unsigned long long>(value);
2270 }
2271
2272 template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
2273 FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
2274 handler_.on_error("precision is not integer");
2275 return 0;
2276 }
2277
2278 private:
2279 ErrorHandler& handler_;
2280 };
2281
2282 template <template <typename> class Handler, typename FormatArg,
2283 typename ErrorHandler>
2284 FMT_CONSTEXPR auto get_dynamic_spec(FormatArg arg, ErrorHandler eh) -> int {
2285 unsigned long long value = visit_format_arg(Handler<ErrorHandler>(eh), arg);
2286 if (value > to_unsigned(max_value<int>())) eh.on_error("number is too big");
2287 return static_cast<int>(value);
2288 }
2289
2290 template <typename Context, typename ID>
2291 FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) ->
2292 typename Context::format_arg {
2293 auto arg = ctx.arg(id);
2294 if (!arg) ctx.on_error("argument not found");
2295 return arg;
2296 }
2297
2298 // The standard format specifier handler with checking.
2299 template <typename Char> class specs_handler : public specs_setter<Char> {
2300 private:
2301 basic_format_parse_context<Char>& parse_context_;
2302 buffer_context<Char>& context_;
2303
2304 // This is only needed for compatibility with gcc 4.4.
2305 using format_arg = basic_format_arg<buffer_context<Char>>;
2306
2307 FMT_CONSTEXPR auto get_arg(auto_id) -> format_arg {
2308 return detail::get_arg(context_, parse_context_.next_arg_id());
2309 }
2310
2311 FMT_CONSTEXPR auto get_arg(int arg_id) -> format_arg {
2312 parse_context_.check_arg_id(arg_id);
2313 return detail::get_arg(context_, arg_id);
2314 }
2315
2316 FMT_CONSTEXPR auto get_arg(basic_string_view<Char> arg_id) -> format_arg {
2317 parse_context_.check_arg_id(arg_id);
2318 return detail::get_arg(context_, arg_id);
2319 }
2320
2321 public:
2322 FMT_CONSTEXPR specs_handler(basic_format_specs<Char>& specs,
2323 basic_format_parse_context<Char>& parse_ctx,
2324 buffer_context<Char>& ctx)
2325 : specs_setter<Char>(specs), parse_context_(parse_ctx), context_(ctx) {}
2326
2327 template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
2328 this->specs_.width = get_dynamic_spec<width_checker>(
2329 get_arg(arg_id), context_.error_handler());
2330 }
2331
2332 template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
2333 this->specs_.precision = get_dynamic_spec<precision_checker>(
2334 get_arg(arg_id), context_.error_handler());
2335 }
2336
2337 void on_error(const char* message) { context_.on_error(message); }
2338 };
2339
2340 template <template <typename> class Handler, typename Context>
2341 FMT_CONSTEXPR void handle_dynamic_spec(int& value,
2342 arg_ref<typename Context::char_type> ref,
2343 Context& ctx) {
2344 switch (ref.kind) {
2345 case arg_id_kind::none:
2346 break;
2347 case arg_id_kind::index:
2348 value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.index),
2349 ctx.error_handler());
2350 break;
2351 case arg_id_kind::name:
2352 value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.name),
2353 ctx.error_handler());
2354 break;
2355 }
2356 }
2357
2358 #define FMT_STRING_IMPL(s, base, explicit) \
2359 [] { \
2360 /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \
2361 /* Use a macro-like name to avoid shadowing warnings. */ \
2362 struct FMT_GCC_VISIBILITY_HIDDEN FMT_COMPILE_STRING : base { \
2363 using char_type = fmt::remove_cvref_t<decltype(s[0])>; \
2364 FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit \
2365 operator fmt::basic_string_view<char_type>() const { \
2366 return fmt::detail_exported::compile_string_to_view<char_type>(s); \
2367 } \
2368 }; \
2369 return FMT_COMPILE_STRING(); \
2370 }()
2371
2372 /**
2373 \rst
2374 Constructs a compile-time format string from a string literal *s*.
2375
2376 **Example**::
2377
2378 // A compile-time error because 'd' is an invalid specifier for strings.
2379 std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
2380 \endrst
2381 */
2382 #define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::compile_string, )
2383
2384 #if FMT_USE_USER_DEFINED_LITERALS
2385 template <typename Char> struct udl_formatter {
2386 basic_string_view<Char> str;
2387
2388 template <typename... T>
2389 auto operator()(T&&... args) const -> std::basic_string<Char> {
2390 return vformat(str, fmt::make_args_checked<T...>(str, args...));
2391 }
2392 };
2393
2394 # if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
2395 template <typename T, typename Char, size_t N,
2396 fmt::detail_exported::fixed_string<Char, N> Str>
2397 struct statically_named_arg : view {
2398 static constexpr auto name = Str.data;
2399
2400 const T& value;
2401 statically_named_arg(const T& v) : value(v) {}
2402 };
2403
2404 template <typename T, typename Char, size_t N,
2405 fmt::detail_exported::fixed_string<Char, N> Str>
2406 struct is_named_arg<statically_named_arg<T, Char, N, Str>> : std::true_type {};
2407
2408 template <typename T, typename Char, size_t N,
2409 fmt::detail_exported::fixed_string<Char, N> Str>
2410 struct is_statically_named_arg<statically_named_arg<T, Char, N, Str>>
2411 : std::true_type {};
2412
2413 template <typename Char, size_t N,
2414 fmt::detail_exported::fixed_string<Char, N> Str>
2415 struct udl_arg {
2416 template <typename T> auto operator=(T&& value) const {
2417 return statically_named_arg<T, Char, N, Str>(std::forward<T>(value));
2418 }
2419 };
2420 # else
2421 template <typename Char> struct udl_arg {
2422 const Char* str;
2423
2424 template <typename T> auto operator=(T&& value) const -> named_arg<Char, T> {
2425 return {str, std::forward<T>(value)};
2426 }
2427 };
2428 # endif
2429 #endif // FMT_USE_USER_DEFINED_LITERALS
2430
2431 template <typename Locale, typename Char>
2432 auto vformat(const Locale& loc, basic_string_view<Char> format_str,
2433 basic_format_args<buffer_context<type_identity_t<Char>>> args)
2434 -> std::basic_string<Char> {
2435 basic_memory_buffer<Char> buffer;
2436 detail::vformat_to(buffer, format_str, args, detail::locale_ref(loc));
2437 return {buffer.data(), buffer.size()};
2438 }
2439
2440 using format_func = void (*)(detail::buffer<char>&, int, const char*);
2441
2442 FMT_API void format_error_code(buffer<char>& out, int error_code,
2443 string_view message) FMT_NOEXCEPT;
2444
2445 FMT_API void report_error(format_func func, int error_code,
2446 const char* message) FMT_NOEXCEPT;
2447 FMT_END_DETAIL_NAMESPACE
2448
2449 FMT_API auto vsystem_error(int error_code, string_view format_str,
2450 format_args args) -> std::system_error;
2451
2452 /**
2453 \rst
2454 Constructs :class:`std::system_error` with a message formatted with
2455 ``fmt::format(fmt, args...)``.
2456 *error_code* is a system error code as given by ``errno``.
2457
2458 **Example**::
2459
2460 // This throws std::system_error with the description
2461 // cannot open file 'madeup': No such file or directory
2462 // or similar (system message may vary).
2463 const char* filename = "madeup";
2464 std::FILE* file = std::fopen(filename, "r");
2465 if (!file)
2466 throw fmt::system_error(errno, "cannot open file '{}'", filename);
2467 \endrst
2468 */
2469 template <typename... T>
2470 auto system_error(int error_code, format_string<T...> fmt, T&&... args)
2471 -> std::system_error {
2472 return vsystem_error(error_code, fmt, fmt::make_format_args(args...));
2473 }
2474
2475 /**
2476 \rst
2477 Formats an error message for an error returned by an operating system or a
2478 language runtime, for example a file opening error, and writes it to *out*.
2479 The format is the same as the one used by ``std::system_error(ec, message)``
2480 where ``ec`` is ``std::error_code(error_code, std::generic_category()})``.
2481 It is implementation-defined but normally looks like:
2482
2483 .. parsed-literal::
2484 *<message>*: *<system-message>*
2485
2486 where *<message>* is the passed message and *<system-message>* is the system
2487 message corresponding to the error code.
2488 *error_code* is a system error code as given by ``errno``.
2489 \endrst
2490 */
2491 FMT_API void format_system_error(detail::buffer<char>& out, int error_code,
2492 const char* message) FMT_NOEXCEPT;
2493
2494 // Reports a system error without throwing an exception.
2495 // Can be used to report errors from destructors.
2496 FMT_API void report_system_error(int error_code,
2497 const char* message) FMT_NOEXCEPT;
2498
2499 /** Fast integer formatter. */
2500 class format_int {
2501 private:
2502 // Buffer should be large enough to hold all digits (digits10 + 1),
2503 // a sign and a null character.
2504 enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
2505 mutable char buffer_[buffer_size];
2506 char* str_;
2507
2508 template <typename UInt> auto format_unsigned(UInt value) -> char* {
2509 auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);
2510 return detail::format_decimal(buffer_, n, buffer_size - 1).begin;
2511 }
2512
2513 template <typename Int> auto format_signed(Int value) -> char* {
2514 auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);
2515 bool negative = value < 0;
2516 if (negative) abs_value = 0 - abs_value;
2517 auto begin = format_unsigned(abs_value);
2518 if (negative) *--begin = '-';
2519 return begin;
2520 }
2521
2522 public:
2523 explicit format_int(int value) : str_(format_signed(value)) {}
2524 explicit format_int(long value) : str_(format_signed(value)) {}
2525 explicit format_int(long long value) : str_(format_signed(value)) {}
2526 explicit format_int(unsigned value) : str_(format_unsigned(value)) {}
2527 explicit format_int(unsigned long value) : str_(format_unsigned(value)) {}
2528 explicit format_int(unsigned long long value)
2529 : str_(format_unsigned(value)) {}
2530
2531 /** Returns the number of characters written to the output buffer. */
2532 auto size() const -> size_t {
2533 return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);
2534 }
2535
2536 /**
2537 Returns a pointer to the output buffer content. No terminating null
2538 character is appended.
2539 */
2540 auto data() const -> const char* { return str_; }
2541
2542 /**
2543 Returns a pointer to the output buffer content with terminating null
2544 character appended.
2545 */
2546 auto c_str() const -> const char* {
2547 buffer_[buffer_size - 1] = '\0';
2548 return str_;
2549 }
2550
2551 /**
2552 \rst
2553 Returns the content of the output buffer as an ``std::string``.
2554 \endrst
2555 */
2556 auto str() const -> std::string { return std::string(str_, size()); }
2557 };
2558
2559 template <typename T, typename Char>
2560 template <typename FormatContext>
2561 FMT_CONSTEXPR FMT_INLINE auto
2562 formatter<T, Char,
2563 enable_if_t<detail::type_constant<T, Char>::value !=
2564 detail::type::custom_type>>::format(const T& val,
2565 FormatContext& ctx)
2566 const -> decltype(ctx.out()) {
2567 if (specs_.width_ref.kind != detail::arg_id_kind::none ||
2568 specs_.precision_ref.kind != detail::arg_id_kind::none) {
2569 auto specs = specs_;
2570 detail::handle_dynamic_spec<detail::width_checker>(specs.width,
2571 specs.width_ref, ctx);
2572 detail::handle_dynamic_spec<detail::precision_checker>(
2573 specs.precision, specs.precision_ref, ctx);
2574 return detail::write<Char>(ctx.out(), val, specs, ctx.locale());
2575 }
2576 return detail::write<Char>(ctx.out(), val, specs_, ctx.locale());
2577 }
2578
2579 #define FMT_FORMAT_AS(Type, Base) \
2580 template <typename Char> \
2581 struct formatter<Type, Char> : formatter<Base, Char> { \
2582 template <typename FormatContext> \
2583 auto format(Type const& val, FormatContext& ctx) const \
2584 -> decltype(ctx.out()) { \
2585 return formatter<Base, Char>::format(static_cast<Base>(val), ctx); \
2586 } \
2587 }
2588
2589 FMT_FORMAT_AS(signed char, int);
2590 FMT_FORMAT_AS(unsigned char, unsigned);
2591 FMT_FORMAT_AS(short, int);
2592 FMT_FORMAT_AS(unsigned short, unsigned);
2593 FMT_FORMAT_AS(long, long long);
2594 FMT_FORMAT_AS(unsigned long, unsigned long long);
2595 FMT_FORMAT_AS(Char*, const Char*);
2596 FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
2597 FMT_FORMAT_AS(std::nullptr_t, const void*);
2598 FMT_FORMAT_AS(detail::byte, unsigned char);
2599 FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
2600
2601 template <typename Char>
2602 struct formatter<void*, Char> : formatter<const void*, Char> {
2603 template <typename FormatContext>
2604 auto format(void* val, FormatContext& ctx) const -> decltype(ctx.out()) {
2605 return formatter<const void*, Char>::format(val, ctx);
2606 }
2607 };
2608
2609 template <typename Char, size_t N>
2610 struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {
2611 template <typename FormatContext>
2612 FMT_CONSTEXPR auto format(const Char* val, FormatContext& ctx) const
2613 -> decltype(ctx.out()) {
2614 return formatter<basic_string_view<Char>, Char>::format(val, ctx);
2615 }
2616 };
2617
2618 // A formatter for types known only at run time such as variant alternatives.
2619 //
2620 // Usage:
2621 // using variant = std::variant<int, std::string>;
2622 // template <>
2623 // struct formatter<variant>: dynamic_formatter<> {
2624 // auto format(const variant& v, format_context& ctx) {
2625 // return visit([&](const auto& val) {
2626 // return dynamic_formatter<>::format(val, ctx);
2627 // }, v);
2628 // }
2629 // };
2630 template <typename Char = char> class dynamic_formatter {
2631 private:
2632 detail::dynamic_format_specs<Char> specs_;
2633 const Char* format_str_;
2634
2635 struct null_handler : detail::error_handler {
2636 void on_align(align_t) {}
2637 void on_sign(sign_t) {}
2638 void on_hash() {}
2639 };
2640
2641 template <typename Context> void handle_specs(Context& ctx) {
2642 detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
2643 specs_.width_ref, ctx);
2644 detail::handle_dynamic_spec<detail::precision_checker>(
2645 specs_.precision, specs_.precision_ref, ctx);
2646 }
2647
2648 public:
2649 template <typename ParseContext>
2650 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
2651 format_str_ = ctx.begin();
2652 // Checks are deferred to formatting time when the argument type is known.
2653 detail::dynamic_specs_handler<ParseContext> handler(specs_, ctx);
2654 return detail::parse_format_specs(ctx.begin(), ctx.end(), handler);
2655 }
2656
2657 template <typename T, typename FormatContext>
2658 auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
2659 handle_specs(ctx);
2660 detail::specs_checker<null_handler> checker(
2661 null_handler(), detail::mapped_type_constant<T, FormatContext>::value);
2662 checker.on_align(specs_.align);
2663 if (specs_.sign != sign::none) checker.on_sign(specs_.sign);
2664 if (specs_.alt) checker.on_hash();
2665 if (specs_.precision >= 0) checker.end_precision();
2666 return detail::write<Char>(ctx.out(), val, specs_, ctx.locale());
2667 }
2668 };
2669
2670 /**
2671 \rst
2672 Converts ``p`` to ``const void*`` for pointer formatting.
2673
2674 **Example**::
2675
2676 auto s = fmt::format("{}", fmt::ptr(p));
2677 \endrst
2678 */
2679 template <typename T> auto ptr(T p) -> const void* {
2680 static_assert(std::is_pointer<T>::value, "");
2681 return detail::bit_cast<const void*>(p);
2682 }
2683 template <typename T> auto ptr(const std::unique_ptr<T>& p) -> const void* {
2684 return p.get();
2685 }
2686 template <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {
2687 return p.get();
2688 }
2689
2690 class bytes {
2691 private:
2692 string_view data_;
2693 friend struct formatter<bytes>;
2694
2695 public:
2696 explicit bytes(string_view data) : data_(data) {}
2697 };
2698
2699 template <> struct formatter<bytes> {
2700 private:
2701 detail::dynamic_format_specs<char> specs_;
2702
2703 public:
2704 template <typename ParseContext>
2705 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
2706 using handler_type = detail::dynamic_specs_handler<ParseContext>;
2707 detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
2708 detail::type::string_type);
2709 auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
2710 detail::check_string_type_spec(specs_.type, ctx.error_handler());
2711 return it;
2712 }
2713
2714 template <typename FormatContext>
2715 auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) {
2716 detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
2717 specs_.width_ref, ctx);
2718 detail::handle_dynamic_spec<detail::precision_checker>(
2719 specs_.precision, specs_.precision_ref, ctx);
2720 return detail::write_bytes(ctx.out(), b.data_, specs_);
2721 }
2722 };
2723
2724 // group_digits_view is not derived from view because it copies the argument.
2725 template <typename T> struct group_digits_view { T value; };
2726
2727 /**
2728 \rst
2729 Returns a view that formats an integer value using ',' as a locale-independent
2730 thousands separator.
2731
2732 **Example**::
2733
2734 fmt::print("{}", fmt::group_digits(12345));
2735 // Output: "12,345"
2736 \endrst
2737 */
2738 template <typename T> auto group_digits(T value) -> group_digits_view<T> {
2739 return {value};
2740 }
2741
2742 template <typename T> struct formatter<group_digits_view<T>> : formatter<T> {
2743 private:
2744 detail::dynamic_format_specs<char> specs_;
2745
2746 public:
2747 template <typename ParseContext>
2748 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
2749 using handler_type = detail::dynamic_specs_handler<ParseContext>;
2750 detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
2751 detail::type::int_type);
2752 auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
2753 detail::check_string_type_spec(specs_.type, ctx.error_handler());
2754 return it;
2755 }
2756
2757 template <typename FormatContext>
2758 auto format(group_digits_view<T> t, FormatContext& ctx)
2759 -> decltype(ctx.out()) {
2760 detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
2761 specs_.width_ref, ctx);
2762 detail::handle_dynamic_spec<detail::precision_checker>(
2763 specs_.precision, specs_.precision_ref, ctx);
2764 return detail::write_int_localized(
2765 ctx.out(), static_cast<detail::uint64_or_128_t<T>>(t.value), 0, specs_,
2766 detail::digit_grouping<char>({"\3", ','}));
2767 }
2768 };
2769
2770 template <typename It, typename Sentinel, typename Char = char>
2771 struct join_view : detail::view {
2772 It begin;
2773 Sentinel end;
2774 basic_string_view<Char> sep;
2775
2776 join_view(It b, Sentinel e, basic_string_view<Char> s)
2777 : begin(b), end(e), sep(s) {}
2778 };
2779
2780 template <typename It, typename Sentinel, typename Char>
2781 using arg_join FMT_DEPRECATED_ALIAS = join_view<It, Sentinel, Char>;
2782
2783 template <typename It, typename Sentinel, typename Char>
2784 struct formatter<join_view<It, Sentinel, Char>, Char> {
2785 private:
2786 using value_type =
2787 #ifdef __cpp_lib_ranges
2788 std::iter_value_t<It>;
2789 #else
2790 typename std::iterator_traits<It>::value_type;
2791 #endif
2792 using context = buffer_context<Char>;
2793 using mapper = detail::arg_mapper<context>;
2794
2795 template <typename T, FMT_ENABLE_IF(has_formatter<T, context>::value)>
2796 static auto map(const T& value) -> const T& {
2797 return value;
2798 }
2799 template <typename T, FMT_ENABLE_IF(!has_formatter<T, context>::value)>
2800 static auto map(const T& value) -> decltype(mapper().map(value)) {
2801 return mapper().map(value);
2802 }
2803
2804 using formatter_type =
2805 conditional_t<is_formattable<value_type, Char>::value,
2806 formatter<remove_cvref_t<decltype(map(
2807 std::declval<const value_type&>()))>,
2808 Char>,
2809 detail::fallback_formatter<value_type, Char>>;
2810
2811 formatter_type value_formatter_;
2812
2813 public:
2814 template <typename ParseContext>
2815 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
2816 return value_formatter_.parse(ctx);
2817 }
2818
2819 template <typename FormatContext>
2820 auto format(const join_view<It, Sentinel, Char>& value, FormatContext& ctx)
2821 -> decltype(ctx.out()) {
2822 auto it = value.begin;
2823 auto out = ctx.out();
2824 if (it != value.end) {
2825 out = value_formatter_.format(map(*it), ctx);
2826 ++it;
2827 while (it != value.end) {
2828 out = detail::copy_str<Char>(value.sep.begin(), value.sep.end(), out);
2829 ctx.advance_to(out);
2830 out = value_formatter_.format(map(*it), ctx);
2831 ++it;
2832 }
2833 }
2834 return out;
2835 }
2836 };
2837
2838 /**
2839 Returns a view that formats the iterator range `[begin, end)` with elements
2840 separated by `sep`.
2841 */
2842 template <typename It, typename Sentinel>
2843 auto join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel> {
2844 return {begin, end, sep};
2845 }
2846
2847 /**
2848 \rst
2849 Returns a view that formats `range` with elements separated by `sep`.
2850
2851 **Example**::
2852
2853 std::vector<int> v = {1, 2, 3};
2854 fmt::print("{}", fmt::join(v, ", "));
2855 // Output: "1, 2, 3"
2856
2857 ``fmt::join`` applies passed format specifiers to the range elements::
2858
2859 fmt::print("{:02}", fmt::join(v, ", "));
2860 // Output: "01, 02, 03"
2861 \endrst
2862 */
2863 template <typename Range>
2864 auto join(Range&& range, string_view sep)
2865 -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>> {
2866 return join(std::begin(range), std::end(range), sep);
2867 }
2868
2869 /**
2870 \rst
2871 Converts *value* to ``std::string`` using the default format for type *T*.
2872
2873 **Example**::
2874
2875 #include <fmt/format.h>
2876
2877 std::string answer = fmt::to_string(42);
2878 \endrst
2879 */
2880 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
2881 inline auto to_string(const T& value) -> std::string {
2882 auto result = std::string();
2883 detail::write<char>(std::back_inserter(result), value);
2884 return result;
2885 }
2886
2887 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
2888 FMT_NODISCARD inline auto to_string(T value) -> std::string {
2889 // The buffer should be large enough to store the number including the sign
2890 // or "false" for bool.
2891 constexpr int max_size = detail::digits10<T>() + 2;
2892 char buffer[max_size > 5 ? static_cast<unsigned>(max_size) : 5];
2893 char* begin = buffer;
2894 return std::string(begin, detail::write<char>(begin, value));
2895 }
2896
2897 template <typename Char, size_t SIZE>
2898 FMT_NODISCARD auto to_string(const basic_memory_buffer<Char, SIZE>& buf)
2899 -> std::basic_string<Char> {
2900 auto size = buf.size();
2901 detail::assume(size < std::basic_string<Char>().max_size());
2902 return std::basic_string<Char>(buf.data(), size);
2903 }
2904
2905 FMT_BEGIN_DETAIL_NAMESPACE
2906
2907 template <typename Char>
2908 void vformat_to(
2909 buffer<Char>& buf, basic_string_view<Char> fmt,
2910 basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
2911 locale_ref loc) {
2912 // workaround for msvc bug regarding name-lookup in module
2913 // link names into function scope
2914 using detail::arg_formatter;
2915 using detail::buffer_appender;
2916 using detail::custom_formatter;
2917 using detail::default_arg_formatter;
2918 using detail::get_arg;
2919 using detail::locale_ref;
2920 using detail::parse_format_specs;
2921 using detail::specs_checker;
2922 using detail::specs_handler;
2923 using detail::to_unsigned;
2924 using detail::type;
2925 using detail::write;
2926 auto out = buffer_appender<Char>(buf);
2927 if (fmt.size() == 2 && equal2(fmt.data(), "{}")) {
2928 auto arg = args.get(0);
2929 if (!arg) error_handler().on_error("argument not found");
2930 visit_format_arg(default_arg_formatter<Char>{out, args, loc}, arg);
2931 return;
2932 }
2933
2934 struct format_handler : error_handler {
2935 basic_format_parse_context<Char> parse_context;
2936 buffer_context<Char> context;
2937
2938 format_handler(buffer_appender<Char> out, basic_string_view<Char> str,
2939 basic_format_args<buffer_context<Char>> args, locale_ref loc)
2940 : parse_context(str), context(out, args, loc) {}
2941
2942 void on_text(const Char* begin, const Char* end) {
2943 auto text = basic_string_view<Char>(begin, to_unsigned(end - begin));
2944 context.advance_to(write<Char>(context.out(), text));
2945 }
2946
2947 FMT_CONSTEXPR auto on_arg_id() -> int {
2948 return parse_context.next_arg_id();
2949 }
2950 FMT_CONSTEXPR auto on_arg_id(int id) -> int {
2951 return parse_context.check_arg_id(id), id;
2952 }
2953 FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
2954 int arg_id = context.arg_id(id);
2955 if (arg_id < 0) on_error("argument not found");
2956 return arg_id;
2957 }
2958
2959 FMT_INLINE void on_replacement_field(int id, const Char*) {
2960 auto arg = get_arg(context, id);
2961 context.advance_to(visit_format_arg(
2962 default_arg_formatter<Char>{context.out(), context.args(),
2963 context.locale()},
2964 arg));
2965 }
2966
2967 auto on_format_specs(int id, const Char* begin, const Char* end)
2968 -> const Char* {
2969 auto arg = get_arg(context, id);
2970 if (arg.type() == type::custom_type) {
2971 parse_context.advance_to(parse_context.begin() +
2972 (begin - &*parse_context.begin()));
2973 visit_format_arg(custom_formatter<Char>{parse_context, context}, arg);
2974 return parse_context.begin();
2975 }
2976 auto specs = basic_format_specs<Char>();
2977 specs_checker<specs_handler<Char>> handler(
2978 specs_handler<Char>(specs, parse_context, context), arg.type());
2979 begin = parse_format_specs(begin, end, handler);
2980 if (begin == end || *begin != '}')
2981 on_error("missing '}' in format string");
2982 auto f = arg_formatter<Char>{context.out(), specs, context.locale()};
2983 context.advance_to(visit_format_arg(f, arg));
2984 return begin;
2985 }
2986 };
2987 detail::parse_format_string<false>(fmt, format_handler(out, fmt, args, loc));
2988 }
2989
2990 #ifndef FMT_HEADER_ONLY
2991 extern template FMT_API auto thousands_sep_impl<char>(locale_ref)
2992 -> thousands_sep_result<char>;
2993 extern template FMT_API auto thousands_sep_impl<wchar_t>(locale_ref)
2994 -> thousands_sep_result<wchar_t>;
2995 extern template FMT_API auto decimal_point_impl(locale_ref) -> char;
2996 extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
2997 extern template auto format_float<double>(double value, int precision,
2998 float_specs specs, buffer<char>& buf)
2999 -> int;
3000 extern template auto format_float<long double>(long double value, int precision,
3001 float_specs specs,
3002 buffer<char>& buf) -> int;
3003 void snprintf_float(float, int, float_specs, buffer<char>&) = delete;
3004 extern template auto snprintf_float<double>(double value, int precision,
3005 float_specs specs,
3006 buffer<char>& buf) -> int;
3007 extern template auto snprintf_float<long double>(long double value,
3008 int precision,
3009 float_specs specs,
3010 buffer<char>& buf) -> int;
3011 #endif // FMT_HEADER_ONLY
3012
3013 FMT_END_DETAIL_NAMESPACE
3014
3015 #if FMT_USE_USER_DEFINED_LITERALS
3016 inline namespace literals {
3017 /**
3018 \rst
3019 User-defined literal equivalent of :func:`fmt::arg`.
3020
3021 **Example**::
3022
3023 using namespace fmt::literals;
3024 fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
3025 \endrst
3026 */
3027 # if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
3028 template <detail_exported::fixed_string Str>
3029 constexpr auto operator""_a()
3030 -> detail::udl_arg<remove_cvref_t<decltype(Str.data[0])>,
3031 sizeof(Str.data) / sizeof(decltype(Str.data[0])), Str> {
3032 return {};
3033 }
3034 # else
3035 constexpr auto operator"" _a(const char* s, size_t) -> detail::udl_arg<char> {
3036 return {s};
3037 }
3038 # endif
3039
3040 // DEPRECATED!
3041 // User-defined literal equivalent of fmt::format.
3042 FMT_DEPRECATED constexpr auto operator"" _format(const char* s, size_t n)
3043 -> detail::udl_formatter<char> {
3044 return {{s, n}};
3045 }
3046 } // namespace literals
3047 #endif // FMT_USE_USER_DEFINED_LITERALS
3048
3049 template <typename Locale, FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
3050 inline auto vformat(const Locale& loc, string_view fmt, format_args args)
3051 -> std::string {
3052 return detail::vformat(loc, fmt, args);
3053 }
3054
3055 template <typename Locale, typename... T,
3056 FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
3057 inline auto format(const Locale& loc, format_string<T...> fmt, T&&... args)
3058 -> std::string {
3059 return vformat(loc, string_view(fmt), fmt::make_format_args(args...));
3060 }
3061
3062 template <typename... T, size_t SIZE, typename Allocator>
3063 FMT_DEPRECATED auto format_to(basic_memory_buffer<char, SIZE, Allocator>& buf,
3064 format_string<T...> fmt, T&&... args)
3065 -> appender {
3066 detail::vformat_to(buf, string_view(fmt), fmt::make_format_args(args...));
3067 return appender(buf);
3068 }
3069
3070 template <typename OutputIt, typename Locale,
3071 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
3072 detail::is_locale<Locale>::value)>
3073 auto vformat_to(OutputIt out, const Locale& loc, string_view fmt,
3074 format_args args) -> OutputIt {
3075 using detail::get_buffer;
3076 auto&& buf = get_buffer<char>(out);
3077 detail::vformat_to(buf, fmt, args, detail::locale_ref(loc));
3078 return detail::get_iterator(buf);
3079 }
3080
3081 template <typename OutputIt, typename Locale, typename... T,
3082 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
3083 detail::is_locale<Locale>::value)>
3084 FMT_INLINE auto format_to(OutputIt out, const Locale& loc,
3085 format_string<T...> fmt, T&&... args) -> OutputIt {
3086 return vformat_to(out, loc, fmt, fmt::make_format_args(args...));
3087 }
3088
3089 FMT_MODULE_EXPORT_END
3090 FMT_END_NAMESPACE
3091
3092 #ifdef FMT_DEPRECATED_INCLUDE_XCHAR
3093 # include "xchar.h"
3094 #endif
3095
3096 #ifdef FMT_HEADER_ONLY
3097 # define FMT_FUNC inline
3098 # include "format-inl.h"
3099 #else
3100 # define FMT_FUNC
3101 #endif
3102
3103 #endif // FMT_FORMAT_H_
+0
-2
source/misc/embedded_libs/fmt-8.1.1/include/fmt/locale.h less more
0 #include "xchar.h"
1 #warning fmt/locale.h is deprecated, include fmt/format.h or fmt/xchar.h instead
+0
-527
source/misc/embedded_libs/fmt-8.1.1/include/fmt/os.h less more
0 // Formatting library for C++ - optional OS-specific functionality
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_OS_H_
8 #define FMT_OS_H_
9
10 #include <cerrno>
11 #include <clocale> // locale_t
12 #include <cstddef>
13 #include <cstdio>
14 #include <cstdlib> // strtod_l
15 #include <system_error> // std::system_error
16
17 #if defined __APPLE__ || defined(__FreeBSD__)
18 # include <xlocale.h> // for LC_NUMERIC_MASK on OS X
19 #endif
20
21 #include "format.h"
22
23 #ifndef FMT_USE_FCNTL
24 // UWP doesn't provide _pipe.
25 # if FMT_HAS_INCLUDE("winapifamily.h")
26 # include <winapifamily.h>
27 # endif
28 # if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
29 defined(__linux__)) && \
30 (!defined(WINAPI_FAMILY) || \
31 (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
32 # include <fcntl.h> // for O_RDONLY
33 # define FMT_USE_FCNTL 1
34 # else
35 # define FMT_USE_FCNTL 0
36 # endif
37 #endif
38
39 #ifndef FMT_POSIX
40 # if defined(_WIN32) && !defined(__MINGW32__)
41 // Fix warnings about deprecated symbols.
42 # define FMT_POSIX(call) _##call
43 # else
44 # define FMT_POSIX(call) call
45 # endif
46 #endif
47
48 // Calls to system functions are wrapped in FMT_SYSTEM for testability.
49 #ifdef FMT_SYSTEM
50 # define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
51 #else
52 # define FMT_SYSTEM(call) ::call
53 # ifdef _WIN32
54 // Fix warnings about deprecated symbols.
55 # define FMT_POSIX_CALL(call) ::_##call
56 # else
57 # define FMT_POSIX_CALL(call) ::call
58 # endif
59 #endif
60
61 // Retries the expression while it evaluates to error_result and errno
62 // equals to EINTR.
63 #ifndef _WIN32
64 # define FMT_RETRY_VAL(result, expression, error_result) \
65 do { \
66 (result) = (expression); \
67 } while ((result) == (error_result) && errno == EINTR)
68 #else
69 # define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
70 #endif
71
72 #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
73
74 FMT_BEGIN_NAMESPACE
75 FMT_MODULE_EXPORT_BEGIN
76
77 /**
78 \rst
79 A reference to a null-terminated string. It can be constructed from a C
80 string or ``std::string``.
81
82 You can use one of the following type aliases for common character types:
83
84 +---------------+-----------------------------+
85 | Type | Definition |
86 +===============+=============================+
87 | cstring_view | basic_cstring_view<char> |
88 +---------------+-----------------------------+
89 | wcstring_view | basic_cstring_view<wchar_t> |
90 +---------------+-----------------------------+
91
92 This class is most useful as a parameter type to allow passing
93 different types of strings to a function, for example::
94
95 template <typename... Args>
96 std::string format(cstring_view format_str, const Args & ... args);
97
98 format("{}", 42);
99 format(std::string("{}"), 42);
100 \endrst
101 */
102 template <typename Char> class basic_cstring_view {
103 private:
104 const Char* data_;
105
106 public:
107 /** Constructs a string reference object from a C string. */
108 basic_cstring_view(const Char* s) : data_(s) {}
109
110 /**
111 \rst
112 Constructs a string reference from an ``std::string`` object.
113 \endrst
114 */
115 basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}
116
117 /** Returns the pointer to a C string. */
118 const Char* c_str() const { return data_; }
119 };
120
121 using cstring_view = basic_cstring_view<char>;
122 using wcstring_view = basic_cstring_view<wchar_t>;
123
124 template <typename Char> struct formatter<std::error_code, Char> {
125 template <typename ParseContext>
126 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
127 return ctx.begin();
128 }
129
130 template <typename FormatContext>
131 FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const
132 -> decltype(ctx.out()) {
133 auto out = ctx.out();
134 out = detail::write_bytes(out, ec.category().name(),
135 basic_format_specs<Char>());
136 out = detail::write<Char>(out, Char(':'));
137 out = detail::write<Char>(out, ec.value());
138 return out;
139 }
140 };
141
142 #ifdef _WIN32
143 FMT_API const std::error_category& system_category() FMT_NOEXCEPT;
144
145 FMT_BEGIN_DETAIL_NAMESPACE
146 // A converter from UTF-16 to UTF-8.
147 // It is only provided for Windows since other systems support UTF-8 natively.
148 class utf16_to_utf8 {
149 private:
150 memory_buffer buffer_;
151
152 public:
153 utf16_to_utf8() {}
154 FMT_API explicit utf16_to_utf8(basic_string_view<wchar_t> s);
155 operator string_view() const { return string_view(&buffer_[0], size()); }
156 size_t size() const { return buffer_.size() - 1; }
157 const char* c_str() const { return &buffer_[0]; }
158 std::string str() const { return std::string(&buffer_[0], size()); }
159
160 // Performs conversion returning a system error code instead of
161 // throwing exception on conversion error. This method may still throw
162 // in case of memory allocation error.
163 FMT_API int convert(basic_string_view<wchar_t> s);
164 };
165
166 FMT_API void format_windows_error(buffer<char>& out, int error_code,
167 const char* message) FMT_NOEXCEPT;
168 FMT_END_DETAIL_NAMESPACE
169
170 FMT_API std::system_error vwindows_error(int error_code, string_view format_str,
171 format_args args);
172
173 /**
174 \rst
175 Constructs a :class:`std::system_error` object with the description
176 of the form
177
178 .. parsed-literal::
179 *<message>*: *<system-message>*
180
181 where *<message>* is the formatted message and *<system-message>* is the
182 system message corresponding to the error code.
183 *error_code* is a Windows error code as given by ``GetLastError``.
184 If *error_code* is not a valid error code such as -1, the system message
185 will look like "error -1".
186
187 **Example**::
188
189 // This throws a system_error with the description
190 // cannot open file 'madeup': The system cannot find the file specified.
191 // or similar (system message may vary).
192 const char *filename = "madeup";
193 LPOFSTRUCT of = LPOFSTRUCT();
194 HFILE file = OpenFile(filename, &of, OF_READ);
195 if (file == HFILE_ERROR) {
196 throw fmt::windows_error(GetLastError(),
197 "cannot open file '{}'", filename);
198 }
199 \endrst
200 */
201 template <typename... Args>
202 std::system_error windows_error(int error_code, string_view message,
203 const Args&... args) {
204 return vwindows_error(error_code, message, fmt::make_format_args(args...));
205 }
206
207 // Reports a Windows error without throwing an exception.
208 // Can be used to report errors from destructors.
209 FMT_API void report_windows_error(int error_code,
210 const char* message) FMT_NOEXCEPT;
211 #else
212 inline const std::error_category& system_category() FMT_NOEXCEPT {
213 return std::system_category();
214 }
215 #endif // _WIN32
216
217 // std::system is not available on some platforms such as iOS (#2248).
218 #ifdef __OSX__
219 template <typename S, typename... Args, typename Char = char_t<S>>
220 void say(const S& format_str, Args&&... args) {
221 std::system(format("say \"{}\"", format(format_str, args...)).c_str());
222 }
223 #endif
224
225 // A buffered file.
226 class buffered_file {
227 private:
228 FILE* file_;
229
230 friend class file;
231
232 explicit buffered_file(FILE* f) : file_(f) {}
233
234 public:
235 buffered_file(const buffered_file&) = delete;
236 void operator=(const buffered_file&) = delete;
237
238 // Constructs a buffered_file object which doesn't represent any file.
239 buffered_file() FMT_NOEXCEPT : file_(nullptr) {}
240
241 // Destroys the object closing the file it represents if any.
242 FMT_API ~buffered_file() FMT_NOEXCEPT;
243
244 public:
245 buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) {
246 other.file_ = nullptr;
247 }
248
249 buffered_file& operator=(buffered_file&& other) {
250 close();
251 file_ = other.file_;
252 other.file_ = nullptr;
253 return *this;
254 }
255
256 // Opens a file.
257 FMT_API buffered_file(cstring_view filename, cstring_view mode);
258
259 // Closes the file.
260 FMT_API void close();
261
262 // Returns the pointer to a FILE object representing this file.
263 FILE* get() const FMT_NOEXCEPT { return file_; }
264
265 // We place parentheses around fileno to workaround a bug in some versions
266 // of MinGW that define fileno as a macro.
267 FMT_API int(fileno)() const;
268
269 void vprint(string_view format_str, format_args args) {
270 fmt::vprint(file_, format_str, args);
271 }
272
273 template <typename... Args>
274 inline void print(string_view format_str, const Args&... args) {
275 vprint(format_str, fmt::make_format_args(args...));
276 }
277 };
278
279 #if FMT_USE_FCNTL
280 // A file. Closed file is represented by a file object with descriptor -1.
281 // Methods that are not declared with FMT_NOEXCEPT may throw
282 // fmt::system_error in case of failure. Note that some errors such as
283 // closing the file multiple times will cause a crash on Windows rather
284 // than an exception. You can get standard behavior by overriding the
285 // invalid parameter handler with _set_invalid_parameter_handler.
286 class file {
287 private:
288 int fd_; // File descriptor.
289
290 // Constructs a file object with a given descriptor.
291 explicit file(int fd) : fd_(fd) {}
292
293 public:
294 // Possible values for the oflag argument to the constructor.
295 enum {
296 RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
297 WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
298 RDWR = FMT_POSIX(O_RDWR), // Open for reading and writing.
299 CREATE = FMT_POSIX(O_CREAT), // Create if the file doesn't exist.
300 APPEND = FMT_POSIX(O_APPEND), // Open in append mode.
301 TRUNC = FMT_POSIX(O_TRUNC) // Truncate the content of the file.
302 };
303
304 // Constructs a file object which doesn't represent any file.
305 file() FMT_NOEXCEPT : fd_(-1) {}
306
307 // Opens a file and constructs a file object representing this file.
308 FMT_API file(cstring_view path, int oflag);
309
310 public:
311 file(const file&) = delete;
312 void operator=(const file&) = delete;
313
314 file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
315
316 // Move assignment is not noexcept because close may throw.
317 file& operator=(file&& other) {
318 close();
319 fd_ = other.fd_;
320 other.fd_ = -1;
321 return *this;
322 }
323
324 // Destroys the object closing the file it represents if any.
325 FMT_API ~file() FMT_NOEXCEPT;
326
327 // Returns the file descriptor.
328 int descriptor() const FMT_NOEXCEPT { return fd_; }
329
330 // Closes the file.
331 FMT_API void close();
332
333 // Returns the file size. The size has signed type for consistency with
334 // stat::st_size.
335 FMT_API long long size() const;
336
337 // Attempts to read count bytes from the file into the specified buffer.
338 FMT_API size_t read(void* buffer, size_t count);
339
340 // Attempts to write count bytes from the specified buffer to the file.
341 FMT_API size_t write(const void* buffer, size_t count);
342
343 // Duplicates a file descriptor with the dup function and returns
344 // the duplicate as a file object.
345 FMT_API static file dup(int fd);
346
347 // Makes fd be the copy of this file descriptor, closing fd first if
348 // necessary.
349 FMT_API void dup2(int fd);
350
351 // Makes fd be the copy of this file descriptor, closing fd first if
352 // necessary.
353 FMT_API void dup2(int fd, std::error_code& ec) FMT_NOEXCEPT;
354
355 // Creates a pipe setting up read_end and write_end file objects for reading
356 // and writing respectively.
357 FMT_API static void pipe(file& read_end, file& write_end);
358
359 // Creates a buffered_file object associated with this file and detaches
360 // this file object from the file.
361 FMT_API buffered_file fdopen(const char* mode);
362 };
363
364 // Returns the memory page size.
365 long getpagesize();
366
367 FMT_BEGIN_DETAIL_NAMESPACE
368
369 struct buffer_size {
370 buffer_size() = default;
371 size_t value = 0;
372 buffer_size operator=(size_t val) const {
373 auto bs = buffer_size();
374 bs.value = val;
375 return bs;
376 }
377 };
378
379 struct ostream_params {
380 int oflag = file::WRONLY | file::CREATE | file::TRUNC;
381 size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768;
382
383 ostream_params() {}
384
385 template <typename... T>
386 ostream_params(T... params, int new_oflag) : ostream_params(params...) {
387 oflag = new_oflag;
388 }
389
390 template <typename... T>
391 ostream_params(T... params, detail::buffer_size bs)
392 : ostream_params(params...) {
393 this->buffer_size = bs.value;
394 }
395
396 // Intel has a bug that results in failure to deduce a constructor
397 // for empty parameter packs.
398 # if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000
399 ostream_params(int new_oflag) : oflag(new_oflag) {}
400 ostream_params(detail::buffer_size bs) : buffer_size(bs.value) {}
401 # endif
402 };
403
404 FMT_END_DETAIL_NAMESPACE
405
406 // Added {} below to work around default constructor error known to
407 // occur in Xcode versions 7.2.1 and 8.2.1.
408 constexpr detail::buffer_size buffer_size{};
409
410 /** A fast output stream which is not thread-safe. */
411 class FMT_API ostream final : private detail::buffer<char> {
412 private:
413 file file_;
414
415 void grow(size_t) override;
416
417 ostream(cstring_view path, const detail::ostream_params& params)
418 : file_(path, params.oflag) {
419 set(new char[params.buffer_size], params.buffer_size);
420 }
421
422 public:
423 ostream(ostream&& other)
424 : detail::buffer<char>(other.data(), other.size(), other.capacity()),
425 file_(std::move(other.file_)) {
426 other.clear();
427 other.set(nullptr, 0);
428 }
429 ~ostream() {
430 flush();
431 delete[] data();
432 }
433
434 void flush() {
435 if (size() == 0) return;
436 file_.write(data(), size());
437 clear();
438 }
439
440 template <typename... T>
441 friend ostream output_file(cstring_view path, T... params);
442
443 void close() {
444 flush();
445 file_.close();
446 }
447
448 /**
449 Formats ``args`` according to specifications in ``fmt`` and writes the
450 output to the file.
451 */
452 template <typename... T> void print(format_string<T...> fmt, T&&... args) {
453 vformat_to(detail::buffer_appender<char>(*this), fmt,
454 fmt::make_format_args(args...));
455 }
456 };
457
458 /**
459 \rst
460 Opens a file for writing. Supported parameters passed in *params*:
461
462 * ``<integer>``: Flags passed to `open
463 <https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html>`_
464 (``file::WRONLY | file::CREATE`` by default)
465 * ``buffer_size=<integer>``: Output buffer size
466
467 **Example**::
468
469 auto out = fmt::output_file("guide.txt");
470 out.print("Don't {}", "Panic");
471 \endrst
472 */
473 template <typename... T>
474 inline ostream output_file(cstring_view path, T... params) {
475 return {path, detail::ostream_params(params...)};
476 }
477 #endif // FMT_USE_FCNTL
478
479 #ifdef FMT_LOCALE
480 // A "C" numeric locale.
481 class locale {
482 private:
483 # ifdef _WIN32
484 using locale_t = _locale_t;
485
486 static void freelocale(locale_t loc) { _free_locale(loc); }
487
488 static double strtod_l(const char* nptr, char** endptr, _locale_t loc) {
489 return _strtod_l(nptr, endptr, loc);
490 }
491 # endif
492
493 locale_t locale_;
494
495 public:
496 using type = locale_t;
497 locale(const locale&) = delete;
498 void operator=(const locale&) = delete;
499
500 locale() {
501 # ifndef _WIN32
502 locale_ = FMT_SYSTEM(newlocale(LC_NUMERIC_MASK, "C", nullptr));
503 # else
504 locale_ = _create_locale(LC_NUMERIC, "C");
505 # endif
506 if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
507 }
508 ~locale() { freelocale(locale_); }
509
510 type get() const { return locale_; }
511
512 // Converts string to floating-point number and advances str past the end
513 // of the parsed input.
514 FMT_DEPRECATED double strtod(const char*& str) const {
515 char* end = nullptr;
516 double result = strtod_l(str, &end, locale_);
517 str = end;
518 return result;
519 }
520 };
521 using Locale FMT_DEPRECATED_ALIAS = locale;
522 #endif // FMT_LOCALE
523 FMT_MODULE_EXPORT_END
524 FMT_END_NAMESPACE
525
526 #endif // FMT_OS_H_
+0
-135
source/misc/embedded_libs/fmt-8.1.1/include/fmt/ostream.h less more
0 // Formatting library for C++ - std::ostream support
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_OSTREAM_H_
8 #define FMT_OSTREAM_H_
9
10 #include <ostream>
11
12 #include "format.h"
13
14 FMT_BEGIN_NAMESPACE
15
16 template <typename OutputIt, typename Char> class basic_printf_context;
17
18 namespace detail {
19
20 // Checks if T has a user-defined operator<<.
21 template <typename T, typename Char, typename Enable = void>
22 class is_streamable {
23 private:
24 template <typename U>
25 static auto test(int)
26 -> bool_constant<sizeof(std::declval<std::basic_ostream<Char>&>()
27 << std::declval<U>()) != 0>;
28
29 template <typename> static auto test(...) -> std::false_type;
30
31 using result = decltype(test<T>(0));
32
33 public:
34 is_streamable() = default;
35
36 static const bool value = result::value;
37 };
38
39 // Formatting of built-in types and arrays is intentionally disabled because
40 // it's handled by standard (non-ostream) formatters.
41 template <typename T, typename Char>
42 struct is_streamable<
43 T, Char,
44 enable_if_t<
45 std::is_arithmetic<T>::value || std::is_array<T>::value ||
46 std::is_pointer<T>::value || std::is_same<T, char8_type>::value ||
47 std::is_same<T, std::basic_string<Char>>::value ||
48 std::is_same<T, std_string_view<Char>>::value ||
49 (std::is_convertible<T, int>::value && !std::is_enum<T>::value)>>
50 : std::false_type {};
51
52 // Write the content of buf to os.
53 // It is a separate function rather than a part of vprint to simplify testing.
54 template <typename Char>
55 void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) {
56 const Char* buf_data = buf.data();
57 using unsigned_streamsize = std::make_unsigned<std::streamsize>::type;
58 unsigned_streamsize size = buf.size();
59 unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());
60 do {
61 unsigned_streamsize n = size <= max_size ? size : max_size;
62 os.write(buf_data, static_cast<std::streamsize>(n));
63 buf_data += n;
64 size -= n;
65 } while (size != 0);
66 }
67
68 template <typename Char, typename T>
69 void format_value(buffer<Char>& buf, const T& value,
70 locale_ref loc = locale_ref()) {
71 auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);
72 auto&& output = std::basic_ostream<Char>(&format_buf);
73 #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
74 if (loc) output.imbue(loc.get<std::locale>());
75 #endif
76 output << value;
77 output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
78 buf.try_resize(buf.size());
79 }
80
81 // Formats an object of type T that has an overloaded ostream operator<<.
82 template <typename T, typename Char>
83 struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
84 : private formatter<basic_string_view<Char>, Char> {
85 using formatter<basic_string_view<Char>, Char>::parse;
86
87 template <typename OutputIt>
88 auto format(const T& value, basic_format_context<OutputIt, Char>& ctx)
89 -> OutputIt {
90 auto buffer = basic_memory_buffer<Char>();
91 format_value(buffer, value, ctx.locale());
92 return formatter<basic_string_view<Char>, Char>::format(
93 {buffer.data(), buffer.size()}, ctx);
94 }
95
96 // DEPRECATED!
97 template <typename OutputIt>
98 auto format(const T& value, basic_printf_context<OutputIt, Char>& ctx)
99 -> OutputIt {
100 auto buffer = basic_memory_buffer<Char>();
101 format_value(buffer, value, ctx.locale());
102 return std::copy(buffer.begin(), buffer.end(), ctx.out());
103 }
104 };
105 } // namespace detail
106
107 FMT_MODULE_EXPORT
108 template <typename Char>
109 void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
110 basic_format_args<buffer_context<type_identity_t<Char>>> args) {
111 auto buffer = basic_memory_buffer<Char>();
112 detail::vformat_to(buffer, format_str, args);
113 detail::write_buffer(os, buffer);
114 }
115
116 /**
117 \rst
118 Prints formatted data to the stream *os*.
119
120 **Example**::
121
122 fmt::print(cerr, "Don't {}!", "panic");
123 \endrst
124 */
125 FMT_MODULE_EXPORT
126 template <typename S, typename... Args,
127 typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
128 void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) {
129 vprint(os, to_string_view(format_str),
130 fmt::make_args_checked<Args...>(format_str, args...));
131 }
132 FMT_END_NAMESPACE
133
134 #endif // FMT_OSTREAM_H_
+0
-657
source/misc/embedded_libs/fmt-8.1.1/include/fmt/printf.h less more
0 // Formatting library for C++ - legacy printf implementation
1 //
2 // Copyright (c) 2012 - 2016, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_PRINTF_H_
8 #define FMT_PRINTF_H_
9
10 #include <algorithm> // std::max
11 #include <limits> // std::numeric_limits
12 #include <ostream>
13
14 #include "format.h"
15
16 FMT_BEGIN_NAMESPACE
17 FMT_MODULE_EXPORT_BEGIN
18
19 template <typename T> struct printf_formatter { printf_formatter() = delete; };
20
21 template <typename Char>
22 class basic_printf_parse_context : public basic_format_parse_context<Char> {
23 using basic_format_parse_context<Char>::basic_format_parse_context;
24 };
25
26 template <typename OutputIt, typename Char> class basic_printf_context {
27 private:
28 OutputIt out_;
29 basic_format_args<basic_printf_context> args_;
30
31 public:
32 using char_type = Char;
33 using format_arg = basic_format_arg<basic_printf_context>;
34 using parse_context_type = basic_printf_parse_context<Char>;
35 template <typename T> using formatter_type = printf_formatter<T>;
36
37 /**
38 \rst
39 Constructs a ``printf_context`` object. References to the arguments are
40 stored in the context object so make sure they have appropriate lifetimes.
41 \endrst
42 */
43 basic_printf_context(OutputIt out,
44 basic_format_args<basic_printf_context> args)
45 : out_(out), args_(args) {}
46
47 OutputIt out() { return out_; }
48 void advance_to(OutputIt it) { out_ = it; }
49
50 detail::locale_ref locale() { return {}; }
51
52 format_arg arg(int id) const { return args_.get(id); }
53
54 FMT_CONSTEXPR void on_error(const char* message) {
55 detail::error_handler().on_error(message);
56 }
57 };
58
59 FMT_BEGIN_DETAIL_NAMESPACE
60
61 // Checks if a value fits in int - used to avoid warnings about comparing
62 // signed and unsigned integers.
63 template <bool IsSigned> struct int_checker {
64 template <typename T> static bool fits_in_int(T value) {
65 unsigned max = max_value<int>();
66 return value <= max;
67 }
68 static bool fits_in_int(bool) { return true; }
69 };
70
71 template <> struct int_checker<true> {
72 template <typename T> static bool fits_in_int(T value) {
73 return value >= (std::numeric_limits<int>::min)() &&
74 value <= max_value<int>();
75 }
76 static bool fits_in_int(int) { return true; }
77 };
78
79 class printf_precision_handler {
80 public:
81 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
82 int operator()(T value) {
83 if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
84 FMT_THROW(format_error("number is too big"));
85 return (std::max)(static_cast<int>(value), 0);
86 }
87
88 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
89 int operator()(T) {
90 FMT_THROW(format_error("precision is not integer"));
91 return 0;
92 }
93 };
94
95 // An argument visitor that returns true iff arg is a zero integer.
96 class is_zero_int {
97 public:
98 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
99 bool operator()(T value) {
100 return value == 0;
101 }
102
103 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
104 bool operator()(T) {
105 return false;
106 }
107 };
108
109 template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
110
111 template <> struct make_unsigned_or_bool<bool> { using type = bool; };
112
113 template <typename T, typename Context> class arg_converter {
114 private:
115 using char_type = typename Context::char_type;
116
117 basic_format_arg<Context>& arg_;
118 char_type type_;
119
120 public:
121 arg_converter(basic_format_arg<Context>& arg, char_type type)
122 : arg_(arg), type_(type) {}
123
124 void operator()(bool value) {
125 if (type_ != 's') operator()<bool>(value);
126 }
127
128 template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)>
129 void operator()(U value) {
130 bool is_signed = type_ == 'd' || type_ == 'i';
131 using target_type = conditional_t<std::is_same<T, void>::value, U, T>;
132 if (const_check(sizeof(target_type) <= sizeof(int))) {
133 // Extra casts are used to silence warnings.
134 if (is_signed) {
135 arg_ = detail::make_arg<Context>(
136 static_cast<int>(static_cast<target_type>(value)));
137 } else {
138 using unsigned_type = typename make_unsigned_or_bool<target_type>::type;
139 arg_ = detail::make_arg<Context>(
140 static_cast<unsigned>(static_cast<unsigned_type>(value)));
141 }
142 } else {
143 if (is_signed) {
144 // glibc's printf doesn't sign extend arguments of smaller types:
145 // std::printf("%lld", -42); // prints "4294967254"
146 // but we don't have to do the same because it's a UB.
147 arg_ = detail::make_arg<Context>(static_cast<long long>(value));
148 } else {
149 arg_ = detail::make_arg<Context>(
150 static_cast<typename make_unsigned_or_bool<U>::type>(value));
151 }
152 }
153 }
154
155 template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)>
156 void operator()(U) {} // No conversion needed for non-integral types.
157 };
158
159 // Converts an integer argument to T for printf, if T is an integral type.
160 // If T is void, the argument is converted to corresponding signed or unsigned
161 // type depending on the type specifier: 'd' and 'i' - signed, other -
162 // unsigned).
163 template <typename T, typename Context, typename Char>
164 void convert_arg(basic_format_arg<Context>& arg, Char type) {
165 visit_format_arg(arg_converter<T, Context>(arg, type), arg);
166 }
167
168 // Converts an integer argument to char for printf.
169 template <typename Context> class char_converter {
170 private:
171 basic_format_arg<Context>& arg_;
172
173 public:
174 explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}
175
176 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
177 void operator()(T value) {
178 arg_ = detail::make_arg<Context>(
179 static_cast<typename Context::char_type>(value));
180 }
181
182 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
183 void operator()(T) {} // No conversion needed for non-integral types.
184 };
185
186 // An argument visitor that return a pointer to a C string if argument is a
187 // string or null otherwise.
188 template <typename Char> struct get_cstring {
189 template <typename T> const Char* operator()(T) { return nullptr; }
190 const Char* operator()(const Char* s) { return s; }
191 };
192
193 // Checks if an argument is a valid printf width specifier and sets
194 // left alignment if it is negative.
195 template <typename Char> class printf_width_handler {
196 private:
197 using format_specs = basic_format_specs<Char>;
198
199 format_specs& specs_;
200
201 public:
202 explicit printf_width_handler(format_specs& specs) : specs_(specs) {}
203
204 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
205 unsigned operator()(T value) {
206 auto width = static_cast<uint32_or_64_or_128_t<T>>(value);
207 if (detail::is_negative(value)) {
208 specs_.align = align::left;
209 width = 0 - width;
210 }
211 unsigned int_max = max_value<int>();
212 if (width > int_max) FMT_THROW(format_error("number is too big"));
213 return static_cast<unsigned>(width);
214 }
215
216 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
217 unsigned operator()(T) {
218 FMT_THROW(format_error("width is not integer"));
219 return 0;
220 }
221 };
222
223 // The ``printf`` argument formatter.
224 template <typename OutputIt, typename Char>
225 class printf_arg_formatter : public arg_formatter<Char> {
226 private:
227 using base = arg_formatter<Char>;
228 using context_type = basic_printf_context<OutputIt, Char>;
229 using format_specs = basic_format_specs<Char>;
230
231 context_type& context_;
232
233 OutputIt write_null_pointer(bool is_string = false) {
234 auto s = this->specs;
235 s.type = presentation_type::none;
236 return write_bytes(this->out, is_string ? "(null)" : "(nil)", s);
237 }
238
239 public:
240 printf_arg_formatter(OutputIt iter, format_specs& s, context_type& ctx)
241 : base{iter, s, locale_ref()}, context_(ctx) {}
242
243 OutputIt operator()(monostate value) { return base::operator()(value); }
244
245 template <typename T, FMT_ENABLE_IF(detail::is_integral<T>::value)>
246 OutputIt operator()(T value) {
247 // MSVC2013 fails to compile separate overloads for bool and Char so use
248 // std::is_same instead.
249 if (std::is_same<T, Char>::value) {
250 format_specs fmt_specs = this->specs;
251 if (fmt_specs.type != presentation_type::none &&
252 fmt_specs.type != presentation_type::chr) {
253 return (*this)(static_cast<int>(value));
254 }
255 fmt_specs.sign = sign::none;
256 fmt_specs.alt = false;
257 fmt_specs.fill[0] = ' '; // Ignore '0' flag for char types.
258 // align::numeric needs to be overwritten here since the '0' flag is
259 // ignored for non-numeric types
260 if (fmt_specs.align == align::none || fmt_specs.align == align::numeric)
261 fmt_specs.align = align::right;
262 return write<Char>(this->out, static_cast<Char>(value), fmt_specs);
263 }
264 return base::operator()(value);
265 }
266
267 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
268 OutputIt operator()(T value) {
269 return base::operator()(value);
270 }
271
272 /** Formats a null-terminated C string. */
273 OutputIt operator()(const char* value) {
274 if (value) return base::operator()(value);
275 return write_null_pointer(this->specs.type != presentation_type::pointer);
276 }
277
278 /** Formats a null-terminated wide C string. */
279 OutputIt operator()(const wchar_t* value) {
280 if (value) return base::operator()(value);
281 return write_null_pointer(this->specs.type != presentation_type::pointer);
282 }
283
284 OutputIt operator()(basic_string_view<Char> value) {
285 return base::operator()(value);
286 }
287
288 /** Formats a pointer. */
289 OutputIt operator()(const void* value) {
290 return value ? base::operator()(value) : write_null_pointer();
291 }
292
293 /** Formats an argument of a custom (user-defined) type. */
294 OutputIt operator()(typename basic_format_arg<context_type>::handle handle) {
295 auto parse_ctx =
296 basic_printf_parse_context<Char>(basic_string_view<Char>());
297 handle.format(parse_ctx, context_);
298 return this->out;
299 }
300 };
301
302 template <typename Char>
303 void parse_flags(basic_format_specs<Char>& specs, const Char*& it,
304 const Char* end) {
305 for (; it != end; ++it) {
306 switch (*it) {
307 case '-':
308 specs.align = align::left;
309 break;
310 case '+':
311 specs.sign = sign::plus;
312 break;
313 case '0':
314 specs.fill[0] = '0';
315 break;
316 case ' ':
317 if (specs.sign != sign::plus) {
318 specs.sign = sign::space;
319 }
320 break;
321 case '#':
322 specs.alt = true;
323 break;
324 default:
325 return;
326 }
327 }
328 }
329
330 template <typename Char, typename GetArg>
331 int parse_header(const Char*& it, const Char* end,
332 basic_format_specs<Char>& specs, GetArg get_arg) {
333 int arg_index = -1;
334 Char c = *it;
335 if (c >= '0' && c <= '9') {
336 // Parse an argument index (if followed by '$') or a width possibly
337 // preceded with '0' flag(s).
338 int value = parse_nonnegative_int(it, end, -1);
339 if (it != end && *it == '$') { // value is an argument index
340 ++it;
341 arg_index = value != -1 ? value : max_value<int>();
342 } else {
343 if (c == '0') specs.fill[0] = '0';
344 if (value != 0) {
345 // Nonzero value means that we parsed width and don't need to
346 // parse it or flags again, so return now.
347 if (value == -1) FMT_THROW(format_error("number is too big"));
348 specs.width = value;
349 return arg_index;
350 }
351 }
352 }
353 parse_flags(specs, it, end);
354 // Parse width.
355 if (it != end) {
356 if (*it >= '0' && *it <= '9') {
357 specs.width = parse_nonnegative_int(it, end, -1);
358 if (specs.width == -1) FMT_THROW(format_error("number is too big"));
359 } else if (*it == '*') {
360 ++it;
361 specs.width = static_cast<int>(visit_format_arg(
362 detail::printf_width_handler<Char>(specs), get_arg(-1)));
363 }
364 }
365 return arg_index;
366 }
367
368 template <typename Char, typename Context>
369 void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
370 basic_format_args<Context> args) {
371 using OutputIt = buffer_appender<Char>;
372 auto out = OutputIt(buf);
373 auto context = basic_printf_context<OutputIt, Char>(out, args);
374 auto parse_ctx = basic_printf_parse_context<Char>(format);
375
376 // Returns the argument with specified index or, if arg_index is -1, the next
377 // argument.
378 auto get_arg = [&](int arg_index) {
379 if (arg_index < 0)
380 arg_index = parse_ctx.next_arg_id();
381 else
382 parse_ctx.check_arg_id(--arg_index);
383 return detail::get_arg(context, arg_index);
384 };
385
386 const Char* start = parse_ctx.begin();
387 const Char* end = parse_ctx.end();
388 auto it = start;
389 while (it != end) {
390 if (!detail::find<false, Char>(it, end, '%', it)) {
391 it = end; // detail::find leaves it == nullptr if it doesn't find '%'
392 break;
393 }
394 Char c = *it++;
395 if (it != end && *it == c) {
396 out = detail::write(
397 out, basic_string_view<Char>(start, detail::to_unsigned(it - start)));
398 start = ++it;
399 continue;
400 }
401 out = detail::write(out, basic_string_view<Char>(
402 start, detail::to_unsigned(it - 1 - start)));
403
404 basic_format_specs<Char> specs;
405 specs.align = align::right;
406
407 // Parse argument index, flags and width.
408 int arg_index = parse_header(it, end, specs, get_arg);
409 if (arg_index == 0) parse_ctx.on_error("argument not found");
410
411 // Parse precision.
412 if (it != end && *it == '.') {
413 ++it;
414 c = it != end ? *it : 0;
415 if ('0' <= c && c <= '9') {
416 specs.precision = parse_nonnegative_int(it, end, 0);
417 } else if (c == '*') {
418 ++it;
419 specs.precision = static_cast<int>(
420 visit_format_arg(detail::printf_precision_handler(), get_arg(-1)));
421 } else {
422 specs.precision = 0;
423 }
424 }
425
426 auto arg = get_arg(arg_index);
427 // For d, i, o, u, x, and X conversion specifiers, if a precision is
428 // specified, the '0' flag is ignored
429 if (specs.precision >= 0 && arg.is_integral())
430 specs.fill[0] =
431 ' '; // Ignore '0' flag for non-numeric types or if '-' present.
432 if (specs.precision >= 0 && arg.type() == detail::type::cstring_type) {
433 auto str = visit_format_arg(detail::get_cstring<Char>(), arg);
434 auto str_end = str + specs.precision;
435 auto nul = std::find(str, str_end, Char());
436 arg = detail::make_arg<basic_printf_context<OutputIt, Char>>(
437 basic_string_view<Char>(
438 str, detail::to_unsigned(nul != str_end ? nul - str
439 : specs.precision)));
440 }
441 if (specs.alt && visit_format_arg(detail::is_zero_int(), arg))
442 specs.alt = false;
443 if (specs.fill[0] == '0') {
444 if (arg.is_arithmetic() && specs.align != align::left)
445 specs.align = align::numeric;
446 else
447 specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types or if '-'
448 // flag is also present.
449 }
450
451 // Parse length and convert the argument to the required type.
452 c = it != end ? *it++ : 0;
453 Char t = it != end ? *it : 0;
454 using detail::convert_arg;
455 switch (c) {
456 case 'h':
457 if (t == 'h') {
458 ++it;
459 t = it != end ? *it : 0;
460 convert_arg<signed char>(arg, t);
461 } else {
462 convert_arg<short>(arg, t);
463 }
464 break;
465 case 'l':
466 if (t == 'l') {
467 ++it;
468 t = it != end ? *it : 0;
469 convert_arg<long long>(arg, t);
470 } else {
471 convert_arg<long>(arg, t);
472 }
473 break;
474 case 'j':
475 convert_arg<intmax_t>(arg, t);
476 break;
477 case 'z':
478 convert_arg<size_t>(arg, t);
479 break;
480 case 't':
481 convert_arg<std::ptrdiff_t>(arg, t);
482 break;
483 case 'L':
484 // printf produces garbage when 'L' is omitted for long double, no
485 // need to do the same.
486 break;
487 default:
488 --it;
489 convert_arg<void>(arg, c);
490 }
491
492 // Parse type.
493 if (it == end) FMT_THROW(format_error("invalid format string"));
494 char type = static_cast<char>(*it++);
495 if (arg.is_integral()) {
496 // Normalize type.
497 switch (type) {
498 case 'i':
499 case 'u':
500 type = 'd';
501 break;
502 case 'c':
503 visit_format_arg(
504 detail::char_converter<basic_printf_context<OutputIt, Char>>(arg),
505 arg);
506 break;
507 }
508 }
509 specs.type = parse_presentation_type(type);
510 if (specs.type == presentation_type::none)
511 parse_ctx.on_error("invalid type specifier");
512
513 start = it;
514
515 // Format argument.
516 out = visit_format_arg(
517 detail::printf_arg_formatter<OutputIt, Char>(out, specs, context), arg);
518 }
519 detail::write(out, basic_string_view<Char>(start, to_unsigned(it - start)));
520 }
521 FMT_END_DETAIL_NAMESPACE
522
523 template <typename Char>
524 using basic_printf_context_t =
525 basic_printf_context<detail::buffer_appender<Char>, Char>;
526
527 using printf_context = basic_printf_context_t<char>;
528 using wprintf_context = basic_printf_context_t<wchar_t>;
529
530 using printf_args = basic_format_args<printf_context>;
531 using wprintf_args = basic_format_args<wprintf_context>;
532
533 /**
534 \rst
535 Constructs an `~fmt::format_arg_store` object that contains references to
536 arguments and can be implicitly converted to `~fmt::printf_args`.
537 \endrst
538 */
539 template <typename... T>
540 inline auto make_printf_args(const T&... args)
541 -> format_arg_store<printf_context, T...> {
542 return {args...};
543 }
544
545 /**
546 \rst
547 Constructs an `~fmt::format_arg_store` object that contains references to
548 arguments and can be implicitly converted to `~fmt::wprintf_args`.
549 \endrst
550 */
551 template <typename... T>
552 inline auto make_wprintf_args(const T&... args)
553 -> format_arg_store<wprintf_context, T...> {
554 return {args...};
555 }
556
557 template <typename S, typename Char = char_t<S>>
558 inline auto vsprintf(
559 const S& fmt,
560 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
561 -> std::basic_string<Char> {
562 basic_memory_buffer<Char> buffer;
563 vprintf(buffer, to_string_view(fmt), args);
564 return to_string(buffer);
565 }
566
567 /**
568 \rst
569 Formats arguments and returns the result as a string.
570
571 **Example**::
572
573 std::string message = fmt::sprintf("The answer is %d", 42);
574 \endrst
575 */
576 template <typename S, typename... T,
577 typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
578 inline auto sprintf(const S& fmt, const T&... args) -> std::basic_string<Char> {
579 using context = basic_printf_context_t<Char>;
580 return vsprintf(to_string_view(fmt), fmt::make_format_args<context>(args...));
581 }
582
583 template <typename S, typename Char = char_t<S>>
584 inline auto vfprintf(
585 std::FILE* f, const S& fmt,
586 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
587 -> int {
588 basic_memory_buffer<Char> buffer;
589 vprintf(buffer, to_string_view(fmt), args);
590 size_t size = buffer.size();
591 return std::fwrite(buffer.data(), sizeof(Char), size, f) < size
592 ? -1
593 : static_cast<int>(size);
594 }
595
596 /**
597 \rst
598 Prints formatted data to the file *f*.
599
600 **Example**::
601
602 fmt::fprintf(stderr, "Don't %s!", "panic");
603 \endrst
604 */
605 template <typename S, typename... T, typename Char = char_t<S>>
606 inline auto fprintf(std::FILE* f, const S& fmt, const T&... args) -> int {
607 using context = basic_printf_context_t<Char>;
608 return vfprintf(f, to_string_view(fmt),
609 fmt::make_format_args<context>(args...));
610 }
611
612 template <typename S, typename Char = char_t<S>>
613 inline auto vprintf(
614 const S& fmt,
615 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
616 -> int {
617 return vfprintf(stdout, to_string_view(fmt), args);
618 }
619
620 /**
621 \rst
622 Prints formatted data to ``stdout``.
623
624 **Example**::
625
626 fmt::printf("Elapsed time: %.2f seconds", 1.23);
627 \endrst
628 */
629 template <typename S, typename... T, FMT_ENABLE_IF(detail::is_string<S>::value)>
630 inline auto printf(const S& fmt, const T&... args) -> int {
631 return vprintf(
632 to_string_view(fmt),
633 fmt::make_format_args<basic_printf_context_t<char_t<S>>>(args...));
634 }
635
636 template <typename S, typename Char = char_t<S>>
637 FMT_DEPRECATED auto vfprintf(
638 std::basic_ostream<Char>& os, const S& fmt,
639 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
640 -> int {
641 basic_memory_buffer<Char> buffer;
642 vprintf(buffer, to_string_view(fmt), args);
643 os.write(buffer.data(), static_cast<std::streamsize>(buffer.size()));
644 return static_cast<int>(buffer.size());
645 }
646 template <typename S, typename... T, typename Char = char_t<S>>
647 FMT_DEPRECATED auto fprintf(std::basic_ostream<Char>& os, const S& fmt,
648 const T&... args) -> int {
649 return vfprintf(os, to_string_view(fmt),
650 fmt::make_format_args<basic_printf_context_t<Char>>(args...));
651 }
652
653 FMT_MODULE_EXPORT_END
654 FMT_END_NAMESPACE
655
656 #endif // FMT_PRINTF_H_
+0
-793
source/misc/embedded_libs/fmt-8.1.1/include/fmt/ranges.h less more
0 // Formatting library for C++ - experimental range support
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6 //
7 // Copyright (c) 2018 - present, Remotion (Igor Schulz)
8 // All Rights Reserved
9 // {fmt} support for ranges, containers and types tuple interface.
10
11 #ifndef FMT_RANGES_H_
12 #define FMT_RANGES_H_
13
14 #include <initializer_list>
15 #include <tuple>
16 #include <type_traits>
17
18 #include "format.h"
19
20 FMT_BEGIN_NAMESPACE
21
22 namespace detail {
23
24 template <typename RangeT, typename OutputIterator>
25 OutputIterator copy(const RangeT& range, OutputIterator out) {
26 for (auto it = range.begin(), end = range.end(); it != end; ++it)
27 *out++ = *it;
28 return out;
29 }
30
31 template <typename OutputIterator>
32 OutputIterator copy(const char* str, OutputIterator out) {
33 while (*str) *out++ = *str++;
34 return out;
35 }
36
37 template <typename OutputIterator>
38 OutputIterator copy(char ch, OutputIterator out) {
39 *out++ = ch;
40 return out;
41 }
42
43 template <typename OutputIterator>
44 OutputIterator copy(wchar_t ch, OutputIterator out) {
45 *out++ = ch;
46 return out;
47 }
48
49 // Returns true if T has a std::string-like interface, like std::string_view.
50 template <typename T> class is_std_string_like {
51 template <typename U>
52 static auto check(U* p)
53 -> decltype((void)p->find('a'), p->length(), (void)p->data(), int());
54 template <typename> static void check(...);
55
56 public:
57 static FMT_CONSTEXPR_DECL const bool value =
58 is_string<T>::value ||
59 std::is_convertible<T, std_string_view<char>>::value ||
60 !std::is_void<decltype(check<T>(nullptr))>::value;
61 };
62
63 template <typename Char>
64 struct is_std_string_like<fmt::basic_string_view<Char>> : std::true_type {};
65
66 template <typename T> class is_map {
67 template <typename U> static auto check(U*) -> typename U::mapped_type;
68 template <typename> static void check(...);
69
70 public:
71 #ifdef FMT_FORMAT_MAP_AS_LIST
72 static FMT_CONSTEXPR_DECL const bool value = false;
73 #else
74 static FMT_CONSTEXPR_DECL const bool value =
75 !std::is_void<decltype(check<T>(nullptr))>::value;
76 #endif
77 };
78
79 template <typename T> class is_set {
80 template <typename U> static auto check(U*) -> typename U::key_type;
81 template <typename> static void check(...);
82
83 public:
84 #ifdef FMT_FORMAT_SET_AS_LIST
85 static FMT_CONSTEXPR_DECL const bool value = false;
86 #else
87 static FMT_CONSTEXPR_DECL const bool value =
88 !std::is_void<decltype(check<T>(nullptr))>::value && !is_map<T>::value;
89 #endif
90 };
91
92 template <typename... Ts> struct conditional_helper {};
93
94 template <typename T, typename _ = void> struct is_range_ : std::false_type {};
95
96 #if !FMT_MSC_VER || FMT_MSC_VER > 1800
97
98 # define FMT_DECLTYPE_RETURN(val) \
99 ->decltype(val) { return val; } \
100 static_assert( \
101 true, "") // This makes it so that a semicolon is required after the
102 // macro, which helps clang-format handle the formatting.
103
104 // C array overload
105 template <typename T, std::size_t N>
106 auto range_begin(const T (&arr)[N]) -> const T* {
107 return arr;
108 }
109 template <typename T, std::size_t N>
110 auto range_end(const T (&arr)[N]) -> const T* {
111 return arr + N;
112 }
113
114 template <typename T, typename Enable = void>
115 struct has_member_fn_begin_end_t : std::false_type {};
116
117 template <typename T>
118 struct has_member_fn_begin_end_t<T, void_t<decltype(std::declval<T>().begin()),
119 decltype(std::declval<T>().end())>>
120 : std::true_type {};
121
122 // Member function overload
123 template <typename T>
124 auto range_begin(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).begin());
125 template <typename T>
126 auto range_end(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).end());
127
128 // ADL overload. Only participates in overload resolution if member functions
129 // are not found.
130 template <typename T>
131 auto range_begin(T&& rng)
132 -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
133 decltype(begin(static_cast<T&&>(rng)))> {
134 return begin(static_cast<T&&>(rng));
135 }
136 template <typename T>
137 auto range_end(T&& rng) -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
138 decltype(end(static_cast<T&&>(rng)))> {
139 return end(static_cast<T&&>(rng));
140 }
141
142 template <typename T, typename Enable = void>
143 struct has_const_begin_end : std::false_type {};
144 template <typename T, typename Enable = void>
145 struct has_mutable_begin_end : std::false_type {};
146
147 template <typename T>
148 struct has_const_begin_end<
149 T,
150 void_t<
151 decltype(detail::range_begin(std::declval<const remove_cvref_t<T>&>())),
152 decltype(detail::range_end(std::declval<const remove_cvref_t<T>&>()))>>
153 : std::true_type {};
154
155 template <typename T>
156 struct has_mutable_begin_end<
157 T, void_t<decltype(detail::range_begin(std::declval<T>())),
158 decltype(detail::range_end(std::declval<T>())),
159 enable_if_t<std::is_copy_constructible<T>::value>>>
160 : std::true_type {};
161
162 template <typename T>
163 struct is_range_<T, void>
164 : std::integral_constant<bool, (has_const_begin_end<T>::value ||
165 has_mutable_begin_end<T>::value)> {};
166 # undef FMT_DECLTYPE_RETURN
167 #endif
168
169 // tuple_size and tuple_element check.
170 template <typename T> class is_tuple_like_ {
171 template <typename U>
172 static auto check(U* p) -> decltype(std::tuple_size<U>::value, int());
173 template <typename> static void check(...);
174
175 public:
176 static FMT_CONSTEXPR_DECL const bool value =
177 !std::is_void<decltype(check<T>(nullptr))>::value;
178 };
179
180 // Check for integer_sequence
181 #if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
182 template <typename T, T... N>
183 using integer_sequence = std::integer_sequence<T, N...>;
184 template <size_t... N> using index_sequence = std::index_sequence<N...>;
185 template <size_t N> using make_index_sequence = std::make_index_sequence<N>;
186 #else
187 template <typename T, T... N> struct integer_sequence {
188 using value_type = T;
189
190 static FMT_CONSTEXPR size_t size() { return sizeof...(N); }
191 };
192
193 template <size_t... N> using index_sequence = integer_sequence<size_t, N...>;
194
195 template <typename T, size_t N, T... Ns>
196 struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
197 template <typename T, T... Ns>
198 struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
199
200 template <size_t N>
201 using make_index_sequence = make_integer_sequence<size_t, N>;
202 #endif
203
204 template <class Tuple, class F, size_t... Is>
205 void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
206 using std::get;
207 // using free function get<I>(T) now.
208 const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
209 (void)_; // blocks warnings
210 }
211
212 template <class T>
213 FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
214 T const&) {
215 return {};
216 }
217
218 template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
219 const auto indexes = get_indexes(tup);
220 for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
221 }
222
223 template <typename Range>
224 using value_type =
225 remove_cvref_t<decltype(*detail::range_begin(std::declval<Range>()))>;
226
227 template <typename OutputIt> OutputIt write_delimiter(OutputIt out) {
228 *out++ = ',';
229 *out++ = ' ';
230 return out;
231 }
232
233 struct singleton {
234 unsigned char upper;
235 unsigned char lower_count;
236 };
237
238 inline auto is_printable(uint16_t x, const singleton* singletons,
239 size_t singletons_size,
240 const unsigned char* singleton_lowers,
241 const unsigned char* normal, size_t normal_size)
242 -> bool {
243 auto upper = x >> 8;
244 auto lower_start = 0;
245 for (size_t i = 0; i < singletons_size; ++i) {
246 auto s = singletons[i];
247 auto lower_end = lower_start + s.lower_count;
248 if (upper < s.upper) break;
249 if (upper == s.upper) {
250 for (auto j = lower_start; j < lower_end; ++j) {
251 if (singleton_lowers[j] == (x & 0xff)) return false;
252 }
253 }
254 lower_start = lower_end;
255 }
256
257 auto xsigned = static_cast<int>(x);
258 auto current = true;
259 for (size_t i = 0; i < normal_size; ++i) {
260 auto v = static_cast<int>(normal[i]);
261 auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v;
262 xsigned -= len;
263 if (xsigned < 0) break;
264 current = !current;
265 }
266 return current;
267 }
268
269 // Returns true iff the code point cp is printable.
270 // This code is generated by support/printable.py.
271 inline auto is_printable(uint32_t cp) -> bool {
272 static constexpr singleton singletons0[] = {
273 {0x00, 1}, {0x03, 5}, {0x05, 6}, {0x06, 3}, {0x07, 6}, {0x08, 8},
274 {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13},
275 {0x0f, 4}, {0x10, 3}, {0x12, 18}, {0x13, 9}, {0x16, 1}, {0x17, 5},
276 {0x18, 2}, {0x19, 3}, {0x1a, 7}, {0x1c, 2}, {0x1d, 1}, {0x1f, 22},
277 {0x20, 3}, {0x2b, 3}, {0x2c, 2}, {0x2d, 11}, {0x2e, 1}, {0x30, 3},
278 {0x31, 2}, {0x32, 1}, {0xa7, 2}, {0xa9, 2}, {0xaa, 4}, {0xab, 8},
279 {0xfa, 2}, {0xfb, 5}, {0xfd, 4}, {0xfe, 3}, {0xff, 9},
280 };
281 static constexpr unsigned char singletons0_lower[] = {
282 0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90,
283 0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f,
284 0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1,
285 0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04,
286 0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d,
287 0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf,
288 0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
289 0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d,
290 0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d,
291 0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d,
292 0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5,
293 0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7,
294 0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49,
295 0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7,
296 0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7,
297 0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e,
298 0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16,
299 0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e,
300 0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f,
301 0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf,
302 0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0,
303 0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27,
304 0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91,
305 0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7,
306 0xfe, 0xff,
307 };
308 static constexpr singleton singletons1[] = {
309 {0x00, 6}, {0x01, 1}, {0x03, 1}, {0x04, 2}, {0x08, 8}, {0x09, 2},
310 {0x0a, 5}, {0x0b, 2}, {0x0e, 4}, {0x10, 1}, {0x11, 2}, {0x12, 5},
311 {0x13, 17}, {0x14, 1}, {0x15, 2}, {0x17, 2}, {0x19, 13}, {0x1c, 5},
312 {0x1d, 8}, {0x24, 1}, {0x6a, 3}, {0x6b, 2}, {0xbc, 2}, {0xd1, 2},
313 {0xd4, 12}, {0xd5, 9}, {0xd6, 2}, {0xd7, 2}, {0xda, 1}, {0xe0, 5},
314 {0xe1, 2}, {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2}, {0xf9, 2},
315 {0xfa, 2}, {0xfb, 1},
316 };
317 static constexpr unsigned char singletons1_lower[] = {
318 0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07,
319 0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36,
320 0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87,
321 0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
322 0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b,
323 0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9,
324 0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66,
325 0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27,
326 0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc,
327 0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7,
328 0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6,
329 0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c,
330 0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66,
331 0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0,
332 0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93,
333 };
334 static constexpr unsigned char normal0[] = {
335 0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04,
336 0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0,
337 0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01,
338 0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03,
339 0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03,
340 0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a,
341 0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15,
342 0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f,
343 0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80,
344 0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07,
345 0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06,
346 0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04,
347 0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac,
348 0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c,
349 0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11,
350 0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c,
351 0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b,
352 0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6,
353 0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03,
354 0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80,
355 0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06,
356 0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c,
357 0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17,
358 0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80,
359 0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80,
360 0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d,
361 };
362 static constexpr unsigned char normal1[] = {
363 0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f,
364 0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e,
365 0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04,
366 0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09,
367 0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16,
368 0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f,
369 0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36,
370 0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33,
371 0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08,
372 0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e,
373 0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41,
374 0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03,
375 0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22,
376 0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04,
377 0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45,
378 0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03,
379 0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81,
380 0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75,
381 0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1,
382 0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a,
383 0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11,
384 0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09,
385 0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89,
386 0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6,
387 0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09,
388 0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50,
389 0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05,
390 0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83,
391 0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05,
392 0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80,
393 0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80,
394 0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07,
395 0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e,
396 0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07,
397 0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06,
398 };
399 auto lower = static_cast<uint16_t>(cp);
400 if (cp < 0x10000) {
401 return is_printable(lower, singletons0,
402 sizeof(singletons0) / sizeof(*singletons0),
403 singletons0_lower, normal0, sizeof(normal0));
404 }
405 if (cp < 0x20000) {
406 return is_printable(lower, singletons1,
407 sizeof(singletons1) / sizeof(*singletons1),
408 singletons1_lower, normal1, sizeof(normal1));
409 }
410 if (0x2a6de <= cp && cp < 0x2a700) return false;
411 if (0x2b735 <= cp && cp < 0x2b740) return false;
412 if (0x2b81e <= cp && cp < 0x2b820) return false;
413 if (0x2cea2 <= cp && cp < 0x2ceb0) return false;
414 if (0x2ebe1 <= cp && cp < 0x2f800) return false;
415 if (0x2fa1e <= cp && cp < 0x30000) return false;
416 if (0x3134b <= cp && cp < 0xe0100) return false;
417 if (0xe01f0 <= cp && cp < 0x110000) return false;
418 return cp < 0x110000;
419 }
420
421 inline auto needs_escape(uint32_t cp) -> bool {
422 return cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\' ||
423 !is_printable(cp);
424 }
425
426 template <typename Char> struct find_escape_result {
427 const Char* begin;
428 const Char* end;
429 uint32_t cp;
430 };
431
432 template <typename Char>
433 auto find_escape(const Char* begin, const Char* end)
434 -> find_escape_result<Char> {
435 for (; begin != end; ++begin) {
436 auto cp = static_cast<typename std::make_unsigned<Char>::type>(*begin);
437 if (sizeof(Char) == 1 && cp >= 0x80) continue;
438 if (needs_escape(cp)) return {begin, begin + 1, cp};
439 }
440 return {begin, nullptr, 0};
441 }
442
443 inline auto find_escape(const char* begin, const char* end)
444 -> find_escape_result<char> {
445 if (!is_utf8()) return find_escape<char>(begin, end);
446 auto result = find_escape_result<char>{end, nullptr, 0};
447 for_each_codepoint(string_view(begin, to_unsigned(end - begin)),
448 [&](uint32_t cp, string_view sv) {
449 if (needs_escape(cp)) {
450 result = {sv.begin(), sv.end(), cp};
451 return false;
452 }
453 return true;
454 });
455 return result;
456 }
457
458 template <typename Char, typename OutputIt>
459 auto write_range_entry(OutputIt out, basic_string_view<Char> str) -> OutputIt {
460 *out++ = '"';
461 auto begin = str.begin(), end = str.end();
462 do {
463 auto escape = find_escape(begin, end);
464 out = copy_str<Char>(begin, escape.begin, out);
465 begin = escape.end;
466 if (!begin) break;
467 auto c = static_cast<Char>(escape.cp);
468 switch (escape.cp) {
469 case '\n':
470 *out++ = '\\';
471 c = 'n';
472 break;
473 case '\r':
474 *out++ = '\\';
475 c = 'r';
476 break;
477 case '\t':
478 *out++ = '\\';
479 c = 't';
480 break;
481 case '"':
482 FMT_FALLTHROUGH;
483 case '\\':
484 *out++ = '\\';
485 break;
486 default:
487 if (is_utf8()) {
488 if (escape.cp < 0x100) {
489 out = format_to(out, "\\x{:02x}", escape.cp);
490 continue;
491 }
492 if (escape.cp < 0x10000) {
493 out = format_to(out, "\\u{:04x}", escape.cp);
494 continue;
495 }
496 if (escape.cp < 0x110000) {
497 out = format_to(out, "\\U{:08x}", escape.cp);
498 continue;
499 }
500 }
501 for (Char escape_char : basic_string_view<Char>(
502 escape.begin, to_unsigned(escape.end - escape.begin))) {
503 out = format_to(
504 out, "\\x{:02x}",
505 static_cast<typename std::make_unsigned<Char>::type>(escape_char));
506 }
507 continue;
508 }
509 *out++ = c;
510 } while (begin != end);
511 *out++ = '"';
512 return out;
513 }
514
515 template <typename Char, typename OutputIt, typename T,
516 FMT_ENABLE_IF(std::is_convertible<T, std_string_view<char>>::value)>
517 inline auto write_range_entry(OutputIt out, const T& str) -> OutputIt {
518 auto sv = std_string_view<Char>(str);
519 return write_range_entry<Char>(out, basic_string_view<Char>(sv));
520 }
521
522 template <typename Char, typename OutputIt, typename Arg,
523 FMT_ENABLE_IF(std::is_same<Arg, Char>::value)>
524 OutputIt write_range_entry(OutputIt out, const Arg v) {
525 *out++ = '\'';
526 *out++ = v;
527 *out++ = '\'';
528 return out;
529 }
530
531 template <
532 typename Char, typename OutputIt, typename Arg,
533 FMT_ENABLE_IF(!is_std_string_like<typename std::decay<Arg>::type>::value &&
534 !std::is_same<Arg, Char>::value)>
535 OutputIt write_range_entry(OutputIt out, const Arg& v) {
536 return write<Char>(out, v);
537 }
538
539 } // namespace detail
540
541 template <typename T> struct is_tuple_like {
542 static FMT_CONSTEXPR_DECL const bool value =
543 detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
544 };
545
546 template <typename TupleT, typename Char>
547 struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> {
548 private:
549 // C++11 generic lambda for format().
550 template <typename FormatContext> struct format_each {
551 template <typename T> void operator()(const T& v) {
552 if (i > 0) out = detail::write_delimiter(out);
553 out = detail::write_range_entry<Char>(out, v);
554 ++i;
555 }
556 int i;
557 typename FormatContext::iterator& out;
558 };
559
560 public:
561 template <typename ParseContext>
562 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
563 return ctx.begin();
564 }
565
566 template <typename FormatContext = format_context>
567 auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
568 auto out = ctx.out();
569 *out++ = '(';
570 detail::for_each(values, format_each<FormatContext>{0, out});
571 *out++ = ')';
572 return out;
573 }
574 };
575
576 template <typename T, typename Char> struct is_range {
577 static FMT_CONSTEXPR_DECL const bool value =
578 detail::is_range_<T>::value && !detail::is_std_string_like<T>::value &&
579 !detail::is_map<T>::value &&
580 !std::is_convertible<T, std::basic_string<Char>>::value &&
581 !std::is_constructible<detail::std_string_view<Char>, T>::value;
582 };
583
584 template <typename T, typename Char>
585 struct formatter<
586 T, Char,
587 enable_if_t<
588 fmt::is_range<T, Char>::value
589 // Workaround a bug in MSVC 2019 and earlier.
590 #if !FMT_MSC_VER
591 && (is_formattable<detail::value_type<T>, Char>::value ||
592 detail::has_fallback_formatter<detail::value_type<T>, Char>::value)
593 #endif
594 >> {
595 template <typename ParseContext>
596 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
597 return ctx.begin();
598 }
599
600 template <
601 typename FormatContext, typename U,
602 FMT_ENABLE_IF(
603 std::is_same<U, conditional_t<detail::has_const_begin_end<T>::value,
604 const T, T>>::value)>
605 auto format(U& range, FormatContext& ctx) -> decltype(ctx.out()) {
606 #ifdef FMT_DEPRECATED_BRACED_RANGES
607 Char prefix = '{';
608 Char postfix = '}';
609 #else
610 Char prefix = detail::is_set<T>::value ? '{' : '[';
611 Char postfix = detail::is_set<T>::value ? '}' : ']';
612 #endif
613 auto out = ctx.out();
614 *out++ = prefix;
615 int i = 0;
616 auto it = std::begin(range);
617 auto end = std::end(range);
618 for (; it != end; ++it) {
619 if (i > 0) out = detail::write_delimiter(out);
620 out = detail::write_range_entry<Char>(out, *it);
621 ++i;
622 }
623 *out++ = postfix;
624 return out;
625 }
626 };
627
628 template <typename T, typename Char>
629 struct formatter<
630 T, Char,
631 enable_if_t<
632 detail::is_map<T>::value
633 // Workaround a bug in MSVC 2019 and earlier.
634 #if !FMT_MSC_VER
635 && (is_formattable<detail::value_type<T>, Char>::value ||
636 detail::has_fallback_formatter<detail::value_type<T>, Char>::value)
637 #endif
638 >> {
639 template <typename ParseContext>
640 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
641 return ctx.begin();
642 }
643
644 template <
645 typename FormatContext, typename U,
646 FMT_ENABLE_IF(
647 std::is_same<U, conditional_t<detail::has_const_begin_end<T>::value,
648 const T, T>>::value)>
649 auto format(U& map, FormatContext& ctx) -> decltype(ctx.out()) {
650 auto out = ctx.out();
651 *out++ = '{';
652 int i = 0;
653 for (const auto& item : map) {
654 if (i > 0) out = detail::write_delimiter(out);
655 out = detail::write_range_entry<Char>(out, item.first);
656 *out++ = ':';
657 *out++ = ' ';
658 out = detail::write_range_entry<Char>(out, item.second);
659 ++i;
660 }
661 *out++ = '}';
662 return out;
663 }
664 };
665
666 template <typename Char, typename... T> struct tuple_join_view : detail::view {
667 const std::tuple<T...>& tuple;
668 basic_string_view<Char> sep;
669
670 tuple_join_view(const std::tuple<T...>& t, basic_string_view<Char> s)
671 : tuple(t), sep{s} {}
672 };
673
674 template <typename Char, typename... T>
675 using tuple_arg_join = tuple_join_view<Char, T...>;
676
677 // Define FMT_TUPLE_JOIN_SPECIFIERS to enable experimental format specifiers
678 // support in tuple_join. It is disabled by default because of issues with
679 // the dynamic width and precision.
680 #ifndef FMT_TUPLE_JOIN_SPECIFIERS
681 # define FMT_TUPLE_JOIN_SPECIFIERS 0
682 #endif
683
684 template <typename Char, typename... T>
685 struct formatter<tuple_join_view<Char, T...>, Char> {
686 template <typename ParseContext>
687 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
688 return do_parse(ctx, std::integral_constant<size_t, sizeof...(T)>());
689 }
690
691 template <typename FormatContext>
692 auto format(const tuple_join_view<Char, T...>& value,
693 FormatContext& ctx) const -> typename FormatContext::iterator {
694 return do_format(value, ctx,
695 std::integral_constant<size_t, sizeof...(T)>());
696 }
697
698 private:
699 std::tuple<formatter<typename std::decay<T>::type, Char>...> formatters_;
700
701 template <typename ParseContext>
702 FMT_CONSTEXPR auto do_parse(ParseContext& ctx,
703 std::integral_constant<size_t, 0>)
704 -> decltype(ctx.begin()) {
705 return ctx.begin();
706 }
707
708 template <typename ParseContext, size_t N>
709 FMT_CONSTEXPR auto do_parse(ParseContext& ctx,
710 std::integral_constant<size_t, N>)
711 -> decltype(ctx.begin()) {
712 auto end = ctx.begin();
713 #if FMT_TUPLE_JOIN_SPECIFIERS
714 end = std::get<sizeof...(T) - N>(formatters_).parse(ctx);
715 if (N > 1) {
716 auto end1 = do_parse(ctx, std::integral_constant<size_t, N - 1>());
717 if (end != end1)
718 FMT_THROW(format_error("incompatible format specs for tuple elements"));
719 }
720 #endif
721 return end;
722 }
723
724 template <typename FormatContext>
725 auto do_format(const tuple_join_view<Char, T...>&, FormatContext& ctx,
726 std::integral_constant<size_t, 0>) const ->
727 typename FormatContext::iterator {
728 return ctx.out();
729 }
730
731 template <typename FormatContext, size_t N>
732 auto do_format(const tuple_join_view<Char, T...>& value, FormatContext& ctx,
733 std::integral_constant<size_t, N>) const ->
734 typename FormatContext::iterator {
735 auto out = std::get<sizeof...(T) - N>(formatters_)
736 .format(std::get<sizeof...(T) - N>(value.tuple), ctx);
737 if (N > 1) {
738 out = std::copy(value.sep.begin(), value.sep.end(), out);
739 ctx.advance_to(out);
740 return do_format(value, ctx, std::integral_constant<size_t, N - 1>());
741 }
742 return out;
743 }
744 };
745
746 FMT_MODULE_EXPORT_BEGIN
747
748 /**
749 \rst
750 Returns an object that formats `tuple` with elements separated by `sep`.
751
752 **Example**::
753
754 std::tuple<int, char> t = {1, 'a'};
755 fmt::print("{}", fmt::join(t, ", "));
756 // Output: "1, a"
757 \endrst
758 */
759 template <typename... T>
760 FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple, string_view sep)
761 -> tuple_join_view<char, T...> {
762 return {tuple, sep};
763 }
764
765 template <typename... T>
766 FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple,
767 basic_string_view<wchar_t> sep)
768 -> tuple_join_view<wchar_t, T...> {
769 return {tuple, sep};
770 }
771
772 /**
773 \rst
774 Returns an object that formats `initializer_list` with elements separated by
775 `sep`.
776
777 **Example**::
778
779 fmt::print("{}", fmt::join({1, 2, 3}, ", "));
780 // Output: "1, 2, 3"
781 \endrst
782 */
783 template <typename T>
784 auto join(std::initializer_list<T> list, string_view sep)
785 -> join_view<const T*, const T*> {
786 return join(std::begin(list), std::end(list), sep);
787 }
788
789 FMT_MODULE_EXPORT_END
790 FMT_END_NAMESPACE
791
792 #endif // FMT_RANGES_H_
+0
-236
source/misc/embedded_libs/fmt-8.1.1/include/fmt/xchar.h less more
0 // Formatting library for C++ - optional wchar_t and exotic character support
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_XCHAR_H_
8 #define FMT_XCHAR_H_
9
10 #include <cwchar>
11 #include <tuple>
12
13 #include "format.h"
14
15 FMT_BEGIN_NAMESPACE
16 namespace detail {
17 template <typename T>
18 using is_exotic_char = bool_constant<!std::is_same<T, char>::value>;
19 }
20
21 FMT_MODULE_EXPORT_BEGIN
22
23 using wstring_view = basic_string_view<wchar_t>;
24 using wformat_parse_context = basic_format_parse_context<wchar_t>;
25 using wformat_context = buffer_context<wchar_t>;
26 using wformat_args = basic_format_args<wformat_context>;
27 using wmemory_buffer = basic_memory_buffer<wchar_t>;
28
29 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
30 // Workaround broken conversion on older gcc.
31 template <typename... Args> using wformat_string = wstring_view;
32 #else
33 template <typename... Args>
34 using wformat_string = basic_format_string<wchar_t, type_identity_t<Args>...>;
35 #endif
36
37 template <> struct is_char<wchar_t> : std::true_type {};
38 template <> struct is_char<detail::char8_type> : std::true_type {};
39 template <> struct is_char<char16_t> : std::true_type {};
40 template <> struct is_char<char32_t> : std::true_type {};
41
42 template <typename... Args>
43 constexpr format_arg_store<wformat_context, Args...> make_wformat_args(
44 const Args&... args) {
45 return {args...};
46 }
47
48 inline namespace literals {
49 constexpr auto operator"" _format(const wchar_t* s, size_t n)
50 -> detail::udl_formatter<wchar_t> {
51 return {{s, n}};
52 }
53
54 #if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
55 constexpr detail::udl_arg<wchar_t> operator"" _a(const wchar_t* s, size_t) {
56 return {s};
57 }
58 #endif
59 } // namespace literals
60
61 template <typename It, typename Sentinel>
62 auto join(It begin, Sentinel end, wstring_view sep)
63 -> join_view<It, Sentinel, wchar_t> {
64 return {begin, end, sep};
65 }
66
67 template <typename Range>
68 auto join(Range&& range, wstring_view sep)
69 -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>,
70 wchar_t> {
71 return join(std::begin(range), std::end(range), sep);
72 }
73
74 template <typename T>
75 auto join(std::initializer_list<T> list, wstring_view sep)
76 -> join_view<const T*, const T*, wchar_t> {
77 return join(std::begin(list), std::end(list), sep);
78 }
79
80 template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
81 auto vformat(basic_string_view<Char> format_str,
82 basic_format_args<buffer_context<type_identity_t<Char>>> args)
83 -> std::basic_string<Char> {
84 basic_memory_buffer<Char> buffer;
85 detail::vformat_to(buffer, format_str, args);
86 return to_string(buffer);
87 }
88
89 // Pass char_t as a default template parameter instead of using
90 // std::basic_string<char_t<S>> to reduce the symbol size.
91 template <typename S, typename... Args, typename Char = char_t<S>,
92 FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
93 auto format(const S& format_str, Args&&... args) -> std::basic_string<Char> {
94 const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
95 return vformat(to_string_view(format_str), vargs);
96 }
97
98 template <typename Locale, typename S, typename Char = char_t<S>,
99 FMT_ENABLE_IF(detail::is_locale<Locale>::value&&
100 detail::is_exotic_char<Char>::value)>
101 inline auto vformat(
102 const Locale& loc, const S& format_str,
103 basic_format_args<buffer_context<type_identity_t<Char>>> args)
104 -> std::basic_string<Char> {
105 return detail::vformat(loc, to_string_view(format_str), args);
106 }
107
108 template <typename Locale, typename S, typename... Args,
109 typename Char = char_t<S>,
110 FMT_ENABLE_IF(detail::is_locale<Locale>::value&&
111 detail::is_exotic_char<Char>::value)>
112 inline auto format(const Locale& loc, const S& format_str, Args&&... args)
113 -> std::basic_string<Char> {
114 return detail::vformat(loc, to_string_view(format_str),
115 fmt::make_args_checked<Args...>(format_str, args...));
116 }
117
118 template <typename OutputIt, typename S, typename Char = char_t<S>,
119 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
120 detail::is_exotic_char<Char>::value)>
121 auto vformat_to(OutputIt out, const S& format_str,
122 basic_format_args<buffer_context<type_identity_t<Char>>> args)
123 -> OutputIt {
124 auto&& buf = detail::get_buffer<Char>(out);
125 detail::vformat_to(buf, to_string_view(format_str), args);
126 return detail::get_iterator(buf);
127 }
128
129 template <typename OutputIt, typename S, typename... Args,
130 typename Char = char_t<S>,
131 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
132 detail::is_exotic_char<Char>::value)>
133 inline auto format_to(OutputIt out, const S& fmt, Args&&... args) -> OutputIt {
134 const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
135 return vformat_to(out, to_string_view(fmt), vargs);
136 }
137
138 template <typename S, typename... Args, typename Char, size_t SIZE,
139 typename Allocator, FMT_ENABLE_IF(detail::is_string<S>::value)>
140 FMT_DEPRECATED auto format_to(basic_memory_buffer<Char, SIZE, Allocator>& buf,
141 const S& format_str, Args&&... args) ->
142 typename buffer_context<Char>::iterator {
143 const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
144 detail::vformat_to(buf, to_string_view(format_str), vargs, {});
145 return detail::buffer_appender<Char>(buf);
146 }
147
148 template <typename Locale, typename S, typename OutputIt, typename... Args,
149 typename Char = char_t<S>,
150 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
151 detail::is_locale<Locale>::value&&
152 detail::is_exotic_char<Char>::value)>
153 inline auto vformat_to(
154 OutputIt out, const Locale& loc, const S& format_str,
155 basic_format_args<buffer_context<type_identity_t<Char>>> args) -> OutputIt {
156 auto&& buf = detail::get_buffer<Char>(out);
157 vformat_to(buf, to_string_view(format_str), args, detail::locale_ref(loc));
158 return detail::get_iterator(buf);
159 }
160
161 template <
162 typename OutputIt, typename Locale, typename S, typename... Args,
163 typename Char = char_t<S>,
164 bool enable = detail::is_output_iterator<OutputIt, Char>::value&&
165 detail::is_locale<Locale>::value&& detail::is_exotic_char<Char>::value>
166 inline auto format_to(OutputIt out, const Locale& loc, const S& format_str,
167 Args&&... args) ->
168 typename std::enable_if<enable, OutputIt>::type {
169 const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
170 return vformat_to(out, loc, to_string_view(format_str), vargs);
171 }
172
173 template <typename OutputIt, typename Char, typename... Args,
174 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
175 detail::is_exotic_char<Char>::value)>
176 inline auto vformat_to_n(
177 OutputIt out, size_t n, basic_string_view<Char> format_str,
178 basic_format_args<buffer_context<type_identity_t<Char>>> args)
179 -> format_to_n_result<OutputIt> {
180 detail::iterator_buffer<OutputIt, Char, detail::fixed_buffer_traits> buf(out,
181 n);
182 detail::vformat_to(buf, format_str, args);
183 return {buf.out(), buf.count()};
184 }
185
186 template <typename OutputIt, typename S, typename... Args,
187 typename Char = char_t<S>,
188 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
189 detail::is_exotic_char<Char>::value)>
190 inline auto format_to_n(OutputIt out, size_t n, const S& fmt,
191 const Args&... args) -> format_to_n_result<OutputIt> {
192 const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
193 return vformat_to_n(out, n, to_string_view(fmt), vargs);
194 }
195
196 template <typename S, typename... Args, typename Char = char_t<S>,
197 FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
198 inline auto formatted_size(const S& fmt, Args&&... args) -> size_t {
199 detail::counting_buffer<Char> buf;
200 const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
201 detail::vformat_to(buf, to_string_view(fmt), vargs);
202 return buf.count();
203 }
204
205 inline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) {
206 wmemory_buffer buffer;
207 detail::vformat_to(buffer, fmt, args);
208 buffer.push_back(L'\0');
209 if (std::fputws(buffer.data(), f) == -1)
210 FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
211 }
212
213 inline void vprint(wstring_view fmt, wformat_args args) {
214 vprint(stdout, fmt, args);
215 }
216
217 template <typename... T>
218 void print(std::FILE* f, wformat_string<T...> fmt, T&&... args) {
219 return vprint(f, wstring_view(fmt), fmt::make_wformat_args(args...));
220 }
221
222 template <typename... T> void print(wformat_string<T...> fmt, T&&... args) {
223 return vprint(wstring_view(fmt), fmt::make_wformat_args(args...));
224 }
225
226 /**
227 Converts *value* to ``std::wstring`` using the default format for type *T*.
228 */
229 template <typename T> inline auto to_wstring(const T& value) -> std::wstring {
230 return format(FMT_STRING(L"{}"), value);
231 }
232 FMT_MODULE_EXPORT_END
233 FMT_END_NAMESPACE
234
235 #endif // FMT_XCHAR_H_
+0
-99
source/misc/embedded_libs/fmt-8.1.1/src/fmt.cc less more
0 module;
1 #ifndef __cpp_modules
2 # error Module not supported.
3 #endif
4
5 // put all implementation-provided headers into the global module fragment
6 // to prevent attachment to this module
7 #if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER)
8 # define _CRT_SECURE_NO_WARNINGS
9 #endif
10 #if !defined(WIN32_LEAN_AND_MEAN) && defined(_WIN32)
11 # define WIN32_LEAN_AND_MEAN
12 #endif
13
14 #include <algorithm>
15 #include <cctype>
16 #include <cerrno>
17 #include <chrono>
18 #include <climits>
19 #include <clocale>
20 #include <cmath>
21 #include <cstdarg>
22 #include <cstddef>
23 #include <cstdint>
24 #include <cstdio>
25 #include <cstdlib>
26 #include <cstring>
27 #include <ctime>
28 #include <cwchar>
29 #include <exception>
30 #include <functional>
31 #include <iterator>
32 #include <limits>
33 #include <locale>
34 #include <memory>
35 #include <ostream>
36 #include <sstream>
37 #include <stdexcept>
38 #include <string>
39 #include <string_view>
40 #include <system_error>
41 #include <type_traits>
42 #include <utility>
43 #include <vector>
44
45 #if _MSC_VER
46 # include <intrin.h>
47 #endif
48 #if defined __APPLE__ || defined(__FreeBSD__)
49 # include <xlocale.h>
50 #endif
51 #if __has_include(<winapifamily.h>)
52 # include <winapifamily.h>
53 #endif
54 #if (__has_include(<fcntl.h>) || defined(__APPLE__) || \
55 defined(__linux__)) && \
56 (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
57 # include <fcntl.h>
58 # include <sys/stat.h>
59 # include <sys/types.h>
60 # ifndef _WIN32
61 # include <unistd.h>
62 # else
63 # include <io.h>
64 # endif
65 #endif
66 #ifdef _WIN32
67 # include <windows.h>
68 #endif
69
70 export module fmt;
71
72 #define FMT_MODULE_EXPORT export
73 #define FMT_MODULE_EXPORT_BEGIN export {
74 #define FMT_MODULE_EXPORT_END }
75 #define FMT_BEGIN_DETAIL_NAMESPACE \
76 } \
77 namespace detail {
78 #define FMT_END_DETAIL_NAMESPACE \
79 } \
80 export {
81 // all library-provided declarations and definitions
82 // must be in the module purview to be exported
83 #include "fmt/args.h"
84 #include "fmt/chrono.h"
85 #include "fmt/color.h"
86 #include "fmt/compile.h"
87 #include "fmt/format.h"
88 #include "fmt/os.h"
89 #include "fmt/printf.h"
90 #include "fmt/xchar.h"
91
92 // gcc doesn't yet implement private module fragments
93 #if !FMT_GCC_VERSION
94 module : private;
95 #endif
96
97 #include "format.cc"
98 #include "os.cc"
+0
-124
source/misc/embedded_libs/fmt-8.1.1/src/format.cc less more
0 // Formatting library for C++
1 //
2 // Copyright (c) 2012 - 2016, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/format-inl.h"
8
9 FMT_BEGIN_NAMESPACE
10 namespace detail {
11
12 // DEPRECATED!
13 template <typename T = void> struct basic_data {
14 FMT_API static constexpr const char digits[100][2] = {
15 {'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'}, {'0', '5'},
16 {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'}, {'1', '0'}, {'1', '1'},
17 {'1', '2'}, {'1', '3'}, {'1', '4'}, {'1', '5'}, {'1', '6'}, {'1', '7'},
18 {'1', '8'}, {'1', '9'}, {'2', '0'}, {'2', '1'}, {'2', '2'}, {'2', '3'},
19 {'2', '4'}, {'2', '5'}, {'2', '6'}, {'2', '7'}, {'2', '8'}, {'2', '9'},
20 {'3', '0'}, {'3', '1'}, {'3', '2'}, {'3', '3'}, {'3', '4'}, {'3', '5'},
21 {'3', '6'}, {'3', '7'}, {'3', '8'}, {'3', '9'}, {'4', '0'}, {'4', '1'},
22 {'4', '2'}, {'4', '3'}, {'4', '4'}, {'4', '5'}, {'4', '6'}, {'4', '7'},
23 {'4', '8'}, {'4', '9'}, {'5', '0'}, {'5', '1'}, {'5', '2'}, {'5', '3'},
24 {'5', '4'}, {'5', '5'}, {'5', '6'}, {'5', '7'}, {'5', '8'}, {'5', '9'},
25 {'6', '0'}, {'6', '1'}, {'6', '2'}, {'6', '3'}, {'6', '4'}, {'6', '5'},
26 {'6', '6'}, {'6', '7'}, {'6', '8'}, {'6', '9'}, {'7', '0'}, {'7', '1'},
27 {'7', '2'}, {'7', '3'}, {'7', '4'}, {'7', '5'}, {'7', '6'}, {'7', '7'},
28 {'7', '8'}, {'7', '9'}, {'8', '0'}, {'8', '1'}, {'8', '2'}, {'8', '3'},
29 {'8', '4'}, {'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'},
30 {'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'}, {'9', '5'},
31 {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'}};
32 FMT_API static constexpr const char hex_digits[] = "0123456789abcdef";
33 FMT_API static constexpr const char signs[4] = {0, '-', '+', ' '};
34 FMT_API static constexpr const char left_padding_shifts[5] = {31, 31, 0, 1,
35 0};
36 FMT_API static constexpr const char right_padding_shifts[5] = {0, 31, 0, 1,
37 0};
38 FMT_API static constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+',
39 0x1000000u | ' '};
40 };
41
42 #ifdef FMT_SHARED
43 // Required for -flto, -fivisibility=hidden and -shared to work
44 extern template struct basic_data<void>;
45 #endif
46
47 #if __cplusplus < 201703L
48 // DEPRECATED! These are here only for ABI compatiblity.
49 template <typename T> constexpr const char basic_data<T>::digits[][2];
50 template <typename T> constexpr const char basic_data<T>::hex_digits[];
51 template <typename T> constexpr const char basic_data<T>::signs[];
52 template <typename T> constexpr const char basic_data<T>::left_padding_shifts[];
53 template <typename T>
54 constexpr const char basic_data<T>::right_padding_shifts[];
55 template <typename T> constexpr const unsigned basic_data<T>::prefixes[];
56 #endif
57
58 template <typename T>
59 int format_float(char* buf, std::size_t size, const char* format, int precision,
60 T value) {
61 #ifdef FMT_FUZZ
62 if (precision > 100000)
63 throw std::runtime_error(
64 "fuzz mode - avoid large allocation inside snprintf");
65 #endif
66 // Suppress the warning about nonliteral format string.
67 int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF;
68 return precision < 0 ? snprintf_ptr(buf, size, format, value)
69 : snprintf_ptr(buf, size, format, precision, value);
70 }
71
72 template FMT_API dragonbox::decimal_fp<float> dragonbox::to_decimal(float x)
73 FMT_NOEXCEPT;
74 template FMT_API dragonbox::decimal_fp<double> dragonbox::to_decimal(double x)
75 FMT_NOEXCEPT;
76 } // namespace detail
77
78 // Workaround a bug in MSVC2013 that prevents instantiation of format_float.
79 int (*instantiate_format_float)(double, int, detail::float_specs,
80 detail::buffer<char>&) = detail::format_float;
81
82 #ifndef FMT_STATIC_THOUSANDS_SEPARATOR
83 template FMT_API detail::locale_ref::locale_ref(const std::locale& loc);
84 template FMT_API std::locale detail::locale_ref::get<std::locale>() const;
85 #endif
86
87 // Explicit instantiations for char.
88
89 template FMT_API auto detail::thousands_sep_impl(locale_ref)
90 -> thousands_sep_result<char>;
91 template FMT_API char detail::decimal_point_impl(locale_ref);
92
93 template FMT_API void detail::buffer<char>::append(const char*, const char*);
94
95 // DEPRECATED!
96 // There is no correspondent extern template in format.h because of
97 // incompatibility between clang and gcc (#2377).
98 template FMT_API void detail::vformat_to(
99 detail::buffer<char>&, string_view,
100 basic_format_args<FMT_BUFFER_CONTEXT(char)>, detail::locale_ref);
101
102 template FMT_API int detail::snprintf_float(double, int, detail::float_specs,
103 detail::buffer<char>&);
104 template FMT_API int detail::snprintf_float(long double, int,
105 detail::float_specs,
106 detail::buffer<char>&);
107 template FMT_API int detail::format_float(double, int, detail::float_specs,
108 detail::buffer<char>&);
109 template FMT_API int detail::format_float(long double, int, detail::float_specs,
110 detail::buffer<char>&);
111
112 // Explicit instantiations for wchar_t.
113
114 template FMT_API auto detail::thousands_sep_impl(locale_ref)
115 -> thousands_sep_result<wchar_t>;
116 template FMT_API wchar_t detail::decimal_point_impl(locale_ref);
117
118 template FMT_API void detail::buffer<wchar_t>::append(const wchar_t*,
119 const wchar_t*);
120
121 template struct detail::basic_data<void>;
122
123 FMT_END_NAMESPACE
+0
-361
source/misc/embedded_libs/fmt-8.1.1/src/os.cc less more
0 // Formatting library for C++ - optional OS-specific functionality
1 //
2 // Copyright (c) 2012 - 2016, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 // Disable bogus MSVC warnings.
8 #if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER)
9 # define _CRT_SECURE_NO_WARNINGS
10 #endif
11
12 #include "fmt/os.h"
13
14 #include <climits>
15
16 #if FMT_USE_FCNTL
17 # include <sys/stat.h>
18 # include <sys/types.h>
19
20 # ifndef _WIN32
21 # include <unistd.h>
22 # else
23 # ifndef WIN32_LEAN_AND_MEAN
24 # define WIN32_LEAN_AND_MEAN
25 # endif
26 # include <io.h>
27
28 # ifndef S_IRUSR
29 # define S_IRUSR _S_IREAD
30 # endif
31 # ifndef S_IWUSR
32 # define S_IWUSR _S_IWRITE
33 # endif
34 # ifndef S_IRGRP
35 # define S_IRGRP 0
36 # endif
37 # ifndef S_IROTH
38 # define S_IROTH 0
39 # endif
40 # endif // _WIN32
41 #endif // FMT_USE_FCNTL
42
43 #ifdef _WIN32
44 # include <windows.h>
45 #endif
46
47 #ifdef fileno
48 # undef fileno
49 #endif
50
51 namespace {
52 #ifdef _WIN32
53 // Return type of read and write functions.
54 using rwresult = int;
55
56 // On Windows the count argument to read and write is unsigned, so convert
57 // it from size_t preventing integer overflow.
58 inline unsigned convert_rwcount(std::size_t count) {
59 return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
60 }
61 #elif FMT_USE_FCNTL
62 // Return type of read and write functions.
63 using rwresult = ssize_t;
64
65 inline std::size_t convert_rwcount(std::size_t count) { return count; }
66 #endif
67 } // namespace
68
69 FMT_BEGIN_NAMESPACE
70
71 #ifdef _WIN32
72 detail::utf16_to_utf8::utf16_to_utf8(basic_string_view<wchar_t> s) {
73 if (int error_code = convert(s)) {
74 FMT_THROW(windows_error(error_code,
75 "cannot convert string from UTF-16 to UTF-8"));
76 }
77 }
78
79 int detail::utf16_to_utf8::convert(basic_string_view<wchar_t> s) {
80 if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER;
81 int s_size = static_cast<int>(s.size());
82 if (s_size == 0) {
83 // WideCharToMultiByte does not support zero length, handle separately.
84 buffer_.resize(1);
85 buffer_[0] = 0;
86 return 0;
87 }
88
89 int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0,
90 nullptr, nullptr);
91 if (length == 0) return GetLastError();
92 buffer_.resize(length + 1);
93 length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0],
94 length, nullptr, nullptr);
95 if (length == 0) return GetLastError();
96 buffer_[length] = 0;
97 return 0;
98 }
99
100 namespace detail {
101
102 class system_message {
103 system_message(const system_message&) = delete;
104 void operator=(const system_message&) = delete;
105
106 unsigned long result_;
107 wchar_t* message_;
108
109 static bool is_whitespace(wchar_t c) FMT_NOEXCEPT {
110 return c == L' ' || c == L'\n' || c == L'\r' || c == L'\t' || c == L'\0';
111 }
112
113 public:
114 explicit system_message(unsigned long error_code)
115 : result_(0), message_(nullptr) {
116 result_ = FormatMessageW(
117 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
118 FORMAT_MESSAGE_IGNORE_INSERTS,
119 nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
120 reinterpret_cast<wchar_t*>(&message_), 0, nullptr);
121 if (result_ != 0) {
122 while (result_ != 0 && is_whitespace(message_[result_ - 1])) {
123 --result_;
124 }
125 }
126 }
127 ~system_message() { LocalFree(message_); }
128 explicit operator bool() const FMT_NOEXCEPT { return result_ != 0; }
129 operator basic_string_view<wchar_t>() const FMT_NOEXCEPT {
130 return basic_string_view<wchar_t>(message_, result_);
131 }
132 };
133
134 class utf8_system_category final : public std::error_category {
135 public:
136 const char* name() const FMT_NOEXCEPT override { return "system"; }
137 std::string message(int error_code) const override {
138 system_message msg(error_code);
139 if (msg) {
140 utf16_to_utf8 utf8_message;
141 if (utf8_message.convert(msg) == ERROR_SUCCESS) {
142 return utf8_message.str();
143 }
144 }
145 return "unknown error";
146 }
147 };
148
149 } // namespace detail
150
151 FMT_API const std::error_category& system_category() FMT_NOEXCEPT {
152 static const detail::utf8_system_category category;
153 return category;
154 }
155
156 std::system_error vwindows_error(int err_code, string_view format_str,
157 format_args args) {
158 auto ec = std::error_code(err_code, system_category());
159 return std::system_error(ec, vformat(format_str, args));
160 }
161
162 void detail::format_windows_error(detail::buffer<char>& out, int error_code,
163 const char* message) FMT_NOEXCEPT {
164 FMT_TRY {
165 system_message msg(error_code);
166 if (msg) {
167 utf16_to_utf8 utf8_message;
168 if (utf8_message.convert(msg) == ERROR_SUCCESS) {
169 format_to(buffer_appender<char>(out), "{}: {}", message, utf8_message);
170 return;
171 }
172 }
173 }
174 FMT_CATCH(...) {}
175 format_error_code(out, error_code, message);
176 }
177
178 void report_windows_error(int error_code, const char* message) FMT_NOEXCEPT {
179 report_error(detail::format_windows_error, error_code, message);
180 }
181 #endif // _WIN32
182
183 buffered_file::~buffered_file() FMT_NOEXCEPT {
184 if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
185 report_system_error(errno, "cannot close file");
186 }
187
188 buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
189 FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())),
190 nullptr);
191 if (!file_)
192 FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
193 }
194
195 void buffered_file::close() {
196 if (!file_) return;
197 int result = FMT_SYSTEM(fclose(file_));
198 file_ = nullptr;
199 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
200 }
201
202 // A macro used to prevent expansion of fileno on broken versions of MinGW.
203 #define FMT_ARGS
204
205 int buffered_file::fileno() const {
206 int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
207 if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
208 return fd;
209 }
210
211 #if FMT_USE_FCNTL
212 file::file(cstring_view path, int oflag) {
213 # ifdef _WIN32
214 using mode_t = int;
215 # endif
216 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
217 # if defined(_WIN32) && !defined(__MINGW32__)
218 fd_ = -1;
219 FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
220 # else
221 FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
222 # endif
223 if (fd_ == -1)
224 FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
225 }
226
227 file::~file() FMT_NOEXCEPT {
228 // Don't retry close in case of EINTR!
229 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
230 if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
231 report_system_error(errno, "cannot close file");
232 }
233
234 void file::close() {
235 if (fd_ == -1) return;
236 // Don't retry close in case of EINTR!
237 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
238 int result = FMT_POSIX_CALL(close(fd_));
239 fd_ = -1;
240 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
241 }
242
243 long long file::size() const {
244 # ifdef _WIN32
245 // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
246 // is less than 0x0500 as is the case with some default MinGW builds.
247 // Both functions support large file sizes.
248 DWORD size_upper = 0;
249 HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
250 DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
251 if (size_lower == INVALID_FILE_SIZE) {
252 DWORD error = GetLastError();
253 if (error != NO_ERROR)
254 FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
255 }
256 unsigned long long long_size = size_upper;
257 return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
258 # else
259 using Stat = struct stat;
260 Stat file_stat = Stat();
261 if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
262 FMT_THROW(system_error(errno, "cannot get file attributes"));
263 static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
264 "return type of file::size is not large enough");
265 return file_stat.st_size;
266 # endif
267 }
268
269 std::size_t file::read(void* buffer, std::size_t count) {
270 rwresult result = 0;
271 FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
272 if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
273 return detail::to_unsigned(result);
274 }
275
276 std::size_t file::write(const void* buffer, std::size_t count) {
277 rwresult result = 0;
278 FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
279 if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
280 return detail::to_unsigned(result);
281 }
282
283 file file::dup(int fd) {
284 // Don't retry as dup doesn't return EINTR.
285 // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
286 int new_fd = FMT_POSIX_CALL(dup(fd));
287 if (new_fd == -1)
288 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
289 return file(new_fd);
290 }
291
292 void file::dup2(int fd) {
293 int result = 0;
294 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
295 if (result == -1) {
296 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
297 fd_, fd));
298 }
299 }
300
301 void file::dup2(int fd, std::error_code& ec) FMT_NOEXCEPT {
302 int result = 0;
303 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
304 if (result == -1) ec = std::error_code(errno, std::generic_category());
305 }
306
307 void file::pipe(file& read_end, file& write_end) {
308 // Close the descriptors first to make sure that assignments don't throw
309 // and there are no leaks.
310 read_end.close();
311 write_end.close();
312 int fds[2] = {};
313 # ifdef _WIN32
314 // Make the default pipe capacity same as on Linux 2.6.11+.
315 enum { DEFAULT_CAPACITY = 65536 };
316 int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
317 # else
318 // Don't retry as the pipe function doesn't return EINTR.
319 // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
320 int result = FMT_POSIX_CALL(pipe(fds));
321 # endif
322 if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
323 // The following assignments don't throw because read_fd and write_fd
324 // are closed.
325 read_end = file(fds[0]);
326 write_end = file(fds[1]);
327 }
328
329 buffered_file file::fdopen(const char* mode) {
330 // Don't retry as fdopen doesn't return EINTR.
331 # if defined(__MINGW32__) && defined(_POSIX_)
332 FILE* f = ::fdopen(fd_, mode);
333 # else
334 FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
335 # endif
336 if (!f)
337 FMT_THROW(
338 system_error(errno, "cannot associate stream with file descriptor"));
339 buffered_file bf(f);
340 fd_ = -1;
341 return bf;
342 }
343
344 long getpagesize() {
345 # ifdef _WIN32
346 SYSTEM_INFO si;
347 GetSystemInfo(&si);
348 return si.dwPageSize;
349 # else
350 long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
351 if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
352 return size;
353 # endif
354 }
355
356 FMT_API void ostream::grow(size_t) {
357 if (this->size() == this->capacity()) flush();
358 }
359 #endif // FMT_USE_FCNTL
360 FMT_END_NAMESPACE
+0
-15
source/misc/embedded_libs/fmt-8.1.1/support/Android.mk less more
0 LOCAL_PATH := $(call my-dir)
1 include $(CLEAR_VARS)
2
3 LOCAL_MODULE := fmt_static
4 LOCAL_MODULE_FILENAME := libfmt
5
6 LOCAL_SRC_FILES := ../src/format.cc
7
8 LOCAL_C_INCLUDES := $(LOCAL_PATH)
9 LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
10
11 LOCAL_CFLAGS += -std=c++11 -fexceptions
12
13 include $(BUILD_STATIC_LIBRARY)
14
+0
-1
source/misc/embedded_libs/fmt-8.1.1/support/AndroidManifest.xml less more
0 <manifest package="net.fmtlib" />
+0
-2061
source/misc/embedded_libs/fmt-8.1.1/support/C++.sublime-syntax less more
0 %YAML 1.2
1 ---
2 # http://www.sublimetext.com/docs/3/syntax.html
3 name: C++ (fmt)
4 comment: I don't think anyone uses .hp. .cp tends to be paired with .h. (I could be wrong. :) -- chris
5 file_extensions:
6 - cpp
7 - cc
8 - cp
9 - cxx
10 - c++
11 - C
12 - h
13 - hh
14 - hpp
15 - hxx
16 - h++
17 - inl
18 - ipp
19 first_line_match: '-\*- C\+\+ -\*-'
20 scope: source.c++
21 variables:
22 identifier: \b[[:alpha:]_][[:alnum:]_]*\b # upper and lowercase
23 macro_identifier: \b[[:upper:]_][[:upper:][:digit:]_]{2,}\b # only uppercase, at least 3 chars
24 path_lookahead: '(?:::\s*)?(?:{{identifier}}\s*::\s*)*(?:template\s+)?{{identifier}}'
25 operator_method_name: '\boperator\s*(?:[-+*/%^&|~!=<>]|[-+*/%^&|=!<>]=|<<=?|>>=?|&&|\|\||\+\+|--|,|->\*?|\(\)|\[\]|""\s*{{identifier}})'
26 casts: 'const_cast|dynamic_cast|reinterpret_cast|static_cast'
27 operator_keywords: 'and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|xor|xor_eq|noexcept'
28 control_keywords: 'break|case|catch|continue|default|do|else|for|goto|if|_Pragma|return|switch|throw|try|while'
29 memory_operators: 'new|delete'
30 basic_types: 'asm|__asm__|auto|bool|_Bool|char|_Complex|double|float|_Imaginary|int|long|short|signed|unsigned|void'
31 before_tag: 'struct|union|enum\s+class|enum\s+struct|enum|class'
32 declspec: '__declspec\(\s*\w+(?:\([^)]+\))?\s*\)'
33 storage_classes: 'static|export|extern|friend|explicit|virtual|register|thread_local'
34 type_qualifier: 'const|constexpr|mutable|typename|volatile'
35 compiler_directive: 'inline|restrict|__restrict__|__restrict'
36 visibility_modifiers: 'private|protected|public'
37 other_keywords: 'typedef|nullptr|{{visibility_modifiers}}|static_assert|sizeof|using|typeid|alignof|alignas|namespace|template'
38 modifiers: '{{storage_classes}}|{{type_qualifier}}|{{compiler_directive}}'
39 non_angle_brackets: '(?=<<|<=)'
40
41 regular: '[^(){}&;*^%=<>-]*'
42 paren_open: (?:\(
43 paren_close: '\))?'
44 generic_open: (?:<
45 generic_close: '>)?'
46 balance_parentheses: '{{regular}}{{paren_open}}{{regular}}{{paren_close}}{{regular}}'
47 generic_lookahead: <{{regular}}{{generic_open}}{{regular}}{{generic_open}}{{regular}}{{generic_close}}\s*{{generic_close}}{{balance_parentheses}}>
48
49 data_structures_forward_decl_lookahead: '(\s+{{macro_identifier}})*\s*(:\s*({{path_lookahead}}|{{visibility_modifiers}}|,|\s|<[^;]*>)+)?;'
50 non_func_keywords: 'if|for|switch|while|decltype|sizeof|__declspec|__attribute__|typeid|alignof|alignas|static_assert'
51
52 format_spec: |-
53 (?x:
54 (?:.? [<>=^])? # fill align
55 [ +-]? # sign
56 \#? # alternate form
57 # technically, octal and hexadecimal integers are also supported as 'width', but rarely used
58 \d* # width
59 ,? # thousands separator
60 (?:\.\d+)? # precision
61 [bcdeEfFgGnosxX%]? # type
62 )
63
64 contexts:
65 main:
66 - include: preprocessor-global
67 - include: global
68
69 #############################################################################
70 # Reusable contexts
71 #
72 # The follow contexts are currently constructed to be reused in the
73 # Objetive-C++ syntax. They are specifically constructed to not push into
74 # sub-contexts, which ensures that Objective-C++ code isn't accidentally
75 # lexed as plain C++.
76 #
77 # The "unique-*" contexts are additions that C++ makes over C, and thus can
78 # be directly reused in Objective-C++ along with contexts from Objective-C
79 # and C.
80 #############################################################################
81
82 unique-late-expressions:
83 # This is highlighted after all of the other control keywords
84 # to allow operator overloading to be lexed properly
85 - match: \boperator\b
86 scope: keyword.control.c++
87
88 unique-modifiers:
89 - match: \b({{modifiers}})\b
90 scope: storage.modifier.c++
91
92 unique-variables:
93 - match: \bthis\b
94 scope: variable.language.c++
95 # common C++ instance var naming idiom -- fMemberName
96 - match: '\b(f|m)[[:upper:]]\w*\b'
97 scope: variable.other.readwrite.member.c++
98 # common C++ instance var naming idiom -- m_member_name
99 - match: '\bm_[[:alnum:]_]+\b'
100 scope: variable.other.readwrite.member.c++
101
102 unique-constants:
103 - match: \bnullptr\b
104 scope: constant.language.c++
105
106 unique-keywords:
107 - match: \busing\b
108 scope: keyword.control.c++
109 - match: \bbreak\b
110 scope: keyword.control.flow.break.c++
111 - match: \bcontinue\b
112 scope: keyword.control.flow.continue.c++
113 - match: \bgoto\b
114 scope: keyword.control.flow.goto.c++
115 - match: \breturn\b
116 scope: keyword.control.flow.return.c++
117 - match: \bthrow\b
118 scope: keyword.control.flow.throw.c++
119 - match: \b({{control_keywords}})\b
120 scope: keyword.control.c++
121 - match: '\bdelete\b(\s*\[\])?|\bnew\b(?!])'
122 scope: keyword.control.c++
123 - match: \b({{operator_keywords}})\b
124 scope: keyword.operator.word.c++
125
126 unique-types:
127 - match: \b(char16_t|char32_t|wchar_t|nullptr_t)\b
128 scope: storage.type.c++
129 - match: \bclass\b
130 scope: storage.type.c++
131
132 unique-strings:
133 - match: '((?:L|u8|u|U)?R)("([^\(\)\\ ]{0,16})\()'
134 captures:
135 1: storage.type.string.c++
136 2: punctuation.definition.string.begin.c++
137 push:
138 - meta_scope: string.quoted.double.c++
139 - match: '\)\3"'
140 scope: punctuation.definition.string.end.c++
141 pop: true
142 - match: '\{\{|\}\}'
143 scope: constant.character.escape.c++
144 - include: formatting-syntax
145
146 unique-numbers:
147 - match: |-
148 (?x)
149 (?:
150 # floats
151 (?:
152 (?:\b\d(?:[\d']*\d)?\.\d(?:[\d']*\d)?|\B\.\d(?:[\d']*\d)?)(?:[Ee][+-]?\d(?:[\d']*\d)?)?(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b
153 |
154 (?:\b\d(?:[\d']*\d)?\.)(?:\B|(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))\b|(?:[Ee][+-]?\d(?:[\d']*\d)?)(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b)
155 |
156 \b\d(?:[\d']*\d)?(?:[Ee][+-]?\d(?:[\d']*\d)?)(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b
157 )
158 |
159 # ints
160 \b(?:
161 (?:
162 # dec
163 [1-9](?:[\d']*\d)?
164 |
165 # oct
166 0(?:[0-7']*[0-7])?
167 |
168 # hex
169 0[Xx][\da-fA-F](?:[\da-fA-F']*[\da-fA-F])?
170 |
171 # bin
172 0[Bb][01](?:[01']*[01])?
173 )
174 # int suffixes
175 (?:(?:l{1,2}|L{1,2})[uU]?|[uU](?:l{0,2}|L{0,2})|(?:i[fl]?|h|min|[mun]?s|_\w*))?)\b
176 )
177 (?!\.) # Number must not be followed by a decimal point
178 scope: constant.numeric.c++
179
180 identifiers:
181 - match: '{{identifier}}\s*(::)\s*'
182 captures:
183 1: punctuation.accessor.c++
184 - match: '(?:(::)\s*)?{{identifier}}'
185 captures:
186 1: punctuation.accessor.c++
187
188 function-specifiers:
189 - match: \b(const|final|noexcept|override)\b
190 scope: storage.modifier.c++
191
192 #############################################################################
193 # The following are C++-specific contexts that should not be reused. This is
194 # because they push into subcontexts and use variables that are C++-specific.
195 #############################################################################
196
197 ## Common context layout
198
199 global:
200 - match: '(?=\btemplate\b)'
201 push:
202 - include: template
203 - match: (?=\S)
204 set: global-modifier
205 - include: namespace
206 - include: keywords-angle-brackets
207 - match: '(?={{path_lookahead}}\s*<)'
208 push: global-modifier
209 # Take care of comments just before a function definition.
210 - match: /\*
211 scope: punctuation.definition.comment.c
212 push:
213 - - match: \s*(?=\w)
214 set: global-modifier
215 - match: ""
216 pop: true
217 - - meta_scope: comment.block.c
218 - match: \*/
219 scope: punctuation.definition.comment.c
220 pop: true
221 - include: early-expressions
222 - match: ^\s*\b(extern)(?=\s+"C(\+\+)?")
223 scope: storage.modifier.c++
224 push:
225 - include: comments
226 - include: strings
227 - match: '\{'
228 scope: punctuation.section.block.begin.c++
229 set:
230 - meta_scope: meta.extern-c.c++
231 - match: '^\s*(#\s*ifdef)\s*__cplusplus\s*'
232 scope: meta.preprocessor.c++
233 captures:
234 1: keyword.control.import.c++
235 set:
236 - match: '\}'
237 scope: punctuation.section.block.end.c++
238 pop: true
239 - include: preprocessor-global
240 - include: global
241 - match: '\}'
242 scope: punctuation.section.block.end.c++
243 pop: true
244 - include: preprocessor-global
245 - include: global
246 - match: (?=\S)
247 set: global-modifier
248 - match: ^\s*(?=\w)
249 push: global-modifier
250 - include: late-expressions
251
252 statements:
253 - include: preprocessor-statements
254 - include: scope:source.c#label
255 - include: expressions
256
257 expressions:
258 - include: early-expressions
259 - include: late-expressions
260
261 early-expressions:
262 - include: early-expressions-before-generic-type
263 - include: generic-type
264 - include: early-expressions-after-generic-type
265
266 early-expressions-before-generic-type:
267 - include: preprocessor-expressions
268 - include: comments
269 - include: case-default
270 - include: typedef
271 - include: keywords-angle-brackets
272 - include: keywords-parens
273 - include: keywords
274 - include: numbers
275 # Prevent a '<' from getting scoped as the start of another template
276 # parameter list, if in reality a less-than-or-equals sign is meant.
277 - match: <=
278 scope: keyword.operator.comparison.c
279
280 early-expressions-after-generic-type:
281 - include: members-arrow
282 - include: operators
283 - include: members-dot
284 - include: strings
285 - include: parens
286 - include: brackets
287 - include: block
288 - include: variables
289 - include: constants
290 - match: ','
291 scope: punctuation.separator.c++
292 - match: '\)|\}'
293 scope: invalid.illegal.stray-bracket-end.c++
294
295 expressions-minus-generic-type:
296 - include: early-expressions-before-generic-type
297 - include: angle-brackets
298 - include: early-expressions-after-generic-type
299 - include: late-expressions
300
301 expressions-minus-generic-type-function-call:
302 - include: early-expressions-before-generic-type
303 - include: angle-brackets
304 - include: early-expressions-after-generic-type
305 - include: late-expressions-before-function-call
306 - include: identifiers
307 - match: ';'
308 scope: punctuation.terminator.c++
309
310 late-expressions:
311 - include: late-expressions-before-function-call
312 - include: function-call
313 - include: identifiers
314 - match: ';'
315 scope: punctuation.terminator.c++
316
317 late-expressions-before-function-call:
318 - include: unique-late-expressions
319 - include: modifiers-parens
320 - include: modifiers
321 - include: types
322
323 expressions-minus-function-call:
324 - include: early-expressions
325 - include: late-expressions-before-function-call
326 - include: identifiers
327 - match: ';'
328 scope: punctuation.terminator.c++
329
330 comments:
331 - include: scope:source.c#comments
332
333 operators:
334 - include: scope:source.c#operators
335
336 modifiers:
337 - include: unique-modifiers
338 - include: scope:source.c#modifiers
339
340 variables:
341 - include: unique-variables
342 - include: scope:source.c#variables
343
344 constants:
345 - include: unique-constants
346 - include: scope:source.c#constants
347
348 keywords:
349 - include: unique-keywords
350 - include: scope:source.c#keywords
351
352 types:
353 - include: unique-types
354 - include: types-parens
355 - include: scope:source.c#types
356
357 strings:
358 - include: unique-strings
359 - match: '(L|u8|u|U)?(")'
360 captures:
361 1: storage.type.string.c++
362 2: punctuation.definition.string.begin.c++
363 push:
364 - meta_scope: string.quoted.double.c++
365 - match: '"'
366 scope: punctuation.definition.string.end.c++
367 pop: true
368 - include: scope:source.c#string_escaped_char
369 - match: |-
370 (?x)%
371 (\d+\$)? # field (argument #)
372 [#0\- +']* # flags
373 [,;:_]? # separator character (AltiVec)
374 ((-?\d+)|\*(-?\d+\$)?)? # minimum field width
375 (\.((-?\d+)|\*(-?\d+\$)?)?)? # precision
376 (hh|h|ll|l|j|t|z|q|L|vh|vl|v|hv|hl)? # length modifier
377 (\[[^\]]+\]|[am]s|[diouxXDOUeEfFgGaACcSspn%]) # conversion type
378 scope: constant.other.placeholder.c++
379 - match: '\{\{|\}\}'
380 scope: constant.character.escape.c++
381 - include: formatting-syntax
382 - include: scope:source.c#strings
383
384 formatting-syntax:
385 # https://docs.python.org/3.6/library/string.html#formatstrings
386 - match: |- # simple form
387 (?x)
388 (\{)
389 (?: [\w.\[\]]+)? # field_name
390 ( ! [ars])? # conversion
391 ( : (?:{{format_spec}}| # format_spec OR
392 [^}%]*%.[^}]*) # any format-like string
393 )?
394 (\})
395 scope: constant.other.placeholder.c++
396 captures:
397 1: punctuation.definition.placeholder.begin.c++
398 2: storage.modifier.c++onversion.c++
399 3: constant.other.format-spec.c++
400 4: punctuation.definition.placeholder.end.c++
401 - match: \{(?=[^\}"']+\{[^"']*\}) # complex (nested) form
402 scope: punctuation.definition.placeholder.begin.c++
403 push:
404 - meta_scope: constant.other.placeholder.c++
405 - match: \}
406 scope: punctuation.definition.placeholder.end.c++
407 pop: true
408 - match: '[\w.\[\]]+'
409 - match: '![ars]'
410 scope: storage.modifier.conversion.c++
411 - match: ':'
412 push:
413 - meta_scope: meta.format-spec.c++ constant.other.format-spec.c++
414 - match: (?=\})
415 pop: true
416 - include: formatting-syntax
417
418 numbers:
419 - include: unique-numbers
420 - include: scope:source.c#numbers
421
422 ## C++-specific contexts
423
424 case-default:
425 - match: '\b(default|case)\b'
426 scope: keyword.control.c++
427 push:
428 - match: (?=[);,])
429 pop: true
430 - match: ':'
431 scope: punctuation.separator.c++
432 pop: true
433 - include: expressions
434
435 modifiers-parens:
436 - match: '\b(alignas)\b\s*(\()'
437 captures:
438 1: storage.modifier.c++
439 2: meta.group.c++ punctuation.section.group.begin.c++
440 push:
441 - meta_content_scope: meta.group.c++
442 - match: '\)'
443 scope: meta.group.c++ punctuation.section.group.end.c++
444 pop: true
445 - include: expressions
446 - match: \b(__attribute__)\s*(\(\()
447 captures:
448 1: storage.modifier.c++
449 2: meta.group.c++ punctuation.section.group.begin.c++
450 push :
451 - meta_scope: meta.attribute.c++
452 - meta_content_scope: meta.group.c++
453 - include: parens
454 - include: strings
455 - match: \)\)
456 scope: meta.group.c++ punctuation.section.group.end.c++
457 pop: true
458 - match: \b(__declspec)(\()
459 captures:
460 1: storage.modifier.c++
461 2: meta.group.c++ punctuation.section.group.begin.c++
462 push:
463 - meta_content_scope: meta.group.c++
464 - match: '\)'
465 scope: meta.group.c++ punctuation.section.group.end.c++
466 pop: true
467 - match: '\b(align|allocate|code_seg|deprecated|property|uuid)\b\s*(\()'
468 captures:
469 1: storage.modifier.c++
470 2: meta.group.c++ punctuation.section.group.begin.c++
471 push:
472 - meta_content_scope: meta.group.c++
473 - match: '\)'
474 scope: meta.group.c++ punctuation.section.group.end.c++
475 pop: true
476 - include: numbers
477 - include: strings
478 - match: \b(get|put)\b
479 scope: variable.parameter.c++
480 - match: ','
481 scope: punctuation.separator.c++
482 - match: '='
483 scope: keyword.operator.assignment.c++
484 - match: '\b(appdomain|deprecated|dllimport|dllexport|jintrinsic|naked|noalias|noinline|noreturn|nothrow|novtable|process|restrict|safebuffers|selectany|thread)\b'
485 scope: constant.other.c++
486
487 types-parens:
488 - match: '\b(decltype)\b\s*(\()'
489 captures:
490 1: storage.type.c++
491 2: meta.group.c++ punctuation.section.group.begin.c++
492 push:
493 - meta_content_scope: meta.group.c++
494 - match: '\)'
495 scope: meta.group.c++ punctuation.section.group.end.c++
496 pop: true
497 - include: expressions
498
499 keywords-angle-brackets:
500 - match: \b({{casts}})\b\s*
501 scope: keyword.operator.word.cast.c++
502 push:
503 - match: '>'
504 scope: punctuation.section.generic.end.c++
505 pop: true
506 - match: '<'
507 scope: punctuation.section.generic.begin.c++
508 push:
509 - match: '(?=>)'
510 pop: true
511 - include: expressions-minus-generic-type-function-call
512
513 keywords-parens:
514 - match: '\b(alignof|typeid|static_assert|sizeof)\b\s*(\()'
515 captures:
516 1: keyword.operator.word.c++
517 2: meta.group.c++ punctuation.section.group.begin.c++
518 push:
519 - meta_content_scope: meta.group.c++
520 - match: '\)'
521 scope: meta.group.c++ punctuation.section.group.end.c++
522 pop: true
523 - include: expressions
524
525 namespace:
526 - match: '\b(using)\s+(namespace)\s+(?={{path_lookahead}})'
527 captures:
528 1: keyword.control.c++
529 2: keyword.control.c++
530 push:
531 - include: identifiers
532 - match: ''
533 pop: true
534 - match: '\b(namespace)\s+(?=({{path_lookahead}})?(?!\s*[;,]))'
535 scope: meta.namespace.c++
536 captures:
537 1: keyword.control.c++
538 push:
539 - meta_content_scope: meta.namespace.c++ entity.name.namespace.c++
540 - include: identifiers
541 - match: ''
542 set:
543 - meta_scope: meta.namespace.c++
544 - include: comments
545 - match: '='
546 scope: keyword.operator.alias.c++
547 - match: '(?=;)'
548 pop: true
549 - match: '\}'
550 scope: meta.block.c++ punctuation.section.block.end.c++
551 pop: true
552 - match: '\{'
553 scope: punctuation.section.block.begin.c++
554 push:
555 - meta_scope: meta.block.c++
556 - match: '(?=\})'
557 pop: true
558 - include: preprocessor-global
559 - include: global
560 - include: expressions
561
562 template-common:
563 # Exit the template scope if we hit some basic invalid characters. This
564 # helps when a user is in the middle of typing their template types and
565 # prevents re-highlighting the whole file until the next > is found.
566 - match: (?=[{};])
567 pop: true
568 - include: expressions
569
570 template:
571 - match: \btemplate\b
572 scope: storage.type.template.c++
573 push:
574 - meta_scope: meta.template.c++
575 # Explicitly include comments here at the top, in order to NOT match the
576 # \S lookahead in the case of comments.
577 - include: comments
578 - match: <
579 scope: punctuation.section.generic.begin.c++
580 set:
581 - meta_content_scope: meta.template.c++
582 - match: '>'
583 scope: meta.template.c++ punctuation.section.generic.end.c++
584 pop: true
585 - match: \.{3}
586 scope: keyword.operator.variadic.c++
587 - match: \b(typename|{{before_tag}})\b
588 scope: storage.type.c++
589 - include: template # include template here for nested templates
590 - include: template-common
591 - match: (?=\S)
592 set:
593 - meta_content_scope: meta.template.c++
594 - match: \b({{before_tag}})\b
595 scope: storage.type.c++
596 - include: template-common
597
598 generic-type:
599 - match: '(?=(?!template){{path_lookahead}}\s*{{generic_lookahead}}\s*\()'
600 push:
601 - meta_scope: meta.function-call.c++
602 - match: \btemplate\b
603 scope: storage.type.template.c++
604 - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*'
605 captures:
606 1: punctuation.accessor.double-colon.c++
607 2: punctuation.accessor.double-colon.c++
608 - match: (?:(::)\s*)?({{identifier}})\s*(<)
609 captures:
610 1: punctuation.accessor.double-colon.c++
611 2: variable.function.c++
612 3: punctuation.section.generic.begin.c++
613 push:
614 - match: '>'
615 scope: punctuation.section.generic.end.c++
616 pop: true
617 - include: expressions-minus-generic-type-function-call
618 - match: (?:(::)\s*)?({{identifier}})\s*(\()
619 captures:
620 1: punctuation.accessor.double-colon.c++
621 2: variable.function.c++
622 3: punctuation.section.group.begin.c++
623 set:
624 - meta_scope: meta.function-call.c++
625 - meta_content_scope: meta.group.c++
626 - match: '\)'
627 scope: meta.group.c++ punctuation.section.group.end.c++
628 pop: true
629 - include: expressions
630 - include: angle-brackets
631 - match: '\('
632 scope: meta.group.c++ punctuation.section.group.begin.c++
633 set:
634 - meta_scope: meta.function-call.c++
635 - meta_content_scope: meta.group.c++
636 - match: '\)'
637 scope: meta.group.c++ punctuation.section.group.end.c++
638 pop: true
639 - include: expressions
640 - match: '(?=(?!template){{path_lookahead}}\s*{{generic_lookahead}})'
641 push:
642 - include: identifiers
643 - match: '<'
644 scope: punctuation.section.generic.begin.c++
645 set:
646 - match: '>'
647 scope: punctuation.section.generic.end.c++
648 pop: true
649 - include: expressions-minus-generic-type-function-call
650
651 angle-brackets:
652 - match: '<(?!<)'
653 scope: punctuation.section.generic.begin.c++
654 push:
655 - match: '>'
656 scope: punctuation.section.generic.end.c++
657 pop: true
658 - include: expressions-minus-generic-type-function-call
659
660 block:
661 - match: '\{'
662 scope: punctuation.section.block.begin.c++
663 push:
664 - meta_scope: meta.block.c++
665 - match: (?=^\s*#\s*(elif|else|endif)\b)
666 pop: true
667 - match: '\}'
668 scope: punctuation.section.block.end.c++
669 pop: true
670 - include: statements
671
672 function-call:
673 - match: (?={{path_lookahead}}\s*\()
674 push:
675 - meta_scope: meta.function-call.c++
676 - include: scope:source.c#c99
677 - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*'
678 scope: variable.function.c++
679 captures:
680 1: punctuation.accessor.c++
681 2: punctuation.accessor.c++
682 - match: '(?:(::)\s*)?{{identifier}}'
683 scope: variable.function.c++
684 captures:
685 1: punctuation.accessor.c++
686 - match: '\('
687 scope: meta.group.c++ punctuation.section.group.begin.c++
688 set:
689 - meta_content_scope: meta.function-call.c++ meta.group.c++
690 - match: '\)'
691 scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
692 pop: true
693 - include: expressions
694
695 members-inside-function-call:
696 - meta_content_scope: meta.method-call.c++ meta.group.c++
697 - match: \)
698 scope: meta.method-call.c++ meta.group.c++ punctuation.section.group.end.c++
699 pop: true
700 - include: expressions
701
702 members-after-accessor-junction:
703 # After we've seen an accessor (dot or arrow), this context decides what
704 # kind of entity we're accessing.
705 - include: comments
706 - match: \btemplate\b
707 scope: meta.method-call.c++ storage.type.template.c++
708 # Guaranteed to be a template member function call after we match this
709 set:
710 - meta_content_scope: meta.method-call.c++
711 - include: comments
712 - match: '{{identifier}}'
713 scope: variable.function.member.c++
714 set:
715 - meta_content_scope: meta.method-call.c++
716 - match: \(
717 scope: meta.group.c++ punctuation.section.group.begin.c++
718 set: members-inside-function-call
719 - include: comments
720 - include: angle-brackets
721 - match: (?=\S) # safety pop
722 pop: true
723 - match: (?=\S) # safety pop
724 pop: true
725 # Operator overloading
726 - match: '({{operator_method_name}})\s*(\()'
727 captures:
728 0: meta.method-call.c++
729 1: variable.function.member.c++
730 2: meta.group.c++ punctuation.section.group.begin.c++
731 set: members-inside-function-call
732 # Non-templated member function call
733 - match: (~?{{identifier}})\s*(\()
734 captures:
735 0: meta.method-call.c++
736 1: variable.function.member.c++
737 2: meta.group.c++ punctuation.section.group.begin.c++
738 set: members-inside-function-call
739 # Templated member function call
740 - match: (~?{{identifier}})\s*(?={{generic_lookahead}})
741 captures:
742 1: variable.function.member.c++
743 set:
744 - meta_scope: meta.method-call.c++
745 - match: <
746 scope: punctuation.section.generic.begin.c++
747 set:
748 - meta_content_scope: meta.method-call.c++
749 - match: '>'
750 scope: punctuation.section.generic.end.c++
751 set:
752 - meta_content_scope: meta.method-call.c++
753 - include: comments
754 - match: \(
755 scope: punctuation.section.group.begin.c++
756 set: members-inside-function-call
757 - match: (?=\S) # safety pop
758 pop: true
759 - include: expressions
760 # Explicit base-class access
761 - match: ({{identifier}})\s*(::)
762 captures:
763 1: variable.other.base-class.c++
764 2: punctuation.accessor.double-colon.c++
765 set: members-after-accessor-junction # reset
766 # Just a regular member variable
767 - match: '{{identifier}}'
768 scope: variable.other.readwrite.member.c++
769 pop: true
770
771 members-dot:
772 - include: scope:source.c#access-illegal
773 # No lookahead required because members-dot goes after operators in the
774 # early-expressions-after-generic-type context. This means triple dots
775 # (i.e. "..." or "variadic") is attempted first.
776 - match: \.
777 scope: punctuation.accessor.dot.c++
778 push: members-after-accessor-junction
779
780 members-arrow:
781 # This needs to be before operators in the
782 # early-expressions-after-generic-type context because otherwise the "->"
783 # from the C language will match.
784 - match: ->
785 scope: punctuation.accessor.arrow.c++
786 push: members-after-accessor-junction
787
788 typedef:
789 - match: \btypedef\b
790 scope: storage.type.c++
791 push:
792 - match: ({{identifier}})?\s*(?=;)
793 captures:
794 1: entity.name.type.typedef.c++
795 pop: true
796 - match: \b(struct)\s+({{identifier}})\b
797 captures:
798 1: storage.type.c++
799 - include: expressions-minus-generic-type
800
801 parens:
802 - match: \(
803 scope: punctuation.section.group.begin.c++
804 push:
805 - meta_scope: meta.group.c++
806 - match: \)
807 scope: punctuation.section.group.end.c++
808 pop: true
809 - include: expressions
810
811 brackets:
812 - match: \[
813 scope: punctuation.section.brackets.begin.c++
814 push:
815 - meta_scope: meta.brackets.c++
816 - match: \]
817 scope: punctuation.section.brackets.end.c++
818 pop: true
819 - include: expressions
820
821 function-trailing-return-type:
822 - match: '{{non_angle_brackets}}'
823 pop: true
824 - include: angle-brackets
825 - include: types
826 - include: modifiers-parens
827 - include: modifiers
828 - include: identifiers
829 - match: \*|&
830 scope: keyword.operator.c++
831 - include: function-trailing-return-type-parens
832 - match: '(?=\S)'
833 pop: true
834
835 function-trailing-return-type-parens:
836 - match: \(
837 scope: punctuation.section.group.begin.c++
838 push:
839 - meta_scope: meta.group.c++
840 - match: \)
841 scope: punctuation.section.group.end.c++
842 pop: true
843 - include: function-trailing-return-type
844
845 ## Detection of function and data structure definitions at the global level
846
847 global-modifier:
848 - include: comments
849 - include: modifiers-parens
850 - include: modifiers
851 # Constructors and destructors don't have a type
852 - match: '(?={{path_lookahead}}\s*::\s*{{identifier}}\s*(\(|$))'
853 set:
854 - meta_content_scope: meta.function.c++ entity.name.function.constructor.c++
855 - include: identifiers
856 - match: '(?=[^\w\s])'
857 set: function-definition-params
858 - match: '(?={{path_lookahead}}\s*::\s*~{{identifier}}\s*(\(|$))'
859 set:
860 - meta_content_scope: meta.function.c++ entity.name.function.destructor.c++
861 - include: identifiers
862 - match: '~{{identifier}}'
863 - match: '(?=[^\w\s])'
864 set: function-definition-params
865 # If we see a path ending in :: before a newline, we don't know if it is
866 # a constructor or destructor, or a long return type, so we are just going
867 # to treat it like a regular function. Most likely it is a constructor,
868 # since it doesn't seem most developers would create such a long typename.
869 - match: '(?={{path_lookahead}}\s*::\s*$)'
870 set:
871 - meta_content_scope: meta.function.c++ entity.name.function.c++
872 - include: identifiers
873 - match: '~{{identifier}}'
874 - match: '(?=[^\w\s])'
875 set: function-definition-params
876 - include: unique-strings
877 - match: '(?=\S)'
878 set: global-type
879
880 global-type:
881 - include: comments
882 - match: \*|&
883 scope: keyword.operator.c++
884 - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}}|operator)\b)'
885 pop: true
886 - match: '(?=\s)'
887 set: global-maybe-function
888 # If a class/struct/enum followed by a name that is not a macro or declspec
889 # then this is likely a return type of a function. This is uncommon.
890 - match: |-
891 (?x:
892 ({{before_tag}})
893 \s+
894 (?=
895 (?![[:upper:][:digit:]_]+\b|__declspec|{{before_tag}})
896 {{path_lookahead}}
897 (\s+{{identifier}}\s*\(|\s*[*&])
898 )
899 )
900 captures:
901 1: storage.type.c++
902 set:
903 - include: identifiers
904 - match: ''
905 set: global-maybe-function
906 # The previous match handles return types of struct/enum/etc from a func,
907 # there this one exits the context to allow matching an actual struct/class
908 - match: '(?=\b({{before_tag}})\b)'
909 set: data-structures
910 - match: '(?=\b({{casts}})\b\s*<)'
911 pop: true
912 - match: '{{non_angle_brackets}}'
913 pop: true
914 - include: angle-brackets
915 - include: types
916 # Allow a macro call
917 - match: '({{identifier}})\s*(\()(?=[^\)]+\))'
918 captures:
919 1: variable.function.c++
920 2: meta.group.c++ punctuation.section.group.begin.c++
921 push:
922 - meta_scope: meta.function-call.c++
923 - meta_content_scope: meta.group.c++
924 - match: '\)'
925 scope: meta.group.c++ punctuation.section.group.end.c++
926 pop: true
927 - include: expressions
928 - match: '(?={{path_lookahead}}\s*\()'
929 set:
930 - include: function-call
931 - match: ''
932 pop: true
933 - include: variables
934 - include: constants
935 - include: identifiers
936 - match: (?=\W)
937 pop: true
938
939 global-maybe-function:
940 - include: comments
941 # Consume pointer info, macros and any type info that was offset by macros
942 - match: \*|&
943 scope: keyword.operator.c++
944 - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}})\b)'
945 pop: true
946 - match: '\b({{type_qualifier}})\b'
947 scope: storage.modifier.c++
948 - match: '{{non_angle_brackets}}'
949 pop: true
950 - include: angle-brackets
951 - include: types
952 - include: modifiers-parens
953 - include: modifiers
954 # All uppercase identifier just before a newline is most likely a macro
955 - match: '[[:upper:][:digit:]_]+\s*$'
956 # Operator overloading
957 - match: '(?=({{path_lookahead}}\s*(?:{{generic_lookahead}})?::\s*)?{{operator_method_name}}\s*(\(|$))'
958 set:
959 - meta_content_scope: meta.function.c++ entity.name.function.c++
960 - include: identifiers
961 - match: '(?=\s*(\(|$))'
962 set: function-definition-params
963 # Identifier that is not the function name - likely a macro or type
964 - match: '(?={{path_lookahead}}([ \t]+|[*&])(?!\s*(<|::|\(|$)))'
965 push:
966 - include: identifiers
967 - match: ''
968 pop: true
969 # Real function definition
970 - match: '(?={{path_lookahead}}({{generic_lookahead}}({{path_lookahead}})?)\s*(\(|$))'
971 set: [function-definition-params, global-function-identifier-generic]
972 - match: '(?={{path_lookahead}}\s*(\(|$))'
973 set: [function-definition-params, global-function-identifier]
974 - match: '(?={{path_lookahead}}\s*::\s*$)'
975 set: [function-definition-params, global-function-identifier]
976 - match: '(?=\S)'
977 pop: true
978
979 global-function-identifier-generic:
980 - include: angle-brackets
981 - match: '::'
982 scope: punctuation.accessor.c++
983 - match: '(?={{identifier}}<.*>\s*\()'
984 push:
985 - meta_content_scope: entity.name.function.c++
986 - include: identifiers
987 - match: '(?=<)'
988 pop: true
989 - match: '(?={{identifier}}\s*\()'
990 push:
991 - meta_content_scope: entity.name.function.c++
992 - include: identifiers
993 - match: ''
994 pop: true
995 - match: '(?=\()'
996 pop: true
997
998 global-function-identifier:
999 - meta_content_scope: entity.name.function.c++
1000 - include: identifiers
1001 - match: '(?=\S)'
1002 pop: true
1003
1004 function-definition-params:
1005 - meta_content_scope: meta.function.c++
1006 - include: comments
1007 - match: '(?=\()'
1008 set:
1009 - match: \(
1010 scope: meta.function.parameters.c++ meta.group.c++ punctuation.section.group.begin.c++
1011 set:
1012 - meta_content_scope: meta.function.parameters.c++ meta.group.c++
1013 - match : \)
1014 scope: punctuation.section.group.end.c++
1015 set: function-definition-continue
1016 - match: '\bvoid\b'
1017 scope: storage.type.c++
1018 - match: '{{identifier}}(?=\s*(\[|,|\)|=))'
1019 scope: variable.parameter.c++
1020 - match: '='
1021 scope: keyword.operator.assignment.c++
1022 push:
1023 - match: '(?=,|\))'
1024 pop: true
1025 - include: expressions-minus-generic-type
1026 - include: scope:source.c#preprocessor-line-continuation
1027 - include: expressions-minus-generic-type
1028 - include: scope:source.c#preprocessor-line-continuation
1029 - match: (?=\S)
1030 pop: true
1031
1032 function-definition-continue:
1033 - meta_content_scope: meta.function.c++
1034 - include: comments
1035 - match: '(?=;)'
1036 pop: true
1037 - match: '->'
1038 scope: punctuation.separator.c++
1039 set: function-definition-trailing-return
1040 - include: function-specifiers
1041 - match: '='
1042 scope: keyword.operator.assignment.c++
1043 - match: '&'
1044 scope: keyword.operator.c++
1045 - match: \b0\b
1046 scope: constant.numeric.c++
1047 - match: \b(default|delete)\b
1048 scope: storage.modifier.c++
1049 - match: '(?=\{)'
1050 set: function-definition-body
1051 - match: '(?=\S)'
1052 pop: true
1053
1054 function-definition-trailing-return:
1055 - include: comments
1056 - match: '(?=;)'
1057 pop: true
1058 - match: '(?=\{)'
1059 set: function-definition-body
1060 - include: function-specifiers
1061 - include: function-trailing-return-type
1062
1063 function-definition-body:
1064 - meta_content_scope: meta.function.c++ meta.block.c++
1065 - match: '\{'
1066 scope: punctuation.section.block.begin.c++
1067 set:
1068 - meta_content_scope: meta.function.c++ meta.block.c++
1069 - match: '\}'
1070 scope: meta.function.c++ meta.block.c++ punctuation.section.block.end.c++
1071 pop: true
1072 - match: (?=^\s*#\s*(elif|else|endif)\b)
1073 pop: true
1074 - match: '(?=({{before_tag}})([^(;]+$|.*\{))'
1075 push: data-structures
1076 - include: statements
1077
1078 ## Data structures including classes, structs, unions and enums
1079
1080 data-structures:
1081 - match: '\bclass\b'
1082 scope: storage.type.c++
1083 set: data-structures-class-definition
1084 # Detect variable type definitions using struct/enum/union followed by a tag
1085 - match: '\b({{before_tag}})(?=\s+{{path_lookahead}}\s+{{path_lookahead}}\s*[=;\[])'
1086 scope: storage.type.c++
1087 - match: '\bstruct\b'
1088 scope: storage.type.c++
1089 set: data-structures-struct-definition
1090 - match: '\benum(\s+(class|struct))?\b'
1091 scope: storage.type.c++
1092 set: data-structures-enum-definition
1093 - match: '\bunion\b'
1094 scope: storage.type.c++
1095 set: data-structures-union-definition
1096 - match: '(?=\S)'
1097 pop: true
1098
1099 preprocessor-workaround-eat-macro-before-identifier:
1100 # Handle macros so they aren't matched as the class name
1101 - match: ({{macro_identifier}})(?=\s+~?{{identifier}})
1102 captures:
1103 1: meta.assumed-macro.c
1104
1105 data-structures-class-definition:
1106 - meta_scope: meta.class.c++
1107 - include: data-structures-definition-common-begin
1108 - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
1109 scope: entity.name.class.forward-decl.c++
1110 set: data-structures-class-definition-after-identifier
1111 - match: '{{identifier}}'
1112 scope: entity.name.class.c++
1113 set: data-structures-class-definition-after-identifier
1114 - match: '(?=[:{])'
1115 set: data-structures-class-definition-after-identifier
1116 - match: '(?=;)'
1117 pop: true
1118
1119 data-structures-class-definition-after-identifier:
1120 - meta_content_scope: meta.class.c++
1121 - include: data-structures-definition-common-begin
1122 # No matching of identifiers since they should all be macros at this point
1123 - include: data-structures-definition-common-end
1124 - match: '\{'
1125 scope: meta.block.c++ punctuation.section.block.begin.c++
1126 set:
1127 - meta_content_scope: meta.class.c++ meta.block.c++
1128 - match: '\}'
1129 scope: meta.class.c++ meta.block.c++ punctuation.section.block.end.c++
1130 pop: true
1131 - include: data-structures-body
1132
1133 data-structures-struct-definition:
1134 - meta_scope: meta.struct.c++
1135 - include: data-structures-definition-common-begin
1136 - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
1137 scope: entity.name.struct.forward-decl.c++
1138 set: data-structures-struct-definition-after-identifier
1139 - match: '{{identifier}}'
1140 scope: entity.name.struct.c++
1141 set: data-structures-struct-definition-after-identifier
1142 - match: '(?=[:{])'
1143 set: data-structures-struct-definition-after-identifier
1144 - match: '(?=;)'
1145 pop: true
1146
1147 data-structures-struct-definition-after-identifier:
1148 - meta_content_scope: meta.struct.c++
1149 - include: data-structures-definition-common-begin
1150 # No matching of identifiers since they should all be macros at this point
1151 - include: data-structures-definition-common-end
1152 - match: '\{'
1153 scope: meta.block.c++ punctuation.section.block.begin.c++
1154 set:
1155 - meta_content_scope: meta.struct.c++ meta.block.c++
1156 - match: '\}'
1157 scope: meta.struct.c++ meta.block.c++ punctuation.section.block.end.c++
1158 pop: true
1159 - include: data-structures-body
1160
1161 data-structures-enum-definition:
1162 - meta_scope: meta.enum.c++
1163 - include: data-structures-definition-common-begin
1164 - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
1165 scope: entity.name.enum.forward-decl.c++
1166 set: data-structures-enum-definition-after-identifier
1167 - match: '{{identifier}}'
1168 scope: entity.name.enum.c++
1169 set: data-structures-enum-definition-after-identifier
1170 - match: '(?=[:{])'
1171 set: data-structures-enum-definition-after-identifier
1172 - match: '(?=;)'
1173 pop: true
1174
1175 data-structures-enum-definition-after-identifier:
1176 - meta_content_scope: meta.enum.c++
1177 - include: data-structures-definition-common-begin
1178 # No matching of identifiers since they should all be macros at this point
1179 - include: data-structures-definition-common-end
1180 - match: '\{'
1181 scope: meta.block.c++ punctuation.section.block.begin.c++
1182 set:
1183 - meta_content_scope: meta.enum.c++ meta.block.c++
1184 # Enums don't support methods so we have a simplified body
1185 - match: '\}'
1186 scope: meta.enum.c++ meta.block.c++ punctuation.section.block.end.c++
1187 pop: true
1188 - include: statements
1189
1190 data-structures-union-definition:
1191 - meta_scope: meta.union.c++
1192 - include: data-structures-definition-common-begin
1193 - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
1194 scope: entity.name.union.forward-decl.c++
1195 set: data-structures-union-definition-after-identifier
1196 - match: '{{identifier}}'
1197 scope: entity.name.union.c++
1198 set: data-structures-union-definition-after-identifier
1199 - match: '(?=[{])'
1200 set: data-structures-union-definition-after-identifier
1201 - match: '(?=;)'
1202 pop: true
1203
1204 data-structures-union-definition-after-identifier:
1205 - meta_content_scope: meta.union.c++
1206 - include: data-structures-definition-common-begin
1207 # No matching of identifiers since they should all be macros at this point
1208 # Unions don't support base classes
1209 - include: angle-brackets
1210 - match: '\{'
1211 scope: meta.block.c++ punctuation.section.block.begin.c++
1212 set:
1213 - meta_content_scope: meta.union.c++ meta.block.c++
1214 - match: '\}'
1215 scope: meta.union.c++ meta.block.c++ punctuation.section.block.end.c++
1216 pop: true
1217 - include: data-structures-body
1218 - match: '(?=;)'
1219 pop: true
1220
1221 data-structures-definition-common-begin:
1222 - include: comments
1223 - match: '(?=\b(?:{{before_tag}}|{{control_keywords}})\b)'
1224 pop: true
1225 - include: preprocessor-other
1226 - include: modifiers-parens
1227 - include: modifiers
1228 - include: preprocessor-workaround-eat-macro-before-identifier
1229
1230 data-structures-definition-common-end:
1231 - include: angle-brackets
1232 - match: \bfinal\b
1233 scope: storage.modifier.c++
1234 - match: ':'
1235 scope: punctuation.separator.c++
1236 push:
1237 - include: comments
1238 - include: preprocessor-other
1239 - include: modifiers-parens
1240 - include: modifiers
1241 - match: '\b(virtual|{{visibility_modifiers}})\b'
1242 scope: storage.modifier.c++
1243 - match: (?={{path_lookahead}})
1244 push:
1245 - meta_scope: entity.other.inherited-class.c++
1246 - include: identifiers
1247 - match: ''
1248 pop: true
1249 - include: angle-brackets
1250 - match: ','
1251 scope: punctuation.separator.c++
1252 - match: (?=\{|;)
1253 pop: true
1254 - match: '(?=;)'
1255 pop: true
1256
1257 data-structures-body:
1258 - include: preprocessor-data-structures
1259 - match: '(?=\btemplate\b)'
1260 push:
1261 - include: template
1262 - match: (?=\S)
1263 set: data-structures-modifier
1264 - include: typedef
1265 - match: \b({{visibility_modifiers}})\s*(:)(?!:)
1266 captures:
1267 1: storage.modifier.c++
1268 2: punctuation.section.class.c++
1269 - match: '^\s*(?=(?:~?\w+|::))'
1270 push: data-structures-modifier
1271 - include: expressions-minus-generic-type
1272
1273 data-structures-modifier:
1274 - match: '\bfriend\b'
1275 scope: storage.modifier.c++
1276 push:
1277 - match: (?=;)
1278 pop: true
1279 - match: '\{'
1280 scope: punctuation.section.block.begin.c++
1281 set:
1282 - meta_scope: meta.block.c++
1283 - match: '\}'
1284 scope: punctuation.section.block.end.c++
1285 pop: true
1286 - include: statements
1287 - match: '\b({{before_tag}})\b'
1288 scope: storage.type.c++
1289 - include: expressions-minus-function-call
1290 - include: comments
1291 - include: modifiers-parens
1292 - include: modifiers
1293 - match: '\bstatic_assert(?=\s*\()'
1294 scope: meta.static-assert.c++ keyword.operator.word.c++
1295 push:
1296 - match: '\('
1297 scope: meta.group.c++ punctuation.section.group.begin.c++
1298 set:
1299 - meta_content_scope: meta.function-call.c++ meta.group.c++
1300 - match: '\)'
1301 scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
1302 pop: true
1303 - include: expressions
1304 # Destructor
1305 - match: '(?:{{identifier}}\s*(::)\s*)?~{{identifier}}(?=\s*(\(|$))'
1306 scope: meta.method.destructor.c++ entity.name.function.destructor.c++
1307 captures:
1308 1: punctuation.accessor.c++
1309 set: method-definition-params
1310 # It's a macro, not a constructor if there is no type in the first param
1311 - match: '({{identifier}})\s*(\()(?=\s*(?!void){{identifier}}\s*[),])'
1312 captures:
1313 1: variable.function.c++
1314 2: meta.group.c++ punctuation.section.group.begin.c++
1315 push:
1316 - meta_scope: meta.function-call.c++
1317 - meta_content_scope: meta.group.c++
1318 - match: '\)'
1319 scope: meta.group.c++ punctuation.section.group.end.c++
1320 pop: true
1321 - include: expressions
1322 # Constructor
1323 - include: preprocessor-workaround-eat-macro-before-identifier
1324 - match: '((?!{{before_tag}}|template){{identifier}})(?=\s*\()'
1325 scope: meta.method.constructor.c++ entity.name.function.constructor.c++
1326 set: method-definition-params
1327 # Long form constructor
1328 - match: '({{identifier}}\s*(::)\s*{{identifier}})(?=\s*\()'
1329 captures:
1330 1: meta.method.constructor.c++ entity.name.function.constructor.c++
1331 2: punctuation.accessor.c++
1332 push: method-definition-params
1333 - match: '(?=\S)'
1334 set: data-structures-type
1335
1336 data-structures-type:
1337 - include: comments
1338 - match: \*|&
1339 scope: keyword.operator.c++
1340 # Cast methods
1341 - match: '(operator)\s+({{identifier}})(?=\s*(\(|$))'
1342 captures:
1343 1: keyword.control.c++
1344 2: meta.method.c++ entity.name.function.c++
1345 set: method-definition-params
1346 - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}}|operator)\b)'
1347 pop: true
1348 - match: '(?=\s)'
1349 set: data-structures-maybe-method
1350 # If a class/struct/enum followed by a name that is not a macro or declspec
1351 # then this is likely a return type of a function. This is uncommon.
1352 - match: |-
1353 (?x:
1354 ({{before_tag}})
1355 \s+
1356 (?=
1357 (?![[:upper:][:digit:]_]+\b|__declspec|{{before_tag}})
1358 {{path_lookahead}}
1359 (\s+{{identifier}}\s*\(|\s*[*&])
1360 )
1361 )
1362 captures:
1363 1: storage.type.c++
1364 set:
1365 - include: identifiers
1366 - match: ''
1367 set: data-structures-maybe-method
1368 # The previous match handles return types of struct/enum/etc from a func,
1369 # there this one exits the context to allow matching an actual struct/class
1370 - match: '(?=\b({{before_tag}})\b)'
1371 set: data-structures
1372 - match: '(?=\b({{casts}})\b\s*<)'
1373 pop: true
1374 - match: '{{non_angle_brackets}}'
1375 pop: true
1376 - include: angle-brackets
1377 - include: types
1378 - include: variables
1379 - include: constants
1380 - include: identifiers
1381 - match: (?=[&*])
1382 set: data-structures-maybe-method
1383 - match: (?=\W)
1384 pop: true
1385
1386 data-structures-maybe-method:
1387 - include: comments
1388 # Consume pointer info, macros and any type info that was offset by macros
1389 - match: \*|&
1390 scope: keyword.operator.c++
1391 - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}})\b)'
1392 pop: true
1393 - match: '\b({{type_qualifier}})\b'
1394 scope: storage.modifier.c++
1395 - match: '{{non_angle_brackets}}'
1396 pop: true
1397 - include: angle-brackets
1398 - include: types
1399 - include: modifiers-parens
1400 - include: modifiers
1401 # Operator overloading
1402 - match: '{{operator_method_name}}(?=\s*(\(|$))'
1403 scope: meta.method.c++ entity.name.function.c++
1404 set: method-definition-params
1405 # Identifier that is not the function name - likely a macro or type
1406 - match: '(?={{path_lookahead}}([ \t]+|[*&])(?!\s*(<|::|\()))'
1407 push:
1408 - include: identifiers
1409 - match: ''
1410 pop: true
1411 # Real function definition
1412 - match: '(?={{path_lookahead}}({{generic_lookahead}})\s*(\())'
1413 set: [method-definition-params, data-structures-function-identifier-generic]
1414 - match: '(?={{path_lookahead}}\s*(\())'
1415 set: [method-definition-params, data-structures-function-identifier]
1416 - match: '(?={{path_lookahead}}\s*::\s*$)'
1417 set: [method-definition-params, data-structures-function-identifier]
1418 - match: '(?=\S)'
1419 pop: true
1420
1421 data-structures-function-identifier-generic:
1422 - include: angle-brackets
1423 - match: '(?={{identifier}})'
1424 push:
1425 - meta_content_scope: entity.name.function.c++
1426 - include: identifiers
1427 - match: '(?=<)'
1428 pop: true
1429 - match: '(?=\()'
1430 pop: true
1431
1432 data-structures-function-identifier:
1433 - meta_content_scope: entity.name.function.c++
1434 - include: identifiers
1435 - match: '(?=\S)'
1436 pop: true
1437
1438 method-definition-params:
1439 - meta_content_scope: meta.method.c++
1440 - include: comments
1441 - match: '(?=\()'
1442 set:
1443 - match: \(
1444 scope: meta.method.parameters.c++ meta.group.c++ punctuation.section.group.begin.c++
1445 set:
1446 - meta_content_scope: meta.method.parameters.c++ meta.group.c++
1447 - match : \)
1448 scope: punctuation.section.group.end.c++
1449 set: method-definition-continue
1450 - match: '\bvoid\b'
1451 scope: storage.type.c++
1452 - match: '{{identifier}}(?=\s*(\[|,|\)|=))'
1453 scope: variable.parameter.c++
1454 - match: '='
1455 scope: keyword.operator.assignment.c++
1456 push:
1457 - match: '(?=,|\))'
1458 pop: true
1459 - include: expressions-minus-generic-type
1460 - include: expressions-minus-generic-type
1461 - match: '(?=\S)'
1462 pop: true
1463
1464 method-definition-continue:
1465 - meta_content_scope: meta.method.c++
1466 - include: comments
1467 - match: '(?=;)'
1468 pop: true
1469 - match: '->'
1470 scope: punctuation.separator.c++
1471 set: method-definition-trailing-return
1472 - include: function-specifiers
1473 - match: '='
1474 scope: keyword.operator.assignment.c++
1475 - match: '&'
1476 scope: keyword.operator.c++
1477 - match: \b0\b
1478 scope: constant.numeric.c++
1479 - match: \b(default|delete)\b
1480 scope: storage.modifier.c++
1481 - match: '(?=:)'
1482 set:
1483 - match: ':'
1484 scope: punctuation.separator.initializer-list.c++
1485 set:
1486 - meta_scope: meta.method.constructor.initializer-list.c++
1487 - match: '{{identifier}}'
1488 scope: variable.other.readwrite.member.c++
1489 push:
1490 - match: \(
1491 scope: meta.group.c++ punctuation.section.group.begin.c++
1492 set:
1493 - meta_content_scope: meta.group.c++
1494 - match: \)
1495 scope: meta.group.c++ punctuation.section.group.end.c++
1496 pop: true
1497 - include: expressions
1498 - match: \{
1499 scope: meta.group.c++ punctuation.section.group.begin.c++
1500 set:
1501 - meta_content_scope: meta.group.c++
1502 - match: \}
1503 scope: meta.group.c++ punctuation.section.group.end.c++
1504 pop: true
1505 - include: expressions
1506 - include: comments
1507 - match: (?=\{|;)
1508 set: method-definition-continue
1509 - include: expressions
1510 - match: '(?=\{)'
1511 set: method-definition-body
1512 - match: '(?=\S)'
1513 pop: true
1514
1515 method-definition-trailing-return:
1516 - include: comments
1517 - match: '(?=;)'
1518 pop: true
1519 - match: '(?=\{)'
1520 set: method-definition-body
1521 - include: function-specifiers
1522 - include: function-trailing-return-type
1523
1524 method-definition-body:
1525 - meta_content_scope: meta.method.c++ meta.block.c++
1526 - match: '\{'
1527 scope: punctuation.section.block.begin.c++
1528 set:
1529 - meta_content_scope: meta.method.c++ meta.block.c++
1530 - match: '\}'
1531 scope: meta.method.c++ meta.block.c++ punctuation.section.block.end.c++
1532 pop: true
1533 - match: (?=^\s*#\s*(elif|else|endif)\b)
1534 pop: true
1535 - match: '(?=({{before_tag}})([^(;]+$|.*\{))'
1536 push: data-structures
1537 - include: statements
1538
1539 ## Preprocessor for data-structures
1540
1541 preprocessor-data-structures:
1542 - include: preprocessor-rule-enabled-data-structures
1543 - include: preprocessor-rule-disabled-data-structures
1544 - include: preprocessor-practical-workarounds
1545
1546 preprocessor-rule-disabled-data-structures:
1547 - match: ^\s*((#if)\s+(0))\b
1548 captures:
1549 1: meta.preprocessor.c++
1550 2: keyword.control.import.c++
1551 3: constant.numeric.preprocessor.c++
1552 push:
1553 - match: ^\s*(#\s*endif)\b
1554 captures:
1555 1: meta.preprocessor.c++ keyword.control.import.c++
1556 pop: true
1557 - match: ^\s*(#\s*else)\b
1558 captures:
1559 1: meta.preprocessor.c++ keyword.control.import.else.c++
1560 push:
1561 - match: (?=^\s*#\s*endif\b)
1562 pop: true
1563 - include: negated-block
1564 - include: data-structures-body
1565 - match: ""
1566 push:
1567 - meta_scope: comment.block.preprocessor.if-branch.c++
1568 - match: (?=^\s*#\s*(else|endif)\b)
1569 pop: true
1570 - include: scope:source.c#preprocessor-disabled
1571
1572 preprocessor-rule-enabled-data-structures:
1573 - match: ^\s*((#if)\s+(0*1))\b
1574 captures:
1575 1: meta.preprocessor.c++
1576 2: keyword.control.import.c++
1577 3: constant.numeric.preprocessor.c++
1578 push:
1579 - match: ^\s*(#\s*endif)\b
1580 captures:
1581 1: meta.preprocessor.c++ keyword.control.import.c++
1582 pop: true
1583 - match: ^\s*(#\s*else)\b
1584 captures:
1585 1: meta.preprocessor.c++ keyword.control.import.else.c++
1586 push:
1587 - meta_content_scope: comment.block.preprocessor.else-branch.c++
1588 - match: (?=^\s*#\s*endif\b)
1589 pop: true
1590 - include: scope:source.c#preprocessor-disabled
1591 - match: ""
1592 push:
1593 - match: (?=^\s*#\s*(else|endif)\b)
1594 pop: true
1595 - include: negated-block
1596 - include: data-structures-body
1597
1598 ## Preprocessor for global
1599
1600 preprocessor-global:
1601 - include: preprocessor-rule-enabled-global
1602 - include: preprocessor-rule-disabled-global
1603 - include: preprocessor-rule-other-global
1604
1605 preprocessor-statements:
1606 - include: preprocessor-rule-enabled-statements
1607 - include: preprocessor-rule-disabled-statements
1608 - include: preprocessor-rule-other-statements
1609
1610 preprocessor-expressions:
1611 - include: scope:source.c#incomplete-inc
1612 - include: preprocessor-macro-define
1613 - include: scope:source.c#pragma-mark
1614 - include: preprocessor-other
1615
1616 preprocessor-rule-disabled-global:
1617 - match: ^\s*((#if)\s+(0))\b
1618 captures:
1619 1: meta.preprocessor.c++
1620 2: keyword.control.import.c++
1621 3: constant.numeric.preprocessor.c++
1622 push:
1623 - match: ^\s*(#\s*endif)\b
1624 captures:
1625 1: meta.preprocessor.c++ keyword.control.import.c++
1626 pop: true
1627 - match: ^\s*(#\s*else)\b
1628 captures:
1629 1: meta.preprocessor.c++ keyword.control.import.else.c++
1630 push:
1631 - match: (?=^\s*#\s*endif\b)
1632 pop: true
1633 - include: preprocessor-global
1634 - include: negated-block
1635 - include: global
1636 - match: ""
1637 push:
1638 - meta_scope: comment.block.preprocessor.if-branch.c++
1639 - match: (?=^\s*#\s*(else|endif)\b)
1640 pop: true
1641 - include: scope:source.c#preprocessor-disabled
1642
1643 preprocessor-rule-enabled-global:
1644 - match: ^\s*((#if)\s+(0*1))\b
1645 captures:
1646 1: meta.preprocessor.c++
1647 2: keyword.control.import.c++
1648 3: constant.numeric.preprocessor.c++
1649 push:
1650 - match: ^\s*(#\s*endif)\b
1651 captures:
1652 1: meta.preprocessor.c++ keyword.control.import.c++
1653 pop: true
1654 - match: ^\s*(#\s*else)\b
1655 captures:
1656 1: meta.preprocessor.c++ keyword.control.import.else.c++
1657 push:
1658 - meta_content_scope: comment.block.preprocessor.else-branch.c++
1659 - match: (?=^\s*#\s*endif\b)
1660 pop: true
1661 - include: scope:source.c#preprocessor-disabled
1662 - match: ""
1663 push:
1664 - match: (?=^\s*#\s*(else|endif)\b)
1665 pop: true
1666 - include: preprocessor-global
1667 - include: negated-block
1668 - include: global
1669
1670 preprocessor-rule-other-global:
1671 - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
1672 captures:
1673 1: keyword.control.import.c++
1674 push:
1675 - meta_scope: meta.preprocessor.c++
1676 - include: scope:source.c#preprocessor-line-continuation
1677 - include: scope:source.c#preprocessor-comments
1678 - match: \bdefined\b
1679 scope: keyword.control.c++
1680 # Enter a new scope where all elif/else branches have their
1681 # contexts popped by a subsequent elif/else/endif. This ensures that
1682 # preprocessor branches don't push multiple meta.block scopes on
1683 # the stack, thus messing up the "global" context's detection of
1684 # functions.
1685 - match: $\n
1686 set: preprocessor-if-branch-global
1687
1688 # These gymnastics here ensure that we are properly handling scope even
1689 # when the preprocessor is used to create different scope beginnings, such
1690 # as a different if/while condition
1691 preprocessor-if-branch-global:
1692 - match: ^\s*(#\s*endif)\b
1693 captures:
1694 1: meta.preprocessor.c++ keyword.control.import.c++
1695 pop: true
1696 - match: (?=^\s*#\s*(elif|else)\b)
1697 push: preprocessor-elif-else-branch-global
1698 - match: \{
1699 scope: punctuation.section.block.begin.c++
1700 set: preprocessor-block-if-branch-global
1701 - include: preprocessor-global
1702 - include: negated-block
1703 - include: global
1704
1705 preprocessor-block-if-branch-global:
1706 - meta_scope: meta.block.c++
1707 - match: ^\s*(#\s*endif)\b
1708 captures:
1709 1: meta.preprocessor.c++ keyword.control.import.c++
1710 set: preprocessor-block-finish-global
1711 - match: (?=^\s*#\s*(elif|else)\b)
1712 push: preprocessor-elif-else-branch-global
1713 - match: \}
1714 scope: punctuation.section.block.end.c++
1715 set: preprocessor-if-branch-global
1716 - include: statements
1717
1718 preprocessor-block-finish-global:
1719 - meta_scope: meta.block.c++
1720 - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
1721 captures:
1722 1: meta.preprocessor.c++ keyword.control.import.c++
1723 set: preprocessor-block-finish-if-branch-global
1724 - match: \}
1725 scope: punctuation.section.block.end.c++
1726 pop: true
1727 - include: statements
1728
1729 preprocessor-block-finish-if-branch-global:
1730 - match: ^\s*(#\s*endif)\b
1731 captures:
1732 1: keyword.control.import.c++
1733 pop: true
1734 - match: \}
1735 scope: punctuation.section.block.end.c++
1736 set: preprocessor-if-branch-global
1737 - include: statements
1738
1739 preprocessor-elif-else-branch-global:
1740 - match: (?=^\s*#\s*(endif)\b)
1741 pop: true
1742 - include: preprocessor-global
1743 - include: negated-block
1744 - include: global
1745
1746 ## Preprocessor for statements
1747
1748 preprocessor-rule-disabled-statements:
1749 - match: ^\s*((#if)\s+(0))\b
1750 captures:
1751 1: meta.preprocessor.c++
1752 2: keyword.control.import.c++
1753 3: constant.numeric.preprocessor.c++
1754 push:
1755 - match: ^\s*(#\s*endif)\b
1756 captures:
1757 1: meta.preprocessor.c++ keyword.control.import.c++
1758 pop: true
1759 - match: ^\s*(#\s*else)\b
1760 captures:
1761 1: meta.preprocessor.c++ keyword.control.import.else.c++
1762 push:
1763 - match: (?=^\s*#\s*endif\b)
1764 pop: true
1765 - include: negated-block
1766 - include: statements
1767 - match: ""
1768 push:
1769 - meta_scope: comment.block.preprocessor.if-branch.c++
1770 - match: (?=^\s*#\s*(else|endif)\b)
1771 pop: true
1772 - include: scope:source.c#preprocessor-disabled
1773
1774 preprocessor-rule-enabled-statements:
1775 - match: ^\s*((#if)\s+(0*1))\b
1776 captures:
1777 1: meta.preprocessor.c++
1778 2: keyword.control.import.c++
1779 3: constant.numeric.preprocessor.c++
1780 push:
1781 - match: ^\s*(#\s*endif)\b
1782 captures:
1783 1: meta.preprocessor.c++ keyword.control.import.c++
1784 pop: true
1785 - match: ^\s*(#\s*else)\b
1786 captures:
1787 1: meta.preprocessor.c++ keyword.control.import.else.c++
1788 push:
1789 - meta_content_scope: comment.block.preprocessor.else-branch.c++
1790 - match: (?=^\s*#\s*endif\b)
1791 pop: true
1792 - include: scope:source.c#preprocessor-disabled
1793 - match: ""
1794 push:
1795 - match: (?=^\s*#\s*(else|endif)\b)
1796 pop: true
1797 - include: negated-block
1798 - include: statements
1799
1800 preprocessor-rule-other-statements:
1801 - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
1802 captures:
1803 1: keyword.control.import.c++
1804 push:
1805 - meta_scope: meta.preprocessor.c++
1806 - include: scope:source.c#preprocessor-line-continuation
1807 - include: scope:source.c#preprocessor-comments
1808 - match: \bdefined\b
1809 scope: keyword.control.c++
1810 # Enter a new scope where all elif/else branches have their
1811 # contexts popped by a subsequent elif/else/endif. This ensures that
1812 # preprocessor branches don't push multiple meta.block scopes on
1813 # the stack, thus messing up the "global" context's detection of
1814 # functions.
1815 - match: $\n
1816 set: preprocessor-if-branch-statements
1817
1818 # These gymnastics here ensure that we are properly handling scope even
1819 # when the preprocessor is used to create different scope beginnings, such
1820 # as a different if/while condition
1821 preprocessor-if-branch-statements:
1822 - match: ^\s*(#\s*endif)\b
1823 captures:
1824 1: meta.preprocessor.c++ keyword.control.import.c++
1825 pop: true
1826 - match: (?=^\s*#\s*(elif|else)\b)
1827 push: preprocessor-elif-else-branch-statements
1828 - match: \{
1829 scope: punctuation.section.block.begin.c++
1830 set: preprocessor-block-if-branch-statements
1831 - match: (?=(?!{{non_func_keywords}}){{path_lookahead}}\s*\()
1832 set: preprocessor-if-branch-function-call
1833 - include: negated-block
1834 - include: statements
1835
1836 preprocessor-if-branch-function-call:
1837 - meta_content_scope: meta.function-call.c++
1838 - include: scope:source.c#c99
1839 - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*'
1840 scope: variable.function.c++
1841 captures:
1842 1: punctuation.accessor.c++
1843 2: punctuation.accessor.c++
1844 - match: '(?:(::)\s*)?{{identifier}}'
1845 scope: variable.function.c++
1846 captures:
1847 1: punctuation.accessor.c++
1848 - match: '\('
1849 scope: meta.group.c++ punctuation.section.group.begin.c++
1850 set: preprocessor-if-branch-function-call-arguments
1851
1852 preprocessor-if-branch-function-call-arguments:
1853 - meta_content_scope: meta.function-call.c++ meta.group.c++
1854 - match : \)
1855 scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
1856 set: preprocessor-if-branch-statements
1857 - match: ^\s*(#\s*(?:elif|else))\b
1858 captures:
1859 1: meta.preprocessor.c++ keyword.control.import.c++
1860 set: preprocessor-if-branch-statements
1861 - match: ^\s*(#\s*endif)\b
1862 captures:
1863 1: meta.preprocessor.c++ keyword.control.import.c++
1864 set: preprocessor-if-branch-function-call-arguments-finish
1865 - include: expressions
1866
1867 preprocessor-if-branch-function-call-arguments-finish:
1868 - meta_content_scope: meta.function-call.c++ meta.group.c++
1869 - match: \)
1870 scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
1871 pop: true
1872 - include: expressions
1873
1874 preprocessor-block-if-branch-statements:
1875 - meta_scope: meta.block.c++
1876 - match: ^\s*(#\s*endif)\b
1877 captures:
1878 1: meta.preprocessor.c++ keyword.control.import.c++
1879 set: preprocessor-block-finish-statements
1880 - match: (?=^\s*#\s*(elif|else)\b)
1881 push: preprocessor-elif-else-branch-statements
1882 - match: \}
1883 scope: punctuation.section.block.end.c++
1884 set: preprocessor-if-branch-statements
1885 - include: statements
1886
1887 preprocessor-block-finish-statements:
1888 - meta_scope: meta.block.c++
1889 - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
1890 captures:
1891 1: meta.preprocessor.c++ keyword.control.import.c++
1892 set: preprocessor-block-finish-if-branch-statements
1893 - match: \}
1894 scope: punctuation.section.block.end.c++
1895 pop: true
1896 - include: statements
1897
1898 preprocessor-block-finish-if-branch-statements:
1899 - match: ^\s*(#\s*endif)\b
1900 captures:
1901 1: keyword.control.import.c++
1902 pop: true
1903 - match: \}
1904 scope: meta.block.c++ punctuation.section.block.end.c++
1905 set: preprocessor-if-branch-statements
1906 - include: statements
1907
1908 preprocessor-elif-else-branch-statements:
1909 - match: (?=^\s*#\s*endif\b)
1910 pop: true
1911 - include: negated-block
1912 - include: statements
1913
1914 ## Preprocessor other
1915
1916 negated-block:
1917 - match: '\}'
1918 scope: punctuation.section.block.end.c++
1919 push:
1920 - match: '\{'
1921 scope: punctuation.section.block.begin.c++
1922 pop: true
1923 - match: (?=^\s*#\s*(elif|else|endif)\b)
1924 pop: true
1925 - include: statements
1926
1927 preprocessor-macro-define:
1928 - match: ^\s*(\#\s*define)\b
1929 captures:
1930 1: meta.preprocessor.macro.c++ keyword.control.import.define.c++
1931 push:
1932 - meta_content_scope: meta.preprocessor.macro.c++
1933 - include: scope:source.c#preprocessor-line-continuation
1934 - include: scope:source.c#preprocessor-line-ending
1935 - include: scope:source.c#preprocessor-comments
1936 - match: '({{identifier}})(?=\()'
1937 scope: entity.name.function.preprocessor.c++
1938 set:
1939 - match: '\('
1940 scope: punctuation.section.group.begin.c++
1941 set: preprocessor-macro-params
1942 - match: '{{identifier}}'
1943 scope: entity.name.constant.preprocessor.c++
1944 set: preprocessor-macro-definition
1945
1946 preprocessor-macro-params:
1947 - meta_scope: meta.preprocessor.macro.parameters.c++ meta.group.c++
1948 - match: '{{identifier}}'
1949 scope: variable.parameter.c++
1950 - match: \)
1951 scope: punctuation.section.group.end.c++
1952 set: preprocessor-macro-definition
1953 - match: ','
1954 scope: punctuation.separator.c++
1955 push:
1956 - match: '{{identifier}}'
1957 scope: variable.parameter.c++
1958 pop: true
1959 - include: scope:source.c#preprocessor-line-continuation
1960 - include: scope:source.c#preprocessor-comments
1961 - match: '\.\.\.'
1962 scope: keyword.operator.variadic.c++
1963 - match: '(?=\))'
1964 pop: true
1965 - match: (/\*).*(\*/)
1966 scope: comment.block.c++
1967 captures:
1968 1: punctuation.definition.comment.c++
1969 2: punctuation.definition.comment.c++
1970 - match: '\S+'
1971 scope: invalid.illegal.unexpected-character.c++
1972 - include: scope:source.c#preprocessor-line-continuation
1973 - include: scope:source.c#preprocessor-comments
1974 - match: '\.\.\.'
1975 scope: keyword.operator.variadic.c++
1976 - match: (/\*).*(\*/)
1977 scope: comment.block.c++
1978 captures:
1979 1: punctuation.definition.comment.c++
1980 2: punctuation.definition.comment.c++
1981 - match: $\n
1982 scope: invalid.illegal.unexpected-end-of-line.c++
1983
1984 preprocessor-macro-definition:
1985 - meta_content_scope: meta.preprocessor.macro.c++
1986 - include: scope:source.c#preprocessor-line-continuation
1987 - include: scope:source.c#preprocessor-line-ending
1988 - include: scope:source.c#preprocessor-comments
1989 # Don't define blocks in define statements
1990 - match: '\{'
1991 scope: punctuation.section.block.begin.c++
1992 - match: '\}'
1993 scope: punctuation.section.block.end.c++
1994 - include: expressions
1995
1996 preprocessor-practical-workarounds:
1997 - include: preprocessor-convention-ignore-uppercase-ident-lines
1998 - include: scope:source.c#preprocessor-convention-ignore-uppercase-calls-without-semicolon
1999
2000 preprocessor-convention-ignore-uppercase-ident-lines:
2001 - match: ^(\s*{{macro_identifier}})+\s*$
2002 scope: meta.assumed-macro.c++
2003 push:
2004 # It's possible that we are dealing with a function return type on its own line, and the
2005 # name of the function is on the subsequent line.
2006 - match: '(?={{path_lookahead}}({{generic_lookahead}}({{path_lookahead}})?)\s*\()'
2007 set: [function-definition-params, global-function-identifier-generic]
2008 - match: '(?={{path_lookahead}}\s*\()'
2009 set: [function-definition-params, global-function-identifier]
2010 - match: ^
2011 pop: true
2012
2013 preprocessor-other:
2014 - match: ^\s*(#\s*(?:if|ifdef|ifndef|elif|else|line|pragma|undef))\b
2015 captures:
2016 1: keyword.control.import.c++
2017 push:
2018 - meta_scope: meta.preprocessor.c++
2019 - include: scope:source.c#preprocessor-line-continuation
2020 - include: scope:source.c#preprocessor-line-ending
2021 - include: scope:source.c#preprocessor-comments
2022 - match: \bdefined\b
2023 scope: keyword.control.c++
2024 - match: ^\s*(#\s*endif)\b
2025 captures:
2026 1: meta.preprocessor.c++ keyword.control.import.c++
2027 - match: ^\s*(#\s*(?:error|warning))\b
2028 captures:
2029 1: keyword.control.import.error.c++
2030 push:
2031 - meta_scope: meta.preprocessor.diagnostic.c++
2032 - include: scope:source.c#preprocessor-line-continuation
2033 - include: scope:source.c#preprocessor-line-ending
2034 - include: scope:source.c#preprocessor-comments
2035 - include: strings
2036 - match: '\S+'
2037 scope: string.unquoted.c++
2038 - match: ^\s*(#\s*(?:include|include_next|import))\b
2039 captures:
2040 1: keyword.control.import.include.c++
2041 push:
2042 - meta_scope: meta.preprocessor.include.c++
2043 - include: scope:source.c#preprocessor-line-continuation
2044 - include: scope:source.c#preprocessor-line-ending
2045 - include: scope:source.c#preprocessor-comments
2046 - match: '"'
2047 scope: punctuation.definition.string.begin.c++
2048 push:
2049 - meta_scope: string.quoted.double.include.c++
2050 - match: '"'
2051 scope: punctuation.definition.string.end.c++
2052 pop: true
2053 - match: <
2054 scope: punctuation.definition.string.begin.c++
2055 push:
2056 - meta_scope: string.quoted.other.lt-gt.include.c++
2057 - match: '>'
2058 scope: punctuation.definition.string.end.c++
2059 pop: true
2060 - include: preprocessor-practical-workarounds
+0
-4
source/misc/embedded_libs/fmt-8.1.1/support/README less more
0 This directory contains build support files such as
1
2 * CMake modules
3 * Build scripts
+0
-20
source/misc/embedded_libs/fmt-8.1.1/support/Vagrantfile less more
0 # -*- mode: ruby -*-
1 # vi: set ft=ruby :
2
3 # A vagrant config for testing against gcc-4.8.
4 Vagrant.configure("2") do |config|
5 config.vm.box = "ubuntu/xenial64"
6 config.disksize.size = '15GB'
7
8 config.vm.provider "virtualbox" do |vb|
9 vb.memory = "4096"
10 end
11
12 config.vm.provision "shell", inline: <<-SHELL
13 apt-get update
14 apt-get install -y g++ make wget git
15 wget -q https://github.com/Kitware/CMake/releases/download/v3.14.4/cmake-3.14.4-Linux-x86_64.tar.gz
16 tar xzf cmake-3.14.4-Linux-x86_64.tar.gz
17 ln -s `pwd`/cmake-3.14.4-Linux-x86_64/bin/cmake /usr/local/bin
18 SHELL
19 end
+0
-43
source/misc/embedded_libs/fmt-8.1.1/support/appveyor-build.py less more
0 #!/usr/bin/env python
1 # Build the project on AppVeyor.
2
3 import os
4 from subprocess import check_call
5
6 build = os.environ['BUILD']
7 config = os.environ['CONFIGURATION']
8 platform = os.environ['PLATFORM']
9 path = os.environ['PATH']
10 image = os.environ['APPVEYOR_BUILD_WORKER_IMAGE']
11 jobid = os.environ['APPVEYOR_JOB_ID']
12 cmake_command = ['cmake', '-DFMT_PEDANTIC=ON', '-DCMAKE_BUILD_TYPE=' + config, '..']
13 if build == 'mingw':
14 cmake_command.append('-GMinGW Makefiles')
15 build_command = ['mingw32-make', '-j4']
16 test_command = ['mingw32-make', 'test']
17 # Remove the path to Git bin directory from $PATH because it breaks
18 # MinGW config.
19 path = path.replace(r'C:\Program Files (x86)\Git\bin', '')
20 os.environ['PATH'] = r'C:\MinGW\bin;' + path
21 else:
22 # Add MSBuild 14.0 to PATH as described in
23 # http://help.appveyor.com/discussions/problems/2229-v140-not-found-on-vs2105rc.
24 os.environ['PATH'] = r'C:\Program Files (x86)\MSBuild\15.0\Bin;' + path
25 if image == 'Visual Studio 2019':
26 generator = 'Visual Studio 16 2019'
27 if platform == 'x64':
28 cmake_command.extend(['-A', 'x64'])
29 else:
30 if image == 'Visual Studio 2015':
31 generator = 'Visual Studio 14 2015'
32 elif image == 'Visual Studio 2017':
33 generator = 'Visual Studio 15 2017'
34 if platform == 'x64':
35 generator += ' Win64'
36 cmake_command.append('-G' + generator)
37 build_command = ['cmake', '--build', '.', '--config', config, '--', '/m:4']
38 test_command = ['ctest', '-C', config]
39
40 check_call(cmake_command)
41 check_call(build_command)
42 check_call(test_command)
+0
-31
source/misc/embedded_libs/fmt-8.1.1/support/appveyor.yml less more
0 configuration:
1 - Debug
2 - Release
3
4 clone_depth: 1
5
6 image:
7 - Visual Studio 2015
8
9 platform:
10 - x64
11
12 environment:
13 CTEST_OUTPUT_ON_FAILURE: 1
14 MSVC_DEFAULT_OPTIONS: ON
15 BUILD: msvc
16
17 before_build:
18 - mkdir build
19 - cd build
20
21 build_script:
22 - python ../support/appveyor-build.py
23
24 on_failure:
25 - appveyor PushArtifact Testing/Temporary/LastTest.log
26 - appveyor AddTest test
27
28 # Uncomment this to debug AppVeyor failures.
29 #on_finish:
30 # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
+0
-29
source/misc/embedded_libs/fmt-8.1.1/support/bazel/BUILD.bazel less more
0 cc_library(
1 name = "fmt",
2 srcs = [
3 #"src/fmt.cc", # No C++ module support
4 "src/format.cc",
5 "src/os.cc",
6 ],
7 hdrs = [
8 "include/fmt/args.h",
9 "include/fmt/chrono.h",
10 "include/fmt/color.h",
11 "include/fmt/compile.h",
12 "include/fmt/core.h",
13 "include/fmt/format.h",
14 "include/fmt/format-inl.h",
15 "include/fmt/locale.h",
16 "include/fmt/os.h",
17 "include/fmt/ostream.h",
18 "include/fmt/printf.h",
19 "include/fmt/ranges.h",
20 "include/fmt/xchar.h",
21 ],
22 includes = [
23 "include",
24 "src",
25 ],
26 strip_include_prefix = "include",
27 visibility = ["//visibility:public"],
28 )
+0
-73
source/misc/embedded_libs/fmt-8.1.1/support/bazel/README.md less more
0 # Bazel support
1
2 To get [Bazel](https://bazel.build/) working with {fmt} you can copy the files `BUILD.bazel`, `WORKSPACE.bazel`, `.bazelrc`, 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}).
3
4 ## Using {fmt} as a dependency
5
6 The following minimal example shows how to use {fmt} as a dependency within a Bazel project.
7
8 The following file structure is assumed:
9
10 ```
11 example
12 ├── BUILD.bazel
13 ├── main.cpp
14 └── WORKSPACE.bazel
15 ```
16
17 *main.cpp*:
18
19 ```c++
20 #include "fmt/core.h"
21
22 int main() {
23 fmt::print("The answer is {}\n", 42);
24 }
25 ```
26
27 The expected output of this example is `The answer is 42`.
28
29 *WORKSPACE.bazel*:
30
31 ```python
32 load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
33
34 git_repository(
35 name = "fmt",
36 branch = "master",
37 remote = "https://github.com/fmtlib/fmt",
38 patch_cmds = [
39 "mv support/bazel/.bazelrc .bazelrc",
40 "mv support/bazel/.bazelversion .bazelversion",
41 "mv support/bazel/BUILD.bazel BUILD.bazel",
42 "mv support/bazel/WORKSPACE.bazel WORKSPACE.bazel",
43 ],
44 # Windows-related patch commands are only needed in the case MSYS2 is not installed.
45 # More details about the installation process of MSYS2 on Windows systems can be found here:
46 # https://docs.bazel.build/versions/main/install-windows.html#installing-compilers-and-language-runtimes
47 # Even if MSYS2 is installed the Windows related patch commands can still be used.
48 patch_cmds_win = [
49 "Move-Item -Path support/bazel/.bazelrc -Destination .bazelrc",
50 "Move-Item -Path support/bazel/.bazelversion -Destination .bazelversion",
51 "Move-Item -Path support/bazel/BUILD.bazel -Destination BUILD.bazel",
52 "Move-Item -Path support/bazel/WORKSPACE.bazel -Destination WORKSPACE.bazel",
53 ],
54 )
55 ```
56
57 In the *WORKSPACE* file, the {fmt} GitHub repository is fetched. Using the attribute `patch_cmds` the files `BUILD.bazel`, `WORKSPACE.bazel`, `.bazelrc`, and `.bazelversion` are moved to the root of the {fmt} repository. This way the {fmt} repository is recognized as a bazelized workspace.
58
59 *BUILD.bazel*:
60
61 ```python
62 cc_binary(
63 name = "Demo",
64 srcs = ["main.cpp"],
65 deps = ["@fmt"],
66 )
67 ```
68
69 The *BUILD* file defines a binary named `Demo` that has a dependency to {fmt}.
70
71 To execute the binary you can run `bazel run //:Demo`.
72
+0
-1
source/misc/embedded_libs/fmt-8.1.1/support/bazel/WORKSPACE.bazel less more
0 workspace(name = "fmt")
+0
-58
source/misc/embedded_libs/fmt-8.1.1/support/build-docs.py less more
0 #!/usr/bin/env python
1 # Build the documentation in CI.
2
3 from __future__ import print_function
4 import errno, os, shutil, subprocess, sys, urllib
5 from subprocess import call, check_call, Popen, PIPE, STDOUT
6
7 def rmtree_if_exists(dir):
8 try:
9 shutil.rmtree(dir)
10 except OSError as e:
11 if e.errno == errno.ENOENT:
12 pass
13
14 # Build the docs.
15 fmt_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
16 sys.path.insert(0, os.path.join(fmt_dir, 'doc'))
17 import build
18 build.create_build_env()
19 html_dir = build.build_docs()
20
21 repo = 'fmtlib.github.io'
22 branch = os.environ['GITHUB_REF']
23 is_ci = 'CI' in os.environ
24 if is_ci and branch != 'refs/heads/master':
25 print('Branch: ' + branch)
26 exit(0) # Ignore non-master branches
27 if is_ci and 'KEY' not in os.environ:
28 # Don't update the repo if building in CI from an account that doesn't have
29 # push access.
30 print('Skipping update of ' + repo)
31 exit(0)
32
33 # Clone the fmtlib.github.io repo.
34 rmtree_if_exists(repo)
35 git_url = 'https://github.com/' if is_ci else 'git@github.com:'
36 check_call(['git', 'clone', git_url + 'fmtlib/{}.git'.format(repo)])
37
38 # Copy docs to the repo.
39 target_dir = os.path.join(repo, 'dev')
40 rmtree_if_exists(target_dir)
41 shutil.copytree(html_dir, target_dir, ignore=shutil.ignore_patterns('.*'))
42 if is_ci:
43 check_call(['git', 'config', '--global', 'user.name', 'fmtbot'])
44 check_call(['git', 'config', '--global', 'user.email', 'viz@fmt.dev'])
45
46 # Push docs to GitHub pages.
47 check_call(['git', 'add', '--all'], cwd=repo)
48 if call(['git', 'diff-index', '--quiet', 'HEAD'], cwd=repo):
49 check_call(['git', 'commit', '-m', 'Update documentation'], cwd=repo)
50 cmd = 'git push'
51 if is_ci:
52 cmd += ' https://$KEY@github.com/fmtlib/fmtlib.github.io.git master'
53 p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, cwd=repo)
54 # Print the output without the key.
55 print(p.communicate()[0].decode('utf-8').replace(os.environ['KEY'], '$KEY'))
56 if p.returncode != 0:
57 raise subprocess.CalledProcessError(p.returncode, cmd)
+0
-132
source/misc/embedded_libs/fmt-8.1.1/support/build.gradle less more
0 import java.nio.file.Paths
1
2 // General gradle arguments for root project
3 buildscript {
4 repositories {
5 google()
6 jcenter()
7 }
8 dependencies {
9 //
10 // https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
11 //
12 // Notice that 4.0.0 here is the version of [Android Gradle Plugin]
13 // Accroding to URL above you will need Gradle 6.1 or higher
14 //
15 classpath "com.android.tools.build:gradle:4.1.1"
16 }
17 }
18 repositories {
19 google()
20 jcenter()
21 }
22
23 // Project's root where CMakeLists.txt exists: rootDir/support/.cxx -> rootDir
24 def rootDir = Paths.get(project.buildDir.getParent()).getParent()
25 println("rootDir: ${rootDir}")
26
27 // Output: Shared library (.so) for Android
28 apply plugin: "com.android.library"
29 android {
30 compileSdkVersion 25 // Android 7.0
31
32 // Target ABI
33 // - This option controls target platform of module
34 // - The platform might be limited by compiler's support
35 // some can work with Clang(default), but some can work only with GCC...
36 // if bad, both toolchains might not support it
37 splits {
38 abi {
39 enable true
40 // Specify platforms for Application
41 reset()
42 include "arm64-v8a", "armeabi-v7a", "x86_64"
43 }
44 }
45 ndkVersion "21.3.6528147" // ANDROID_NDK_HOME is deprecated. Be explicit
46
47 defaultConfig {
48 minSdkVersion 21 // Android 5.0+
49 targetSdkVersion 25 // Follow Compile SDK
50 versionCode 34 // Follow release count
51 versionName "7.1.2" // Follow Official version
52
53 externalNativeBuild {
54 cmake {
55 arguments "-DANDROID_STL=c++_shared" // Specify Android STL
56 arguments "-DBUILD_SHARED_LIBS=true" // Build shared object
57 arguments "-DFMT_TEST=false" // Skip test
58 arguments "-DFMT_DOC=false" // Skip document
59 cppFlags "-std=c++17"
60 targets "fmt"
61 }
62 }
63 println(externalNativeBuild.cmake.cppFlags)
64 println(externalNativeBuild.cmake.arguments)
65 }
66
67 // External Native build
68 // - Use existing CMakeList.txt
69 // - Give path to CMake. This gradle file should be
70 // neighbor of the top level cmake
71 externalNativeBuild {
72 cmake {
73 version "3.10.0+"
74 path "${rootDir}/CMakeLists.txt"
75 // buildStagingDirectory "./build" // Custom path for cmake output
76 }
77 }
78
79 sourceSets{
80 // Android Manifest for Gradle
81 main {
82 manifest.srcFile "AndroidManifest.xml"
83 }
84 }
85
86 // https://developer.android.com/studio/build/native-dependencies#build_system_configuration
87 buildFeatures {
88 prefab true
89 prefabPublishing true
90 }
91 prefab {
92 fmt {
93 headers "${rootDir}/include"
94 }
95 }
96 }
97
98 assemble.doLast
99 {
100 // Instead of `ninja install`, Gradle will deploy the files.
101 // We are doing this since FMT is dependent to the ANDROID_STL after build
102 copy {
103 from "build/intermediates/cmake"
104 into "${rootDir}/libs"
105 }
106 // Copy debug binaries
107 copy {
108 from "${rootDir}/libs/debug/obj"
109 into "${rootDir}/libs/debug"
110 }
111 // Copy Release binaries
112 copy {
113 from "${rootDir}/libs/release/obj"
114 into "${rootDir}/libs/release"
115 }
116 // Remove empty directory
117 delete "${rootDir}/libs/debug/obj"
118 delete "${rootDir}/libs/release/obj"
119
120 // Copy AAR files. Notice that the aar is named after the folder of this script.
121 copy {
122 from "build/outputs/aar/support-release.aar"
123 into "${rootDir}/libs"
124 rename "support-release.aar", "fmt-release.aar"
125 }
126 copy {
127 from "build/outputs/aar/support-debug.aar"
128 into "${rootDir}/libs"
129 rename "support-debug.aar", "fmt-debug.aar"
130 }
131 }
+0
-7
source/misc/embedded_libs/fmt-8.1.1/support/cmake/FindSetEnv.cmake less more
0 # A CMake script to find SetEnv.cmd.
1
2 find_program(WINSDK_SETENV NAMES SetEnv.cmd
3 PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows;CurrentInstallFolder]/bin")
4 if (WINSDK_SETENV AND PRINT_PATH)
5 execute_process(COMMAND ${CMAKE_COMMAND} -E echo "${WINSDK_SETENV}")
6 endif ()
+0
-26
source/misc/embedded_libs/fmt-8.1.1/support/cmake/JoinPaths.cmake less more
0 # This module provides function for joining paths
1 # known from from most languages
2 #
3 # Original license:
4 # SPDX-License-Identifier: (MIT OR CC0-1.0)
5 # Explicit permission given to distribute this module under
6 # the terms of the project as described in /LICENSE.rst.
7 # Copyright 2020 Jan Tojnar
8 # https://github.com/jtojnar/cmake-snips
9 #
10 # Modelled after Python’s os.path.join
11 # https://docs.python.org/3.7/library/os.path.html#os.path.join
12 # Windows not supported
13 function(join_paths joined_path first_path_segment)
14 set(temp_path "${first_path_segment}")
15 foreach(current_segment IN LISTS ARGN)
16 if(NOT ("${current_segment}" STREQUAL ""))
17 if(IS_ABSOLUTE "${current_segment}")
18 set(temp_path "${current_segment}")
19 else()
20 set(temp_path "${temp_path}/${current_segment}")
21 endif()
22 endif()
23 endforeach()
24 set(${joined_path} "${temp_path}" PARENT_SCOPE)
25 endfunction()
+0
-70
source/misc/embedded_libs/fmt-8.1.1/support/cmake/cxx14.cmake less more
0 # C++14 feature support detection
1
2 include(CheckCXXSourceCompiles)
3 include(CheckCXXCompilerFlag)
4
5 if (NOT CMAKE_CXX_STANDARD)
6 set(CMAKE_CXX_STANDARD 11)
7 endif()
8 message(STATUS "CXX_STANDARD: ${CMAKE_CXX_STANDARD}")
9
10 if (CMAKE_CXX_STANDARD EQUAL 20)
11 check_cxx_compiler_flag(-std=c++20 has_std_20_flag)
12 check_cxx_compiler_flag(-std=c++2a has_std_2a_flag)
13
14 if (has_std_20_flag)
15 set(CXX_STANDARD_FLAG -std=c++20)
16 elseif (has_std_2a_flag)
17 set(CXX_STANDARD_FLAG -std=c++2a)
18 endif ()
19 elseif (CMAKE_CXX_STANDARD EQUAL 17)
20 check_cxx_compiler_flag(-std=c++17 has_std_17_flag)
21 check_cxx_compiler_flag(-std=c++1z has_std_1z_flag)
22
23 if (has_std_17_flag)
24 set(CXX_STANDARD_FLAG -std=c++17)
25 elseif (has_std_1z_flag)
26 set(CXX_STANDARD_FLAG -std=c++1z)
27 endif ()
28 elseif (CMAKE_CXX_STANDARD EQUAL 14)
29 check_cxx_compiler_flag(-std=c++14 has_std_14_flag)
30 check_cxx_compiler_flag(-std=c++1y has_std_1y_flag)
31
32 if (has_std_14_flag)
33 set(CXX_STANDARD_FLAG -std=c++14)
34 elseif (has_std_1y_flag)
35 set(CXX_STANDARD_FLAG -std=c++1y)
36 endif ()
37 elseif (CMAKE_CXX_STANDARD EQUAL 11)
38 check_cxx_compiler_flag(-std=c++11 has_std_11_flag)
39 check_cxx_compiler_flag(-std=c++0x has_std_0x_flag)
40
41 if (has_std_11_flag)
42 set(CXX_STANDARD_FLAG -std=c++11)
43 elseif (has_std_0x_flag)
44 set(CXX_STANDARD_FLAG -std=c++0x)
45 endif ()
46 endif ()
47
48 set(CMAKE_REQUIRED_FLAGS ${CXX_STANDARD_FLAG})
49
50 # Check if user-defined literals are available
51 check_cxx_source_compiles("
52 void operator\"\" _udl(long double);
53 int main() {}"
54 SUPPORTS_USER_DEFINED_LITERALS)
55 if (NOT SUPPORTS_USER_DEFINED_LITERALS)
56 set (SUPPORTS_USER_DEFINED_LITERALS OFF)
57 endif ()
58
59 # Check if <variant> is available
60 set(CMAKE_REQUIRED_FLAGS -std=c++1z)
61 check_cxx_source_compiles("
62 #include <variant>
63 int main() {}"
64 FMT_HAS_VARIANT)
65 if (NOT FMT_HAS_VARIANT)
66 set (FMT_HAS_VARIANT OFF)
67 endif ()
68
69 set(CMAKE_REQUIRED_FLAGS )
+0
-4
source/misc/embedded_libs/fmt-8.1.1/support/cmake/fmt-config.cmake.in less more
0 @PACKAGE_INIT@
1
2 include(${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake)
3 check_required_components(fmt)
+0
-11
source/misc/embedded_libs/fmt-8.1.1/support/cmake/fmt.pc.in less more
0 prefix=@CMAKE_INSTALL_PREFIX@
1 exec_prefix=@CMAKE_INSTALL_PREFIX@
2 libdir=@libdir_for_pc_file@
3 includedir=@includedir_for_pc_file@
4
5 Name: fmt
6 Description: A modern formatting library
7 Version: @FMT_VERSION@
8 Libs: -L${libdir} -l@FMT_LIB_NAME@
9 Cflags: -I${includedir}
10
+0
-53
source/misc/embedded_libs/fmt-8.1.1/support/compute-powers.py less more
0 #!/usr/bin/env python
1 # Compute 10 ** exp with exp in the range [min_exponent, max_exponent] and print
2 # normalized (with most-significant bit equal to 1) significands in hexadecimal.
3
4 from __future__ import print_function
5
6 min_exponent = -348
7 max_exponent = 340
8 step = 8
9 significand_size = 64
10 exp_offset = 2000
11
12 class fp:
13 pass
14
15 powers = []
16 for i, exp in enumerate(range(min_exponent, max_exponent + 1, step)):
17 result = fp()
18 n = 10 ** exp if exp >= 0 else 2 ** exp_offset / 10 ** -exp
19 k = significand_size + 1
20 # Convert to binary and round.
21 binary = '{:b}'.format(n)
22 result.f = (int('{:0<{}}'.format(binary[:k], k), 2) + 1) / 2
23 result.e = len(binary) - (exp_offset if exp < 0 else 0) - significand_size
24 powers.append(result)
25 # Sanity check.
26 exp_offset10 = 400
27 actual = result.f * 10 ** exp_offset10
28 if result.e > 0:
29 actual *= 2 ** result.e
30 else:
31 for j in range(-result.e):
32 actual /= 2
33 expected = 10 ** (exp_offset10 + exp)
34 precision = len('{}'.format(expected)) - len('{}'.format(actual - expected))
35 if precision < 19:
36 print('low precision:', precision)
37 exit(1)
38
39 print('Significands:', end='')
40 for i, fp in enumerate(powers):
41 if i % 3 == 0:
42 print(end='\n ')
43 print(' {:0<#16x}'.format(fp.f, ), end=',')
44
45 print('\n\nExponents:', end='')
46 for i, fp in enumerate(powers):
47 if i % 11 == 0:
48 print(end='\n ')
49 print(' {:5}'.format(fp.e), end=',')
50
51 print('\n\nMax exponent difference:',
52 max([x.e - powers[i - 1].e for i, x in enumerate(powers)][1:]))
+0
-581
source/misc/embedded_libs/fmt-8.1.1/support/docopt.py less more
0 """Pythonic command-line interface parser that will make you smile.
1
2 * http://docopt.org
3 * Repository and issue-tracker: https://github.com/docopt/docopt
4 * Licensed under terms of MIT license (see LICENSE-MIT)
5 * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
6
7 """
8 import sys
9 import re
10
11
12 __all__ = ['docopt']
13 __version__ = '0.6.1'
14
15
16 class DocoptLanguageError(Exception):
17
18 """Error in construction of usage-message by developer."""
19
20
21 class DocoptExit(SystemExit):
22
23 """Exit in case user invoked program with incorrect arguments."""
24
25 usage = ''
26
27 def __init__(self, message=''):
28 SystemExit.__init__(self, (message + '\n' + self.usage).strip())
29
30
31 class Pattern(object):
32
33 def __eq__(self, other):
34 return repr(self) == repr(other)
35
36 def __hash__(self):
37 return hash(repr(self))
38
39 def fix(self):
40 self.fix_identities()
41 self.fix_repeating_arguments()
42 return self
43
44 def fix_identities(self, uniq=None):
45 """Make pattern-tree tips point to same object if they are equal."""
46 if not hasattr(self, 'children'):
47 return self
48 uniq = list(set(self.flat())) if uniq is None else uniq
49 for i, child in enumerate(self.children):
50 if not hasattr(child, 'children'):
51 assert child in uniq
52 self.children[i] = uniq[uniq.index(child)]
53 else:
54 child.fix_identities(uniq)
55
56 def fix_repeating_arguments(self):
57 """Fix elements that should accumulate/increment values."""
58 either = [list(child.children) for child in transform(self).children]
59 for case in either:
60 for e in [child for child in case if case.count(child) > 1]:
61 if type(e) is Argument or type(e) is Option and e.argcount:
62 if e.value is None:
63 e.value = []
64 elif type(e.value) is not list:
65 e.value = e.value.split()
66 if type(e) is Command or type(e) is Option and e.argcount == 0:
67 e.value = 0
68 return self
69
70
71 def transform(pattern):
72 """Expand pattern into an (almost) equivalent one, but with single Either.
73
74 Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
75 Quirks: [-a] => (-a), (-a...) => (-a -a)
76
77 """
78 result = []
79 groups = [[pattern]]
80 while groups:
81 children = groups.pop(0)
82 parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]
83 if any(t in map(type, children) for t in parents):
84 child = [c for c in children if type(c) in parents][0]
85 children.remove(child)
86 if type(child) is Either:
87 for c in child.children:
88 groups.append([c] + children)
89 elif type(child) is OneOrMore:
90 groups.append(child.children * 2 + children)
91 else:
92 groups.append(child.children + children)
93 else:
94 result.append(children)
95 return Either(*[Required(*e) for e in result])
96
97
98 class LeafPattern(Pattern):
99
100 """Leaf/terminal node of a pattern tree."""
101
102 def __init__(self, name, value=None):
103 self.name, self.value = name, value
104
105 def __repr__(self):
106 return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value)
107
108 def flat(self, *types):
109 return [self] if not types or type(self) in types else []
110
111 def match(self, left, collected=None):
112 collected = [] if collected is None else collected
113 pos, match = self.single_match(left)
114 if match is None:
115 return False, left, collected
116 left_ = left[:pos] + left[pos + 1:]
117 same_name = [a for a in collected if a.name == self.name]
118 if type(self.value) in (int, list):
119 if type(self.value) is int:
120 increment = 1
121 else:
122 increment = ([match.value] if type(match.value) is str
123 else match.value)
124 if not same_name:
125 match.value = increment
126 return True, left_, collected + [match]
127 same_name[0].value += increment
128 return True, left_, collected
129 return True, left_, collected + [match]
130
131
132 class BranchPattern(Pattern):
133
134 """Branch/inner node of a pattern tree."""
135
136 def __init__(self, *children):
137 self.children = list(children)
138
139 def __repr__(self):
140 return '%s(%s)' % (self.__class__.__name__,
141 ', '.join(repr(a) for a in self.children))
142
143 def flat(self, *types):
144 if type(self) in types:
145 return [self]
146 return sum([child.flat(*types) for child in self.children], [])
147
148
149 class Argument(LeafPattern):
150
151 def single_match(self, left):
152 for n, pattern in enumerate(left):
153 if type(pattern) is Argument:
154 return n, Argument(self.name, pattern.value)
155 return None, None
156
157 @classmethod
158 def parse(class_, source):
159 name = re.findall('(<\S*?>)', source)[0]
160 value = re.findall('\[default: (.*)\]', source, flags=re.I)
161 return class_(name, value[0] if value else None)
162
163
164 class Command(Argument):
165
166 def __init__(self, name, value=False):
167 self.name, self.value = name, value
168
169 def single_match(self, left):
170 for n, pattern in enumerate(left):
171 if type(pattern) is Argument:
172 if pattern.value == self.name:
173 return n, Command(self.name, True)
174 else:
175 break
176 return None, None
177
178
179 class Option(LeafPattern):
180
181 def __init__(self, short=None, long=None, argcount=0, value=False):
182 assert argcount in (0, 1)
183 self.short, self.long, self.argcount = short, long, argcount
184 self.value = None if value is False and argcount else value
185
186 @classmethod
187 def parse(class_, option_description):
188 short, long, argcount, value = None, None, 0, False
189 options, _, description = option_description.strip().partition(' ')
190 options = options.replace(',', ' ').replace('=', ' ')
191 for s in options.split():
192 if s.startswith('--'):
193 long = s
194 elif s.startswith('-'):
195 short = s
196 else:
197 argcount = 1
198 if argcount:
199 matched = re.findall('\[default: (.*)\]', description, flags=re.I)
200 value = matched[0] if matched else None
201 return class_(short, long, argcount, value)
202
203 def single_match(self, left):
204 for n, pattern in enumerate(left):
205 if self.name == pattern.name:
206 return n, pattern
207 return None, None
208
209 @property
210 def name(self):
211 return self.long or self.short
212
213 def __repr__(self):
214 return 'Option(%r, %r, %r, %r)' % (self.short, self.long,
215 self.argcount, self.value)
216
217
218 class Required(BranchPattern):
219
220 def match(self, left, collected=None):
221 collected = [] if collected is None else collected
222 l = left
223 c = collected
224 for pattern in self.children:
225 matched, l, c = pattern.match(l, c)
226 if not matched:
227 return False, left, collected
228 return True, l, c
229
230
231 class Optional(BranchPattern):
232
233 def match(self, left, collected=None):
234 collected = [] if collected is None else collected
235 for pattern in self.children:
236 m, left, collected = pattern.match(left, collected)
237 return True, left, collected
238
239
240 class OptionsShortcut(Optional):
241
242 """Marker/placeholder for [options] shortcut."""
243
244
245 class OneOrMore(BranchPattern):
246
247 def match(self, left, collected=None):
248 assert len(self.children) == 1
249 collected = [] if collected is None else collected
250 l = left
251 c = collected
252 l_ = None
253 matched = True
254 times = 0
255 while matched:
256 # could it be that something didn't match but changed l or c?
257 matched, l, c = self.children[0].match(l, c)
258 times += 1 if matched else 0
259 if l_ == l:
260 break
261 l_ = l
262 if times >= 1:
263 return True, l, c
264 return False, left, collected
265
266
267 class Either(BranchPattern):
268
269 def match(self, left, collected=None):
270 collected = [] if collected is None else collected
271 outcomes = []
272 for pattern in self.children:
273 matched, _, _ = outcome = pattern.match(left, collected)
274 if matched:
275 outcomes.append(outcome)
276 if outcomes:
277 return min(outcomes, key=lambda outcome: len(outcome[1]))
278 return False, left, collected
279
280
281 class Tokens(list):
282
283 def __init__(self, source, error=DocoptExit):
284 self += source.split() if hasattr(source, 'split') else source
285 self.error = error
286
287 @staticmethod
288 def from_pattern(source):
289 source = re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source)
290 source = [s for s in re.split('\s+|(\S*<.*?>)', source) if s]
291 return Tokens(source, error=DocoptLanguageError)
292
293 def move(self):
294 return self.pop(0) if len(self) else None
295
296 def current(self):
297 return self[0] if len(self) else None
298
299
300 def parse_long(tokens, options):
301 """long ::= '--' chars [ ( ' ' | '=' ) chars ] ;"""
302 long, eq, value = tokens.move().partition('=')
303 assert long.startswith('--')
304 value = None if eq == value == '' else value
305 similar = [o for o in options if o.long == long]
306 if tokens.error is DocoptExit and similar == []: # if no exact match
307 similar = [o for o in options if o.long and o.long.startswith(long)]
308 if len(similar) > 1: # might be simply specified ambiguously 2+ times?
309 raise tokens.error('%s is not a unique prefix: %s?' %
310 (long, ', '.join(o.long for o in similar)))
311 elif len(similar) < 1:
312 argcount = 1 if eq == '=' else 0
313 o = Option(None, long, argcount)
314 options.append(o)
315 if tokens.error is DocoptExit:
316 o = Option(None, long, argcount, value if argcount else True)
317 else:
318 o = Option(similar[0].short, similar[0].long,
319 similar[0].argcount, similar[0].value)
320 if o.argcount == 0:
321 if value is not None:
322 raise tokens.error('%s must not have an argument' % o.long)
323 else:
324 if value is None:
325 if tokens.current() in [None, '--']:
326 raise tokens.error('%s requires argument' % o.long)
327 value = tokens.move()
328 if tokens.error is DocoptExit:
329 o.value = value if value is not None else True
330 return [o]
331
332
333 def parse_shorts(tokens, options):
334 """shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;"""
335 token = tokens.move()
336 assert token.startswith('-') and not token.startswith('--')
337 left = token.lstrip('-')
338 parsed = []
339 while left != '':
340 short, left = '-' + left[0], left[1:]
341 similar = [o for o in options if o.short == short]
342 if len(similar) > 1:
343 raise tokens.error('%s is specified ambiguously %d times' %
344 (short, len(similar)))
345 elif len(similar) < 1:
346 o = Option(short, None, 0)
347 options.append(o)
348 if tokens.error is DocoptExit:
349 o = Option(short, None, 0, True)
350 else: # why copying is necessary here?
351 o = Option(short, similar[0].long,
352 similar[0].argcount, similar[0].value)
353 value = None
354 if o.argcount != 0:
355 if left == '':
356 if tokens.current() in [None, '--']:
357 raise tokens.error('%s requires argument' % short)
358 value = tokens.move()
359 else:
360 value = left
361 left = ''
362 if tokens.error is DocoptExit:
363 o.value = value if value is not None else True
364 parsed.append(o)
365 return parsed
366
367
368 def parse_pattern(source, options):
369 tokens = Tokens.from_pattern(source)
370 result = parse_expr(tokens, options)
371 if tokens.current() is not None:
372 raise tokens.error('unexpected ending: %r' % ' '.join(tokens))
373 return Required(*result)
374
375
376 def parse_expr(tokens, options):
377 """expr ::= seq ( '|' seq )* ;"""
378 seq = parse_seq(tokens, options)
379 if tokens.current() != '|':
380 return seq
381 result = [Required(*seq)] if len(seq) > 1 else seq
382 while tokens.current() == '|':
383 tokens.move()
384 seq = parse_seq(tokens, options)
385 result += [Required(*seq)] if len(seq) > 1 else seq
386 return [Either(*result)] if len(result) > 1 else result
387
388
389 def parse_seq(tokens, options):
390 """seq ::= ( atom [ '...' ] )* ;"""
391 result = []
392 while tokens.current() not in [None, ']', ')', '|']:
393 atom = parse_atom(tokens, options)
394 if tokens.current() == '...':
395 atom = [OneOrMore(*atom)]
396 tokens.move()
397 result += atom
398 return result
399
400
401 def parse_atom(tokens, options):
402 """atom ::= '(' expr ')' | '[' expr ']' | 'options'
403 | long | shorts | argument | command ;
404 """
405 token = tokens.current()
406 result = []
407 if token in '([':
408 tokens.move()
409 matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
410 result = pattern(*parse_expr(tokens, options))
411 if tokens.move() != matching:
412 raise tokens.error("unmatched '%s'" % token)
413 return [result]
414 elif token == 'options':
415 tokens.move()
416 return [OptionsShortcut()]
417 elif token.startswith('--') and token != '--':
418 return parse_long(tokens, options)
419 elif token.startswith('-') and token not in ('-', '--'):
420 return parse_shorts(tokens, options)
421 elif token.startswith('<') and token.endswith('>') or token.isupper():
422 return [Argument(tokens.move())]
423 else:
424 return [Command(tokens.move())]
425
426
427 def parse_argv(tokens, options, options_first=False):
428 """Parse command-line argument vector.
429
430 If options_first:
431 argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
432 else:
433 argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
434
435 """
436 parsed = []
437 while tokens.current() is not None:
438 if tokens.current() == '--':
439 return parsed + [Argument(None, v) for v in tokens]
440 elif tokens.current().startswith('--'):
441 parsed += parse_long(tokens, options)
442 elif tokens.current().startswith('-') and tokens.current() != '-':
443 parsed += parse_shorts(tokens, options)
444 elif options_first:
445 return parsed + [Argument(None, v) for v in tokens]
446 else:
447 parsed.append(Argument(None, tokens.move()))
448 return parsed
449
450
451 def parse_defaults(doc):
452 defaults = []
453 for s in parse_section('options:', doc):
454 # FIXME corner case "bla: options: --foo"
455 _, _, s = s.partition(':') # get rid of "options:"
456 split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:]
457 split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
458 options = [Option.parse(s) for s in split if s.startswith('-')]
459 defaults += options
460 return defaults
461
462
463 def parse_section(name, source):
464 pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
465 re.IGNORECASE | re.MULTILINE)
466 return [s.strip() for s in pattern.findall(source)]
467
468
469 def formal_usage(section):
470 _, _, section = section.partition(':') # drop "usage:"
471 pu = section.split()
472 return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'
473
474
475 def extras(help, version, options, doc):
476 if help and any((o.name in ('-h', '--help')) and o.value for o in options):
477 print(doc.strip("\n"))
478 sys.exit()
479 if version and any(o.name == '--version' and o.value for o in options):
480 print(version)
481 sys.exit()
482
483
484 class Dict(dict):
485 def __repr__(self):
486 return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items()))
487
488
489 def docopt(doc, argv=None, help=True, version=None, options_first=False):
490 """Parse `argv` based on command-line interface described in `doc`.
491
492 `docopt` creates your command-line interface based on its
493 description that you pass as `doc`. Such description can contain
494 --options, <positional-argument>, commands, which could be
495 [optional], (required), (mutually | exclusive) or repeated...
496
497 Parameters
498 ----------
499 doc : str
500 Description of your command-line interface.
501 argv : list of str, optional
502 Argument vector to be parsed. sys.argv[1:] is used if not
503 provided.
504 help : bool (default: True)
505 Set to False to disable automatic help on -h or --help
506 options.
507 version : any object
508 If passed, the object will be printed if --version is in
509 `argv`.
510 options_first : bool (default: False)
511 Set to True to require options precede positional arguments,
512 i.e. to forbid options and positional arguments intermix.
513
514 Returns
515 -------
516 args : dict
517 A dictionary, where keys are names of command-line elements
518 such as e.g. "--verbose" and "<path>", and values are the
519 parsed values of those elements.
520
521 Example
522 -------
523 >>> from docopt import docopt
524 >>> doc = '''
525 ... Usage:
526 ... my_program tcp <host> <port> [--timeout=<seconds>]
527 ... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
528 ... my_program (-h | --help | --version)
529 ...
530 ... Options:
531 ... -h, --help Show this screen and exit.
532 ... --baud=<n> Baudrate [default: 9600]
533 ... '''
534 >>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
535 >>> docopt(doc, argv)
536 {'--baud': '9600',
537 '--help': False,
538 '--timeout': '30',
539 '--version': False,
540 '<host>': '127.0.0.1',
541 '<port>': '80',
542 'serial': False,
543 'tcp': True}
544
545 See also
546 --------
547 * For video introduction see http://docopt.org
548 * Full documentation is available in README.rst as well as online
549 at https://github.com/docopt/docopt#readme
550
551 """
552 argv = sys.argv[1:] if argv is None else argv
553
554 usage_sections = parse_section('usage:', doc)
555 if len(usage_sections) == 0:
556 raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
557 if len(usage_sections) > 1:
558 raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
559 DocoptExit.usage = usage_sections[0]
560
561 options = parse_defaults(doc)
562 pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
563 # [default] syntax for argument is disabled
564 #for a in pattern.flat(Argument):
565 # same_name = [d for d in arguments if d.name == a.name]
566 # if same_name:
567 # a.value = same_name[0].value
568 argv = parse_argv(Tokens(argv), list(options), options_first)
569 pattern_options = set(pattern.flat(Option))
570 for options_shortcut in pattern.flat(OptionsShortcut):
571 doc_options = parse_defaults(doc)
572 options_shortcut.children = list(set(doc_options) - pattern_options)
573 #if any_options:
574 # options_shortcut.children += [Option(o.short, o.long, o.argcount)
575 # for o in argv if type(o) is Option]
576 extras(help, version, argv, doc)
577 matched, left, collected = pattern.fix().match(argv)
578 if matched and left == []: # better error message if left?
579 return Dict((a.name, a.value) for a in (pattern.flat() + collected))
580 raise DocoptExit()
+0
-297
source/misc/embedded_libs/fmt-8.1.1/support/manage.py less more
0 #!/usr/bin/env python3
1
2 """Manage site and releases.
3
4 Usage:
5 manage.py release [<branch>]
6 manage.py site
7
8 For the release command $FMT_TOKEN should contain a GitHub personal access token
9 obtained from https://github.com/settings/tokens.
10 """
11
12 from __future__ import print_function
13 import datetime, docopt, errno, fileinput, json, os
14 import re, requests, shutil, sys, tempfile
15 from contextlib import contextmanager
16 from distutils.version import LooseVersion
17 from subprocess import check_call
18
19
20 class Git:
21 def __init__(self, dir):
22 self.dir = dir
23
24 def call(self, method, args, **kwargs):
25 return check_call(['git', method] + list(args), **kwargs)
26
27 def add(self, *args):
28 return self.call('add', args, cwd=self.dir)
29
30 def checkout(self, *args):
31 return self.call('checkout', args, cwd=self.dir)
32
33 def clean(self, *args):
34 return self.call('clean', args, cwd=self.dir)
35
36 def clone(self, *args):
37 return self.call('clone', list(args) + [self.dir])
38
39 def commit(self, *args):
40 return self.call('commit', args, cwd=self.dir)
41
42 def pull(self, *args):
43 return self.call('pull', args, cwd=self.dir)
44
45 def push(self, *args):
46 return self.call('push', args, cwd=self.dir)
47
48 def reset(self, *args):
49 return self.call('reset', args, cwd=self.dir)
50
51 def update(self, *args):
52 clone = not os.path.exists(self.dir)
53 if clone:
54 self.clone(*args)
55 return clone
56
57
58 def clean_checkout(repo, branch):
59 repo.clean('-f', '-d')
60 repo.reset('--hard')
61 repo.checkout(branch)
62
63
64 class Runner:
65 def __init__(self, cwd):
66 self.cwd = cwd
67
68 def __call__(self, *args, **kwargs):
69 kwargs['cwd'] = kwargs.get('cwd', self.cwd)
70 check_call(args, **kwargs)
71
72
73 def create_build_env():
74 """Create a build environment."""
75 class Env:
76 pass
77 env = Env()
78
79 # Import the documentation build module.
80 env.fmt_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
81 sys.path.insert(0, os.path.join(env.fmt_dir, 'doc'))
82 import build
83
84 env.build_dir = 'build'
85 env.versions = build.versions
86
87 # Virtualenv and repos are cached to speed up builds.
88 build.create_build_env(os.path.join(env.build_dir, 'virtualenv'))
89
90 env.fmt_repo = Git(os.path.join(env.build_dir, 'fmt'))
91 return env
92
93
94 @contextmanager
95 def rewrite(filename):
96 class Buffer:
97 pass
98 buffer = Buffer()
99 if not os.path.exists(filename):
100 buffer.data = ''
101 yield buffer
102 return
103 with open(filename) as f:
104 buffer.data = f.read()
105 yield buffer
106 with open(filename, 'w') as f:
107 f.write(buffer.data)
108
109
110 fmt_repo_url = 'git@github.com:fmtlib/fmt'
111
112
113 def update_site(env):
114 env.fmt_repo.update(fmt_repo_url)
115
116 doc_repo = Git(os.path.join(env.build_dir, 'fmtlib.github.io'))
117 doc_repo.update('git@github.com:fmtlib/fmtlib.github.io')
118
119 for version in env.versions:
120 clean_checkout(env.fmt_repo, version)
121 target_doc_dir = os.path.join(env.fmt_repo.dir, 'doc')
122 # Remove the old theme.
123 for entry in os.listdir(target_doc_dir):
124 path = os.path.join(target_doc_dir, entry)
125 if os.path.isdir(path):
126 shutil.rmtree(path)
127 # Copy the new theme.
128 for entry in ['_static', '_templates', 'basic-bootstrap', 'bootstrap',
129 'conf.py', 'fmt.less']:
130 src = os.path.join(env.fmt_dir, 'doc', entry)
131 dst = os.path.join(target_doc_dir, entry)
132 copy = shutil.copytree if os.path.isdir(src) else shutil.copyfile
133 copy(src, dst)
134 # Rename index to contents.
135 contents = os.path.join(target_doc_dir, 'contents.rst')
136 if not os.path.exists(contents):
137 os.rename(os.path.join(target_doc_dir, 'index.rst'), contents)
138 # Fix issues in reference.rst/api.rst.
139 for filename in ['reference.rst', 'api.rst', 'index.rst']:
140 pattern = re.compile('doxygenfunction.. (bin|oct|hexu|hex)$', re.M)
141 with rewrite(os.path.join(target_doc_dir, filename)) as b:
142 b.data = b.data.replace('std::ostream &', 'std::ostream&')
143 b.data = re.sub(pattern, r'doxygenfunction:: \1(int)', b.data)
144 b.data = b.data.replace('std::FILE*', 'std::FILE *')
145 b.data = b.data.replace('unsigned int', 'unsigned')
146 #b.data = b.data.replace('operator""_', 'operator"" _')
147 b.data = b.data.replace(
148 'format_to_n(OutputIt, size_t, string_view, Args&&',
149 'format_to_n(OutputIt, size_t, const S&, const Args&')
150 b.data = b.data.replace(
151 'format_to_n(OutputIt, std::size_t, string_view, Args&&',
152 'format_to_n(OutputIt, std::size_t, const S&, const Args&')
153 if version == ('3.0.2'):
154 b.data = b.data.replace(
155 'fprintf(std::ostream&', 'fprintf(std::ostream &')
156 if version == ('5.3.0'):
157 b.data = b.data.replace(
158 'format_to(OutputIt, const S&, const Args&...)',
159 'format_to(OutputIt, const S &, const Args &...)')
160 if version.startswith('5.') or version.startswith('6.'):
161 b.data = b.data.replace(', size_t', ', std::size_t')
162 if version.startswith('7.'):
163 b.data = b.data.replace(', std::size_t', ', size_t')
164 b.data = b.data.replace('join(It, It', 'join(It, Sentinel')
165 if version.startswith('7.1.'):
166 b.data = b.data.replace(', std::size_t', ', size_t')
167 b.data = b.data.replace('join(It, It', 'join(It, Sentinel')
168 b.data = b.data.replace(
169 'fmt::format_to(OutputIt, const S&, Args&&...)',
170 'fmt::format_to(OutputIt, const S&, Args&&...) -> ' +
171 'typename std::enable_if<enable, OutputIt>::type')
172 b.data = b.data.replace('aa long', 'a long')
173 b.data = b.data.replace('serveral', 'several')
174 if version.startswith('6.2.'):
175 b.data = b.data.replace(
176 'vformat(const S&, basic_format_args<' +
177 'buffer_context<Char>>)',
178 'vformat(const S&, basic_format_args<' +
179 'buffer_context<type_identity_t<Char>>>)')
180 # Fix a broken link in index.rst.
181 index = os.path.join(target_doc_dir, 'index.rst')
182 with rewrite(index) as b:
183 b.data = b.data.replace(
184 'doc/latest/index.html#format-string-syntax', 'syntax.html')
185 # Build the docs.
186 html_dir = os.path.join(env.build_dir, 'html')
187 if os.path.exists(html_dir):
188 shutil.rmtree(html_dir)
189 include_dir = env.fmt_repo.dir
190 if LooseVersion(version) >= LooseVersion('5.0.0'):
191 include_dir = os.path.join(include_dir, 'include', 'fmt')
192 elif LooseVersion(version) >= LooseVersion('3.0.0'):
193 include_dir = os.path.join(include_dir, 'fmt')
194 import build
195 build.build_docs(version, doc_dir=target_doc_dir,
196 include_dir=include_dir, work_dir=env.build_dir)
197 shutil.rmtree(os.path.join(html_dir, '.doctrees'))
198 # Create symlinks for older versions.
199 for link, target in {'index': 'contents', 'api': 'reference'}.items():
200 link = os.path.join(html_dir, link) + '.html'
201 target += '.html'
202 if os.path.exists(os.path.join(html_dir, target)) and \
203 not os.path.exists(link):
204 os.symlink(target, link)
205 # Copy docs to the website.
206 version_doc_dir = os.path.join(doc_repo.dir, version)
207 try:
208 shutil.rmtree(version_doc_dir)
209 except OSError as e:
210 if e.errno != errno.ENOENT:
211 raise
212 shutil.move(html_dir, version_doc_dir)
213
214
215 def release(args):
216 env = create_build_env()
217 fmt_repo = env.fmt_repo
218
219 branch = args.get('<branch>')
220 if branch is None:
221 branch = 'master'
222 if not fmt_repo.update('-b', branch, fmt_repo_url):
223 clean_checkout(fmt_repo, branch)
224
225 # Convert changelog from RST to GitHub-flavored Markdown and get the
226 # version.
227 changelog = 'ChangeLog.rst'
228 changelog_path = os.path.join(fmt_repo.dir, changelog)
229 import rst2md
230 changes, version = rst2md.convert(changelog_path)
231 cmakelists = 'CMakeLists.txt'
232 for line in fileinput.input(os.path.join(fmt_repo.dir, cmakelists),
233 inplace=True):
234 prefix = 'set(FMT_VERSION '
235 if line.startswith(prefix):
236 line = prefix + version + ')\n'
237 sys.stdout.write(line)
238
239 # Update the version in the changelog.
240 title_len = 0
241 for line in fileinput.input(changelog_path, inplace=True):
242 if line.startswith(version + ' - TBD'):
243 line = version + ' - ' + datetime.date.today().isoformat()
244 title_len = len(line)
245 line += '\n'
246 elif title_len:
247 line = '-' * title_len + '\n'
248 title_len = 0
249 sys.stdout.write(line)
250
251 # Add the version to the build script.
252 script = os.path.join('doc', 'build.py')
253 script_path = os.path.join(fmt_repo.dir, script)
254 for line in fileinput.input(script_path, inplace=True):
255 m = re.match(r'( *versions = )\[(.+)\]', line)
256 if m:
257 line = '{}[{}, \'{}\']\n'.format(m.group(1), m.group(2), version)
258 sys.stdout.write(line)
259
260 fmt_repo.checkout('-B', 'release')
261 fmt_repo.add(changelog, cmakelists, script)
262 fmt_repo.commit('-m', 'Update version')
263
264 # Build the docs and package.
265 run = Runner(fmt_repo.dir)
266 run('cmake', '.')
267 run('make', 'doc', 'package_source')
268 update_site(env)
269
270 # Create a release on GitHub.
271 fmt_repo.push('origin', 'release')
272 auth_headers = {'Authorization': 'token ' + os.getenv('FMT_TOKEN')}
273 r = requests.post('https://api.github.com/repos/fmtlib/fmt/releases',
274 headers=auth_headers,
275 data=json.dumps({'tag_name': version,
276 'target_commitish': 'release',
277 'body': changes, 'draft': True}))
278 if r.status_code != 201:
279 raise Exception('Failed to create a release ' + str(r))
280 id = r.json()['id']
281 uploads_url = 'https://uploads.github.com/repos/fmtlib/fmt/releases'
282 package = 'fmt-{}.zip'.format(version)
283 r = requests.post(
284 '{}/{}/assets?name={}'.format(uploads_url, id, package),
285 headers={'Content-Type': 'application/zip'} | auth_headers,
286 data=open('build/fmt/' + package, 'rb'))
287 if r.status_code != 201:
288 raise Exception('Failed to upload an asset ' + str(r))
289
290
291 if __name__ == '__main__':
292 args = docopt.docopt(__doc__)
293 if args.get('release'):
294 release(args)
295 elif args.get('site'):
296 update_site(create_build_env())
+0
-201
source/misc/embedded_libs/fmt-8.1.1/support/printable.py less more
0 #!/usr/bin/env python3
1
2 # This script is based on
3 # https://github.com/rust-lang/rust/blob/master/library/core/src/unicode/printable.py
4 # distributed under https://github.com/rust-lang/rust/blob/master/LICENSE-MIT.
5
6 # This script uses the following Unicode tables:
7 # - UnicodeData.txt
8
9
10 from collections import namedtuple
11 import csv
12 import os
13 import subprocess
14
15 NUM_CODEPOINTS=0x110000
16
17 def to_ranges(iter):
18 current = None
19 for i in iter:
20 if current is None or i != current[1] or i in (0x10000, 0x20000):
21 if current is not None:
22 yield tuple(current)
23 current = [i, i + 1]
24 else:
25 current[1] += 1
26 if current is not None:
27 yield tuple(current)
28
29 def get_escaped(codepoints):
30 for c in codepoints:
31 if (c.class_ or "Cn") in "Cc Cf Cs Co Cn Zl Zp Zs".split() and c.value != ord(' '):
32 yield c.value
33
34 def get_file(f):
35 try:
36 return open(os.path.basename(f))
37 except FileNotFoundError:
38 subprocess.run(["curl", "-O", f], check=True)
39 return open(os.path.basename(f))
40
41 Codepoint = namedtuple('Codepoint', 'value class_')
42
43 def get_codepoints(f):
44 r = csv.reader(f, delimiter=";")
45 prev_codepoint = 0
46 class_first = None
47 for row in r:
48 codepoint = int(row[0], 16)
49 name = row[1]
50 class_ = row[2]
51
52 if class_first is not None:
53 if not name.endswith("Last>"):
54 raise ValueError("Missing Last after First")
55
56 for c in range(prev_codepoint + 1, codepoint):
57 yield Codepoint(c, class_first)
58
59 class_first = None
60 if name.endswith("First>"):
61 class_first = class_
62
63 yield Codepoint(codepoint, class_)
64 prev_codepoint = codepoint
65
66 if class_first is not None:
67 raise ValueError("Missing Last after First")
68
69 for c in range(prev_codepoint + 1, NUM_CODEPOINTS):
70 yield Codepoint(c, None)
71
72 def compress_singletons(singletons):
73 uppers = [] # (upper, # items in lowers)
74 lowers = []
75
76 for i in singletons:
77 upper = i >> 8
78 lower = i & 0xff
79 if len(uppers) == 0 or uppers[-1][0] != upper:
80 uppers.append((upper, 1))
81 else:
82 upper, count = uppers[-1]
83 uppers[-1] = upper, count + 1
84 lowers.append(lower)
85
86 return uppers, lowers
87
88 def compress_normal(normal):
89 # lengths 0x00..0x7f are encoded as 00, 01, ..., 7e, 7f
90 # lengths 0x80..0x7fff are encoded as 80 80, 80 81, ..., ff fe, ff ff
91 compressed = [] # [truelen, (truelenaux), falselen, (falselenaux)]
92
93 prev_start = 0
94 for start, count in normal:
95 truelen = start - prev_start
96 falselen = count
97 prev_start = start + count
98
99 assert truelen < 0x8000 and falselen < 0x8000
100 entry = []
101 if truelen > 0x7f:
102 entry.append(0x80 | (truelen >> 8))
103 entry.append(truelen & 0xff)
104 else:
105 entry.append(truelen & 0x7f)
106 if falselen > 0x7f:
107 entry.append(0x80 | (falselen >> 8))
108 entry.append(falselen & 0xff)
109 else:
110 entry.append(falselen & 0x7f)
111
112 compressed.append(entry)
113
114 return compressed
115
116 def print_singletons(uppers, lowers, uppersname, lowersname):
117 print(" static constexpr singleton {}[] = {{".format(uppersname))
118 for u, c in uppers:
119 print(" {{{:#04x}, {}}},".format(u, c))
120 print(" };")
121 print(" static constexpr unsigned char {}[] = {{".format(lowersname))
122 for i in range(0, len(lowers), 8):
123 print(" {}".format(" ".join("{:#04x},".format(l) for l in lowers[i:i+8])))
124 print(" };")
125
126 def print_normal(normal, normalname):
127 print(" static constexpr unsigned char {}[] = {{".format(normalname))
128 for v in normal:
129 print(" {}".format(" ".join("{:#04x},".format(i) for i in v)))
130 print(" };")
131
132 def main():
133 file = get_file("https://www.unicode.org/Public/UNIDATA/UnicodeData.txt")
134
135 codepoints = get_codepoints(file)
136
137 CUTOFF=0x10000
138 singletons0 = []
139 singletons1 = []
140 normal0 = []
141 normal1 = []
142 extra = []
143
144 for a, b in to_ranges(get_escaped(codepoints)):
145 if a > 2 * CUTOFF:
146 extra.append((a, b - a))
147 elif a == b - 1:
148 if a & CUTOFF:
149 singletons1.append(a & ~CUTOFF)
150 else:
151 singletons0.append(a)
152 elif a == b - 2:
153 if a & CUTOFF:
154 singletons1.append(a & ~CUTOFF)
155 singletons1.append((a + 1) & ~CUTOFF)
156 else:
157 singletons0.append(a)
158 singletons0.append(a + 1)
159 else:
160 if a >= 2 * CUTOFF:
161 extra.append((a, b - a))
162 elif a & CUTOFF:
163 normal1.append((a & ~CUTOFF, b - a))
164 else:
165 normal0.append((a, b - a))
166
167 singletons0u, singletons0l = compress_singletons(singletons0)
168 singletons1u, singletons1l = compress_singletons(singletons1)
169 normal0 = compress_normal(normal0)
170 normal1 = compress_normal(normal1)
171
172 print("""\
173 inline auto is_printable(uint32_t cp) -> bool {\
174 """)
175 print_singletons(singletons0u, singletons0l, 'singletons0', 'singletons0_lower')
176 print_singletons(singletons1u, singletons1l, 'singletons1', 'singletons1_lower')
177 print_normal(normal0, 'normal0')
178 print_normal(normal1, 'normal1')
179 print("""\
180 auto lower = static_cast<uint16_t>(cp);
181 if (cp < 0x10000) {
182 return is_printable(lower, singletons0,
183 sizeof(singletons0) / sizeof(*singletons0),
184 singletons0_lower, normal0, sizeof(normal0));
185 }
186 if (cp < 0x20000) {
187 return is_printable(lower, singletons1,
188 sizeof(singletons1) / sizeof(*singletons1),
189 singletons1_lower, normal1, sizeof(normal1));
190 }\
191 """)
192 for a, b in extra:
193 print(" if (0x{:x} <= cp && cp < 0x{:x}) return false;".format(a, a + b))
194 print("""\
195 return cp < 0x{:x};
196 }}\
197 """.format(NUM_CODEPOINTS))
198
199 if __name__ == '__main__':
200 main()
+0
-159
source/misc/embedded_libs/fmt-8.1.1/support/rst2md.py less more
0 #!/usr/bin/env python
1 # reStructuredText (RST) to GitHub-flavored Markdown converter
2
3 import re, sys
4 from docutils import core, nodes, writers
5
6
7 def is_github_ref(node):
8 return re.match('https://github.com/.*/(issues|pull)/.*', node['refuri'])
9
10
11 class Translator(nodes.NodeVisitor):
12 def __init__(self, document):
13 nodes.NodeVisitor.__init__(self, document)
14 self.output = ''
15 self.indent = 0
16 self.preserve_newlines = False
17
18 def write(self, text):
19 self.output += text.replace('\n', '\n' + ' ' * self.indent)
20
21 def visit_document(self, node):
22 pass
23
24 def depart_document(self, node):
25 pass
26
27 def visit_section(self, node):
28 pass
29
30 def depart_section(self, node):
31 # Skip all sections except the first one.
32 raise nodes.StopTraversal
33
34 def visit_title(self, node):
35 self.version = re.match(r'(\d+\.\d+\.\d+).*', node.children[0]).group(1)
36 raise nodes.SkipChildren
37
38 def visit_title_reference(self, node):
39 raise Exception(node)
40
41 def depart_title(self, node):
42 pass
43
44 def visit_Text(self, node):
45 if not self.preserve_newlines:
46 node = node.replace('\n', ' ')
47 self.write(node)
48
49 def depart_Text(self, node):
50 pass
51
52 def visit_bullet_list(self, node):
53 pass
54
55 def depart_bullet_list(self, node):
56 pass
57
58 def visit_list_item(self, node):
59 self.write('* ')
60 self.indent += 2
61
62 def depart_list_item(self, node):
63 self.indent -= 2
64 self.write('\n\n')
65
66 def visit_paragraph(self, node):
67 self.write('\n\n')
68
69 def depart_paragraph(self, node):
70 pass
71
72 def visit_reference(self, node):
73 if not is_github_ref(node):
74 self.write('[')
75
76 def depart_reference(self, node):
77 if not is_github_ref(node):
78 self.write('](' + node['refuri'] + ')')
79
80 def visit_target(self, node):
81 pass
82
83 def depart_target(self, node):
84 pass
85
86 def visit_literal(self, node):
87 self.write('`')
88
89 def depart_literal(self, node):
90 self.write('`')
91
92 def visit_literal_block(self, node):
93 self.write('\n\n```')
94 if 'c++' in node['classes']:
95 self.write('c++')
96 self.write('\n')
97 self.preserve_newlines = True
98
99 def depart_literal_block(self, node):
100 self.write('\n```\n')
101 self.preserve_newlines = False
102
103 def visit_inline(self, node):
104 pass
105
106 def depart_inline(self, node):
107 pass
108
109 def visit_image(self, node):
110 self.write('![](' + node['uri'] + ')')
111
112 def depart_image(self, node):
113 pass
114
115 def write_row(self, row, widths):
116 for i, entry in enumerate(row):
117 text = entry[0][0] if len(entry) > 0 else ''
118 if i != 0:
119 self.write('|')
120 self.write('{:{}}'.format(text, widths[i]))
121 self.write('\n')
122
123 def visit_table(self, node):
124 table = node.children[0]
125 colspecs = table[:-2]
126 thead = table[-2]
127 tbody = table[-1]
128 widths = [int(cs['colwidth']) for cs in colspecs]
129 sep = '|'.join(['-' * w for w in widths]) + '\n'
130 self.write('\n\n')
131 self.write_row(thead[0], widths)
132 self.write(sep)
133 for row in tbody:
134 self.write_row(row, widths)
135 raise nodes.SkipChildren
136
137 def depart_table(self, node):
138 pass
139
140 class MDWriter(writers.Writer):
141 """GitHub-flavored markdown writer"""
142
143 supported = ('md',)
144 """Formats this writer supports."""
145
146 def translate(self):
147 translator = Translator(self.document)
148 self.document.walkabout(translator)
149 self.output = (translator.output, translator.version)
150
151
152 def convert(rst_path):
153 """Converts RST file to Markdown."""
154 return core.publish_file(source_path=rst_path, writer=MDWriter())
155
156
157 if __name__ == '__main__':
158 convert(sys.argv[1])
+0
-7
source/misc/embedded_libs/fmt-8.1.1/support/rtd/conf.py less more
0 # Sphinx configuration for readthedocs.
1
2 import os, sys
3
4 master_doc = 'index'
5 html_theme = 'theme'
6 html_theme_path = ["."]
+0
-2
source/misc/embedded_libs/fmt-8.1.1/support/rtd/index.rst less more
0 If you are not redirected automatically, follow the
1 `link to the fmt documentation <https://fmt.dev/latest/>`_.
+0
-17
source/misc/embedded_libs/fmt-8.1.1/support/rtd/theme/layout.html less more
0 {% extends "basic/layout.html" %}
1
2 {% block extrahead %}
3 <meta charset="UTF-8">
4 <meta http-equiv="refresh" content="1;url=https://fmt.dev/latest/">
5 <script type="text/javascript">
6 window.location.href = "https://fmt.dev/latest/"
7 </script>
8 <title>Page Redirection</title>
9 {% endblock %}
10
11 {% block document %}
12 If you are not redirected automatically, follow the <a href='https://fmt.dev/latest/'>link to the fmt documentation</a>.
13 {% endblock %}
14
15 {% block footer %}
16 {% endblock %}
+0
-2
source/misc/embedded_libs/fmt-8.1.1/support/rtd/theme/theme.conf less more
0 [theme]
1 inherit = basic
+0
-244
source/misc/embedded_libs/fmt-8.1.1/test/CMakeLists.txt less more
0 add_subdirectory(gtest)
1
2 set(TEST_MAIN_SRC test-main.cc gtest-extra.cc gtest-extra.h util.cc)
3 add_library(test-main STATIC ${TEST_MAIN_SRC})
4 target_include_directories(test-main PUBLIC
5 $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>)
6 target_link_libraries(test-main gtest)
7
8 include(CheckCXXCompilerFlag)
9
10 function(add_fmt_executable name)
11 add_executable(${name} ${ARGN})
12 if (MINGW)
13 target_link_libraries(${name} -static-libgcc -static-libstdc++)
14 endif ()
15 # (Wstringop-overflow) - [meta-bug] bogus/missing -Wstringop-overflow warnings
16 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88443
17 # Bogus -Wstringop-overflow warning
18 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100395
19 # [10 Regression] spurious -Wstringop-overflow writing to a trailing array plus offset
20 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95353
21 if (CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND
22 NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0)
23 target_link_libraries(${name} -Wno-stringop-overflow)
24 endif ()
25 endfunction()
26
27 # Adds a test.
28 # Usage: add_fmt_test(name srcs...)
29 function(add_fmt_test name)
30 cmake_parse_arguments(ADD_FMT_TEST "HEADER_ONLY;MODULE" "" "" ${ARGN})
31
32 set(sources ${name}.cc ${ADD_FMT_TEST_UNPARSED_ARGUMENTS})
33 if (ADD_FMT_TEST_HEADER_ONLY)
34 set(sources ${sources} ${TEST_MAIN_SRC} ../src/os.cc)
35 set(libs gtest fmt-header-only)
36 if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
37 set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wno-weak-vtables)
38 endif ()
39 elseif (ADD_FMT_TEST_MODULE)
40 set(libs gtest test-module)
41 set_source_files_properties(${name}.cc PROPERTIES OBJECT_DEPENDS test-module)
42 else ()
43 set(libs test-main fmt)
44 endif ()
45 add_fmt_executable(${name} ${sources})
46 target_link_libraries(${name} ${libs})
47
48 # Define if certain C++ features can be used.
49 if (FMT_PEDANTIC)
50 target_compile_options(${name} PRIVATE ${PEDANTIC_COMPILE_FLAGS})
51 endif ()
52 if (FMT_WERROR)
53 target_compile_options(${name} PRIVATE ${WERROR_FLAG})
54 endif ()
55 add_test(NAME ${name} COMMAND ${name})
56 endfunction()
57
58 add_fmt_test(args-test)
59 add_fmt_test(assert-test)
60 add_fmt_test(chrono-test)
61 add_fmt_test(color-test)
62 add_fmt_test(core-test)
63 add_fmt_test(gtest-extra-test)
64 add_fmt_test(format-test mock-allocator.h)
65 if (MSVC)
66 target_compile_options(format-test PRIVATE /bigobj)
67 endif ()
68 if (NOT (MSVC AND BUILD_SHARED_LIBS))
69 add_fmt_test(format-impl-test HEADER_ONLY header-only-test.cc)
70 endif ()
71 add_fmt_test(ostream-test)
72 add_fmt_test(compile-test)
73 add_fmt_test(compile-fp-test HEADER_ONLY)
74 if (MSVC)
75 # Without this option, MSVC returns 199711L for the __cplusplus macro.
76 target_compile_options(compile-fp-test PRIVATE /Zc:__cplusplus)
77 endif()
78 add_fmt_test(printf-test)
79 add_fmt_test(ranges-test ranges-odr-test.cc)
80 add_fmt_test(scan-test)
81 add_fmt_test(unicode-test HEADER_ONLY)
82 if (MSVC)
83 target_compile_options(unicode-test PRIVATE /utf-8)
84 endif ()
85 add_fmt_test(xchar-test)
86 add_fmt_test(enforce-checks-test)
87 target_compile_definitions(enforce-checks-test PRIVATE
88 -DFMT_ENFORCE_COMPILE_STRING)
89
90 if (FMT_CAN_MODULE)
91 # The tests need {fmt} to be compiled as traditional library
92 # because of visibility of implementation details.
93 # If module support is present the module tests require a
94 # test-only module to be built from {fmt}
95 add_library(test-module OBJECT ${CMAKE_SOURCE_DIR}/src/fmt.cc)
96 target_compile_features(test-module PUBLIC ${FMT_REQUIRED_FEATURES})
97 target_include_directories(test-module PUBLIC
98 $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>)
99 enable_module(test-module)
100
101 add_fmt_test(module-test MODULE test-main.cc)
102 if (MSVC)
103 target_compile_options(test-module PRIVATE /utf-8 /Zc:__cplusplus
104 /Zc:externConstexpr /Zc:inline)
105 target_compile_options(module-test PRIVATE /utf-8 /Zc:__cplusplus
106 /Zc:externConstexpr /Zc:inline)
107 endif ()
108 endif ()
109
110 if (NOT DEFINED MSVC_STATIC_RUNTIME AND MSVC)
111 foreach (flag_var
112 CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
113 CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
114 if (${flag_var} MATCHES "^(/|-)(MT|MTd)")
115 set(MSVC_STATIC_RUNTIME ON)
116 break()
117 endif()
118 endforeach()
119 endif()
120
121 if (NOT MSVC_STATIC_RUNTIME)
122 add_fmt_executable(posix-mock-test
123 posix-mock-test.cc ../src/format.cc ${TEST_MAIN_SRC})
124 target_include_directories(
125 posix-mock-test PRIVATE ${PROJECT_SOURCE_DIR}/include)
126 target_link_libraries(posix-mock-test gtest)
127 if (FMT_PEDANTIC)
128 target_compile_options(posix-mock-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
129 endif ()
130 if (HAVE_STRTOD_L)
131 target_compile_definitions(posix-mock-test PRIVATE FMT_LOCALE)
132 endif ()
133 add_test(NAME posix-mock-test COMMAND posix-mock-test)
134 add_fmt_test(os-test)
135 endif ()
136
137 message(STATUS "FMT_PEDANTIC: ${FMT_PEDANTIC}")
138
139 if (FMT_PEDANTIC)
140 # Test that the library can be compiled with exceptions disabled.
141 # -fno-exception is broken in icc: https://github.com/fmtlib/fmt/issues/822.
142 if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
143 check_cxx_compiler_flag(-fno-exceptions HAVE_FNO_EXCEPTIONS_FLAG)
144 endif ()
145 if (HAVE_FNO_EXCEPTIONS_FLAG)
146 add_library(noexception-test ../src/format.cc noexception-test.cc)
147 target_include_directories(
148 noexception-test PRIVATE ${PROJECT_SOURCE_DIR}/include)
149 target_compile_options(noexception-test PRIVATE -fno-exceptions)
150 if (FMT_PEDANTIC)
151 target_compile_options(noexception-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
152 endif ()
153 endif ()
154
155 # Test that the library compiles without locale.
156 add_library(nolocale-test ../src/format.cc)
157 target_include_directories(
158 nolocale-test PRIVATE ${PROJECT_SOURCE_DIR}/include)
159 target_compile_definitions(
160 nolocale-test PRIVATE FMT_STATIC_THOUSANDS_SEPARATOR=1)
161 endif ()
162
163 # These tests are disabled on Windows because they take too long.
164 if (FMT_PEDANTIC AND NOT WIN32)
165 # Test if incorrect API usages produce compilation error.
166 add_test(compile-error-test ${CMAKE_CTEST_COMMAND}
167 --build-and-test
168 "${CMAKE_CURRENT_SOURCE_DIR}/compile-error-test"
169 "${CMAKE_CURRENT_BINARY_DIR}/compile-error-test"
170 --build-generator ${CMAKE_GENERATOR}
171 --build-makeprogram ${CMAKE_MAKE_PROGRAM}
172 --build-options
173 "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
174 "-DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}"
175 "-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}"
176 "-DFMT_DIR=${CMAKE_SOURCE_DIR}"
177 "-DSUPPORTS_USER_DEFINED_LITERALS=${SUPPORTS_USER_DEFINED_LITERALS}")
178
179 # Test if the targets are found from the build directory.
180 add_test(find-package-test ${CMAKE_CTEST_COMMAND}
181 -C ${CMAKE_BUILD_TYPE}
182 --build-and-test
183 "${CMAKE_CURRENT_SOURCE_DIR}/find-package-test"
184 "${CMAKE_CURRENT_BINARY_DIR}/find-package-test"
185 --build-generator ${CMAKE_GENERATOR}
186 --build-makeprogram ${CMAKE_MAKE_PROGRAM}
187 --build-options
188 "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
189 "-DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}"
190 "-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}"
191 "-DFMT_DIR=${PROJECT_BINARY_DIR}"
192 "-DPEDANTIC_COMPILE_FLAGS=${PEDANTIC_COMPILE_FLAGS}"
193 "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
194
195 # Test if the targets are found when add_subdirectory is used.
196 add_test(add-subdirectory-test ${CMAKE_CTEST_COMMAND}
197 -C ${CMAKE_BUILD_TYPE}
198 --build-and-test
199 "${CMAKE_CURRENT_SOURCE_DIR}/add-subdirectory-test"
200 "${CMAKE_CURRENT_BINARY_DIR}/add-subdirectory-test"
201 --build-generator ${CMAKE_GENERATOR}
202 --build-makeprogram ${CMAKE_MAKE_PROGRAM}
203 --build-options
204 "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
205 "-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}"
206 "-DPEDANTIC_COMPILE_FLAGS=${PEDANTIC_COMPILE_FLAGS}"
207 "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
208 endif ()
209
210 # This test are disabled on Windows because it is only *NIX issue.
211 if (FMT_PEDANTIC AND NOT WIN32)
212 add_test(static-export-test ${CMAKE_CTEST_COMMAND}
213 -C ${CMAKE_BUILD_TYPE}
214 --build-and-test
215 "${CMAKE_CURRENT_SOURCE_DIR}/static-export-test"
216 "${CMAKE_CURRENT_BINARY_DIR}/static-export-test"
217 --build-generator ${CMAKE_GENERATOR}
218 --build-makeprogram ${CMAKE_MAKE_PROGRAM}
219 --build-options
220 "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
221 "-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}"
222 "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
223 endif ()
224
225 # Activate optional CUDA tests if CUDA is found. For version selection see
226 # https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#cpp14-language-features
227 if (FMT_CUDA_TEST)
228 if (${CMAKE_VERSION} VERSION_LESS 3.15)
229 find_package(CUDA 9.0)
230 else ()
231 include(CheckLanguage)
232 check_language(CUDA)
233 if (CMAKE_CUDA_COMPILER)
234 enable_language(CUDA OPTIONAL)
235 set(CUDA_FOUND TRUE)
236 endif ()
237 endif ()
238
239 if (CUDA_FOUND)
240 add_subdirectory(cuda-test)
241 add_test(NAME cuda-test COMMAND fmt-in-cuda-test)
242 endif ()
243 endif ()
+0
-17
source/misc/embedded_libs/fmt-8.1.1/test/add-subdirectory-test/CMakeLists.txt less more
0 cmake_minimum_required(VERSION 3.1...3.18)
1
2 project(fmt-test CXX)
3
4 add_subdirectory(../.. fmt)
5
6 add_executable(library-test main.cc)
7 target_include_directories(library-test PUBLIC SYSTEM .)
8 target_compile_options(library-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
9 target_link_libraries(library-test fmt::fmt)
10
11 if (TARGET fmt::fmt-header-only)
12 add_executable(header-only-test main.cc)
13 target_include_directories(header-only-test PUBLIC SYSTEM .)
14 target_compile_options(header-only-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
15 target_link_libraries(header-only-test fmt::fmt-header-only)
16 endif ()
+0
-5
source/misc/embedded_libs/fmt-8.1.1/test/add-subdirectory-test/main.cc less more
0 #include "fmt/core.h"
1
2 int main(int argc, char** argv) {
3 for (int i = 0; i < argc; ++i) fmt::print("{}: {}\n", i, argv[i]);
4 }
+0
-186
source/misc/embedded_libs/fmt-8.1.1/test/args-test.cc less more
0 // Formatting library for C++ - dynamic argument store tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/args.h"
8
9 #include <memory>
10
11 #include "gtest/gtest.h"
12
13 TEST(args_test, basic) {
14 fmt::dynamic_format_arg_store<fmt::format_context> store;
15 store.push_back(42);
16 store.push_back("abc1");
17 store.push_back(1.5f);
18 EXPECT_EQ("42 and abc1 and 1.5", fmt::vformat("{} and {} and {}", store));
19 }
20
21 TEST(args_test, strings_and_refs) {
22 // Unfortunately the tests are compiled with old ABI so strings use COW.
23 fmt::dynamic_format_arg_store<fmt::format_context> store;
24 char str[] = "1234567890";
25 store.push_back(str);
26 store.push_back(std::cref(str));
27 store.push_back(fmt::string_view{str});
28 str[0] = 'X';
29
30 auto result = fmt::vformat("{} and {} and {}", store);
31 EXPECT_EQ("1234567890 and X234567890 and X234567890", result);
32 }
33
34 struct custom_type {
35 int i = 0;
36 };
37
38 FMT_BEGIN_NAMESPACE
39 template <> struct formatter<custom_type> {
40 auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) {
41 return ctx.begin();
42 }
43
44 template <typename FormatContext>
45 auto format(const custom_type& p, FormatContext& ctx) -> decltype(ctx.out()) {
46 return format_to(ctx.out(), "cust={}", p.i);
47 }
48 };
49 FMT_END_NAMESPACE
50
51 TEST(args_test, custom_format) {
52 fmt::dynamic_format_arg_store<fmt::format_context> store;
53 auto c = custom_type();
54 store.push_back(c);
55 ++c.i;
56 store.push_back(c);
57 ++c.i;
58 store.push_back(std::cref(c));
59 ++c.i;
60 auto result = fmt::vformat("{} and {} and {}", store);
61 EXPECT_EQ("cust=0 and cust=1 and cust=3", result);
62 }
63
64 struct to_stringable {
65 friend fmt::string_view to_string_view(to_stringable) { return {}; }
66 };
67
68 FMT_BEGIN_NAMESPACE
69 template <> struct formatter<to_stringable> {
70 auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) {
71 return ctx.begin();
72 }
73
74 auto format(to_stringable, format_context& ctx) -> decltype(ctx.out()) {
75 return ctx.out();
76 }
77 };
78 FMT_END_NAMESPACE
79
80 TEST(args_test, to_string_and_formatter) {
81 fmt::dynamic_format_arg_store<fmt::format_context> store;
82 auto s = to_stringable();
83 store.push_back(s);
84 store.push_back(std::cref(s));
85 fmt::vformat("", store);
86 }
87
88 TEST(args_test, named_int) {
89 fmt::dynamic_format_arg_store<fmt::format_context> store;
90 store.push_back(fmt::arg("a1", 42));
91 EXPECT_EQ("42", fmt::vformat("{a1}", store));
92 }
93
94 TEST(args_test, named_strings) {
95 fmt::dynamic_format_arg_store<fmt::format_context> store;
96 char str[] = "1234567890";
97 store.push_back(fmt::arg("a1", str));
98 store.push_back(fmt::arg("a2", std::cref(str)));
99 str[0] = 'X';
100 EXPECT_EQ("1234567890 and X234567890", fmt::vformat("{a1} and {a2}", store));
101 }
102
103 TEST(args_test, named_arg_by_ref) {
104 fmt::dynamic_format_arg_store<fmt::format_context> store;
105 char band[] = "Rolling Stones";
106 store.push_back(fmt::arg("band", std::cref(band)));
107 band[9] = 'c'; // Changing band affects the output.
108 EXPECT_EQ(fmt::vformat("{band}", store), "Rolling Scones");
109 }
110
111 TEST(args_test, named_custom_format) {
112 fmt::dynamic_format_arg_store<fmt::format_context> store;
113 auto c = custom_type();
114 store.push_back(fmt::arg("c1", c));
115 ++c.i;
116 store.push_back(fmt::arg("c2", c));
117 ++c.i;
118 store.push_back(fmt::arg("c_ref", std::cref(c)));
119 ++c.i;
120 auto result = fmt::vformat("{c1} and {c2} and {c_ref}", store);
121 EXPECT_EQ("cust=0 and cust=1 and cust=3", result);
122 }
123
124 TEST(args_test, clear) {
125 fmt::dynamic_format_arg_store<fmt::format_context> store;
126 store.push_back(42);
127
128 auto result = fmt::vformat("{}", store);
129 EXPECT_EQ("42", result);
130
131 store.push_back(43);
132 result = fmt::vformat("{} and {}", store);
133 EXPECT_EQ("42 and 43", result);
134
135 store.clear();
136 store.push_back(44);
137 result = fmt::vformat("{}", store);
138 EXPECT_EQ("44", result);
139 }
140
141 TEST(args_test, reserve) {
142 fmt::dynamic_format_arg_store<fmt::format_context> store;
143 store.reserve(2, 1);
144 store.push_back(1.5f);
145 store.push_back(fmt::arg("a1", 42));
146 auto result = fmt::vformat("{a1} and {}", store);
147 EXPECT_EQ("42 and 1.5", result);
148 }
149
150 struct copy_throwable {
151 copy_throwable() {}
152 copy_throwable(const copy_throwable&) { throw "deal with it"; }
153 };
154
155 FMT_BEGIN_NAMESPACE
156 template <> struct formatter<copy_throwable> {
157 auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) {
158 return ctx.begin();
159 }
160 auto format(copy_throwable, format_context& ctx) -> decltype(ctx.out()) {
161 return ctx.out();
162 }
163 };
164 FMT_END_NAMESPACE
165
166 TEST(args_test, throw_on_copy) {
167 fmt::dynamic_format_arg_store<fmt::format_context> store;
168 store.push_back(std::string("foo"));
169 try {
170 store.push_back(copy_throwable());
171 } catch (...) {
172 }
173 EXPECT_EQ(fmt::vformat("{}", store), "foo");
174 }
175
176 TEST(args_test, move_constructor) {
177 using store_type = fmt::dynamic_format_arg_store<fmt::format_context>;
178 auto store = std::unique_ptr<store_type>(new store_type());
179 store->push_back(42);
180 store->push_back(std::string("foo"));
181 store->push_back(fmt::arg("a1", "foo"));
182 auto moved_store = std::move(*store);
183 store.reset();
184 EXPECT_EQ(fmt::vformat("{} {} {a1}", moved_store), "42 foo foo");
185 }
+0
-31
source/misc/embedded_libs/fmt-8.1.1/test/assert-test.cc less more
0 // Formatting library for C++ - FMT_ASSERT test
1 //
2 // It is a separate test to minimize the number of EXPECT_DEBUG_DEATH checks
3 // which are slow on some platforms. In other tests FMT_ASSERT is made to throw
4 // an exception which is much faster and easier to check.
5 //
6 // Copyright (c) 2012 - present, Victor Zverovich
7 // All rights reserved.
8 //
9 // For the license information refer to format.h.
10
11 #include "fmt/core.h"
12 #include "gtest/gtest.h"
13
14 TEST(assert_test, fail) {
15 #if GTEST_HAS_DEATH_TEST
16 EXPECT_DEBUG_DEATH(FMT_ASSERT(false, "don't panic!"), "don't panic!");
17 #else
18 fmt::print("warning: death tests are not supported\n");
19 #endif
20 }
21
22 TEST(assert_test, dangling_else) {
23 bool test_condition = false;
24 bool executed_else = false;
25 if (test_condition)
26 FMT_ASSERT(true, "");
27 else
28 executed_else = true;
29 EXPECT_TRUE(executed_else);
30 }
+0
-625
source/misc/embedded_libs/fmt-8.1.1/test/chrono-test.cc less more
0 // Formatting library for C++ - time formatting tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/chrono.h"
8
9 #include <ctime>
10 #include <vector>
11
12 #include "gtest-extra.h" // EXPECT_THROW_MSG
13 #include "util.h" // get_locale
14
15 using fmt::runtime;
16
17 using testing::Contains;
18
19 auto make_tm() -> std::tm {
20 auto time = std::tm();
21 time.tm_mday = 1;
22 return time;
23 }
24
25 auto make_hour(int h) -> std::tm {
26 auto time = make_tm();
27 time.tm_hour = h;
28 return time;
29 }
30
31 auto make_minute(int m) -> std::tm {
32 auto time = make_tm();
33 time.tm_min = m;
34 return time;
35 }
36
37 auto make_second(int s) -> std::tm {
38 auto time = make_tm();
39 time.tm_sec = s;
40 return time;
41 }
42
43 std::string system_strftime(const std::string& format, const std::tm* timeptr,
44 std::locale* locptr = nullptr) {
45 auto loc = locptr ? *locptr : std::locale::classic();
46 auto& facet = std::use_facet<std::time_put<char>>(loc);
47 std::ostringstream os;
48 os.imbue(loc);
49 facet.put(os, os, ' ', timeptr, format.c_str(),
50 format.c_str() + format.size());
51 #ifdef _WIN32
52 // Workaround a bug in older versions of Universal CRT.
53 auto str = os.str();
54 if (str == "-0000") str = "+0000";
55 return str;
56 #else
57 return os.str();
58 #endif
59 }
60
61 FMT_CONSTEXPR std::tm make_tm(int year, int mon, int mday, int hour, int min,
62 int sec) {
63 auto tm = std::tm();
64 tm.tm_sec = sec;
65 tm.tm_min = min;
66 tm.tm_hour = hour;
67 tm.tm_mday = mday;
68 tm.tm_mon = mon - 1;
69 tm.tm_year = year - 1900;
70 return tm;
71 }
72
73 TEST(chrono_test, format_tm) {
74 auto tm = std::tm();
75 tm.tm_year = 116;
76 tm.tm_mon = 3;
77 tm.tm_mday = 25;
78 tm.tm_hour = 11;
79 tm.tm_min = 22;
80 tm.tm_sec = 33;
81 EXPECT_EQ(fmt::format("The date is {:%Y-%m-%d %H:%M:%S}.", tm),
82 "The date is 2016-04-25 11:22:33.");
83 EXPECT_EQ(fmt::format("{:%Y}", tm), "2016");
84 EXPECT_EQ(fmt::format("{:%C}", tm), "20");
85 EXPECT_EQ(fmt::format("{:%C%y}", tm), fmt::format("{:%Y}", tm));
86 EXPECT_EQ(fmt::format("{:%e}", tm), "25");
87 EXPECT_EQ(fmt::format("{:%D}", tm), "04/25/16");
88 EXPECT_EQ(fmt::format("{:%F}", tm), "2016-04-25");
89 EXPECT_EQ(fmt::format("{:%T}", tm), "11:22:33");
90
91 // Short year
92 tm.tm_year = 999 - 1900;
93 tm.tm_mon = 0; // for %G
94 tm.tm_mday = 2; // for %G
95 tm.tm_wday = 3; // for %G
96 tm.tm_yday = 1; // for %G
97 EXPECT_EQ(fmt::format("{:%Y}", tm), "0999");
98 EXPECT_EQ(fmt::format("{:%C%y}", tm), "0999");
99 EXPECT_EQ(fmt::format("{:%G}", tm), "0999");
100
101 tm.tm_year = 27 - 1900;
102 EXPECT_EQ(fmt::format("{:%Y}", tm), "0027");
103 EXPECT_EQ(fmt::format("{:%C%y}", tm), "0027");
104
105 // Overflow year
106 tm.tm_year = 2147483647;
107 EXPECT_EQ(fmt::format("{:%Y}", tm), "2147485547");
108
109 tm.tm_year = -2147483648;
110 EXPECT_EQ(fmt::format("{:%Y}", tm), "-2147481748");
111
112 // for week on the year
113 // https://www.cl.cam.ac.uk/~mgk25/iso-time.html
114 std::vector<std::tm> tm_list = {
115 make_tm(1975, 12, 29, 12, 14, 16), // W01
116 make_tm(1977, 1, 2, 12, 14, 16), // W53
117 make_tm(1999, 12, 27, 12, 14, 16), // W52
118 make_tm(1999, 12, 31, 12, 14, 16), // W52
119 make_tm(2000, 1, 1, 12, 14, 16), // W52
120 make_tm(2000, 1, 2, 12, 14, 16), // W52
121 make_tm(2000, 1, 3, 12, 14, 16) // W1
122 };
123 const std::string iso_week_spec = "%Y-%m-%d: %G %g %V";
124 for (auto ctm : tm_list) {
125 // Calculate tm_yday, tm_wday, etc.
126 std::time_t t = std::mktime(&ctm);
127 tm = *std::localtime(&t);
128
129 auto fmt_spec = fmt::format("{{:{}}}", iso_week_spec);
130 EXPECT_EQ(system_strftime(iso_week_spec, &tm),
131 fmt::format(fmt::runtime(fmt_spec), tm));
132 }
133
134 // Every day from 1970-01-01
135 std::time_t time_now = std::time(nullptr);
136 for (std::time_t t = 6 * 3600; t < time_now; t += 86400) {
137 tm = *std::localtime(&t);
138
139 auto fmt_spec = fmt::format("{{:{}}}", iso_week_spec);
140 EXPECT_EQ(system_strftime(iso_week_spec, &tm),
141 fmt::format(fmt::runtime(fmt_spec), tm));
142 }
143 }
144
145 // MSVC:
146 // minkernel\crts\ucrt\src\appcrt\time\wcsftime.cpp(971) : Assertion failed:
147 // timeptr->tm_year >= -1900 && timeptr->tm_year <= 8099
148 #ifndef _WIN32
149 TEST(chrono_test, format_tm_future) {
150 auto tm = std::tm();
151 tm.tm_year = 10445; // 10000+ years
152 tm.tm_mon = 3;
153 tm.tm_mday = 25;
154 tm.tm_hour = 11;
155 tm.tm_min = 22;
156 tm.tm_sec = 33;
157 EXPECT_EQ(fmt::format("The date is {:%Y-%m-%d %H:%M:%S}.", tm),
158 "The date is 12345-04-25 11:22:33.");
159 EXPECT_EQ(fmt::format("{:%Y}", tm), "12345");
160 EXPECT_EQ(fmt::format("{:%C}", tm), "123");
161 EXPECT_EQ(fmt::format("{:%C%y}", tm), fmt::format("{:%Y}", tm));
162 EXPECT_EQ(fmt::format("{:%D}", tm), "04/25/45");
163 EXPECT_EQ(fmt::format("{:%F}", tm), "12345-04-25");
164 EXPECT_EQ(fmt::format("{:%T}", tm), "11:22:33");
165 }
166
167 TEST(chrono_test, format_tm_past) {
168 auto tm = std::tm();
169 tm.tm_year = -2001;
170 tm.tm_mon = 3;
171 tm.tm_mday = 25;
172 tm.tm_hour = 11;
173 tm.tm_min = 22;
174 tm.tm_sec = 33;
175 EXPECT_EQ(fmt::format("The date is {:%Y-%m-%d %H:%M:%S}.", tm),
176 "The date is -101-04-25 11:22:33.");
177 EXPECT_EQ(fmt::format("{:%Y}", tm), "-101");
178
179 // macOS %C - "-1"
180 // Linux %C - "-2"
181 // fmt %C - "-1"
182 EXPECT_EQ(fmt::format("{:%C}", tm), "-1");
183 EXPECT_EQ(fmt::format("{:%C%y}", tm), fmt::format("{:%Y}", tm));
184
185 // macOS %D - "04/25/01" (%y)
186 // Linux %D - "04/25/99" (%y)
187 // fmt %D - "04/25/01" (%y)
188 EXPECT_EQ(fmt::format("{:%D}", tm), "04/25/01");
189
190 EXPECT_EQ(fmt::format("{:%F}", tm), "-101-04-25");
191 EXPECT_EQ(fmt::format("{:%T}", tm), "11:22:33");
192
193 tm.tm_year = -1901; // -1
194 EXPECT_EQ(fmt::format("{:%Y}", tm), "-001");
195 EXPECT_EQ(fmt::format("{:%C%y}", tm), fmt::format("{:%Y}", tm));
196
197 tm.tm_year = -1911; // -11
198 EXPECT_EQ(fmt::format("{:%Y}", tm), "-011");
199 EXPECT_EQ(fmt::format("{:%C%y}", tm), fmt::format("{:%Y}", tm));
200 }
201 #endif
202
203 TEST(chrono_test, grow_buffer) {
204 auto s = std::string("{:");
205 for (int i = 0; i < 30; ++i) s += "%c";
206 s += "}\n";
207 auto t = std::time(nullptr);
208 (void)fmt::format(fmt::runtime(s), *std::localtime(&t));
209 }
210
211 TEST(chrono_test, format_to_empty_container) {
212 auto time = std::tm();
213 time.tm_sec = 42;
214 auto s = std::string();
215 fmt::format_to(std::back_inserter(s), "{:%S}", time);
216 EXPECT_EQ(s, "42");
217 }
218
219 TEST(chrono_test, empty_result) { EXPECT_EQ(fmt::format("{}", std::tm()), ""); }
220
221 auto equal(const std::tm& lhs, const std::tm& rhs) -> bool {
222 return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min &&
223 lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday &&
224 lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year &&
225 lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday &&
226 lhs.tm_isdst == rhs.tm_isdst;
227 }
228
229 TEST(chrono_test, localtime) {
230 auto t = std::time(nullptr);
231 auto tm = *std::localtime(&t);
232 EXPECT_TRUE(equal(tm, fmt::localtime(t)));
233 }
234
235 TEST(chrono_test, gmtime) {
236 auto t = std::time(nullptr);
237 auto tm = *std::gmtime(&t);
238 EXPECT_TRUE(equal(tm, fmt::gmtime(t)));
239 }
240
241 template <typename TimePoint> auto strftime_full(TimePoint tp) -> std::string {
242 auto t = std::chrono::system_clock::to_time_t(tp);
243 auto tm = *std::localtime(&t);
244 return system_strftime("%Y-%m-%d %H:%M:%S", &tm);
245 }
246
247 TEST(chrono_test, time_point) {
248 auto t1 = std::chrono::system_clock::now();
249 EXPECT_EQ(strftime_full(t1), fmt::format("{:%Y-%m-%d %H:%M:%S}", t1));
250 EXPECT_EQ(strftime_full(t1), fmt::format("{}", t1));
251 using time_point =
252 std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>;
253 auto t2 = time_point(std::chrono::seconds(42));
254 EXPECT_EQ(strftime_full(t2), fmt::format("{:%Y-%m-%d %H:%M:%S}", t2));
255
256 std::vector<std::string> spec_list = {
257 "%%", "%n", "%t", "%Y", "%EY", "%y", "%Oy", "%Ey", "%C",
258 "%EC", "%G", "%g", "%b", "%h", "%B", "%m", "%Om", "%U",
259 "%OU", "%W", "%OW", "%V", "%OV", "%j", "%d", "%Od", "%e",
260 "%Oe", "%a", "%A", "%w", "%Ow", "%u", "%Ou", "%H", "%OH",
261 "%I", "%OI", "%M", "%OM", "%S", "%OS", "%x", "%Ex", "%X",
262 "%EX", "%D", "%F", "%R", "%T", "%p", "%z", "%Z"};
263 spec_list.push_back("%Y-%m-%d %H:%M:%S");
264 #ifndef _WIN32
265 // Disabled on Windows because these formats are not consistent among
266 // platforms.
267 spec_list.insert(spec_list.end(), {"%c", "%Ec", "%r"});
268 #endif
269
270 for (const auto& spec : spec_list) {
271 auto t = std::chrono::system_clock::to_time_t(t1);
272 auto tm = *std::localtime(&t);
273
274 auto sys_output = system_strftime(spec, &tm);
275
276 auto fmt_spec = fmt::format("{{:{}}}", spec);
277 EXPECT_EQ(sys_output, fmt::format(fmt::runtime(fmt_spec), t1));
278 EXPECT_EQ(sys_output, fmt::format(fmt::runtime(fmt_spec), tm));
279 }
280 }
281
282 #ifndef FMT_STATIC_THOUSANDS_SEPARATOR
283
284 TEST(chrono_test, format_default) {
285 EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42)));
286 EXPECT_EQ("42as",
287 fmt::format("{}", std::chrono::duration<int, std::atto>(42)));
288 EXPECT_EQ("42fs",
289 fmt::format("{}", std::chrono::duration<int, std::femto>(42)));
290 EXPECT_EQ("42ps",
291 fmt::format("{}", std::chrono::duration<int, std::pico>(42)));
292 EXPECT_EQ("42ns", fmt::format("{}", std::chrono::nanoseconds(42)));
293 EXPECT_EQ("42µs", fmt::format("{}", std::chrono::microseconds(42)));
294 EXPECT_EQ("42ms", fmt::format("{}", std::chrono::milliseconds(42)));
295 EXPECT_EQ("42cs",
296 fmt::format("{}", std::chrono::duration<int, std::centi>(42)));
297 EXPECT_EQ("42ds",
298 fmt::format("{}", std::chrono::duration<int, std::deci>(42)));
299 EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42)));
300 EXPECT_EQ("42das",
301 fmt::format("{}", std::chrono::duration<int, std::deca>(42)));
302 EXPECT_EQ("42hs",
303 fmt::format("{}", std::chrono::duration<int, std::hecto>(42)));
304 EXPECT_EQ("42ks",
305 fmt::format("{}", std::chrono::duration<int, std::kilo>(42)));
306 EXPECT_EQ("42Ms",
307 fmt::format("{}", std::chrono::duration<int, std::mega>(42)));
308 EXPECT_EQ("42Gs",
309 fmt::format("{}", std::chrono::duration<int, std::giga>(42)));
310 EXPECT_EQ("42Ts",
311 fmt::format("{}", std::chrono::duration<int, std::tera>(42)));
312 EXPECT_EQ("42Ps",
313 fmt::format("{}", std::chrono::duration<int, std::peta>(42)));
314 EXPECT_EQ("42Es",
315 fmt::format("{}", std::chrono::duration<int, std::exa>(42)));
316 EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42)));
317 EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42)));
318 EXPECT_EQ(
319 "42[15]s",
320 fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42)));
321 EXPECT_EQ(
322 "42[15/4]s",
323 fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42)));
324 }
325
326 TEST(chrono_test, align) {
327 auto s = std::chrono::seconds(42);
328 EXPECT_EQ("42s ", fmt::format("{:5}", s));
329 EXPECT_EQ("42s ", fmt::format("{:{}}", s, 5));
330 EXPECT_EQ(" 42s", fmt::format("{:>5}", s));
331 EXPECT_EQ("**42s**", fmt::format("{:*^7}", s));
332 EXPECT_EQ("03:25:45 ",
333 fmt::format("{:12%H:%M:%S}", std::chrono::seconds(12345)));
334 EXPECT_EQ(" 03:25:45",
335 fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345)));
336 EXPECT_EQ("~~03:25:45~~",
337 fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345)));
338 EXPECT_EQ("03:25:45 ",
339 fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12));
340 }
341
342 TEST(chrono_test, format_specs) {
343 EXPECT_EQ("%", fmt::format("{:%%}", std::chrono::seconds(0)));
344 EXPECT_EQ("\n", fmt::format("{:%n}", std::chrono::seconds(0)));
345 EXPECT_EQ("\t", fmt::format("{:%t}", std::chrono::seconds(0)));
346 EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(0)));
347 EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(60)));
348 EXPECT_EQ("42", fmt::format("{:%S}", std::chrono::seconds(42)));
349 EXPECT_EQ("01.234", fmt::format("{:%S}", std::chrono::milliseconds(1234)));
350 EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(0)));
351 EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(60)));
352 EXPECT_EQ("42", fmt::format("{:%M}", std::chrono::minutes(42)));
353 EXPECT_EQ("01", fmt::format("{:%M}", std::chrono::seconds(61)));
354 EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(0)));
355 EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(24)));
356 EXPECT_EQ("14", fmt::format("{:%H}", std::chrono::hours(14)));
357 EXPECT_EQ("01", fmt::format("{:%H}", std::chrono::minutes(61)));
358 EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(0)));
359 EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(12)));
360 EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(24)));
361 EXPECT_EQ("04", fmt::format("{:%I}", std::chrono::hours(4)));
362 EXPECT_EQ("02", fmt::format("{:%I}", std::chrono::hours(14)));
363 EXPECT_EQ("03:25:45",
364 fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345)));
365 EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345)));
366 EXPECT_EQ("03:25:45", fmt::format("{:%T}", std::chrono::seconds(12345)));
367 EXPECT_EQ("12345", fmt::format("{:%Q}", std::chrono::seconds(12345)));
368 EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(12345)));
369 }
370
371 TEST(chrono_test, invalid_specs) {
372 auto sec = std::chrono::seconds(0);
373 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%a}"), sec), fmt::format_error,
374 "no date");
375 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%A}"), sec), fmt::format_error,
376 "no date");
377 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%c}"), sec), fmt::format_error,
378 "no date");
379 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%x}"), sec), fmt::format_error,
380 "no date");
381 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%Ex}"), sec), fmt::format_error,
382 "no date");
383 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%X}"), sec), fmt::format_error,
384 "no date");
385 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%EX}"), sec), fmt::format_error,
386 "no date");
387 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%D}"), sec), fmt::format_error,
388 "no date");
389 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%F}"), sec), fmt::format_error,
390 "no date");
391 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%Ec}"), sec), fmt::format_error,
392 "no date");
393 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%w}"), sec), fmt::format_error,
394 "no date");
395 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%u}"), sec), fmt::format_error,
396 "no date");
397 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%b}"), sec), fmt::format_error,
398 "no date");
399 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%B}"), sec), fmt::format_error,
400 "no date");
401 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%z}"), sec), fmt::format_error,
402 "no date");
403 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%Z}"), sec), fmt::format_error,
404 "no date");
405 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%Eq}"), sec), fmt::format_error,
406 "invalid format");
407 EXPECT_THROW_MSG((void)fmt::format(runtime("{:%Oq}"), sec), fmt::format_error,
408 "invalid format");
409 }
410
411 auto format_tm(const std::tm& time, fmt::string_view spec,
412 const std::locale& loc) -> std::string {
413 auto& facet = std::use_facet<std::time_put<char>>(loc);
414 std::ostringstream os;
415 os.imbue(loc);
416 facet.put(os, os, ' ', &time, spec.begin(), spec.end());
417 return os.str();
418 }
419
420 TEST(chrono_test, locale) {
421 auto loc = get_locale("ja_JP.utf8");
422 if (loc == std::locale::classic()) return;
423 # define EXPECT_TIME(spec, time, duration) \
424 { \
425 auto jp_loc = std::locale("ja_JP.utf8"); \
426 EXPECT_EQ(format_tm(time, spec, jp_loc), \
427 fmt::format(jp_loc, "{:L" spec "}", duration)); \
428 }
429 EXPECT_TIME("%OH", make_hour(14), std::chrono::hours(14));
430 EXPECT_TIME("%OI", make_hour(14), std::chrono::hours(14));
431 EXPECT_TIME("%OM", make_minute(42), std::chrono::minutes(42));
432 EXPECT_TIME("%OS", make_second(42), std::chrono::seconds(42));
433 auto time = make_tm();
434 time.tm_hour = 3;
435 time.tm_min = 25;
436 time.tm_sec = 45;
437 auto sec = std::chrono::seconds(12345);
438 EXPECT_TIME("%r", time, sec);
439 EXPECT_TIME("%p", time, sec);
440 }
441
442 using dms = std::chrono::duration<double, std::milli>;
443
444 TEST(chrono_test, format_default_fp) {
445 typedef std::chrono::duration<float> fs;
446 EXPECT_EQ("1.234s", fmt::format("{}", fs(1.234)));
447 typedef std::chrono::duration<float, std::milli> fms;
448 EXPECT_EQ("1.234ms", fmt::format("{}", fms(1.234)));
449 typedef std::chrono::duration<double> ds;
450 EXPECT_EQ("1.234s", fmt::format("{}", ds(1.234)));
451 EXPECT_EQ("1.234ms", fmt::format("{}", dms(1.234)));
452 }
453
454 TEST(chrono_test, format_precision) {
455 EXPECT_THROW_MSG(
456 (void)fmt::format(runtime("{:.2}"), std::chrono::seconds(42)),
457 fmt::format_error, "precision not allowed for this argument type");
458 EXPECT_EQ("1ms", fmt::format("{:.0}", dms(1.234)));
459 EXPECT_EQ("1.2ms", fmt::format("{:.1}", dms(1.234)));
460 EXPECT_EQ("1.23ms", fmt::format("{:.{}}", dms(1.234), 2));
461
462 EXPECT_EQ("13ms", fmt::format("{:.0}", dms(12.56)));
463 EXPECT_EQ("12.6ms", fmt::format("{:.1}", dms(12.56)));
464 EXPECT_EQ("12.56ms", fmt::format("{:.2}", dms(12.56)));
465 }
466
467 TEST(chrono_test, format_full_specs) {
468 EXPECT_EQ("1ms ", fmt::format("{:6.0}", dms(1.234)));
469 EXPECT_EQ("1.2ms ", fmt::format("{:6.1}", dms(1.234)));
470 EXPECT_EQ(" 1.23ms", fmt::format("{:>8.{}}", dms(1.234), 2));
471 EXPECT_EQ(" 1.2ms ", fmt::format("{:^{}.{}}", dms(1.234), 7, 1));
472 EXPECT_EQ(" 1.23ms ", fmt::format("{0:^{2}.{1}}", dms(1.234), 2, 8));
473 EXPECT_EQ("=1.234ms=", fmt::format("{:=^{}.{}}", dms(1.234), 9, 3));
474 EXPECT_EQ("*1.2340ms*", fmt::format("{:*^10.4}", dms(1.234)));
475
476 EXPECT_EQ("13ms ", fmt::format("{:6.0}", dms(12.56)));
477 EXPECT_EQ(" 13ms", fmt::format("{:>8.{}}", dms(12.56), 0));
478 EXPECT_EQ(" 13ms ", fmt::format("{:^{}.{}}", dms(12.56), 6, 0));
479 EXPECT_EQ(" 13ms ", fmt::format("{0:^{2}.{1}}", dms(12.56), 0, 8));
480 EXPECT_EQ("==13ms===", fmt::format("{:=^{}.{}}", dms(12.56), 9, 0));
481 EXPECT_EQ("***13ms***", fmt::format("{:*^10.0}", dms(12.56)));
482 }
483
484 TEST(chrono_test, format_simple_q) {
485 typedef std::chrono::duration<float> fs;
486 EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", fs(1.234)));
487 typedef std::chrono::duration<float, std::milli> fms;
488 EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", fms(1.234)));
489 typedef std::chrono::duration<double> ds;
490 EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", ds(1.234)));
491 EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", dms(1.234)));
492 }
493
494 TEST(chrono_test, format_precision_q) {
495 EXPECT_THROW_MSG(
496 (void)fmt::format(runtime("{:.2%Q %q}"), std::chrono::seconds(42)),
497 fmt::format_error, "precision not allowed for this argument type");
498 EXPECT_EQ("1.2 ms", fmt::format("{:.1%Q %q}", dms(1.234)));
499 EXPECT_EQ("1.23 ms", fmt::format("{:.{}%Q %q}", dms(1.234), 2));
500 }
501
502 TEST(chrono_test, format_full_specs_q) {
503 EXPECT_EQ("1 ms ", fmt::format("{:7.0%Q %q}", dms(1.234)));
504 EXPECT_EQ("1.2 ms ", fmt::format("{:7.1%Q %q}", dms(1.234)));
505 EXPECT_EQ(" 1.23 ms", fmt::format("{:>8.{}%Q %q}", dms(1.234), 2));
506 EXPECT_EQ(" 1.2 ms ", fmt::format("{:^{}.{}%Q %q}", dms(1.234), 8, 1));
507 EXPECT_EQ(" 1.23 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(1.234), 2, 9));
508 EXPECT_EQ("=1.234 ms=", fmt::format("{:=^{}.{}%Q %q}", dms(1.234), 10, 3));
509 EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234)));
510
511 EXPECT_EQ("13 ms ", fmt::format("{:7.0%Q %q}", dms(12.56)));
512 EXPECT_EQ(" 13 ms", fmt::format("{:>8.{}%Q %q}", dms(12.56), 0));
513 EXPECT_EQ(" 13 ms ", fmt::format("{:^{}.{}%Q %q}", dms(12.56), 8, 0));
514 EXPECT_EQ(" 13 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(12.56), 0, 9));
515 EXPECT_EQ("==13 ms==", fmt::format("{:=^{}.{}%Q %q}", dms(12.56), 9, 0));
516 EXPECT_EQ("***13 ms***", fmt::format("{:*^11.0%Q %q}", dms(12.56)));
517 }
518
519 TEST(chrono_test, invalid_width_id) {
520 EXPECT_THROW((void)fmt::format(runtime("{:{o}"), std::chrono::seconds(0)),
521 fmt::format_error);
522 }
523
524 TEST(chrono_test, invalid_colons) {
525 EXPECT_THROW((void)fmt::format(runtime("{0}=:{0::"), std::chrono::seconds(0)),
526 fmt::format_error);
527 }
528
529 TEST(chrono_test, negative_durations) {
530 EXPECT_EQ("-12345", fmt::format("{:%Q}", std::chrono::seconds(-12345)));
531 EXPECT_EQ("-03:25:45",
532 fmt::format("{:%H:%M:%S}", std::chrono::seconds(-12345)));
533 EXPECT_EQ("-00:01",
534 fmt::format("{:%M:%S}", std::chrono::duration<double>(-1)));
535 EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(-12345)));
536 EXPECT_EQ("-00.127",
537 fmt::format("{:%S}",
538 std::chrono::duration<signed char, std::milli>{-127}));
539 auto min = std::numeric_limits<int>::min();
540 EXPECT_EQ(fmt::format("{}", min),
541 fmt::format("{:%Q}", std::chrono::duration<int>(min)));
542 }
543
544 TEST(chrono_test, special_durations) {
545 auto value = fmt::format("{:%S}", std::chrono::duration<double>(1e20));
546 EXPECT_EQ(value, "40");
547 auto nan = std::numeric_limits<double>::quiet_NaN();
548 EXPECT_EQ(
549 "nan nan nan nan nan:nan nan",
550 fmt::format("{:%I %H %M %S %R %r}", std::chrono::duration<double>(nan)));
551 EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::exa>(1)),
552 "1Es");
553 EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::atto>(1)),
554 "1as");
555 EXPECT_EQ(fmt::format("{:%R}", std::chrono::duration<char, std::mega>{2}),
556 "03:33");
557 EXPECT_EQ(fmt::format("{:%T}", std::chrono::duration<char, std::mega>{2}),
558 "03:33:20");
559 }
560
561 TEST(chrono_test, unsigned_duration) {
562 EXPECT_EQ("42s", fmt::format("{}", std::chrono::duration<unsigned>(42)));
563 }
564
565 TEST(chrono_test, weekday) {
566 auto loc = get_locale("ru_RU.UTF-8");
567 std::locale::global(loc);
568 auto mon = fmt::weekday(1);
569
570 auto tm = std::tm();
571 tm.tm_wday = static_cast<int>(mon.c_encoding());
572
573 EXPECT_EQ(fmt::format("{}", mon), "Mon");
574 EXPECT_EQ(fmt::format("{:%a}", tm), "Mon");
575
576 if (loc != std::locale::classic()) {
577 EXPECT_THAT((std::vector<std::string>{"пн", "Пн", "пнд", "Пнд"}),
578 Contains(fmt::format(loc, "{:L}", mon)));
579 EXPECT_THAT((std::vector<std::string>{"пн", "Пн", "пнд", "Пнд"}),
580 Contains(fmt::format(loc, "{:%a}", tm)));
581 }
582 }
583
584 TEST(chrono_test, cpp20_duration_subsecond_support) {
585 using attoseconds = std::chrono::duration<long long, std::atto>;
586 // Check that 18 digits of subsecond precision are supported.
587 EXPECT_EQ(fmt::format("{:%S}", attoseconds{999999999999999999}),
588 "00.999999999999999999");
589 EXPECT_EQ(fmt::format("{:%S}", attoseconds{673231113420148734}),
590 "00.673231113420148734");
591 EXPECT_EQ(fmt::format("{:%S}", attoseconds{-673231113420148734}),
592 "-00.673231113420148734");
593 EXPECT_EQ(fmt::format("{:%S}", std::chrono::nanoseconds{13420148734}),
594 "13.420148734");
595 EXPECT_EQ(fmt::format("{:%S}", std::chrono::nanoseconds{-13420148734}),
596 "-13.420148734");
597 EXPECT_EQ(fmt::format("{:%S}", std::chrono::milliseconds{1234}), "01.234");
598 {
599 // Check that {:%H:%M:%S} is equivalent to {:%T}.
600 auto dur = std::chrono::milliseconds{3601234};
601 auto formatted_dur = fmt::format("{:%T}", dur);
602 EXPECT_EQ(formatted_dur, "01:00:01.234");
603 EXPECT_EQ(fmt::format("{:%H:%M:%S}", dur), formatted_dur);
604 }
605 using nanoseconds_dbl = std::chrono::duration<double, std::nano>;
606 EXPECT_EQ(fmt::format("{:%S}", nanoseconds_dbl{-123456789}), "-00.123456789");
607 EXPECT_EQ(fmt::format("{:%S}", nanoseconds_dbl{9123456789}), "09.123456789");
608 // Verify that only the seconds part is extracted and printed.
609 EXPECT_EQ(fmt::format("{:%S}", nanoseconds_dbl{99123456789}), "39.123456789");
610 EXPECT_EQ(fmt::format("{:%S}", nanoseconds_dbl{99123000000}), "39.123000000");
611 {
612 // Now the hour is printed, and we also test if negative doubles work.
613 auto dur = nanoseconds_dbl{-99123456789};
614 auto formatted_dur = fmt::format("{:%T}", dur);
615 EXPECT_EQ(formatted_dur, "-00:01:39.123456789");
616 EXPECT_EQ(fmt::format("{:%H:%M:%S}", dur), formatted_dur);
617 }
618 // Check that durations with precision greater than std::chrono::seconds have
619 // fixed precision, and print zeros even if there is no fractional part.
620 EXPECT_EQ(fmt::format("{:%S}", std::chrono::microseconds{7000000}),
621 "07.000000");
622 }
623
624 #endif // FMT_STATIC_THOUSANDS_SEPARATOR
+0
-66
source/misc/embedded_libs/fmt-8.1.1/test/color-test.cc less more
0 // Formatting library for C++ - color tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/color.h"
8
9 #include <iterator> // std::back_inserter
10
11 #include "gtest-extra.h" // EXPECT_WRITE
12
13 TEST(color_test, format) {
14 EXPECT_EQ(fmt::format(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"),
15 "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m");
16 EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue"),
17 "\x1b[38;2;000;000;255mblue\x1b[0m");
18 EXPECT_EQ(
19 fmt::format(fg(fmt::color::blue) | bg(fmt::color::red), "two color"),
20 "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m");
21 EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold"), "\x1b[1mbold\x1b[0m");
22 EXPECT_EQ(fmt::format(fmt::emphasis::faint, "faint"), "\x1b[2mfaint\x1b[0m");
23 EXPECT_EQ(fmt::format(fmt::emphasis::italic, "italic"),
24 "\x1b[3mitalic\x1b[0m");
25 EXPECT_EQ(fmt::format(fmt::emphasis::underline, "underline"),
26 "\x1b[4munderline\x1b[0m");
27 EXPECT_EQ(fmt::format(fmt::emphasis::blink, "blink"), "\x1b[5mblink\x1b[0m");
28 EXPECT_EQ(fmt::format(fmt::emphasis::reverse, "reverse"),
29 "\x1b[7mreverse\x1b[0m");
30 EXPECT_EQ(fmt::format(fmt::emphasis::conceal, "conceal"),
31 "\x1b[8mconceal\x1b[0m");
32 EXPECT_EQ(fmt::format(fmt::emphasis::strikethrough, "strikethrough"),
33 "\x1b[9mstrikethrough\x1b[0m");
34 EXPECT_EQ(
35 fmt::format(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"),
36 "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m");
37 EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold error"),
38 "\x1b[1mbold error\x1b[0m");
39 EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue log"),
40 "\x1b[38;2;000;000;255mblue log\x1b[0m");
41 EXPECT_EQ(fmt::format(fmt::text_style(), "hi"), "hi");
42 EXPECT_EQ(fmt::format(fg(fmt::terminal_color::red), "tred"),
43 "\x1b[31mtred\x1b[0m");
44 EXPECT_EQ(fmt::format(bg(fmt::terminal_color::cyan), "tcyan"),
45 "\x1b[46mtcyan\x1b[0m");
46 EXPECT_EQ(fmt::format(fg(fmt::terminal_color::bright_green), "tbgreen"),
47 "\x1b[92mtbgreen\x1b[0m");
48 EXPECT_EQ(fmt::format(bg(fmt::terminal_color::bright_magenta), "tbmagenta"),
49 "\x1b[105mtbmagenta\x1b[0m");
50 EXPECT_EQ(fmt::format(fg(fmt::terminal_color::red), "{}", "foo"),
51 "\x1b[31mfoo\x1b[0m");
52 }
53
54 TEST(color_test, format_to) {
55 auto out = std::string();
56 fmt::format_to(std::back_inserter(out), fg(fmt::rgb(255, 20, 30)),
57 "rgb(255,20,30){}{}{}", 1, 2, 3);
58 EXPECT_EQ(fmt::to_string(out),
59 "\x1b[38;2;255;020;030mrgb(255,20,30)123\x1b[0m");
60 }
61
62 TEST(color_test, print) {
63 EXPECT_WRITE(stdout, fmt::print(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"),
64 "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m");
65 }
+0
-203
source/misc/embedded_libs/fmt-8.1.1/test/compile-error-test/CMakeLists.txt less more
0 # Test if compile errors are produced where necessary.
1
2 cmake_minimum_required(VERSION 3.1...3.18)
3 project(compile-error-test CXX)
4
5 set(fmt_headers "
6 #include <fmt/format.h>
7 #include <fmt/xchar.h>
8 ")
9
10 set(error_test_names "")
11 set(non_error_test_content "")
12
13 # For error tests (we expect them to produce compilation error):
14 # * adds a name of test into `error_test_names` list
15 # * generates a single source file (with the same name) for each test
16 # For non-error tests (we expect them to compile successfully):
17 # * adds a code segment as separate function to `non_error_test_content`
18 function (expect_compile name code_fragment)
19 cmake_parse_arguments(EXPECT_COMPILE "ERROR" "" "" ${ARGN})
20 string(MAKE_C_IDENTIFIER "${name}" test_name)
21
22 if (EXPECT_COMPILE_ERROR)
23 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/${test_name}.cc" "
24 ${fmt_headers}
25 void ${test_name}() {
26 ${code_fragment}
27 }
28 ")
29 set(error_test_names_copy "${error_test_names}")
30 list(APPEND error_test_names_copy "${test_name}")
31 set(error_test_names "${error_test_names_copy}" PARENT_SCOPE)
32 else()
33 set(non_error_test_content "
34 ${non_error_test_content}
35 void ${test_name}() {
36 ${code_fragment}
37 }" PARENT_SCOPE)
38 endif()
39 endfunction ()
40
41 # Generates a source file for non-error test with `non_error_test_content` and
42 # CMake project file with all error and single non-error test targets.
43 function (run_tests)
44 set(cmake_targets "")
45 foreach(test_name IN LISTS error_test_names)
46 set(cmake_targets "
47 ${cmake_targets}
48 add_library(test-${test_name} ${test_name}.cc)
49 target_link_libraries(test-${test_name} PRIVATE fmt::fmt)
50 ")
51 endforeach()
52
53 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/non_error_test.cc" "
54 ${fmt_headers}
55 ${non_error_test_content}
56 ")
57 set(cmake_targets "
58 ${cmake_targets}
59 add_library(non-error-test non_error_test.cc)
60 target_link_libraries(non-error-test PRIVATE fmt::fmt)
61 ")
62
63 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/CMakeLists.txt" "
64 cmake_minimum_required(VERSION 3.1...3.18)
65 project(tests CXX)
66 add_subdirectory(${FMT_DIR} fmt)
67 ${cmake_targets}
68 ")
69
70 set(build_directory "${CMAKE_CURRENT_BINARY_DIR}/test/build")
71 file(MAKE_DIRECTORY "${build_directory}")
72 execute_process(
73 COMMAND
74 "${CMAKE_COMMAND}"
75 "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
76 "-DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}"
77 "-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}"
78 "-DCMAKE_GENERATOR=${CMAKE_GENERATOR}"
79 "-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}"
80 "-DFMT_DIR=${FMT_DIR}"
81 "${CMAKE_CURRENT_BINARY_DIR}/test"
82 WORKING_DIRECTORY "${build_directory}"
83 RESULT_VARIABLE result_var
84 OUTPUT_VARIABLE output_var
85 ERROR_VARIABLE output_var)
86 if (NOT result_var EQUAL 0)
87 message(FATAL_ERROR "Unable to configure:\n${output_var}")
88 endif()
89
90 foreach(test_name IN LISTS error_test_names)
91 execute_process(
92 COMMAND
93 "${CMAKE_COMMAND}" --build "${build_directory}" --target "test-${test_name}"
94 WORKING_DIRECTORY "${build_directory}"
95 RESULT_VARIABLE result_var
96 OUTPUT_VARIABLE output_var
97 ERROR_QUIET)
98 if (result_var EQUAL 0)
99 message(SEND_ERROR "No compile error for \"${test_name}\":\n${output_var}")
100 endif ()
101 endforeach()
102
103 execute_process(
104 COMMAND
105 "${CMAKE_COMMAND}" --build "${build_directory}" --target "non-error-test"
106 WORKING_DIRECTORY "${build_directory}"
107 RESULT_VARIABLE result_var
108 OUTPUT_VARIABLE output_var
109 ERROR_VARIABLE output_var)
110 if (NOT result_var EQUAL 0)
111 message(SEND_ERROR "Compile error for combined non-error test:\n${output_var}")
112 endif ()
113 endfunction ()
114
115
116 # check if the source file skeleton compiles
117 expect_compile(check "")
118 expect_compile(check-error "compilation_error" ERROR)
119
120 # Formatting a wide character with a narrow format string is forbidden.
121 expect_compile(wide-character-narrow-format-string "fmt::format(L\"{}\", L'a');")
122 expect_compile(wide-character-narrow-format-string-error "fmt::format(\"{}\", L'a');" ERROR)
123
124 # Formatting a wide string with a narrow format string is forbidden.
125 expect_compile(wide-string-narrow-format-string "fmt::format(L\"{}\", L\"foo\");")
126 expect_compile(wide-string-narrow-format-string-error "fmt::format(\"{}\", L\"foo\");" ERROR)
127
128 # Formatting a narrow string with a wide format string is forbidden because
129 # mixing UTF-8 with UTF-16/32 can result in an invalid output.
130 expect_compile(narrow-string-wide-format-string "fmt::format(L\"{}\", L\"foo\");")
131 expect_compile(narrow-string-wide-format-string-error "fmt::format(L\"{}\", \"foo\");" ERROR)
132
133 expect_compile(cast-to-string "
134 struct S {
135 operator std::string() const { return std::string(); }
136 };
137 fmt::format(\"{}\", std::string(S()));
138 ")
139 expect_compile(cast-to-string-error "
140 struct S {
141 operator std::string() const { return std::string(); }
142 };
143 fmt::format(\"{}\", S());
144 " ERROR)
145
146 # Formatting a function
147 expect_compile(format-function "
148 void (*f)();
149 fmt::format(\"{}\", fmt::ptr(f));
150 ")
151 expect_compile(format-function-error "
152 void (*f)();
153 fmt::format(\"{}\", f);
154 " ERROR)
155
156 # Make sure that compiler features detected in the header
157 # match the features detected in CMake.
158 if (SUPPORTS_USER_DEFINED_LITERALS)
159 set(supports_udl 1)
160 else ()
161 set(supports_udl 0)
162 endif ()
163 expect_compile(udl-check "
164 #if FMT_USE_USER_DEFINED_LITERALS != ${supports_udl}
165 # error
166 #endif
167 ")
168
169 if (CMAKE_CXX_STANDARD GREATER_EQUAL 20)
170 # Compile-time argument type check
171 expect_compile(format-string-number-spec "
172 #ifdef FMT_HAS_CONSTEVAL
173 fmt::format(\"{:d}\", 42);
174 #endif
175 ")
176 expect_compile(format-string-number-spec-error "
177 #ifdef FMT_HAS_CONSTEVAL
178 fmt::format(\"{:d}\", \"I am not a number\");
179 #else
180 #error
181 #endif
182 " ERROR)
183
184 # Compile-time argument name check
185 expect_compile(format-string-name "
186 #if defined(FMT_HAS_CONSTEVAL) && FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
187 using namespace fmt::literals;
188 fmt::print(\"{foo}\", \"foo\"_a=42);
189 #endif
190 ")
191 expect_compile(format-string-name-error "
192 #if defined(FMT_HAS_CONSTEVAL) && FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
193 using namespace fmt::literals;
194 fmt::print(\"{foo}\", \"bar\"_a=42);
195 #else
196 #error
197 #endif
198 " ERROR)
199 endif ()
200
201 # Run all tests
202 run_tests()
+0
-62
source/misc/embedded_libs/fmt-8.1.1/test/compile-fp-test.cc less more
0 // Formatting library for C++ - formatting library tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/compile.h"
8 #include "gmock/gmock.h"
9
10 #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806 && \
11 defined(__cpp_constexpr) && __cpp_constexpr >= 201907 && \
12 defined(__cpp_constexpr_dynamic_alloc) && \
13 __cpp_constexpr_dynamic_alloc >= 201907 && __cplusplus >= 202002L
14 template <size_t max_string_length, typename Char = char> struct test_string {
15 template <typename T> constexpr bool operator==(const T& rhs) const noexcept {
16 return fmt::basic_string_view<Char>(rhs).compare(buffer) == 0;
17 }
18 Char buffer[max_string_length]{};
19 };
20
21 template <size_t max_string_length, typename Char = char, typename... Args>
22 consteval auto test_format(auto format, const Args&... args) {
23 test_string<max_string_length, Char> string{};
24 fmt::format_to(string.buffer, format, args...);
25 return string;
26 }
27
28 TEST(compile_time_formatting_test, floating_point) {
29 EXPECT_EQ("0", test_format<2>(FMT_COMPILE("{}"), 0.0f));
30 EXPECT_EQ("392.500000", test_format<11>(FMT_COMPILE("{0:f}"), 392.5f));
31
32 EXPECT_EQ("0", test_format<2>(FMT_COMPILE("{:}"), 0.0));
33 EXPECT_EQ("0.000000", test_format<9>(FMT_COMPILE("{:f}"), 0.0));
34 EXPECT_EQ("0", test_format<2>(FMT_COMPILE("{:g}"), 0.0));
35 EXPECT_EQ("392.65", test_format<7>(FMT_COMPILE("{:}"), 392.65));
36 EXPECT_EQ("392.65", test_format<7>(FMT_COMPILE("{:g}"), 392.65));
37 EXPECT_EQ("392.65", test_format<7>(FMT_COMPILE("{:G}"), 392.65));
38 EXPECT_EQ("4.9014e+06", test_format<11>(FMT_COMPILE("{:g}"), 4.9014e6));
39 EXPECT_EQ("-392.650000", test_format<12>(FMT_COMPILE("{:f}"), -392.65));
40 EXPECT_EQ("-392.650000", test_format<12>(FMT_COMPILE("{:F}"), -392.65));
41
42 EXPECT_EQ("3.926500e+02", test_format<13>(FMT_COMPILE("{0:e}"), 392.65));
43 EXPECT_EQ("3.926500E+02", test_format<13>(FMT_COMPILE("{0:E}"), 392.65));
44 EXPECT_EQ("+0000392.6", test_format<11>(FMT_COMPILE("{0:+010.4g}"), 392.65));
45 EXPECT_EQ("9223372036854775808.000000",
46 test_format<27>(FMT_COMPILE("{:f}"), 9223372036854775807.0));
47
48 constexpr double nan = std::numeric_limits<double>::quiet_NaN();
49 EXPECT_EQ("nan", test_format<4>(FMT_COMPILE("{}"), nan));
50 EXPECT_EQ("+nan", test_format<5>(FMT_COMPILE("{:+}"), nan));
51 if (std::signbit(-nan))
52 EXPECT_EQ("-nan", test_format<5>(FMT_COMPILE("{}"), -nan));
53 else
54 fmt::print("Warning: compiler doesn't handle negative NaN correctly");
55
56 constexpr double inf = std::numeric_limits<double>::infinity();
57 EXPECT_EQ("inf", test_format<4>(FMT_COMPILE("{}"), inf));
58 EXPECT_EQ("+inf", test_format<5>(FMT_COMPILE("{:+}"), inf));
59 EXPECT_EQ("-inf", test_format<5>(FMT_COMPILE("{}"), -inf));
60 }
61 #endif
+0
-376
source/misc/embedded_libs/fmt-8.1.1/test/compile-test.cc less more
0 // Formatting library for C++ - formatting library tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/compile.h"
8
9 #include <type_traits>
10
11 #include "fmt/chrono.h"
12 #include "gmock/gmock.h"
13 #include "gtest-extra.h"
14
15 TEST(iterator_test, counting_iterator) {
16 auto it = fmt::detail::counting_iterator();
17 auto prev = it++;
18 EXPECT_EQ(prev.count(), 0);
19 EXPECT_EQ(it.count(), 1);
20 EXPECT_EQ((it + 41).count(), 42);
21 }
22
23 TEST(iterator_test, truncating_iterator) {
24 char* p = nullptr;
25 auto it = fmt::detail::truncating_iterator<char*>(p, 3);
26 auto prev = it++;
27 EXPECT_EQ(prev.base(), p);
28 EXPECT_EQ(it.base(), p + 1);
29 }
30
31 TEST(iterator_test, truncating_iterator_default_construct) {
32 auto it = fmt::detail::truncating_iterator<char*>();
33 EXPECT_EQ(nullptr, it.base());
34 EXPECT_EQ(std::size_t{0}, it.count());
35 }
36
37 #ifdef __cpp_lib_ranges
38 TEST(iterator_test, truncating_iterator_is_output_iterator) {
39 static_assert(
40 std::output_iterator<fmt::detail::truncating_iterator<char*>, char>);
41 }
42 #endif
43
44 TEST(iterator_test, truncating_back_inserter) {
45 auto buffer = std::string();
46 auto bi = std::back_inserter(buffer);
47 auto it = fmt::detail::truncating_iterator<decltype(bi)>(bi, 2);
48 *it++ = '4';
49 *it++ = '2';
50 *it++ = '1';
51 EXPECT_EQ(buffer.size(), 2);
52 EXPECT_EQ(buffer, "42");
53 }
54
55 TEST(compile_test, compile_fallback) {
56 // FMT_COMPILE should fallback on runtime formatting when `if constexpr` is
57 // not available.
58 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), 42));
59 }
60
61 struct type_with_get {
62 template <int> friend void get(type_with_get);
63 };
64
65 FMT_BEGIN_NAMESPACE
66 template <> struct formatter<type_with_get> : formatter<int> {
67 template <typename FormatContext>
68 auto format(type_with_get, FormatContext& ctx) -> decltype(ctx.out()) {
69 return formatter<int>::format(42, ctx);
70 }
71 };
72 FMT_END_NAMESPACE
73
74 TEST(compile_test, compile_type_with_get) {
75 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), type_with_get()));
76 }
77
78 #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
79 struct test_formattable {};
80
81 FMT_BEGIN_NAMESPACE
82 template <> struct formatter<test_formattable> : formatter<const char*> {
83 char word_spec = 'f';
84 constexpr auto parse(format_parse_context& ctx) {
85 auto it = ctx.begin(), end = ctx.end();
86 if (it == end || *it == '}') return it;
87 if (it != end && (*it == 'f' || *it == 'b')) word_spec = *it++;
88 if (it != end && *it != '}') throw format_error("invalid format");
89 return it;
90 }
91 template <typename FormatContext>
92 constexpr auto format(test_formattable, FormatContext& ctx) const
93 -> decltype(ctx.out()) {
94 return formatter<const char*>::format(word_spec == 'f' ? "foo" : "bar",
95 ctx);
96 }
97 };
98 FMT_END_NAMESPACE
99
100 TEST(compile_test, format_default) {
101 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), 42));
102 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), 42u));
103 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), 42ll));
104 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), 42ull));
105 EXPECT_EQ("true", fmt::format(FMT_COMPILE("{}"), true));
106 EXPECT_EQ("x", fmt::format(FMT_COMPILE("{}"), 'x'));
107 EXPECT_EQ("4.2", fmt::format(FMT_COMPILE("{}"), 4.2));
108 EXPECT_EQ("foo", fmt::format(FMT_COMPILE("{}"), "foo"));
109 EXPECT_EQ("foo", fmt::format(FMT_COMPILE("{}"), std::string("foo")));
110 EXPECT_EQ("foo", fmt::format(FMT_COMPILE("{}"), test_formattable()));
111 auto t = std::chrono::system_clock::now();
112 EXPECT_EQ(fmt::format("{}", t), fmt::format(FMT_COMPILE("{}"), t));
113 # ifdef __cpp_lib_byte
114 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), std::byte{42}));
115 # endif
116 }
117
118 TEST(compile_test, format_wide_string) {
119 EXPECT_EQ(L"42", fmt::format(FMT_COMPILE(L"{}"), 42));
120 }
121
122 TEST(compile_test, format_specs) {
123 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{:x}"), 0x42));
124 EXPECT_EQ("1.2 ms ",
125 fmt::format(FMT_COMPILE("{:7.1%Q %q}"),
126 std::chrono::duration<double, std::milli>(1.234)));
127 }
128
129 TEST(compile_test, dynamic_format_specs) {
130 EXPECT_EQ("foo ", fmt::format(FMT_COMPILE("{:{}}"), "foo", 5));
131 EXPECT_EQ(" 3.14", fmt::format(FMT_COMPILE("{:{}.{}f}"), 3.141592, 6, 2));
132 EXPECT_EQ(
133 "=1.234ms=",
134 fmt::format(FMT_COMPILE("{:=^{}.{}}"),
135 std::chrono::duration<double, std::milli>(1.234), 9, 3));
136 }
137
138 TEST(compile_test, manual_ordering) {
139 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{0}"), 42));
140 EXPECT_EQ(" -42", fmt::format(FMT_COMPILE("{0:4}"), -42));
141 EXPECT_EQ("41 43", fmt::format(FMT_COMPILE("{0} {1}"), 41, 43));
142 EXPECT_EQ("41 43", fmt::format(FMT_COMPILE("{1} {0}"), 43, 41));
143 EXPECT_EQ("41 43", fmt::format(FMT_COMPILE("{0} {2}"), 41, 42, 43));
144 EXPECT_EQ(" 41 43", fmt::format(FMT_COMPILE("{1:{2}} {0:4}"), 43, 41, 4));
145 EXPECT_EQ("42 1.2 ms ",
146 fmt::format(FMT_COMPILE("{0} {1:7.1%Q %q}"), 42,
147 std::chrono::duration<double, std::milli>(1.234)));
148 EXPECT_EQ(
149 "true 42 42 foo 0x1234 foo",
150 fmt::format(FMT_COMPILE("{0} {1} {2} {3} {4} {5}"), true, 42, 42.0f,
151 "foo", reinterpret_cast<void*>(0x1234), test_formattable()));
152 EXPECT_EQ(L"42", fmt::format(FMT_COMPILE(L"{0}"), 42));
153 }
154
155 TEST(compile_test, named) {
156 auto runtime_named_field_compiled =
157 fmt::detail::compile<decltype(fmt::arg("arg", 42))>(FMT_COMPILE("{arg}"));
158 static_assert(std::is_same_v<decltype(runtime_named_field_compiled),
159 fmt::detail::runtime_named_field<char>>);
160
161 EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), fmt::arg("arg", 42)));
162 EXPECT_EQ("41 43", fmt::format(FMT_COMPILE("{} {}"), fmt::arg("arg", 41),
163 fmt::arg("arg", 43)));
164
165 EXPECT_EQ("foobar",
166 fmt::format(FMT_COMPILE("{a0}{a1}"), fmt::arg("a0", "foo"),
167 fmt::arg("a1", "bar")));
168 EXPECT_EQ("foobar", fmt::format(FMT_COMPILE("{}{a1}"), fmt::arg("a0", "foo"),
169 fmt::arg("a1", "bar")));
170 EXPECT_EQ("foofoo", fmt::format(FMT_COMPILE("{a0}{}"), fmt::arg("a0", "foo"),
171 fmt::arg("a1", "bar")));
172 EXPECT_EQ("foobar", fmt::format(FMT_COMPILE("{0}{a1}"), fmt::arg("a0", "foo"),
173 fmt::arg("a1", "bar")));
174 EXPECT_EQ("foobar", fmt::format(FMT_COMPILE("{a0}{1}"), fmt::arg("a0", "foo"),
175 fmt::arg("a1", "bar")));
176
177 EXPECT_EQ("foobar",
178 fmt::format(FMT_COMPILE("{}{a1}"), "foo", fmt::arg("a1", "bar")));
179 EXPECT_EQ("foobar",
180 fmt::format(FMT_COMPILE("{a0}{a1}"), fmt::arg("a1", "bar"),
181 fmt::arg("a2", "baz"), fmt::arg("a0", "foo")));
182 EXPECT_EQ(" bar foo ",
183 fmt::format(FMT_COMPILE(" {foo} {bar} "), fmt::arg("foo", "bar"),
184 fmt::arg("bar", "foo")));
185
186 EXPECT_THROW(fmt::format(FMT_COMPILE("{invalid}"), fmt::arg("valid", 42)),
187 fmt::format_error);
188
189 # if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
190 using namespace fmt::literals;
191 auto statically_named_field_compiled =
192 fmt::detail::compile<decltype("arg"_a = 42)>(FMT_COMPILE("{arg}"));
193 static_assert(std::is_same_v<decltype(statically_named_field_compiled),
194 fmt::detail::field<char, int, 0>>);
195
196 EXPECT_EQ("41 43",
197 fmt::format(FMT_COMPILE("{a0} {a1}"), "a0"_a = 41, "a1"_a = 43));
198 EXPECT_EQ("41 43",
199 fmt::format(FMT_COMPILE("{a1} {a0}"), "a0"_a = 43, "a1"_a = 41));
200 # endif
201 }
202
203 TEST(compile_test, format_to) {
204 char buf[8];
205 auto end = fmt::format_to(buf, FMT_COMPILE("{}"), 42);
206 *end = '\0';
207 EXPECT_STREQ("42", buf);
208 end = fmt::format_to(buf, FMT_COMPILE("{:x}"), 42);
209 *end = '\0';
210 EXPECT_STREQ("2a", buf);
211 }
212
213 TEST(compile_test, format_to_n) {
214 constexpr auto buffer_size = 8;
215 char buffer[buffer_size];
216 auto res = fmt::format_to_n(buffer, buffer_size, FMT_COMPILE("{}"), 42);
217 *res.out = '\0';
218 EXPECT_STREQ("42", buffer);
219 res = fmt::format_to_n(buffer, buffer_size, FMT_COMPILE("{:x}"), 42);
220 *res.out = '\0';
221 EXPECT_STREQ("2a", buffer);
222 }
223
224 TEST(compile_test, formatted_size) {
225 EXPECT_EQ(2, fmt::formatted_size(FMT_COMPILE("{0}"), 42));
226 EXPECT_EQ(5, fmt::formatted_size(FMT_COMPILE("{0:<4.2f}"), 42.0));
227 }
228
229 TEST(compile_test, text_and_arg) {
230 EXPECT_EQ(">>>42<<<", fmt::format(FMT_COMPILE(">>>{}<<<"), 42));
231 EXPECT_EQ("42!", fmt::format(FMT_COMPILE("{}!"), 42));
232 }
233
234 TEST(compile_test, unknown_format_fallback) {
235 EXPECT_EQ(" 42 ",
236 fmt::format(FMT_COMPILE("{name:^4}"), fmt::arg("name", 42)));
237
238 std::vector<char> v;
239 fmt::format_to(std::back_inserter(v), FMT_COMPILE("{name:^4}"),
240 fmt::arg("name", 42));
241 EXPECT_EQ(" 42 ", fmt::string_view(v.data(), v.size()));
242
243 char buffer[4];
244 auto result = fmt::format_to_n(buffer, 4, FMT_COMPILE("{name:^5}"),
245 fmt::arg("name", 42));
246 EXPECT_EQ(5u, result.size);
247 EXPECT_EQ(buffer + 4, result.out);
248 EXPECT_EQ(" 42 ", fmt::string_view(buffer, 4));
249 }
250
251 TEST(compile_test, empty) { EXPECT_EQ("", fmt::format(FMT_COMPILE(""))); }
252
253 struct to_stringable {
254 friend fmt::string_view to_string_view(to_stringable) { return {}; }
255 };
256
257 FMT_BEGIN_NAMESPACE
258 template <> struct formatter<to_stringable> {
259 auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) {
260 return ctx.begin();
261 }
262
263 template <typename FormatContext>
264 auto format(const to_stringable&, FormatContext& ctx) -> decltype(ctx.out()) {
265 return ctx.out();
266 }
267 };
268 FMT_END_NAMESPACE
269
270 TEST(compile_test, to_string_and_formatter) {
271 fmt::format(FMT_COMPILE("{}"), to_stringable());
272 }
273
274 TEST(compile_test, print) {
275 EXPECT_WRITE(stdout, fmt::print(FMT_COMPILE("Don't {}!"), "panic"),
276 "Don't panic!");
277 EXPECT_WRITE(stderr, fmt::print(stderr, FMT_COMPILE("Don't {}!"), "panic"),
278 "Don't panic!");
279 }
280 #endif
281
282 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
283 TEST(compile_test, compile_format_string_literal) {
284 using namespace fmt::literals;
285 EXPECT_EQ("", fmt::format(""_cf));
286 EXPECT_EQ("42", fmt::format("{}"_cf, 42));
287 EXPECT_EQ(L"42", fmt::format(L"{}"_cf, 42));
288 }
289 #endif
290
291 #if __cplusplus >= 202002L || \
292 (__cplusplus >= 201709L && FMT_GCC_VERSION >= 1002)
293 template <size_t max_string_length, typename Char = char> struct test_string {
294 template <typename T> constexpr bool operator==(const T& rhs) const noexcept {
295 return fmt::basic_string_view<Char>(rhs).compare(buffer) == 0;
296 }
297 Char buffer[max_string_length]{};
298 };
299
300 template <size_t max_string_length, typename Char = char, typename... Args>
301 consteval auto test_format(auto format, const Args&... args) {
302 test_string<max_string_length, Char> string{};
303 fmt::format_to(string.buffer, format, args...);
304 return string;
305 }
306
307 TEST(compile_time_formatting_test, bool) {
308 EXPECT_EQ("true", test_format<5>(FMT_COMPILE("{}"), true));
309 EXPECT_EQ("false", test_format<6>(FMT_COMPILE("{}"), false));
310 EXPECT_EQ("true ", test_format<6>(FMT_COMPILE("{:5}"), true));
311 EXPECT_EQ("1", test_format<2>(FMT_COMPILE("{:d}"), true));
312 }
313
314 TEST(compile_time_formatting_test, integer) {
315 EXPECT_EQ("42", test_format<3>(FMT_COMPILE("{}"), 42));
316 EXPECT_EQ("420", test_format<4>(FMT_COMPILE("{}"), 420));
317 EXPECT_EQ("42 42", test_format<6>(FMT_COMPILE("{} {}"), 42, 42));
318 EXPECT_EQ("42 42",
319 test_format<6>(FMT_COMPILE("{} {}"), uint32_t{42}, uint64_t{42}));
320
321 EXPECT_EQ("+42", test_format<4>(FMT_COMPILE("{:+}"), 42));
322 EXPECT_EQ("42", test_format<3>(FMT_COMPILE("{:-}"), 42));
323 EXPECT_EQ(" 42", test_format<4>(FMT_COMPILE("{: }"), 42));
324
325 EXPECT_EQ("-0042", test_format<6>(FMT_COMPILE("{:05}"), -42));
326
327 EXPECT_EQ("101010", test_format<7>(FMT_COMPILE("{:b}"), 42));
328 EXPECT_EQ("0b101010", test_format<9>(FMT_COMPILE("{:#b}"), 42));
329 EXPECT_EQ("0B101010", test_format<9>(FMT_COMPILE("{:#B}"), 42));
330 EXPECT_EQ("042", test_format<4>(FMT_COMPILE("{:#o}"), 042));
331 EXPECT_EQ("0x4a", test_format<5>(FMT_COMPILE("{:#x}"), 0x4a));
332 EXPECT_EQ("0X4A", test_format<5>(FMT_COMPILE("{:#X}"), 0x4a));
333
334 EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42));
335 EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42ll));
336 EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42ull));
337
338 EXPECT_EQ("42 ", test_format<5>(FMT_COMPILE("{:<4}"), 42));
339 EXPECT_EQ(" 42", test_format<5>(FMT_COMPILE("{:>4}"), 42));
340 EXPECT_EQ(" 42 ", test_format<5>(FMT_COMPILE("{:^4}"), 42));
341 EXPECT_EQ("**-42", test_format<6>(FMT_COMPILE("{:*>5}"), -42));
342 }
343
344 TEST(compile_time_formatting_test, char) {
345 EXPECT_EQ("c", test_format<2>(FMT_COMPILE("{}"), 'c'));
346
347 EXPECT_EQ("c ", test_format<4>(FMT_COMPILE("{:3}"), 'c'));
348 EXPECT_EQ("99", test_format<3>(FMT_COMPILE("{:d}"), 'c'));
349 }
350
351 TEST(compile_time_formatting_test, string) {
352 EXPECT_EQ("42", test_format<3>(FMT_COMPILE("{}"), "42"));
353 EXPECT_EQ("The answer is 42",
354 test_format<17>(FMT_COMPILE("{} is {}"), "The answer", "42"));
355
356 EXPECT_EQ("abc**", test_format<6>(FMT_COMPILE("{:*<5}"), "abc"));
357 EXPECT_EQ("**🤡**", test_format<9>(FMT_COMPILE("{:*^6}"), "🤡"));
358 }
359
360 TEST(compile_time_formatting_test, combination) {
361 EXPECT_EQ("420, true, answer",
362 test_format<18>(FMT_COMPILE("{}, {}, {}"), 420, true, "answer"));
363
364 EXPECT_EQ(" -42", test_format<5>(FMT_COMPILE("{:{}}"), -42, 4));
365 }
366
367 TEST(compile_time_formatting_test, custom_type) {
368 EXPECT_EQ("foo", test_format<4>(FMT_COMPILE("{}"), test_formattable()));
369 EXPECT_EQ("bar", test_format<4>(FMT_COMPILE("{:b}"), test_formattable()));
370 }
371
372 TEST(compile_time_formatting_test, multibyte_fill) {
373 EXPECT_EQ("жж42", test_format<8>(FMT_COMPILE("{:ж>4}"), 42));
374 }
375 #endif
+0
-923
source/misc/embedded_libs/fmt-8.1.1/test/core-test.cc less more
0 // Formatting library for C++ - core tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 // clang-format off
8 #include "test-assert.h"
9 // clang-format on
10
11 #include "fmt/core.h"
12
13 #include <algorithm> // std::copy_n
14 #include <climits> // INT_MAX
15 #include <cstring> // std::strlen
16 #include <functional> // std::equal_to
17 #include <iterator> // std::back_insert_iterator
18 #include <limits> // std::numeric_limits
19 #include <string> // std::string
20 #include <type_traits> // std::is_same
21
22 #include "gmock/gmock.h"
23
24 using fmt::string_view;
25 using fmt::detail::buffer;
26
27 using testing::_;
28 using testing::Invoke;
29 using testing::Return;
30
31 #ifdef FMT_FORMAT_H_
32 # error core-test includes format.h
33 #endif
34
35 TEST(string_view_test, value_type) {
36 static_assert(std::is_same<string_view::value_type, char>::value, "");
37 }
38
39 TEST(string_view_test, ctor) {
40 EXPECT_STREQ("abc", fmt::string_view("abc").data());
41 EXPECT_EQ(3u, fmt::string_view("abc").size());
42
43 EXPECT_STREQ("defg", fmt::string_view(std::string("defg")).data());
44 EXPECT_EQ(4u, fmt::string_view(std::string("defg")).size());
45 }
46
47 TEST(string_view_test, length) {
48 // Test that string_view::size() returns string length, not buffer size.
49 char str[100] = "some string";
50 EXPECT_EQ(std::strlen(str), string_view(str).size());
51 EXPECT_LT(std::strlen(str), sizeof(str));
52 }
53
54 // Check string_view's comparison operator.
55 template <template <typename> class Op> void check_op() {
56 const char* inputs[] = {"foo", "fop", "fo"};
57 size_t num_inputs = sizeof(inputs) / sizeof(*inputs);
58 for (size_t i = 0; i < num_inputs; ++i) {
59 for (size_t j = 0; j < num_inputs; ++j) {
60 string_view lhs(inputs[i]), rhs(inputs[j]);
61 EXPECT_EQ(Op<int>()(lhs.compare(rhs), 0), Op<string_view>()(lhs, rhs));
62 }
63 }
64 }
65
66 TEST(string_view_test, compare) {
67 EXPECT_EQ(string_view("foo").compare(string_view("foo")), 0);
68 EXPECT_GT(string_view("fop").compare(string_view("foo")), 0);
69 EXPECT_LT(string_view("foo").compare(string_view("fop")), 0);
70 EXPECT_GT(string_view("foo").compare(string_view("fo")), 0);
71 EXPECT_LT(string_view("fo").compare(string_view("foo")), 0);
72 check_op<std::equal_to>();
73 check_op<std::not_equal_to>();
74 check_op<std::less>();
75 check_op<std::less_equal>();
76 check_op<std::greater>();
77 check_op<std::greater_equal>();
78 }
79
80 namespace test_ns {
81 template <typename Char> class test_string {
82 private:
83 std::basic_string<Char> s_;
84
85 public:
86 test_string(const Char* s) : s_(s) {}
87 const Char* data() const { return s_.data(); }
88 size_t length() const { return s_.size(); }
89 operator const Char*() const { return s_.c_str(); }
90 };
91
92 template <typename Char>
93 fmt::basic_string_view<Char> to_string_view(const test_string<Char>& s) {
94 return {s.data(), s.length()};
95 }
96 } // namespace test_ns
97
98 TEST(core_test, is_output_iterator) {
99 EXPECT_TRUE((fmt::detail::is_output_iterator<char*, char>::value));
100 EXPECT_FALSE((fmt::detail::is_output_iterator<const char*, char>::value));
101 EXPECT_FALSE((fmt::detail::is_output_iterator<std::string, char>::value));
102 EXPECT_TRUE(
103 (fmt::detail::is_output_iterator<std::back_insert_iterator<std::string>,
104 char>::value));
105 EXPECT_TRUE(
106 (fmt::detail::is_output_iterator<std::string::iterator, char>::value));
107 EXPECT_FALSE((fmt::detail::is_output_iterator<std::string::const_iterator,
108 char>::value));
109 }
110
111 TEST(core_test, buffer_appender) {
112 // back_insert_iterator is not default-constructible before C++20, so
113 // buffer_appender can only be default-constructible when back_insert_iterator
114 // is.
115 static_assert(
116 std::is_default_constructible<
117 std::back_insert_iterator<fmt::detail::buffer<char>>>::value ==
118 std::is_default_constructible<
119 fmt::detail::buffer_appender<char>>::value,
120 "");
121
122 #ifdef __cpp_lib_ranges
123 static_assert(std::output_iterator<fmt::detail::buffer_appender<char>, char>);
124 #endif
125 }
126
127 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470
128 TEST(buffer_test, noncopyable) {
129 EXPECT_FALSE(std::is_copy_constructible<buffer<char>>::value);
130 # if !FMT_MSC_VER
131 // std::is_copy_assignable is broken in MSVC2013.
132 EXPECT_FALSE(std::is_copy_assignable<buffer<char>>::value);
133 # endif
134 }
135
136 TEST(buffer_test, nonmoveable) {
137 EXPECT_FALSE(std::is_move_constructible<buffer<char>>::value);
138 # if !FMT_MSC_VER
139 // std::is_move_assignable is broken in MSVC2013.
140 EXPECT_FALSE(std::is_move_assignable<buffer<char>>::value);
141 # endif
142 }
143 #endif
144
145 TEST(buffer_test, indestructible) {
146 static_assert(!std::is_destructible<fmt::detail::buffer<int>>(),
147 "buffer's destructor is protected");
148 }
149
150 template <typename T> struct mock_buffer final : buffer<T> {
151 MOCK_METHOD1(do_grow, size_t(size_t capacity));
152
153 void grow(size_t capacity) override {
154 this->set(this->data(), do_grow(capacity));
155 }
156
157 mock_buffer(T* data = nullptr, size_t buf_capacity = 0) {
158 this->set(data, buf_capacity);
159 ON_CALL(*this, do_grow(_)).WillByDefault(Invoke([](size_t capacity) {
160 return capacity;
161 }));
162 }
163 };
164
165 TEST(buffer_test, ctor) {
166 {
167 mock_buffer<int> buffer;
168 EXPECT_EQ(nullptr, buffer.data());
169 EXPECT_EQ(static_cast<size_t>(0), buffer.size());
170 EXPECT_EQ(static_cast<size_t>(0), buffer.capacity());
171 }
172 {
173 int dummy;
174 mock_buffer<int> buffer(&dummy);
175 EXPECT_EQ(&dummy, &buffer[0]);
176 EXPECT_EQ(static_cast<size_t>(0), buffer.size());
177 EXPECT_EQ(static_cast<size_t>(0), buffer.capacity());
178 }
179 {
180 int dummy;
181 size_t capacity = std::numeric_limits<size_t>::max();
182 mock_buffer<int> buffer(&dummy, capacity);
183 EXPECT_EQ(&dummy, &buffer[0]);
184 EXPECT_EQ(static_cast<size_t>(0), buffer.size());
185 EXPECT_EQ(capacity, buffer.capacity());
186 }
187 }
188
189 TEST(buffer_test, access) {
190 char data[10];
191 mock_buffer<char> buffer(data, sizeof(data));
192 buffer[0] = 11;
193 EXPECT_EQ(11, buffer[0]);
194 buffer[3] = 42;
195 EXPECT_EQ(42, *(&buffer[0] + 3));
196 const fmt::detail::buffer<char>& const_buffer = buffer;
197 EXPECT_EQ(42, const_buffer[3]);
198 }
199
200 TEST(buffer_test, try_resize) {
201 char data[123];
202 mock_buffer<char> buffer(data, sizeof(data));
203 buffer[10] = 42;
204 EXPECT_EQ(42, buffer[10]);
205 buffer.try_resize(20);
206 EXPECT_EQ(20u, buffer.size());
207 EXPECT_EQ(123u, buffer.capacity());
208 EXPECT_EQ(42, buffer[10]);
209 buffer.try_resize(5);
210 EXPECT_EQ(5u, buffer.size());
211 EXPECT_EQ(123u, buffer.capacity());
212 EXPECT_EQ(42, buffer[10]);
213 // Check if try_resize calls grow.
214 EXPECT_CALL(buffer, do_grow(124));
215 buffer.try_resize(124);
216 EXPECT_CALL(buffer, do_grow(200));
217 buffer.try_resize(200);
218 }
219
220 TEST(buffer_test, try_resize_partial) {
221 char data[10];
222 mock_buffer<char> buffer(data, sizeof(data));
223 EXPECT_CALL(buffer, do_grow(20)).WillOnce(Return(15));
224 buffer.try_resize(20);
225 EXPECT_EQ(buffer.capacity(), 15);
226 EXPECT_EQ(buffer.size(), 15);
227 }
228
229 TEST(buffer_test, clear) {
230 mock_buffer<char> buffer;
231 EXPECT_CALL(buffer, do_grow(20));
232 buffer.try_resize(20);
233 buffer.try_resize(0);
234 EXPECT_EQ(static_cast<size_t>(0), buffer.size());
235 EXPECT_EQ(20u, buffer.capacity());
236 }
237
238 TEST(buffer_test, append) {
239 char data[15];
240 mock_buffer<char> buffer(data, 10);
241 auto test = "test";
242 buffer.append(test, test + 5);
243 EXPECT_STREQ(test, &buffer[0]);
244 EXPECT_EQ(5u, buffer.size());
245 buffer.try_resize(10);
246 EXPECT_CALL(buffer, do_grow(12));
247 buffer.append(test, test + 2);
248 EXPECT_EQ('t', buffer[10]);
249 EXPECT_EQ('e', buffer[11]);
250 EXPECT_EQ(12u, buffer.size());
251 }
252
253 TEST(buffer_test, append_partial) {
254 char data[10];
255 mock_buffer<char> buffer(data, sizeof(data));
256 testing::InSequence seq;
257 EXPECT_CALL(buffer, do_grow(15)).WillOnce(Return(10));
258 EXPECT_CALL(buffer, do_grow(15)).WillOnce(Invoke([&buffer](size_t) {
259 EXPECT_EQ(fmt::string_view(buffer.data(), buffer.size()), "0123456789");
260 buffer.clear();
261 return 10;
262 }));
263 auto test = "0123456789abcde";
264 buffer.append(test, test + 15);
265 }
266
267 TEST(buffer_test, append_allocates_enough_storage) {
268 char data[19];
269 mock_buffer<char> buffer(data, 10);
270 auto test = "abcdefgh";
271 buffer.try_resize(10);
272 EXPECT_CALL(buffer, do_grow(19));
273 buffer.append(test, test + 9);
274 }
275
276 struct custom_context {
277 using char_type = char;
278 using parse_context_type = fmt::format_parse_context;
279
280 bool called = false;
281
282 template <typename T> struct formatter_type {
283 auto parse(fmt::format_parse_context& ctx) -> decltype(ctx.begin()) {
284 return ctx.begin();
285 }
286
287 const char* format(const T&, custom_context& ctx) {
288 ctx.called = true;
289 return nullptr;
290 }
291 };
292
293 void advance_to(const char*) {}
294 };
295
296 struct test_struct {};
297
298 FMT_BEGIN_NAMESPACE
299 template <typename Char> struct formatter<test_struct, Char> {
300 auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
301 return ctx.begin();
302 }
303
304 auto format(test_struct, format_context& ctx) -> decltype(ctx.out()) {
305 auto test = string_view("test");
306 return std::copy_n(test.data(), test.size(), ctx.out());
307 }
308 };
309 FMT_END_NAMESPACE
310
311 TEST(arg_test, format_args) {
312 auto args = fmt::format_args();
313 EXPECT_FALSE(args.get(1));
314 }
315
316 TEST(arg_test, make_value_with_custom_context) {
317 auto t = test_struct();
318 fmt::detail::value<custom_context> arg(
319 fmt::detail::arg_mapper<custom_context>().map(t));
320 auto ctx = custom_context();
321 auto parse_ctx = fmt::format_parse_context("");
322 arg.custom.format(&t, parse_ctx, ctx);
323 EXPECT_TRUE(ctx.called);
324 }
325
326 // Use a unique result type to make sure that there are no undesirable
327 // conversions.
328 struct test_result {};
329
330 template <typename T> struct mock_visitor {
331 template <typename U> struct result { using type = test_result; };
332
333 mock_visitor() {
334 ON_CALL(*this, visit(_)).WillByDefault(Return(test_result()));
335 }
336
337 MOCK_METHOD1_T(visit, test_result(T value));
338 MOCK_METHOD0_T(unexpected, void());
339
340 test_result operator()(T value) { return visit(value); }
341
342 template <typename U> test_result operator()(U) {
343 unexpected();
344 return test_result();
345 }
346 };
347
348 template <typename T> struct visit_type { using type = T; };
349
350 #define VISIT_TYPE(type_, visit_type_) \
351 template <> struct visit_type<type_> { using type = visit_type_; }
352
353 VISIT_TYPE(signed char, int);
354 VISIT_TYPE(unsigned char, unsigned);
355 VISIT_TYPE(short, int);
356 VISIT_TYPE(unsigned short, unsigned);
357
358 #if LONG_MAX == INT_MAX
359 VISIT_TYPE(long, int);
360 VISIT_TYPE(unsigned long, unsigned);
361 #else
362 VISIT_TYPE(long, long long);
363 VISIT_TYPE(unsigned long, unsigned long long);
364 #endif
365
366 #define CHECK_ARG(Char, expected, value) \
367 { \
368 testing::StrictMock<mock_visitor<decltype(expected)>> visitor; \
369 EXPECT_CALL(visitor, visit(expected)); \
370 using iterator = std::back_insert_iterator<buffer<Char>>; \
371 fmt::visit_format_arg( \
372 visitor, \
373 fmt::detail::make_arg<fmt::basic_format_context<iterator, Char>>( \
374 value)); \
375 }
376
377 #define CHECK_ARG_SIMPLE(value) \
378 { \
379 using value_type = decltype(value); \
380 typename visit_type<value_type>::type expected = value; \
381 CHECK_ARG(char, expected, value) \
382 CHECK_ARG(wchar_t, expected, value) \
383 }
384
385 template <typename T> class numeric_arg_test : public testing::Test {};
386
387 using types =
388 testing::Types<bool, signed char, unsigned char, short, unsigned short, int,
389 unsigned, long, unsigned long, long long, unsigned long long,
390 float, double, long double>;
391 TYPED_TEST_SUITE(numeric_arg_test, types);
392
393 template <typename T, fmt::enable_if_t<std::is_integral<T>::value, int> = 0>
394 T test_value() {
395 return static_cast<T>(42);
396 }
397
398 template <typename T,
399 fmt::enable_if_t<std::is_floating_point<T>::value, int> = 0>
400 T test_value() {
401 return static_cast<T>(4.2);
402 }
403
404 TYPED_TEST(numeric_arg_test, make_and_visit) {
405 CHECK_ARG_SIMPLE(test_value<TypeParam>());
406 CHECK_ARG_SIMPLE(std::numeric_limits<TypeParam>::min());
407 CHECK_ARG_SIMPLE(std::numeric_limits<TypeParam>::max());
408 }
409
410 TEST(arg_test, char_arg) { CHECK_ARG(char, 'a', 'a'); }
411
412 TEST(arg_test, string_arg) {
413 char str_data[] = "test";
414 char* str = str_data;
415 const char* cstr = str;
416 CHECK_ARG(char, cstr, str);
417
418 auto sv = fmt::string_view(str);
419 CHECK_ARG(char, sv, std::string(str));
420 }
421
422 TEST(arg_test, wstring_arg) {
423 wchar_t str_data[] = L"test";
424 wchar_t* str = str_data;
425 const wchar_t* cstr = str;
426
427 auto sv = fmt::basic_string_view<wchar_t>(str);
428 CHECK_ARG(wchar_t, cstr, str);
429 CHECK_ARG(wchar_t, cstr, cstr);
430 CHECK_ARG(wchar_t, sv, std::wstring(str));
431 CHECK_ARG(wchar_t, sv, fmt::basic_string_view<wchar_t>(str));
432 }
433
434 TEST(arg_test, pointer_arg) {
435 void* p = nullptr;
436 const void* cp = nullptr;
437 CHECK_ARG(char, cp, p);
438 CHECK_ARG(wchar_t, cp, p);
439 CHECK_ARG_SIMPLE(cp);
440 }
441
442 struct check_custom {
443 test_result operator()(
444 fmt::basic_format_arg<fmt::format_context>::handle h) const {
445 struct test_buffer final : fmt::detail::buffer<char> {
446 char data[10];
447 test_buffer() : fmt::detail::buffer<char>(data, 0, 10) {}
448 void grow(size_t) override {}
449 } buffer;
450 auto parse_ctx = fmt::format_parse_context("");
451 auto ctx = fmt::format_context(fmt::detail::buffer_appender<char>(buffer),
452 fmt::format_args());
453 h.format(parse_ctx, ctx);
454 EXPECT_EQ("test", std::string(buffer.data, buffer.size()));
455 return test_result();
456 }
457 };
458
459 TEST(arg_test, custom_arg) {
460 auto test = test_struct();
461 using visitor =
462 mock_visitor<fmt::basic_format_arg<fmt::format_context>::handle>;
463 testing::StrictMock<visitor> v;
464 EXPECT_CALL(v, visit(_)).WillOnce(Invoke(check_custom()));
465 fmt::visit_format_arg(v, fmt::detail::make_arg<fmt::format_context>(test));
466 }
467
468 TEST(arg_test, visit_invalid_arg) {
469 testing::StrictMock<mock_visitor<fmt::monostate>> visitor;
470 EXPECT_CALL(visitor, visit(_));
471 auto arg = fmt::basic_format_arg<fmt::format_context>();
472 fmt::visit_format_arg(visitor, arg);
473 }
474
475 #if FMT_USE_CONSTEXPR
476
477 enum class arg_id_result { none, empty, index, name, error };
478 struct test_arg_id_handler {
479 arg_id_result res = arg_id_result::none;
480 int index = 0;
481 string_view name;
482
483 constexpr void operator()() { res = arg_id_result::empty; }
484
485 constexpr void operator()(int i) {
486 res = arg_id_result::index;
487 index = i;
488 }
489
490 constexpr void operator()(string_view n) {
491 res = arg_id_result::name;
492 name = n;
493 }
494
495 constexpr void on_error(const char*) { res = arg_id_result::error; }
496 };
497
498 template <size_t N>
499 constexpr test_arg_id_handler parse_arg_id(const char (&s)[N]) {
500 test_arg_id_handler h;
501 fmt::detail::parse_arg_id(s, s + N, h);
502 return h;
503 }
504
505 TEST(format_test, constexpr_parse_arg_id) {
506 static_assert(parse_arg_id(":").res == arg_id_result::empty, "");
507 static_assert(parse_arg_id("}").res == arg_id_result::empty, "");
508 static_assert(parse_arg_id("42:").res == arg_id_result::index, "");
509 static_assert(parse_arg_id("42:").index == 42, "");
510 static_assert(parse_arg_id("foo:").res == arg_id_result::name, "");
511 static_assert(parse_arg_id("foo:").name.size() == 3, "");
512 static_assert(parse_arg_id("!").res == arg_id_result::error, "");
513 }
514
515 struct test_format_specs_handler {
516 enum result { none, hash, zero, loc, error };
517 result res = none;
518
519 fmt::align_t alignment = fmt::align::none;
520 fmt::sign_t sign = fmt::sign::none;
521 char fill = 0;
522 int width = 0;
523 fmt::detail::arg_ref<char> width_ref;
524 int precision = 0;
525 fmt::detail::arg_ref<char> precision_ref;
526 fmt::presentation_type type = fmt::presentation_type::none;
527
528 // Workaround for MSVC2017 bug that results in "expression did not evaluate
529 // to a constant" with compiler-generated copy ctor.
530 constexpr test_format_specs_handler() {}
531 constexpr test_format_specs_handler(const test_format_specs_handler& other) =
532 default;
533
534 constexpr void on_align(fmt::align_t a) { alignment = a; }
535 constexpr void on_fill(fmt::string_view f) { fill = f[0]; }
536 constexpr void on_sign(fmt::sign_t s) { sign = s; }
537 constexpr void on_hash() { res = hash; }
538 constexpr void on_zero() { res = zero; }
539 constexpr void on_localized() { res = loc; }
540
541 constexpr void on_width(int w) { width = w; }
542 constexpr void on_dynamic_width(fmt::detail::auto_id) {}
543 constexpr void on_dynamic_width(int index) { width_ref = index; }
544 constexpr void on_dynamic_width(string_view) {}
545
546 constexpr void on_precision(int p) { precision = p; }
547 constexpr void on_dynamic_precision(fmt::detail::auto_id) {}
548 constexpr void on_dynamic_precision(int index) { precision_ref = index; }
549 constexpr void on_dynamic_precision(string_view) {}
550
551 constexpr void end_precision() {}
552 constexpr void on_type(fmt::presentation_type t) { type = t; }
553 constexpr void on_error(const char*) { res = error; }
554 };
555
556 template <size_t N>
557 constexpr test_format_specs_handler parse_test_specs(const char (&s)[N]) {
558 auto h = test_format_specs_handler();
559 fmt::detail::parse_format_specs(s, s + N - 1, h);
560 return h;
561 }
562
563 TEST(core_test, constexpr_parse_format_specs) {
564 using handler = test_format_specs_handler;
565 static_assert(parse_test_specs("<").alignment == fmt::align::left, "");
566 static_assert(parse_test_specs("*^").fill == '*', "");
567 static_assert(parse_test_specs("+").sign == fmt::sign::plus, "");
568 static_assert(parse_test_specs("-").sign == fmt::sign::minus, "");
569 static_assert(parse_test_specs(" ").sign == fmt::sign::space, "");
570 static_assert(parse_test_specs("#").res == handler::hash, "");
571 static_assert(parse_test_specs("0").res == handler::zero, "");
572 static_assert(parse_test_specs("L").res == handler::loc, "");
573 static_assert(parse_test_specs("42").width == 42, "");
574 static_assert(parse_test_specs("{42}").width_ref.val.index == 42, "");
575 static_assert(parse_test_specs(".42").precision == 42, "");
576 static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, "");
577 static_assert(parse_test_specs("d").type == fmt::presentation_type::dec, "");
578 static_assert(parse_test_specs("{<").res == handler::error, "");
579 }
580
581 struct test_parse_context {
582 using char_type = char;
583
584 constexpr int next_arg_id() { return 11; }
585 template <typename Id> FMT_CONSTEXPR void check_arg_id(Id) {}
586
587 constexpr const char* begin() { return nullptr; }
588 constexpr const char* end() { return nullptr; }
589
590 void on_error(const char*) {}
591 };
592
593 template <size_t N>
594 constexpr fmt::detail::dynamic_format_specs<char> parse_dynamic_specs(
595 const char (&s)[N]) {
596 auto specs = fmt::detail::dynamic_format_specs<char>();
597 auto ctx = test_parse_context();
598 auto h = fmt::detail::dynamic_specs_handler<test_parse_context>(specs, ctx);
599 parse_format_specs(s, s + N - 1, h);
600 return specs;
601 }
602
603 TEST(format_test, constexpr_dynamic_specs_handler) {
604 static_assert(parse_dynamic_specs("<").align == fmt::align::left, "");
605 static_assert(parse_dynamic_specs("*^").fill[0] == '*', "");
606 static_assert(parse_dynamic_specs("+").sign == fmt::sign::plus, "");
607 static_assert(parse_dynamic_specs("-").sign == fmt::sign::minus, "");
608 static_assert(parse_dynamic_specs(" ").sign == fmt::sign::space, "");
609 static_assert(parse_dynamic_specs("#").alt, "");
610 static_assert(parse_dynamic_specs("0").align == fmt::align::numeric, "");
611 static_assert(parse_dynamic_specs("42").width == 42, "");
612 static_assert(parse_dynamic_specs("{}").width_ref.val.index == 11, "");
613 static_assert(parse_dynamic_specs("{42}").width_ref.val.index == 42, "");
614 static_assert(parse_dynamic_specs(".42").precision == 42, "");
615 static_assert(parse_dynamic_specs(".{}").precision_ref.val.index == 11, "");
616 static_assert(parse_dynamic_specs(".{42}").precision_ref.val.index == 42, "");
617 static_assert(parse_dynamic_specs("d").type == fmt::presentation_type::dec,
618 "");
619 }
620
621 template <size_t N>
622 constexpr test_format_specs_handler check_specs(const char (&s)[N]) {
623 fmt::detail::specs_checker<test_format_specs_handler> checker(
624 test_format_specs_handler(), fmt::detail::type::double_type);
625 parse_format_specs(s, s + N - 1, checker);
626 return checker;
627 }
628
629 TEST(format_test, constexpr_specs_checker) {
630 using handler = test_format_specs_handler;
631 static_assert(check_specs("<").alignment == fmt::align::left, "");
632 static_assert(check_specs("*^").fill == '*', "");
633 static_assert(check_specs("+").sign == fmt::sign::plus, "");
634 static_assert(check_specs("-").sign == fmt::sign::minus, "");
635 static_assert(check_specs(" ").sign == fmt::sign::space, "");
636 static_assert(check_specs("#").res == handler::hash, "");
637 static_assert(check_specs("0").res == handler::zero, "");
638 static_assert(check_specs("42").width == 42, "");
639 static_assert(check_specs("{42}").width_ref.val.index == 42, "");
640 static_assert(check_specs(".42").precision == 42, "");
641 static_assert(check_specs(".{42}").precision_ref.val.index == 42, "");
642 static_assert(check_specs("d").type == fmt::presentation_type::dec, "");
643 static_assert(check_specs("{<").res == handler::error, "");
644 }
645
646 struct test_format_string_handler {
647 constexpr void on_text(const char*, const char*) {}
648
649 constexpr int on_arg_id() { return 0; }
650
651 template <typename T> constexpr int on_arg_id(T) { return 0; }
652
653 constexpr void on_replacement_field(int, const char*) {}
654
655 constexpr const char* on_format_specs(int, const char* begin, const char*) {
656 return begin;
657 }
658
659 constexpr void on_error(const char*) { error = true; }
660
661 bool error = false;
662 };
663
664 template <size_t N> constexpr bool parse_string(const char (&s)[N]) {
665 auto h = test_format_string_handler();
666 fmt::detail::parse_format_string<true>(fmt::string_view(s, N - 1), h);
667 return !h.error;
668 }
669
670 TEST(format_test, constexpr_parse_format_string) {
671 static_assert(parse_string("foo"), "");
672 static_assert(!parse_string("}"), "");
673 static_assert(parse_string("{}"), "");
674 static_assert(parse_string("{42}"), "");
675 static_assert(parse_string("{foo}"), "");
676 static_assert(parse_string("{:}"), "");
677 }
678 #endif // FMT_USE_CONSTEXPR
679
680 struct enabled_formatter {};
681 struct disabled_formatter {};
682 struct disabled_formatter_convertible {
683 operator int() const { return 42; }
684 };
685
686 FMT_BEGIN_NAMESPACE
687 template <> struct formatter<enabled_formatter> {
688 auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
689 return ctx.begin();
690 }
691 auto format(enabled_formatter, format_context& ctx) -> decltype(ctx.out()) {
692 return ctx.out();
693 }
694 };
695 FMT_END_NAMESPACE
696
697 TEST(core_test, has_formatter) {
698 using fmt::has_formatter;
699 using context = fmt::format_context;
700 static_assert(has_formatter<enabled_formatter, context>::value, "");
701 static_assert(!has_formatter<disabled_formatter, context>::value, "");
702 static_assert(!has_formatter<disabled_formatter_convertible, context>::value,
703 "");
704 }
705
706 struct const_formattable {};
707 struct nonconst_formattable {};
708
709 FMT_BEGIN_NAMESPACE
710 template <> struct formatter<const_formattable> {
711 auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
712 return ctx.begin();
713 }
714
715 auto format(const const_formattable&, format_context& ctx)
716 -> decltype(ctx.out()) {
717 auto test = string_view("test");
718 return std::copy_n(test.data(), test.size(), ctx.out());
719 }
720 };
721
722 template <> struct formatter<nonconst_formattable> {
723 auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
724 return ctx.begin();
725 }
726
727 auto format(nonconst_formattable&, format_context& ctx)
728 -> decltype(ctx.out()) {
729 auto test = string_view("test");
730 return std::copy_n(test.data(), test.size(), ctx.out());
731 }
732 };
733 FMT_END_NAMESPACE
734
735 struct convertible_to_pointer {
736 operator const int*() const { return nullptr; }
737 };
738
739 enum class test_scoped_enum {};
740
741 TEST(core_test, is_formattable) {
742 #if 0
743 // This should be enabled once corresponding map overloads are gone.
744 static_assert(fmt::is_formattable<signed char*>::value, "");
745 static_assert(fmt::is_formattable<unsigned char*>::value, "");
746 static_assert(fmt::is_formattable<const signed char*>::value, "");
747 static_assert(fmt::is_formattable<const unsigned char*>::value, "");
748 #endif
749 static_assert(!fmt::is_formattable<wchar_t>::value, "");
750 #ifdef __cpp_char8_t
751 static_assert(!fmt::is_formattable<char8_t>::value, "");
752 #endif
753 static_assert(!fmt::is_formattable<char16_t>::value, "");
754 static_assert(!fmt::is_formattable<char32_t>::value, "");
755 static_assert(!fmt::is_formattable<const wchar_t*>::value, "");
756 static_assert(!fmt::is_formattable<const wchar_t[3]>::value, "");
757 static_assert(!fmt::is_formattable<fmt::basic_string_view<wchar_t>>::value,
758 "");
759 static_assert(fmt::is_formattable<enabled_formatter>::value, "");
760 static_assert(!fmt::is_formattable<disabled_formatter>::value, "");
761 static_assert(fmt::is_formattable<disabled_formatter_convertible>::value, "");
762
763 static_assert(fmt::is_formattable<const_formattable&>::value, "");
764 static_assert(fmt::is_formattable<const const_formattable&>::value, "");
765
766 static_assert(fmt::is_formattable<nonconst_formattable&>::value, "");
767 #if !FMT_MSC_VER || FMT_MSC_VER >= 1910
768 static_assert(!fmt::is_formattable<const nonconst_formattable&>::value, "");
769 #endif
770
771 static_assert(!fmt::is_formattable<convertible_to_pointer>::value, "");
772
773 static_assert(!fmt::is_formattable<void (*)()>::value, "");
774
775 struct s;
776
777 static_assert(!fmt::is_formattable<int(s::*)>::value, "");
778 static_assert(!fmt::is_formattable<int (s::*)()>::value, "");
779 static_assert(!fmt::is_formattable<test_scoped_enum>::value, "");
780 }
781
782 TEST(core_test, format) { EXPECT_EQ(fmt::format("{}", 42), "42"); }
783
784 TEST(core_test, format_to) {
785 std::string s;
786 fmt::format_to(std::back_inserter(s), "{}", 42);
787 EXPECT_EQ(s, "42");
788 }
789
790 struct convertible_to_int {
791 operator int() const { return 42; }
792 };
793
794 struct convertible_to_c_string {
795 operator const char*() const { return "foo"; }
796 };
797
798 FMT_BEGIN_NAMESPACE
799 template <> struct formatter<convertible_to_int> {
800 auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
801 return ctx.begin();
802 }
803 auto format(convertible_to_int, format_context& ctx) -> decltype(ctx.out()) {
804 return std::copy_n("foo", 3, ctx.out());
805 }
806 };
807
808 template <> struct formatter<convertible_to_c_string> {
809 FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
810 return ctx.begin();
811 }
812 auto format(convertible_to_c_string, format_context& ctx)
813 -> decltype(ctx.out()) {
814 return std::copy_n("bar", 3, ctx.out());
815 }
816 };
817 FMT_END_NAMESPACE
818
819 TEST(core_test, formatter_overrides_implicit_conversion) {
820 EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo");
821 EXPECT_EQ(fmt::format("{}", convertible_to_c_string()), "bar");
822 }
823
824 // Test that check is not found by ADL.
825 template <typename T> void check(T);
826 TEST(core_test, adl_check) {
827 EXPECT_EQ(fmt::format("{}", test_struct()), "test");
828 }
829
830 TEST(core_test, to_string_view_foreign_strings) {
831 using namespace test_ns;
832 EXPECT_EQ(to_string_view(test_string<char>("42")), "42");
833 fmt::detail::type type =
834 fmt::detail::mapped_type_constant<test_string<char>,
835 fmt::format_context>::value;
836 EXPECT_EQ(type, fmt::detail::type::string_type);
837 }
838
839 struct implicitly_convertible_to_string {
840 operator std::string() const { return "foo"; }
841 };
842
843 struct implicitly_convertible_to_string_view {
844 operator fmt::string_view() const { return "foo"; }
845 };
846
847 TEST(core_test, format_implicitly_convertible_to_string_view) {
848 EXPECT_EQ("foo", fmt::format("{}", implicitly_convertible_to_string_view()));
849 }
850
851 // std::is_constructible is broken in MSVC until version 2015.
852 #if !FMT_MSC_VER || FMT_MSC_VER >= 1900
853 struct explicitly_convertible_to_string_view {
854 explicit operator fmt::string_view() const { return "foo"; }
855 };
856
857 TEST(core_test, format_explicitly_convertible_to_string_view) {
858 EXPECT_EQ("foo", fmt::format("{}", explicitly_convertible_to_string_view()));
859 }
860
861 # ifdef FMT_USE_STRING_VIEW
862 struct explicitly_convertible_to_std_string_view {
863 explicit operator std::string_view() const { return "foo"; }
864 };
865
866 TEST(core_test, format_explicitly_convertible_to_std_string_view) {
867 EXPECT_EQ("foo",
868 fmt::format("{}", explicitly_convertible_to_std_string_view()));
869 }
870 # endif
871 #endif
872
873 struct convertible_to_long_long {
874 operator long long() const { return 1LL << 32; }
875 };
876
877 TEST(format_test, format_convertible_to_long_long) {
878 EXPECT_EQ("100000000", fmt::format("{:x}", convertible_to_long_long()));
879 }
880
881 struct disabled_rvalue_conversion {
882 operator const char*() const& { return "foo"; }
883 operator const char*() & { return "foo"; }
884 operator const char*() const&& = delete;
885 operator const char*() && = delete;
886 };
887
888 TEST(core_test, disabled_rvalue_conversion) {
889 EXPECT_EQ("foo", fmt::format("{}", disabled_rvalue_conversion()));
890 }
891
892 namespace adl_test {
893 template <typename... T> void make_format_args(const T&...) = delete;
894
895 struct string : std::string {};
896 } // namespace adl_test
897
898 // Test that formatting functions compile when make_format_args is found by ADL.
899 TEST(core_test, adl) {
900 // Only check compilation and don't run the code to avoid polluting the output
901 // and since the output is tested elsewhere.
902 if (fmt::detail::const_check(true)) return;
903 auto s = adl_test::string();
904 char buf[10];
905 (void)fmt::format("{}", s);
906 fmt::format_to(buf, "{}", s);
907 fmt::format_to_n(buf, 10, "{}", s);
908 (void)fmt::formatted_size("{}", s);
909 fmt::print("{}", s);
910 fmt::print(stdout, "{}", s);
911 }
912
913 TEST(core_test, has_const_formatter) {
914 EXPECT_TRUE((fmt::detail::has_const_formatter<const_formattable,
915 fmt::format_context>()));
916 EXPECT_FALSE((fmt::detail::has_const_formatter<nonconst_formattable,
917 fmt::format_context>()));
918 }
919
920 TEST(core_test, format_nonconst) {
921 EXPECT_EQ(fmt::format("{}", nonconst_formattable()), "test");
922 }
+0
-73
source/misc/embedded_libs/fmt-8.1.1/test/cuda-test/CMakeLists.txt less more
0 # We can find some usecases which follow the guide of CMake which uses
1 # `enable_language(CUDA)` instead of `find_package(CUDA)` and let the CMake
2 # built-in functions use NVCC.
3
4 # See: https://cmake.org/cmake/help/latest/module/FindCUDA.html#replacement
5 #
6 # However, this requires CMake version 3.10 or higher and we can't be sure most
7 # of the CUDA projects are using those.
8 #
9 # This test relies on `find_package(CUDA)` in the parent CMake config.
10
11 # These can be updated when NVCC becomes ready for C++ 17 features
12 # https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#cpp14-language-features
13 set(CMAKE_CUDA_STANDARD 14)
14 set(CMAKE_CUDA_STANDARD_REQUIRED 14)
15
16 # In this test, we assume that the user is going to compile CUDA source code
17 # with some libraries (fmt in this case).
18 #
19 # In addition to that, this test invokes both the C++ host compiler and NVCC
20 # by providing another (non-CUDA) C++ source code.
21 if (${CMAKE_VERSION} VERSION_LESS 3.15)
22 # https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html
23 list(APPEND CUDA_NVCC_FLAGS "-std=c++14")
24 if (MSVC)
25 # This is the solution of pytorch:
26 # https://github.com/pytorch/pytorch/pull/7118
27 list(APPEND CUDA_NVCC_FLAGS "-Xcompiler" "/std:c++14")
28 list(APPEND CUDA_NVCC_FLAGS "-Xcompiler" "/Zc:__cplusplus")
29 # for the reason of this -Xcompiler options, see below.
30 endif ()
31 cuda_add_executable(fmt-in-cuda-test cuda-cpp14.cu cpp14.cc)
32 target_compile_features(fmt-in-cuda-test PRIVATE cxx_std_14)
33 if (MSVC)
34 # This part is for (non-CUDA) C++ code. MSVC can define incorrect
35 # `__cplusplus` macro. Fix for the issue is to use additional compiler flag.
36 #
37 # See Also:
38 # https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
39 # https://github.com/Microsoft/vscode-cpptools/issues/2595
40 target_compile_options(fmt-in-cuda-test PRIVATE /Zc:__cplusplus /permissive-)
41 endif ()
42 else()
43 # now using a "new" way of handling CUDA
44 add_executable(fmt-in-cuda-test cuda-cpp14.cu cpp14.cc)
45 set_target_properties(fmt-in-cuda-test PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
46 target_compile_features(fmt-in-cuda-test PRIVATE cxx_std_14)
47 if (MSVC)
48 # with MSVC, 'cxx_std_14' will only propagate to the host code (MSVC), but will
49 # not set __cplusplus correctly anyway, while nvcc will ignore it.
50 # If specified for nvcc on the command line as '-std=c++14' nvcc will emit this
51 # message instead:
52 # nvcc warning : The -std=c++14 flag is not supported with the configured host
53 # compiler. Flag will be ignored.
54 set_property(SOURCE cuda-cpp14.cu APPEND PROPERTY
55 COMPILE_OPTIONS -Xcompiler /std:c++14 -Xcompiler /Zc:__cplusplus)
56 set_property(SOURCE cpp14.cc APPEND PROPERTY
57 COMPILE_OPTIONS /std:c++14 /Zc:__cplusplus)
58 endif()
59 endif()
60
61 get_target_property(IN_USE_CUDA_STANDARD fmt-in-cuda-test CUDA_STANDARD)
62 message(STATUS "cuda_standard: ${IN_USE_CUDA_STANDARD}")
63
64 get_target_property(IN_USE_CUDA_STANDARD_REQUIRED
65 fmt-in-cuda-test CUDA_STANDARD_REQUIRED)
66 message(STATUS "cuda_standard_required: ${IN_USE_CUDA_STANDARD_REQUIRED}")
67
68 # We don't use PUBLIC or other keyword for reasons explained in the
69 # CUDA_LINK_LIBRARIES_KEYWORD section in
70 # https://cmake.org/cmake/help/latest/module/FindCUDA.html
71 target_link_libraries(fmt-in-cuda-test fmt::fmt)
72
+0
-11
source/misc/embedded_libs/fmt-8.1.1/test/cuda-test/cpp14.cc less more
0 #include <fmt/core.h>
1
2 // The purpose of this part is to ensure NVCC's host compiler also supports
3 // the standard version. See 'cuda-cpp14.cu'.
4 //
5 // https://en.cppreference.com/w/cpp/preprocessor/replace#Predefined_macros
6 static_assert(__cplusplus >= 201402L, "expect C++ 2014 for host compiler");
7
8 auto make_message_cpp() -> std::string {
9 return fmt::format("host compiler \t: __cplusplus == {}", __cplusplus);
10 }
+0
-28
source/misc/embedded_libs/fmt-8.1.1/test/cuda-test/cuda-cpp14.cu less more
0 // Direct NVCC command line example:
1 //
2 // nvcc ./cuda-cpp14.cu -x cu -I"../include" -l"fmtd" -L"../build/Debug" \
3 // -std=c++14 -Xcompiler /std:c++14 -Xcompiler /Zc:__cplusplus
4
5 // Ensure that we are using the latest C++ standard for NVCC
6 // The version is C++14
7 //
8 // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#c-cplusplus-language-support
9 // https://en.cppreference.com/w/cpp/preprocessor/replace#Predefined_macros
10 static_assert(__cplusplus >= 201402L, "expect C++ 2014 for nvcc");
11
12 #include <fmt/core.h>
13
14 #include <cuda.h>
15 #include <iostream>
16
17 extern auto make_message_cpp() -> std::string;
18 extern auto make_message_cuda() -> std::string;
19
20 int main() {
21 std::cout << make_message_cuda() << std::endl;
22 std::cout << make_message_cpp() << std::endl;
23 }
24
25 auto make_message_cuda() -> std::string {
26 return fmt::format("nvcc compiler \t: __cplusplus == {}", __cplusplus);
27 }
+0
-63
source/misc/embedded_libs/fmt-8.1.1/test/enforce-checks-test.cc less more
0 // Formatting library for C++ - formatting library tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include <iterator>
8 #include <vector>
9
10 #include "fmt/chrono.h"
11 #include "fmt/color.h"
12 #include "fmt/format.h"
13 #include "fmt/ostream.h"
14 #include "fmt/ranges.h"
15 #include "fmt/xchar.h"
16
17 // Exercise the API to verify that everything we expect to can compile.
18 void test_format_api() {
19 (void)fmt::format(FMT_STRING("{}"), 42);
20 (void)fmt::format(FMT_STRING(L"{}"), 42);
21 (void)fmt::format(FMT_STRING("noop"));
22
23 (void)fmt::to_string(42);
24 (void)fmt::to_wstring(42);
25
26 std::vector<char> out;
27 fmt::format_to(std::back_inserter(out), FMT_STRING("{}"), 42);
28
29 char buffer[4];
30 fmt::format_to_n(buffer, 3, FMT_STRING("{}"), 12345);
31
32 wchar_t wbuffer[4];
33 fmt::format_to_n(wbuffer, 3, FMT_STRING(L"{}"), 12345);
34 }
35
36 void test_chrono() {
37 (void)fmt::format(FMT_STRING("{}"), std::chrono::seconds(42));
38 (void)fmt::format(FMT_STRING(L"{}"), std::chrono::seconds(42));
39 }
40
41 void test_text_style() {
42 fmt::print(fg(fmt::rgb(255, 20, 30)), FMT_STRING("{}"), "rgb(255,20,30)");
43 (void)fmt::format(fg(fmt::rgb(255, 20, 30)), FMT_STRING("{}"),
44 "rgb(255,20,30)");
45
46 fmt::text_style ts = fg(fmt::rgb(255, 20, 30));
47 std::string out;
48 fmt::format_to(std::back_inserter(out), ts,
49 FMT_STRING("rgb(255,20,30){}{}{}"), 1, 2, 3);
50 }
51
52 void test_range() {
53 std::vector<char> hello = {'h', 'e', 'l', 'l', 'o'};
54 (void)fmt::format(FMT_STRING("{}"), hello);
55 }
56
57 int main() {
58 test_format_api();
59 test_chrono();
60 test_text_style();
61 test_range();
62 }
+0
-17
source/misc/embedded_libs/fmt-8.1.1/test/find-package-test/CMakeLists.txt less more
0 cmake_minimum_required(VERSION 3.1...3.18)
1
2 project(fmt-test)
3
4 find_package(FMT REQUIRED)
5
6 add_executable(library-test main.cc)
7 target_link_libraries(library-test fmt::fmt)
8 target_compile_options(library-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
9 target_include_directories(library-test PUBLIC SYSTEM .)
10
11 if (TARGET fmt::fmt-header-only)
12 add_executable(header-only-test main.cc)
13 target_link_libraries(header-only-test fmt::fmt-header-only)
14 target_compile_options(header-only-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
15 target_include_directories(header-only-test PUBLIC SYSTEM .)
16 endif ()
+0
-5
source/misc/embedded_libs/fmt-8.1.1/test/find-package-test/main.cc less more
0 #include "fmt/format.h"
1
2 int main(int argc, char** argv) {
3 for (int i = 0; i < argc; ++i) fmt::print("{}: {}\n", i, argv[i]);
4 }
+0
-377
source/misc/embedded_libs/fmt-8.1.1/test/format-impl-test.cc less more
0 // Formatting library for C++ - formatting library implementation tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include <algorithm>
8 #include <cstring>
9
10 // clang-format off
11 #include "test-assert.h"
12 // clang-format on
13
14 #include "fmt/format.h"
15 #include "gmock/gmock.h"
16 #include "util.h"
17
18 using fmt::detail::bigint;
19 using fmt::detail::fp;
20 using fmt::detail::max_value;
21
22 static_assert(!std::is_copy_constructible<bigint>::value, "");
23 static_assert(!std::is_copy_assignable<bigint>::value, "");
24
25 TEST(bigint_test, construct) {
26 EXPECT_EQ("", fmt::format("{}", bigint()));
27 EXPECT_EQ("42", fmt::format("{}", bigint(0x42)));
28 EXPECT_EQ("123456789abcedf0", fmt::format("{}", bigint(0x123456789abcedf0)));
29 }
30
31 TEST(bigint_test, compare) {
32 bigint n1(42);
33 bigint n2(42);
34 EXPECT_EQ(compare(n1, n2), 0);
35 n2 <<= 32;
36 EXPECT_LT(compare(n1, n2), 0);
37 bigint n3(43);
38 EXPECT_LT(compare(n1, n3), 0);
39 EXPECT_GT(compare(n3, n1), 0);
40 bigint n4(42 * 0x100000001);
41 EXPECT_LT(compare(n2, n4), 0);
42 EXPECT_GT(compare(n4, n2), 0);
43 }
44
45 TEST(bigint_test, add_compare) {
46 EXPECT_LT(
47 add_compare(bigint(0xffffffff), bigint(0xffffffff), bigint(1) <<= 64), 0);
48 EXPECT_LT(add_compare(bigint(1) <<= 32, bigint(1), bigint(1) <<= 96), 0);
49 EXPECT_GT(add_compare(bigint(1) <<= 32, bigint(0), bigint(0xffffffff)), 0);
50 EXPECT_GT(add_compare(bigint(0), bigint(1) <<= 32, bigint(0xffffffff)), 0);
51 EXPECT_GT(add_compare(bigint(42), bigint(1), bigint(42)), 0);
52 EXPECT_GT(add_compare(bigint(0xffffffff), bigint(1), bigint(0xffffffff)), 0);
53 EXPECT_LT(add_compare(bigint(10), bigint(10), bigint(22)), 0);
54 EXPECT_LT(add_compare(bigint(0x100000010), bigint(0x100000010),
55 bigint(0x300000010)),
56 0);
57 EXPECT_GT(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
58 bigint(0x300000000)),
59 0);
60 EXPECT_EQ(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
61 bigint(0x300000001)),
62 0);
63 EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
64 bigint(0x300000002)),
65 0);
66 EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
67 bigint(0x300000003)),
68 0);
69 }
70
71 TEST(bigint_test, shift_left) {
72 bigint n(0x42);
73 n <<= 0;
74 EXPECT_EQ("42", fmt::format("{}", n));
75 n <<= 1;
76 EXPECT_EQ("84", fmt::format("{}", n));
77 n <<= 25;
78 EXPECT_EQ("108000000", fmt::format("{}", n));
79 }
80
81 TEST(bigint_test, multiply) {
82 bigint n(0x42);
83 EXPECT_THROW(n *= 0, assertion_failure);
84 n *= 1;
85 EXPECT_EQ("42", fmt::format("{}", n));
86 n *= 2;
87 EXPECT_EQ("84", fmt::format("{}", n));
88 n *= 0x12345678;
89 EXPECT_EQ("962fc95e0", fmt::format("{}", n));
90 bigint bigmax(max_value<uint32_t>());
91 bigmax *= max_value<uint32_t>();
92 EXPECT_EQ("fffffffe00000001", fmt::format("{}", bigmax));
93 bigmax.assign(max_value<uint64_t>());
94 bigmax *= max_value<uint64_t>();
95 EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", bigmax));
96 }
97
98 TEST(bigint_test, accumulator) {
99 fmt::detail::accumulator acc;
100 EXPECT_EQ(acc.lower, 0);
101 EXPECT_EQ(acc.upper, 0);
102 acc.upper = 12;
103 acc.lower = 34;
104 EXPECT_EQ(static_cast<uint32_t>(acc), 34);
105 acc += 56;
106 EXPECT_EQ(acc.lower, 90);
107 acc += max_value<uint64_t>();
108 EXPECT_EQ(acc.upper, 13);
109 EXPECT_EQ(acc.lower, 89);
110 acc >>= 32;
111 EXPECT_EQ(acc.upper, 0);
112 EXPECT_EQ(acc.lower, 13 * 0x100000000);
113 }
114
115 TEST(bigint_test, square) {
116 bigint n0(0);
117 n0.square();
118 EXPECT_EQ("0", fmt::format("{}", n0));
119 bigint n1(0x100);
120 n1.square();
121 EXPECT_EQ("10000", fmt::format("{}", n1));
122 bigint n2(0xfffffffff);
123 n2.square();
124 EXPECT_EQ("ffffffffe000000001", fmt::format("{}", n2));
125 bigint n3(max_value<uint64_t>());
126 n3.square();
127 EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", n3));
128 bigint n4;
129 n4.assign_pow10(10);
130 EXPECT_EQ("2540be400", fmt::format("{}", n4));
131 }
132
133 TEST(bigint_test, divmod_assign_zero_divisor) {
134 bigint zero(0);
135 EXPECT_THROW(bigint(0).divmod_assign(zero), assertion_failure);
136 EXPECT_THROW(bigint(42).divmod_assign(zero), assertion_failure);
137 }
138
139 TEST(bigint_test, divmod_assign_self) {
140 bigint n(100);
141 EXPECT_THROW(n.divmod_assign(n), assertion_failure);
142 }
143
144 TEST(bigint_test, divmod_assign_unaligned) {
145 // (42 << 340) / pow(10, 100):
146 bigint n1(42);
147 n1 <<= 340;
148 bigint n2;
149 n2.assign_pow10(100);
150 int result = n1.divmod_assign(n2);
151 EXPECT_EQ(result, 9406);
152 EXPECT_EQ("10f8353019583bfc29ffc8f564e1b9f9d819dbb4cf783e4507eca1539220p96",
153 fmt::format("{}", n1));
154 }
155
156 TEST(bigint_test, divmod_assign) {
157 // 100 / 10:
158 bigint n1(100);
159 int result = n1.divmod_assign(bigint(10));
160 EXPECT_EQ(result, 10);
161 EXPECT_EQ("0", fmt::format("{}", n1));
162 // pow(10, 100) / (42 << 320):
163 n1.assign_pow10(100);
164 result = n1.divmod_assign(bigint(42) <<= 320);
165 EXPECT_EQ(result, 111);
166 EXPECT_EQ("13ad2594c37ceb0b2784c4ce0bf38ace408e211a7caab24308a82e8f10p96",
167 fmt::format("{}", n1));
168 // 42 / 100:
169 bigint n2(42);
170 n1.assign_pow10(2);
171 result = n2.divmod_assign(n1);
172 EXPECT_EQ(result, 0);
173 EXPECT_EQ("2a", fmt::format("{}", n2));
174 }
175
176 template <bool is_iec559> void run_double_tests() {
177 fmt::print("warning: double is not IEC559, skipping FP tests\n");
178 }
179
180 template <> void run_double_tests<true>() {
181 // Construct from double.
182 EXPECT_EQ(fp(1.23), fp(0x13ae147ae147aeu, -52));
183 }
184
185 TEST(fp_test, double_tests) {
186 run_double_tests<std::numeric_limits<double>::is_iec559>();
187 }
188
189 TEST(fp_test, normalize) {
190 const auto v = fp(0xbeef, 42);
191 auto normalized = normalize(v);
192 EXPECT_EQ(0xbeef000000000000, normalized.f);
193 EXPECT_EQ(-6, normalized.e);
194 }
195
196 TEST(fp_test, multiply) {
197 auto v = fp(123ULL << 32, 4) * fp(56ULL << 32, 7);
198 EXPECT_EQ(v.f, 123u * 56u);
199 EXPECT_EQ(v.e, 4 + 7 + 64);
200 v = fp(123ULL << 32, 4) * fp(567ULL << 31, 8);
201 EXPECT_EQ(v.f, (123 * 567 + 1u) / 2);
202 EXPECT_EQ(v.e, 4 + 8 + 64);
203 }
204
205 TEST(fp_test, get_cached_power) {
206 using limits = std::numeric_limits<double>;
207 for (auto exp = limits::min_exponent; exp <= limits::max_exponent; ++exp) {
208 int dec_exp = 0;
209 auto fp = fmt::detail::get_cached_power(exp, dec_exp);
210 bigint exact, cache(fp.f);
211 if (dec_exp >= 0) {
212 exact.assign_pow10(dec_exp);
213 if (fp.e <= 0)
214 exact <<= -fp.e;
215 else
216 cache <<= fp.e;
217 exact.align(cache);
218 cache.align(exact);
219 auto exact_str = fmt::format("{}", exact);
220 auto cache_str = fmt::format("{}", cache);
221 EXPECT_EQ(exact_str.size(), cache_str.size());
222 EXPECT_EQ(exact_str.substr(0, 15), cache_str.substr(0, 15));
223 int diff = cache_str[15] - exact_str[15];
224 if (diff == 1)
225 EXPECT_GT(exact_str[16], '8');
226 else
227 EXPECT_EQ(diff, 0);
228 } else {
229 cache.assign_pow10(-dec_exp);
230 cache *= fp.f + 1; // Inexact check.
231 exact.assign(1);
232 exact <<= -fp.e;
233 exact.align(cache);
234 auto exact_str = fmt::format("{}", exact);
235 auto cache_str = fmt::format("{}", cache);
236 EXPECT_EQ(exact_str.size(), cache_str.size());
237 EXPECT_EQ(exact_str.substr(0, 16), cache_str.substr(0, 16));
238 }
239 }
240 }
241
242 TEST(fp_test, dragonbox_max_k) {
243 using fmt::detail::dragonbox::floor_log10_pow2;
244 using float_info = fmt::detail::dragonbox::float_info<float>;
245 EXPECT_EQ(fmt::detail::const_check(float_info::max_k),
246 float_info::kappa - floor_log10_pow2(float_info::min_exponent -
247 float_info::significand_bits));
248 using double_info = fmt::detail::dragonbox::float_info<double>;
249 EXPECT_EQ(
250 fmt::detail::const_check(double_info::max_k),
251 double_info::kappa - floor_log10_pow2(double_info::min_exponent -
252 double_info::significand_bits));
253 }
254
255 TEST(fp_test, get_round_direction) {
256 using fmt::detail::get_round_direction;
257 using fmt::detail::round_direction;
258 EXPECT_EQ(round_direction::down, get_round_direction(100, 50, 0));
259 EXPECT_EQ(round_direction::up, get_round_direction(100, 51, 0));
260 EXPECT_EQ(round_direction::down, get_round_direction(100, 40, 10));
261 EXPECT_EQ(round_direction::up, get_round_direction(100, 60, 10));
262 for (size_t i = 41; i < 60; ++i)
263 EXPECT_EQ(round_direction::unknown, get_round_direction(100, i, 10));
264 uint64_t max = max_value<uint64_t>();
265 EXPECT_THROW(get_round_direction(100, 100, 0), assertion_failure);
266 EXPECT_THROW(get_round_direction(100, 0, 100), assertion_failure);
267 EXPECT_THROW(get_round_direction(100, 0, 50), assertion_failure);
268 // Check that remainder + error doesn't overflow.
269 EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 2));
270 // Check that 2 * (remainder + error) doesn't overflow.
271 EXPECT_EQ(round_direction::unknown,
272 get_round_direction(max, max / 2 + 1, max / 2));
273 // Check that remainder - error doesn't overflow.
274 EXPECT_EQ(round_direction::unknown, get_round_direction(100, 40, 41));
275 // Check that 2 * (remainder - error) doesn't overflow.
276 EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 1));
277 }
278
279 TEST(fp_test, fixed_handler) {
280 struct handler : fmt::detail::gen_digits_handler {
281 char buffer[10];
282 handler(int prec = 0) : fmt::detail::gen_digits_handler() {
283 buf = buffer;
284 precision = prec;
285 }
286 };
287 handler().on_digit('0', 100, 99, 0, false);
288 EXPECT_THROW(handler().on_digit('0', 100, 100, 0, false), assertion_failure);
289 namespace digits = fmt::detail::digits;
290 EXPECT_EQ(handler(1).on_digit('0', 100, 10, 10, false), digits::error);
291 // Check that divisor - error doesn't overflow.
292 EXPECT_EQ(handler(1).on_digit('0', 100, 10, 101, false), digits::error);
293 // Check that 2 * error doesn't overflow.
294 uint64_t max = max_value<uint64_t>();
295 EXPECT_EQ(handler(1).on_digit('0', max, 10, max - 1, false), digits::error);
296 }
297
298 TEST(fp_test, grisu_format_compiles_with_on_ieee_double) {
299 fmt::memory_buffer buf;
300 format_float(0.42, -1, fmt::detail::float_specs(), buf);
301 }
302
303 TEST(format_impl_test, format_error_code) {
304 std::string msg = "error 42", sep = ": ";
305 {
306 fmt::memory_buffer buffer;
307 format_to(fmt::appender(buffer), "garbage");
308 fmt::detail::format_error_code(buffer, 42, "test");
309 EXPECT_EQ("test: " + msg, to_string(buffer));
310 }
311 {
312 fmt::memory_buffer buffer;
313 auto prefix =
314 std::string(fmt::inline_buffer_size - msg.size() - sep.size() + 1, 'x');
315 fmt::detail::format_error_code(buffer, 42, prefix);
316 EXPECT_EQ(msg, to_string(buffer));
317 }
318 int codes[] = {42, -1};
319 for (size_t i = 0, n = sizeof(codes) / sizeof(*codes); i < n; ++i) {
320 // Test maximum buffer size.
321 msg = fmt::format("error {}", codes[i]);
322 fmt::memory_buffer buffer;
323 auto prefix =
324 std::string(fmt::inline_buffer_size - msg.size() - sep.size(), 'x');
325 fmt::detail::format_error_code(buffer, codes[i], prefix);
326 EXPECT_EQ(prefix + sep + msg, to_string(buffer));
327 size_t size = fmt::inline_buffer_size;
328 EXPECT_EQ(size, buffer.size());
329 buffer.resize(0);
330 // Test with a message that doesn't fit into the buffer.
331 prefix += 'x';
332 fmt::detail::format_error_code(buffer, codes[i], prefix);
333 EXPECT_EQ(msg, to_string(buffer));
334 }
335 }
336
337 TEST(format_impl_test, compute_width) {
338 EXPECT_EQ(4,
339 fmt::detail::compute_width(
340 fmt::basic_string_view<fmt::detail::char8_type>(
341 reinterpret_cast<const fmt::detail::char8_type*>("ёжик"))));
342 }
343
344 // Tests fmt::detail::count_digits for integer type Int.
345 template <typename Int> void test_count_digits() {
346 for (Int i = 0; i < 10; ++i) EXPECT_EQ(1u, fmt::detail::count_digits(i));
347 for (Int i = 1, n = 1, end = max_value<Int>() / 10; n <= end; ++i) {
348 n *= 10;
349 EXPECT_EQ(i, fmt::detail::count_digits(n - 1));
350 EXPECT_EQ(i + 1, fmt::detail::count_digits(n));
351 }
352 }
353
354 TEST(format_impl_test, count_digits) {
355 test_count_digits<uint32_t>();
356 test_count_digits<uint64_t>();
357 }
358
359 TEST(format_impl_test, write_fallback_uintptr) {
360 std::string s;
361 fmt::detail::write_ptr<char>(
362 std::back_inserter(s),
363 fmt::detail::fallback_uintptr(reinterpret_cast<void*>(0xface)), nullptr);
364 EXPECT_EQ(s, "0xface");
365 }
366
367 #ifdef _WIN32
368 # include <windows.h>
369 #endif
370
371 #ifdef _WIN32
372 TEST(format_impl_test, write_console_signature) {
373 decltype(WriteConsoleW)* p = fmt::detail::WriteConsoleW;
374 (void)p;
375 }
376 #endif
+0
-2190
source/misc/embedded_libs/fmt-8.1.1/test/format-test.cc less more
0 // Formatting library for C++ - formatting library tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 // Check if fmt/format.h compiles with windows.h included before it.
8 #ifdef _WIN32
9 # include <windows.h>
10 #endif
11 // clang-format off
12 #include "fmt/format.h"
13 // clang-format on
14
15 #include <stdint.h> // uint32_t
16
17 #include <climits> // INT_MAX
18 #include <cmath> // std::signbit
19 #include <cstring> // std::strlen
20 #include <iterator> // std::back_inserter
21 #include <list> // std::list
22 #include <memory> // std::unique_ptr
23 #include <type_traits> // std::is_default_constructible
24
25 #include "gtest-extra.h"
26 #include "mock-allocator.h"
27 #include "util.h"
28
29 using fmt::basic_memory_buffer;
30 using fmt::format_error;
31 using fmt::memory_buffer;
32 using fmt::runtime;
33 using fmt::string_view;
34 using fmt::detail::max_value;
35
36 using testing::Return;
37 using testing::StrictMock;
38
39 enum { buffer_size = 256 };
40
41 struct uint32_pair {
42 uint32_t u[2];
43 };
44
45 TEST(util_test, bit_cast) {
46 auto s = fmt::detail::bit_cast<uint32_pair>(uint64_t{42});
47 EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), 42ull);
48 s = fmt::detail::bit_cast<uint32_pair>(~uint64_t{0});
49 EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), ~0ull);
50 }
51
52 // Increment a number in a string.
53 void increment(char* s) {
54 for (int i = static_cast<int>(std::strlen(s)) - 1; i >= 0; --i) {
55 if (s[i] != '9') {
56 ++s[i];
57 break;
58 }
59 s[i] = '0';
60 }
61 }
62
63 TEST(util_test, increment) {
64 char s[10] = "123";
65 increment(s);
66 EXPECT_STREQ("124", s);
67 s[2] = '8';
68 increment(s);
69 EXPECT_STREQ("129", s);
70 increment(s);
71 EXPECT_STREQ("130", s);
72 s[1] = s[2] = '9';
73 increment(s);
74 EXPECT_STREQ("200", s);
75 }
76
77 TEST(util_test, parse_nonnegative_int) {
78 auto s = fmt::string_view("10000000000");
79 auto begin = s.begin(), end = s.end();
80 EXPECT_EQ(fmt::detail::parse_nonnegative_int(begin, end, -1), -1);
81 s = "2147483649";
82 begin = s.begin();
83 end = s.end();
84 EXPECT_EQ(fmt::detail::parse_nonnegative_int(begin, end, -1), -1);
85 }
86
87 TEST(util_test, utf8_to_utf16) {
88 auto u = fmt::detail::utf8_to_utf16("лошадка");
89 EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str());
90 EXPECT_EQ(7, u.size());
91 // U+10437 { DESERET SMALL LETTER YEE }
92 EXPECT_EQ(L"\xD801\xDC37", fmt::detail::utf8_to_utf16("𐐷").str());
93 EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16("\xc3\x28"), std::runtime_error,
94 "invalid utf8");
95 EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16(fmt::string_view("л", 1)),
96 std::runtime_error, "invalid utf8");
97 EXPECT_EQ(L"123456", fmt::detail::utf8_to_utf16("123456").str());
98 }
99
100 TEST(util_test, utf8_to_utf16_empty_string) {
101 auto s = std::string();
102 auto u = fmt::detail::utf8_to_utf16(s.c_str());
103 EXPECT_EQ(L"", u.str());
104 EXPECT_EQ(s.size(), u.size());
105 }
106
107 TEST(util_test, allocator_ref) {
108 using test_allocator_ref = allocator_ref<mock_allocator<int>>;
109 auto check_forwarding = [](mock_allocator<int>& alloc,
110 test_allocator_ref& ref) {
111 int mem;
112 // Check if value_type is properly defined.
113 allocator_ref<mock_allocator<int>>::value_type* ptr = &mem;
114 // Check forwarding.
115 EXPECT_CALL(alloc, allocate(42)).WillOnce(Return(ptr));
116 ref.allocate(42);
117 EXPECT_CALL(alloc, deallocate(ptr, 42));
118 ref.deallocate(ptr, 42);
119 };
120
121 StrictMock<mock_allocator<int>> alloc;
122 auto ref = test_allocator_ref(&alloc);
123 // Check if allocator_ref forwards to the underlying allocator.
124 check_forwarding(alloc, ref);
125 test_allocator_ref ref2(ref);
126 check_forwarding(alloc, ref2);
127 test_allocator_ref ref3;
128 EXPECT_EQ(nullptr, ref3.get());
129 ref3 = ref;
130 check_forwarding(alloc, ref3);
131 }
132
133 TEST(util_test, format_system_error) {
134 fmt::memory_buffer message;
135 fmt::format_system_error(message, EDOM, "test");
136 auto ec = std::error_code(EDOM, std::generic_category());
137 EXPECT_EQ(to_string(message), std::system_error(ec, "test").what());
138 message = fmt::memory_buffer();
139
140 // Check if std::allocator throws on allocating max size_t / 2 chars.
141 size_t max_size = max_value<size_t>() / 2;
142 bool throws_on_alloc = false;
143 try {
144 auto alloc = std::allocator<char>();
145 alloc.deallocate(alloc.allocate(max_size), max_size);
146 } catch (const std::bad_alloc&) {
147 throws_on_alloc = true;
148 }
149 if (!throws_on_alloc) {
150 fmt::print("warning: std::allocator allocates {} chars", max_size);
151 return;
152 }
153 }
154
155 TEST(util_test, system_error) {
156 auto test_error = fmt::system_error(EDOM, "test");
157 auto ec = std::error_code(EDOM, std::generic_category());
158 EXPECT_STREQ(test_error.what(), std::system_error(ec, "test").what());
159 EXPECT_EQ(test_error.code(), ec);
160
161 auto error = std::system_error(std::error_code());
162 try {
163 throw fmt::system_error(EDOM, "test {}", "error");
164 } catch (const std::system_error& e) {
165 error = e;
166 }
167 fmt::memory_buffer message;
168 fmt::format_system_error(message, EDOM, "test error");
169 EXPECT_EQ(error.what(), to_string(message));
170 EXPECT_EQ(error.code(), std::error_code(EDOM, std::generic_category()));
171 }
172
173 TEST(util_test, report_system_error) {
174 fmt::memory_buffer out;
175 fmt::format_system_error(out, EDOM, "test error");
176 out.push_back('\n');
177 EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"),
178 to_string(out));
179 }
180
181 TEST(memory_buffer_test, ctor) {
182 basic_memory_buffer<char, 123> buffer;
183 EXPECT_EQ(static_cast<size_t>(0), buffer.size());
184 EXPECT_EQ(123u, buffer.capacity());
185 }
186
187 using std_allocator = allocator_ref<std::allocator<char>>;
188
189 TEST(memory_buffer_test, move_ctor_inline_buffer) {
190 auto check_move_buffer =
191 [](const char* str, basic_memory_buffer<char, 5, std_allocator>& buffer) {
192 std::allocator<char>* alloc = buffer.get_allocator().get();
193 basic_memory_buffer<char, 5, std_allocator> buffer2(std::move(buffer));
194 // Move shouldn't destroy the inline content of the first buffer.
195 EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
196 EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
197 EXPECT_EQ(5u, buffer2.capacity());
198 // Move should transfer allocator.
199 EXPECT_EQ(nullptr, buffer.get_allocator().get());
200 EXPECT_EQ(alloc, buffer2.get_allocator().get());
201 };
202
203 auto alloc = std::allocator<char>();
204 basic_memory_buffer<char, 5, std_allocator> buffer((std_allocator(&alloc)));
205 const char test[] = "test";
206 buffer.append(string_view(test, 4));
207 check_move_buffer("test", buffer);
208 // Adding one more character fills the inline buffer, but doesn't cause
209 // dynamic allocation.
210 buffer.push_back('a');
211 check_move_buffer("testa", buffer);
212 }
213
214 TEST(memory_buffer_test, move_ctor_dynamic_buffer) {
215 auto alloc = std::allocator<char>();
216 basic_memory_buffer<char, 4, std_allocator> buffer((std_allocator(&alloc)));
217 const char test[] = "test";
218 buffer.append(test, test + 4);
219 const char* inline_buffer_ptr = &buffer[0];
220 // Adding one more character causes the content to move from the inline to
221 // a dynamically allocated buffer.
222 buffer.push_back('a');
223 basic_memory_buffer<char, 4, std_allocator> buffer2(std::move(buffer));
224 // Move should rip the guts of the first buffer.
225 EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
226 EXPECT_EQ("testa", std::string(&buffer2[0], buffer2.size()));
227 EXPECT_GT(buffer2.capacity(), 4u);
228 }
229
230 void check_move_assign_buffer(const char* str,
231 basic_memory_buffer<char, 5>& buffer) {
232 basic_memory_buffer<char, 5> buffer2;
233 buffer2 = std::move(buffer);
234 // Move shouldn't destroy the inline content of the first buffer.
235 EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
236 EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
237 EXPECT_EQ(5u, buffer2.capacity());
238 }
239
240 TEST(memory_buffer_test, move_assignment) {
241 basic_memory_buffer<char, 5> buffer;
242 const char test[] = "test";
243 buffer.append(test, test + 4);
244 check_move_assign_buffer("test", buffer);
245 // Adding one more character fills the inline buffer, but doesn't cause
246 // dynamic allocation.
247 buffer.push_back('a');
248 check_move_assign_buffer("testa", buffer);
249 const char* inline_buffer_ptr = &buffer[0];
250 // Adding one more character causes the content to move from the inline to
251 // a dynamically allocated buffer.
252 buffer.push_back('b');
253 basic_memory_buffer<char, 5> buffer2;
254 buffer2 = std::move(buffer);
255 // Move should rip the guts of the first buffer.
256 EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
257 EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size()));
258 EXPECT_GT(buffer2.capacity(), 5u);
259 }
260
261 TEST(memory_buffer_test, grow) {
262 typedef allocator_ref<mock_allocator<int>> Allocator;
263 mock_allocator<int> alloc;
264 basic_memory_buffer<int, 10, Allocator> buffer((Allocator(&alloc)));
265 buffer.resize(7);
266 using fmt::detail::to_unsigned;
267 for (int i = 0; i < 7; ++i) buffer[to_unsigned(i)] = i * i;
268 EXPECT_EQ(10u, buffer.capacity());
269 int mem[20];
270 mem[7] = 0xdead;
271 EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem));
272 buffer.try_reserve(20);
273 EXPECT_EQ(20u, buffer.capacity());
274 // Check if size elements have been copied
275 for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[to_unsigned(i)]);
276 // and no more than that.
277 EXPECT_EQ(0xdead, buffer[7]);
278 EXPECT_CALL(alloc, deallocate(mem, 20));
279 }
280
281 TEST(memory_buffer_test, allocator) {
282 using test_allocator = allocator_ref<mock_allocator<char>>;
283 basic_memory_buffer<char, 10, test_allocator> buffer;
284 EXPECT_EQ(nullptr, buffer.get_allocator().get());
285 StrictMock<mock_allocator<char>> alloc;
286 char mem;
287 {
288 basic_memory_buffer<char, 10, test_allocator> buffer2(
289 (test_allocator(&alloc)));
290 EXPECT_EQ(&alloc, buffer2.get_allocator().get());
291 size_t size = 2 * fmt::inline_buffer_size;
292 EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem));
293 buffer2.reserve(size);
294 EXPECT_CALL(alloc, deallocate(&mem, size));
295 }
296 }
297
298 TEST(memory_buffer_test, exception_in_deallocate) {
299 using test_allocator = allocator_ref<mock_allocator<char>>;
300 StrictMock<mock_allocator<char>> alloc;
301 basic_memory_buffer<char, 10, test_allocator> buffer(
302 (test_allocator(&alloc)));
303 size_t size = 2 * fmt::inline_buffer_size;
304 auto mem = std::vector<char>(size);
305 {
306 EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0]));
307 buffer.resize(size);
308 std::fill(&buffer[0], &buffer[0] + size, 'x');
309 }
310 auto mem2 = std::vector<char>(2 * size);
311 {
312 EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0]));
313 auto e = std::exception();
314 EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e));
315 EXPECT_THROW(buffer.reserve(2 * size), std::exception);
316 EXPECT_EQ(&mem2[0], &buffer[0]);
317 // Check that the data has been copied.
318 for (size_t i = 0; i < size; ++i) EXPECT_EQ('x', buffer[i]);
319 }
320 EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size));
321 }
322
323 template <typename Allocator, size_t MaxSize>
324 class max_size_allocator : public Allocator {
325 public:
326 using typename Allocator::value_type;
327 size_t max_size() const FMT_NOEXCEPT { return MaxSize; }
328 value_type* allocate(size_t n) {
329 if (n > max_size()) {
330 throw std::length_error("size > max_size");
331 }
332 return std::allocator_traits<Allocator>::allocate(
333 *static_cast<Allocator*>(this), n);
334 }
335 void deallocate(value_type* p, size_t n) {
336 std::allocator_traits<Allocator>::deallocate(*static_cast<Allocator*>(this),
337 p, n);
338 }
339 };
340
341 TEST(memory_buffer_test, max_size_allocator) {
342 // 160 = 128 + 32
343 using test_allocator = max_size_allocator<std::allocator<char>, 160>;
344 basic_memory_buffer<char, 10, test_allocator> buffer;
345 buffer.resize(128);
346 // new_capacity = 128 + 128/2 = 192 > 160
347 buffer.resize(160); // Shouldn't throw.
348 }
349
350 TEST(memory_buffer_test, max_size_allocator_overflow) {
351 using test_allocator = max_size_allocator<std::allocator<char>, 160>;
352 basic_memory_buffer<char, 10, test_allocator> buffer;
353 EXPECT_THROW(buffer.resize(161), std::exception);
354 }
355
356 TEST(format_test, escape) {
357 EXPECT_EQ("{", fmt::format("{{"));
358 EXPECT_EQ("before {", fmt::format("before {{"));
359 EXPECT_EQ("{ after", fmt::format("{{ after"));
360 EXPECT_EQ("before { after", fmt::format("before {{ after"));
361
362 EXPECT_EQ("}", fmt::format("}}"));
363 EXPECT_EQ("before }", fmt::format("before }}"));
364 EXPECT_EQ("} after", fmt::format("}} after"));
365 EXPECT_EQ("before } after", fmt::format("before }} after"));
366
367 EXPECT_EQ("{}", fmt::format("{{}}"));
368 EXPECT_EQ("{42}", fmt::format("{{{0}}}", 42));
369 }
370
371 TEST(format_test, unmatched_braces) {
372 EXPECT_THROW_MSG((void)fmt::format(runtime("{")), format_error,
373 "invalid format string");
374 EXPECT_THROW_MSG((void)fmt::format(runtime("}")), format_error,
375 "unmatched '}' in format string");
376 EXPECT_THROW_MSG((void)fmt::format(runtime("{0{}")), format_error,
377 "invalid format string");
378 }
379
380 TEST(format_test, no_args) { EXPECT_EQ("test", fmt::format("test")); }
381
382 TEST(format_test, args_in_different_positions) {
383 EXPECT_EQ("42", fmt::format("{0}", 42));
384 EXPECT_EQ("before 42", fmt::format("before {0}", 42));
385 EXPECT_EQ("42 after", fmt::format("{0} after", 42));
386 EXPECT_EQ("before 42 after", fmt::format("before {0} after", 42));
387 EXPECT_EQ("answer = 42", fmt::format("{0} = {1}", "answer", 42));
388 EXPECT_EQ("42 is the answer", fmt::format("{1} is the {0}", "answer", 42));
389 EXPECT_EQ("abracadabra", fmt::format("{0}{1}{0}", "abra", "cad"));
390 }
391
392 TEST(format_test, arg_errors) {
393 EXPECT_THROW_MSG((void)fmt::format(runtime("{")), format_error,
394 "invalid format string");
395 EXPECT_THROW_MSG((void)fmt::format(runtime("{?}")), format_error,
396 "invalid format string");
397 EXPECT_THROW_MSG((void)fmt::format(runtime("{0")), format_error,
398 "invalid format string");
399 EXPECT_THROW_MSG((void)fmt::format(runtime("{0}")), format_error,
400 "argument not found");
401 EXPECT_THROW_MSG((void)fmt::format(runtime("{00}"), 42), format_error,
402 "invalid format string");
403
404 char format_str[buffer_size];
405 safe_sprintf(format_str, "{%u", INT_MAX);
406 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str)), format_error,
407 "invalid format string");
408 safe_sprintf(format_str, "{%u}", INT_MAX);
409 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str)), format_error,
410 "argument not found");
411
412 safe_sprintf(format_str, "{%u", INT_MAX + 1u);
413 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str)), format_error,
414 "invalid format string");
415 safe_sprintf(format_str, "{%u}", INT_MAX + 1u);
416 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str)), format_error,
417 "argument not found");
418 }
419
420 template <int N> struct test_format {
421 template <typename... T>
422 static std::string format(fmt::string_view fmt, const T&... args) {
423 return test_format<N - 1>::format(fmt, N - 1, args...);
424 }
425 };
426
427 template <> struct test_format<0> {
428 template <typename... T>
429 static std::string format(fmt::string_view fmt, const T&... args) {
430 return fmt::format(runtime(fmt), args...);
431 }
432 };
433
434 TEST(format_test, many_args) {
435 EXPECT_EQ("19", test_format<20>::format("{19}"));
436 EXPECT_THROW_MSG(test_format<20>::format("{20}"), format_error,
437 "argument not found");
438 EXPECT_THROW_MSG(test_format<21>::format("{21}"), format_error,
439 "argument not found");
440 using fmt::detail::max_packed_args;
441 std::string format_str = fmt::format("{{{}}}", max_packed_args + 1);
442 EXPECT_THROW_MSG(test_format<max_packed_args>::format(format_str),
443 format_error, "argument not found");
444 }
445
446 TEST(format_test, named_arg) {
447 EXPECT_EQ("1/a/A", fmt::format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'),
448 fmt::arg("A_", "A"), fmt::arg("_1", 1)));
449 EXPECT_EQ(" -42", fmt::format("{0:{width}}", -42, fmt::arg("width", 4)));
450 EXPECT_EQ("st",
451 fmt::format("{0:.{precision}}", "str", fmt::arg("precision", 2)));
452 EXPECT_EQ("1 2", fmt::format("{} {two}", 1, fmt::arg("two", 2)));
453 EXPECT_EQ("42",
454 fmt::format("{c}", fmt::arg("a", 0), fmt::arg("b", 0),
455 fmt::arg("c", 42), fmt::arg("d", 0), fmt::arg("e", 0),
456 fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0),
457 fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0),
458 fmt::arg("l", 0), fmt::arg("m", 0), fmt::arg("n", 0),
459 fmt::arg("o", 0), fmt::arg("p", 0)));
460 EXPECT_THROW_MSG((void)fmt::format(runtime("{a}")), format_error,
461 "argument not found");
462 EXPECT_THROW_MSG((void)fmt::format(runtime("{a}"), 42), format_error,
463 "argument not found");
464 }
465
466 TEST(format_test, auto_arg_index) {
467 EXPECT_EQ("abc", fmt::format("{}{}{}", 'a', 'b', 'c'));
468 EXPECT_THROW_MSG((void)fmt::format(runtime("{0}{}"), 'a', 'b'), format_error,
469 "cannot switch from manual to automatic argument indexing");
470 EXPECT_THROW_MSG((void)fmt::format(runtime("{}{0}"), 'a', 'b'), format_error,
471 "cannot switch from automatic to manual argument indexing");
472 EXPECT_EQ("1.2", fmt::format("{:.{}}", 1.2345, 2));
473 EXPECT_THROW_MSG((void)fmt::format(runtime("{0}:.{}"), 1.2345, 2),
474 format_error,
475 "cannot switch from manual to automatic argument indexing");
476 EXPECT_THROW_MSG((void)fmt::format(runtime("{:.{0}}"), 1.2345, 2),
477 format_error,
478 "cannot switch from automatic to manual argument indexing");
479 EXPECT_THROW_MSG((void)fmt::format(runtime("{}")), format_error,
480 "argument not found");
481 }
482
483 TEST(format_test, empty_specs) { EXPECT_EQ("42", fmt::format("{0:}", 42)); }
484
485 TEST(format_test, left_align) {
486 EXPECT_EQ("42 ", fmt::format("{0:<4}", 42));
487 EXPECT_EQ("42 ", fmt::format("{0:<4o}", 042));
488 EXPECT_EQ("42 ", fmt::format("{0:<4x}", 0x42));
489 EXPECT_EQ("-42 ", fmt::format("{0:<5}", -42));
490 EXPECT_EQ("42 ", fmt::format("{0:<5}", 42u));
491 EXPECT_EQ("-42 ", fmt::format("{0:<5}", -42l));
492 EXPECT_EQ("42 ", fmt::format("{0:<5}", 42ul));
493 EXPECT_EQ("-42 ", fmt::format("{0:<5}", -42ll));
494 EXPECT_EQ("42 ", fmt::format("{0:<5}", 42ull));
495 EXPECT_EQ("-42 ", fmt::format("{0:<5}", -42.0));
496 EXPECT_EQ("-42 ", fmt::format("{0:<5}", -42.0l));
497 EXPECT_EQ("c ", fmt::format("{0:<5}", 'c'));
498 EXPECT_EQ("abc ", fmt::format("{0:<5}", "abc"));
499 EXPECT_EQ("0xface ", fmt::format("{0:<8}", reinterpret_cast<void*>(0xface)));
500 }
501
502 TEST(format_test, right_align) {
503 EXPECT_EQ(" 42", fmt::format("{0:>4}", 42));
504 EXPECT_EQ(" 42", fmt::format("{0:>4o}", 042));
505 EXPECT_EQ(" 42", fmt::format("{0:>4x}", 0x42));
506 EXPECT_EQ(" -42", fmt::format("{0:>5}", -42));
507 EXPECT_EQ(" 42", fmt::format("{0:>5}", 42u));
508 EXPECT_EQ(" -42", fmt::format("{0:>5}", -42l));
509 EXPECT_EQ(" 42", fmt::format("{0:>5}", 42ul));
510 EXPECT_EQ(" -42", fmt::format("{0:>5}", -42ll));
511 EXPECT_EQ(" 42", fmt::format("{0:>5}", 42ull));
512 EXPECT_EQ(" -42", fmt::format("{0:>5}", -42.0));
513 EXPECT_EQ(" -42", fmt::format("{0:>5}", -42.0l));
514 EXPECT_EQ(" c", fmt::format("{0:>5}", 'c'));
515 EXPECT_EQ(" abc", fmt::format("{0:>5}", "abc"));
516 EXPECT_EQ(" 0xface", fmt::format("{0:>8}", reinterpret_cast<void*>(0xface)));
517 }
518
519 TEST(format_test, center_align) {
520 EXPECT_EQ(" 42 ", fmt::format("{0:^5}", 42));
521 EXPECT_EQ(" 42 ", fmt::format("{0:^5o}", 042));
522 EXPECT_EQ(" 42 ", fmt::format("{0:^5x}", 0x42));
523 EXPECT_EQ(" -42 ", fmt::format("{0:^5}", -42));
524 EXPECT_EQ(" 42 ", fmt::format("{0:^5}", 42u));
525 EXPECT_EQ(" -42 ", fmt::format("{0:^5}", -42l));
526 EXPECT_EQ(" 42 ", fmt::format("{0:^5}", 42ul));
527 EXPECT_EQ(" -42 ", fmt::format("{0:^5}", -42ll));
528 EXPECT_EQ(" 42 ", fmt::format("{0:^5}", 42ull));
529 EXPECT_EQ(" -42 ", fmt::format("{0:^5}", -42.0));
530 EXPECT_EQ(" -42 ", fmt::format("{0:^5}", -42.0l));
531 EXPECT_EQ(" c ", fmt::format("{0:^5}", 'c'));
532 EXPECT_EQ(" abc ", fmt::format("{0:^6}", "abc"));
533 EXPECT_EQ(" 0xface ", fmt::format("{0:^8}", reinterpret_cast<void*>(0xface)));
534 }
535
536 TEST(format_test, fill) {
537 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{<5}"), 'c'), format_error,
538 "invalid fill character '{'");
539 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{<5}}"), 'c'), format_error,
540 "invalid fill character '{'");
541 EXPECT_EQ("**42", fmt::format("{0:*>4}", 42));
542 EXPECT_EQ("**-42", fmt::format("{0:*>5}", -42));
543 EXPECT_EQ("***42", fmt::format("{0:*>5}", 42u));
544 EXPECT_EQ("**-42", fmt::format("{0:*>5}", -42l));
545 EXPECT_EQ("***42", fmt::format("{0:*>5}", 42ul));
546 EXPECT_EQ("**-42", fmt::format("{0:*>5}", -42ll));
547 EXPECT_EQ("***42", fmt::format("{0:*>5}", 42ull));
548 EXPECT_EQ("**-42", fmt::format("{0:*>5}", -42.0));
549 EXPECT_EQ("**-42", fmt::format("{0:*>5}", -42.0l));
550 EXPECT_EQ("c****", fmt::format("{0:*<5}", 'c'));
551 EXPECT_EQ("abc**", fmt::format("{0:*<5}", "abc"));
552 EXPECT_EQ("**0xface",
553 fmt::format("{0:*>8}", reinterpret_cast<void*>(0xface)));
554 EXPECT_EQ("foo=", fmt::format("{:}=", "foo"));
555 EXPECT_EQ(std::string("\0\0\0*", 4),
556 fmt::format(string_view("{:\0>4}", 6), '*'));
557 EXPECT_EQ("жж42", fmt::format("{0:ж>4}", 42));
558 EXPECT_THROW_MSG((void)fmt::format(runtime("{:\x80\x80\x80\x80\x80>}"), 0),
559 format_error, "invalid type specifier");
560 }
561
562 TEST(format_test, plus_sign) {
563 EXPECT_EQ("+42", fmt::format("{0:+}", 42));
564 EXPECT_EQ("-42", fmt::format("{0:+}", -42));
565 EXPECT_EQ("+42", fmt::format("{0:+}", 42));
566 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 42u), format_error,
567 "format specifier requires signed argument");
568 EXPECT_EQ("+42", fmt::format("{0:+}", 42l));
569 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 42ul), format_error,
570 "format specifier requires signed argument");
571 EXPECT_EQ("+42", fmt::format("{0:+}", 42ll));
572 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 42ull), format_error,
573 "format specifier requires signed argument");
574 EXPECT_EQ("+42", fmt::format("{0:+}", 42.0));
575 EXPECT_EQ("+42", fmt::format("{0:+}", 42.0l));
576 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+"), 'c'), format_error,
577 "missing '}' in format string");
578 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 'c'), format_error,
579 "invalid format specifier for char");
580 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), "abc"), format_error,
581 "format specifier requires numeric argument");
582 EXPECT_THROW_MSG(
583 (void)fmt::format(runtime("{0:+}"), reinterpret_cast<void*>(0x42)),
584 format_error, "format specifier requires numeric argument");
585 }
586
587 TEST(format_test, minus_sign) {
588 EXPECT_EQ("42", fmt::format("{0:-}", 42));
589 EXPECT_EQ("-42", fmt::format("{0:-}", -42));
590 EXPECT_EQ("42", fmt::format("{0:-}", 42));
591 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 42u), format_error,
592 "format specifier requires signed argument");
593 EXPECT_EQ("42", fmt::format("{0:-}", 42l));
594 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 42ul), format_error,
595 "format specifier requires signed argument");
596 EXPECT_EQ("42", fmt::format("{0:-}", 42ll));
597 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 42ull), format_error,
598 "format specifier requires signed argument");
599 EXPECT_EQ("42", fmt::format("{0:-}", 42.0));
600 EXPECT_EQ("42", fmt::format("{0:-}", 42.0l));
601 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-"), 'c'), format_error,
602 "missing '}' in format string");
603 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 'c'), format_error,
604 "invalid format specifier for char");
605 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), "abc"), format_error,
606 "format specifier requires numeric argument");
607 EXPECT_THROW_MSG(
608 (void)fmt::format(runtime("{0:-}"), reinterpret_cast<void*>(0x42)),
609 format_error, "format specifier requires numeric argument");
610 }
611
612 TEST(format_test, space_sign) {
613 EXPECT_EQ(" 42", fmt::format("{0: }", 42));
614 EXPECT_EQ("-42", fmt::format("{0: }", -42));
615 EXPECT_EQ(" 42", fmt::format("{0: }", 42));
616 EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 42u), format_error,
617 "format specifier requires signed argument");
618 EXPECT_EQ(" 42", fmt::format("{0: }", 42l));
619 EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 42ul), format_error,
620 "format specifier requires signed argument");
621 EXPECT_EQ(" 42", fmt::format("{0: }", 42ll));
622 EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 42ull), format_error,
623 "format specifier requires signed argument");
624 EXPECT_EQ(" 42", fmt::format("{0: }", 42.0));
625 EXPECT_EQ(" 42", fmt::format("{0: }", 42.0l));
626 EXPECT_THROW_MSG((void)fmt::format(runtime("{0: "), 'c'), format_error,
627 "missing '}' in format string");
628 EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 'c'), format_error,
629 "invalid format specifier for char");
630 EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), "abc"), format_error,
631 "format specifier requires numeric argument");
632 EXPECT_THROW_MSG(
633 (void)fmt::format(runtime("{0: }"), reinterpret_cast<void*>(0x42)),
634 format_error, "format specifier requires numeric argument");
635 }
636
637 TEST(format_test, hash_flag) {
638 EXPECT_EQ("42", fmt::format("{0:#}", 42));
639 EXPECT_EQ("-42", fmt::format("{0:#}", -42));
640 EXPECT_EQ("0b101010", fmt::format("{0:#b}", 42));
641 EXPECT_EQ("0B101010", fmt::format("{0:#B}", 42));
642 EXPECT_EQ("-0b101010", fmt::format("{0:#b}", -42));
643 EXPECT_EQ("0x42", fmt::format("{0:#x}", 0x42));
644 EXPECT_EQ("0X42", fmt::format("{0:#X}", 0x42));
645 EXPECT_EQ("-0x42", fmt::format("{0:#x}", -0x42));
646 EXPECT_EQ("0", fmt::format("{0:#o}", 0));
647 EXPECT_EQ("042", fmt::format("{0:#o}", 042));
648 EXPECT_EQ("-042", fmt::format("{0:#o}", -042));
649 EXPECT_EQ("42", fmt::format("{0:#}", 42u));
650 EXPECT_EQ("0x42", fmt::format("{0:#x}", 0x42u));
651 EXPECT_EQ("042", fmt::format("{0:#o}", 042u));
652
653 EXPECT_EQ("-42", fmt::format("{0:#}", -42l));
654 EXPECT_EQ("0x42", fmt::format("{0:#x}", 0x42l));
655 EXPECT_EQ("-0x42", fmt::format("{0:#x}", -0x42l));
656 EXPECT_EQ("042", fmt::format("{0:#o}", 042l));
657 EXPECT_EQ("-042", fmt::format("{0:#o}", -042l));
658 EXPECT_EQ("42", fmt::format("{0:#}", 42ul));
659 EXPECT_EQ("0x42", fmt::format("{0:#x}", 0x42ul));
660 EXPECT_EQ("042", fmt::format("{0:#o}", 042ul));
661
662 EXPECT_EQ("-42", fmt::format("{0:#}", -42ll));
663 EXPECT_EQ("0x42", fmt::format("{0:#x}", 0x42ll));
664 EXPECT_EQ("-0x42", fmt::format("{0:#x}", -0x42ll));
665 EXPECT_EQ("042", fmt::format("{0:#o}", 042ll));
666 EXPECT_EQ("-042", fmt::format("{0:#o}", -042ll));
667 EXPECT_EQ("42", fmt::format("{0:#}", 42ull));
668 EXPECT_EQ("0x42", fmt::format("{0:#x}", 0x42ull));
669 EXPECT_EQ("042", fmt::format("{0:#o}", 042ull));
670
671 EXPECT_EQ("-42.0", fmt::format("{0:#}", -42.0));
672 EXPECT_EQ("-42.0", fmt::format("{0:#}", -42.0l));
673 EXPECT_EQ("4.e+01", fmt::format("{:#.0e}", 42.0));
674 EXPECT_EQ("0.", fmt::format("{:#.0f}", 0.01));
675 EXPECT_EQ("0.50", fmt::format("{:#.2g}", 0.5));
676 EXPECT_EQ("0.", fmt::format("{:#.0f}", 0.5));
677 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#"), 'c'), format_error,
678 "missing '}' in format string");
679 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#}"), 'c'), format_error,
680 "invalid format specifier for char");
681 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#}"), "abc"), format_error,
682 "format specifier requires numeric argument");
683 EXPECT_THROW_MSG(
684 (void)fmt::format(runtime("{0:#}"), reinterpret_cast<void*>(0x42)),
685 format_error, "format specifier requires numeric argument");
686 }
687
688 TEST(format_test, zero_flag) {
689 EXPECT_EQ("42", fmt::format("{0:0}", 42));
690 EXPECT_EQ("-0042", fmt::format("{0:05}", -42));
691 EXPECT_EQ("00042", fmt::format("{0:05}", 42u));
692 EXPECT_EQ("-0042", fmt::format("{0:05}", -42l));
693 EXPECT_EQ("00042", fmt::format("{0:05}", 42ul));
694 EXPECT_EQ("-0042", fmt::format("{0:05}", -42ll));
695 EXPECT_EQ("00042", fmt::format("{0:05}", 42ull));
696 EXPECT_EQ("-000042", fmt::format("{0:07}", -42.0));
697 EXPECT_EQ("-000042", fmt::format("{0:07}", -42.0l));
698 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:0"), 'c'), format_error,
699 "missing '}' in format string");
700 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:05}"), 'c'), format_error,
701 "invalid format specifier for char");
702 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:05}"), "abc"), format_error,
703 "format specifier requires numeric argument");
704 EXPECT_THROW_MSG(
705 (void)fmt::format(runtime("{0:05}"), reinterpret_cast<void*>(0x42)),
706 format_error, "format specifier requires numeric argument");
707 }
708
709 TEST(format_test, width) {
710 char format_str[buffer_size];
711 safe_sprintf(format_str, "{0:%u", UINT_MAX);
712 increment(format_str + 3);
713 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
714 "number is too big");
715 size_t size = std::strlen(format_str);
716 format_str[size] = '}';
717 format_str[size + 1] = 0;
718 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
719 "number is too big");
720
721 safe_sprintf(format_str, "{0:%u", INT_MAX + 1u);
722 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
723 "number is too big");
724 safe_sprintf(format_str, "{0:%u}", INT_MAX + 1u);
725 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
726 "number is too big");
727 EXPECT_EQ(" -42", fmt::format("{0:4}", -42));
728 EXPECT_EQ(" 42", fmt::format("{0:5}", 42u));
729 EXPECT_EQ(" -42", fmt::format("{0:6}", -42l));
730 EXPECT_EQ(" 42", fmt::format("{0:7}", 42ul));
731 EXPECT_EQ(" -42", fmt::format("{0:6}", -42ll));
732 EXPECT_EQ(" 42", fmt::format("{0:7}", 42ull));
733 EXPECT_EQ(" -1.23", fmt::format("{0:8}", -1.23));
734 EXPECT_EQ(" -1.23", fmt::format("{0:9}", -1.23l));
735 EXPECT_EQ(" 0xcafe",
736 fmt::format("{0:10}", reinterpret_cast<void*>(0xcafe)));
737 EXPECT_EQ("x ", fmt::format("{0:11}", 'x'));
738 EXPECT_EQ("str ", fmt::format("{0:12}", "str"));
739 EXPECT_EQ(fmt::format("{:*^6}", "🤡"), "**🤡**");
740 EXPECT_EQ(fmt::format("{:*^8}", "你好"), "**你好**");
741 EXPECT_EQ(fmt::format("{:#6}", 42.0), " 42.0");
742 EXPECT_EQ(fmt::format("{:6c}", static_cast<int>('x')), "x ");
743 EXPECT_EQ(fmt::format("{:>06.0f}", 0.00884311), "000000");
744 }
745
746 TEST(format_test, runtime_width) {
747 char format_str[buffer_size];
748 safe_sprintf(format_str, "{0:{%u", UINT_MAX);
749 increment(format_str + 4);
750 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
751 "invalid format string");
752 size_t size = std::strlen(format_str);
753 format_str[size] = '}';
754 format_str[size + 1] = 0;
755 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
756 "argument not found");
757 format_str[size + 1] = '}';
758 format_str[size + 2] = 0;
759 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
760 "argument not found");
761
762 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{"), 0), format_error,
763 "invalid format string");
764 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{}"), 0), format_error,
765 "cannot switch from manual to automatic argument indexing");
766 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{?}}"), 0), format_error,
767 "invalid format string");
768 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0), format_error,
769 "argument not found");
770
771 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{0:}}"), 0), format_error,
772 "invalid format string");
773
774 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, -1), format_error,
775 "negative width");
776 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (INT_MAX + 1u)),
777 format_error, "number is too big");
778 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, -1l), format_error,
779 "negative width");
780 if (fmt::detail::const_check(sizeof(long) > sizeof(int))) {
781 long value = INT_MAX;
782 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (value + 1)),
783 format_error, "number is too big");
784 }
785 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (INT_MAX + 1ul)),
786 format_error, "number is too big");
787
788 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, '0'), format_error,
789 "width is not integer");
790 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, 0.0), format_error,
791 "width is not integer");
792
793 EXPECT_EQ(" -42", fmt::format("{0:{1}}", -42, 4));
794 EXPECT_EQ(" 42", fmt::format("{0:{1}}", 42u, 5));
795 EXPECT_EQ(" -42", fmt::format("{0:{1}}", -42l, 6));
796 EXPECT_EQ(" 42", fmt::format("{0:{1}}", 42ul, 7));
797 EXPECT_EQ(" -42", fmt::format("{0:{1}}", -42ll, 6));
798 EXPECT_EQ(" 42", fmt::format("{0:{1}}", 42ull, 7));
799 EXPECT_EQ(" -1.23", fmt::format("{0:{1}}", -1.23, 8));
800 EXPECT_EQ(" -1.23", fmt::format("{0:{1}}", -1.23l, 9));
801 EXPECT_EQ(" 0xcafe",
802 fmt::format("{0:{1}}", reinterpret_cast<void*>(0xcafe), 10));
803 EXPECT_EQ("x ", fmt::format("{0:{1}}", 'x', 11));
804 EXPECT_EQ("str ", fmt::format("{0:{1}}", "str", 12));
805 }
806
807 TEST(format_test, precision) {
808 char format_str[buffer_size];
809 safe_sprintf(format_str, "{0:.%u", UINT_MAX);
810 increment(format_str + 4);
811 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
812 "number is too big");
813 size_t size = std::strlen(format_str);
814 format_str[size] = '}';
815 format_str[size + 1] = 0;
816 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
817 "number is too big");
818
819 safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u);
820 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
821 "number is too big");
822 safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u);
823 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
824 "number is too big");
825
826 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:."), 0), format_error,
827 "missing precision specifier");
828 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.}"), 0), format_error,
829 "missing precision specifier");
830
831 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2"), 0), format_error,
832 "precision not allowed for this argument type");
833 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42), format_error,
834 "precision not allowed for this argument type");
835 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42), format_error,
836 "precision not allowed for this argument type");
837 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42u), format_error,
838 "precision not allowed for this argument type");
839 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42u), format_error,
840 "precision not allowed for this argument type");
841 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42l), format_error,
842 "precision not allowed for this argument type");
843 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42l), format_error,
844 "precision not allowed for this argument type");
845 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42ul), format_error,
846 "precision not allowed for this argument type");
847 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42ul), format_error,
848 "precision not allowed for this argument type");
849 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42ll), format_error,
850 "precision not allowed for this argument type");
851 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42ll), format_error,
852 "precision not allowed for this argument type");
853 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42ull), format_error,
854 "precision not allowed for this argument type");
855 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42ull), format_error,
856 "precision not allowed for this argument type");
857 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:3.0}"), 'x'), format_error,
858 "precision not allowed for this argument type");
859 EXPECT_EQ("1.2", fmt::format("{0:.2}", 1.2345));
860 EXPECT_EQ("1.2", fmt::format("{0:.2}", 1.2345l));
861 EXPECT_EQ("1.2e+56", fmt::format("{:.2}", 1.234e56));
862 EXPECT_EQ("1.1", fmt::format("{0:.3}", 1.1));
863 EXPECT_EQ("1e+00", fmt::format("{:.0e}", 1.0L));
864 EXPECT_EQ(" 0.0e+00", fmt::format("{:9.1e}", 0.0));
865 EXPECT_EQ(
866 fmt::format("{:.494}", 4.9406564584124654E-324),
867 "4.9406564584124654417656879286822137236505980261432476442558568250067550"
868 "727020875186529983636163599237979656469544571773092665671035593979639877"
869 "479601078187812630071319031140452784581716784898210368871863605699873072"
870 "305000638740915356498438731247339727316961514003171538539807412623856559"
871 "117102665855668676818703956031062493194527159149245532930545654440112748"
872 "012970999954193198940908041656332452475714786901472678015935523861155013"
873 "480352649347201937902681071074917033322268447533357208324319361e-324");
874 EXPECT_EQ(
875 fmt::format("{:.1074f}", 1.1125369292536e-308),
876 "0.0000000000000000000000000000000000000000000000000000000000000000000000"
877 "000000000000000000000000000000000000000000000000000000000000000000000000"
878 "000000000000000000000000000000000000000000000000000000000000000000000000"
879 "000000000000000000000000000000000000000000000000000000000000000000000000"
880 "000000000000000000000111253692925360019747947051741965785554081512200979"
881 "355021686109411883779182127659725163430929750364498219730822952552570601"
882 "152163505899912777129583674906301179059298598412303893909188340988729019"
883 "014361467448914817838555156840459458527907308695109202499990850735085304"
884 "478476991912072201449236975063640913461919914396877093174125167509869762"
885 "482369631100360266123742648159508919592746619553246586039571522788247697"
886 "156360766271842991667238355464496455107749716934387136380536472531224398"
887 "559833794807213172371254492216255558078524900147957309382830827524104234"
888 "530961756787819847850302379672357738807808384667004752163416921762619527"
889 "462847642037420991432005657440259928195996762610375541867198059294212446"
890 "81962777939941034720757232455434770912461317493580281734466552734375");
891
892 std::string outputs[] = {
893 "-0X1.41FE3FFE71C9E000000000000000000000000000000000000000000000000000000"
894 "000000000000000000000000000000000000000000000000000000000000000000000000"
895 "000000000000000000000000000000000000000000000000000000000000000000000000"
896 "000000000000000000000000000000000000000000000000000000000000000000000000"
897 "000000000000000000000000000000000000000000000000000000000000000000000000"
898 "000000000000000000000000000000000000000000000000000000000000000000000000"
899 "000000000000000000000000000000000000000000000000000000000000000000000000"
900 "000000000000000000000000000000000000000000000000000000000000000000000000"
901 "000000000000000000000000000000000000000000000000000000000000000000000000"
902 "000000000000000000000000000000000000000000000000000000000000000000000000"
903 "000000000000000000000000000000000000000000000000000000000000000000000000"
904 "000000000000000000000000000000000000000000000000000P+127",
905 "-0XA.0FF1FFF38E4F0000000000000000000000000000000000000000000000000000000"
906 "000000000000000000000000000000000000000000000000000000000000000000000000"
907 "000000000000000000000000000000000000000000000000000000000000000000000000"
908 "000000000000000000000000000000000000000000000000000000000000000000000000"
909 "000000000000000000000000000000000000000000000000000000000000000000000000"
910 "000000000000000000000000000000000000000000000000000000000000000000000000"
911 "000000000000000000000000000000000000000000000000000000000000000000000000"
912 "000000000000000000000000000000000000000000000000000000000000000000000000"
913 "000000000000000000000000000000000000000000000000000000000000000000000000"
914 "000000000000000000000000000000000000000000000000000000000000000000000000"
915 "000000000000000000000000000000000000000000000000000000000000000000000000"
916 "000000000000000000000000000000000000000000000000000P+124"};
917 EXPECT_THAT(outputs,
918 testing::Contains(fmt::format("{:.838A}", -2.14001164E+38)));
919
920 EXPECT_EQ("123.", fmt::format("{:#.0f}", 123.0));
921 EXPECT_EQ("1.23", fmt::format("{:.02f}", 1.234));
922 EXPECT_EQ("0.001", fmt::format("{:.1g}", 0.001));
923 EXPECT_EQ("1019666400", fmt::format("{}", 1019666432.0f));
924 EXPECT_EQ("1e+01", fmt::format("{:.0e}", 9.5));
925 EXPECT_EQ("1.0e-34", fmt::format("{:.1e}", 1e-34));
926
927 EXPECT_THROW_MSG(
928 (void)fmt::format(runtime("{0:.2}"), reinterpret_cast<void*>(0xcafe)),
929 format_error, "precision not allowed for this argument type");
930 EXPECT_THROW_MSG(
931 (void)fmt::format(runtime("{0:.2f}"), reinterpret_cast<void*>(0xcafe)),
932 format_error, "precision not allowed for this argument type");
933 EXPECT_THROW_MSG((void)fmt::format(runtime("{:.{}e}"), 42.0,
934 fmt::detail::max_value<int>()),
935 format_error, "number is too big");
936 EXPECT_THROW_MSG(
937 (void)fmt::format("{:.2147483646f}", -2.2121295195081227E+304),
938 format_error, "number is too big");
939
940 EXPECT_EQ("st", fmt::format("{0:.2}", "str"));
941 }
942
943 TEST(format_test, runtime_precision) {
944 char format_str[buffer_size];
945 safe_sprintf(format_str, "{0:.{%u", UINT_MAX);
946 increment(format_str + 5);
947 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
948 "invalid format string");
949 size_t size = std::strlen(format_str);
950 format_str[size] = '}';
951 format_str[size + 1] = 0;
952 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
953 "argument not found");
954 format_str[size + 1] = '}';
955 format_str[size + 2] = 0;
956 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0), format_error,
957 "argument not found");
958
959 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{"), 0), format_error,
960 "invalid format string");
961 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{}"), 0), format_error,
962 "cannot switch from manual to automatic argument indexing");
963 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{?}}"), 0), format_error,
964 "invalid format string");
965 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}"), 0, 0), format_error,
966 "precision not allowed for this argument type");
967 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0), format_error,
968 "argument not found");
969
970 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{0:}}"), 0), format_error,
971 "invalid format string");
972
973 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0, -1), format_error,
974 "negative precision");
975 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0, (INT_MAX + 1u)),
976 format_error, "number is too big");
977 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0, -1l), format_error,
978 "negative precision");
979 if (fmt::detail::const_check(sizeof(long) > sizeof(int))) {
980 long value = INT_MAX;
981 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0, (value + 1)),
982 format_error, "number is too big");
983 }
984 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0, (INT_MAX + 1ul)),
985 format_error, "number is too big");
986
987 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0, '0'), format_error,
988 "precision is not integer");
989 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0, 0.0), format_error,
990 "precision is not integer");
991
992 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42, 2), format_error,
993 "precision not allowed for this argument type");
994 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42, 2), format_error,
995 "precision not allowed for this argument type");
996 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42u, 2), format_error,
997 "precision not allowed for this argument type");
998 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42u, 2),
999 format_error,
1000 "precision not allowed for this argument type");
1001 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42l, 2), format_error,
1002 "precision not allowed for this argument type");
1003 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42l, 2),
1004 format_error,
1005 "precision not allowed for this argument type");
1006 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42ul, 2),
1007 format_error,
1008 "precision not allowed for this argument type");
1009 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42ul, 2),
1010 format_error,
1011 "precision not allowed for this argument type");
1012 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42ll, 2),
1013 format_error,
1014 "precision not allowed for this argument type");
1015 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42ll, 2),
1016 format_error,
1017 "precision not allowed for this argument type");
1018 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42ull, 2),
1019 format_error,
1020 "precision not allowed for this argument type");
1021 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42ull, 2),
1022 format_error,
1023 "precision not allowed for this argument type");
1024 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:3.{1}}"), 'x', 0),
1025 format_error,
1026 "precision not allowed for this argument type");
1027 EXPECT_EQ("1.2", fmt::format("{0:.{1}}", 1.2345, 2));
1028 EXPECT_EQ("1.2", fmt::format("{1:.{0}}", 2, 1.2345l));
1029
1030 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"),
1031 reinterpret_cast<void*>(0xcafe), 2),
1032 format_error,
1033 "precision not allowed for this argument type");
1034 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"),
1035 reinterpret_cast<void*>(0xcafe), 2),
1036 format_error,
1037 "precision not allowed for this argument type");
1038
1039 EXPECT_EQ("st", fmt::format("{0:.{1}}", "str", 2));
1040 }
1041
1042 TEST(format_test, format_bool) {
1043 EXPECT_EQ("true", fmt::format("{}", true));
1044 EXPECT_EQ("false", fmt::format("{}", false));
1045 EXPECT_EQ("1", fmt::format("{:d}", true));
1046 EXPECT_EQ("true ", fmt::format("{:5}", true));
1047 EXPECT_EQ("true", fmt::format("{:s}", true));
1048 EXPECT_EQ("false", fmt::format("{:s}", false));
1049 EXPECT_EQ("false ", fmt::format("{:6s}", false));
1050 }
1051
1052 TEST(format_test, format_short) {
1053 short s = 42;
1054 EXPECT_EQ("42", fmt::format("{0:d}", s));
1055 unsigned short us = 42;
1056 EXPECT_EQ("42", fmt::format("{0:d}", us));
1057 }
1058
1059 template <typename T>
1060 void check_unknown_types(const T& value, const char* types, const char*) {
1061 char format_str[buffer_size];
1062 const char* special = ".0123456789L}";
1063 for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) {
1064 char c = static_cast<char>(i);
1065 if (std::strchr(types, c) || std::strchr(special, c) || !c) continue;
1066 safe_sprintf(format_str, "{0:10%c}", c);
1067 const char* message = "invalid type specifier";
1068 EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), value),
1069 format_error, message)
1070 << format_str << " " << message;
1071 }
1072 }
1073
1074 TEST(format_test, format_int) {
1075 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:v"), 42), format_error,
1076 "invalid type specifier");
1077 check_unknown_types(42, "bBdoxXnLc", "integer");
1078 EXPECT_EQ("x", fmt::format("{:c}", static_cast<int>('x')));
1079 }
1080
1081 TEST(format_test, format_bin) {
1082 EXPECT_EQ("0", fmt::format("{0:b}", 0));
1083 EXPECT_EQ("101010", fmt::format("{0:b}", 42));
1084 EXPECT_EQ("101010", fmt::format("{0:b}", 42u));
1085 EXPECT_EQ("-101010", fmt::format("{0:b}", -42));
1086 EXPECT_EQ("11000000111001", fmt::format("{0:b}", 12345));
1087 EXPECT_EQ("10010001101000101011001111000", fmt::format("{0:b}", 0x12345678));
1088 EXPECT_EQ("10010000101010111100110111101111",
1089 fmt::format("{0:b}", 0x90ABCDEF));
1090 EXPECT_EQ("11111111111111111111111111111111",
1091 fmt::format("{0:b}", max_value<uint32_t>()));
1092 }
1093
1094 #if FMT_USE_INT128
1095 constexpr auto int128_max = static_cast<__int128_t>(
1096 (static_cast<__uint128_t>(1) << ((__SIZEOF_INT128__ * CHAR_BIT) - 1)) - 1);
1097 constexpr auto int128_min = -int128_max - 1;
1098
1099 constexpr auto uint128_max = ~static_cast<__uint128_t>(0);
1100 #endif
1101
1102 TEST(format_test, format_dec) {
1103 EXPECT_EQ("0", fmt::format("{0}", 0));
1104 EXPECT_EQ("42", fmt::format("{0}", 42));
1105 EXPECT_EQ("42", fmt::format("{0:d}", 42));
1106 EXPECT_EQ("42", fmt::format("{0}", 42u));
1107 EXPECT_EQ("-42", fmt::format("{0}", -42));
1108 EXPECT_EQ("12345", fmt::format("{0}", 12345));
1109 EXPECT_EQ("67890", fmt::format("{0}", 67890));
1110 #if FMT_USE_INT128
1111 EXPECT_EQ("0", fmt::format("{0}", static_cast<__int128_t>(0)));
1112 EXPECT_EQ("0", fmt::format("{0}", static_cast<__uint128_t>(0)));
1113 EXPECT_EQ("9223372036854775808",
1114 fmt::format("{0}", static_cast<__int128_t>(INT64_MAX) + 1));
1115 EXPECT_EQ("-9223372036854775809",
1116 fmt::format("{0}", static_cast<__int128_t>(INT64_MIN) - 1));
1117 EXPECT_EQ("18446744073709551616",
1118 fmt::format("{0}", static_cast<__int128_t>(UINT64_MAX) + 1));
1119 EXPECT_EQ("170141183460469231731687303715884105727",
1120 fmt::format("{0}", int128_max));
1121 EXPECT_EQ("-170141183460469231731687303715884105728",
1122 fmt::format("{0}", int128_min));
1123 EXPECT_EQ("340282366920938463463374607431768211455",
1124 fmt::format("{0}", uint128_max));
1125 #endif
1126
1127 char buffer[buffer_size];
1128 safe_sprintf(buffer, "%d", INT_MIN);
1129 EXPECT_EQ(buffer, fmt::format("{0}", INT_MIN));
1130 safe_sprintf(buffer, "%d", INT_MAX);
1131 EXPECT_EQ(buffer, fmt::format("{0}", INT_MAX));
1132 safe_sprintf(buffer, "%u", UINT_MAX);
1133 EXPECT_EQ(buffer, fmt::format("{0}", UINT_MAX));
1134 safe_sprintf(buffer, "%ld", 0 - static_cast<unsigned long>(LONG_MIN));
1135 EXPECT_EQ(buffer, fmt::format("{0}", LONG_MIN));
1136 safe_sprintf(buffer, "%ld", LONG_MAX);
1137 EXPECT_EQ(buffer, fmt::format("{0}", LONG_MAX));
1138 safe_sprintf(buffer, "%lu", ULONG_MAX);
1139 EXPECT_EQ(buffer, fmt::format("{0}", ULONG_MAX));
1140 }
1141
1142 TEST(format_test, format_hex) {
1143 EXPECT_EQ("0", fmt::format("{0:x}", 0));
1144 EXPECT_EQ("42", fmt::format("{0:x}", 0x42));
1145 EXPECT_EQ("42", fmt::format("{0:x}", 0x42u));
1146 EXPECT_EQ("-42", fmt::format("{0:x}", -0x42));
1147 EXPECT_EQ("12345678", fmt::format("{0:x}", 0x12345678));
1148 EXPECT_EQ("90abcdef", fmt::format("{0:x}", 0x90abcdef));
1149 EXPECT_EQ("12345678", fmt::format("{0:X}", 0x12345678));
1150 EXPECT_EQ("90ABCDEF", fmt::format("{0:X}", 0x90ABCDEF));
1151 #if FMT_USE_INT128
1152 EXPECT_EQ("0", fmt::format("{0:x}", static_cast<__int128_t>(0)));
1153 EXPECT_EQ("0", fmt::format("{0:x}", static_cast<__uint128_t>(0)));
1154 EXPECT_EQ("8000000000000000",
1155 fmt::format("{0:x}", static_cast<__int128_t>(INT64_MAX) + 1));
1156 EXPECT_EQ("-8000000000000001",
1157 fmt::format("{0:x}", static_cast<__int128_t>(INT64_MIN) - 1));
1158 EXPECT_EQ("10000000000000000",
1159 fmt::format("{0:x}", static_cast<__int128_t>(UINT64_MAX) + 1));
1160 EXPECT_EQ("7fffffffffffffffffffffffffffffff",
1161 fmt::format("{0:x}", int128_max));
1162 EXPECT_EQ("-80000000000000000000000000000000",
1163 fmt::format("{0:x}", int128_min));
1164 EXPECT_EQ("ffffffffffffffffffffffffffffffff",
1165 fmt::format("{0:x}", uint128_max));
1166 #endif
1167
1168 char buffer[buffer_size];
1169 safe_sprintf(buffer, "-%x", 0 - static_cast<unsigned>(INT_MIN));
1170 EXPECT_EQ(buffer, fmt::format("{0:x}", INT_MIN));
1171 safe_sprintf(buffer, "%x", INT_MAX);
1172 EXPECT_EQ(buffer, fmt::format("{0:x}", INT_MAX));
1173 safe_sprintf(buffer, "%x", UINT_MAX);
1174 EXPECT_EQ(buffer, fmt::format("{0:x}", UINT_MAX));
1175 safe_sprintf(buffer, "-%lx", 0 - static_cast<unsigned long>(LONG_MIN));
1176 EXPECT_EQ(buffer, fmt::format("{0:x}", LONG_MIN));
1177 safe_sprintf(buffer, "%lx", LONG_MAX);
1178 EXPECT_EQ(buffer, fmt::format("{0:x}", LONG_MAX));
1179 safe_sprintf(buffer, "%lx", ULONG_MAX);
1180 EXPECT_EQ(buffer, fmt::format("{0:x}", ULONG_MAX));
1181 }
1182
1183 TEST(format_test, format_oct) {
1184 EXPECT_EQ("0", fmt::format("{0:o}", 0));
1185 EXPECT_EQ("42", fmt::format("{0:o}", 042));
1186 EXPECT_EQ("42", fmt::format("{0:o}", 042u));
1187 EXPECT_EQ("-42", fmt::format("{0:o}", -042));
1188 EXPECT_EQ("12345670", fmt::format("{0:o}", 012345670));
1189 #if FMT_USE_INT128
1190 EXPECT_EQ("0", fmt::format("{0:o}", static_cast<__int128_t>(0)));
1191 EXPECT_EQ("0", fmt::format("{0:o}", static_cast<__uint128_t>(0)));
1192 EXPECT_EQ("1000000000000000000000",
1193 fmt::format("{0:o}", static_cast<__int128_t>(INT64_MAX) + 1));
1194 EXPECT_EQ("-1000000000000000000001",
1195 fmt::format("{0:o}", static_cast<__int128_t>(INT64_MIN) - 1));
1196 EXPECT_EQ("2000000000000000000000",
1197 fmt::format("{0:o}", static_cast<__int128_t>(UINT64_MAX) + 1));
1198 EXPECT_EQ("1777777777777777777777777777777777777777777",
1199 fmt::format("{0:o}", int128_max));
1200 EXPECT_EQ("-2000000000000000000000000000000000000000000",
1201 fmt::format("{0:o}", int128_min));
1202 EXPECT_EQ("3777777777777777777777777777777777777777777",
1203 fmt::format("{0:o}", uint128_max));
1204 #endif
1205
1206 char buffer[buffer_size];
1207 safe_sprintf(buffer, "-%o", 0 - static_cast<unsigned>(INT_MIN));
1208 EXPECT_EQ(buffer, fmt::format("{0:o}", INT_MIN));
1209 safe_sprintf(buffer, "%o", INT_MAX);
1210 EXPECT_EQ(buffer, fmt::format("{0:o}", INT_MAX));
1211 safe_sprintf(buffer, "%o", UINT_MAX);
1212 EXPECT_EQ(buffer, fmt::format("{0:o}", UINT_MAX));
1213 safe_sprintf(buffer, "-%lo", 0 - static_cast<unsigned long>(LONG_MIN));
1214 EXPECT_EQ(buffer, fmt::format("{0:o}", LONG_MIN));
1215 safe_sprintf(buffer, "%lo", LONG_MAX);
1216 EXPECT_EQ(buffer, fmt::format("{0:o}", LONG_MAX));
1217 safe_sprintf(buffer, "%lo", ULONG_MAX);
1218 EXPECT_EQ(buffer, fmt::format("{0:o}", ULONG_MAX));
1219 }
1220
1221 TEST(format_test, format_int_locale) {
1222 EXPECT_EQ("1234", fmt::format("{:L}", 1234));
1223 }
1224
1225 TEST(format_test, format_float) {
1226 EXPECT_EQ("0", fmt::format("{}", 0.0f));
1227 EXPECT_EQ("392.500000", fmt::format("{0:f}", 392.5f));
1228 }
1229
1230 TEST(format_test, format_double) {
1231 EXPECT_EQ("0", fmt::format("{}", 0.0));
1232 check_unknown_types(1.2, "eEfFgGaAnL%", "double");
1233 EXPECT_EQ("0", fmt::format("{:}", 0.0));
1234 EXPECT_EQ("0.000000", fmt::format("{:f}", 0.0));
1235 EXPECT_EQ("0", fmt::format("{:g}", 0.0));
1236 EXPECT_EQ("392.65", fmt::format("{:}", 392.65));
1237 EXPECT_EQ("392.65", fmt::format("{:g}", 392.65));
1238 EXPECT_EQ("392.65", fmt::format("{:G}", 392.65));
1239 EXPECT_EQ("4.9014e+06", fmt::format("{:g}", 4.9014e6));
1240 EXPECT_EQ("392.650000", fmt::format("{:f}", 392.65));
1241 EXPECT_EQ("392.650000", fmt::format("{:F}", 392.65));
1242 EXPECT_EQ("42", fmt::format("{:L}", 42.0));
1243 EXPECT_EQ(" 0x1.0cccccccccccdp+2", fmt::format("{:24a}", 4.2));
1244 EXPECT_EQ("0x1.0cccccccccccdp+2 ", fmt::format("{:<24a}", 4.2));
1245 char buffer[buffer_size];
1246 safe_sprintf(buffer, "%e", 392.65);
1247 EXPECT_EQ(buffer, fmt::format("{0:e}", 392.65));
1248 safe_sprintf(buffer, "%E", 392.65);
1249 EXPECT_EQ(buffer, fmt::format("{0:E}", 392.65));
1250 EXPECT_EQ("+0000392.6", fmt::format("{0:+010.4g}", 392.65));
1251 safe_sprintf(buffer, "%a", -42.0);
1252 EXPECT_EQ(buffer, fmt::format("{:a}", -42.0));
1253 safe_sprintf(buffer, "%A", -42.0);
1254 EXPECT_EQ(buffer, fmt::format("{:A}", -42.0));
1255 EXPECT_EQ("9223372036854775808.000000",
1256 fmt::format("{:f}", 9223372036854775807.0));
1257 }
1258
1259 TEST(format_test, precision_rounding) {
1260 EXPECT_EQ("0", fmt::format("{:.0f}", 0.0));
1261 EXPECT_EQ("0", fmt::format("{:.0f}", 0.01));
1262 EXPECT_EQ("0", fmt::format("{:.0f}", 0.1));
1263 EXPECT_EQ("0.000", fmt::format("{:.3f}", 0.00049));
1264 EXPECT_EQ("0.001", fmt::format("{:.3f}", 0.0005));
1265 EXPECT_EQ("0.001", fmt::format("{:.3f}", 0.00149));
1266 EXPECT_EQ("0.002", fmt::format("{:.3f}", 0.0015));
1267 EXPECT_EQ("1.000", fmt::format("{:.3f}", 0.9999));
1268 EXPECT_EQ("0.00123", fmt::format("{:.3}", 0.00123));
1269 EXPECT_EQ("0.1", fmt::format("{:.16g}", 0.1));
1270 EXPECT_EQ("1", fmt::format("{:.0}", 1.0));
1271 EXPECT_EQ("225.51575035152063720",
1272 fmt::format("{:.17f}", 225.51575035152064));
1273 EXPECT_EQ("-761519619559038.2", fmt::format("{:.1f}", -761519619559038.2));
1274 EXPECT_EQ("1.9156918820264798e-56",
1275 fmt::format("{}", 1.9156918820264798e-56));
1276 EXPECT_EQ("0.0000", fmt::format("{:.4f}", 7.2809479766055470e-15));
1277
1278 // Trigger a rounding error in Grisu by a specially chosen number.
1279 EXPECT_EQ("3788512123356.985352", fmt::format("{:f}", 3788512123356.985352));
1280 }
1281
1282 TEST(format_test, prettify_float) {
1283 EXPECT_EQ("0.0001", fmt::format("{}", 1e-4));
1284 EXPECT_EQ("1e-05", fmt::format("{}", 1e-5));
1285 EXPECT_EQ("1000000000000000", fmt::format("{}", 1e15));
1286 EXPECT_EQ("1e+16", fmt::format("{}", 1e16));
1287 EXPECT_EQ("9.999e-05", fmt::format("{}", 9.999e-5));
1288 EXPECT_EQ("10000000000", fmt::format("{}", 1e10));
1289 EXPECT_EQ("100000000000", fmt::format("{}", 1e11));
1290 EXPECT_EQ("12340000000", fmt::format("{}", 1234e7));
1291 EXPECT_EQ("12.34", fmt::format("{}", 1234e-2));
1292 EXPECT_EQ("0.001234", fmt::format("{}", 1234e-6));
1293 EXPECT_EQ("0.1", fmt::format("{}", 0.1f));
1294 EXPECT_EQ("0.10000000149011612", fmt::format("{}", double(0.1f)));
1295 EXPECT_EQ("1.3563156e-19", fmt::format("{}", 1.35631564e-19f));
1296 }
1297
1298 TEST(format_test, format_nan) {
1299 double nan = std::numeric_limits<double>::quiet_NaN();
1300 EXPECT_EQ("nan", fmt::format("{}", nan));
1301 EXPECT_EQ("+nan", fmt::format("{:+}", nan));
1302 EXPECT_EQ(" +nan", fmt::format("{:+06}", nan));
1303 EXPECT_EQ("+nan ", fmt::format("{:<+06}", nan));
1304 EXPECT_EQ(" +nan ", fmt::format("{:^+06}", nan));
1305 EXPECT_EQ(" +nan", fmt::format("{:>+06}", nan));
1306 if (std::signbit(-nan)) {
1307 EXPECT_EQ("-nan", fmt::format("{}", -nan));
1308 EXPECT_EQ(" -nan", fmt::format("{:+06}", -nan));
1309 } else {
1310 fmt::print("Warning: compiler doesn't handle negative NaN correctly");
1311 }
1312 EXPECT_EQ(" nan", fmt::format("{: }", nan));
1313 EXPECT_EQ("NAN", fmt::format("{:F}", nan));
1314 EXPECT_EQ("nan ", fmt::format("{:<7}", nan));
1315 EXPECT_EQ(" nan ", fmt::format("{:^7}", nan));
1316 EXPECT_EQ(" nan", fmt::format("{:>7}", nan));
1317 }
1318
1319 TEST(format_test, format_infinity) {
1320 double inf = std::numeric_limits<double>::infinity();
1321 EXPECT_EQ("inf", fmt::format("{}", inf));
1322 EXPECT_EQ("+inf", fmt::format("{:+}", inf));
1323 EXPECT_EQ("-inf", fmt::format("{}", -inf));
1324 EXPECT_EQ(" +inf", fmt::format("{:+06}", inf));
1325 EXPECT_EQ(" -inf", fmt::format("{:+06}", -inf));
1326 EXPECT_EQ("+inf ", fmt::format("{:<+06}", inf));
1327 EXPECT_EQ(" +inf ", fmt::format("{:^+06}", inf));
1328 EXPECT_EQ(" +inf", fmt::format("{:>+06}", inf));
1329 EXPECT_EQ(" inf", fmt::format("{: }", inf));
1330 EXPECT_EQ("INF", fmt::format("{:F}", inf));
1331 EXPECT_EQ("inf ", fmt::format("{:<7}", inf));
1332 EXPECT_EQ(" inf ", fmt::format("{:^7}", inf));
1333 EXPECT_EQ(" inf", fmt::format("{:>7}", inf));
1334 }
1335
1336 TEST(format_test, format_long_double) {
1337 EXPECT_EQ("0", fmt::format("{0:}", 0.0l));
1338 EXPECT_EQ("0.000000", fmt::format("{0:f}", 0.0l));
1339 EXPECT_EQ("392.65", fmt::format("{0:}", 392.65l));
1340 EXPECT_EQ("392.65", fmt::format("{0:g}", 392.65l));
1341 EXPECT_EQ("392.65", fmt::format("{0:G}", 392.65l));
1342 EXPECT_EQ("392.650000", fmt::format("{0:f}", 392.65l));
1343 EXPECT_EQ("392.650000", fmt::format("{0:F}", 392.65l));
1344 char buffer[buffer_size];
1345 safe_sprintf(buffer, "%Le", 392.65l);
1346 EXPECT_EQ(buffer, fmt::format("{0:e}", 392.65l));
1347 EXPECT_EQ("+0000392.6", fmt::format("{0:+010.4g}", 392.64l));
1348 safe_sprintf(buffer, "%La", 3.31l);
1349 EXPECT_EQ(buffer, fmt::format("{:a}", 3.31l));
1350 }
1351
1352 TEST(format_test, format_char) {
1353 const char types[] = "cbBdoxX";
1354 check_unknown_types('a', types, "char");
1355 EXPECT_EQ("a", fmt::format("{0}", 'a'));
1356 EXPECT_EQ("z", fmt::format("{0:c}", 'z'));
1357 int n = 'x';
1358 for (const char* type = types + 1; *type; ++type) {
1359 std::string format_str = fmt::format("{{:{}}}", *type);
1360 EXPECT_EQ(fmt::format(runtime(format_str), n),
1361 fmt::format(runtime(format_str), 'x'))
1362 << format_str;
1363 }
1364 EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x'));
1365 }
1366
1367 TEST(format_test, format_volatile_char) {
1368 volatile char c = 'x';
1369 EXPECT_EQ("x", fmt::format("{}", c));
1370 }
1371
1372 TEST(format_test, format_unsigned_char) {
1373 EXPECT_EQ("42", fmt::format("{}", static_cast<unsigned char>(42)));
1374 EXPECT_EQ("42", fmt::format("{}", static_cast<uint8_t>(42)));
1375 }
1376
1377 TEST(format_test, format_cstring) {
1378 check_unknown_types("test", "sp", "string");
1379 EXPECT_EQ("test", fmt::format("{0}", "test"));
1380 EXPECT_EQ("test", fmt::format("{0:s}", "test"));
1381 char nonconst[] = "nonconst";
1382 EXPECT_EQ("nonconst", fmt::format("{0}", nonconst));
1383 EXPECT_THROW_MSG(
1384 (void)fmt::format(runtime("{0}"), static_cast<const char*>(nullptr)),
1385 format_error, "string pointer is null");
1386 }
1387
1388 void function_pointer_test(int, double, std::string) {}
1389
1390 TEST(format_test, format_pointer) {
1391 check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer");
1392 EXPECT_EQ("0x0", fmt::format("{0}", static_cast<void*>(nullptr)));
1393 EXPECT_EQ("0x1234", fmt::format("{0}", reinterpret_cast<void*>(0x1234)));
1394 EXPECT_EQ("0x1234", fmt::format("{0:p}", reinterpret_cast<void*>(0x1234)));
1395 EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'),
1396 fmt::format("{0}", reinterpret_cast<void*>(~uintptr_t())));
1397 EXPECT_EQ("0x1234",
1398 fmt::format("{}", fmt::ptr(reinterpret_cast<int*>(0x1234))));
1399 std::unique_ptr<int> up(new int(1));
1400 EXPECT_EQ(fmt::format("{}", fmt::ptr(up.get())),
1401 fmt::format("{}", fmt::ptr(up)));
1402 std::shared_ptr<int> sp(new int(1));
1403 EXPECT_EQ(fmt::format("{}", fmt::ptr(sp.get())),
1404 fmt::format("{}", fmt::ptr(sp)));
1405 EXPECT_EQ(fmt::format("{}", fmt::detail::bit_cast<const void*>(
1406 &function_pointer_test)),
1407 fmt::format("{}", fmt::ptr(function_pointer_test)));
1408 EXPECT_EQ("0x0", fmt::format("{}", nullptr));
1409 }
1410
1411 TEST(format_test, format_string) {
1412 EXPECT_EQ("test", fmt::format("{0}", std::string("test")));
1413 EXPECT_THROW((void)fmt::format(fmt::runtime("{:x}"), std::string("test")),
1414 fmt::format_error);
1415 }
1416
1417 TEST(format_test, format_string_view) {
1418 EXPECT_EQ("test", fmt::format("{}", string_view("test")));
1419 EXPECT_EQ("", fmt::format("{}", string_view()));
1420 }
1421
1422 #ifdef FMT_USE_STRING_VIEW
1423 struct string_viewable {};
1424
1425 FMT_BEGIN_NAMESPACE
1426 template <> struct formatter<string_viewable> : formatter<std::string_view> {
1427 auto format(string_viewable, format_context& ctx) -> decltype(ctx.out()) {
1428 return formatter<std::string_view>::format("foo", ctx);
1429 }
1430 };
1431 FMT_END_NAMESPACE
1432
1433 TEST(format_test, format_std_string_view) {
1434 EXPECT_EQ("test", fmt::format("{}", std::string_view("test")));
1435 EXPECT_EQ("foo", fmt::format("{}", string_viewable()));
1436 }
1437
1438 struct explicitly_convertible_to_std_string_view {
1439 explicit operator std::string_view() const { return "foo"; }
1440 };
1441
1442 template <>
1443 struct fmt::formatter<explicitly_convertible_to_std_string_view>
1444 : formatter<std::string_view> {
1445 auto format(explicitly_convertible_to_std_string_view v, format_context& ctx)
1446 -> decltype(ctx.out()) {
1447 return format_to(ctx.out(), "'{}'", std::string_view(v));
1448 }
1449 };
1450
1451 TEST(format_test, format_explicitly_convertible_to_std_string_view) {
1452 EXPECT_EQ("'foo'",
1453 fmt::format("{}", explicitly_convertible_to_std_string_view()));
1454 }
1455 #endif
1456
1457 struct converible_to_anything {
1458 template <typename T> operator T() const { return T(); }
1459 };
1460
1461 FMT_BEGIN_NAMESPACE
1462 template <> struct formatter<converible_to_anything> {
1463 FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
1464 return ctx.begin();
1465 }
1466
1467 auto format(converible_to_anything, format_context& ctx)
1468 -> decltype(ctx.out()) {
1469 return format_to(ctx.out(), "foo");
1470 }
1471 };
1472 FMT_END_NAMESPACE
1473
1474 TEST(format_test, format_convertible_to_anything) {
1475 EXPECT_EQ("foo", fmt::format("{}", converible_to_anything()));
1476 }
1477
1478 class Answer {};
1479
1480 FMT_BEGIN_NAMESPACE
1481 template <> struct formatter<date> {
1482 template <typename ParseContext>
1483 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
1484 auto it = ctx.begin();
1485 if (it != ctx.end() && *it == 'd') ++it;
1486 return it;
1487 }
1488
1489 auto format(const date& d, format_context& ctx) -> decltype(ctx.out()) {
1490 format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day());
1491 return ctx.out();
1492 }
1493 };
1494
1495 template <> struct formatter<Answer> : formatter<int> {
1496 template <typename FormatContext>
1497 auto format(Answer, FormatContext& ctx) -> decltype(ctx.out()) {
1498 return formatter<int>::format(42, ctx);
1499 }
1500 };
1501 FMT_END_NAMESPACE
1502
1503 TEST(format_test, format_custom) {
1504 EXPECT_THROW_MSG((void)fmt::format(runtime("{:s}"), date(2012, 12, 9)),
1505 format_error, "unknown format specifier");
1506 EXPECT_EQ("42", fmt::format("{0}", Answer()));
1507 EXPECT_EQ("0042", fmt::format("{:04}", Answer()));
1508 }
1509
1510 TEST(format_test, format_to_custom) {
1511 char buf[10] = {};
1512 auto end =
1513 &*fmt::format_to(fmt::detail::make_checked(buf, 10), "{}", Answer());
1514 EXPECT_EQ(end, buf + 2);
1515 EXPECT_STREQ(buf, "42");
1516 }
1517
1518 TEST(format_test, format_string_from_speed_test) {
1519 EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%",
1520 fmt::format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42,
1521 3.13, "str", reinterpret_cast<void*>(1000), 'X'));
1522 }
1523
1524 TEST(format_test, format_examples) {
1525 std::string message = fmt::format("The answer is {}", 42);
1526 EXPECT_EQ("The answer is 42", message);
1527
1528 EXPECT_EQ("42", fmt::format("{}", 42));
1529
1530 memory_buffer out;
1531 format_to(std::back_inserter(out), "The answer is {}.", 42);
1532 EXPECT_EQ("The answer is 42.", to_string(out));
1533
1534 const char* filename = "nonexistent";
1535 FILE* ftest = safe_fopen(filename, "r");
1536 if (ftest) fclose(ftest);
1537 int error_code = errno;
1538 EXPECT_TRUE(ftest == nullptr);
1539 EXPECT_SYSTEM_ERROR(
1540 {
1541 FILE* f = safe_fopen(filename, "r");
1542 if (!f)
1543 throw fmt::system_error(errno, "Cannot open file '{}'", filename);
1544 fclose(f);
1545 },
1546 error_code, "Cannot open file 'nonexistent'");
1547
1548 EXPECT_EQ("First, thou shalt count to three",
1549 fmt::format("First, thou shalt count to {0}", "three"));
1550 EXPECT_EQ("Bring me a shrubbery", fmt::format("Bring me a {}", "shrubbery"));
1551 EXPECT_EQ("From 1 to 3", fmt::format("From {} to {}", 1, 3));
1552
1553 char buffer[buffer_size];
1554 safe_sprintf(buffer, "%03.2f", -1.2);
1555 EXPECT_EQ(buffer, fmt::format("{:03.2f}", -1.2));
1556
1557 EXPECT_EQ("a, b, c", fmt::format("{0}, {1}, {2}", 'a', 'b', 'c'));
1558 EXPECT_EQ("a, b, c", fmt::format("{}, {}, {}", 'a', 'b', 'c'));
1559 EXPECT_EQ("c, b, a", fmt::format("{2}, {1}, {0}", 'a', 'b', 'c'));
1560 EXPECT_EQ("abracadabra", fmt::format("{0}{1}{0}", "abra", "cad"));
1561
1562 EXPECT_EQ("left aligned ",
1563 fmt::format("{:<30}", "left aligned"));
1564 EXPECT_EQ(" right aligned",
1565 fmt::format("{:>30}", "right aligned"));
1566 EXPECT_EQ(" centered ",
1567 fmt::format("{:^30}", "centered"));
1568 EXPECT_EQ("***********centered***********",
1569 fmt::format("{:*^30}", "centered"));
1570
1571 EXPECT_EQ("+3.140000; -3.140000", fmt::format("{:+f}; {:+f}", 3.14, -3.14));
1572 EXPECT_EQ(" 3.140000; -3.140000", fmt::format("{: f}; {: f}", 3.14, -3.14));
1573 EXPECT_EQ("3.140000; -3.140000", fmt::format("{:-f}; {:-f}", 3.14, -3.14));
1574
1575 EXPECT_EQ("int: 42; hex: 2a; oct: 52",
1576 fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42));
1577 EXPECT_EQ("int: 42; hex: 0x2a; oct: 052",
1578 fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42));
1579
1580 EXPECT_EQ("The answer is 42", fmt::format("The answer is {}", 42));
1581 EXPECT_THROW_MSG(
1582 (void)fmt::format(runtime("The answer is {:d}"), "forty-two"),
1583 format_error, "invalid type specifier");
1584
1585 EXPECT_WRITE(
1586 stdout, fmt::print("{}", std::numeric_limits<double>::infinity()), "inf");
1587 }
1588
1589 TEST(format_test, print) {
1590 EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!");
1591 EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"),
1592 "Don't panic!");
1593 }
1594
1595 TEST(format_test, variadic) {
1596 EXPECT_EQ("abc1", fmt::format("{}c{}", "ab", 1));
1597 }
1598
1599 TEST(format_test, dynamic) {
1600 using ctx = fmt::format_context;
1601 auto args = std::vector<fmt::basic_format_arg<ctx>>();
1602 args.emplace_back(fmt::detail::make_arg<ctx>(42));
1603 args.emplace_back(fmt::detail::make_arg<ctx>("abc1"));
1604 args.emplace_back(fmt::detail::make_arg<ctx>(1.5f));
1605
1606 std::string result = fmt::vformat(
1607 "{} and {} and {}",
1608 fmt::format_args(args.data(), static_cast<int>(args.size())));
1609
1610 EXPECT_EQ("42 and abc1 and 1.5", result);
1611 }
1612
1613 TEST(format_test, bytes) {
1614 auto s = fmt::format("{:10}", fmt::bytes("ёжик"));
1615 EXPECT_EQ("ёжик ", s);
1616 EXPECT_EQ(10, s.size());
1617 }
1618
1619 TEST(format_test, group_digits_view) {
1620 EXPECT_EQ(fmt::format("{}", fmt::group_digits(10000000)), "10,000,000");
1621 EXPECT_EQ(fmt::format("{:8}", fmt::group_digits(1000)), " 1,000");
1622 }
1623
1624 enum test_enum { foo, bar };
1625
1626 TEST(format_test, join) {
1627 using fmt::join;
1628 int v1[3] = {1, 2, 3};
1629 auto v2 = std::vector<float>();
1630 v2.push_back(1.2f);
1631 v2.push_back(3.4f);
1632 void* v3[2] = {&v1[0], &v1[1]};
1633
1634 EXPECT_EQ("(1, 2, 3)", fmt::format("({})", join(v1, v1 + 3, ", ")));
1635 EXPECT_EQ("(1)", fmt::format("({})", join(v1, v1 + 1, ", ")));
1636 EXPECT_EQ("()", fmt::format("({})", join(v1, v1, ", ")));
1637 EXPECT_EQ("(001, 002, 003)", fmt::format("({:03})", join(v1, v1 + 3, ", ")));
1638 EXPECT_EQ("(+01.20, +03.40)",
1639 fmt::format("({:+06.2f})", join(v2.begin(), v2.end(), ", ")));
1640
1641 EXPECT_EQ("1, 2, 3", fmt::format("{0:{1}}", join(v1, v1 + 3, ", "), 1));
1642
1643 EXPECT_EQ(fmt::format("{}, {}", v3[0], v3[1]),
1644 fmt::format("{}", join(v3, v3 + 2, ", ")));
1645
1646 EXPECT_EQ("(1, 2, 3)", fmt::format("({})", join(v1, ", ")));
1647 EXPECT_EQ("(+01.20, +03.40)", fmt::format("({:+06.2f})", join(v2, ", ")));
1648
1649 auto v4 = std::vector<test_enum>{foo, bar, foo};
1650 EXPECT_EQ("0 1 0", fmt::format("{}", join(v4, " ")));
1651 }
1652
1653 #ifdef __cpp_lib_byte
1654 TEST(format_test, join_bytes) {
1655 auto v = std::vector<std::byte>{std::byte(1), std::byte(2), std::byte(3)};
1656 EXPECT_EQ("1, 2, 3", fmt::format("{}", fmt::join(v, ", ")));
1657 }
1658 #endif
1659
1660 std::string vformat_message(int id, const char* format, fmt::format_args args) {
1661 auto buffer = fmt::memory_buffer();
1662 format_to(fmt::appender(buffer), "[{}] ", id);
1663 vformat_to(fmt::appender(buffer), format, args);
1664 return to_string(buffer);
1665 }
1666
1667 template <typename... Args>
1668 std::string format_message(int id, const char* format, const Args&... args) {
1669 auto va = fmt::make_format_args(args...);
1670 return vformat_message(id, format, va);
1671 }
1672
1673 TEST(format_test, format_message_example) {
1674 EXPECT_EQ("[42] something happened",
1675 format_message(42, "{} happened", "something"));
1676 }
1677
1678 template <typename... Args>
1679 void print_error(const char* file, int line, const char* format,
1680 const Args&... args) {
1681 fmt::print("{}: {}: ", file, line);
1682 fmt::print(format, args...);
1683 }
1684
1685 TEST(format_test, unpacked_args) {
1686 EXPECT_EQ("0123456789abcdefg",
1687 fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5,
1688 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g'));
1689 }
1690
1691 struct string_like {};
1692 fmt::string_view to_string_view(string_like) { return "foo"; }
1693
1694 constexpr char with_null[3] = {'{', '}', '\0'};
1695 constexpr char no_null[2] = {'{', '}'};
1696 static FMT_CONSTEXPR_DECL const char static_with_null[3] = {'{', '}', '\0'};
1697 static FMT_CONSTEXPR_DECL const char static_no_null[2] = {'{', '}'};
1698
1699 TEST(format_test, compile_time_string) {
1700 EXPECT_EQ("foo", fmt::format(FMT_STRING("foo")));
1701 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), 42));
1702 EXPECT_EQ("foo", fmt::format(FMT_STRING("{}"), string_like()));
1703
1704 #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
1705 using namespace fmt::literals;
1706 EXPECT_EQ("foobar", fmt::format(FMT_STRING("{foo}{bar}"), "bar"_a = "bar",
1707 "foo"_a = "foo"));
1708 EXPECT_EQ("", fmt::format(FMT_STRING("")));
1709 EXPECT_EQ("", fmt::format(FMT_STRING(""), "arg"_a = 42));
1710 #endif
1711
1712 (void)static_with_null;
1713 (void)static_no_null;
1714 #ifndef _MSC_VER
1715 EXPECT_EQ("42", fmt::format(FMT_STRING(static_with_null), 42));
1716 EXPECT_EQ("42", fmt::format(FMT_STRING(static_no_null), 42));
1717 #endif
1718
1719 (void)with_null;
1720 (void)no_null;
1721 #if __cplusplus >= 201703L
1722 EXPECT_EQ("42", fmt::format(FMT_STRING(with_null), 42));
1723 EXPECT_EQ("42", fmt::format(FMT_STRING(no_null), 42));
1724 #endif
1725 #if defined(FMT_USE_STRING_VIEW) && __cplusplus >= 201703L
1726 EXPECT_EQ("42", fmt::format(FMT_STRING(std::string_view("{}")), 42));
1727 #endif
1728 }
1729
1730 TEST(format_test, custom_format_compile_time_string) {
1731 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), Answer()));
1732 auto answer = Answer();
1733 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), answer));
1734 char buf[10] = {};
1735 fmt::format_to(buf, FMT_STRING("{}"), answer);
1736 const Answer const_answer = Answer();
1737 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), const_answer));
1738 }
1739
1740 #if FMT_USE_USER_DEFINED_LITERALS
1741 // Passing user-defined literals directly to EXPECT_EQ causes problems
1742 // with macro argument stringification (#) on some versions of GCC.
1743 // Workaround: Assing the UDL result to a variable before the macro.
1744
1745 using namespace fmt::literals;
1746
1747 # if FMT_GCC_VERSION
1748 # define FMT_CHECK_DEPRECATED_UDL_FORMAT 1
1749 # elif FMT_CLANG_VERSION && defined(__has_warning)
1750 # if __has_warning("-Wdeprecated-declarations")
1751 # define FMT_CHECK_DEPRECATED_UDL_FORMAT 1
1752 # endif
1753 # endif
1754 # ifndef FMT_CHECK_DEPRECATED_UDL_FORMAT
1755 # define FMT_CHECK_DEPRECATED_UDL_FORMAT 0
1756 # endif
1757
1758 # if FMT_CHECK_DEPRECATED_UDL_FORMAT
1759 # pragma GCC diagnostic push
1760 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
1761
1762 TEST(format_test, format_udl) {
1763 EXPECT_EQ("{}c{}"_format("ab", 1), fmt::format("{}c{}", "ab", 1));
1764 EXPECT_EQ("foo"_format(), "foo");
1765 EXPECT_EQ("{0:10}"_format(42), " 42");
1766 EXPECT_EQ("{}"_format(date(2015, 10, 21)), "2015-10-21");
1767 }
1768
1769 # pragma GCC diagnostic pop
1770 # endif
1771
1772 TEST(format_test, named_arg_udl) {
1773 auto udl_a = fmt::format("{first}{second}{first}{third}", "first"_a = "abra",
1774 "second"_a = "cad", "third"_a = 99);
1775 EXPECT_EQ(
1776 fmt::format("{first}{second}{first}{third}", fmt::arg("first", "abra"),
1777 fmt::arg("second", "cad"), fmt::arg("third", 99)),
1778 udl_a);
1779 }
1780 #endif // FMT_USE_USER_DEFINED_LITERALS
1781
1782 TEST(format_test, enum) { EXPECT_EQ("0", fmt::format("{}", foo)); }
1783
1784 TEST(format_test, formatter_not_specialized) {
1785 static_assert(!fmt::has_formatter<fmt::formatter<test_enum>,
1786 fmt::format_context>::value,
1787 "");
1788 }
1789
1790 #if FMT_HAS_FEATURE(cxx_strong_enums)
1791 enum big_enum : unsigned long long { big_enum_value = 5000000000ULL };
1792
1793 TEST(format_test, strong_enum) {
1794 EXPECT_EQ("5000000000", fmt::format("{}", big_enum_value));
1795 }
1796 #endif
1797
1798 TEST(format_test, non_null_terminated_format_string) {
1799 EXPECT_EQ("42", fmt::format(string_view("{}foo", 2), 42));
1800 }
1801
1802 struct variant {
1803 enum { int_type, string_type } type;
1804 explicit variant(int) : type(int_type) {}
1805 explicit variant(const char*) : type(string_type) {}
1806 };
1807
1808 FMT_BEGIN_NAMESPACE
1809 template <> struct formatter<variant> : dynamic_formatter<> {
1810 auto format(variant value, format_context& ctx) -> decltype(ctx.out()) {
1811 if (value.type == variant::int_type)
1812 return dynamic_formatter<>::format(42, ctx);
1813 return dynamic_formatter<>::format("foo", ctx);
1814 }
1815 };
1816 FMT_END_NAMESPACE
1817
1818 TEST(format_test, dynamic_formatter) {
1819 auto num = variant(42);
1820 auto str = variant("foo");
1821 EXPECT_EQ("42", fmt::format("{:d}", num));
1822 EXPECT_EQ("foo", fmt::format("{:s}", str));
1823 EXPECT_EQ(" 42 foo ", fmt::format("{:{}} {:{}}", num, 3, str, 4));
1824 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{}}"), num), format_error,
1825 "cannot switch from manual to automatic argument indexing");
1826 EXPECT_THROW_MSG((void)fmt::format(runtime("{:{0}}"), num), format_error,
1827 "cannot switch from automatic to manual argument indexing");
1828 EXPECT_THROW_MSG((void)fmt::format(runtime("{:+}"), str), format_error,
1829 "format specifier requires numeric argument");
1830 EXPECT_THROW_MSG((void)fmt::format(runtime("{:-}"), str), format_error,
1831 "format specifier requires numeric argument");
1832 EXPECT_THROW_MSG((void)fmt::format(runtime("{: }"), str), format_error,
1833 "format specifier requires numeric argument");
1834 EXPECT_THROW_MSG((void)fmt::format(runtime("{:#}"), str), format_error,
1835 "format specifier requires numeric argument");
1836 EXPECT_THROW_MSG((void)fmt::format(runtime("{:0}"), str), format_error,
1837 "format specifier requires numeric argument");
1838 EXPECT_THROW_MSG((void)fmt::format(runtime("{:.2}"), num), format_error,
1839 "precision not allowed for this argument type");
1840 }
1841
1842 namespace adl_test {
1843 namespace fmt {
1844 namespace detail {
1845 struct foo {};
1846 template <typename, typename OutputIt> void write(OutputIt, foo) = delete;
1847 } // namespace detail
1848 } // namespace fmt
1849 } // namespace adl_test
1850
1851 FMT_BEGIN_NAMESPACE
1852 template <>
1853 struct formatter<adl_test::fmt::detail::foo> : formatter<std::string> {
1854 template <typename FormatContext>
1855 auto format(adl_test::fmt::detail::foo, FormatContext& ctx)
1856 -> decltype(ctx.out()) {
1857 return formatter<std::string>::format("foo", ctx);
1858 }
1859 };
1860 FMT_END_NAMESPACE
1861
1862 struct convertible_to_int {
1863 operator int() const { return value; }
1864
1865 int value = 42;
1866 };
1867
1868 TEST(format_test, to_string) {
1869 EXPECT_EQ(fmt::to_string(42), "42");
1870 EXPECT_EQ(fmt::to_string(reinterpret_cast<void*>(0x1234)), "0x1234");
1871 EXPECT_EQ(fmt::to_string(adl_test::fmt::detail::foo()), "foo");
1872 EXPECT_EQ(fmt::to_string(convertible_to_int()), "42");
1873
1874 enum foo : unsigned char { zero };
1875 EXPECT_EQ(fmt::to_string(zero), "0");
1876 }
1877
1878 TEST(format_test, output_iterators) {
1879 std::list<char> out;
1880 fmt::format_to(std::back_inserter(out), "{}", 42);
1881 EXPECT_EQ("42", std::string(out.begin(), out.end()));
1882 std::stringstream s;
1883 fmt::format_to(std::ostream_iterator<char>(s), "{}", 42);
1884 EXPECT_EQ("42", s.str());
1885 }
1886
1887 TEST(format_test, formatted_size) {
1888 EXPECT_EQ(2u, fmt::formatted_size("{}", 42));
1889 }
1890
1891 TEST(format_test, format_to_no_args) {
1892 std::string s;
1893 fmt::format_to(std::back_inserter(s), "test");
1894 EXPECT_EQ("test", s);
1895 }
1896
1897 TEST(format_test, format_to) {
1898 std::string s;
1899 fmt::format_to(std::back_inserter(s), "part{0}", 1);
1900 EXPECT_EQ("part1", s);
1901 fmt::format_to(std::back_inserter(s), "part{0}", 2);
1902 EXPECT_EQ("part1part2", s);
1903 }
1904
1905 TEST(format_test, format_to_memory_buffer) {
1906 auto buf = fmt::basic_memory_buffer<char, 100>();
1907 fmt::format_to(fmt::appender(buf), "{}", "foo");
1908 EXPECT_EQ("foo", to_string(buf));
1909 }
1910
1911 TEST(format_test, format_to_vector) {
1912 std::vector<char> v;
1913 fmt::format_to(std::back_inserter(v), "{}", "foo");
1914 EXPECT_EQ(string_view(v.data(), v.size()), "foo");
1915 }
1916
1917 struct nongrowing_container {
1918 using value_type = char;
1919 void push_back(char) { throw std::runtime_error("can't take it any more"); }
1920 };
1921
1922 TEST(format_test, format_to_propagates_exceptions) {
1923 auto c = nongrowing_container();
1924 EXPECT_THROW(fmt::format_to(std::back_inserter(c), "{}", 42),
1925 std::runtime_error);
1926 }
1927
1928 TEST(format_test, format_to_n) {
1929 char buffer[4];
1930 buffer[3] = 'x';
1931 auto result = fmt::format_to_n(buffer, 3, "{}", 12345);
1932 EXPECT_EQ(5u, result.size);
1933 EXPECT_EQ(buffer + 3, result.out);
1934 EXPECT_EQ("123x", fmt::string_view(buffer, 4));
1935
1936 result = fmt::format_to_n(buffer, 3, "{:s}", "foobar");
1937 EXPECT_EQ(6u, result.size);
1938 EXPECT_EQ(buffer + 3, result.out);
1939 EXPECT_EQ("foox", fmt::string_view(buffer, 4));
1940
1941 buffer[0] = 'x';
1942 buffer[1] = 'x';
1943 buffer[2] = 'x';
1944 result = fmt::format_to_n(buffer, 3, "{}", 'A');
1945 EXPECT_EQ(1u, result.size);
1946 EXPECT_EQ(buffer + 1, result.out);
1947 EXPECT_EQ("Axxx", fmt::string_view(buffer, 4));
1948
1949 result = fmt::format_to_n(buffer, 3, "{}{} ", 'B', 'C');
1950 EXPECT_EQ(3u, result.size);
1951 EXPECT_EQ(buffer + 3, result.out);
1952 EXPECT_EQ("BC x", fmt::string_view(buffer, 4));
1953
1954 result = fmt::format_to_n(buffer, 4, "{}", "ABCDE");
1955 EXPECT_EQ(5u, result.size);
1956 EXPECT_EQ("ABCD", fmt::string_view(buffer, 4));
1957
1958 buffer[3] = 'x';
1959 result = fmt::format_to_n(buffer, 3, "{}", std::string(1000, '*'));
1960 EXPECT_EQ(1000u, result.size);
1961 EXPECT_EQ("***x", fmt::string_view(buffer, 4));
1962 }
1963
1964 struct test_output_iterator {
1965 char* data;
1966
1967 using iterator_category = std::output_iterator_tag;
1968 using value_type = void;
1969 using difference_type = void;
1970 using pointer = void;
1971 using reference = void;
1972
1973 test_output_iterator& operator++() {
1974 ++data;
1975 return *this;
1976 }
1977 test_output_iterator operator++(int) {
1978 auto tmp = *this;
1979 ++data;
1980 return tmp;
1981 }
1982 char& operator*() { return *data; }
1983 };
1984
1985 TEST(format_test, format_to_n_output_iterator) {
1986 char buf[10] = {};
1987 fmt::format_to_n(test_output_iterator{buf}, 10, "{}", 42);
1988 EXPECT_STREQ(buf, "42");
1989 }
1990
1991 #if FMT_USE_CONSTEXPR
1992 struct test_error_handler {
1993 const char*& error;
1994
1995 FMT_CONSTEXPR test_error_handler(const char*& err) : error(err) {}
1996
1997 FMT_CONSTEXPR test_error_handler(const test_error_handler& other)
1998 : error(other.error) {}
1999
2000 FMT_CONSTEXPR void on_error(const char* message) {
2001 if (!error) error = message;
2002 }
2003 };
2004
2005 FMT_CONSTEXPR size_t len(const char* s) {
2006 size_t len = 0;
2007 while (*s++) ++len;
2008 return len;
2009 }
2010
2011 FMT_CONSTEXPR bool equal(const char* s1, const char* s2) {
2012 if (!s1 || !s2) return s1 == s2;
2013 while (*s1 && *s1 == *s2) {
2014 ++s1;
2015 ++s2;
2016 }
2017 return *s1 == *s2;
2018 }
2019
2020 template <typename... Args>
2021 FMT_CONSTEXPR bool test_error(const char* fmt, const char* expected_error) {
2022 const char* actual_error = nullptr;
2023 auto s = string_view(fmt, len(fmt));
2024 auto checker =
2025 fmt::detail::format_string_checker<char, test_error_handler, Args...>(
2026 s, test_error_handler(actual_error));
2027 fmt::detail::parse_format_string<true>(s, checker);
2028 return equal(actual_error, expected_error);
2029 }
2030
2031 # define EXPECT_ERROR_NOARGS(fmt, error) \
2032 static_assert(test_error(fmt, error), "")
2033 # define EXPECT_ERROR(fmt, error, ...) \
2034 static_assert(test_error<__VA_ARGS__>(fmt, error), "")
2035
2036 TEST(format_test, format_string_errors) {
2037 EXPECT_ERROR_NOARGS("foo", nullptr);
2038 EXPECT_ERROR_NOARGS("}", "unmatched '}' in format string");
2039 EXPECT_ERROR("{0:s", "unknown format specifier", date);
2040 # if !FMT_MSC_VER || FMT_MSC_VER >= 1916
2041 // This causes an detail compiler error in MSVC2017.
2042 EXPECT_ERROR("{:{<}", "invalid fill character '{'", int);
2043 EXPECT_ERROR("{:10000000000}", "number is too big", int);
2044 EXPECT_ERROR("{:.10000000000}", "number is too big", int);
2045 EXPECT_ERROR_NOARGS("{:x}", "argument not found");
2046 EXPECT_ERROR("{:+}", "format specifier requires numeric argument",
2047 const char*);
2048 EXPECT_ERROR("{:-}", "format specifier requires numeric argument",
2049 const char*);
2050 EXPECT_ERROR("{:#}", "format specifier requires numeric argument",
2051 const char*);
2052 EXPECT_ERROR("{: }", "format specifier requires numeric argument",
2053 const char*);
2054 EXPECT_ERROR("{:0}", "format specifier requires numeric argument",
2055 const char*);
2056 EXPECT_ERROR("{:+}", "format specifier requires signed argument", unsigned);
2057 EXPECT_ERROR("{:-}", "format specifier requires signed argument", unsigned);
2058 EXPECT_ERROR("{: }", "format specifier requires signed argument", unsigned);
2059 EXPECT_ERROR("{:{}}", "argument not found", int);
2060 EXPECT_ERROR("{:.{}}", "argument not found", double);
2061 EXPECT_ERROR("{:.2}", "precision not allowed for this argument type", int);
2062 EXPECT_ERROR("{:s}", "invalid type specifier", int);
2063 EXPECT_ERROR("{:s}", "invalid type specifier", char);
2064 EXPECT_ERROR("{:+}", "invalid format specifier for char", char);
2065 EXPECT_ERROR("{:s}", "invalid type specifier", double);
2066 EXPECT_ERROR("{:d}", "invalid type specifier", const char*);
2067 EXPECT_ERROR("{:d}", "invalid type specifier", std::string);
2068 EXPECT_ERROR("{:s}", "invalid type specifier", void*);
2069 # else
2070 fmt::print("warning: constexpr is broken in this version of MSVC\n");
2071 # endif
2072 # if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
2073 EXPECT_ERROR("{foo}", "named argument is not found", decltype("bar"_a = 42));
2074 EXPECT_ERROR("{foo}", "named argument is not found",
2075 decltype(fmt::arg("foo", 42)));
2076 # else
2077 EXPECT_ERROR("{foo}",
2078 "compile-time checks for named arguments require C++20 support",
2079 int);
2080 # endif
2081 EXPECT_ERROR_NOARGS("{10000000000}", "argument not found");
2082 EXPECT_ERROR_NOARGS("{0x}", "invalid format string");
2083 EXPECT_ERROR_NOARGS("{-}", "invalid format string");
2084 EXPECT_ERROR("{:{0x}}", "invalid format string", int);
2085 EXPECT_ERROR("{:{-}}", "invalid format string", int);
2086 EXPECT_ERROR("{:.{0x}}", "invalid format string", int);
2087 EXPECT_ERROR("{:.{-}}", "invalid format string", int);
2088 EXPECT_ERROR("{:.x}", "missing precision specifier", int);
2089 EXPECT_ERROR_NOARGS("{}", "argument not found");
2090 EXPECT_ERROR("{1}", "argument not found", int);
2091 EXPECT_ERROR("{1}{}",
2092 "cannot switch from manual to automatic argument indexing", int,
2093 int);
2094 EXPECT_ERROR("{}{1}",
2095 "cannot switch from automatic to manual argument indexing", int,
2096 int);
2097 }
2098
2099 TEST(format_test, vformat_to) {
2100 using context = fmt::format_context;
2101 fmt::basic_format_arg<context> arg = fmt::detail::make_arg<context>(42);
2102 auto args = fmt::basic_format_args<context>(&arg, 1);
2103 auto s = std::string();
2104 fmt::vformat_to(std::back_inserter(s), "{}", args);
2105 EXPECT_EQ("42", s);
2106 s.clear();
2107 fmt::vformat_to(std::back_inserter(s), FMT_STRING("{}"), args);
2108 EXPECT_EQ("42", s);
2109 }
2110
2111 #endif // FMT_USE_CONSTEXPR
2112
2113 TEST(format_test, char_traits_is_not_ambiguous) {
2114 // Test that we don't inject detail names into the std namespace.
2115 using namespace std;
2116 auto c = char_traits<char>::char_type();
2117 (void)c;
2118 #if __cplusplus >= 201103L
2119 auto s = std::string();
2120 auto lval = begin(s);
2121 (void)lval;
2122 #endif
2123 }
2124
2125 struct check_back_appender {};
2126
2127 FMT_BEGIN_NAMESPACE
2128 template <> struct formatter<check_back_appender> {
2129 auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
2130 return ctx.begin();
2131 }
2132
2133 template <typename Context>
2134 auto format(check_back_appender, Context& ctx) -> decltype(ctx.out()) {
2135 auto out = ctx.out();
2136 static_assert(std::is_same<decltype(++out), decltype(out)&>::value,
2137 "needs to satisfy weakly_incrementable");
2138 *out = 'y';
2139 return ++out;
2140 }
2141 };
2142 FMT_END_NAMESPACE
2143
2144 TEST(format_test, back_insert_slicing) {
2145 EXPECT_EQ(fmt::format("{}", check_back_appender{}), "y");
2146 }
2147
2148 template <typename Char, typename T> bool check_enabled_formatter() {
2149 static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value,
2150 "");
2151 return true;
2152 }
2153
2154 template <typename Char, typename... T> void check_enabled_formatters() {
2155 auto dummy = {check_enabled_formatter<Char, T>()...};
2156 (void)dummy;
2157 }
2158
2159 TEST(format_test, test_formatters_enabled) {
2160 check_enabled_formatters<char, bool, char, signed char, unsigned char, short,
2161 unsigned short, int, unsigned, long, unsigned long,
2162 long long, unsigned long long, float, double,
2163 long double, void*, const void*, char*, const char*,
2164 std::string, std::nullptr_t>();
2165 check_enabled_formatters<wchar_t, bool, wchar_t, signed char, unsigned char,
2166 short, unsigned short, int, unsigned, long,
2167 unsigned long, long long, unsigned long long, float,
2168 double, long double, void*, const void*, wchar_t*,
2169 const wchar_t*, std::wstring, std::nullptr_t>();
2170 }
2171
2172 TEST(format_int_test, data) {
2173 fmt::format_int format_int(42);
2174 EXPECT_EQ("42", std::string(format_int.data(), format_int.size()));
2175 }
2176
2177 TEST(format_int_test, format_int) {
2178 EXPECT_EQ("42", fmt::format_int(42).str());
2179 EXPECT_EQ(2u, fmt::format_int(42).size());
2180 EXPECT_EQ("-42", fmt::format_int(-42).str());
2181 EXPECT_EQ(3u, fmt::format_int(-42).size());
2182 EXPECT_EQ("42", fmt::format_int(42ul).str());
2183 EXPECT_EQ("-42", fmt::format_int(-42l).str());
2184 EXPECT_EQ("42", fmt::format_int(42ull).str());
2185 EXPECT_EQ("-42", fmt::format_int(-42ll).str());
2186 std::ostringstream os;
2187 os << max_value<int64_t>();
2188 EXPECT_EQ(os.str(), fmt::format_int(max_value<int64_t>()).str());
2189 }
+0
-3
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/.gitignore less more
0 # ignore artifacts from the build.sh script
1 build-*/
2
+0
-30
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/CMakeLists.txt less more
0 # Copyright (c) 2019, Paul Dreik
1 # License: see LICENSE.rst in the fmt root directory
2
3 # Link in the main function. Useful for reproducing, kcov, gdb, afl, valgrind.
4 # (Note that libFuzzer can also reproduce, just pass it the files.)
5 option(FMT_FUZZ_LINKMAIN "Enables the reproduce mode, instead of libFuzzer" On)
6
7 # For oss-fuzz - insert $LIB_FUZZING_ENGINE into the link flags, but only for
8 # the fuzz targets, otherwise the CMake configuration step fails.
9 set(FMT_FUZZ_LDFLAGS "" CACHE STRING "LDFLAGS for the fuzz targets")
10
11 # Adds a binary for reproducing, i.e. no fuzzing, just enables replaying data
12 # through the fuzzers.
13 function(add_fuzzer source)
14 get_filename_component(basename ${source} NAME_WE)
15 set(name ${basename}-fuzzer)
16 add_executable(${name} ${source} fuzzer-common.h)
17 if (FMT_FUZZ_LINKMAIN)
18 target_sources(${name} PRIVATE main.cc)
19 endif ()
20 target_link_libraries(${name} PRIVATE fmt)
21 if (FMT_FUZZ_LDFLAGS)
22 target_link_libraries(${name} PRIVATE ${FMT_FUZZ_LDFLAGS})
23 endif ()
24 target_compile_features(${name} PRIVATE cxx_generic_lambdas)
25 endfunction()
26
27 foreach (source chrono-duration.cc chrono-timepoint.cc float.cc named-arg.cc one-arg.cc two-args.cc)
28 add_fuzzer(${source})
29 endforeach ()
+0
-25
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/README.md less more
0 # Running the fuzzers locally
1
2 There is a [helper script](build.sh) to build the fuzzers, which has only been
3 tested on Debian and Ubuntu linux so far. There should be no problems fuzzing on
4 Windows (using clang>=8) or on Mac, but the script will probably not work out of
5 the box.
6
7 Something along
8 ```sh
9 mkdir build
10 cd build
11 export CXX=clang++
12 export CXXFLAGS="-fsanitize=fuzzer-no-link -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION= -g"
13 cmake .. -DFMT_SAFE_DURATION_CAST=On -DFMT_FUZZ=On -DFMT_FUZZ_LINKMAIN=Off -DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer"
14 cmake --build .
15 ```
16 should work to build the fuzzers for all platforms which clang supports.
17
18 Execute a fuzzer with for instance
19 ```sh
20 cd build
21 export UBSAN_OPTIONS=halt_on_error=1
22 mkdir out_chrono
23 bin/fuzzer_chrono_duration out_chrono
24 ```
+0
-90
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/build.sh less more
0 #!/bin/sh
1 #
2 # Creates fuzzer builds of various kinds
3 # - oss-fuzz emulated mode (makes sure a simulated invocation by oss-fuzz works)
4 # - libFuzzer build (you will need clang)
5 # - afl build (you will need afl)
6 #
7 #
8 # Copyright (c) 2019 Paul Dreik
9 #
10 # For the license information refer to format.h.
11
12 set -e
13 me=$(basename $0)
14 root=$(readlink -f "$(dirname "$0")/../..")
15
16
17 echo $me: root=$root
18
19 here=$(pwd)
20
21 CXXFLAGSALL="-DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION= -g"
22 CMAKEFLAGSALL="$root -GNinja -DCMAKE_BUILD_TYPE=Debug -DFMT_DOC=Off -DFMT_TEST=Off -DFMT_FUZZ=On -DCMAKE_CXX_STANDARD=17"
23
24 CLANG=clang++-11
25
26 # For performance analysis of the fuzzers.
27 builddir=$here/build-fuzzers-perfanalysis
28 mkdir -p $builddir
29 cd $builddir
30 CXX="ccache g++" CXXFLAGS="$CXXFLAGSALL -g" cmake \
31 $CMAKEFLAGSALL \
32 -DFMT_FUZZ_LINKMAIN=On \
33 -DCMAKE_BUILD_TYPE=Release
34
35 cmake --build $builddir
36
37 # Builds the fuzzers as oss-fuzz does.
38 builddir=$here/build-fuzzers-ossfuzz
39 mkdir -p $builddir
40 cd $builddir
41 CXX=$CLANG \
42 CXXFLAGS="$CXXFLAGSALL -fsanitize=fuzzer-no-link" cmake \
43 cmake $CMAKEFLAGSALL \
44 -DFMT_FUZZ_LINKMAIN=Off \
45 -DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer"
46
47 cmake --build $builddir
48
49
50 # Builds fuzzers for local fuzzing with libfuzzer with asan+usan.
51 builddir=$here/build-fuzzers-libfuzzer
52 mkdir -p $builddir
53 cd $builddir
54 CXX=$CLANG \
55 CXXFLAGS="$CXXFLAGSALL -fsanitize=fuzzer-no-link,address,undefined" cmake \
56 cmake $CMAKEFLAGSALL \
57 -DFMT_FUZZ_LINKMAIN=Off \
58 -DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer"
59
60 cmake --build $builddir
61
62 # Builds a fast fuzzer for making coverage fast.
63 builddir=$here/build-fuzzers-fast
64 mkdir -p $builddir
65 cd $builddir
66 CXX=$CLANG \
67 CXXFLAGS="$CXXFLAGSALL -fsanitize=fuzzer-no-link -O3" cmake \
68 cmake $CMAKEFLAGSALL \
69 -DFMT_FUZZ_LINKMAIN=Off \
70 -DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer" \
71 -DCMAKE_BUILD_TYPE=Release
72
73 cmake --build $builddir
74
75
76 # Builds fuzzers for local fuzzing with afl.
77 builddir=$here/build-fuzzers-afl
78 mkdir -p $builddir
79 cd $builddir
80 CXX="afl-g++" \
81 CXXFLAGS="$CXXFLAGSALL -fsanitize=address,undefined" \
82 cmake $CMAKEFLAGSALL \
83 -DFMT_FUZZ_LINKMAIN=On
84
85 cmake --build $builddir
86
87
88 echo $me: all good
89
+0
-136
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/chrono-duration.cc less more
0 // Copyright (c) 2019, Paul Dreik
1 // For the license information refer to format.h.
2
3 #include <fmt/chrono.h>
4
5 #include <cstdint>
6
7 #include "fuzzer-common.h"
8
9 template <typename Period, typename Rep>
10 void invoke_inner(fmt::string_view format_str, Rep rep) {
11 auto value = std::chrono::duration<Rep, Period>(rep);
12 try {
13 #if FMT_FUZZ_FORMAT_TO_STRING
14 std::string message = fmt::format(format_str, value);
15 #else
16 auto buf = fmt::memory_buffer();
17 fmt::format_to(std::back_inserter(buf), format_str, value);
18 #endif
19 } catch (std::exception&) {
20 }
21 }
22
23 // Rep is a duration's representation type.
24 template <typename Rep>
25 void invoke_outer(const uint8_t* data, size_t size, int period) {
26 // Always use a fixed location of the data.
27 static_assert(sizeof(Rep) <= fixed_size, "fixed size is too small");
28 if (size <= fixed_size + 1) return;
29
30 const Rep rep = assign_from_buf<Rep>(data);
31 data += fixed_size;
32 size -= fixed_size;
33
34 // data is already allocated separately in libFuzzer so reading past the end
35 // will most likely be detected anyway.
36 const auto format_str = fmt::string_view(as_chars(data), size);
37
38 // yocto, zepto, zetta and yotta are not handled.
39 switch (period) {
40 case 1:
41 invoke_inner<std::atto>(format_str, rep);
42 break;
43 case 2:
44 invoke_inner<std::femto>(format_str, rep);
45 break;
46 case 3:
47 invoke_inner<std::pico>(format_str, rep);
48 break;
49 case 4:
50 invoke_inner<std::nano>(format_str, rep);
51 break;
52 case 5:
53 invoke_inner<std::micro>(format_str, rep);
54 break;
55 case 6:
56 invoke_inner<std::milli>(format_str, rep);
57 break;
58 case 7:
59 invoke_inner<std::centi>(format_str, rep);
60 break;
61 case 8:
62 invoke_inner<std::deci>(format_str, rep);
63 break;
64 case 9:
65 invoke_inner<std::deca>(format_str, rep);
66 break;
67 case 10:
68 invoke_inner<std::kilo>(format_str, rep);
69 break;
70 case 11:
71 invoke_inner<std::mega>(format_str, rep);
72 break;
73 case 12:
74 invoke_inner<std::giga>(format_str, rep);
75 break;
76 case 13:
77 invoke_inner<std::tera>(format_str, rep);
78 break;
79 case 14:
80 invoke_inner<std::peta>(format_str, rep);
81 break;
82 case 15:
83 invoke_inner<std::exa>(format_str, rep);
84 break;
85 }
86 }
87
88 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
89 if (size <= 4) return 0;
90
91 const auto representation = data[0];
92 const auto period = data[1];
93 data += 2;
94 size -= 2;
95
96 switch (representation) {
97 case 1:
98 invoke_outer<char>(data, size, period);
99 break;
100 case 2:
101 invoke_outer<signed char>(data, size, period);
102 break;
103 case 3:
104 invoke_outer<unsigned char>(data, size, period);
105 break;
106 case 4:
107 invoke_outer<short>(data, size, period);
108 break;
109 case 5:
110 invoke_outer<unsigned short>(data, size, period);
111 break;
112 case 6:
113 invoke_outer<int>(data, size, period);
114 break;
115 case 7:
116 invoke_outer<unsigned int>(data, size, period);
117 break;
118 case 8:
119 invoke_outer<long>(data, size, period);
120 break;
121 case 9:
122 invoke_outer<unsigned long>(data, size, period);
123 break;
124 case 10:
125 invoke_outer<float>(data, size, period);
126 break;
127 case 11:
128 invoke_outer<double>(data, size, period);
129 break;
130 case 12:
131 invoke_outer<long double>(data, size, period);
132 break;
133 }
134 return 0;
135 }
+0
-32
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/chrono-timepoint.cc less more
0 // Copyright (c) 2021, Paul Dreik
1 // For license information refer to format.h.
2 #include <fmt/chrono.h>
3
4 #include "fuzzer-common.h"
5
6 /*
7 * a fuzzer for the chrono timepoints formatters
8 * C is a clock (std::chrono::system_clock etc)
9 */
10 template <typename C> void doit(const uint8_t* data, size_t size) {
11 using Rep = typename C::time_point::rep;
12 constexpr auto N = sizeof(Rep);
13 if (size < N) return;
14
15 const auto x = assign_from_buf<Rep>(data);
16 typename C::duration dur{x};
17 typename C::time_point timepoint{dur};
18 data += N;
19 size -= N;
20 data_to_string format_str(data, size);
21
22 std::string message = fmt::format(format_str.get(), timepoint);
23 }
24
25 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
26 try {
27 doit<std::chrono::system_clock>(data, size);
28 } catch (...) {
29 }
30 return 0;
31 }
+0
-39
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/float.cc less more
0 // A fuzzer for floating-point formatter.
1 // For the license information refer to format.h.
2
3 #include <fmt/format.h>
4
5 #include <cstdint>
6 #include <cstdlib>
7 #include <limits>
8 #include <stdexcept>
9
10 #include "fuzzer-common.h"
11
12 void check_round_trip(fmt::string_view format_str, double value) {
13 auto buffer = fmt::memory_buffer();
14 fmt::format_to(std::back_inserter(buffer), format_str, value);
15
16 if (std::isnan(value)) {
17 auto nan = std::signbit(value) ? "-nan" : "nan";
18 if (fmt::string_view(buffer.data(), buffer.size()) != nan)
19 throw std::runtime_error("round trip failure");
20 return;
21 }
22
23 buffer.push_back('\0');
24 char* ptr = nullptr;
25 if (std::strtod(buffer.data(), &ptr) != value)
26 throw std::runtime_error("round trip failure");
27 if (ptr + 1 != buffer.end()) throw std::runtime_error("unparsed output");
28 }
29
30 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
31 if (size <= sizeof(double) || !std::numeric_limits<double>::is_iec559)
32 return 0;
33 check_round_trip("{}", assign_from_buf<double>(data));
34 // A larger than necessary precision is used to trigger the fallback
35 // formatter.
36 check_round_trip("{:.50g}", assign_from_buf<double>(data));
37 return 0;
38 }
+0
-77
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/fuzzer-common.h less more
0 // Copyright (c) 2019, Paul Dreik
1 // For the license information refer to format.h.
2
3 #ifndef FUZZER_COMMON_H
4 #define FUZZER_COMMON_H
5
6 #include <fmt/core.h>
7
8 #include <cstdint> // std::uint8_t
9 #include <cstring> // memcpy
10 #include <vector>
11
12 // One can format to either a string, or a buffer. The latter is faster, but
13 // one may be interested in formatting to a string instead to verify it works
14 // as intended. To avoid a combinatoric explosion, select this at compile time
15 // instead of dynamically from the fuzz data.
16 #define FMT_FUZZ_FORMAT_TO_STRING 0
17
18 // If {fmt} is given a buffer that is separately allocated, chances that address
19 // sanitizer detects out of bound reads is much higher. However, it slows down
20 // the fuzzing.
21 #define FMT_FUZZ_SEPARATE_ALLOCATION 1
22
23 // The size of the largest possible type in use.
24 // To let the the fuzzer mutation be efficient at cross pollinating between
25 // different types, use a fixed size format. The same bit pattern, interpreted
26 // as another type, is likely interesting.
27 constexpr auto fixed_size = 16;
28
29 // Casts data to a char pointer.
30 template <typename T> inline const char* as_chars(const T* data) {
31 return reinterpret_cast<const char*>(data);
32 }
33
34 // Casts data to a byte pointer.
35 template <typename T> inline const std::uint8_t* as_bytes(const T* data) {
36 return reinterpret_cast<const std::uint8_t*>(data);
37 }
38
39 // Blits bytes from data to form an (assumed trivially constructible) object
40 // of type Item.
41 template <class Item> inline Item assign_from_buf(const std::uint8_t* data) {
42 auto item = Item();
43 std::memcpy(&item, data, sizeof(Item));
44 return item;
45 }
46
47 // Reads a boolean value by looking at the first byte from data.
48 template <> inline bool assign_from_buf<bool>(const std::uint8_t* data) {
49 return *data != 0;
50 }
51
52 struct data_to_string {
53 #if FMT_FUZZ_SEPARATE_ALLOCATION
54 std::vector<char> buffer;
55
56 data_to_string(const uint8_t* data, size_t size, bool add_terminator = false)
57 : buffer(size + (add_terminator ? 1 : 0)) {
58 if (size) {
59 std::memcpy(buffer.data(), data, size);
60 }
61 }
62
63 fmt::string_view get() const { return {buffer.data(), buffer.size()}; }
64 #else
65 fmt::string_view sv;
66
67 data_to_string(const uint8_t* data, size_t size, bool = false)
68 : str(as_chars(data), size) {}
69
70 fmt::string_view get() const { return sv; }
71 #endif
72
73 const char* data() const { return get().data(); }
74 };
75
76 #endif // FUZZER_COMMON_H
+0
-22
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/main.cc less more
0 #include <cassert>
1 #include <fstream>
2 #include <vector>
3
4 #include "fuzzer-common.h"
5
6 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
7
8 int main(int argc, char** argv) {
9 for (int i = 1; i < argc; ++i) {
10 std::ifstream in(argv[i]);
11 assert(in);
12 in.seekg(0, std::ios_base::end);
13 const auto size = in.tellg();
14 assert(size >= 0);
15 in.seekg(0, std::ios_base::beg);
16 std::vector<char> buf(static_cast<size_t>(size));
17 in.read(buf.data(), size);
18 assert(in.gcount() == size);
19 LLVMFuzzerTestOneInput(as_bytes(buf.data()), buf.size());
20 }
21 }
+0
-102
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/named-arg.cc less more
0 // Copyright (c) 2019, Paul Dreik
1 // For the license information refer to format.h.
2
3 #include <fmt/chrono.h>
4
5 #include <cstdint>
6 #include <type_traits>
7 #include <vector>
8
9 #include "fuzzer-common.h"
10
11 template <typename T>
12 void invoke_fmt(const uint8_t* data, size_t size, unsigned arg_name_size) {
13 static_assert(sizeof(T) <= fixed_size, "fixed_size too small");
14 if (size <= fixed_size) return;
15 const T value = assign_from_buf<T>(data);
16 data += fixed_size;
17 size -= fixed_size;
18
19 if (arg_name_size <= 0 || arg_name_size >= size) return;
20 data_to_string arg_name(data, arg_name_size, true);
21 data += arg_name_size;
22 size -= arg_name_size;
23
24 data_to_string format_str(data, size);
25 try {
26 #if FMT_FUZZ_FORMAT_TO_STRING
27 std::string message =
28 fmt::format(format_str.get(), fmt::arg(arg_name.data(), value));
29 #else
30 fmt::memory_buffer out;
31 fmt::format_to(std::back_inserter(out), format_str.get(),
32 fmt::arg(arg_name.data(), value));
33 #endif
34 } catch (std::exception&) {
35 }
36 }
37
38 // For dynamic dispatching to an explicit instantiation.
39 template <typename Callback> void invoke(int type, Callback callback) {
40 switch (type) {
41 case 0:
42 callback(bool());
43 break;
44 case 1:
45 callback(char());
46 break;
47 case 2:
48 using sc = signed char;
49 callback(sc());
50 break;
51 case 3:
52 using uc = unsigned char;
53 callback(uc());
54 break;
55 case 4:
56 callback(short());
57 break;
58 case 5:
59 using us = unsigned short;
60 callback(us());
61 break;
62 case 6:
63 callback(int());
64 break;
65 case 7:
66 callback(unsigned());
67 break;
68 case 8:
69 callback(long());
70 break;
71 case 9:
72 using ul = unsigned long;
73 callback(ul());
74 break;
75 case 10:
76 callback(float());
77 break;
78 case 11:
79 callback(double());
80 break;
81 case 12:
82 using LD = long double;
83 callback(LD());
84 break;
85 }
86 }
87
88 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
89 if (size <= 3) return 0;
90
91 // Switch types depending on the first byte of the input.
92 const auto type = data[0] & 0x0F;
93 const unsigned arg_name_size = (data[0] & 0xF0) >> 4;
94 data++;
95 size--;
96
97 invoke(type, [=](auto arg) {
98 invoke_fmt<decltype(arg)>(data, size, arg_name_size);
99 });
100 return 0;
101 }
+0
-92
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/one-arg.cc less more
0 // Copyright (c) 2019, Paul Dreik
1 // For the license information refer to format.h.
2
3 #include <fmt/chrono.h>
4
5 #include <cstdint>
6 #include <exception>
7
8 #include "fuzzer-common.h"
9
10 template <typename T, typename Repr> const T* from_repr(const Repr& r) {
11 return &r;
12 }
13
14 template <> const std::tm* from_repr<std::tm>(const std::time_t& t) {
15 return std::localtime(&t);
16 }
17
18 template <typename T, typename Repr = T>
19 void invoke_fmt(const uint8_t* data, size_t size) {
20 static_assert(sizeof(Repr) <= fixed_size, "Nfixed is too small");
21 if (size <= fixed_size) return;
22 auto repr = assign_from_buf<Repr>(data);
23 const T* value = from_repr<T>(repr);
24 if (!value) return;
25 data += fixed_size;
26 size -= fixed_size;
27 data_to_string format_str(data, size);
28 try {
29 #if FMT_FUZZ_FORMAT_TO_STRING
30 std::string message = fmt::format(format_str.get(), *value);
31 #else
32 fmt::memory_buffer message;
33 fmt::format_to(message, format_str.get(), *value);
34 #endif
35 } catch (std::exception&) {
36 }
37 }
38
39 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
40 if (size <= 3) return 0;
41
42 const auto first = data[0];
43 data++;
44 size--;
45
46 switch (first) {
47 case 0:
48 invoke_fmt<bool>(data, size);
49 break;
50 case 1:
51 invoke_fmt<char>(data, size);
52 break;
53 case 2:
54 invoke_fmt<unsigned char>(data, size);
55 break;
56 case 3:
57 invoke_fmt<signed char>(data, size);
58 break;
59 case 4:
60 invoke_fmt<short>(data, size);
61 break;
62 case 5:
63 invoke_fmt<unsigned short>(data, size);
64 break;
65 case 6:
66 invoke_fmt<int>(data, size);
67 break;
68 case 7:
69 invoke_fmt<unsigned int>(data, size);
70 break;
71 case 8:
72 invoke_fmt<long>(data, size);
73 break;
74 case 9:
75 invoke_fmt<unsigned long>(data, size);
76 break;
77 case 10:
78 invoke_fmt<float>(data, size);
79 break;
80 case 11:
81 invoke_fmt<double>(data, size);
82 break;
83 case 12:
84 invoke_fmt<long double>(data, size);
85 break;
86 case 13:
87 invoke_fmt<std::tm, std::time_t>(data, size);
88 break;
89 }
90 return 0;
91 }
+0
-106
source/misc/embedded_libs/fmt-8.1.1/test/fuzzing/two-args.cc less more
0 // Copyright (c) 2019, Paul Dreik
1 // For the license information refer to format.h.
2
3 #include <fmt/format.h>
4
5 #include <cstdint>
6 #include <exception>
7 #include <string>
8
9 #include "fuzzer-common.h"
10
11 template <typename Item1, typename Item2>
12 void invoke_fmt(const uint8_t* data, size_t size) {
13 static_assert(sizeof(Item1) <= fixed_size, "size1 exceeded");
14 static_assert(sizeof(Item2) <= fixed_size, "size2 exceeded");
15 if (size <= fixed_size + fixed_size) return;
16
17 const Item1 item1 = assign_from_buf<Item1>(data);
18 data += fixed_size;
19 size -= fixed_size;
20
21 const Item2 item2 = assign_from_buf<Item2>(data);
22 data += fixed_size;
23 size -= fixed_size;
24
25 auto format_str = fmt::string_view(as_chars(data), size);
26 #if FMT_FUZZ_FORMAT_TO_STRING
27 std::string message = fmt::format(format_str, item1, item2);
28 #else
29 fmt::memory_buffer message;
30 fmt::format_to(message, format_str, item1, item2);
31 #endif
32 }
33
34 // For dynamic dispatching to an explicit instantiation.
35 template <typename Callback> void invoke(int index, Callback callback) {
36 switch (index) {
37 case 0:
38 callback(bool());
39 break;
40 case 1:
41 callback(char());
42 break;
43 case 2:
44 using sc = signed char;
45 callback(sc());
46 break;
47 case 3:
48 using uc = unsigned char;
49 callback(uc());
50 break;
51 case 4:
52 callback(short());
53 break;
54 case 5:
55 using us = unsigned short;
56 callback(us());
57 break;
58 case 6:
59 callback(int());
60 break;
61 case 7:
62 callback(unsigned());
63 break;
64 case 8:
65 callback(long());
66 break;
67 case 9:
68 using ul = unsigned long;
69 callback(ul());
70 break;
71 case 10:
72 callback(float());
73 break;
74 case 11:
75 callback(double());
76 break;
77 case 12:
78 using LD = long double;
79 callback(LD());
80 break;
81 case 13:
82 using ptr = void*;
83 callback(ptr());
84 break;
85 }
86 }
87
88 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
89 if (size <= 3) return 0;
90
91 // Switch types depending on the first byte of the input.
92 const auto type1 = data[0] & 0x0F;
93 const auto type2 = (data[0] & 0xF0) >> 4;
94 data++;
95 size--;
96 try {
97 invoke(type1, [=](auto param1) {
98 invoke(type2, [=](auto param2) {
99 invoke_fmt<decltype(param1), decltype(param2)>(data, size);
100 });
101 });
102 } catch (std::exception&) {
103 }
104 return 0;
105 }
+0
-38
source/misc/embedded_libs/fmt-8.1.1/test/gtest/CMakeLists.txt less more
0 #------------------------------------------------------------------------------
1 # Build the google test library
2
3 # We compile Google Test ourselves instead of using pre-compiled libraries.
4 # See the Google Test FAQ "Why is it not recommended to install a
5 # pre-compiled copy of Google Test (for example, into /usr/local)?"
6 # at http://code.google.com/p/googletest/wiki/FAQ for more details.
7 add_library(gtest STATIC
8 gmock-gtest-all.cc gmock/gmock.h gtest/gtest.h gtest/gtest-spi.h)
9 target_compile_definitions(gtest PUBLIC GTEST_HAS_STD_WSTRING=1)
10 target_include_directories(gtest SYSTEM PUBLIC .)
11
12 find_package(Threads)
13 if (Threads_FOUND)
14 target_link_libraries(gtest ${CMAKE_THREAD_LIBS_INIT})
15 else ()
16 target_compile_definitions(gtest PUBLIC GTEST_HAS_PTHREAD=0)
17 endif ()
18
19 # Workaround GTest bug https://github.com/google/googletest/issues/705.
20 check_cxx_compiler_flag(
21 -fno-delete-null-pointer-checks HAVE_FNO_DELETE_NULL_POINTER_CHECKS)
22 if (HAVE_FNO_DELETE_NULL_POINTER_CHECKS)
23 target_compile_options(gtest PUBLIC -fno-delete-null-pointer-checks)
24 endif ()
25
26 if (MSVC)
27 # Disable MSVC warnings of _CRT_INSECURE_DEPRECATE functions.
28 target_compile_definitions(gtest PRIVATE _CRT_SECURE_NO_WARNINGS)
29 if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
30 # Disable MSVC warnings of POSIX functions.
31 target_compile_options(gtest PUBLIC -Wno-deprecated-declarations)
32 endif ()
33 endif ()
34
35 # Silence MSVC tr1 deprecation warning in gmock.
36 target_compile_definitions(gtest
37 PUBLIC _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1)
+0
-11645
source/misc/embedded_libs/fmt-8.1.1/test/gtest/gmock/gmock.h less more
0 // Copyright 2007, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29
30 // Google Mock - a framework for writing C++ mock classes.
31 //
32 // This is the main header file a user should include.
33
34 // GOOGLETEST_CM0002 DO NOT DELETE
35
36 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
37 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
38
39 // This file implements the following syntax:
40 //
41 // ON_CALL(mock_object, Method(...))
42 // .With(...) ?
43 // .WillByDefault(...);
44 //
45 // where With() is optional and WillByDefault() must appear exactly
46 // once.
47 //
48 // EXPECT_CALL(mock_object, Method(...))
49 // .With(...) ?
50 // .Times(...) ?
51 // .InSequence(...) *
52 // .WillOnce(...) *
53 // .WillRepeatedly(...) ?
54 // .RetiresOnSaturation() ? ;
55 //
56 // where all clauses are optional and WillOnce() can be repeated.
57
58 // Copyright 2007, Google Inc.
59 // All rights reserved.
60 //
61 // Redistribution and use in source and binary forms, with or without
62 // modification, are permitted provided that the following conditions are
63 // met:
64 //
65 // * Redistributions of source code must retain the above copyright
66 // notice, this list of conditions and the following disclaimer.
67 // * Redistributions in binary form must reproduce the above
68 // copyright notice, this list of conditions and the following disclaimer
69 // in the documentation and/or other materials provided with the
70 // distribution.
71 // * Neither the name of Google Inc. nor the names of its
72 // contributors may be used to endorse or promote products derived from
73 // this software without specific prior written permission.
74 //
75 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
76 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
77 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
78 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
79 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
80 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
81 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
82 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
83 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
84 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
85 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
86
87
88 // Google Mock - a framework for writing C++ mock classes.
89 //
90 // The ACTION* family of macros can be used in a namespace scope to
91 // define custom actions easily. The syntax:
92 //
93 // ACTION(name) { statements; }
94 //
95 // will define an action with the given name that executes the
96 // statements. The value returned by the statements will be used as
97 // the return value of the action. Inside the statements, you can
98 // refer to the K-th (0-based) argument of the mock function by
99 // 'argK', and refer to its type by 'argK_type'. For example:
100 //
101 // ACTION(IncrementArg1) {
102 // arg1_type temp = arg1;
103 // return ++(*temp);
104 // }
105 //
106 // allows you to write
107 //
108 // ...WillOnce(IncrementArg1());
109 //
110 // You can also refer to the entire argument tuple and its type by
111 // 'args' and 'args_type', and refer to the mock function type and its
112 // return type by 'function_type' and 'return_type'.
113 //
114 // Note that you don't need to specify the types of the mock function
115 // arguments. However rest assured that your code is still type-safe:
116 // you'll get a compiler error if *arg1 doesn't support the ++
117 // operator, or if the type of ++(*arg1) isn't compatible with the
118 // mock function's return type, for example.
119 //
120 // Sometimes you'll want to parameterize the action. For that you can use
121 // another macro:
122 //
123 // ACTION_P(name, param_name) { statements; }
124 //
125 // For example:
126 //
127 // ACTION_P(Add, n) { return arg0 + n; }
128 //
129 // will allow you to write:
130 //
131 // ...WillOnce(Add(5));
132 //
133 // Note that you don't need to provide the type of the parameter
134 // either. If you need to reference the type of a parameter named
135 // 'foo', you can write 'foo_type'. For example, in the body of
136 // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
137 // of 'n'.
138 //
139 // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
140 // multi-parameter actions.
141 //
142 // For the purpose of typing, you can view
143 //
144 // ACTION_Pk(Foo, p1, ..., pk) { ... }
145 //
146 // as shorthand for
147 //
148 // template <typename p1_type, ..., typename pk_type>
149 // FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
150 //
151 // In particular, you can provide the template type arguments
152 // explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
153 // although usually you can rely on the compiler to infer the types
154 // for you automatically. You can assign the result of expression
155 // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
156 // pk_type>. This can be useful when composing actions.
157 //
158 // You can also overload actions with different numbers of parameters:
159 //
160 // ACTION_P(Plus, a) { ... }
161 // ACTION_P2(Plus, a, b) { ... }
162 //
163 // While it's tempting to always use the ACTION* macros when defining
164 // a new action, you should also consider implementing ActionInterface
165 // or using MakePolymorphicAction() instead, especially if you need to
166 // use the action a lot. While these approaches require more work,
167 // they give you more control on the types of the mock function
168 // arguments and the action parameters, which in general leads to
169 // better compiler error messages that pay off in the long run. They
170 // also allow overloading actions based on parameter types (as opposed
171 // to just based on the number of parameters).
172 //
173 // CAVEAT:
174 //
175 // ACTION*() can only be used in a namespace scope as templates cannot be
176 // declared inside of a local class.
177 // Users can, however, define any local functors (e.g. a lambda) that
178 // can be used as actions.
179 //
180 // MORE INFORMATION:
181 //
182 // To learn more about using these macros, please search for 'ACTION' on
183 // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
184
185 // GOOGLETEST_CM0002 DO NOT DELETE
186
187 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
188 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
189
190 #ifndef _WIN32_WCE
191 # include <errno.h>
192 #endif
193
194 #include <algorithm>
195 #include <functional>
196 #include <memory>
197 #include <string>
198 #include <tuple>
199 #include <type_traits>
200 #include <utility>
201
202 // Copyright 2007, Google Inc.
203 // All rights reserved.
204 //
205 // Redistribution and use in source and binary forms, with or without
206 // modification, are permitted provided that the following conditions are
207 // met:
208 //
209 // * Redistributions of source code must retain the above copyright
210 // notice, this list of conditions and the following disclaimer.
211 // * Redistributions in binary form must reproduce the above
212 // copyright notice, this list of conditions and the following disclaimer
213 // in the documentation and/or other materials provided with the
214 // distribution.
215 // * Neither the name of Google Inc. nor the names of its
216 // contributors may be used to endorse or promote products derived from
217 // this software without specific prior written permission.
218 //
219 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
220 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
222 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
223 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
224 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
225 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
226 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
227 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
228 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
229 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
230
231
232 // Google Mock - a framework for writing C++ mock classes.
233 //
234 // This file defines some utilities useful for implementing Google
235 // Mock. They are subject to change without notice, so please DO NOT
236 // USE THEM IN USER CODE.
237
238 // GOOGLETEST_CM0002 DO NOT DELETE
239
240 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
241 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
242
243 #include <stdio.h>
244 #include <ostream> // NOLINT
245 #include <string>
246 #include <type_traits>
247 // Copyright 2008, Google Inc.
248 // All rights reserved.
249 //
250 // Redistribution and use in source and binary forms, with or without
251 // modification, are permitted provided that the following conditions are
252 // met:
253 //
254 // * Redistributions of source code must retain the above copyright
255 // notice, this list of conditions and the following disclaimer.
256 // * Redistributions in binary form must reproduce the above
257 // copyright notice, this list of conditions and the following disclaimer
258 // in the documentation and/or other materials provided with the
259 // distribution.
260 // * Neither the name of Google Inc. nor the names of its
261 // contributors may be used to endorse or promote products derived from
262 // this software without specific prior written permission.
263 //
264 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
265 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
266 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
267 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
268 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
269 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
270 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
271 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
272 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
273 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
274 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
275
276 //
277 // Low-level types and utilities for porting Google Mock to various
278 // platforms. All macros ending with _ and symbols defined in an
279 // internal namespace are subject to change without notice. Code
280 // outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't
281 // end with _ are part of Google Mock's public API and can be used by
282 // code outside Google Mock.
283
284 // GOOGLETEST_CM0002 DO NOT DELETE
285
286 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
287 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
288
289 #include <assert.h>
290 #include <stdlib.h>
291 #include <cstdint>
292 #include <iostream>
293
294 // Most of the utilities needed for porting Google Mock are also
295 // required for Google Test and are defined in gtest-port.h.
296 //
297 // Note to maintainers: to reduce code duplication, prefer adding
298 // portability utilities to Google Test's gtest-port.h instead of
299 // here, as Google Mock depends on Google Test. Only add a utility
300 // here if it's truly specific to Google Mock.
301
302 #include "gtest/gtest.h"
303 // Copyright 2015, Google Inc.
304 // All rights reserved.
305 //
306 // Redistribution and use in source and binary forms, with or without
307 // modification, are permitted provided that the following conditions are
308 // met:
309 //
310 // * Redistributions of source code must retain the above copyright
311 // notice, this list of conditions and the following disclaimer.
312 // * Redistributions in binary form must reproduce the above
313 // copyright notice, this list of conditions and the following disclaimer
314 // in the documentation and/or other materials provided with the
315 // distribution.
316 // * Neither the name of Google Inc. nor the names of its
317 // contributors may be used to endorse or promote products derived from
318 // this software without specific prior written permission.
319 //
320 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
321 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
322 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
323 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
324 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
325 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
326 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
327 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
328 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
329 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
330 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
331 //
332 // Injection point for custom user configurations. See README for details
333 //
334 // ** Custom implementation starts here **
335
336 // GOOGLETEST_CM0002 DO NOT DELETE
337
338 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
339 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
340
341 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
342
343 // For MS Visual C++, check the compiler version. At least VS 2015 is
344 // required to compile Google Mock.
345 #if defined(_MSC_VER) && _MSC_VER < 1900
346 # error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
347 #endif
348
349 // Macro for referencing flags. This is public as we want the user to
350 // use this syntax to reference Google Mock flags.
351 #define GMOCK_FLAG(name) FLAGS_gmock_##name
352
353 #if !defined(GMOCK_DECLARE_bool_)
354
355 // Macros for declaring flags.
356 # define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
357 # define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name)
358 # define GMOCK_DECLARE_string_(name) \
359 extern GTEST_API_ ::std::string GMOCK_FLAG(name)
360
361 // Macros for defining flags.
362 # define GMOCK_DEFINE_bool_(name, default_val, doc) \
363 GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
364 # define GMOCK_DEFINE_int32_(name, default_val, doc) \
365 GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val)
366 # define GMOCK_DEFINE_string_(name, default_val, doc) \
367 GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
368
369 #endif // !defined(GMOCK_DECLARE_bool_)
370
371 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
372
373 namespace testing {
374
375 template <typename>
376 class Matcher;
377
378 namespace internal {
379
380 // Silence MSVC C4100 (unreferenced formal parameter) and
381 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
382 #ifdef _MSC_VER
383 # pragma warning(push)
384 # pragma warning(disable:4100)
385 # pragma warning(disable:4805)
386 #endif
387
388 // Joins a vector of strings as if they are fields of a tuple; returns
389 // the joined string.
390 GTEST_API_ std::string JoinAsTuple(const Strings& fields);
391
392 // Converts an identifier name to a space-separated list of lower-case
393 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
394 // treated as one word. For example, both "FooBar123" and
395 // "foo_bar_123" are converted to "foo bar 123".
396 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
397
398 // GetRawPointer(p) returns the raw pointer underlying p when p is a
399 // smart pointer, or returns p itself when p is already a raw pointer.
400 // The following default implementation is for the smart pointer case.
401 template <typename Pointer>
402 inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
403 return p.get();
404 }
405 // This overloaded version is for the raw pointer case.
406 template <typename Element>
407 inline Element* GetRawPointer(Element* p) { return p; }
408
409 // MSVC treats wchar_t as a native type usually, but treats it as the
410 // same as unsigned short when the compiler option /Zc:wchar_t- is
411 // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
412 // is a native type.
413 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
414 // wchar_t is a typedef.
415 #else
416 # define GMOCK_WCHAR_T_IS_NATIVE_ 1
417 #endif
418
419 // In what follows, we use the term "kind" to indicate whether a type
420 // is bool, an integer type (excluding bool), a floating-point type,
421 // or none of them. This categorization is useful for determining
422 // when a matcher argument type can be safely converted to another
423 // type in the implementation of SafeMatcherCast.
424 enum TypeKind {
425 kBool, kInteger, kFloatingPoint, kOther
426 };
427
428 // KindOf<T>::value is the kind of type T.
429 template <typename T> struct KindOf {
430 enum { value = kOther }; // The default kind.
431 };
432
433 // This macro declares that the kind of 'type' is 'kind'.
434 #define GMOCK_DECLARE_KIND_(type, kind) \
435 template <> struct KindOf<type> { enum { value = kind }; }
436
437 GMOCK_DECLARE_KIND_(bool, kBool);
438
439 // All standard integer types.
440 GMOCK_DECLARE_KIND_(char, kInteger);
441 GMOCK_DECLARE_KIND_(signed char, kInteger);
442 GMOCK_DECLARE_KIND_(unsigned char, kInteger);
443 GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
444 GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
445 GMOCK_DECLARE_KIND_(int, kInteger);
446 GMOCK_DECLARE_KIND_(unsigned int, kInteger);
447 GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
448 GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
449 GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
450 GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
451
452 #if GMOCK_WCHAR_T_IS_NATIVE_
453 GMOCK_DECLARE_KIND_(wchar_t, kInteger);
454 #endif
455
456 // All standard floating-point types.
457 GMOCK_DECLARE_KIND_(float, kFloatingPoint);
458 GMOCK_DECLARE_KIND_(double, kFloatingPoint);
459 GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
460
461 #undef GMOCK_DECLARE_KIND_
462
463 // Evaluates to the kind of 'type'.
464 #define GMOCK_KIND_OF_(type) \
465 static_cast< ::testing::internal::TypeKind>( \
466 ::testing::internal::KindOf<type>::value)
467
468 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
469 // is true if and only if arithmetic type From can be losslessly converted to
470 // arithmetic type To.
471 //
472 // It's the user's responsibility to ensure that both From and To are
473 // raw (i.e. has no CV modifier, is not a pointer, and is not a
474 // reference) built-in arithmetic types, kFromKind is the kind of
475 // From, and kToKind is the kind of To; the value is
476 // implementation-defined when the above pre-condition is violated.
477 template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
478 using LosslessArithmeticConvertibleImpl = std::integral_constant<
479 bool,
480 // clang-format off
481 // Converting from bool is always lossless
482 (kFromKind == kBool) ? true
483 // Converting between any other type kinds will be lossy if the type
484 // kinds are not the same.
485 : (kFromKind != kToKind) ? false
486 : (kFromKind == kInteger &&
487 // Converting between integers of different widths is allowed so long
488 // as the conversion does not go from signed to unsigned.
489 (((sizeof(From) < sizeof(To)) &&
490 !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
491 // Converting between integers of the same width only requires the
492 // two types to have the same signedness.
493 ((sizeof(From) == sizeof(To)) &&
494 (std::is_signed<From>::value == std::is_signed<To>::value)))
495 ) ? true
496 // Floating point conversions are lossless if and only if `To` is at least
497 // as wide as `From`.
498 : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
499 : false
500 // clang-format on
501 >;
502
503 // LosslessArithmeticConvertible<From, To>::value is true if and only if
504 // arithmetic type From can be losslessly converted to arithmetic type To.
505 //
506 // It's the user's responsibility to ensure that both From and To are
507 // raw (i.e. has no CV modifier, is not a pointer, and is not a
508 // reference) built-in arithmetic types; the value is
509 // implementation-defined when the above pre-condition is violated.
510 template <typename From, typename To>
511 using LosslessArithmeticConvertible =
512 LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
513 GMOCK_KIND_OF_(To), To>;
514
515 // This interface knows how to report a Google Mock failure (either
516 // non-fatal or fatal).
517 class FailureReporterInterface {
518 public:
519 // The type of a failure (either non-fatal or fatal).
520 enum FailureType {
521 kNonfatal, kFatal
522 };
523
524 virtual ~FailureReporterInterface() {}
525
526 // Reports a failure that occurred at the given source file location.
527 virtual void ReportFailure(FailureType type, const char* file, int line,
528 const std::string& message) = 0;
529 };
530
531 // Returns the failure reporter used by Google Mock.
532 GTEST_API_ FailureReporterInterface* GetFailureReporter();
533
534 // Asserts that condition is true; aborts the process with the given
535 // message if condition is false. We cannot use LOG(FATAL) or CHECK()
536 // as Google Mock might be used to mock the log sink itself. We
537 // inline this function to prevent it from showing up in the stack
538 // trace.
539 inline void Assert(bool condition, const char* file, int line,
540 const std::string& msg) {
541 if (!condition) {
542 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
543 file, line, msg);
544 }
545 }
546 inline void Assert(bool condition, const char* file, int line) {
547 Assert(condition, file, line, "Assertion failed.");
548 }
549
550 // Verifies that condition is true; generates a non-fatal failure if
551 // condition is false.
552 inline void Expect(bool condition, const char* file, int line,
553 const std::string& msg) {
554 if (!condition) {
555 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
556 file, line, msg);
557 }
558 }
559 inline void Expect(bool condition, const char* file, int line) {
560 Expect(condition, file, line, "Expectation failed.");
561 }
562
563 // Severity level of a log.
564 enum LogSeverity {
565 kInfo = 0,
566 kWarning = 1
567 };
568
569 // Valid values for the --gmock_verbose flag.
570
571 // All logs (informational and warnings) are printed.
572 const char kInfoVerbosity[] = "info";
573 // Only warnings are printed.
574 const char kWarningVerbosity[] = "warning";
575 // No logs are printed.
576 const char kErrorVerbosity[] = "error";
577
578 // Returns true if and only if a log with the given severity is visible
579 // according to the --gmock_verbose flag.
580 GTEST_API_ bool LogIsVisible(LogSeverity severity);
581
582 // Prints the given message to stdout if and only if 'severity' >= the level
583 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
584 // 0, also prints the stack trace excluding the top
585 // stack_frames_to_skip frames. In opt mode, any positive
586 // stack_frames_to_skip is treated as 0, since we don't know which
587 // function calls will be inlined by the compiler and need to be
588 // conservative.
589 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
590 int stack_frames_to_skip);
591
592 // A marker class that is used to resolve parameterless expectations to the
593 // correct overload. This must not be instantiable, to prevent client code from
594 // accidentally resolving to the overload; for example:
595 //
596 // ON_CALL(mock, Method({}, nullptr))...
597 //
598 class WithoutMatchers {
599 private:
600 WithoutMatchers() {}
601 friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
602 };
603
604 // Internal use only: access the singleton instance of WithoutMatchers.
605 GTEST_API_ WithoutMatchers GetWithoutMatchers();
606
607 // Disable MSVC warnings for infinite recursion, since in this case the
608 // the recursion is unreachable.
609 #ifdef _MSC_VER
610 # pragma warning(push)
611 # pragma warning(disable:4717)
612 #endif
613
614 // Invalid<T>() is usable as an expression of type T, but will terminate
615 // the program with an assertion failure if actually run. This is useful
616 // when a value of type T is needed for compilation, but the statement
617 // will not really be executed (or we don't care if the statement
618 // crashes).
619 template <typename T>
620 inline T Invalid() {
621 Assert(false, "", -1, "Internal error: attempt to return invalid value");
622 // This statement is unreachable, and would never terminate even if it
623 // could be reached. It is provided only to placate compiler warnings
624 // about missing return statements.
625 return Invalid<T>();
626 }
627
628 #ifdef _MSC_VER
629 # pragma warning(pop)
630 #endif
631
632 // Given a raw type (i.e. having no top-level reference or const
633 // modifier) RawContainer that's either an STL-style container or a
634 // native array, class StlContainerView<RawContainer> has the
635 // following members:
636 //
637 // - type is a type that provides an STL-style container view to
638 // (i.e. implements the STL container concept for) RawContainer;
639 // - const_reference is a type that provides a reference to a const
640 // RawContainer;
641 // - ConstReference(raw_container) returns a const reference to an STL-style
642 // container view to raw_container, which is a RawContainer.
643 // - Copy(raw_container) returns an STL-style container view of a
644 // copy of raw_container, which is a RawContainer.
645 //
646 // This generic version is used when RawContainer itself is already an
647 // STL-style container.
648 template <class RawContainer>
649 class StlContainerView {
650 public:
651 typedef RawContainer type;
652 typedef const type& const_reference;
653
654 static const_reference ConstReference(const RawContainer& container) {
655 static_assert(!std::is_const<RawContainer>::value,
656 "RawContainer type must not be const");
657 return container;
658 }
659 static type Copy(const RawContainer& container) { return container; }
660 };
661
662 // This specialization is used when RawContainer is a native array type.
663 template <typename Element, size_t N>
664 class StlContainerView<Element[N]> {
665 public:
666 typedef typename std::remove_const<Element>::type RawElement;
667 typedef internal::NativeArray<RawElement> type;
668 // NativeArray<T> can represent a native array either by value or by
669 // reference (selected by a constructor argument), so 'const type'
670 // can be used to reference a const native array. We cannot
671 // 'typedef const type& const_reference' here, as that would mean
672 // ConstReference() has to return a reference to a local variable.
673 typedef const type const_reference;
674
675 static const_reference ConstReference(const Element (&array)[N]) {
676 static_assert(std::is_same<Element, RawElement>::value,
677 "Element type must not be const");
678 return type(array, N, RelationToSourceReference());
679 }
680 static type Copy(const Element (&array)[N]) {
681 return type(array, N, RelationToSourceCopy());
682 }
683 };
684
685 // This specialization is used when RawContainer is a native array
686 // represented as a (pointer, size) tuple.
687 template <typename ElementPointer, typename Size>
688 class StlContainerView< ::std::tuple<ElementPointer, Size> > {
689 public:
690 typedef typename std::remove_const<
691 typename std::pointer_traits<ElementPointer>::element_type>::type
692 RawElement;
693 typedef internal::NativeArray<RawElement> type;
694 typedef const type const_reference;
695
696 static const_reference ConstReference(
697 const ::std::tuple<ElementPointer, Size>& array) {
698 return type(std::get<0>(array), std::get<1>(array),
699 RelationToSourceReference());
700 }
701 static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
702 return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
703 }
704 };
705
706 // The following specialization prevents the user from instantiating
707 // StlContainer with a reference type.
708 template <typename T> class StlContainerView<T&>;
709
710 // A type transform to remove constness from the first part of a pair.
711 // Pairs like that are used as the value_type of associative containers,
712 // and this transform produces a similar but assignable pair.
713 template <typename T>
714 struct RemoveConstFromKey {
715 typedef T type;
716 };
717
718 // Partially specialized to remove constness from std::pair<const K, V>.
719 template <typename K, typename V>
720 struct RemoveConstFromKey<std::pair<const K, V> > {
721 typedef std::pair<K, V> type;
722 };
723
724 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
725 // reduce code size.
726 GTEST_API_ void IllegalDoDefault(const char* file, int line);
727
728 template <typename F, typename Tuple, size_t... Idx>
729 auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
730 std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
731 return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
732 }
733
734 // Apply the function to a tuple of arguments.
735 template <typename F, typename Tuple>
736 auto Apply(F&& f, Tuple&& args) -> decltype(
737 ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
738 MakeIndexSequence<std::tuple_size<
739 typename std::remove_reference<Tuple>::type>::value>())) {
740 return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
741 MakeIndexSequence<std::tuple_size<
742 typename std::remove_reference<Tuple>::type>::value>());
743 }
744
745 // Template struct Function<F>, where F must be a function type, contains
746 // the following typedefs:
747 //
748 // Result: the function's return type.
749 // Arg<N>: the type of the N-th argument, where N starts with 0.
750 // ArgumentTuple: the tuple type consisting of all parameters of F.
751 // ArgumentMatcherTuple: the tuple type consisting of Matchers for all
752 // parameters of F.
753 // MakeResultVoid: the function type obtained by substituting void
754 // for the return type of F.
755 // MakeResultIgnoredValue:
756 // the function type obtained by substituting Something
757 // for the return type of F.
758 template <typename T>
759 struct Function;
760
761 template <typename R, typename... Args>
762 struct Function<R(Args...)> {
763 using Result = R;
764 static constexpr size_t ArgumentCount = sizeof...(Args);
765 template <size_t I>
766 using Arg = ElemFromList<I, Args...>;
767 using ArgumentTuple = std::tuple<Args...>;
768 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
769 using MakeResultVoid = void(Args...);
770 using MakeResultIgnoredValue = IgnoredValue(Args...);
771 };
772
773 template <typename R, typename... Args>
774 constexpr size_t Function<R(Args...)>::ArgumentCount;
775
776 #ifdef _MSC_VER
777 # pragma warning(pop)
778 #endif
779
780 } // namespace internal
781 } // namespace testing
782
783 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
784 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
785 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
786
787 // Expands and concatenates the arguments. Constructed macros reevaluate.
788 #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)
789
790 // Expands and stringifies the only argument.
791 #define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__)
792
793 // Returns empty. Given a variadic number of arguments.
794 #define GMOCK_PP_EMPTY(...)
795
796 // Returns a comma. Given a variadic number of arguments.
797 #define GMOCK_PP_COMMA(...) ,
798
799 // Returns the only argument.
800 #define GMOCK_PP_IDENTITY(_1) _1
801
802 // Evaluates to the number of arguments after expansion.
803 //
804 // #define PAIR x, y
805 //
806 // GMOCK_PP_NARG() => 1
807 // GMOCK_PP_NARG(x) => 1
808 // GMOCK_PP_NARG(x, y) => 2
809 // GMOCK_PP_NARG(PAIR) => 2
810 //
811 // Requires: the number of arguments after expansion is at most 15.
812 #define GMOCK_PP_NARG(...) \
813 GMOCK_PP_INTERNAL_16TH( \
814 (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
815
816 // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
817 // returns 0. Requires no more than 15 unprotected commas.
818 #define GMOCK_PP_HAS_COMMA(...) \
819 GMOCK_PP_INTERNAL_16TH( \
820 (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))
821
822 // Returns the first argument.
823 #define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))
824
825 // Returns the tail. A variadic list of all arguments minus the first. Requires
826 // at least one argument.
827 #define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__))
828
829 // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__)
830 #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
831 GMOCK_PP_IDENTITY( \
832 GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__))
833
834 // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise
835 // evaluates to `0`.
836 //
837 // Requires: * the number of arguments after expansion is at most 15.
838 // * If the argument is a macro, it must be able to be called with one
839 // argument.
840 //
841 // Implementation details:
842 //
843 // There is one case when it generates a compile error: if the argument is macro
844 // that cannot be called with one argument.
845 //
846 // #define M(a, b) // it doesn't matter what it expands to
847 //
848 // // Expected: expands to `0`.
849 // // Actual: compile error.
850 // GMOCK_PP_IS_EMPTY(M)
851 //
852 // There are 4 cases tested:
853 //
854 // * __VA_ARGS__ possible expansion has no unparen'd commas. Expected 0.
855 // * __VA_ARGS__ possible expansion is not enclosed in parenthesis. Expected 0.
856 // * __VA_ARGS__ possible expansion is not a macro that ()-evaluates to a comma.
857 // Expected 0
858 // * __VA_ARGS__ is empty, or has unparen'd commas, or is enclosed in
859 // parenthesis, or is a macro that ()-evaluates to comma. Expected 1.
860 //
861 // We trigger detection on '0001', i.e. on empty.
862 #define GMOCK_PP_IS_EMPTY(...) \
863 GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__), \
864 GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \
865 GMOCK_PP_HAS_COMMA(__VA_ARGS__()), \
866 GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__()))
867
868 // Evaluates to _Then if _Cond is 1 and _Else if _Cond is 0.
869 #define GMOCK_PP_IF(_Cond, _Then, _Else) \
870 GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
871
872 // Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.
873 //
874 // GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c
875 // GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f
876 //
877 #define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \
878 GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))
879
880 // Evaluates to the number of arguments after expansion. Identifies 'empty' as
881 // 0.
882 //
883 // #define PAIR x, y
884 //
885 // GMOCK_PP_NARG0() => 0
886 // GMOCK_PP_NARG0(x) => 1
887 // GMOCK_PP_NARG0(x, y) => 2
888 // GMOCK_PP_NARG0(PAIR) => 2
889 //
890 // Requires: * the number of arguments after expansion is at most 15.
891 // * If the argument is a macro, it must be able to be called with one
892 // argument.
893 #define GMOCK_PP_NARG0(...) \
894 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__))
895
896 // Expands to 1 if the first argument starts with something in parentheses,
897 // otherwise to 0.
898 #define GMOCK_PP_IS_BEGIN_PARENS(...) \
899 GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \
900 GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
901
902 // Expands to 1 is there is only one argument and it is enclosed in parentheses.
903 #define GMOCK_PP_IS_ENCLOSED_PARENS(...) \
904 GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \
905 GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0)
906
907 // Remove the parens, requires GMOCK_PP_IS_ENCLOSED_PARENS(args) => 1.
908 #define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__
909
910 // Expands to _Macro(0, _Data, e1) _Macro(1, _Data, e2) ... _Macro(K -1, _Data,
911 // eK) as many of GMOCK_INTERNAL_NARG0 _Tuple.
912 // Requires: * |_Macro| can be called with 3 arguments.
913 // * |_Tuple| expansion has no more than 15 elements.
914 #define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple) \
915 GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \
916 (0, _Macro, _Data, _Tuple)
917
918 // Expands to _Macro(0, _Data, ) _Macro(1, _Data, ) ... _Macro(K - 1, _Data, )
919 // Empty if _K = 0.
920 // Requires: * |_Macro| can be called with 3 arguments.
921 // * |_K| literal between 0 and 15
922 #define GMOCK_PP_REPEAT(_Macro, _Data, _N) \
923 GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \
924 (0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE)
925
926 // Increments the argument, requires the argument to be between 0 and 15.
927 #define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i)
928
929 // Returns comma if _i != 0. Requires _i to be between 0 and 15.
930 #define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i)
931
932 // Internal details follow. Do not use any of these symbols outside of this
933 // file or we will break your code.
934 #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , )
935 #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2
936 #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__
937 #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5
938 #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \
939 GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \
940 _1, _2, _3, _4))
941 #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 ,
942 #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then
943 #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else
944
945 // Because of MSVC treating a token with a comma in it as a single token when
946 // passed to another macro, we need to force it to evaluate it as multiple
947 // tokens. We do that by using a "IDENTITY(MACRO PARENTHESIZED_ARGS)" macro. We
948 // define one per possible macro that relies on this behavior. Note "_Args" must
949 // be parenthesized.
950 #define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
951 _10, _11, _12, _13, _14, _15, _16, \
952 ...) \
953 _16
954 #define GMOCK_PP_INTERNAL_16TH(_Args) \
955 GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args)
956 #define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1
957 #define GMOCK_PP_INTERNAL_HEAD(_Args) \
958 GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args)
959 #define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__
960 #define GMOCK_PP_INTERNAL_TAIL(_Args) \
961 GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args)
962
963 #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _
964 #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1,
965 #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \
966 0,
967 #define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__
968 #define GMOCK_PP_INTERNAL_INC_0 1
969 #define GMOCK_PP_INTERNAL_INC_1 2
970 #define GMOCK_PP_INTERNAL_INC_2 3
971 #define GMOCK_PP_INTERNAL_INC_3 4
972 #define GMOCK_PP_INTERNAL_INC_4 5
973 #define GMOCK_PP_INTERNAL_INC_5 6
974 #define GMOCK_PP_INTERNAL_INC_6 7
975 #define GMOCK_PP_INTERNAL_INC_7 8
976 #define GMOCK_PP_INTERNAL_INC_8 9
977 #define GMOCK_PP_INTERNAL_INC_9 10
978 #define GMOCK_PP_INTERNAL_INC_10 11
979 #define GMOCK_PP_INTERNAL_INC_11 12
980 #define GMOCK_PP_INTERNAL_INC_12 13
981 #define GMOCK_PP_INTERNAL_INC_13 14
982 #define GMOCK_PP_INTERNAL_INC_14 15
983 #define GMOCK_PP_INTERNAL_INC_15 16
984 #define GMOCK_PP_INTERNAL_COMMA_IF_0
985 #define GMOCK_PP_INTERNAL_COMMA_IF_1 ,
986 #define GMOCK_PP_INTERNAL_COMMA_IF_2 ,
987 #define GMOCK_PP_INTERNAL_COMMA_IF_3 ,
988 #define GMOCK_PP_INTERNAL_COMMA_IF_4 ,
989 #define GMOCK_PP_INTERNAL_COMMA_IF_5 ,
990 #define GMOCK_PP_INTERNAL_COMMA_IF_6 ,
991 #define GMOCK_PP_INTERNAL_COMMA_IF_7 ,
992 #define GMOCK_PP_INTERNAL_COMMA_IF_8 ,
993 #define GMOCK_PP_INTERNAL_COMMA_IF_9 ,
994 #define GMOCK_PP_INTERNAL_COMMA_IF_10 ,
995 #define GMOCK_PP_INTERNAL_COMMA_IF_11 ,
996 #define GMOCK_PP_INTERNAL_COMMA_IF_12 ,
997 #define GMOCK_PP_INTERNAL_COMMA_IF_13 ,
998 #define GMOCK_PP_INTERNAL_COMMA_IF_14 ,
999 #define GMOCK_PP_INTERNAL_COMMA_IF_15 ,
1000 #define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \
1001 _Macro(_i, _Data, _element)
1002 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple)
1003 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \
1004 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple)
1005 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple) \
1006 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1007 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data, \
1008 (GMOCK_PP_TAIL _Tuple))
1009 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple) \
1010 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1011 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data, \
1012 (GMOCK_PP_TAIL _Tuple))
1013 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple) \
1014 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1015 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data, \
1016 (GMOCK_PP_TAIL _Tuple))
1017 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple) \
1018 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1019 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data, \
1020 (GMOCK_PP_TAIL _Tuple))
1021 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple) \
1022 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1023 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data, \
1024 (GMOCK_PP_TAIL _Tuple))
1025 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple) \
1026 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1027 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data, \
1028 (GMOCK_PP_TAIL _Tuple))
1029 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple) \
1030 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1031 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data, \
1032 (GMOCK_PP_TAIL _Tuple))
1033 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple) \
1034 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1035 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data, \
1036 (GMOCK_PP_TAIL _Tuple))
1037 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple) \
1038 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1039 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data, \
1040 (GMOCK_PP_TAIL _Tuple))
1041 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple) \
1042 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1043 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data, \
1044 (GMOCK_PP_TAIL _Tuple))
1045 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple) \
1046 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1047 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data, \
1048 (GMOCK_PP_TAIL _Tuple))
1049 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple) \
1050 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1051 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data, \
1052 (GMOCK_PP_TAIL _Tuple))
1053 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple) \
1054 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1055 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data, \
1056 (GMOCK_PP_TAIL _Tuple))
1057 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple) \
1058 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1059 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \
1060 (GMOCK_PP_TAIL _Tuple))
1061
1062 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
1063
1064 #ifdef _MSC_VER
1065 # pragma warning(push)
1066 # pragma warning(disable:4100)
1067 #endif
1068
1069 namespace testing {
1070
1071 // To implement an action Foo, define:
1072 // 1. a class FooAction that implements the ActionInterface interface, and
1073 // 2. a factory function that creates an Action object from a
1074 // const FooAction*.
1075 //
1076 // The two-level delegation design follows that of Matcher, providing
1077 // consistency for extension developers. It also eases ownership
1078 // management as Action objects can now be copied like plain values.
1079
1080 namespace internal {
1081
1082 // BuiltInDefaultValueGetter<T, true>::Get() returns a
1083 // default-constructed T value. BuiltInDefaultValueGetter<T,
1084 // false>::Get() crashes with an error.
1085 //
1086 // This primary template is used when kDefaultConstructible is true.
1087 template <typename T, bool kDefaultConstructible>
1088 struct BuiltInDefaultValueGetter {
1089 static T Get() { return T(); }
1090 };
1091 template <typename T>
1092 struct BuiltInDefaultValueGetter<T, false> {
1093 static T Get() {
1094 Assert(false, __FILE__, __LINE__,
1095 "Default action undefined for the function return type.");
1096 return internal::Invalid<T>();
1097 // The above statement will never be reached, but is required in
1098 // order for this function to compile.
1099 }
1100 };
1101
1102 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
1103 // for type T, which is NULL when T is a raw pointer type, 0 when T is
1104 // a numeric type, false when T is bool, or "" when T is string or
1105 // std::string. In addition, in C++11 and above, it turns a
1106 // default-constructed T value if T is default constructible. For any
1107 // other type T, the built-in default T value is undefined, and the
1108 // function will abort the process.
1109 template <typename T>
1110 class BuiltInDefaultValue {
1111 public:
1112 // This function returns true if and only if type T has a built-in default
1113 // value.
1114 static bool Exists() {
1115 return ::std::is_default_constructible<T>::value;
1116 }
1117
1118 static T Get() {
1119 return BuiltInDefaultValueGetter<
1120 T, ::std::is_default_constructible<T>::value>::Get();
1121 }
1122 };
1123
1124 // This partial specialization says that we use the same built-in
1125 // default value for T and const T.
1126 template <typename T>
1127 class BuiltInDefaultValue<const T> {
1128 public:
1129 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
1130 static T Get() { return BuiltInDefaultValue<T>::Get(); }
1131 };
1132
1133 // This partial specialization defines the default values for pointer
1134 // types.
1135 template <typename T>
1136 class BuiltInDefaultValue<T*> {
1137 public:
1138 static bool Exists() { return true; }
1139 static T* Get() { return nullptr; }
1140 };
1141
1142 // The following specializations define the default values for
1143 // specific types we care about.
1144 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
1145 template <> \
1146 class BuiltInDefaultValue<type> { \
1147 public: \
1148 static bool Exists() { return true; } \
1149 static type Get() { return value; } \
1150 }
1151
1152 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
1153 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
1154 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
1155 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
1156 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
1157 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
1158
1159 // There's no need for a default action for signed wchar_t, as that
1160 // type is the same as wchar_t for gcc, and invalid for MSVC.
1161 //
1162 // There's also no need for a default action for unsigned wchar_t, as
1163 // that type is the same as unsigned int for gcc, and invalid for
1164 // MSVC.
1165 #if GMOCK_WCHAR_T_IS_NATIVE_
1166 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
1167 #endif
1168
1169 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
1170 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
1171 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
1172 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
1173 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
1174 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
1175 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT
1176 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT
1177 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
1178 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
1179
1180 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
1181
1182 // Simple two-arg form of std::disjunction.
1183 template <typename P, typename Q>
1184 using disjunction = typename ::std::conditional<P::value, P, Q>::type;
1185
1186 } // namespace internal
1187
1188 // When an unexpected function call is encountered, Google Mock will
1189 // let it return a default value if the user has specified one for its
1190 // return type, or if the return type has a built-in default value;
1191 // otherwise Google Mock won't know what value to return and will have
1192 // to abort the process.
1193 //
1194 // The DefaultValue<T> class allows a user to specify the
1195 // default value for a type T that is both copyable and publicly
1196 // destructible (i.e. anything that can be used as a function return
1197 // type). The usage is:
1198 //
1199 // // Sets the default value for type T to be foo.
1200 // DefaultValue<T>::Set(foo);
1201 template <typename T>
1202 class DefaultValue {
1203 public:
1204 // Sets the default value for type T; requires T to be
1205 // copy-constructable and have a public destructor.
1206 static void Set(T x) {
1207 delete producer_;
1208 producer_ = new FixedValueProducer(x);
1209 }
1210
1211 // Provides a factory function to be called to generate the default value.
1212 // This method can be used even if T is only move-constructible, but it is not
1213 // limited to that case.
1214 typedef T (*FactoryFunction)();
1215 static void SetFactory(FactoryFunction factory) {
1216 delete producer_;
1217 producer_ = new FactoryValueProducer(factory);
1218 }
1219
1220 // Unsets the default value for type T.
1221 static void Clear() {
1222 delete producer_;
1223 producer_ = nullptr;
1224 }
1225
1226 // Returns true if and only if the user has set the default value for type T.
1227 static bool IsSet() { return producer_ != nullptr; }
1228
1229 // Returns true if T has a default return value set by the user or there
1230 // exists a built-in default value.
1231 static bool Exists() {
1232 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
1233 }
1234
1235 // Returns the default value for type T if the user has set one;
1236 // otherwise returns the built-in default value. Requires that Exists()
1237 // is true, which ensures that the return value is well-defined.
1238 static T Get() {
1239 return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
1240 : producer_->Produce();
1241 }
1242
1243 private:
1244 class ValueProducer {
1245 public:
1246 virtual ~ValueProducer() {}
1247 virtual T Produce() = 0;
1248 };
1249
1250 class FixedValueProducer : public ValueProducer {
1251 public:
1252 explicit FixedValueProducer(T value) : value_(value) {}
1253 T Produce() override { return value_; }
1254
1255 private:
1256 const T value_;
1257 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
1258 };
1259
1260 class FactoryValueProducer : public ValueProducer {
1261 public:
1262 explicit FactoryValueProducer(FactoryFunction factory)
1263 : factory_(factory) {}
1264 T Produce() override { return factory_(); }
1265
1266 private:
1267 const FactoryFunction factory_;
1268 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
1269 };
1270
1271 static ValueProducer* producer_;
1272 };
1273
1274 // This partial specialization allows a user to set default values for
1275 // reference types.
1276 template <typename T>
1277 class DefaultValue<T&> {
1278 public:
1279 // Sets the default value for type T&.
1280 static void Set(T& x) { // NOLINT
1281 address_ = &x;
1282 }
1283
1284 // Unsets the default value for type T&.
1285 static void Clear() { address_ = nullptr; }
1286
1287 // Returns true if and only if the user has set the default value for type T&.
1288 static bool IsSet() { return address_ != nullptr; }
1289
1290 // Returns true if T has a default return value set by the user or there
1291 // exists a built-in default value.
1292 static bool Exists() {
1293 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
1294 }
1295
1296 // Returns the default value for type T& if the user has set one;
1297 // otherwise returns the built-in default value if there is one;
1298 // otherwise aborts the process.
1299 static T& Get() {
1300 return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
1301 : *address_;
1302 }
1303
1304 private:
1305 static T* address_;
1306 };
1307
1308 // This specialization allows DefaultValue<void>::Get() to
1309 // compile.
1310 template <>
1311 class DefaultValue<void> {
1312 public:
1313 static bool Exists() { return true; }
1314 static void Get() {}
1315 };
1316
1317 // Points to the user-set default value for type T.
1318 template <typename T>
1319 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
1320
1321 // Points to the user-set default value for type T&.
1322 template <typename T>
1323 T* DefaultValue<T&>::address_ = nullptr;
1324
1325 // Implement this interface to define an action for function type F.
1326 template <typename F>
1327 class ActionInterface {
1328 public:
1329 typedef typename internal::Function<F>::Result Result;
1330 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1331
1332 ActionInterface() {}
1333 virtual ~ActionInterface() {}
1334
1335 // Performs the action. This method is not const, as in general an
1336 // action can have side effects and be stateful. For example, a
1337 // get-the-next-element-from-the-collection action will need to
1338 // remember the current element.
1339 virtual Result Perform(const ArgumentTuple& args) = 0;
1340
1341 private:
1342 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
1343 };
1344
1345 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
1346 // object that represents an action to be taken when a mock function
1347 // of type F is called. The implementation of Action<T> is just a
1348 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
1349 // You can view an object implementing ActionInterface<F> as a
1350 // concrete action (including its current state), and an Action<F>
1351 // object as a handle to it.
1352 template <typename F>
1353 class Action {
1354 // Adapter class to allow constructing Action from a legacy ActionInterface.
1355 // New code should create Actions from functors instead.
1356 struct ActionAdapter {
1357 // Adapter must be copyable to satisfy std::function requirements.
1358 ::std::shared_ptr<ActionInterface<F>> impl_;
1359
1360 template <typename... Args>
1361 typename internal::Function<F>::Result operator()(Args&&... args) {
1362 return impl_->Perform(
1363 ::std::forward_as_tuple(::std::forward<Args>(args)...));
1364 }
1365 };
1366
1367 template <typename G>
1368 using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
1369
1370 public:
1371 typedef typename internal::Function<F>::Result Result;
1372 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1373
1374 // Constructs a null Action. Needed for storing Action objects in
1375 // STL containers.
1376 Action() {}
1377
1378 // Construct an Action from a specified callable.
1379 // This cannot take std::function directly, because then Action would not be
1380 // directly constructible from lambda (it would require two conversions).
1381 template <
1382 typename G,
1383 typename = typename std::enable_if<internal::disjunction<
1384 IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
1385 G>>::value>::type>
1386 Action(G&& fun) { // NOLINT
1387 Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
1388 }
1389
1390 // Constructs an Action from its implementation.
1391 explicit Action(ActionInterface<F>* impl)
1392 : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
1393
1394 // This constructor allows us to turn an Action<Func> object into an
1395 // Action<F>, as long as F's arguments can be implicitly converted
1396 // to Func's and Func's return type can be implicitly converted to F's.
1397 template <typename Func>
1398 explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
1399
1400 // Returns true if and only if this is the DoDefault() action.
1401 bool IsDoDefault() const { return fun_ == nullptr; }
1402
1403 // Performs the action. Note that this method is const even though
1404 // the corresponding method in ActionInterface is not. The reason
1405 // is that a const Action<F> means that it cannot be re-bound to
1406 // another concrete action, not that the concrete action it binds to
1407 // cannot change state. (Think of the difference between a const
1408 // pointer and a pointer to const.)
1409 Result Perform(ArgumentTuple args) const {
1410 if (IsDoDefault()) {
1411 internal::IllegalDoDefault(__FILE__, __LINE__);
1412 }
1413 return internal::Apply(fun_, ::std::move(args));
1414 }
1415
1416 private:
1417 template <typename G>
1418 friend class Action;
1419
1420 template <typename G>
1421 void Init(G&& g, ::std::true_type) {
1422 fun_ = ::std::forward<G>(g);
1423 }
1424
1425 template <typename G>
1426 void Init(G&& g, ::std::false_type) {
1427 fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
1428 }
1429
1430 template <typename FunctionImpl>
1431 struct IgnoreArgs {
1432 template <typename... Args>
1433 Result operator()(const Args&...) const {
1434 return function_impl();
1435 }
1436
1437 FunctionImpl function_impl;
1438 };
1439
1440 // fun_ is an empty function if and only if this is the DoDefault() action.
1441 ::std::function<F> fun_;
1442 };
1443
1444 // The PolymorphicAction class template makes it easy to implement a
1445 // polymorphic action (i.e. an action that can be used in mock
1446 // functions of than one type, e.g. Return()).
1447 //
1448 // To define a polymorphic action, a user first provides a COPYABLE
1449 // implementation class that has a Perform() method template:
1450 //
1451 // class FooAction {
1452 // public:
1453 // template <typename Result, typename ArgumentTuple>
1454 // Result Perform(const ArgumentTuple& args) const {
1455 // // Processes the arguments and returns a result, using
1456 // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
1457 // }
1458 // ...
1459 // };
1460 //
1461 // Then the user creates the polymorphic action using
1462 // MakePolymorphicAction(object) where object has type FooAction. See
1463 // the definition of Return(void) and SetArgumentPointee<N>(value) for
1464 // complete examples.
1465 template <typename Impl>
1466 class PolymorphicAction {
1467 public:
1468 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
1469
1470 template <typename F>
1471 operator Action<F>() const {
1472 return Action<F>(new MonomorphicImpl<F>(impl_));
1473 }
1474
1475 private:
1476 template <typename F>
1477 class MonomorphicImpl : public ActionInterface<F> {
1478 public:
1479 typedef typename internal::Function<F>::Result Result;
1480 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1481
1482 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
1483
1484 Result Perform(const ArgumentTuple& args) override {
1485 return impl_.template Perform<Result>(args);
1486 }
1487
1488 private:
1489 Impl impl_;
1490 };
1491
1492 Impl impl_;
1493 };
1494
1495 // Creates an Action from its implementation and returns it. The
1496 // created Action object owns the implementation.
1497 template <typename F>
1498 Action<F> MakeAction(ActionInterface<F>* impl) {
1499 return Action<F>(impl);
1500 }
1501
1502 // Creates a polymorphic action from its implementation. This is
1503 // easier to use than the PolymorphicAction<Impl> constructor as it
1504 // doesn't require you to explicitly write the template argument, e.g.
1505 //
1506 // MakePolymorphicAction(foo);
1507 // vs
1508 // PolymorphicAction<TypeOfFoo>(foo);
1509 template <typename Impl>
1510 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
1511 return PolymorphicAction<Impl>(impl);
1512 }
1513
1514 namespace internal {
1515
1516 // Helper struct to specialize ReturnAction to execute a move instead of a copy
1517 // on return. Useful for move-only types, but could be used on any type.
1518 template <typename T>
1519 struct ByMoveWrapper {
1520 explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
1521 T payload;
1522 };
1523
1524 // Implements the polymorphic Return(x) action, which can be used in
1525 // any function that returns the type of x, regardless of the argument
1526 // types.
1527 //
1528 // Note: The value passed into Return must be converted into
1529 // Function<F>::Result when this action is cast to Action<F> rather than
1530 // when that action is performed. This is important in scenarios like
1531 //
1532 // MOCK_METHOD1(Method, T(U));
1533 // ...
1534 // {
1535 // Foo foo;
1536 // X x(&foo);
1537 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
1538 // }
1539 //
1540 // In the example above the variable x holds reference to foo which leaves
1541 // scope and gets destroyed. If copying X just copies a reference to foo,
1542 // that copy will be left with a hanging reference. If conversion to T
1543 // makes a copy of foo, the above code is safe. To support that scenario, we
1544 // need to make sure that the type conversion happens inside the EXPECT_CALL
1545 // statement, and conversion of the result of Return to Action<T(U)> is a
1546 // good place for that.
1547 //
1548 // The real life example of the above scenario happens when an invocation
1549 // of gtl::Container() is passed into Return.
1550 //
1551 template <typename R>
1552 class ReturnAction {
1553 public:
1554 // Constructs a ReturnAction object from the value to be returned.
1555 // 'value' is passed by value instead of by const reference in order
1556 // to allow Return("string literal") to compile.
1557 explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
1558
1559 // This template type conversion operator allows Return(x) to be
1560 // used in ANY function that returns x's type.
1561 template <typename F>
1562 operator Action<F>() const { // NOLINT
1563 // Assert statement belongs here because this is the best place to verify
1564 // conditions on F. It produces the clearest error messages
1565 // in most compilers.
1566 // Impl really belongs in this scope as a local class but can't
1567 // because MSVC produces duplicate symbols in different translation units
1568 // in this case. Until MS fixes that bug we put Impl into the class scope
1569 // and put the typedef both here (for use in assert statement) and
1570 // in the Impl class. But both definitions must be the same.
1571 typedef typename Function<F>::Result Result;
1572 GTEST_COMPILE_ASSERT_(
1573 !std::is_reference<Result>::value,
1574 use_ReturnRef_instead_of_Return_to_return_a_reference);
1575 static_assert(!std::is_void<Result>::value,
1576 "Can't use Return() on an action expected to return `void`.");
1577 return Action<F>(new Impl<R, F>(value_));
1578 }
1579
1580 private:
1581 // Implements the Return(x) action for a particular function type F.
1582 template <typename R_, typename F>
1583 class Impl : public ActionInterface<F> {
1584 public:
1585 typedef typename Function<F>::Result Result;
1586 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1587
1588 // The implicit cast is necessary when Result has more than one
1589 // single-argument constructor (e.g. Result is std::vector<int>) and R
1590 // has a type conversion operator template. In that case, value_(value)
1591 // won't compile as the compiler doesn't known which constructor of
1592 // Result to call. ImplicitCast_ forces the compiler to convert R to
1593 // Result without considering explicit constructors, thus resolving the
1594 // ambiguity. value_ is then initialized using its copy constructor.
1595 explicit Impl(const std::shared_ptr<R>& value)
1596 : value_before_cast_(*value),
1597 value_(ImplicitCast_<Result>(value_before_cast_)) {}
1598
1599 Result Perform(const ArgumentTuple&) override { return value_; }
1600
1601 private:
1602 GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
1603 Result_cannot_be_a_reference_type);
1604 // We save the value before casting just in case it is being cast to a
1605 // wrapper type.
1606 R value_before_cast_;
1607 Result value_;
1608
1609 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
1610 };
1611
1612 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
1613 // move its contents instead.
1614 template <typename R_, typename F>
1615 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
1616 public:
1617 typedef typename Function<F>::Result Result;
1618 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1619
1620 explicit Impl(const std::shared_ptr<R>& wrapper)
1621 : performed_(false), wrapper_(wrapper) {}
1622
1623 Result Perform(const ArgumentTuple&) override {
1624 GTEST_CHECK_(!performed_)
1625 << "A ByMove() action should only be performed once.";
1626 performed_ = true;
1627 return std::move(wrapper_->payload);
1628 }
1629
1630 private:
1631 bool performed_;
1632 const std::shared_ptr<R> wrapper_;
1633 };
1634
1635 const std::shared_ptr<R> value_;
1636 };
1637
1638 // Implements the ReturnNull() action.
1639 class ReturnNullAction {
1640 public:
1641 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
1642 // this is enforced by returning nullptr, and in non-C++11 by asserting a
1643 // pointer type on compile time.
1644 template <typename Result, typename ArgumentTuple>
1645 static Result Perform(const ArgumentTuple&) {
1646 return nullptr;
1647 }
1648 };
1649
1650 // Implements the Return() action.
1651 class ReturnVoidAction {
1652 public:
1653 // Allows Return() to be used in any void-returning function.
1654 template <typename Result, typename ArgumentTuple>
1655 static void Perform(const ArgumentTuple&) {
1656 static_assert(std::is_void<Result>::value, "Result should be void.");
1657 }
1658 };
1659
1660 // Implements the polymorphic ReturnRef(x) action, which can be used
1661 // in any function that returns a reference to the type of x,
1662 // regardless of the argument types.
1663 template <typename T>
1664 class ReturnRefAction {
1665 public:
1666 // Constructs a ReturnRefAction object from the reference to be returned.
1667 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
1668
1669 // This template type conversion operator allows ReturnRef(x) to be
1670 // used in ANY function that returns a reference to x's type.
1671 template <typename F>
1672 operator Action<F>() const {
1673 typedef typename Function<F>::Result Result;
1674 // Asserts that the function return type is a reference. This
1675 // catches the user error of using ReturnRef(x) when Return(x)
1676 // should be used, and generates some helpful error message.
1677 GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
1678 use_Return_instead_of_ReturnRef_to_return_a_value);
1679 return Action<F>(new Impl<F>(ref_));
1680 }
1681
1682 private:
1683 // Implements the ReturnRef(x) action for a particular function type F.
1684 template <typename F>
1685 class Impl : public ActionInterface<F> {
1686 public:
1687 typedef typename Function<F>::Result Result;
1688 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1689
1690 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
1691
1692 Result Perform(const ArgumentTuple&) override { return ref_; }
1693
1694 private:
1695 T& ref_;
1696 };
1697
1698 T& ref_;
1699 };
1700
1701 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
1702 // used in any function that returns a reference to the type of x,
1703 // regardless of the argument types.
1704 template <typename T>
1705 class ReturnRefOfCopyAction {
1706 public:
1707 // Constructs a ReturnRefOfCopyAction object from the reference to
1708 // be returned.
1709 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
1710
1711 // This template type conversion operator allows ReturnRefOfCopy(x) to be
1712 // used in ANY function that returns a reference to x's type.
1713 template <typename F>
1714 operator Action<F>() const {
1715 typedef typename Function<F>::Result Result;
1716 // Asserts that the function return type is a reference. This
1717 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
1718 // should be used, and generates some helpful error message.
1719 GTEST_COMPILE_ASSERT_(
1720 std::is_reference<Result>::value,
1721 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
1722 return Action<F>(new Impl<F>(value_));
1723 }
1724
1725 private:
1726 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
1727 template <typename F>
1728 class Impl : public ActionInterface<F> {
1729 public:
1730 typedef typename Function<F>::Result Result;
1731 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1732
1733 explicit Impl(const T& value) : value_(value) {} // NOLINT
1734
1735 Result Perform(const ArgumentTuple&) override { return value_; }
1736
1737 private:
1738 T value_;
1739 };
1740
1741 const T value_;
1742 };
1743
1744 // Implements the polymorphic ReturnRoundRobin(v) action, which can be
1745 // used in any function that returns the element_type of v.
1746 template <typename T>
1747 class ReturnRoundRobinAction {
1748 public:
1749 explicit ReturnRoundRobinAction(std::vector<T> values) {
1750 GTEST_CHECK_(!values.empty())
1751 << "ReturnRoundRobin requires at least one element.";
1752 state_->values = std::move(values);
1753 }
1754
1755 template <typename... Args>
1756 T operator()(Args&&...) const {
1757 return state_->Next();
1758 }
1759
1760 private:
1761 struct State {
1762 T Next() {
1763 T ret_val = values[i++];
1764 if (i == values.size()) i = 0;
1765 return ret_val;
1766 }
1767
1768 std::vector<T> values;
1769 size_t i = 0;
1770 };
1771 std::shared_ptr<State> state_ = std::make_shared<State>();
1772 };
1773
1774 // Implements the polymorphic DoDefault() action.
1775 class DoDefaultAction {
1776 public:
1777 // This template type conversion operator allows DoDefault() to be
1778 // used in any function.
1779 template <typename F>
1780 operator Action<F>() const { return Action<F>(); } // NOLINT
1781 };
1782
1783 // Implements the Assign action to set a given pointer referent to a
1784 // particular value.
1785 template <typename T1, typename T2>
1786 class AssignAction {
1787 public:
1788 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
1789
1790 template <typename Result, typename ArgumentTuple>
1791 void Perform(const ArgumentTuple& /* args */) const {
1792 *ptr_ = value_;
1793 }
1794
1795 private:
1796 T1* const ptr_;
1797 const T2 value_;
1798 };
1799
1800 #if !GTEST_OS_WINDOWS_MOBILE
1801
1802 // Implements the SetErrnoAndReturn action to simulate return from
1803 // various system calls and libc functions.
1804 template <typename T>
1805 class SetErrnoAndReturnAction {
1806 public:
1807 SetErrnoAndReturnAction(int errno_value, T result)
1808 : errno_(errno_value),
1809 result_(result) {}
1810 template <typename Result, typename ArgumentTuple>
1811 Result Perform(const ArgumentTuple& /* args */) const {
1812 errno = errno_;
1813 return result_;
1814 }
1815
1816 private:
1817 const int errno_;
1818 const T result_;
1819 };
1820
1821 #endif // !GTEST_OS_WINDOWS_MOBILE
1822
1823 // Implements the SetArgumentPointee<N>(x) action for any function
1824 // whose N-th argument (0-based) is a pointer to x's type.
1825 template <size_t N, typename A, typename = void>
1826 struct SetArgumentPointeeAction {
1827 A value;
1828
1829 template <typename... Args>
1830 void operator()(const Args&... args) const {
1831 *::std::get<N>(std::tie(args...)) = value;
1832 }
1833 };
1834
1835 // Implements the Invoke(object_ptr, &Class::Method) action.
1836 template <class Class, typename MethodPtr>
1837 struct InvokeMethodAction {
1838 Class* const obj_ptr;
1839 const MethodPtr method_ptr;
1840
1841 template <typename... Args>
1842 auto operator()(Args&&... args) const
1843 -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
1844 return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
1845 }
1846 };
1847
1848 // Implements the InvokeWithoutArgs(f) action. The template argument
1849 // FunctionImpl is the implementation type of f, which can be either a
1850 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
1851 // Action<F> as long as f's type is compatible with F.
1852 template <typename FunctionImpl>
1853 struct InvokeWithoutArgsAction {
1854 FunctionImpl function_impl;
1855
1856 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
1857 // compatible with f.
1858 template <typename... Args>
1859 auto operator()(const Args&...) -> decltype(function_impl()) {
1860 return function_impl();
1861 }
1862 };
1863
1864 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
1865 template <class Class, typename MethodPtr>
1866 struct InvokeMethodWithoutArgsAction {
1867 Class* const obj_ptr;
1868 const MethodPtr method_ptr;
1869
1870 using ReturnType =
1871 decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
1872
1873 template <typename... Args>
1874 ReturnType operator()(const Args&...) const {
1875 return (obj_ptr->*method_ptr)();
1876 }
1877 };
1878
1879 // Implements the IgnoreResult(action) action.
1880 template <typename A>
1881 class IgnoreResultAction {
1882 public:
1883 explicit IgnoreResultAction(const A& action) : action_(action) {}
1884
1885 template <typename F>
1886 operator Action<F>() const {
1887 // Assert statement belongs here because this is the best place to verify
1888 // conditions on F. It produces the clearest error messages
1889 // in most compilers.
1890 // Impl really belongs in this scope as a local class but can't
1891 // because MSVC produces duplicate symbols in different translation units
1892 // in this case. Until MS fixes that bug we put Impl into the class scope
1893 // and put the typedef both here (for use in assert statement) and
1894 // in the Impl class. But both definitions must be the same.
1895 typedef typename internal::Function<F>::Result Result;
1896
1897 // Asserts at compile time that F returns void.
1898 static_assert(std::is_void<Result>::value, "Result type should be void.");
1899
1900 return Action<F>(new Impl<F>(action_));
1901 }
1902
1903 private:
1904 template <typename F>
1905 class Impl : public ActionInterface<F> {
1906 public:
1907 typedef typename internal::Function<F>::Result Result;
1908 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1909
1910 explicit Impl(const A& action) : action_(action) {}
1911
1912 void Perform(const ArgumentTuple& args) override {
1913 // Performs the action and ignores its result.
1914 action_.Perform(args);
1915 }
1916
1917 private:
1918 // Type OriginalFunction is the same as F except that its return
1919 // type is IgnoredValue.
1920 typedef typename internal::Function<F>::MakeResultIgnoredValue
1921 OriginalFunction;
1922
1923 const Action<OriginalFunction> action_;
1924 };
1925
1926 const A action_;
1927 };
1928
1929 template <typename InnerAction, size_t... I>
1930 struct WithArgsAction {
1931 InnerAction action;
1932
1933 // The inner action could be anything convertible to Action<X>.
1934 // We use the conversion operator to detect the signature of the inner Action.
1935 template <typename R, typename... Args>
1936 operator Action<R(Args...)>() const { // NOLINT
1937 using TupleType = std::tuple<Args...>;
1938 Action<R(typename std::tuple_element<I, TupleType>::type...)>
1939 converted(action);
1940
1941 return [converted](Args... args) -> R {
1942 return converted.Perform(std::forward_as_tuple(
1943 std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
1944 };
1945 }
1946 };
1947
1948 template <typename... Actions>
1949 struct DoAllAction {
1950 private:
1951 template <typename T>
1952 using NonFinalType =
1953 typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
1954
1955 template <typename ActionT, size_t... I>
1956 std::vector<ActionT> Convert(IndexSequence<I...>) const {
1957 return {ActionT(std::get<I>(actions))...};
1958 }
1959
1960 public:
1961 std::tuple<Actions...> actions;
1962
1963 template <typename R, typename... Args>
1964 operator Action<R(Args...)>() const { // NOLINT
1965 struct Op {
1966 std::vector<Action<void(NonFinalType<Args>...)>> converted;
1967 Action<R(Args...)> last;
1968 R operator()(Args... args) const {
1969 auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
1970 for (auto& a : converted) {
1971 a.Perform(tuple_args);
1972 }
1973 return last.Perform(std::move(tuple_args));
1974 }
1975 };
1976 return Op{Convert<Action<void(NonFinalType<Args>...)>>(
1977 MakeIndexSequence<sizeof...(Actions) - 1>()),
1978 std::get<sizeof...(Actions) - 1>(actions)};
1979 }
1980 };
1981
1982 template <typename T, typename... Params>
1983 struct ReturnNewAction {
1984 T* operator()() const {
1985 return internal::Apply(
1986 [](const Params&... unpacked_params) {
1987 return new T(unpacked_params...);
1988 },
1989 params);
1990 }
1991 std::tuple<Params...> params;
1992 };
1993
1994 template <size_t k>
1995 struct ReturnArgAction {
1996 template <typename... Args>
1997 auto operator()(const Args&... args) const ->
1998 typename std::tuple_element<k, std::tuple<Args...>>::type {
1999 return std::get<k>(std::tie(args...));
2000 }
2001 };
2002
2003 template <size_t k, typename Ptr>
2004 struct SaveArgAction {
2005 Ptr pointer;
2006
2007 template <typename... Args>
2008 void operator()(const Args&... args) const {
2009 *pointer = std::get<k>(std::tie(args...));
2010 }
2011 };
2012
2013 template <size_t k, typename Ptr>
2014 struct SaveArgPointeeAction {
2015 Ptr pointer;
2016
2017 template <typename... Args>
2018 void operator()(const Args&... args) const {
2019 *pointer = *std::get<k>(std::tie(args...));
2020 }
2021 };
2022
2023 template <size_t k, typename T>
2024 struct SetArgRefereeAction {
2025 T value;
2026
2027 template <typename... Args>
2028 void operator()(Args&&... args) const {
2029 using argk_type =
2030 typename ::std::tuple_element<k, std::tuple<Args...>>::type;
2031 static_assert(std::is_lvalue_reference<argk_type>::value,
2032 "Argument must be a reference type.");
2033 std::get<k>(std::tie(args...)) = value;
2034 }
2035 };
2036
2037 template <size_t k, typename I1, typename I2>
2038 struct SetArrayArgumentAction {
2039 I1 first;
2040 I2 last;
2041
2042 template <typename... Args>
2043 void operator()(const Args&... args) const {
2044 auto value = std::get<k>(std::tie(args...));
2045 for (auto it = first; it != last; ++it, (void)++value) {
2046 *value = *it;
2047 }
2048 }
2049 };
2050
2051 template <size_t k>
2052 struct DeleteArgAction {
2053 template <typename... Args>
2054 void operator()(const Args&... args) const {
2055 delete std::get<k>(std::tie(args...));
2056 }
2057 };
2058
2059 template <typename Ptr>
2060 struct ReturnPointeeAction {
2061 Ptr pointer;
2062 template <typename... Args>
2063 auto operator()(const Args&...) const -> decltype(*pointer) {
2064 return *pointer;
2065 }
2066 };
2067
2068 #if GTEST_HAS_EXCEPTIONS
2069 template <typename T>
2070 struct ThrowAction {
2071 T exception;
2072 // We use a conversion operator to adapt to any return type.
2073 template <typename R, typename... Args>
2074 operator Action<R(Args...)>() const { // NOLINT
2075 T copy = exception;
2076 return [copy](Args...) -> R { throw copy; };
2077 }
2078 };
2079 #endif // GTEST_HAS_EXCEPTIONS
2080
2081 } // namespace internal
2082
2083 // An Unused object can be implicitly constructed from ANY value.
2084 // This is handy when defining actions that ignore some or all of the
2085 // mock function arguments. For example, given
2086 //
2087 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
2088 // MOCK_METHOD3(Bar, double(int index, double x, double y));
2089 //
2090 // instead of
2091 //
2092 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
2093 // return sqrt(x*x + y*y);
2094 // }
2095 // double DistanceToOriginWithIndex(int index, double x, double y) {
2096 // return sqrt(x*x + y*y);
2097 // }
2098 // ...
2099 // EXPECT_CALL(mock, Foo("abc", _, _))
2100 // .WillOnce(Invoke(DistanceToOriginWithLabel));
2101 // EXPECT_CALL(mock, Bar(5, _, _))
2102 // .WillOnce(Invoke(DistanceToOriginWithIndex));
2103 //
2104 // you could write
2105 //
2106 // // We can declare any uninteresting argument as Unused.
2107 // double DistanceToOrigin(Unused, double x, double y) {
2108 // return sqrt(x*x + y*y);
2109 // }
2110 // ...
2111 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
2112 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
2113 typedef internal::IgnoredValue Unused;
2114
2115 // Creates an action that does actions a1, a2, ..., sequentially in
2116 // each invocation. All but the last action will have a readonly view of the
2117 // arguments.
2118 template <typename... Action>
2119 internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
2120 Action&&... action) {
2121 return {std::forward_as_tuple(std::forward<Action>(action)...)};
2122 }
2123
2124 // WithArg<k>(an_action) creates an action that passes the k-th
2125 // (0-based) argument of the mock function to an_action and performs
2126 // it. It adapts an action accepting one argument to one that accepts
2127 // multiple arguments. For convenience, we also provide
2128 // WithArgs<k>(an_action) (defined below) as a synonym.
2129 template <size_t k, typename InnerAction>
2130 internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
2131 WithArg(InnerAction&& action) {
2132 return {std::forward<InnerAction>(action)};
2133 }
2134
2135 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
2136 // the selected arguments of the mock function to an_action and
2137 // performs it. It serves as an adaptor between actions with
2138 // different argument lists.
2139 template <size_t k, size_t... ks, typename InnerAction>
2140 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
2141 WithArgs(InnerAction&& action) {
2142 return {std::forward<InnerAction>(action)};
2143 }
2144
2145 // WithoutArgs(inner_action) can be used in a mock function with a
2146 // non-empty argument list to perform inner_action, which takes no
2147 // argument. In other words, it adapts an action accepting no
2148 // argument to one that accepts (and ignores) arguments.
2149 template <typename InnerAction>
2150 internal::WithArgsAction<typename std::decay<InnerAction>::type>
2151 WithoutArgs(InnerAction&& action) {
2152 return {std::forward<InnerAction>(action)};
2153 }
2154
2155 // Creates an action that returns 'value'. 'value' is passed by value
2156 // instead of const reference - otherwise Return("string literal")
2157 // will trigger a compiler error about using array as initializer.
2158 template <typename R>
2159 internal::ReturnAction<R> Return(R value) {
2160 return internal::ReturnAction<R>(std::move(value));
2161 }
2162
2163 // Creates an action that returns NULL.
2164 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
2165 return MakePolymorphicAction(internal::ReturnNullAction());
2166 }
2167
2168 // Creates an action that returns from a void function.
2169 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
2170 return MakePolymorphicAction(internal::ReturnVoidAction());
2171 }
2172
2173 // Creates an action that returns the reference to a variable.
2174 template <typename R>
2175 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
2176 return internal::ReturnRefAction<R>(x);
2177 }
2178
2179 // Prevent using ReturnRef on reference to temporary.
2180 template <typename R, R* = nullptr>
2181 internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
2182
2183 // Creates an action that returns the reference to a copy of the
2184 // argument. The copy is created when the action is constructed and
2185 // lives as long as the action.
2186 template <typename R>
2187 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
2188 return internal::ReturnRefOfCopyAction<R>(x);
2189 }
2190
2191 // Modifies the parent action (a Return() action) to perform a move of the
2192 // argument instead of a copy.
2193 // Return(ByMove()) actions can only be executed once and will assert this
2194 // invariant.
2195 template <typename R>
2196 internal::ByMoveWrapper<R> ByMove(R x) {
2197 return internal::ByMoveWrapper<R>(std::move(x));
2198 }
2199
2200 // Creates an action that returns an element of `vals`. Calling this action will
2201 // repeatedly return the next value from `vals` until it reaches the end and
2202 // will restart from the beginning.
2203 template <typename T>
2204 internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
2205 return internal::ReturnRoundRobinAction<T>(std::move(vals));
2206 }
2207
2208 // Creates an action that returns an element of `vals`. Calling this action will
2209 // repeatedly return the next value from `vals` until it reaches the end and
2210 // will restart from the beginning.
2211 template <typename T>
2212 internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
2213 std::initializer_list<T> vals) {
2214 return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
2215 }
2216
2217 // Creates an action that does the default action for the give mock function.
2218 inline internal::DoDefaultAction DoDefault() {
2219 return internal::DoDefaultAction();
2220 }
2221
2222 // Creates an action that sets the variable pointed by the N-th
2223 // (0-based) function argument to 'value'.
2224 template <size_t N, typename T>
2225 internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
2226 return {std::move(value)};
2227 }
2228
2229 // The following version is DEPRECATED.
2230 template <size_t N, typename T>
2231 internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
2232 return {std::move(value)};
2233 }
2234
2235 // Creates an action that sets a pointer referent to a given value.
2236 template <typename T1, typename T2>
2237 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
2238 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
2239 }
2240
2241 #if !GTEST_OS_WINDOWS_MOBILE
2242
2243 // Creates an action that sets errno and returns the appropriate error.
2244 template <typename T>
2245 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
2246 SetErrnoAndReturn(int errval, T result) {
2247 return MakePolymorphicAction(
2248 internal::SetErrnoAndReturnAction<T>(errval, result));
2249 }
2250
2251 #endif // !GTEST_OS_WINDOWS_MOBILE
2252
2253 // Various overloads for Invoke().
2254
2255 // Legacy function.
2256 // Actions can now be implicitly constructed from callables. No need to create
2257 // wrapper objects.
2258 // This function exists for backwards compatibility.
2259 template <typename FunctionImpl>
2260 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
2261 return std::forward<FunctionImpl>(function_impl);
2262 }
2263
2264 // Creates an action that invokes the given method on the given object
2265 // with the mock function's arguments.
2266 template <class Class, typename MethodPtr>
2267 internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
2268 MethodPtr method_ptr) {
2269 return {obj_ptr, method_ptr};
2270 }
2271
2272 // Creates an action that invokes 'function_impl' with no argument.
2273 template <typename FunctionImpl>
2274 internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
2275 InvokeWithoutArgs(FunctionImpl function_impl) {
2276 return {std::move(function_impl)};
2277 }
2278
2279 // Creates an action that invokes the given method on the given object
2280 // with no argument.
2281 template <class Class, typename MethodPtr>
2282 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
2283 Class* obj_ptr, MethodPtr method_ptr) {
2284 return {obj_ptr, method_ptr};
2285 }
2286
2287 // Creates an action that performs an_action and throws away its
2288 // result. In other words, it changes the return type of an_action to
2289 // void. an_action MUST NOT return void, or the code won't compile.
2290 template <typename A>
2291 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
2292 return internal::IgnoreResultAction<A>(an_action);
2293 }
2294
2295 // Creates a reference wrapper for the given L-value. If necessary,
2296 // you can explicitly specify the type of the reference. For example,
2297 // suppose 'derived' is an object of type Derived, ByRef(derived)
2298 // would wrap a Derived&. If you want to wrap a const Base& instead,
2299 // where Base is a base class of Derived, just write:
2300 //
2301 // ByRef<const Base>(derived)
2302 //
2303 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
2304 // However, it may still be used for consistency with ByMove().
2305 template <typename T>
2306 inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
2307 return ::std::reference_wrapper<T>(l_value);
2308 }
2309
2310 // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
2311 // instance of type T, constructed on the heap with constructor arguments
2312 // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
2313 template <typename T, typename... Params>
2314 internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
2315 Params&&... params) {
2316 return {std::forward_as_tuple(std::forward<Params>(params)...)};
2317 }
2318
2319 // Action ReturnArg<k>() returns the k-th argument of the mock function.
2320 template <size_t k>
2321 internal::ReturnArgAction<k> ReturnArg() {
2322 return {};
2323 }
2324
2325 // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
2326 // mock function to *pointer.
2327 template <size_t k, typename Ptr>
2328 internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
2329 return {pointer};
2330 }
2331
2332 // Action SaveArgPointee<k>(pointer) saves the value pointed to
2333 // by the k-th (0-based) argument of the mock function to *pointer.
2334 template <size_t k, typename Ptr>
2335 internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
2336 return {pointer};
2337 }
2338
2339 // Action SetArgReferee<k>(value) assigns 'value' to the variable
2340 // referenced by the k-th (0-based) argument of the mock function.
2341 template <size_t k, typename T>
2342 internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
2343 T&& value) {
2344 return {std::forward<T>(value)};
2345 }
2346
2347 // Action SetArrayArgument<k>(first, last) copies the elements in
2348 // source range [first, last) to the array pointed to by the k-th
2349 // (0-based) argument, which can be either a pointer or an
2350 // iterator. The action does not take ownership of the elements in the
2351 // source range.
2352 template <size_t k, typename I1, typename I2>
2353 internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
2354 I2 last) {
2355 return {first, last};
2356 }
2357
2358 // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
2359 // function.
2360 template <size_t k>
2361 internal::DeleteArgAction<k> DeleteArg() {
2362 return {};
2363 }
2364
2365 // This action returns the value pointed to by 'pointer'.
2366 template <typename Ptr>
2367 internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
2368 return {pointer};
2369 }
2370
2371 // Action Throw(exception) can be used in a mock function of any type
2372 // to throw the given exception. Any copyable value can be thrown.
2373 #if GTEST_HAS_EXCEPTIONS
2374 template <typename T>
2375 internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
2376 return {std::forward<T>(exception)};
2377 }
2378 #endif // GTEST_HAS_EXCEPTIONS
2379
2380 namespace internal {
2381
2382 // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
2383 // defines an action that can be used in a mock function. Typically,
2384 // these actions only care about a subset of the arguments of the mock
2385 // function. For example, if such an action only uses the second
2386 // argument, it can be used in any mock function that takes >= 2
2387 // arguments where the type of the second argument is compatible.
2388 //
2389 // Therefore, the action implementation must be prepared to take more
2390 // arguments than it needs. The ExcessiveArg type is used to
2391 // represent those excessive arguments. In order to keep the compiler
2392 // error messages tractable, we define it in the testing namespace
2393 // instead of testing::internal. However, this is an INTERNAL TYPE
2394 // and subject to change without notice, so a user MUST NOT USE THIS
2395 // TYPE DIRECTLY.
2396 struct ExcessiveArg {};
2397
2398 // Builds an implementation of an Action<> for some particular signature, using
2399 // a class defined by an ACTION* macro.
2400 template <typename F, typename Impl> struct ActionImpl;
2401
2402 template <typename Impl>
2403 struct ImplBase {
2404 struct Holder {
2405 // Allows each copy of the Action<> to get to the Impl.
2406 explicit operator const Impl&() const { return *ptr; }
2407 std::shared_ptr<Impl> ptr;
2408 };
2409 using type = typename std::conditional<std::is_constructible<Impl>::value,
2410 Impl, Holder>::type;
2411 };
2412
2413 template <typename R, typename... Args, typename Impl>
2414 struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
2415 using Base = typename ImplBase<Impl>::type;
2416 using function_type = R(Args...);
2417 using args_type = std::tuple<Args...>;
2418
2419 ActionImpl() = default; // Only defined if appropriate for Base.
2420 explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { }
2421
2422 R operator()(Args&&... arg) const {
2423 static constexpr size_t kMaxArgs =
2424 sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
2425 return Apply(MakeIndexSequence<kMaxArgs>{},
2426 MakeIndexSequence<10 - kMaxArgs>{},
2427 args_type{std::forward<Args>(arg)...});
2428 }
2429
2430 template <std::size_t... arg_id, std::size_t... excess_id>
2431 R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
2432 const args_type& args) const {
2433 // Impl need not be specific to the signature of action being implemented;
2434 // only the implementing function body needs to have all of the specific
2435 // types instantiated. Up to 10 of the args that are provided by the
2436 // args_type get passed, followed by a dummy of unspecified type for the
2437 // remainder up to 10 explicit args.
2438 static constexpr ExcessiveArg kExcessArg{};
2439 return static_cast<const Impl&>(*this).template gmock_PerformImpl<
2440 /*function_type=*/function_type, /*return_type=*/R,
2441 /*args_type=*/args_type,
2442 /*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
2443 /*args=*/args, std::get<arg_id>(args)...,
2444 ((void)excess_id, kExcessArg)...);
2445 }
2446 };
2447
2448 // Stores a default-constructed Impl as part of the Action<>'s
2449 // std::function<>. The Impl should be trivial to copy.
2450 template <typename F, typename Impl>
2451 ::testing::Action<F> MakeAction() {
2452 return ::testing::Action<F>(ActionImpl<F, Impl>());
2453 }
2454
2455 // Stores just the one given instance of Impl.
2456 template <typename F, typename Impl>
2457 ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
2458 return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
2459 }
2460
2461 #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
2462 , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
2463 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
2464 const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
2465 GMOCK_INTERNAL_ARG_UNUSED, , 10)
2466
2467 #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
2468 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
2469 const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
2470
2471 #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
2472 #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
2473 GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
2474
2475 #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
2476 #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
2477 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
2478
2479 #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
2480 #define GMOCK_ACTION_TYPE_PARAMS_(params) \
2481 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
2482
2483 #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
2484 , param##_type gmock_p##i
2485 #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
2486 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
2487
2488 #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
2489 , std::forward<param##_type>(gmock_p##i)
2490 #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
2491 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
2492
2493 #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
2494 , param(::std::forward<param##_type>(gmock_p##i))
2495 #define GMOCK_ACTION_INIT_PARAMS_(params) \
2496 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
2497
2498 #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
2499 #define GMOCK_ACTION_FIELD_PARAMS_(params) \
2500 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
2501
2502 #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
2503 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2504 class full_name { \
2505 public: \
2506 explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
2507 : impl_(std::make_shared<gmock_Impl>( \
2508 GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \
2509 full_name(const full_name&) = default; \
2510 full_name(full_name&&) noexcept = default; \
2511 template <typename F> \
2512 operator ::testing::Action<F>() const { \
2513 return ::testing::internal::MakeAction<F>(impl_); \
2514 } \
2515 private: \
2516 class gmock_Impl { \
2517 public: \
2518 explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
2519 : GMOCK_ACTION_INIT_PARAMS_(params) {} \
2520 template <typename function_type, typename return_type, \
2521 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2522 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
2523 GMOCK_ACTION_FIELD_PARAMS_(params) \
2524 }; \
2525 std::shared_ptr<const gmock_Impl> impl_; \
2526 }; \
2527 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2528 inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
2529 GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
2530 return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
2531 GMOCK_ACTION_GVALUE_PARAMS_(params)); \
2532 } \
2533 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2534 template <typename function_type, typename return_type, typename args_type, \
2535 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2536 return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \
2537 gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2538
2539 } // namespace internal
2540
2541 // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
2542 #define ACTION(name) \
2543 class name##Action { \
2544 public: \
2545 explicit name##Action() noexcept {} \
2546 name##Action(const name##Action&) noexcept {} \
2547 template <typename F> \
2548 operator ::testing::Action<F>() const { \
2549 return ::testing::internal::MakeAction<F, gmock_Impl>(); \
2550 } \
2551 private: \
2552 class gmock_Impl { \
2553 public: \
2554 template <typename function_type, typename return_type, \
2555 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2556 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
2557 }; \
2558 }; \
2559 inline name##Action name() GTEST_MUST_USE_RESULT_; \
2560 inline name##Action name() { return name##Action(); } \
2561 template <typename function_type, typename return_type, typename args_type, \
2562 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2563 return_type name##Action::gmock_Impl::gmock_PerformImpl( \
2564 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2565
2566 #define ACTION_P(name, ...) \
2567 GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
2568
2569 #define ACTION_P2(name, ...) \
2570 GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
2571
2572 #define ACTION_P3(name, ...) \
2573 GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
2574
2575 #define ACTION_P4(name, ...) \
2576 GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
2577
2578 #define ACTION_P5(name, ...) \
2579 GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
2580
2581 #define ACTION_P6(name, ...) \
2582 GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
2583
2584 #define ACTION_P7(name, ...) \
2585 GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
2586
2587 #define ACTION_P8(name, ...) \
2588 GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
2589
2590 #define ACTION_P9(name, ...) \
2591 GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
2592
2593 #define ACTION_P10(name, ...) \
2594 GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
2595
2596 } // namespace testing
2597
2598 #ifdef _MSC_VER
2599 # pragma warning(pop)
2600 #endif
2601
2602 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
2603 // Copyright 2007, Google Inc.
2604 // All rights reserved.
2605 //
2606 // Redistribution and use in source and binary forms, with or without
2607 // modification, are permitted provided that the following conditions are
2608 // met:
2609 //
2610 // * Redistributions of source code must retain the above copyright
2611 // notice, this list of conditions and the following disclaimer.
2612 // * Redistributions in binary form must reproduce the above
2613 // copyright notice, this list of conditions and the following disclaimer
2614 // in the documentation and/or other materials provided with the
2615 // distribution.
2616 // * Neither the name of Google Inc. nor the names of its
2617 // contributors may be used to endorse or promote products derived from
2618 // this software without specific prior written permission.
2619 //
2620 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2621 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2622 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2623 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2624 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2625 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2626 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2627 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2628 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2629 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2630 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2631
2632
2633 // Google Mock - a framework for writing C++ mock classes.
2634 //
2635 // This file implements some commonly used cardinalities. More
2636 // cardinalities can be defined by the user implementing the
2637 // CardinalityInterface interface if necessary.
2638
2639 // GOOGLETEST_CM0002 DO NOT DELETE
2640
2641 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
2642 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
2643
2644 #include <limits.h>
2645 #include <memory>
2646 #include <ostream> // NOLINT
2647
2648 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
2649 /* class A needs to have dll-interface to be used by clients of class B */)
2650
2651 namespace testing {
2652
2653 // To implement a cardinality Foo, define:
2654 // 1. a class FooCardinality that implements the
2655 // CardinalityInterface interface, and
2656 // 2. a factory function that creates a Cardinality object from a
2657 // const FooCardinality*.
2658 //
2659 // The two-level delegation design follows that of Matcher, providing
2660 // consistency for extension developers. It also eases ownership
2661 // management as Cardinality objects can now be copied like plain values.
2662
2663 // The implementation of a cardinality.
2664 class CardinalityInterface {
2665 public:
2666 virtual ~CardinalityInterface() {}
2667
2668 // Conservative estimate on the lower/upper bound of the number of
2669 // calls allowed.
2670 virtual int ConservativeLowerBound() const { return 0; }
2671 virtual int ConservativeUpperBound() const { return INT_MAX; }
2672
2673 // Returns true if and only if call_count calls will satisfy this
2674 // cardinality.
2675 virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
2676
2677 // Returns true if and only if call_count calls will saturate this
2678 // cardinality.
2679 virtual bool IsSaturatedByCallCount(int call_count) const = 0;
2680
2681 // Describes self to an ostream.
2682 virtual void DescribeTo(::std::ostream* os) const = 0;
2683 };
2684
2685 // A Cardinality is a copyable and IMMUTABLE (except by assignment)
2686 // object that specifies how many times a mock function is expected to
2687 // be called. The implementation of Cardinality is just a std::shared_ptr
2688 // to const CardinalityInterface. Don't inherit from Cardinality!
2689 class GTEST_API_ Cardinality {
2690 public:
2691 // Constructs a null cardinality. Needed for storing Cardinality
2692 // objects in STL containers.
2693 Cardinality() {}
2694
2695 // Constructs a Cardinality from its implementation.
2696 explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
2697
2698 // Conservative estimate on the lower/upper bound of the number of
2699 // calls allowed.
2700 int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
2701 int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
2702
2703 // Returns true if and only if call_count calls will satisfy this
2704 // cardinality.
2705 bool IsSatisfiedByCallCount(int call_count) const {
2706 return impl_->IsSatisfiedByCallCount(call_count);
2707 }
2708
2709 // Returns true if and only if call_count calls will saturate this
2710 // cardinality.
2711 bool IsSaturatedByCallCount(int call_count) const {
2712 return impl_->IsSaturatedByCallCount(call_count);
2713 }
2714
2715 // Returns true if and only if call_count calls will over-saturate this
2716 // cardinality, i.e. exceed the maximum number of allowed calls.
2717 bool IsOverSaturatedByCallCount(int call_count) const {
2718 return impl_->IsSaturatedByCallCount(call_count) &&
2719 !impl_->IsSatisfiedByCallCount(call_count);
2720 }
2721
2722 // Describes self to an ostream
2723 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
2724
2725 // Describes the given actual call count to an ostream.
2726 static void DescribeActualCallCountTo(int actual_call_count,
2727 ::std::ostream* os);
2728
2729 private:
2730 std::shared_ptr<const CardinalityInterface> impl_;
2731 };
2732
2733 // Creates a cardinality that allows at least n calls.
2734 GTEST_API_ Cardinality AtLeast(int n);
2735
2736 // Creates a cardinality that allows at most n calls.
2737 GTEST_API_ Cardinality AtMost(int n);
2738
2739 // Creates a cardinality that allows any number of calls.
2740 GTEST_API_ Cardinality AnyNumber();
2741
2742 // Creates a cardinality that allows between min and max calls.
2743 GTEST_API_ Cardinality Between(int min, int max);
2744
2745 // Creates a cardinality that allows exactly n calls.
2746 GTEST_API_ Cardinality Exactly(int n);
2747
2748 // Creates a cardinality from its implementation.
2749 inline Cardinality MakeCardinality(const CardinalityInterface* c) {
2750 return Cardinality(c);
2751 }
2752
2753 } // namespace testing
2754
2755 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2756
2757 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
2758 // Copyright 2007, Google Inc.
2759 // All rights reserved.
2760 //
2761 // Redistribution and use in source and binary forms, with or without
2762 // modification, are permitted provided that the following conditions are
2763 // met:
2764 //
2765 // * Redistributions of source code must retain the above copyright
2766 // notice, this list of conditions and the following disclaimer.
2767 // * Redistributions in binary form must reproduce the above
2768 // copyright notice, this list of conditions and the following disclaimer
2769 // in the documentation and/or other materials provided with the
2770 // distribution.
2771 // * Neither the name of Google Inc. nor the names of its
2772 // contributors may be used to endorse or promote products derived from
2773 // this software without specific prior written permission.
2774 //
2775 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2776 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2777 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2778 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2779 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2780 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2781 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2782 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2783 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2784 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2785 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2786
2787 // Google Mock - a framework for writing C++ mock classes.
2788 //
2789 // This file implements MOCK_METHOD.
2790
2791 // GOOGLETEST_CM0002 DO NOT DELETE
2792
2793 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
2794 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
2795
2796 #include <type_traits> // IWYU pragma: keep
2797 #include <utility> // IWYU pragma: keep
2798
2799 // Copyright 2007, Google Inc.
2800 // All rights reserved.
2801 //
2802 // Redistribution and use in source and binary forms, with or without
2803 // modification, are permitted provided that the following conditions are
2804 // met:
2805 //
2806 // * Redistributions of source code must retain the above copyright
2807 // notice, this list of conditions and the following disclaimer.
2808 // * Redistributions in binary form must reproduce the above
2809 // copyright notice, this list of conditions and the following disclaimer
2810 // in the documentation and/or other materials provided with the
2811 // distribution.
2812 // * Neither the name of Google Inc. nor the names of its
2813 // contributors may be used to endorse or promote products derived from
2814 // this software without specific prior written permission.
2815 //
2816 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2817 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2818 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2819 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2820 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2821 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2822 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2823 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2824 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2825 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2826 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2827
2828
2829 // Google Mock - a framework for writing C++ mock classes.
2830 //
2831 // This file implements the ON_CALL() and EXPECT_CALL() macros.
2832 //
2833 // A user can use the ON_CALL() macro to specify the default action of
2834 // a mock method. The syntax is:
2835 //
2836 // ON_CALL(mock_object, Method(argument-matchers))
2837 // .With(multi-argument-matcher)
2838 // .WillByDefault(action);
2839 //
2840 // where the .With() clause is optional.
2841 //
2842 // A user can use the EXPECT_CALL() macro to specify an expectation on
2843 // a mock method. The syntax is:
2844 //
2845 // EXPECT_CALL(mock_object, Method(argument-matchers))
2846 // .With(multi-argument-matchers)
2847 // .Times(cardinality)
2848 // .InSequence(sequences)
2849 // .After(expectations)
2850 // .WillOnce(action)
2851 // .WillRepeatedly(action)
2852 // .RetiresOnSaturation();
2853 //
2854 // where all clauses are optional, and .InSequence()/.After()/
2855 // .WillOnce() can appear any number of times.
2856
2857 // GOOGLETEST_CM0002 DO NOT DELETE
2858
2859 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
2860 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
2861
2862 #include <functional>
2863 #include <map>
2864 #include <memory>
2865 #include <set>
2866 #include <sstream>
2867 #include <string>
2868 #include <type_traits>
2869 #include <utility>
2870 #include <vector>
2871 // Copyright 2007, Google Inc.
2872 // All rights reserved.
2873 //
2874 // Redistribution and use in source and binary forms, with or without
2875 // modification, are permitted provided that the following conditions are
2876 // met:
2877 //
2878 // * Redistributions of source code must retain the above copyright
2879 // notice, this list of conditions and the following disclaimer.
2880 // * Redistributions in binary form must reproduce the above
2881 // copyright notice, this list of conditions and the following disclaimer
2882 // in the documentation and/or other materials provided with the
2883 // distribution.
2884 // * Neither the name of Google Inc. nor the names of its
2885 // contributors may be used to endorse or promote products derived from
2886 // this software without specific prior written permission.
2887 //
2888 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2889 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2890 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2891 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2892 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2893 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2894 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2895 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2896 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2897 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2898 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2899
2900
2901 // Google Mock - a framework for writing C++ mock classes.
2902 //
2903 // The MATCHER* family of macros can be used in a namespace scope to
2904 // define custom matchers easily.
2905 //
2906 // Basic Usage
2907 // ===========
2908 //
2909 // The syntax
2910 //
2911 // MATCHER(name, description_string) { statements; }
2912 //
2913 // defines a matcher with the given name that executes the statements,
2914 // which must return a bool to indicate if the match succeeds. Inside
2915 // the statements, you can refer to the value being matched by 'arg',
2916 // and refer to its type by 'arg_type'.
2917 //
2918 // The description string documents what the matcher does, and is used
2919 // to generate the failure message when the match fails. Since a
2920 // MATCHER() is usually defined in a header file shared by multiple
2921 // C++ source files, we require the description to be a C-string
2922 // literal to avoid possible side effects. It can be empty, in which
2923 // case we'll use the sequence of words in the matcher name as the
2924 // description.
2925 //
2926 // For example:
2927 //
2928 // MATCHER(IsEven, "") { return (arg % 2) == 0; }
2929 //
2930 // allows you to write
2931 //
2932 // // Expects mock_foo.Bar(n) to be called where n is even.
2933 // EXPECT_CALL(mock_foo, Bar(IsEven()));
2934 //
2935 // or,
2936 //
2937 // // Verifies that the value of some_expression is even.
2938 // EXPECT_THAT(some_expression, IsEven());
2939 //
2940 // If the above assertion fails, it will print something like:
2941 //
2942 // Value of: some_expression
2943 // Expected: is even
2944 // Actual: 7
2945 //
2946 // where the description "is even" is automatically calculated from the
2947 // matcher name IsEven.
2948 //
2949 // Argument Type
2950 // =============
2951 //
2952 // Note that the type of the value being matched (arg_type) is
2953 // determined by the context in which you use the matcher and is
2954 // supplied to you by the compiler, so you don't need to worry about
2955 // declaring it (nor can you). This allows the matcher to be
2956 // polymorphic. For example, IsEven() can be used to match any type
2957 // where the value of "(arg % 2) == 0" can be implicitly converted to
2958 // a bool. In the "Bar(IsEven())" example above, if method Bar()
2959 // takes an int, 'arg_type' will be int; if it takes an unsigned long,
2960 // 'arg_type' will be unsigned long; and so on.
2961 //
2962 // Parameterizing Matchers
2963 // =======================
2964 //
2965 // Sometimes you'll want to parameterize the matcher. For that you
2966 // can use another macro:
2967 //
2968 // MATCHER_P(name, param_name, description_string) { statements; }
2969 //
2970 // For example:
2971 //
2972 // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2973 //
2974 // will allow you to write:
2975 //
2976 // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2977 //
2978 // which may lead to this message (assuming n is 10):
2979 //
2980 // Value of: Blah("a")
2981 // Expected: has absolute value 10
2982 // Actual: -9
2983 //
2984 // Note that both the matcher description and its parameter are
2985 // printed, making the message human-friendly.
2986 //
2987 // In the matcher definition body, you can write 'foo_type' to
2988 // reference the type of a parameter named 'foo'. For example, in the
2989 // body of MATCHER_P(HasAbsoluteValue, value) above, you can write
2990 // 'value_type' to refer to the type of 'value'.
2991 //
2992 // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
2993 // support multi-parameter matchers.
2994 //
2995 // Describing Parameterized Matchers
2996 // =================================
2997 //
2998 // The last argument to MATCHER*() is a string-typed expression. The
2999 // expression can reference all of the matcher's parameters and a
3000 // special bool-typed variable named 'negation'. When 'negation' is
3001 // false, the expression should evaluate to the matcher's description;
3002 // otherwise it should evaluate to the description of the negation of
3003 // the matcher. For example,
3004 //
3005 // using testing::PrintToString;
3006 //
3007 // MATCHER_P2(InClosedRange, low, hi,
3008 // std::string(negation ? "is not" : "is") + " in range [" +
3009 // PrintToString(low) + ", " + PrintToString(hi) + "]") {
3010 // return low <= arg && arg <= hi;
3011 // }
3012 // ...
3013 // EXPECT_THAT(3, InClosedRange(4, 6));
3014 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
3015 //
3016 // would generate two failures that contain the text:
3017 //
3018 // Expected: is in range [4, 6]
3019 // ...
3020 // Expected: is not in range [2, 4]
3021 //
3022 // If you specify "" as the description, the failure message will
3023 // contain the sequence of words in the matcher name followed by the
3024 // parameter values printed as a tuple. For example,
3025 //
3026 // MATCHER_P2(InClosedRange, low, hi, "") { ... }
3027 // ...
3028 // EXPECT_THAT(3, InClosedRange(4, 6));
3029 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
3030 //
3031 // would generate two failures that contain the text:
3032 //
3033 // Expected: in closed range (4, 6)
3034 // ...
3035 // Expected: not (in closed range (2, 4))
3036 //
3037 // Types of Matcher Parameters
3038 // ===========================
3039 //
3040 // For the purpose of typing, you can view
3041 //
3042 // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
3043 //
3044 // as shorthand for
3045 //
3046 // template <typename p1_type, ..., typename pk_type>
3047 // FooMatcherPk<p1_type, ..., pk_type>
3048 // Foo(p1_type p1, ..., pk_type pk) { ... }
3049 //
3050 // When you write Foo(v1, ..., vk), the compiler infers the types of
3051 // the parameters v1, ..., and vk for you. If you are not happy with
3052 // the result of the type inference, you can specify the types by
3053 // explicitly instantiating the template, as in Foo<long, bool>(5,
3054 // false). As said earlier, you don't get to (or need to) specify
3055 // 'arg_type' as that's determined by the context in which the matcher
3056 // is used. You can assign the result of expression Foo(p1, ..., pk)
3057 // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
3058 // can be useful when composing matchers.
3059 //
3060 // While you can instantiate a matcher template with reference types,
3061 // passing the parameters by pointer usually makes your code more
3062 // readable. If, however, you still want to pass a parameter by
3063 // reference, be aware that in the failure message generated by the
3064 // matcher you will see the value of the referenced object but not its
3065 // address.
3066 //
3067 // Explaining Match Results
3068 // ========================
3069 //
3070 // Sometimes the matcher description alone isn't enough to explain why
3071 // the match has failed or succeeded. For example, when expecting a
3072 // long string, it can be very helpful to also print the diff between
3073 // the expected string and the actual one. To achieve that, you can
3074 // optionally stream additional information to a special variable
3075 // named result_listener, whose type is a pointer to class
3076 // MatchResultListener:
3077 //
3078 // MATCHER_P(EqualsLongString, str, "") {
3079 // if (arg == str) return true;
3080 //
3081 // *result_listener << "the difference: "
3082 /// << DiffStrings(str, arg);
3083 // return false;
3084 // }
3085 //
3086 // Overloading Matchers
3087 // ====================
3088 //
3089 // You can overload matchers with different numbers of parameters:
3090 //
3091 // MATCHER_P(Blah, a, description_string1) { ... }
3092 // MATCHER_P2(Blah, a, b, description_string2) { ... }
3093 //
3094 // Caveats
3095 // =======
3096 //
3097 // When defining a new matcher, you should also consider implementing
3098 // MatcherInterface or using MakePolymorphicMatcher(). These
3099 // approaches require more work than the MATCHER* macros, but also
3100 // give you more control on the types of the value being matched and
3101 // the matcher parameters, which may leads to better compiler error
3102 // messages when the matcher is used wrong. They also allow
3103 // overloading matchers based on parameter types (as opposed to just
3104 // based on the number of parameters).
3105 //
3106 // MATCHER*() can only be used in a namespace scope as templates cannot be
3107 // declared inside of a local class.
3108 //
3109 // More Information
3110 // ================
3111 //
3112 // To learn more about using these macros, please search for 'MATCHER'
3113 // on
3114 // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
3115 //
3116 // This file also implements some commonly used argument matchers. More
3117 // matchers can be defined by the user implementing the
3118 // MatcherInterface<T> interface if necessary.
3119 //
3120 // See googletest/include/gtest/gtest-matchers.h for the definition of class
3121 // Matcher, class MatcherInterface, and others.
3122
3123 // GOOGLETEST_CM0002 DO NOT DELETE
3124
3125 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
3126 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
3127
3128 #include <algorithm>
3129 #include <cmath>
3130 #include <initializer_list>
3131 #include <iterator>
3132 #include <limits>
3133 #include <memory>
3134 #include <ostream> // NOLINT
3135 #include <sstream>
3136 #include <string>
3137 #include <type_traits>
3138 #include <utility>
3139 #include <vector>
3140
3141
3142 // MSVC warning C5046 is new as of VS2017 version 15.8.
3143 #if defined(_MSC_VER) && _MSC_VER >= 1915
3144 #define GMOCK_MAYBE_5046_ 5046
3145 #else
3146 #define GMOCK_MAYBE_5046_
3147 #endif
3148
3149 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
3150 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by
3151 clients of class B */
3152 /* Symbol involving type with internal linkage not defined */)
3153
3154 namespace testing {
3155
3156 // To implement a matcher Foo for type T, define:
3157 // 1. a class FooMatcherImpl that implements the
3158 // MatcherInterface<T> interface, and
3159 // 2. a factory function that creates a Matcher<T> object from a
3160 // FooMatcherImpl*.
3161 //
3162 // The two-level delegation design makes it possible to allow a user
3163 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
3164 // is impossible if we pass matchers by pointers. It also eases
3165 // ownership management as Matcher objects can now be copied like
3166 // plain values.
3167
3168 // A match result listener that stores the explanation in a string.
3169 class StringMatchResultListener : public MatchResultListener {
3170 public:
3171 StringMatchResultListener() : MatchResultListener(&ss_) {}
3172
3173 // Returns the explanation accumulated so far.
3174 std::string str() const { return ss_.str(); }
3175
3176 // Clears the explanation accumulated so far.
3177 void Clear() { ss_.str(""); }
3178
3179 private:
3180 ::std::stringstream ss_;
3181
3182 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
3183 };
3184
3185 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
3186 // and MUST NOT BE USED IN USER CODE!!!
3187 namespace internal {
3188
3189 // The MatcherCastImpl class template is a helper for implementing
3190 // MatcherCast(). We need this helper in order to partially
3191 // specialize the implementation of MatcherCast() (C++ allows
3192 // class/struct templates to be partially specialized, but not
3193 // function templates.).
3194
3195 // This general version is used when MatcherCast()'s argument is a
3196 // polymorphic matcher (i.e. something that can be converted to a
3197 // Matcher but is not one yet; for example, Eq(value)) or a value (for
3198 // example, "hello").
3199 template <typename T, typename M>
3200 class MatcherCastImpl {
3201 public:
3202 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
3203 // M can be a polymorphic matcher, in which case we want to use
3204 // its conversion operator to create Matcher<T>. Or it can be a value
3205 // that should be passed to the Matcher<T>'s constructor.
3206 //
3207 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
3208 // polymorphic matcher because it'll be ambiguous if T has an implicit
3209 // constructor from M (this usually happens when T has an implicit
3210 // constructor from any type).
3211 //
3212 // It won't work to unconditionally implicit_cast
3213 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
3214 // a user-defined conversion from M to T if one exists (assuming M is
3215 // a value).
3216 return CastImpl(polymorphic_matcher_or_value,
3217 std::is_convertible<M, Matcher<T>>{},
3218 std::is_convertible<M, T>{});
3219 }
3220
3221 private:
3222 template <bool Ignore>
3223 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
3224 std::true_type /* convertible_to_matcher */,
3225 std::integral_constant<bool, Ignore>) {
3226 // M is implicitly convertible to Matcher<T>, which means that either
3227 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
3228 // from M. In both cases using the implicit conversion will produce a
3229 // matcher.
3230 //
3231 // Even if T has an implicit constructor from M, it won't be called because
3232 // creating Matcher<T> would require a chain of two user-defined conversions
3233 // (first to create T from M and then to create Matcher<T> from T).
3234 return polymorphic_matcher_or_value;
3235 }
3236
3237 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
3238 // matcher. It's a value of a type implicitly convertible to T. Use direct
3239 // initialization to create a matcher.
3240 static Matcher<T> CastImpl(const M& value,
3241 std::false_type /* convertible_to_matcher */,
3242 std::true_type /* convertible_to_T */) {
3243 return Matcher<T>(ImplicitCast_<T>(value));
3244 }
3245
3246 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
3247 // polymorphic matcher Eq(value) in this case.
3248 //
3249 // Note that we first attempt to perform an implicit cast on the value and
3250 // only fall back to the polymorphic Eq() matcher afterwards because the
3251 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
3252 // which might be undefined even when Rhs is implicitly convertible to Lhs
3253 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
3254 //
3255 // We don't define this method inline as we need the declaration of Eq().
3256 static Matcher<T> CastImpl(const M& value,
3257 std::false_type /* convertible_to_matcher */,
3258 std::false_type /* convertible_to_T */);
3259 };
3260
3261 // This more specialized version is used when MatcherCast()'s argument
3262 // is already a Matcher. This only compiles when type T can be
3263 // statically converted to type U.
3264 template <typename T, typename U>
3265 class MatcherCastImpl<T, Matcher<U> > {
3266 public:
3267 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
3268 return Matcher<T>(new Impl(source_matcher));
3269 }
3270
3271 private:
3272 class Impl : public MatcherInterface<T> {
3273 public:
3274 explicit Impl(const Matcher<U>& source_matcher)
3275 : source_matcher_(source_matcher) {}
3276
3277 // We delegate the matching logic to the source matcher.
3278 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
3279 using FromType = typename std::remove_cv<typename std::remove_pointer<
3280 typename std::remove_reference<T>::type>::type>::type;
3281 using ToType = typename std::remove_cv<typename std::remove_pointer<
3282 typename std::remove_reference<U>::type>::type>::type;
3283 // Do not allow implicitly converting base*/& to derived*/&.
3284 static_assert(
3285 // Do not trigger if only one of them is a pointer. That implies a
3286 // regular conversion and not a down_cast.
3287 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
3288 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
3289 std::is_same<FromType, ToType>::value ||
3290 !std::is_base_of<FromType, ToType>::value,
3291 "Can't implicitly convert from <base> to <derived>");
3292
3293 // Do the cast to `U` explicitly if necessary.
3294 // Otherwise, let implicit conversions do the trick.
3295 using CastType =
3296 typename std::conditional<std::is_convertible<T&, const U&>::value,
3297 T&, U>::type;
3298
3299 return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
3300 listener);
3301 }
3302
3303 void DescribeTo(::std::ostream* os) const override {
3304 source_matcher_.DescribeTo(os);
3305 }
3306
3307 void DescribeNegationTo(::std::ostream* os) const override {
3308 source_matcher_.DescribeNegationTo(os);
3309 }
3310
3311 private:
3312 const Matcher<U> source_matcher_;
3313 };
3314 };
3315
3316 // This even more specialized version is used for efficiently casting
3317 // a matcher to its own type.
3318 template <typename T>
3319 class MatcherCastImpl<T, Matcher<T> > {
3320 public:
3321 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
3322 };
3323
3324 // Template specialization for parameterless Matcher.
3325 template <typename Derived>
3326 class MatcherBaseImpl {
3327 public:
3328 MatcherBaseImpl() = default;
3329
3330 template <typename T>
3331 operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
3332 return ::testing::Matcher<T>(new
3333 typename Derived::template gmock_Impl<T>());
3334 }
3335 };
3336
3337 // Template specialization for Matcher with parameters.
3338 template <template <typename...> class Derived, typename... Ts>
3339 class MatcherBaseImpl<Derived<Ts...>> {
3340 public:
3341 // Mark the constructor explicit for single argument T to avoid implicit
3342 // conversions.
3343 template <typename E = std::enable_if<sizeof...(Ts) == 1>,
3344 typename E::type* = nullptr>
3345 explicit MatcherBaseImpl(Ts... params)
3346 : params_(std::forward<Ts>(params)...) {}
3347 template <typename E = std::enable_if<sizeof...(Ts) != 1>,
3348 typename = typename E::type>
3349 MatcherBaseImpl(Ts... params) // NOLINT
3350 : params_(std::forward<Ts>(params)...) {}
3351
3352 template <typename F>
3353 operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
3354 return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
3355 }
3356
3357 private:
3358 template <typename F, std::size_t... tuple_ids>
3359 ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
3360 return ::testing::Matcher<F>(
3361 new typename Derived<Ts...>::template gmock_Impl<F>(
3362 std::get<tuple_ids>(params_)...));
3363 }
3364
3365 const std::tuple<Ts...> params_;
3366 };
3367
3368 } // namespace internal
3369
3370 // In order to be safe and clear, casting between different matcher
3371 // types is done explicitly via MatcherCast<T>(m), which takes a
3372 // matcher m and returns a Matcher<T>. It compiles only when T can be
3373 // statically converted to the argument type of m.
3374 template <typename T, typename M>
3375 inline Matcher<T> MatcherCast(const M& matcher) {
3376 return internal::MatcherCastImpl<T, M>::Cast(matcher);
3377 }
3378
3379 // This overload handles polymorphic matchers and values only since
3380 // monomorphic matchers are handled by the next one.
3381 template <typename T, typename M>
3382 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
3383 return MatcherCast<T>(polymorphic_matcher_or_value);
3384 }
3385
3386 // This overload handles monomorphic matchers.
3387 //
3388 // In general, if type T can be implicitly converted to type U, we can
3389 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
3390 // contravariant): just keep a copy of the original Matcher<U>, convert the
3391 // argument from type T to U, and then pass it to the underlying Matcher<U>.
3392 // The only exception is when U is a reference and T is not, as the
3393 // underlying Matcher<U> may be interested in the argument's address, which
3394 // is not preserved in the conversion from T to U.
3395 template <typename T, typename U>
3396 inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
3397 // Enforce that T can be implicitly converted to U.
3398 static_assert(std::is_convertible<const T&, const U&>::value,
3399 "T must be implicitly convertible to U");
3400 // Enforce that we are not converting a non-reference type T to a reference
3401 // type U.
3402 GTEST_COMPILE_ASSERT_(
3403 std::is_reference<T>::value || !std::is_reference<U>::value,
3404 cannot_convert_non_reference_arg_to_reference);
3405 // In case both T and U are arithmetic types, enforce that the
3406 // conversion is not lossy.
3407 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
3408 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
3409 constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
3410 constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
3411 GTEST_COMPILE_ASSERT_(
3412 kTIsOther || kUIsOther ||
3413 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
3414 conversion_of_arithmetic_types_must_be_lossless);
3415 return MatcherCast<T>(matcher);
3416 }
3417
3418 // A<T>() returns a matcher that matches any value of type T.
3419 template <typename T>
3420 Matcher<T> A();
3421
3422 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
3423 // and MUST NOT BE USED IN USER CODE!!!
3424 namespace internal {
3425
3426 // If the explanation is not empty, prints it to the ostream.
3427 inline void PrintIfNotEmpty(const std::string& explanation,
3428 ::std::ostream* os) {
3429 if (explanation != "" && os != nullptr) {
3430 *os << ", " << explanation;
3431 }
3432 }
3433
3434 // Returns true if the given type name is easy to read by a human.
3435 // This is used to decide whether printing the type of a value might
3436 // be helpful.
3437 inline bool IsReadableTypeName(const std::string& type_name) {
3438 // We consider a type name readable if it's short or doesn't contain
3439 // a template or function type.
3440 return (type_name.length() <= 20 ||
3441 type_name.find_first_of("<(") == std::string::npos);
3442 }
3443
3444 // Matches the value against the given matcher, prints the value and explains
3445 // the match result to the listener. Returns the match result.
3446 // 'listener' must not be NULL.
3447 // Value cannot be passed by const reference, because some matchers take a
3448 // non-const argument.
3449 template <typename Value, typename T>
3450 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
3451 MatchResultListener* listener) {
3452 if (!listener->IsInterested()) {
3453 // If the listener is not interested, we do not need to construct the
3454 // inner explanation.
3455 return matcher.Matches(value);
3456 }
3457
3458 StringMatchResultListener inner_listener;
3459 const bool match = matcher.MatchAndExplain(value, &inner_listener);
3460
3461 UniversalPrint(value, listener->stream());
3462 #if GTEST_HAS_RTTI
3463 const std::string& type_name = GetTypeName<Value>();
3464 if (IsReadableTypeName(type_name))
3465 *listener->stream() << " (of type " << type_name << ")";
3466 #endif
3467 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3468
3469 return match;
3470 }
3471
3472 // An internal helper class for doing compile-time loop on a tuple's
3473 // fields.
3474 template <size_t N>
3475 class TuplePrefix {
3476 public:
3477 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
3478 // if and only if the first N fields of matcher_tuple matches
3479 // the first N fields of value_tuple, respectively.
3480 template <typename MatcherTuple, typename ValueTuple>
3481 static bool Matches(const MatcherTuple& matcher_tuple,
3482 const ValueTuple& value_tuple) {
3483 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&
3484 std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));
3485 }
3486
3487 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
3488 // describes failures in matching the first N fields of matchers
3489 // against the first N fields of values. If there is no failure,
3490 // nothing will be streamed to os.
3491 template <typename MatcherTuple, typename ValueTuple>
3492 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
3493 const ValueTuple& values,
3494 ::std::ostream* os) {
3495 // First, describes failures in the first N - 1 fields.
3496 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
3497
3498 // Then describes the failure (if any) in the (N - 1)-th (0-based)
3499 // field.
3500 typename std::tuple_element<N - 1, MatcherTuple>::type matcher =
3501 std::get<N - 1>(matchers);
3502 typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;
3503 const Value& value = std::get<N - 1>(values);
3504 StringMatchResultListener listener;
3505 if (!matcher.MatchAndExplain(value, &listener)) {
3506 *os << " Expected arg #" << N - 1 << ": ";
3507 std::get<N - 1>(matchers).DescribeTo(os);
3508 *os << "\n Actual: ";
3509 // We remove the reference in type Value to prevent the
3510 // universal printer from printing the address of value, which
3511 // isn't interesting to the user most of the time. The
3512 // matcher's MatchAndExplain() method handles the case when
3513 // the address is interesting.
3514 internal::UniversalPrint(value, os);
3515 PrintIfNotEmpty(listener.str(), os);
3516 *os << "\n";
3517 }
3518 }
3519 };
3520
3521 // The base case.
3522 template <>
3523 class TuplePrefix<0> {
3524 public:
3525 template <typename MatcherTuple, typename ValueTuple>
3526 static bool Matches(const MatcherTuple& /* matcher_tuple */,
3527 const ValueTuple& /* value_tuple */) {
3528 return true;
3529 }
3530
3531 template <typename MatcherTuple, typename ValueTuple>
3532 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
3533 const ValueTuple& /* values */,
3534 ::std::ostream* /* os */) {}
3535 };
3536
3537 // TupleMatches(matcher_tuple, value_tuple) returns true if and only if
3538 // all matchers in matcher_tuple match the corresponding fields in
3539 // value_tuple. It is a compiler error if matcher_tuple and
3540 // value_tuple have different number of fields or incompatible field
3541 // types.
3542 template <typename MatcherTuple, typename ValueTuple>
3543 bool TupleMatches(const MatcherTuple& matcher_tuple,
3544 const ValueTuple& value_tuple) {
3545 // Makes sure that matcher_tuple and value_tuple have the same
3546 // number of fields.
3547 GTEST_COMPILE_ASSERT_(std::tuple_size<MatcherTuple>::value ==
3548 std::tuple_size<ValueTuple>::value,
3549 matcher_and_value_have_different_numbers_of_fields);
3550 return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,
3551 value_tuple);
3552 }
3553
3554 // Describes failures in matching matchers against values. If there
3555 // is no failure, nothing will be streamed to os.
3556 template <typename MatcherTuple, typename ValueTuple>
3557 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
3558 const ValueTuple& values,
3559 ::std::ostream* os) {
3560 TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
3561 matchers, values, os);
3562 }
3563
3564 // TransformTupleValues and its helper.
3565 //
3566 // TransformTupleValuesHelper hides the internal machinery that
3567 // TransformTupleValues uses to implement a tuple traversal.
3568 template <typename Tuple, typename Func, typename OutIter>
3569 class TransformTupleValuesHelper {
3570 private:
3571 typedef ::std::tuple_size<Tuple> TupleSize;
3572
3573 public:
3574 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
3575 // Returns the final value of 'out' in case the caller needs it.
3576 static OutIter Run(Func f, const Tuple& t, OutIter out) {
3577 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
3578 }
3579
3580 private:
3581 template <typename Tup, size_t kRemainingSize>
3582 struct IterateOverTuple {
3583 OutIter operator() (Func f, const Tup& t, OutIter out) const {
3584 *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));
3585 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
3586 }
3587 };
3588 template <typename Tup>
3589 struct IterateOverTuple<Tup, 0> {
3590 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
3591 return out;
3592 }
3593 };
3594 };
3595
3596 // Successively invokes 'f(element)' on each element of the tuple 't',
3597 // appending each result to the 'out' iterator. Returns the final value
3598 // of 'out'.
3599 template <typename Tuple, typename Func, typename OutIter>
3600 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
3601 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
3602 }
3603
3604 // Implements _, a matcher that matches any value of any
3605 // type. This is a polymorphic matcher, so we need a template type
3606 // conversion operator to make it appearing as a Matcher<T> for any
3607 // type T.
3608 class AnythingMatcher {
3609 public:
3610 using is_gtest_matcher = void;
3611
3612 template <typename T>
3613 bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {
3614 return true;
3615 }
3616 void DescribeTo(std::ostream* os) const { *os << "is anything"; }
3617 void DescribeNegationTo(::std::ostream* os) const {
3618 // This is mostly for completeness' sake, as it's not very useful
3619 // to write Not(A<bool>()). However we cannot completely rule out
3620 // such a possibility, and it doesn't hurt to be prepared.
3621 *os << "never matches";
3622 }
3623 };
3624
3625 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
3626 // pointer that is NULL.
3627 class IsNullMatcher {
3628 public:
3629 template <typename Pointer>
3630 bool MatchAndExplain(const Pointer& p,
3631 MatchResultListener* /* listener */) const {
3632 return p == nullptr;
3633 }
3634
3635 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
3636 void DescribeNegationTo(::std::ostream* os) const {
3637 *os << "isn't NULL";
3638 }
3639 };
3640
3641 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
3642 // pointer that is not NULL.
3643 class NotNullMatcher {
3644 public:
3645 template <typename Pointer>
3646 bool MatchAndExplain(const Pointer& p,
3647 MatchResultListener* /* listener */) const {
3648 return p != nullptr;
3649 }
3650
3651 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
3652 void DescribeNegationTo(::std::ostream* os) const {
3653 *os << "is NULL";
3654 }
3655 };
3656
3657 // Ref(variable) matches any argument that is a reference to
3658 // 'variable'. This matcher is polymorphic as it can match any
3659 // super type of the type of 'variable'.
3660 //
3661 // The RefMatcher template class implements Ref(variable). It can
3662 // only be instantiated with a reference type. This prevents a user
3663 // from mistakenly using Ref(x) to match a non-reference function
3664 // argument. For example, the following will righteously cause a
3665 // compiler error:
3666 //
3667 // int n;
3668 // Matcher<int> m1 = Ref(n); // This won't compile.
3669 // Matcher<int&> m2 = Ref(n); // This will compile.
3670 template <typename T>
3671 class RefMatcher;
3672
3673 template <typename T>
3674 class RefMatcher<T&> {
3675 // Google Mock is a generic framework and thus needs to support
3676 // mocking any function types, including those that take non-const
3677 // reference arguments. Therefore the template parameter T (and
3678 // Super below) can be instantiated to either a const type or a
3679 // non-const type.
3680 public:
3681 // RefMatcher() takes a T& instead of const T&, as we want the
3682 // compiler to catch using Ref(const_value) as a matcher for a
3683 // non-const reference.
3684 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
3685
3686 template <typename Super>
3687 operator Matcher<Super&>() const {
3688 // By passing object_ (type T&) to Impl(), which expects a Super&,
3689 // we make sure that Super is a super type of T. In particular,
3690 // this catches using Ref(const_value) as a matcher for a
3691 // non-const reference, as you cannot implicitly convert a const
3692 // reference to a non-const reference.
3693 return MakeMatcher(new Impl<Super>(object_));
3694 }
3695
3696 private:
3697 template <typename Super>
3698 class Impl : public MatcherInterface<Super&> {
3699 public:
3700 explicit Impl(Super& x) : object_(x) {} // NOLINT
3701
3702 // MatchAndExplain() takes a Super& (as opposed to const Super&)
3703 // in order to match the interface MatcherInterface<Super&>.
3704 bool MatchAndExplain(Super& x,
3705 MatchResultListener* listener) const override {
3706 *listener << "which is located @" << static_cast<const void*>(&x);
3707 return &x == &object_;
3708 }
3709
3710 void DescribeTo(::std::ostream* os) const override {
3711 *os << "references the variable ";
3712 UniversalPrinter<Super&>::Print(object_, os);
3713 }
3714
3715 void DescribeNegationTo(::std::ostream* os) const override {
3716 *os << "does not reference the variable ";
3717 UniversalPrinter<Super&>::Print(object_, os);
3718 }
3719
3720 private:
3721 const Super& object_;
3722 };
3723
3724 T& object_;
3725 };
3726
3727 // Polymorphic helper functions for narrow and wide string matchers.
3728 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
3729 return String::CaseInsensitiveCStringEquals(lhs, rhs);
3730 }
3731
3732 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
3733 const wchar_t* rhs) {
3734 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
3735 }
3736
3737 // String comparison for narrow or wide strings that can have embedded NUL
3738 // characters.
3739 template <typename StringType>
3740 bool CaseInsensitiveStringEquals(const StringType& s1,
3741 const StringType& s2) {
3742 // Are the heads equal?
3743 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
3744 return false;
3745 }
3746
3747 // Skip the equal heads.
3748 const typename StringType::value_type nul = 0;
3749 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
3750
3751 // Are we at the end of either s1 or s2?
3752 if (i1 == StringType::npos || i2 == StringType::npos) {
3753 return i1 == i2;
3754 }
3755
3756 // Are the tails equal?
3757 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
3758 }
3759
3760 // String matchers.
3761
3762 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
3763 template <typename StringType>
3764 class StrEqualityMatcher {
3765 public:
3766 StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)
3767 : string_(std::move(str)),
3768 expect_eq_(expect_eq),
3769 case_sensitive_(case_sensitive) {}
3770
3771 #if GTEST_INTERNAL_HAS_STRING_VIEW
3772 bool MatchAndExplain(const internal::StringView& s,
3773 MatchResultListener* listener) const {
3774 // This should fail to compile if StringView is used with wide
3775 // strings.
3776 const StringType& str = std::string(s);
3777 return MatchAndExplain(str, listener);
3778 }
3779 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3780
3781 // Accepts pointer types, particularly:
3782 // const char*
3783 // char*
3784 // const wchar_t*
3785 // wchar_t*
3786 template <typename CharType>
3787 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3788 if (s == nullptr) {
3789 return !expect_eq_;
3790 }
3791 return MatchAndExplain(StringType(s), listener);
3792 }
3793
3794 // Matches anything that can convert to StringType.
3795 //
3796 // This is a template, not just a plain function with const StringType&,
3797 // because StringView has some interfering non-explicit constructors.
3798 template <typename MatcheeStringType>
3799 bool MatchAndExplain(const MatcheeStringType& s,
3800 MatchResultListener* /* listener */) const {
3801 const StringType s2(s);
3802 const bool eq = case_sensitive_ ? s2 == string_ :
3803 CaseInsensitiveStringEquals(s2, string_);
3804 return expect_eq_ == eq;
3805 }
3806
3807 void DescribeTo(::std::ostream* os) const {
3808 DescribeToHelper(expect_eq_, os);
3809 }
3810
3811 void DescribeNegationTo(::std::ostream* os) const {
3812 DescribeToHelper(!expect_eq_, os);
3813 }
3814
3815 private:
3816 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
3817 *os << (expect_eq ? "is " : "isn't ");
3818 *os << "equal to ";
3819 if (!case_sensitive_) {
3820 *os << "(ignoring case) ";
3821 }
3822 UniversalPrint(string_, os);
3823 }
3824
3825 const StringType string_;
3826 const bool expect_eq_;
3827 const bool case_sensitive_;
3828 };
3829
3830 // Implements the polymorphic HasSubstr(substring) matcher, which
3831 // can be used as a Matcher<T> as long as T can be converted to a
3832 // string.
3833 template <typename StringType>
3834 class HasSubstrMatcher {
3835 public:
3836 explicit HasSubstrMatcher(const StringType& substring)
3837 : substring_(substring) {}
3838
3839 #if GTEST_INTERNAL_HAS_STRING_VIEW
3840 bool MatchAndExplain(const internal::StringView& s,
3841 MatchResultListener* listener) const {
3842 // This should fail to compile if StringView is used with wide
3843 // strings.
3844 const StringType& str = std::string(s);
3845 return MatchAndExplain(str, listener);
3846 }
3847 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3848
3849 // Accepts pointer types, particularly:
3850 // const char*
3851 // char*
3852 // const wchar_t*
3853 // wchar_t*
3854 template <typename CharType>
3855 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3856 return s != nullptr && MatchAndExplain(StringType(s), listener);
3857 }
3858
3859 // Matches anything that can convert to StringType.
3860 //
3861 // This is a template, not just a plain function with const StringType&,
3862 // because StringView has some interfering non-explicit constructors.
3863 template <typename MatcheeStringType>
3864 bool MatchAndExplain(const MatcheeStringType& s,
3865 MatchResultListener* /* listener */) const {
3866 return StringType(s).find(substring_) != StringType::npos;
3867 }
3868
3869 // Describes what this matcher matches.
3870 void DescribeTo(::std::ostream* os) const {
3871 *os << "has substring ";
3872 UniversalPrint(substring_, os);
3873 }
3874
3875 void DescribeNegationTo(::std::ostream* os) const {
3876 *os << "has no substring ";
3877 UniversalPrint(substring_, os);
3878 }
3879
3880 private:
3881 const StringType substring_;
3882 };
3883
3884 // Implements the polymorphic StartsWith(substring) matcher, which
3885 // can be used as a Matcher<T> as long as T can be converted to a
3886 // string.
3887 template <typename StringType>
3888 class StartsWithMatcher {
3889 public:
3890 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
3891 }
3892
3893 #if GTEST_INTERNAL_HAS_STRING_VIEW
3894 bool MatchAndExplain(const internal::StringView& s,
3895 MatchResultListener* listener) const {
3896 // This should fail to compile if StringView is used with wide
3897 // strings.
3898 const StringType& str = std::string(s);
3899 return MatchAndExplain(str, listener);
3900 }
3901 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3902
3903 // Accepts pointer types, particularly:
3904 // const char*
3905 // char*
3906 // const wchar_t*
3907 // wchar_t*
3908 template <typename CharType>
3909 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3910 return s != nullptr && MatchAndExplain(StringType(s), listener);
3911 }
3912
3913 // Matches anything that can convert to StringType.
3914 //
3915 // This is a template, not just a plain function with const StringType&,
3916 // because StringView has some interfering non-explicit constructors.
3917 template <typename MatcheeStringType>
3918 bool MatchAndExplain(const MatcheeStringType& s,
3919 MatchResultListener* /* listener */) const {
3920 const StringType& s2(s);
3921 return s2.length() >= prefix_.length() &&
3922 s2.substr(0, prefix_.length()) == prefix_;
3923 }
3924
3925 void DescribeTo(::std::ostream* os) const {
3926 *os << "starts with ";
3927 UniversalPrint(prefix_, os);
3928 }
3929
3930 void DescribeNegationTo(::std::ostream* os) const {
3931 *os << "doesn't start with ";
3932 UniversalPrint(prefix_, os);
3933 }
3934
3935 private:
3936 const StringType prefix_;
3937 };
3938
3939 // Implements the polymorphic EndsWith(substring) matcher, which
3940 // can be used as a Matcher<T> as long as T can be converted to a
3941 // string.
3942 template <typename StringType>
3943 class EndsWithMatcher {
3944 public:
3945 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
3946
3947 #if GTEST_INTERNAL_HAS_STRING_VIEW
3948 bool MatchAndExplain(const internal::StringView& s,
3949 MatchResultListener* listener) const {
3950 // This should fail to compile if StringView is used with wide
3951 // strings.
3952 const StringType& str = std::string(s);
3953 return MatchAndExplain(str, listener);
3954 }
3955 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3956
3957 // Accepts pointer types, particularly:
3958 // const char*
3959 // char*
3960 // const wchar_t*
3961 // wchar_t*
3962 template <typename CharType>
3963 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3964 return s != nullptr && MatchAndExplain(StringType(s), listener);
3965 }
3966
3967 // Matches anything that can convert to StringType.
3968 //
3969 // This is a template, not just a plain function with const StringType&,
3970 // because StringView has some interfering non-explicit constructors.
3971 template <typename MatcheeStringType>
3972 bool MatchAndExplain(const MatcheeStringType& s,
3973 MatchResultListener* /* listener */) const {
3974 const StringType& s2(s);
3975 return s2.length() >= suffix_.length() &&
3976 s2.substr(s2.length() - suffix_.length()) == suffix_;
3977 }
3978
3979 void DescribeTo(::std::ostream* os) const {
3980 *os << "ends with ";
3981 UniversalPrint(suffix_, os);
3982 }
3983
3984 void DescribeNegationTo(::std::ostream* os) const {
3985 *os << "doesn't end with ";
3986 UniversalPrint(suffix_, os);
3987 }
3988
3989 private:
3990 const StringType suffix_;
3991 };
3992
3993 // Implements a matcher that compares the two fields of a 2-tuple
3994 // using one of the ==, <=, <, etc, operators. The two fields being
3995 // compared don't have to have the same type.
3996 //
3997 // The matcher defined here is polymorphic (for example, Eq() can be
3998 // used to match a std::tuple<int, short>, a std::tuple<const long&, double>,
3999 // etc). Therefore we use a template type conversion operator in the
4000 // implementation.
4001 template <typename D, typename Op>
4002 class PairMatchBase {
4003 public:
4004 template <typename T1, typename T2>
4005 operator Matcher<::std::tuple<T1, T2>>() const {
4006 return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);
4007 }
4008 template <typename T1, typename T2>
4009 operator Matcher<const ::std::tuple<T1, T2>&>() const {
4010 return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);
4011 }
4012
4013 private:
4014 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
4015 return os << D::Desc();
4016 }
4017
4018 template <typename Tuple>
4019 class Impl : public MatcherInterface<Tuple> {
4020 public:
4021 bool MatchAndExplain(Tuple args,
4022 MatchResultListener* /* listener */) const override {
4023 return Op()(::std::get<0>(args), ::std::get<1>(args));
4024 }
4025 void DescribeTo(::std::ostream* os) const override {
4026 *os << "are " << GetDesc;
4027 }
4028 void DescribeNegationTo(::std::ostream* os) const override {
4029 *os << "aren't " << GetDesc;
4030 }
4031 };
4032 };
4033
4034 class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
4035 public:
4036 static const char* Desc() { return "an equal pair"; }
4037 };
4038 class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
4039 public:
4040 static const char* Desc() { return "an unequal pair"; }
4041 };
4042 class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
4043 public:
4044 static const char* Desc() { return "a pair where the first < the second"; }
4045 };
4046 class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
4047 public:
4048 static const char* Desc() { return "a pair where the first > the second"; }
4049 };
4050 class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
4051 public:
4052 static const char* Desc() { return "a pair where the first <= the second"; }
4053 };
4054 class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
4055 public:
4056 static const char* Desc() { return "a pair where the first >= the second"; }
4057 };
4058
4059 // Implements the Not(...) matcher for a particular argument type T.
4060 // We do not nest it inside the NotMatcher class template, as that
4061 // will prevent different instantiations of NotMatcher from sharing
4062 // the same NotMatcherImpl<T> class.
4063 template <typename T>
4064 class NotMatcherImpl : public MatcherInterface<const T&> {
4065 public:
4066 explicit NotMatcherImpl(const Matcher<T>& matcher)
4067 : matcher_(matcher) {}
4068
4069 bool MatchAndExplain(const T& x,
4070 MatchResultListener* listener) const override {
4071 return !matcher_.MatchAndExplain(x, listener);
4072 }
4073
4074 void DescribeTo(::std::ostream* os) const override {
4075 matcher_.DescribeNegationTo(os);
4076 }
4077
4078 void DescribeNegationTo(::std::ostream* os) const override {
4079 matcher_.DescribeTo(os);
4080 }
4081
4082 private:
4083 const Matcher<T> matcher_;
4084 };
4085
4086 // Implements the Not(m) matcher, which matches a value that doesn't
4087 // match matcher m.
4088 template <typename InnerMatcher>
4089 class NotMatcher {
4090 public:
4091 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
4092
4093 // This template type conversion operator allows Not(m) to be used
4094 // to match any type m can match.
4095 template <typename T>
4096 operator Matcher<T>() const {
4097 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
4098 }
4099
4100 private:
4101 InnerMatcher matcher_;
4102 };
4103
4104 // Implements the AllOf(m1, m2) matcher for a particular argument type
4105 // T. We do not nest it inside the BothOfMatcher class template, as
4106 // that will prevent different instantiations of BothOfMatcher from
4107 // sharing the same BothOfMatcherImpl<T> class.
4108 template <typename T>
4109 class AllOfMatcherImpl : public MatcherInterface<const T&> {
4110 public:
4111 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
4112 : matchers_(std::move(matchers)) {}
4113
4114 void DescribeTo(::std::ostream* os) const override {
4115 *os << "(";
4116 for (size_t i = 0; i < matchers_.size(); ++i) {
4117 if (i != 0) *os << ") and (";
4118 matchers_[i].DescribeTo(os);
4119 }
4120 *os << ")";
4121 }
4122
4123 void DescribeNegationTo(::std::ostream* os) const override {
4124 *os << "(";
4125 for (size_t i = 0; i < matchers_.size(); ++i) {
4126 if (i != 0) *os << ") or (";
4127 matchers_[i].DescribeNegationTo(os);
4128 }
4129 *os << ")";
4130 }
4131
4132 bool MatchAndExplain(const T& x,
4133 MatchResultListener* listener) const override {
4134 // If either matcher1_ or matcher2_ doesn't match x, we only need
4135 // to explain why one of them fails.
4136 std::string all_match_result;
4137
4138 for (size_t i = 0; i < matchers_.size(); ++i) {
4139 StringMatchResultListener slistener;
4140 if (matchers_[i].MatchAndExplain(x, &slistener)) {
4141 if (all_match_result.empty()) {
4142 all_match_result = slistener.str();
4143 } else {
4144 std::string result = slistener.str();
4145 if (!result.empty()) {
4146 all_match_result += ", and ";
4147 all_match_result += result;
4148 }
4149 }
4150 } else {
4151 *listener << slistener.str();
4152 return false;
4153 }
4154 }
4155
4156 // Otherwise we need to explain why *both* of them match.
4157 *listener << all_match_result;
4158 return true;
4159 }
4160
4161 private:
4162 const std::vector<Matcher<T> > matchers_;
4163 };
4164
4165 // VariadicMatcher is used for the variadic implementation of
4166 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
4167 // CombiningMatcher<T> is used to recursively combine the provided matchers
4168 // (of type Args...).
4169 template <template <typename T> class CombiningMatcher, typename... Args>
4170 class VariadicMatcher {
4171 public:
4172 VariadicMatcher(const Args&... matchers) // NOLINT
4173 : matchers_(matchers...) {
4174 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
4175 }
4176
4177 VariadicMatcher(const VariadicMatcher&) = default;
4178 VariadicMatcher& operator=(const VariadicMatcher&) = delete;
4179
4180 // This template type conversion operator allows an
4181 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
4182 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
4183 template <typename T>
4184 operator Matcher<T>() const {
4185 std::vector<Matcher<T> > values;
4186 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
4187 return Matcher<T>(new CombiningMatcher<T>(std::move(values)));
4188 }
4189
4190 private:
4191 template <typename T, size_t I>
4192 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
4193 std::integral_constant<size_t, I>) const {
4194 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
4195 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
4196 }
4197
4198 template <typename T>
4199 void CreateVariadicMatcher(
4200 std::vector<Matcher<T> >*,
4201 std::integral_constant<size_t, sizeof...(Args)>) const {}
4202
4203 std::tuple<Args...> matchers_;
4204 };
4205
4206 template <typename... Args>
4207 using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
4208
4209 // Implements the AnyOf(m1, m2) matcher for a particular argument type
4210 // T. We do not nest it inside the AnyOfMatcher class template, as
4211 // that will prevent different instantiations of AnyOfMatcher from
4212 // sharing the same EitherOfMatcherImpl<T> class.
4213 template <typename T>
4214 class AnyOfMatcherImpl : public MatcherInterface<const T&> {
4215 public:
4216 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
4217 : matchers_(std::move(matchers)) {}
4218
4219 void DescribeTo(::std::ostream* os) const override {
4220 *os << "(";
4221 for (size_t i = 0; i < matchers_.size(); ++i) {
4222 if (i != 0) *os << ") or (";
4223 matchers_[i].DescribeTo(os);
4224 }
4225 *os << ")";
4226 }
4227
4228 void DescribeNegationTo(::std::ostream* os) const override {
4229 *os << "(";
4230 for (size_t i = 0; i < matchers_.size(); ++i) {
4231 if (i != 0) *os << ") and (";
4232 matchers_[i].DescribeNegationTo(os);
4233 }
4234 *os << ")";
4235 }
4236
4237 bool MatchAndExplain(const T& x,
4238 MatchResultListener* listener) const override {
4239 std::string no_match_result;
4240
4241 // If either matcher1_ or matcher2_ matches x, we just need to
4242 // explain why *one* of them matches.
4243 for (size_t i = 0; i < matchers_.size(); ++i) {
4244 StringMatchResultListener slistener;
4245 if (matchers_[i].MatchAndExplain(x, &slistener)) {
4246 *listener << slistener.str();
4247 return true;
4248 } else {
4249 if (no_match_result.empty()) {
4250 no_match_result = slistener.str();
4251 } else {
4252 std::string result = slistener.str();
4253 if (!result.empty()) {
4254 no_match_result += ", and ";
4255 no_match_result += result;
4256 }
4257 }
4258 }
4259 }
4260
4261 // Otherwise we need to explain why *both* of them fail.
4262 *listener << no_match_result;
4263 return false;
4264 }
4265
4266 private:
4267 const std::vector<Matcher<T> > matchers_;
4268 };
4269
4270 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
4271 template <typename... Args>
4272 using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
4273
4274 // Wrapper for implementation of Any/AllOfArray().
4275 template <template <class> class MatcherImpl, typename T>
4276 class SomeOfArrayMatcher {
4277 public:
4278 // Constructs the matcher from a sequence of element values or
4279 // element matchers.
4280 template <typename Iter>
4281 SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
4282
4283 template <typename U>
4284 operator Matcher<U>() const { // NOLINT
4285 using RawU = typename std::decay<U>::type;
4286 std::vector<Matcher<RawU>> matchers;
4287 for (const auto& matcher : matchers_) {
4288 matchers.push_back(MatcherCast<RawU>(matcher));
4289 }
4290 return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));
4291 }
4292
4293 private:
4294 const ::std::vector<T> matchers_;
4295 };
4296
4297 template <typename T>
4298 using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;
4299
4300 template <typename T>
4301 using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;
4302
4303 // Used for implementing Truly(pred), which turns a predicate into a
4304 // matcher.
4305 template <typename Predicate>
4306 class TrulyMatcher {
4307 public:
4308 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
4309
4310 // This method template allows Truly(pred) to be used as a matcher
4311 // for type T where T is the argument type of predicate 'pred'. The
4312 // argument is passed by reference as the predicate may be
4313 // interested in the address of the argument.
4314 template <typename T>
4315 bool MatchAndExplain(T& x, // NOLINT
4316 MatchResultListener* listener) const {
4317 // Without the if-statement, MSVC sometimes warns about converting
4318 // a value to bool (warning 4800).
4319 //
4320 // We cannot write 'return !!predicate_(x);' as that doesn't work
4321 // when predicate_(x) returns a class convertible to bool but
4322 // having no operator!().
4323 if (predicate_(x))
4324 return true;
4325 *listener << "didn't satisfy the given predicate";
4326 return false;
4327 }
4328
4329 void DescribeTo(::std::ostream* os) const {
4330 *os << "satisfies the given predicate";
4331 }
4332
4333 void DescribeNegationTo(::std::ostream* os) const {
4334 *os << "doesn't satisfy the given predicate";
4335 }
4336
4337 private:
4338 Predicate predicate_;
4339 };
4340
4341 // Used for implementing Matches(matcher), which turns a matcher into
4342 // a predicate.
4343 template <typename M>
4344 class MatcherAsPredicate {
4345 public:
4346 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
4347
4348 // This template operator() allows Matches(m) to be used as a
4349 // predicate on type T where m is a matcher on type T.
4350 //
4351 // The argument x is passed by reference instead of by value, as
4352 // some matcher may be interested in its address (e.g. as in
4353 // Matches(Ref(n))(x)).
4354 template <typename T>
4355 bool operator()(const T& x) const {
4356 // We let matcher_ commit to a particular type here instead of
4357 // when the MatcherAsPredicate object was constructed. This
4358 // allows us to write Matches(m) where m is a polymorphic matcher
4359 // (e.g. Eq(5)).
4360 //
4361 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
4362 // compile when matcher_ has type Matcher<const T&>; if we write
4363 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
4364 // when matcher_ has type Matcher<T>; if we just write
4365 // matcher_.Matches(x), it won't compile when matcher_ is
4366 // polymorphic, e.g. Eq(5).
4367 //
4368 // MatcherCast<const T&>() is necessary for making the code work
4369 // in all of the above situations.
4370 return MatcherCast<const T&>(matcher_).Matches(x);
4371 }
4372
4373 private:
4374 M matcher_;
4375 };
4376
4377 // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
4378 // argument M must be a type that can be converted to a matcher.
4379 template <typename M>
4380 class PredicateFormatterFromMatcher {
4381 public:
4382 explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}
4383
4384 // This template () operator allows a PredicateFormatterFromMatcher
4385 // object to act as a predicate-formatter suitable for using with
4386 // Google Test's EXPECT_PRED_FORMAT1() macro.
4387 template <typename T>
4388 AssertionResult operator()(const char* value_text, const T& x) const {
4389 // We convert matcher_ to a Matcher<const T&> *now* instead of
4390 // when the PredicateFormatterFromMatcher object was constructed,
4391 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
4392 // know which type to instantiate it to until we actually see the
4393 // type of x here.
4394 //
4395 // We write SafeMatcherCast<const T&>(matcher_) instead of
4396 // Matcher<const T&>(matcher_), as the latter won't compile when
4397 // matcher_ has type Matcher<T> (e.g. An<int>()).
4398 // We don't write MatcherCast<const T&> either, as that allows
4399 // potentially unsafe downcasting of the matcher argument.
4400 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
4401
4402 // The expected path here is that the matcher should match (i.e. that most
4403 // tests pass) so optimize for this case.
4404 if (matcher.Matches(x)) {
4405 return AssertionSuccess();
4406 }
4407
4408 ::std::stringstream ss;
4409 ss << "Value of: " << value_text << "\n"
4410 << "Expected: ";
4411 matcher.DescribeTo(&ss);
4412
4413 // Rerun the matcher to "PrintAndExplain" the failure.
4414 StringMatchResultListener listener;
4415 if (MatchPrintAndExplain(x, matcher, &listener)) {
4416 ss << "\n The matcher failed on the initial attempt; but passed when "
4417 "rerun to generate the explanation.";
4418 }
4419 ss << "\n Actual: " << listener.str();
4420 return AssertionFailure() << ss.str();
4421 }
4422
4423 private:
4424 const M matcher_;
4425 };
4426
4427 // A helper function for converting a matcher to a predicate-formatter
4428 // without the user needing to explicitly write the type. This is
4429 // used for implementing ASSERT_THAT() and EXPECT_THAT().
4430 // Implementation detail: 'matcher' is received by-value to force decaying.
4431 template <typename M>
4432 inline PredicateFormatterFromMatcher<M>
4433 MakePredicateFormatterFromMatcher(M matcher) {
4434 return PredicateFormatterFromMatcher<M>(std::move(matcher));
4435 }
4436
4437 // Implements the polymorphic IsNan() matcher, which matches any floating type
4438 // value that is Nan.
4439 class IsNanMatcher {
4440 public:
4441 template <typename FloatType>
4442 bool MatchAndExplain(const FloatType& f,
4443 MatchResultListener* /* listener */) const {
4444 return (::std::isnan)(f);
4445 }
4446
4447 void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }
4448 void DescribeNegationTo(::std::ostream* os) const {
4449 *os << "isn't NaN";
4450 }
4451 };
4452
4453 // Implements the polymorphic floating point equality matcher, which matches
4454 // two float values using ULP-based approximation or, optionally, a
4455 // user-specified epsilon. The template is meant to be instantiated with
4456 // FloatType being either float or double.
4457 template <typename FloatType>
4458 class FloatingEqMatcher {
4459 public:
4460 // Constructor for FloatingEqMatcher.
4461 // The matcher's input will be compared with expected. The matcher treats two
4462 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
4463 // equality comparisons between NANs will always return false. We specify a
4464 // negative max_abs_error_ term to indicate that ULP-based approximation will
4465 // be used for comparison.
4466 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
4467 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
4468 }
4469
4470 // Constructor that supports a user-specified max_abs_error that will be used
4471 // for comparison instead of ULP-based approximation. The max absolute
4472 // should be non-negative.
4473 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
4474 FloatType max_abs_error)
4475 : expected_(expected),
4476 nan_eq_nan_(nan_eq_nan),
4477 max_abs_error_(max_abs_error) {
4478 GTEST_CHECK_(max_abs_error >= 0)
4479 << ", where max_abs_error is" << max_abs_error;
4480 }
4481
4482 // Implements floating point equality matcher as a Matcher<T>.
4483 template <typename T>
4484 class Impl : public MatcherInterface<T> {
4485 public:
4486 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
4487 : expected_(expected),
4488 nan_eq_nan_(nan_eq_nan),
4489 max_abs_error_(max_abs_error) {}
4490
4491 bool MatchAndExplain(T value,
4492 MatchResultListener* listener) const override {
4493 const FloatingPoint<FloatType> actual(value), expected(expected_);
4494
4495 // Compares NaNs first, if nan_eq_nan_ is true.
4496 if (actual.is_nan() || expected.is_nan()) {
4497 if (actual.is_nan() && expected.is_nan()) {
4498 return nan_eq_nan_;
4499 }
4500 // One is nan; the other is not nan.
4501 return false;
4502 }
4503 if (HasMaxAbsError()) {
4504 // We perform an equality check so that inf will match inf, regardless
4505 // of error bounds. If the result of value - expected_ would result in
4506 // overflow or if either value is inf, the default result is infinity,
4507 // which should only match if max_abs_error_ is also infinity.
4508 if (value == expected_) {
4509 return true;
4510 }
4511
4512 const FloatType diff = value - expected_;
4513 if (::std::fabs(diff) <= max_abs_error_) {
4514 return true;
4515 }
4516
4517 if (listener->IsInterested()) {
4518 *listener << "which is " << diff << " from " << expected_;
4519 }
4520 return false;
4521 } else {
4522 return actual.AlmostEquals(expected);
4523 }
4524 }
4525
4526 void DescribeTo(::std::ostream* os) const override {
4527 // os->precision() returns the previously set precision, which we
4528 // store to restore the ostream to its original configuration
4529 // after outputting.
4530 const ::std::streamsize old_precision = os->precision(
4531 ::std::numeric_limits<FloatType>::digits10 + 2);
4532 if (FloatingPoint<FloatType>(expected_).is_nan()) {
4533 if (nan_eq_nan_) {
4534 *os << "is NaN";
4535 } else {
4536 *os << "never matches";
4537 }
4538 } else {
4539 *os << "is approximately " << expected_;
4540 if (HasMaxAbsError()) {
4541 *os << " (absolute error <= " << max_abs_error_ << ")";
4542 }
4543 }
4544 os->precision(old_precision);
4545 }
4546
4547 void DescribeNegationTo(::std::ostream* os) const override {
4548 // As before, get original precision.
4549 const ::std::streamsize old_precision = os->precision(
4550 ::std::numeric_limits<FloatType>::digits10 + 2);
4551 if (FloatingPoint<FloatType>(expected_).is_nan()) {
4552 if (nan_eq_nan_) {
4553 *os << "isn't NaN";
4554 } else {
4555 *os << "is anything";
4556 }
4557 } else {
4558 *os << "isn't approximately " << expected_;
4559 if (HasMaxAbsError()) {
4560 *os << " (absolute error > " << max_abs_error_ << ")";
4561 }
4562 }
4563 // Restore original precision.
4564 os->precision(old_precision);
4565 }
4566
4567 private:
4568 bool HasMaxAbsError() const {
4569 return max_abs_error_ >= 0;
4570 }
4571
4572 const FloatType expected_;
4573 const bool nan_eq_nan_;
4574 // max_abs_error will be used for value comparison when >= 0.
4575 const FloatType max_abs_error_;
4576 };
4577
4578 // The following 3 type conversion operators allow FloatEq(expected) and
4579 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
4580 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
4581 operator Matcher<FloatType>() const {
4582 return MakeMatcher(
4583 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
4584 }
4585
4586 operator Matcher<const FloatType&>() const {
4587 return MakeMatcher(
4588 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
4589 }
4590
4591 operator Matcher<FloatType&>() const {
4592 return MakeMatcher(
4593 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
4594 }
4595
4596 private:
4597 const FloatType expected_;
4598 const bool nan_eq_nan_;
4599 // max_abs_error will be used for value comparison when >= 0.
4600 const FloatType max_abs_error_;
4601 };
4602
4603 // A 2-tuple ("binary") wrapper around FloatingEqMatcher:
4604 // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
4605 // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
4606 // against y. The former implements "Eq", the latter "Near". At present, there
4607 // is no version that compares NaNs as equal.
4608 template <typename FloatType>
4609 class FloatingEq2Matcher {
4610 public:
4611 FloatingEq2Matcher() { Init(-1, false); }
4612
4613 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
4614
4615 explicit FloatingEq2Matcher(FloatType max_abs_error) {
4616 Init(max_abs_error, false);
4617 }
4618
4619 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
4620 Init(max_abs_error, nan_eq_nan);
4621 }
4622
4623 template <typename T1, typename T2>
4624 operator Matcher<::std::tuple<T1, T2>>() const {
4625 return MakeMatcher(
4626 new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));
4627 }
4628 template <typename T1, typename T2>
4629 operator Matcher<const ::std::tuple<T1, T2>&>() const {
4630 return MakeMatcher(
4631 new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
4632 }
4633
4634 private:
4635 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
4636 return os << "an almost-equal pair";
4637 }
4638
4639 template <typename Tuple>
4640 class Impl : public MatcherInterface<Tuple> {
4641 public:
4642 Impl(FloatType max_abs_error, bool nan_eq_nan) :
4643 max_abs_error_(max_abs_error),
4644 nan_eq_nan_(nan_eq_nan) {}
4645
4646 bool MatchAndExplain(Tuple args,
4647 MatchResultListener* listener) const override {
4648 if (max_abs_error_ == -1) {
4649 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);
4650 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
4651 ::std::get<1>(args), listener);
4652 } else {
4653 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,
4654 max_abs_error_);
4655 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
4656 ::std::get<1>(args), listener);
4657 }
4658 }
4659 void DescribeTo(::std::ostream* os) const override {
4660 *os << "are " << GetDesc;
4661 }
4662 void DescribeNegationTo(::std::ostream* os) const override {
4663 *os << "aren't " << GetDesc;
4664 }
4665
4666 private:
4667 FloatType max_abs_error_;
4668 const bool nan_eq_nan_;
4669 };
4670
4671 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
4672 max_abs_error_ = max_abs_error_val;
4673 nan_eq_nan_ = nan_eq_nan_val;
4674 }
4675 FloatType max_abs_error_;
4676 bool nan_eq_nan_;
4677 };
4678
4679 // Implements the Pointee(m) matcher for matching a pointer whose
4680 // pointee matches matcher m. The pointer can be either raw or smart.
4681 template <typename InnerMatcher>
4682 class PointeeMatcher {
4683 public:
4684 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
4685
4686 // This type conversion operator template allows Pointee(m) to be
4687 // used as a matcher for any pointer type whose pointee type is
4688 // compatible with the inner matcher, where type Pointer can be
4689 // either a raw pointer or a smart pointer.
4690 //
4691 // The reason we do this instead of relying on
4692 // MakePolymorphicMatcher() is that the latter is not flexible
4693 // enough for implementing the DescribeTo() method of Pointee().
4694 template <typename Pointer>
4695 operator Matcher<Pointer>() const {
4696 return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));
4697 }
4698
4699 private:
4700 // The monomorphic implementation that works for a particular pointer type.
4701 template <typename Pointer>
4702 class Impl : public MatcherInterface<Pointer> {
4703 public:
4704 using Pointee =
4705 typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
4706 Pointer)>::element_type;
4707
4708 explicit Impl(const InnerMatcher& matcher)
4709 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
4710
4711 void DescribeTo(::std::ostream* os) const override {
4712 *os << "points to a value that ";
4713 matcher_.DescribeTo(os);
4714 }
4715
4716 void DescribeNegationTo(::std::ostream* os) const override {
4717 *os << "does not point to a value that ";
4718 matcher_.DescribeTo(os);
4719 }
4720
4721 bool MatchAndExplain(Pointer pointer,
4722 MatchResultListener* listener) const override {
4723 if (GetRawPointer(pointer) == nullptr) return false;
4724
4725 *listener << "which points to ";
4726 return MatchPrintAndExplain(*pointer, matcher_, listener);
4727 }
4728
4729 private:
4730 const Matcher<const Pointee&> matcher_;
4731 };
4732
4733 const InnerMatcher matcher_;
4734 };
4735
4736 // Implements the Pointer(m) matcher
4737 // Implements the Pointer(m) matcher for matching a pointer that matches matcher
4738 // m. The pointer can be either raw or smart, and will match `m` against the
4739 // raw pointer.
4740 template <typename InnerMatcher>
4741 class PointerMatcher {
4742 public:
4743 explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
4744
4745 // This type conversion operator template allows Pointer(m) to be
4746 // used as a matcher for any pointer type whose pointer type is
4747 // compatible with the inner matcher, where type PointerType can be
4748 // either a raw pointer or a smart pointer.
4749 //
4750 // The reason we do this instead of relying on
4751 // MakePolymorphicMatcher() is that the latter is not flexible
4752 // enough for implementing the DescribeTo() method of Pointer().
4753 template <typename PointerType>
4754 operator Matcher<PointerType>() const { // NOLINT
4755 return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));
4756 }
4757
4758 private:
4759 // The monomorphic implementation that works for a particular pointer type.
4760 template <typename PointerType>
4761 class Impl : public MatcherInterface<PointerType> {
4762 public:
4763 using Pointer =
4764 const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
4765 PointerType)>::element_type*;
4766
4767 explicit Impl(const InnerMatcher& matcher)
4768 : matcher_(MatcherCast<Pointer>(matcher)) {}
4769
4770 void DescribeTo(::std::ostream* os) const override {
4771 *os << "is a pointer that ";
4772 matcher_.DescribeTo(os);
4773 }
4774
4775 void DescribeNegationTo(::std::ostream* os) const override {
4776 *os << "is not a pointer that ";
4777 matcher_.DescribeTo(os);
4778 }
4779
4780 bool MatchAndExplain(PointerType pointer,
4781 MatchResultListener* listener) const override {
4782 *listener << "which is a pointer that ";
4783 Pointer p = GetRawPointer(pointer);
4784 return MatchPrintAndExplain(p, matcher_, listener);
4785 }
4786
4787 private:
4788 Matcher<Pointer> matcher_;
4789 };
4790
4791 const InnerMatcher matcher_;
4792 };
4793
4794 #if GTEST_HAS_RTTI
4795 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
4796 // reference that matches inner_matcher when dynamic_cast<T> is applied.
4797 // The result of dynamic_cast<To> is forwarded to the inner matcher.
4798 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
4799 // If To is a reference and the cast fails, this matcher returns false
4800 // immediately.
4801 template <typename To>
4802 class WhenDynamicCastToMatcherBase {
4803 public:
4804 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
4805 : matcher_(matcher) {}
4806
4807 void DescribeTo(::std::ostream* os) const {
4808 GetCastTypeDescription(os);
4809 matcher_.DescribeTo(os);
4810 }
4811
4812 void DescribeNegationTo(::std::ostream* os) const {
4813 GetCastTypeDescription(os);
4814 matcher_.DescribeNegationTo(os);
4815 }
4816
4817 protected:
4818 const Matcher<To> matcher_;
4819
4820 static std::string GetToName() {
4821 return GetTypeName<To>();
4822 }
4823
4824 private:
4825 static void GetCastTypeDescription(::std::ostream* os) {
4826 *os << "when dynamic_cast to " << GetToName() << ", ";
4827 }
4828 };
4829
4830 // Primary template.
4831 // To is a pointer. Cast and forward the result.
4832 template <typename To>
4833 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
4834 public:
4835 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
4836 : WhenDynamicCastToMatcherBase<To>(matcher) {}
4837
4838 template <typename From>
4839 bool MatchAndExplain(From from, MatchResultListener* listener) const {
4840 To to = dynamic_cast<To>(from);
4841 return MatchPrintAndExplain(to, this->matcher_, listener);
4842 }
4843 };
4844
4845 // Specialize for references.
4846 // In this case we return false if the dynamic_cast fails.
4847 template <typename To>
4848 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
4849 public:
4850 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
4851 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
4852
4853 template <typename From>
4854 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
4855 // We don't want an std::bad_cast here, so do the cast with pointers.
4856 To* to = dynamic_cast<To*>(&from);
4857 if (to == nullptr) {
4858 *listener << "which cannot be dynamic_cast to " << this->GetToName();
4859 return false;
4860 }
4861 return MatchPrintAndExplain(*to, this->matcher_, listener);
4862 }
4863 };
4864 #endif // GTEST_HAS_RTTI
4865
4866 // Implements the Field() matcher for matching a field (i.e. member
4867 // variable) of an object.
4868 template <typename Class, typename FieldType>
4869 class FieldMatcher {
4870 public:
4871 FieldMatcher(FieldType Class::*field,
4872 const Matcher<const FieldType&>& matcher)
4873 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
4874
4875 FieldMatcher(const std::string& field_name, FieldType Class::*field,
4876 const Matcher<const FieldType&>& matcher)
4877 : field_(field),
4878 matcher_(matcher),
4879 whose_field_("whose field `" + field_name + "` ") {}
4880
4881 void DescribeTo(::std::ostream* os) const {
4882 *os << "is an object " << whose_field_;
4883 matcher_.DescribeTo(os);
4884 }
4885
4886 void DescribeNegationTo(::std::ostream* os) const {
4887 *os << "is an object " << whose_field_;
4888 matcher_.DescribeNegationTo(os);
4889 }
4890
4891 template <typename T>
4892 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
4893 // FIXME: The dispatch on std::is_pointer was introduced as a workaround for
4894 // a compiler bug, and can now be removed.
4895 return MatchAndExplainImpl(
4896 typename std::is_pointer<typename std::remove_const<T>::type>::type(),
4897 value, listener);
4898 }
4899
4900 private:
4901 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
4902 const Class& obj,
4903 MatchResultListener* listener) const {
4904 *listener << whose_field_ << "is ";
4905 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
4906 }
4907
4908 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
4909 MatchResultListener* listener) const {
4910 if (p == nullptr) return false;
4911
4912 *listener << "which points to an object ";
4913 // Since *p has a field, it must be a class/struct/union type and
4914 // thus cannot be a pointer. Therefore we pass false_type() as
4915 // the first argument.
4916 return MatchAndExplainImpl(std::false_type(), *p, listener);
4917 }
4918
4919 const FieldType Class::*field_;
4920 const Matcher<const FieldType&> matcher_;
4921
4922 // Contains either "whose given field " if the name of the field is unknown
4923 // or "whose field `name_of_field` " if the name is known.
4924 const std::string whose_field_;
4925 };
4926
4927 // Implements the Property() matcher for matching a property
4928 // (i.e. return value of a getter method) of an object.
4929 //
4930 // Property is a const-qualified member function of Class returning
4931 // PropertyType.
4932 template <typename Class, typename PropertyType, typename Property>
4933 class PropertyMatcher {
4934 public:
4935 typedef const PropertyType& RefToConstProperty;
4936
4937 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
4938 : property_(property),
4939 matcher_(matcher),
4940 whose_property_("whose given property ") {}
4941
4942 PropertyMatcher(const std::string& property_name, Property property,
4943 const Matcher<RefToConstProperty>& matcher)
4944 : property_(property),
4945 matcher_(matcher),
4946 whose_property_("whose property `" + property_name + "` ") {}
4947
4948 void DescribeTo(::std::ostream* os) const {
4949 *os << "is an object " << whose_property_;
4950 matcher_.DescribeTo(os);
4951 }
4952
4953 void DescribeNegationTo(::std::ostream* os) const {
4954 *os << "is an object " << whose_property_;
4955 matcher_.DescribeNegationTo(os);
4956 }
4957
4958 template <typename T>
4959 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
4960 return MatchAndExplainImpl(
4961 typename std::is_pointer<typename std::remove_const<T>::type>::type(),
4962 value, listener);
4963 }
4964
4965 private:
4966 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
4967 const Class& obj,
4968 MatchResultListener* listener) const {
4969 *listener << whose_property_ << "is ";
4970 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
4971 // which takes a non-const reference as argument.
4972 RefToConstProperty result = (obj.*property_)();
4973 return MatchPrintAndExplain(result, matcher_, listener);
4974 }
4975
4976 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
4977 MatchResultListener* listener) const {
4978 if (p == nullptr) return false;
4979
4980 *listener << "which points to an object ";
4981 // Since *p has a property method, it must be a class/struct/union
4982 // type and thus cannot be a pointer. Therefore we pass
4983 // false_type() as the first argument.
4984 return MatchAndExplainImpl(std::false_type(), *p, listener);
4985 }
4986
4987 Property property_;
4988 const Matcher<RefToConstProperty> matcher_;
4989
4990 // Contains either "whose given property " if the name of the property is
4991 // unknown or "whose property `name_of_property` " if the name is known.
4992 const std::string whose_property_;
4993 };
4994
4995 // Type traits specifying various features of different functors for ResultOf.
4996 // The default template specifies features for functor objects.
4997 template <typename Functor>
4998 struct CallableTraits {
4999 typedef Functor StorageType;
5000
5001 static void CheckIsValid(Functor /* functor */) {}
5002
5003 template <typename T>
5004 static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {
5005 return f(arg);
5006 }
5007 };
5008
5009 // Specialization for function pointers.
5010 template <typename ArgType, typename ResType>
5011 struct CallableTraits<ResType(*)(ArgType)> {
5012 typedef ResType ResultType;
5013 typedef ResType(*StorageType)(ArgType);
5014
5015 static void CheckIsValid(ResType(*f)(ArgType)) {
5016 GTEST_CHECK_(f != nullptr)
5017 << "NULL function pointer is passed into ResultOf().";
5018 }
5019 template <typename T>
5020 static ResType Invoke(ResType(*f)(ArgType), T arg) {
5021 return (*f)(arg);
5022 }
5023 };
5024
5025 // Implements the ResultOf() matcher for matching a return value of a
5026 // unary function of an object.
5027 template <typename Callable, typename InnerMatcher>
5028 class ResultOfMatcher {
5029 public:
5030 ResultOfMatcher(Callable callable, InnerMatcher matcher)
5031 : callable_(std::move(callable)), matcher_(std::move(matcher)) {
5032 CallableTraits<Callable>::CheckIsValid(callable_);
5033 }
5034
5035 template <typename T>
5036 operator Matcher<T>() const {
5037 return Matcher<T>(new Impl<const T&>(callable_, matcher_));
5038 }
5039
5040 private:
5041 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
5042
5043 template <typename T>
5044 class Impl : public MatcherInterface<T> {
5045 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
5046 std::declval<CallableStorageType>(), std::declval<T>()));
5047
5048 public:
5049 template <typename M>
5050 Impl(const CallableStorageType& callable, const M& matcher)
5051 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
5052
5053 void DescribeTo(::std::ostream* os) const override {
5054 *os << "is mapped by the given callable to a value that ";
5055 matcher_.DescribeTo(os);
5056 }
5057
5058 void DescribeNegationTo(::std::ostream* os) const override {
5059 *os << "is mapped by the given callable to a value that ";
5060 matcher_.DescribeNegationTo(os);
5061 }
5062
5063 bool MatchAndExplain(T obj, MatchResultListener* listener) const override {
5064 *listener << "which is mapped by the given callable to ";
5065 // Cannot pass the return value directly to MatchPrintAndExplain, which
5066 // takes a non-const reference as argument.
5067 // Also, specifying template argument explicitly is needed because T could
5068 // be a non-const reference (e.g. Matcher<Uncopyable&>).
5069 ResultType result =
5070 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
5071 return MatchPrintAndExplain(result, matcher_, listener);
5072 }
5073
5074 private:
5075 // Functors often define operator() as non-const method even though
5076 // they are actually stateless. But we need to use them even when
5077 // 'this' is a const pointer. It's the user's responsibility not to
5078 // use stateful callables with ResultOf(), which doesn't guarantee
5079 // how many times the callable will be invoked.
5080 mutable CallableStorageType callable_;
5081 const Matcher<ResultType> matcher_;
5082 }; // class Impl
5083
5084 const CallableStorageType callable_;
5085 const InnerMatcher matcher_;
5086 };
5087
5088 // Implements a matcher that checks the size of an STL-style container.
5089 template <typename SizeMatcher>
5090 class SizeIsMatcher {
5091 public:
5092 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
5093 : size_matcher_(size_matcher) {
5094 }
5095
5096 template <typename Container>
5097 operator Matcher<Container>() const {
5098 return Matcher<Container>(new Impl<const Container&>(size_matcher_));
5099 }
5100
5101 template <typename Container>
5102 class Impl : public MatcherInterface<Container> {
5103 public:
5104 using SizeType = decltype(std::declval<Container>().size());
5105 explicit Impl(const SizeMatcher& size_matcher)
5106 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
5107
5108 void DescribeTo(::std::ostream* os) const override {
5109 *os << "size ";
5110 size_matcher_.DescribeTo(os);
5111 }
5112 void DescribeNegationTo(::std::ostream* os) const override {
5113 *os << "size ";
5114 size_matcher_.DescribeNegationTo(os);
5115 }
5116
5117 bool MatchAndExplain(Container container,
5118 MatchResultListener* listener) const override {
5119 SizeType size = container.size();
5120 StringMatchResultListener size_listener;
5121 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
5122 *listener
5123 << "whose size " << size << (result ? " matches" : " doesn't match");
5124 PrintIfNotEmpty(size_listener.str(), listener->stream());
5125 return result;
5126 }
5127
5128 private:
5129 const Matcher<SizeType> size_matcher_;
5130 };
5131
5132 private:
5133 const SizeMatcher size_matcher_;
5134 };
5135
5136 // Implements a matcher that checks the begin()..end() distance of an STL-style
5137 // container.
5138 template <typename DistanceMatcher>
5139 class BeginEndDistanceIsMatcher {
5140 public:
5141 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
5142 : distance_matcher_(distance_matcher) {}
5143
5144 template <typename Container>
5145 operator Matcher<Container>() const {
5146 return Matcher<Container>(new Impl<const Container&>(distance_matcher_));
5147 }
5148
5149 template <typename Container>
5150 class Impl : public MatcherInterface<Container> {
5151 public:
5152 typedef internal::StlContainerView<
5153 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
5154 typedef typename std::iterator_traits<
5155 typename ContainerView::type::const_iterator>::difference_type
5156 DistanceType;
5157 explicit Impl(const DistanceMatcher& distance_matcher)
5158 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
5159
5160 void DescribeTo(::std::ostream* os) const override {
5161 *os << "distance between begin() and end() ";
5162 distance_matcher_.DescribeTo(os);
5163 }
5164 void DescribeNegationTo(::std::ostream* os) const override {
5165 *os << "distance between begin() and end() ";
5166 distance_matcher_.DescribeNegationTo(os);
5167 }
5168
5169 bool MatchAndExplain(Container container,
5170 MatchResultListener* listener) const override {
5171 using std::begin;
5172 using std::end;
5173 DistanceType distance = std::distance(begin(container), end(container));
5174 StringMatchResultListener distance_listener;
5175 const bool result =
5176 distance_matcher_.MatchAndExplain(distance, &distance_listener);
5177 *listener << "whose distance between begin() and end() " << distance
5178 << (result ? " matches" : " doesn't match");
5179 PrintIfNotEmpty(distance_listener.str(), listener->stream());
5180 return result;
5181 }
5182
5183 private:
5184 const Matcher<DistanceType> distance_matcher_;
5185 };
5186
5187 private:
5188 const DistanceMatcher distance_matcher_;
5189 };
5190
5191 // Implements an equality matcher for any STL-style container whose elements
5192 // support ==. This matcher is like Eq(), but its failure explanations provide
5193 // more detailed information that is useful when the container is used as a set.
5194 // The failure message reports elements that are in one of the operands but not
5195 // the other. The failure messages do not report duplicate or out-of-order
5196 // elements in the containers (which don't properly matter to sets, but can
5197 // occur if the containers are vectors or lists, for example).
5198 //
5199 // Uses the container's const_iterator, value_type, operator ==,
5200 // begin(), and end().
5201 template <typename Container>
5202 class ContainerEqMatcher {
5203 public:
5204 typedef internal::StlContainerView<Container> View;
5205 typedef typename View::type StlContainer;
5206 typedef typename View::const_reference StlContainerReference;
5207
5208 static_assert(!std::is_const<Container>::value,
5209 "Container type must not be const");
5210 static_assert(!std::is_reference<Container>::value,
5211 "Container type must not be a reference");
5212
5213 // We make a copy of expected in case the elements in it are modified
5214 // after this matcher is created.
5215 explicit ContainerEqMatcher(const Container& expected)
5216 : expected_(View::Copy(expected)) {}
5217
5218 void DescribeTo(::std::ostream* os) const {
5219 *os << "equals ";
5220 UniversalPrint(expected_, os);
5221 }
5222 void DescribeNegationTo(::std::ostream* os) const {
5223 *os << "does not equal ";
5224 UniversalPrint(expected_, os);
5225 }
5226
5227 template <typename LhsContainer>
5228 bool MatchAndExplain(const LhsContainer& lhs,
5229 MatchResultListener* listener) const {
5230 typedef internal::StlContainerView<
5231 typename std::remove_const<LhsContainer>::type>
5232 LhsView;
5233 typedef typename LhsView::type LhsStlContainer;
5234 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5235 if (lhs_stl_container == expected_)
5236 return true;
5237
5238 ::std::ostream* const os = listener->stream();
5239 if (os != nullptr) {
5240 // Something is different. Check for extra values first.
5241 bool printed_header = false;
5242 for (typename LhsStlContainer::const_iterator it =
5243 lhs_stl_container.begin();
5244 it != lhs_stl_container.end(); ++it) {
5245 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
5246 expected_.end()) {
5247 if (printed_header) {
5248 *os << ", ";
5249 } else {
5250 *os << "which has these unexpected elements: ";
5251 printed_header = true;
5252 }
5253 UniversalPrint(*it, os);
5254 }
5255 }
5256
5257 // Now check for missing values.
5258 bool printed_header2 = false;
5259 for (typename StlContainer::const_iterator it = expected_.begin();
5260 it != expected_.end(); ++it) {
5261 if (internal::ArrayAwareFind(
5262 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
5263 lhs_stl_container.end()) {
5264 if (printed_header2) {
5265 *os << ", ";
5266 } else {
5267 *os << (printed_header ? ",\nand" : "which")
5268 << " doesn't have these expected elements: ";
5269 printed_header2 = true;
5270 }
5271 UniversalPrint(*it, os);
5272 }
5273 }
5274 }
5275
5276 return false;
5277 }
5278
5279 private:
5280 const StlContainer expected_;
5281 };
5282
5283 // A comparator functor that uses the < operator to compare two values.
5284 struct LessComparator {
5285 template <typename T, typename U>
5286 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
5287 };
5288
5289 // Implements WhenSortedBy(comparator, container_matcher).
5290 template <typename Comparator, typename ContainerMatcher>
5291 class WhenSortedByMatcher {
5292 public:
5293 WhenSortedByMatcher(const Comparator& comparator,
5294 const ContainerMatcher& matcher)
5295 : comparator_(comparator), matcher_(matcher) {}
5296
5297 template <typename LhsContainer>
5298 operator Matcher<LhsContainer>() const {
5299 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
5300 }
5301
5302 template <typename LhsContainer>
5303 class Impl : public MatcherInterface<LhsContainer> {
5304 public:
5305 typedef internal::StlContainerView<
5306 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
5307 typedef typename LhsView::type LhsStlContainer;
5308 typedef typename LhsView::const_reference LhsStlContainerReference;
5309 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
5310 // so that we can match associative containers.
5311 typedef typename RemoveConstFromKey<
5312 typename LhsStlContainer::value_type>::type LhsValue;
5313
5314 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
5315 : comparator_(comparator), matcher_(matcher) {}
5316
5317 void DescribeTo(::std::ostream* os) const override {
5318 *os << "(when sorted) ";
5319 matcher_.DescribeTo(os);
5320 }
5321
5322 void DescribeNegationTo(::std::ostream* os) const override {
5323 *os << "(when sorted) ";
5324 matcher_.DescribeNegationTo(os);
5325 }
5326
5327 bool MatchAndExplain(LhsContainer lhs,
5328 MatchResultListener* listener) const override {
5329 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5330 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
5331 lhs_stl_container.end());
5332 ::std::sort(
5333 sorted_container.begin(), sorted_container.end(), comparator_);
5334
5335 if (!listener->IsInterested()) {
5336 // If the listener is not interested, we do not need to
5337 // construct the inner explanation.
5338 return matcher_.Matches(sorted_container);
5339 }
5340
5341 *listener << "which is ";
5342 UniversalPrint(sorted_container, listener->stream());
5343 *listener << " when sorted";
5344
5345 StringMatchResultListener inner_listener;
5346 const bool match = matcher_.MatchAndExplain(sorted_container,
5347 &inner_listener);
5348 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5349 return match;
5350 }
5351
5352 private:
5353 const Comparator comparator_;
5354 const Matcher<const ::std::vector<LhsValue>&> matcher_;
5355
5356 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
5357 };
5358
5359 private:
5360 const Comparator comparator_;
5361 const ContainerMatcher matcher_;
5362 };
5363
5364 // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
5365 // must be able to be safely cast to Matcher<std::tuple<const T1&, const
5366 // T2&> >, where T1 and T2 are the types of elements in the LHS
5367 // container and the RHS container respectively.
5368 template <typename TupleMatcher, typename RhsContainer>
5369 class PointwiseMatcher {
5370 GTEST_COMPILE_ASSERT_(
5371 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
5372 use_UnorderedPointwise_with_hash_tables);
5373
5374 public:
5375 typedef internal::StlContainerView<RhsContainer> RhsView;
5376 typedef typename RhsView::type RhsStlContainer;
5377 typedef typename RhsStlContainer::value_type RhsValue;
5378
5379 static_assert(!std::is_const<RhsContainer>::value,
5380 "RhsContainer type must not be const");
5381 static_assert(!std::is_reference<RhsContainer>::value,
5382 "RhsContainer type must not be a reference");
5383
5384 // Like ContainerEq, we make a copy of rhs in case the elements in
5385 // it are modified after this matcher is created.
5386 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
5387 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}
5388
5389 template <typename LhsContainer>
5390 operator Matcher<LhsContainer>() const {
5391 GTEST_COMPILE_ASSERT_(
5392 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
5393 use_UnorderedPointwise_with_hash_tables);
5394
5395 return Matcher<LhsContainer>(
5396 new Impl<const LhsContainer&>(tuple_matcher_, rhs_));
5397 }
5398
5399 template <typename LhsContainer>
5400 class Impl : public MatcherInterface<LhsContainer> {
5401 public:
5402 typedef internal::StlContainerView<
5403 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
5404 typedef typename LhsView::type LhsStlContainer;
5405 typedef typename LhsView::const_reference LhsStlContainerReference;
5406 typedef typename LhsStlContainer::value_type LhsValue;
5407 // We pass the LHS value and the RHS value to the inner matcher by
5408 // reference, as they may be expensive to copy. We must use tuple
5409 // instead of pair here, as a pair cannot hold references (C++ 98,
5410 // 20.2.2 [lib.pairs]).
5411 typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
5412
5413 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
5414 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
5415 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
5416 rhs_(rhs) {}
5417
5418 void DescribeTo(::std::ostream* os) const override {
5419 *os << "contains " << rhs_.size()
5420 << " values, where each value and its corresponding value in ";
5421 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
5422 *os << " ";
5423 mono_tuple_matcher_.DescribeTo(os);
5424 }
5425 void DescribeNegationTo(::std::ostream* os) const override {
5426 *os << "doesn't contain exactly " << rhs_.size()
5427 << " values, or contains a value x at some index i"
5428 << " where x and the i-th value of ";
5429 UniversalPrint(rhs_, os);
5430 *os << " ";
5431 mono_tuple_matcher_.DescribeNegationTo(os);
5432 }
5433
5434 bool MatchAndExplain(LhsContainer lhs,
5435 MatchResultListener* listener) const override {
5436 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5437 const size_t actual_size = lhs_stl_container.size();
5438 if (actual_size != rhs_.size()) {
5439 *listener << "which contains " << actual_size << " values";
5440 return false;
5441 }
5442
5443 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
5444 typename RhsStlContainer::const_iterator right = rhs_.begin();
5445 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
5446 if (listener->IsInterested()) {
5447 StringMatchResultListener inner_listener;
5448 // Create InnerMatcherArg as a temporarily object to avoid it outlives
5449 // *left and *right. Dereference or the conversion to `const T&` may
5450 // return temp objects, e.g for vector<bool>.
5451 if (!mono_tuple_matcher_.MatchAndExplain(
5452 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
5453 ImplicitCast_<const RhsValue&>(*right)),
5454 &inner_listener)) {
5455 *listener << "where the value pair (";
5456 UniversalPrint(*left, listener->stream());
5457 *listener << ", ";
5458 UniversalPrint(*right, listener->stream());
5459 *listener << ") at index #" << i << " don't match";
5460 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5461 return false;
5462 }
5463 } else {
5464 if (!mono_tuple_matcher_.Matches(
5465 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
5466 ImplicitCast_<const RhsValue&>(*right))))
5467 return false;
5468 }
5469 }
5470
5471 return true;
5472 }
5473
5474 private:
5475 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
5476 const RhsStlContainer rhs_;
5477 };
5478
5479 private:
5480 const TupleMatcher tuple_matcher_;
5481 const RhsStlContainer rhs_;
5482 };
5483
5484 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
5485 template <typename Container>
5486 class QuantifierMatcherImpl : public MatcherInterface<Container> {
5487 public:
5488 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
5489 typedef StlContainerView<RawContainer> View;
5490 typedef typename View::type StlContainer;
5491 typedef typename View::const_reference StlContainerReference;
5492 typedef typename StlContainer::value_type Element;
5493
5494 template <typename InnerMatcher>
5495 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
5496 : inner_matcher_(
5497 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
5498
5499 // Checks whether:
5500 // * All elements in the container match, if all_elements_should_match.
5501 // * Any element in the container matches, if !all_elements_should_match.
5502 bool MatchAndExplainImpl(bool all_elements_should_match,
5503 Container container,
5504 MatchResultListener* listener) const {
5505 StlContainerReference stl_container = View::ConstReference(container);
5506 size_t i = 0;
5507 for (typename StlContainer::const_iterator it = stl_container.begin();
5508 it != stl_container.end(); ++it, ++i) {
5509 StringMatchResultListener inner_listener;
5510 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
5511
5512 if (matches != all_elements_should_match) {
5513 *listener << "whose element #" << i
5514 << (matches ? " matches" : " doesn't match");
5515 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5516 return !all_elements_should_match;
5517 }
5518 }
5519 return all_elements_should_match;
5520 }
5521
5522 protected:
5523 const Matcher<const Element&> inner_matcher_;
5524 };
5525
5526 // Implements Contains(element_matcher) for the given argument type Container.
5527 // Symmetric to EachMatcherImpl.
5528 template <typename Container>
5529 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
5530 public:
5531 template <typename InnerMatcher>
5532 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
5533 : QuantifierMatcherImpl<Container>(inner_matcher) {}
5534
5535 // Describes what this matcher does.
5536 void DescribeTo(::std::ostream* os) const override {
5537 *os << "contains at least one element that ";
5538 this->inner_matcher_.DescribeTo(os);
5539 }
5540
5541 void DescribeNegationTo(::std::ostream* os) const override {
5542 *os << "doesn't contain any element that ";
5543 this->inner_matcher_.DescribeTo(os);
5544 }
5545
5546 bool MatchAndExplain(Container container,
5547 MatchResultListener* listener) const override {
5548 return this->MatchAndExplainImpl(false, container, listener);
5549 }
5550 };
5551
5552 // Implements Each(element_matcher) for the given argument type Container.
5553 // Symmetric to ContainsMatcherImpl.
5554 template <typename Container>
5555 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
5556 public:
5557 template <typename InnerMatcher>
5558 explicit EachMatcherImpl(InnerMatcher inner_matcher)
5559 : QuantifierMatcherImpl<Container>(inner_matcher) {}
5560
5561 // Describes what this matcher does.
5562 void DescribeTo(::std::ostream* os) const override {
5563 *os << "only contains elements that ";
5564 this->inner_matcher_.DescribeTo(os);
5565 }
5566
5567 void DescribeNegationTo(::std::ostream* os) const override {
5568 *os << "contains some element that ";
5569 this->inner_matcher_.DescribeNegationTo(os);
5570 }
5571
5572 bool MatchAndExplain(Container container,
5573 MatchResultListener* listener) const override {
5574 return this->MatchAndExplainImpl(true, container, listener);
5575 }
5576 };
5577
5578 // Implements polymorphic Contains(element_matcher).
5579 template <typename M>
5580 class ContainsMatcher {
5581 public:
5582 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
5583
5584 template <typename Container>
5585 operator Matcher<Container>() const {
5586 return Matcher<Container>(
5587 new ContainsMatcherImpl<const Container&>(inner_matcher_));
5588 }
5589
5590 private:
5591 const M inner_matcher_;
5592 };
5593
5594 // Implements polymorphic Each(element_matcher).
5595 template <typename M>
5596 class EachMatcher {
5597 public:
5598 explicit EachMatcher(M m) : inner_matcher_(m) {}
5599
5600 template <typename Container>
5601 operator Matcher<Container>() const {
5602 return Matcher<Container>(
5603 new EachMatcherImpl<const Container&>(inner_matcher_));
5604 }
5605
5606 private:
5607 const M inner_matcher_;
5608 };
5609
5610 struct Rank1 {};
5611 struct Rank0 : Rank1 {};
5612
5613 namespace pair_getters {
5614 using std::get;
5615 template <typename T>
5616 auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
5617 return get<0>(x);
5618 }
5619 template <typename T>
5620 auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
5621 return x.first;
5622 }
5623
5624 template <typename T>
5625 auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
5626 return get<1>(x);
5627 }
5628 template <typename T>
5629 auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
5630 return x.second;
5631 }
5632 } // namespace pair_getters
5633
5634 // Implements Key(inner_matcher) for the given argument pair type.
5635 // Key(inner_matcher) matches an std::pair whose 'first' field matches
5636 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5637 // std::map that contains at least one element whose key is >= 5.
5638 template <typename PairType>
5639 class KeyMatcherImpl : public MatcherInterface<PairType> {
5640 public:
5641 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
5642 typedef typename RawPairType::first_type KeyType;
5643
5644 template <typename InnerMatcher>
5645 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
5646 : inner_matcher_(
5647 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
5648 }
5649
5650 // Returns true if and only if 'key_value.first' (the key) matches the inner
5651 // matcher.
5652 bool MatchAndExplain(PairType key_value,
5653 MatchResultListener* listener) const override {
5654 StringMatchResultListener inner_listener;
5655 const bool match = inner_matcher_.MatchAndExplain(
5656 pair_getters::First(key_value, Rank0()), &inner_listener);
5657 const std::string explanation = inner_listener.str();
5658 if (explanation != "") {
5659 *listener << "whose first field is a value " << explanation;
5660 }
5661 return match;
5662 }
5663
5664 // Describes what this matcher does.
5665 void DescribeTo(::std::ostream* os) const override {
5666 *os << "has a key that ";
5667 inner_matcher_.DescribeTo(os);
5668 }
5669
5670 // Describes what the negation of this matcher does.
5671 void DescribeNegationTo(::std::ostream* os) const override {
5672 *os << "doesn't have a key that ";
5673 inner_matcher_.DescribeTo(os);
5674 }
5675
5676 private:
5677 const Matcher<const KeyType&> inner_matcher_;
5678 };
5679
5680 // Implements polymorphic Key(matcher_for_key).
5681 template <typename M>
5682 class KeyMatcher {
5683 public:
5684 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
5685
5686 template <typename PairType>
5687 operator Matcher<PairType>() const {
5688 return Matcher<PairType>(
5689 new KeyMatcherImpl<const PairType&>(matcher_for_key_));
5690 }
5691
5692 private:
5693 const M matcher_for_key_;
5694 };
5695
5696 // Implements polymorphic Address(matcher_for_address).
5697 template <typename InnerMatcher>
5698 class AddressMatcher {
5699 public:
5700 explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}
5701
5702 template <typename Type>
5703 operator Matcher<Type>() const { // NOLINT
5704 return Matcher<Type>(new Impl<const Type&>(matcher_));
5705 }
5706
5707 private:
5708 // The monomorphic implementation that works for a particular object type.
5709 template <typename Type>
5710 class Impl : public MatcherInterface<Type> {
5711 public:
5712 using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;
5713 explicit Impl(const InnerMatcher& matcher)
5714 : matcher_(MatcherCast<Address>(matcher)) {}
5715
5716 void DescribeTo(::std::ostream* os) const override {
5717 *os << "has address that ";
5718 matcher_.DescribeTo(os);
5719 }
5720
5721 void DescribeNegationTo(::std::ostream* os) const override {
5722 *os << "does not have address that ";
5723 matcher_.DescribeTo(os);
5724 }
5725
5726 bool MatchAndExplain(Type object,
5727 MatchResultListener* listener) const override {
5728 *listener << "which has address ";
5729 Address address = std::addressof(object);
5730 return MatchPrintAndExplain(address, matcher_, listener);
5731 }
5732
5733 private:
5734 const Matcher<Address> matcher_;
5735 };
5736 const InnerMatcher matcher_;
5737 };
5738
5739 // Implements Pair(first_matcher, second_matcher) for the given argument pair
5740 // type with its two matchers. See Pair() function below.
5741 template <typename PairType>
5742 class PairMatcherImpl : public MatcherInterface<PairType> {
5743 public:
5744 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
5745 typedef typename RawPairType::first_type FirstType;
5746 typedef typename RawPairType::second_type SecondType;
5747
5748 template <typename FirstMatcher, typename SecondMatcher>
5749 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
5750 : first_matcher_(
5751 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
5752 second_matcher_(
5753 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
5754 }
5755
5756 // Describes what this matcher does.
5757 void DescribeTo(::std::ostream* os) const override {
5758 *os << "has a first field that ";
5759 first_matcher_.DescribeTo(os);
5760 *os << ", and has a second field that ";
5761 second_matcher_.DescribeTo(os);
5762 }
5763
5764 // Describes what the negation of this matcher does.
5765 void DescribeNegationTo(::std::ostream* os) const override {
5766 *os << "has a first field that ";
5767 first_matcher_.DescribeNegationTo(os);
5768 *os << ", or has a second field that ";
5769 second_matcher_.DescribeNegationTo(os);
5770 }
5771
5772 // Returns true if and only if 'a_pair.first' matches first_matcher and
5773 // 'a_pair.second' matches second_matcher.
5774 bool MatchAndExplain(PairType a_pair,
5775 MatchResultListener* listener) const override {
5776 if (!listener->IsInterested()) {
5777 // If the listener is not interested, we don't need to construct the
5778 // explanation.
5779 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
5780 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
5781 }
5782 StringMatchResultListener first_inner_listener;
5783 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
5784 &first_inner_listener)) {
5785 *listener << "whose first field does not match";
5786 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
5787 return false;
5788 }
5789 StringMatchResultListener second_inner_listener;
5790 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
5791 &second_inner_listener)) {
5792 *listener << "whose second field does not match";
5793 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
5794 return false;
5795 }
5796 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
5797 listener);
5798 return true;
5799 }
5800
5801 private:
5802 void ExplainSuccess(const std::string& first_explanation,
5803 const std::string& second_explanation,
5804 MatchResultListener* listener) const {
5805 *listener << "whose both fields match";
5806 if (first_explanation != "") {
5807 *listener << ", where the first field is a value " << first_explanation;
5808 }
5809 if (second_explanation != "") {
5810 *listener << ", ";
5811 if (first_explanation != "") {
5812 *listener << "and ";
5813 } else {
5814 *listener << "where ";
5815 }
5816 *listener << "the second field is a value " << second_explanation;
5817 }
5818 }
5819
5820 const Matcher<const FirstType&> first_matcher_;
5821 const Matcher<const SecondType&> second_matcher_;
5822 };
5823
5824 // Implements polymorphic Pair(first_matcher, second_matcher).
5825 template <typename FirstMatcher, typename SecondMatcher>
5826 class PairMatcher {
5827 public:
5828 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
5829 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
5830
5831 template <typename PairType>
5832 operator Matcher<PairType> () const {
5833 return Matcher<PairType>(
5834 new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));
5835 }
5836
5837 private:
5838 const FirstMatcher first_matcher_;
5839 const SecondMatcher second_matcher_;
5840 };
5841
5842 template <typename T, size_t... I>
5843 auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
5844 -> decltype(std::tie(get<I>(t)...)) {
5845 static_assert(std::tuple_size<T>::value == sizeof...(I),
5846 "Number of arguments doesn't match the number of fields.");
5847 return std::tie(get<I>(t)...);
5848 }
5849
5850 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
5851 template <typename T>
5852 auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {
5853 const auto& [a] = t;
5854 return std::tie(a);
5855 }
5856 template <typename T>
5857 auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {
5858 const auto& [a, b] = t;
5859 return std::tie(a, b);
5860 }
5861 template <typename T>
5862 auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {
5863 const auto& [a, b, c] = t;
5864 return std::tie(a, b, c);
5865 }
5866 template <typename T>
5867 auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {
5868 const auto& [a, b, c, d] = t;
5869 return std::tie(a, b, c, d);
5870 }
5871 template <typename T>
5872 auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {
5873 const auto& [a, b, c, d, e] = t;
5874 return std::tie(a, b, c, d, e);
5875 }
5876 template <typename T>
5877 auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {
5878 const auto& [a, b, c, d, e, f] = t;
5879 return std::tie(a, b, c, d, e, f);
5880 }
5881 template <typename T>
5882 auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {
5883 const auto& [a, b, c, d, e, f, g] = t;
5884 return std::tie(a, b, c, d, e, f, g);
5885 }
5886 template <typename T>
5887 auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {
5888 const auto& [a, b, c, d, e, f, g, h] = t;
5889 return std::tie(a, b, c, d, e, f, g, h);
5890 }
5891 template <typename T>
5892 auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {
5893 const auto& [a, b, c, d, e, f, g, h, i] = t;
5894 return std::tie(a, b, c, d, e, f, g, h, i);
5895 }
5896 template <typename T>
5897 auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {
5898 const auto& [a, b, c, d, e, f, g, h, i, j] = t;
5899 return std::tie(a, b, c, d, e, f, g, h, i, j);
5900 }
5901 template <typename T>
5902 auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {
5903 const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
5904 return std::tie(a, b, c, d, e, f, g, h, i, j, k);
5905 }
5906 template <typename T>
5907 auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {
5908 const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
5909 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
5910 }
5911 template <typename T>
5912 auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {
5913 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
5914 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
5915 }
5916 template <typename T>
5917 auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {
5918 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
5919 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
5920 }
5921 template <typename T>
5922 auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {
5923 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
5924 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
5925 }
5926 template <typename T>
5927 auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
5928 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
5929 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
5930 }
5931 #endif // defined(__cpp_structured_bindings)
5932
5933 template <size_t I, typename T>
5934 auto UnpackStruct(const T& t)
5935 -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {
5936 return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);
5937 }
5938
5939 // Helper function to do comma folding in C++11.
5940 // The array ensures left-to-right order of evaluation.
5941 // Usage: VariadicExpand({expr...});
5942 template <typename T, size_t N>
5943 void VariadicExpand(const T (&)[N]) {}
5944
5945 template <typename Struct, typename StructSize>
5946 class FieldsAreMatcherImpl;
5947
5948 template <typename Struct, size_t... I>
5949 class FieldsAreMatcherImpl<Struct, IndexSequence<I...>>
5950 : public MatcherInterface<Struct> {
5951 using UnpackedType =
5952 decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
5953 using MatchersType = std::tuple<
5954 Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;
5955
5956 public:
5957 template <typename Inner>
5958 explicit FieldsAreMatcherImpl(const Inner& matchers)
5959 : matchers_(testing::SafeMatcherCast<
5960 const typename std::tuple_element<I, UnpackedType>::type&>(
5961 std::get<I>(matchers))...) {}
5962
5963 void DescribeTo(::std::ostream* os) const override {
5964 const char* separator = "";
5965 VariadicExpand(
5966 {(*os << separator << "has field #" << I << " that ",
5967 std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});
5968 }
5969
5970 void DescribeNegationTo(::std::ostream* os) const override {
5971 const char* separator = "";
5972 VariadicExpand({(*os << separator << "has field #" << I << " that ",
5973 std::get<I>(matchers_).DescribeNegationTo(os),
5974 separator = ", or ")...});
5975 }
5976
5977 bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {
5978 return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);
5979 }
5980
5981 private:
5982 bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {
5983 if (!listener->IsInterested()) {
5984 // If the listener is not interested, we don't need to construct the
5985 // explanation.
5986 bool good = true;
5987 VariadicExpand({good = good && std::get<I>(matchers_).Matches(
5988 std::get<I>(tuple))...});
5989 return good;
5990 }
5991
5992 size_t failed_pos = ~size_t{};
5993
5994 std::vector<StringMatchResultListener> inner_listener(sizeof...(I));
5995
5996 VariadicExpand(
5997 {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(
5998 std::get<I>(tuple), &inner_listener[I])
5999 ? failed_pos = I
6000 : 0 ...});
6001 if (failed_pos != ~size_t{}) {
6002 *listener << "whose field #" << failed_pos << " does not match";
6003 PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());
6004 return false;
6005 }
6006
6007 *listener << "whose all elements match";
6008 const char* separator = ", where";
6009 for (size_t index = 0; index < sizeof...(I); ++index) {
6010 const std::string str = inner_listener[index].str();
6011 if (!str.empty()) {
6012 *listener << separator << " field #" << index << " is a value " << str;
6013 separator = ", and";
6014 }
6015 }
6016
6017 return true;
6018 }
6019
6020 MatchersType matchers_;
6021 };
6022
6023 template <typename... Inner>
6024 class FieldsAreMatcher {
6025 public:
6026 explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}
6027
6028 template <typename Struct>
6029 operator Matcher<Struct>() const { // NOLINT
6030 return Matcher<Struct>(
6031 new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(
6032 matchers_));
6033 }
6034
6035 private:
6036 std::tuple<Inner...> matchers_;
6037 };
6038
6039 // Implements ElementsAre() and ElementsAreArray().
6040 template <typename Container>
6041 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
6042 public:
6043 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6044 typedef internal::StlContainerView<RawContainer> View;
6045 typedef typename View::type StlContainer;
6046 typedef typename View::const_reference StlContainerReference;
6047 typedef typename StlContainer::value_type Element;
6048
6049 // Constructs the matcher from a sequence of element values or
6050 // element matchers.
6051 template <typename InputIter>
6052 ElementsAreMatcherImpl(InputIter first, InputIter last) {
6053 while (first != last) {
6054 matchers_.push_back(MatcherCast<const Element&>(*first++));
6055 }
6056 }
6057
6058 // Describes what this matcher does.
6059 void DescribeTo(::std::ostream* os) const override {
6060 if (count() == 0) {
6061 *os << "is empty";
6062 } else if (count() == 1) {
6063 *os << "has 1 element that ";
6064 matchers_[0].DescribeTo(os);
6065 } else {
6066 *os << "has " << Elements(count()) << " where\n";
6067 for (size_t i = 0; i != count(); ++i) {
6068 *os << "element #" << i << " ";
6069 matchers_[i].DescribeTo(os);
6070 if (i + 1 < count()) {
6071 *os << ",\n";
6072 }
6073 }
6074 }
6075 }
6076
6077 // Describes what the negation of this matcher does.
6078 void DescribeNegationTo(::std::ostream* os) const override {
6079 if (count() == 0) {
6080 *os << "isn't empty";
6081 return;
6082 }
6083
6084 *os << "doesn't have " << Elements(count()) << ", or\n";
6085 for (size_t i = 0; i != count(); ++i) {
6086 *os << "element #" << i << " ";
6087 matchers_[i].DescribeNegationTo(os);
6088 if (i + 1 < count()) {
6089 *os << ", or\n";
6090 }
6091 }
6092 }
6093
6094 bool MatchAndExplain(Container container,
6095 MatchResultListener* listener) const override {
6096 // To work with stream-like "containers", we must only walk
6097 // through the elements in one pass.
6098
6099 const bool listener_interested = listener->IsInterested();
6100
6101 // explanations[i] is the explanation of the element at index i.
6102 ::std::vector<std::string> explanations(count());
6103 StlContainerReference stl_container = View::ConstReference(container);
6104 typename StlContainer::const_iterator it = stl_container.begin();
6105 size_t exam_pos = 0;
6106 bool mismatch_found = false; // Have we found a mismatched element yet?
6107
6108 // Go through the elements and matchers in pairs, until we reach
6109 // the end of either the elements or the matchers, or until we find a
6110 // mismatch.
6111 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
6112 bool match; // Does the current element match the current matcher?
6113 if (listener_interested) {
6114 StringMatchResultListener s;
6115 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
6116 explanations[exam_pos] = s.str();
6117 } else {
6118 match = matchers_[exam_pos].Matches(*it);
6119 }
6120
6121 if (!match) {
6122 mismatch_found = true;
6123 break;
6124 }
6125 }
6126 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
6127
6128 // Find how many elements the actual container has. We avoid
6129 // calling size() s.t. this code works for stream-like "containers"
6130 // that don't define size().
6131 size_t actual_count = exam_pos;
6132 for (; it != stl_container.end(); ++it) {
6133 ++actual_count;
6134 }
6135
6136 if (actual_count != count()) {
6137 // The element count doesn't match. If the container is empty,
6138 // there's no need to explain anything as Google Mock already
6139 // prints the empty container. Otherwise we just need to show
6140 // how many elements there actually are.
6141 if (listener_interested && (actual_count != 0)) {
6142 *listener << "which has " << Elements(actual_count);
6143 }
6144 return false;
6145 }
6146
6147 if (mismatch_found) {
6148 // The element count matches, but the exam_pos-th element doesn't match.
6149 if (listener_interested) {
6150 *listener << "whose element #" << exam_pos << " doesn't match";
6151 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
6152 }
6153 return false;
6154 }
6155
6156 // Every element matches its expectation. We need to explain why
6157 // (the obvious ones can be skipped).
6158 if (listener_interested) {
6159 bool reason_printed = false;
6160 for (size_t i = 0; i != count(); ++i) {
6161 const std::string& s = explanations[i];
6162 if (!s.empty()) {
6163 if (reason_printed) {
6164 *listener << ",\nand ";
6165 }
6166 *listener << "whose element #" << i << " matches, " << s;
6167 reason_printed = true;
6168 }
6169 }
6170 }
6171 return true;
6172 }
6173
6174 private:
6175 static Message Elements(size_t count) {
6176 return Message() << count << (count == 1 ? " element" : " elements");
6177 }
6178
6179 size_t count() const { return matchers_.size(); }
6180
6181 ::std::vector<Matcher<const Element&> > matchers_;
6182 };
6183
6184 // Connectivity matrix of (elements X matchers), in element-major order.
6185 // Initially, there are no edges.
6186 // Use NextGraph() to iterate over all possible edge configurations.
6187 // Use Randomize() to generate a random edge configuration.
6188 class GTEST_API_ MatchMatrix {
6189 public:
6190 MatchMatrix(size_t num_elements, size_t num_matchers)
6191 : num_elements_(num_elements),
6192 num_matchers_(num_matchers),
6193 matched_(num_elements_* num_matchers_, 0) {
6194 }
6195
6196 size_t LhsSize() const { return num_elements_; }
6197 size_t RhsSize() const { return num_matchers_; }
6198 bool HasEdge(size_t ilhs, size_t irhs) const {
6199 return matched_[SpaceIndex(ilhs, irhs)] == 1;
6200 }
6201 void SetEdge(size_t ilhs, size_t irhs, bool b) {
6202 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
6203 }
6204
6205 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
6206 // adds 1 to that number; returns false if incrementing the graph left it
6207 // empty.
6208 bool NextGraph();
6209
6210 void Randomize();
6211
6212 std::string DebugString() const;
6213
6214 private:
6215 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
6216 return ilhs * num_matchers_ + irhs;
6217 }
6218
6219 size_t num_elements_;
6220 size_t num_matchers_;
6221
6222 // Each element is a char interpreted as bool. They are stored as a
6223 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
6224 // a (ilhs, irhs) matrix coordinate into an offset.
6225 ::std::vector<char> matched_;
6226 };
6227
6228 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
6229 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
6230
6231 // Returns a maximum bipartite matching for the specified graph 'g'.
6232 // The matching is represented as a vector of {element, matcher} pairs.
6233 GTEST_API_ ElementMatcherPairs
6234 FindMaxBipartiteMatching(const MatchMatrix& g);
6235
6236 struct UnorderedMatcherRequire {
6237 enum Flags {
6238 Superset = 1 << 0,
6239 Subset = 1 << 1,
6240 ExactMatch = Superset | Subset,
6241 };
6242 };
6243
6244 // Untyped base class for implementing UnorderedElementsAre. By
6245 // putting logic that's not specific to the element type here, we
6246 // reduce binary bloat and increase compilation speed.
6247 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
6248 protected:
6249 explicit UnorderedElementsAreMatcherImplBase(
6250 UnorderedMatcherRequire::Flags matcher_flags)
6251 : match_flags_(matcher_flags) {}
6252
6253 // A vector of matcher describers, one for each element matcher.
6254 // Does not own the describers (and thus can be used only when the
6255 // element matchers are alive).
6256 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
6257
6258 // Describes this UnorderedElementsAre matcher.
6259 void DescribeToImpl(::std::ostream* os) const;
6260
6261 // Describes the negation of this UnorderedElementsAre matcher.
6262 void DescribeNegationToImpl(::std::ostream* os) const;
6263
6264 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
6265 const MatchMatrix& matrix,
6266 MatchResultListener* listener) const;
6267
6268 bool FindPairing(const MatchMatrix& matrix,
6269 MatchResultListener* listener) const;
6270
6271 MatcherDescriberVec& matcher_describers() {
6272 return matcher_describers_;
6273 }
6274
6275 static Message Elements(size_t n) {
6276 return Message() << n << " element" << (n == 1 ? "" : "s");
6277 }
6278
6279 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
6280
6281 private:
6282 UnorderedMatcherRequire::Flags match_flags_;
6283 MatcherDescriberVec matcher_describers_;
6284 };
6285
6286 // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
6287 // IsSupersetOf.
6288 template <typename Container>
6289 class UnorderedElementsAreMatcherImpl
6290 : public MatcherInterface<Container>,
6291 public UnorderedElementsAreMatcherImplBase {
6292 public:
6293 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6294 typedef internal::StlContainerView<RawContainer> View;
6295 typedef typename View::type StlContainer;
6296 typedef typename View::const_reference StlContainerReference;
6297 typedef typename StlContainer::const_iterator StlContainerConstIterator;
6298 typedef typename StlContainer::value_type Element;
6299
6300 template <typename InputIter>
6301 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
6302 InputIter first, InputIter last)
6303 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
6304 for (; first != last; ++first) {
6305 matchers_.push_back(MatcherCast<const Element&>(*first));
6306 }
6307 for (const auto& m : matchers_) {
6308 matcher_describers().push_back(m.GetDescriber());
6309 }
6310 }
6311
6312 // Describes what this matcher does.
6313 void DescribeTo(::std::ostream* os) const override {
6314 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
6315 }
6316
6317 // Describes what the negation of this matcher does.
6318 void DescribeNegationTo(::std::ostream* os) const override {
6319 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
6320 }
6321
6322 bool MatchAndExplain(Container container,
6323 MatchResultListener* listener) const override {
6324 StlContainerReference stl_container = View::ConstReference(container);
6325 ::std::vector<std::string> element_printouts;
6326 MatchMatrix matrix =
6327 AnalyzeElements(stl_container.begin(), stl_container.end(),
6328 &element_printouts, listener);
6329
6330 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
6331 return true;
6332 }
6333
6334 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
6335 if (matrix.LhsSize() != matrix.RhsSize()) {
6336 // The element count doesn't match. If the container is empty,
6337 // there's no need to explain anything as Google Mock already
6338 // prints the empty container. Otherwise we just need to show
6339 // how many elements there actually are.
6340 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
6341 *listener << "which has " << Elements(matrix.LhsSize());
6342 }
6343 return false;
6344 }
6345 }
6346
6347 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
6348 FindPairing(matrix, listener);
6349 }
6350
6351 private:
6352 template <typename ElementIter>
6353 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
6354 ::std::vector<std::string>* element_printouts,
6355 MatchResultListener* listener) const {
6356 element_printouts->clear();
6357 ::std::vector<char> did_match;
6358 size_t num_elements = 0;
6359 DummyMatchResultListener dummy;
6360 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
6361 if (listener->IsInterested()) {
6362 element_printouts->push_back(PrintToString(*elem_first));
6363 }
6364 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
6365 did_match.push_back(
6366 matchers_[irhs].MatchAndExplain(*elem_first, &dummy));
6367 }
6368 }
6369
6370 MatchMatrix matrix(num_elements, matchers_.size());
6371 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
6372 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
6373 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
6374 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
6375 }
6376 }
6377 return matrix;
6378 }
6379
6380 ::std::vector<Matcher<const Element&> > matchers_;
6381 };
6382
6383 // Functor for use in TransformTuple.
6384 // Performs MatcherCast<Target> on an input argument of any type.
6385 template <typename Target>
6386 struct CastAndAppendTransform {
6387 template <typename Arg>
6388 Matcher<Target> operator()(const Arg& a) const {
6389 return MatcherCast<Target>(a);
6390 }
6391 };
6392
6393 // Implements UnorderedElementsAre.
6394 template <typename MatcherTuple>
6395 class UnorderedElementsAreMatcher {
6396 public:
6397 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
6398 : matchers_(args) {}
6399
6400 template <typename Container>
6401 operator Matcher<Container>() const {
6402 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6403 typedef typename internal::StlContainerView<RawContainer>::type View;
6404 typedef typename View::value_type Element;
6405 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
6406 MatcherVec matchers;
6407 matchers.reserve(::std::tuple_size<MatcherTuple>::value);
6408 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
6409 ::std::back_inserter(matchers));
6410 return Matcher<Container>(
6411 new UnorderedElementsAreMatcherImpl<const Container&>(
6412 UnorderedMatcherRequire::ExactMatch, matchers.begin(),
6413 matchers.end()));
6414 }
6415
6416 private:
6417 const MatcherTuple matchers_;
6418 };
6419
6420 // Implements ElementsAre.
6421 template <typename MatcherTuple>
6422 class ElementsAreMatcher {
6423 public:
6424 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
6425
6426 template <typename Container>
6427 operator Matcher<Container>() const {
6428 GTEST_COMPILE_ASSERT_(
6429 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
6430 ::std::tuple_size<MatcherTuple>::value < 2,
6431 use_UnorderedElementsAre_with_hash_tables);
6432
6433 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6434 typedef typename internal::StlContainerView<RawContainer>::type View;
6435 typedef typename View::value_type Element;
6436 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
6437 MatcherVec matchers;
6438 matchers.reserve(::std::tuple_size<MatcherTuple>::value);
6439 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
6440 ::std::back_inserter(matchers));
6441 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
6442 matchers.begin(), matchers.end()));
6443 }
6444
6445 private:
6446 const MatcherTuple matchers_;
6447 };
6448
6449 // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
6450 template <typename T>
6451 class UnorderedElementsAreArrayMatcher {
6452 public:
6453 template <typename Iter>
6454 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
6455 Iter first, Iter last)
6456 : match_flags_(match_flags), matchers_(first, last) {}
6457
6458 template <typename Container>
6459 operator Matcher<Container>() const {
6460 return Matcher<Container>(
6461 new UnorderedElementsAreMatcherImpl<const Container&>(
6462 match_flags_, matchers_.begin(), matchers_.end()));
6463 }
6464
6465 private:
6466 UnorderedMatcherRequire::Flags match_flags_;
6467 ::std::vector<T> matchers_;
6468 };
6469
6470 // Implements ElementsAreArray().
6471 template <typename T>
6472 class ElementsAreArrayMatcher {
6473 public:
6474 template <typename Iter>
6475 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
6476
6477 template <typename Container>
6478 operator Matcher<Container>() const {
6479 GTEST_COMPILE_ASSERT_(
6480 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
6481 use_UnorderedElementsAreArray_with_hash_tables);
6482
6483 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
6484 matchers_.begin(), matchers_.end()));
6485 }
6486
6487 private:
6488 const ::std::vector<T> matchers_;
6489 };
6490
6491 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
6492 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
6493 // second) is a polymorphic matcher that matches a value x if and only if
6494 // tm matches tuple (x, second). Useful for implementing
6495 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
6496 //
6497 // BoundSecondMatcher is copyable and assignable, as we need to put
6498 // instances of this class in a vector when implementing
6499 // UnorderedPointwise().
6500 template <typename Tuple2Matcher, typename Second>
6501 class BoundSecondMatcher {
6502 public:
6503 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
6504 : tuple2_matcher_(tm), second_value_(second) {}
6505
6506 BoundSecondMatcher(const BoundSecondMatcher& other) = default;
6507
6508 template <typename T>
6509 operator Matcher<T>() const {
6510 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
6511 }
6512
6513 // We have to define this for UnorderedPointwise() to compile in
6514 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
6515 // which requires the elements to be assignable in C++98. The
6516 // compiler cannot generate the operator= for us, as Tuple2Matcher
6517 // and Second may not be assignable.
6518 //
6519 // However, this should never be called, so the implementation just
6520 // need to assert.
6521 void operator=(const BoundSecondMatcher& /*rhs*/) {
6522 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
6523 }
6524
6525 private:
6526 template <typename T>
6527 class Impl : public MatcherInterface<T> {
6528 public:
6529 typedef ::std::tuple<T, Second> ArgTuple;
6530
6531 Impl(const Tuple2Matcher& tm, const Second& second)
6532 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
6533 second_value_(second) {}
6534
6535 void DescribeTo(::std::ostream* os) const override {
6536 *os << "and ";
6537 UniversalPrint(second_value_, os);
6538 *os << " ";
6539 mono_tuple2_matcher_.DescribeTo(os);
6540 }
6541
6542 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
6543 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
6544 listener);
6545 }
6546
6547 private:
6548 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
6549 const Second second_value_;
6550 };
6551
6552 const Tuple2Matcher tuple2_matcher_;
6553 const Second second_value_;
6554 };
6555
6556 // Given a 2-tuple matcher tm and a value second,
6557 // MatcherBindSecond(tm, second) returns a matcher that matches a
6558 // value x if and only if tm matches tuple (x, second). Useful for
6559 // implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().
6560 template <typename Tuple2Matcher, typename Second>
6561 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
6562 const Tuple2Matcher& tm, const Second& second) {
6563 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
6564 }
6565
6566 // Returns the description for a matcher defined using the MATCHER*()
6567 // macro where the user-supplied description string is "", if
6568 // 'negation' is false; otherwise returns the description of the
6569 // negation of the matcher. 'param_values' contains a list of strings
6570 // that are the print-out of the matcher's parameters.
6571 GTEST_API_ std::string FormatMatcherDescription(bool negation,
6572 const char* matcher_name,
6573 const Strings& param_values);
6574
6575 // Implements a matcher that checks the value of a optional<> type variable.
6576 template <typename ValueMatcher>
6577 class OptionalMatcher {
6578 public:
6579 explicit OptionalMatcher(const ValueMatcher& value_matcher)
6580 : value_matcher_(value_matcher) {}
6581
6582 template <typename Optional>
6583 operator Matcher<Optional>() const {
6584 return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));
6585 }
6586
6587 template <typename Optional>
6588 class Impl : public MatcherInterface<Optional> {
6589 public:
6590 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
6591 typedef typename OptionalView::value_type ValueType;
6592 explicit Impl(const ValueMatcher& value_matcher)
6593 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
6594
6595 void DescribeTo(::std::ostream* os) const override {
6596 *os << "value ";
6597 value_matcher_.DescribeTo(os);
6598 }
6599
6600 void DescribeNegationTo(::std::ostream* os) const override {
6601 *os << "value ";
6602 value_matcher_.DescribeNegationTo(os);
6603 }
6604
6605 bool MatchAndExplain(Optional optional,
6606 MatchResultListener* listener) const override {
6607 if (!optional) {
6608 *listener << "which is not engaged";
6609 return false;
6610 }
6611 const ValueType& value = *optional;
6612 StringMatchResultListener value_listener;
6613 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
6614 *listener << "whose value " << PrintToString(value)
6615 << (match ? " matches" : " doesn't match");
6616 PrintIfNotEmpty(value_listener.str(), listener->stream());
6617 return match;
6618 }
6619
6620 private:
6621 const Matcher<ValueType> value_matcher_;
6622 };
6623
6624 private:
6625 const ValueMatcher value_matcher_;
6626 };
6627
6628 namespace variant_matcher {
6629 // Overloads to allow VariantMatcher to do proper ADL lookup.
6630 template <typename T>
6631 void holds_alternative() {}
6632 template <typename T>
6633 void get() {}
6634
6635 // Implements a matcher that checks the value of a variant<> type variable.
6636 template <typename T>
6637 class VariantMatcher {
6638 public:
6639 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
6640 : matcher_(std::move(matcher)) {}
6641
6642 template <typename Variant>
6643 bool MatchAndExplain(const Variant& value,
6644 ::testing::MatchResultListener* listener) const {
6645 using std::get;
6646 if (!listener->IsInterested()) {
6647 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
6648 }
6649
6650 if (!holds_alternative<T>(value)) {
6651 *listener << "whose value is not of type '" << GetTypeName() << "'";
6652 return false;
6653 }
6654
6655 const T& elem = get<T>(value);
6656 StringMatchResultListener elem_listener;
6657 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
6658 *listener << "whose value " << PrintToString(elem)
6659 << (match ? " matches" : " doesn't match");
6660 PrintIfNotEmpty(elem_listener.str(), listener->stream());
6661 return match;
6662 }
6663
6664 void DescribeTo(std::ostream* os) const {
6665 *os << "is a variant<> with value of type '" << GetTypeName()
6666 << "' and the value ";
6667 matcher_.DescribeTo(os);
6668 }
6669
6670 void DescribeNegationTo(std::ostream* os) const {
6671 *os << "is a variant<> with value of type other than '" << GetTypeName()
6672 << "' or the value ";
6673 matcher_.DescribeNegationTo(os);
6674 }
6675
6676 private:
6677 static std::string GetTypeName() {
6678 #if GTEST_HAS_RTTI
6679 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
6680 return internal::GetTypeName<T>());
6681 #endif
6682 return "the element type";
6683 }
6684
6685 const ::testing::Matcher<const T&> matcher_;
6686 };
6687
6688 } // namespace variant_matcher
6689
6690 namespace any_cast_matcher {
6691
6692 // Overloads to allow AnyCastMatcher to do proper ADL lookup.
6693 template <typename T>
6694 void any_cast() {}
6695
6696 // Implements a matcher that any_casts the value.
6697 template <typename T>
6698 class AnyCastMatcher {
6699 public:
6700 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
6701 : matcher_(matcher) {}
6702
6703 template <typename AnyType>
6704 bool MatchAndExplain(const AnyType& value,
6705 ::testing::MatchResultListener* listener) const {
6706 if (!listener->IsInterested()) {
6707 const T* ptr = any_cast<T>(&value);
6708 return ptr != nullptr && matcher_.Matches(*ptr);
6709 }
6710
6711 const T* elem = any_cast<T>(&value);
6712 if (elem == nullptr) {
6713 *listener << "whose value is not of type '" << GetTypeName() << "'";
6714 return false;
6715 }
6716
6717 StringMatchResultListener elem_listener;
6718 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
6719 *listener << "whose value " << PrintToString(*elem)
6720 << (match ? " matches" : " doesn't match");
6721 PrintIfNotEmpty(elem_listener.str(), listener->stream());
6722 return match;
6723 }
6724
6725 void DescribeTo(std::ostream* os) const {
6726 *os << "is an 'any' type with value of type '" << GetTypeName()
6727 << "' and the value ";
6728 matcher_.DescribeTo(os);
6729 }
6730
6731 void DescribeNegationTo(std::ostream* os) const {
6732 *os << "is an 'any' type with value of type other than '" << GetTypeName()
6733 << "' or the value ";
6734 matcher_.DescribeNegationTo(os);
6735 }
6736
6737 private:
6738 static std::string GetTypeName() {
6739 #if GTEST_HAS_RTTI
6740 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
6741 return internal::GetTypeName<T>());
6742 #endif
6743 return "the element type";
6744 }
6745
6746 const ::testing::Matcher<const T&> matcher_;
6747 };
6748
6749 } // namespace any_cast_matcher
6750
6751 // Implements the Args() matcher.
6752 template <class ArgsTuple, size_t... k>
6753 class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
6754 public:
6755 using RawArgsTuple = typename std::decay<ArgsTuple>::type;
6756 using SelectedArgs =
6757 std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;
6758 using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;
6759
6760 template <typename InnerMatcher>
6761 explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
6762 : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
6763
6764 bool MatchAndExplain(ArgsTuple args,
6765 MatchResultListener* listener) const override {
6766 // Workaround spurious C4100 on MSVC<=15.7 when k is empty.
6767 (void)args;
6768 const SelectedArgs& selected_args =
6769 std::forward_as_tuple(std::get<k>(args)...);
6770 if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);
6771
6772 PrintIndices(listener->stream());
6773 *listener << "are " << PrintToString(selected_args);
6774
6775 StringMatchResultListener inner_listener;
6776 const bool match =
6777 inner_matcher_.MatchAndExplain(selected_args, &inner_listener);
6778 PrintIfNotEmpty(inner_listener.str(), listener->stream());
6779 return match;
6780 }
6781
6782 void DescribeTo(::std::ostream* os) const override {
6783 *os << "are a tuple ";
6784 PrintIndices(os);
6785 inner_matcher_.DescribeTo(os);
6786 }
6787
6788 void DescribeNegationTo(::std::ostream* os) const override {
6789 *os << "are a tuple ";
6790 PrintIndices(os);
6791 inner_matcher_.DescribeNegationTo(os);
6792 }
6793
6794 private:
6795 // Prints the indices of the selected fields.
6796 static void PrintIndices(::std::ostream* os) {
6797 *os << "whose fields (";
6798 const char* sep = "";
6799 // Workaround spurious C4189 on MSVC<=15.7 when k is empty.
6800 (void)sep;
6801 const char* dummy[] = {"", (*os << sep << "#" << k, sep = ", ")...};
6802 (void)dummy;
6803 *os << ") ";
6804 }
6805
6806 MonomorphicInnerMatcher inner_matcher_;
6807 };
6808
6809 template <class InnerMatcher, size_t... k>
6810 class ArgsMatcher {
6811 public:
6812 explicit ArgsMatcher(InnerMatcher inner_matcher)
6813 : inner_matcher_(std::move(inner_matcher)) {}
6814
6815 template <typename ArgsTuple>
6816 operator Matcher<ArgsTuple>() const { // NOLINT
6817 return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));
6818 }
6819
6820 private:
6821 InnerMatcher inner_matcher_;
6822 };
6823
6824 } // namespace internal
6825
6826 // ElementsAreArray(iterator_first, iterator_last)
6827 // ElementsAreArray(pointer, count)
6828 // ElementsAreArray(array)
6829 // ElementsAreArray(container)
6830 // ElementsAreArray({ e1, e2, ..., en })
6831 //
6832 // The ElementsAreArray() functions are like ElementsAre(...), except
6833 // that they are given a homogeneous sequence rather than taking each
6834 // element as a function argument. The sequence can be specified as an
6835 // array, a pointer and count, a vector, an initializer list, or an
6836 // STL iterator range. In each of these cases, the underlying sequence
6837 // can be either a sequence of values or a sequence of matchers.
6838 //
6839 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
6840
6841 template <typename Iter>
6842 inline internal::ElementsAreArrayMatcher<
6843 typename ::std::iterator_traits<Iter>::value_type>
6844 ElementsAreArray(Iter first, Iter last) {
6845 typedef typename ::std::iterator_traits<Iter>::value_type T;
6846 return internal::ElementsAreArrayMatcher<T>(first, last);
6847 }
6848
6849 template <typename T>
6850 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
6851 const T* pointer, size_t count) {
6852 return ElementsAreArray(pointer, pointer + count);
6853 }
6854
6855 template <typename T, size_t N>
6856 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
6857 const T (&array)[N]) {
6858 return ElementsAreArray(array, N);
6859 }
6860
6861 template <typename Container>
6862 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
6863 ElementsAreArray(const Container& container) {
6864 return ElementsAreArray(container.begin(), container.end());
6865 }
6866
6867 template <typename T>
6868 inline internal::ElementsAreArrayMatcher<T>
6869 ElementsAreArray(::std::initializer_list<T> xs) {
6870 return ElementsAreArray(xs.begin(), xs.end());
6871 }
6872
6873 // UnorderedElementsAreArray(iterator_first, iterator_last)
6874 // UnorderedElementsAreArray(pointer, count)
6875 // UnorderedElementsAreArray(array)
6876 // UnorderedElementsAreArray(container)
6877 // UnorderedElementsAreArray({ e1, e2, ..., en })
6878 //
6879 // UnorderedElementsAreArray() verifies that a bijective mapping onto a
6880 // collection of matchers exists.
6881 //
6882 // The matchers can be specified as an array, a pointer and count, a container,
6883 // an initializer list, or an STL iterator range. In each of these cases, the
6884 // underlying matchers can be either values or matchers.
6885
6886 template <typename Iter>
6887 inline internal::UnorderedElementsAreArrayMatcher<
6888 typename ::std::iterator_traits<Iter>::value_type>
6889 UnorderedElementsAreArray(Iter first, Iter last) {
6890 typedef typename ::std::iterator_traits<Iter>::value_type T;
6891 return internal::UnorderedElementsAreArrayMatcher<T>(
6892 internal::UnorderedMatcherRequire::ExactMatch, first, last);
6893 }
6894
6895 template <typename T>
6896 inline internal::UnorderedElementsAreArrayMatcher<T>
6897 UnorderedElementsAreArray(const T* pointer, size_t count) {
6898 return UnorderedElementsAreArray(pointer, pointer + count);
6899 }
6900
6901 template <typename T, size_t N>
6902 inline internal::UnorderedElementsAreArrayMatcher<T>
6903 UnorderedElementsAreArray(const T (&array)[N]) {
6904 return UnorderedElementsAreArray(array, N);
6905 }
6906
6907 template <typename Container>
6908 inline internal::UnorderedElementsAreArrayMatcher<
6909 typename Container::value_type>
6910 UnorderedElementsAreArray(const Container& container) {
6911 return UnorderedElementsAreArray(container.begin(), container.end());
6912 }
6913
6914 template <typename T>
6915 inline internal::UnorderedElementsAreArrayMatcher<T>
6916 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
6917 return UnorderedElementsAreArray(xs.begin(), xs.end());
6918 }
6919
6920 // _ is a matcher that matches anything of any type.
6921 //
6922 // This definition is fine as:
6923 //
6924 // 1. The C++ standard permits using the name _ in a namespace that
6925 // is not the global namespace or ::std.
6926 // 2. The AnythingMatcher class has no data member or constructor,
6927 // so it's OK to create global variables of this type.
6928 // 3. c-style has approved of using _ in this case.
6929 const internal::AnythingMatcher _ = {};
6930 // Creates a matcher that matches any value of the given type T.
6931 template <typename T>
6932 inline Matcher<T> A() {
6933 return _;
6934 }
6935
6936 // Creates a matcher that matches any value of the given type T.
6937 template <typename T>
6938 inline Matcher<T> An() {
6939 return _;
6940 }
6941
6942 template <typename T, typename M>
6943 Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
6944 const M& value, std::false_type /* convertible_to_matcher */,
6945 std::false_type /* convertible_to_T */) {
6946 return Eq(value);
6947 }
6948
6949 // Creates a polymorphic matcher that matches any NULL pointer.
6950 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
6951 return MakePolymorphicMatcher(internal::IsNullMatcher());
6952 }
6953
6954 // Creates a polymorphic matcher that matches any non-NULL pointer.
6955 // This is convenient as Not(NULL) doesn't compile (the compiler
6956 // thinks that that expression is comparing a pointer with an integer).
6957 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
6958 return MakePolymorphicMatcher(internal::NotNullMatcher());
6959 }
6960
6961 // Creates a polymorphic matcher that matches any argument that
6962 // references variable x.
6963 template <typename T>
6964 inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
6965 return internal::RefMatcher<T&>(x);
6966 }
6967
6968 // Creates a polymorphic matcher that matches any NaN floating point.
6969 inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {
6970 return MakePolymorphicMatcher(internal::IsNanMatcher());
6971 }
6972
6973 // Creates a matcher that matches any double argument approximately
6974 // equal to rhs, where two NANs are considered unequal.
6975 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
6976 return internal::FloatingEqMatcher<double>(rhs, false);
6977 }
6978
6979 // Creates a matcher that matches any double argument approximately
6980 // equal to rhs, including NaN values when rhs is NaN.
6981 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
6982 return internal::FloatingEqMatcher<double>(rhs, true);
6983 }
6984
6985 // Creates a matcher that matches any double argument approximately equal to
6986 // rhs, up to the specified max absolute error bound, where two NANs are
6987 // considered unequal. The max absolute error bound must be non-negative.
6988 inline internal::FloatingEqMatcher<double> DoubleNear(
6989 double rhs, double max_abs_error) {
6990 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
6991 }
6992
6993 // Creates a matcher that matches any double argument approximately equal to
6994 // rhs, up to the specified max absolute error bound, including NaN values when
6995 // rhs is NaN. The max absolute error bound must be non-negative.
6996 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
6997 double rhs, double max_abs_error) {
6998 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
6999 }
7000
7001 // Creates a matcher that matches any float argument approximately
7002 // equal to rhs, where two NANs are considered unequal.
7003 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
7004 return internal::FloatingEqMatcher<float>(rhs, false);
7005 }
7006
7007 // Creates a matcher that matches any float argument approximately
7008 // equal to rhs, including NaN values when rhs is NaN.
7009 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
7010 return internal::FloatingEqMatcher<float>(rhs, true);
7011 }
7012
7013 // Creates a matcher that matches any float argument approximately equal to
7014 // rhs, up to the specified max absolute error bound, where two NANs are
7015 // considered unequal. The max absolute error bound must be non-negative.
7016 inline internal::FloatingEqMatcher<float> FloatNear(
7017 float rhs, float max_abs_error) {
7018 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
7019 }
7020
7021 // Creates a matcher that matches any float argument approximately equal to
7022 // rhs, up to the specified max absolute error bound, including NaN values when
7023 // rhs is NaN. The max absolute error bound must be non-negative.
7024 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
7025 float rhs, float max_abs_error) {
7026 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
7027 }
7028
7029 // Creates a matcher that matches a pointer (raw or smart) that points
7030 // to a value that matches inner_matcher.
7031 template <typename InnerMatcher>
7032 inline internal::PointeeMatcher<InnerMatcher> Pointee(
7033 const InnerMatcher& inner_matcher) {
7034 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
7035 }
7036
7037 #if GTEST_HAS_RTTI
7038 // Creates a matcher that matches a pointer or reference that matches
7039 // inner_matcher when dynamic_cast<To> is applied.
7040 // The result of dynamic_cast<To> is forwarded to the inner matcher.
7041 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
7042 // If To is a reference and the cast fails, this matcher returns false
7043 // immediately.
7044 template <typename To>
7045 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
7046 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
7047 return MakePolymorphicMatcher(
7048 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
7049 }
7050 #endif // GTEST_HAS_RTTI
7051
7052 // Creates a matcher that matches an object whose given field matches
7053 // 'matcher'. For example,
7054 // Field(&Foo::number, Ge(5))
7055 // matches a Foo object x if and only if x.number >= 5.
7056 template <typename Class, typename FieldType, typename FieldMatcher>
7057 inline PolymorphicMatcher<
7058 internal::FieldMatcher<Class, FieldType> > Field(
7059 FieldType Class::*field, const FieldMatcher& matcher) {
7060 return MakePolymorphicMatcher(
7061 internal::FieldMatcher<Class, FieldType>(
7062 field, MatcherCast<const FieldType&>(matcher)));
7063 // The call to MatcherCast() is required for supporting inner
7064 // matchers of compatible types. For example, it allows
7065 // Field(&Foo::bar, m)
7066 // to compile where bar is an int32 and m is a matcher for int64.
7067 }
7068
7069 // Same as Field() but also takes the name of the field to provide better error
7070 // messages.
7071 template <typename Class, typename FieldType, typename FieldMatcher>
7072 inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
7073 const std::string& field_name, FieldType Class::*field,
7074 const FieldMatcher& matcher) {
7075 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
7076 field_name, field, MatcherCast<const FieldType&>(matcher)));
7077 }
7078
7079 // Creates a matcher that matches an object whose given property
7080 // matches 'matcher'. For example,
7081 // Property(&Foo::str, StartsWith("hi"))
7082 // matches a Foo object x if and only if x.str() starts with "hi".
7083 template <typename Class, typename PropertyType, typename PropertyMatcher>
7084 inline PolymorphicMatcher<internal::PropertyMatcher<
7085 Class, PropertyType, PropertyType (Class::*)() const> >
7086 Property(PropertyType (Class::*property)() const,
7087 const PropertyMatcher& matcher) {
7088 return MakePolymorphicMatcher(
7089 internal::PropertyMatcher<Class, PropertyType,
7090 PropertyType (Class::*)() const>(
7091 property, MatcherCast<const PropertyType&>(matcher)));
7092 // The call to MatcherCast() is required for supporting inner
7093 // matchers of compatible types. For example, it allows
7094 // Property(&Foo::bar, m)
7095 // to compile where bar() returns an int32 and m is a matcher for int64.
7096 }
7097
7098 // Same as Property() above, but also takes the name of the property to provide
7099 // better error messages.
7100 template <typename Class, typename PropertyType, typename PropertyMatcher>
7101 inline PolymorphicMatcher<internal::PropertyMatcher<
7102 Class, PropertyType, PropertyType (Class::*)() const> >
7103 Property(const std::string& property_name,
7104 PropertyType (Class::*property)() const,
7105 const PropertyMatcher& matcher) {
7106 return MakePolymorphicMatcher(
7107 internal::PropertyMatcher<Class, PropertyType,
7108 PropertyType (Class::*)() const>(
7109 property_name, property, MatcherCast<const PropertyType&>(matcher)));
7110 }
7111
7112 // The same as above but for reference-qualified member functions.
7113 template <typename Class, typename PropertyType, typename PropertyMatcher>
7114 inline PolymorphicMatcher<internal::PropertyMatcher<
7115 Class, PropertyType, PropertyType (Class::*)() const &> >
7116 Property(PropertyType (Class::*property)() const &,
7117 const PropertyMatcher& matcher) {
7118 return MakePolymorphicMatcher(
7119 internal::PropertyMatcher<Class, PropertyType,
7120 PropertyType (Class::*)() const&>(
7121 property, MatcherCast<const PropertyType&>(matcher)));
7122 }
7123
7124 // Three-argument form for reference-qualified member functions.
7125 template <typename Class, typename PropertyType, typename PropertyMatcher>
7126 inline PolymorphicMatcher<internal::PropertyMatcher<
7127 Class, PropertyType, PropertyType (Class::*)() const &> >
7128 Property(const std::string& property_name,
7129 PropertyType (Class::*property)() const &,
7130 const PropertyMatcher& matcher) {
7131 return MakePolymorphicMatcher(
7132 internal::PropertyMatcher<Class, PropertyType,
7133 PropertyType (Class::*)() const&>(
7134 property_name, property, MatcherCast<const PropertyType&>(matcher)));
7135 }
7136
7137 // Creates a matcher that matches an object if and only if the result of
7138 // applying a callable to x matches 'matcher'. For example,
7139 // ResultOf(f, StartsWith("hi"))
7140 // matches a Foo object x if and only if f(x) starts with "hi".
7141 // `callable` parameter can be a function, function pointer, or a functor. It is
7142 // required to keep no state affecting the results of the calls on it and make
7143 // no assumptions about how many calls will be made. Any state it keeps must be
7144 // protected from the concurrent access.
7145 template <typename Callable, typename InnerMatcher>
7146 internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
7147 Callable callable, InnerMatcher matcher) {
7148 return internal::ResultOfMatcher<Callable, InnerMatcher>(
7149 std::move(callable), std::move(matcher));
7150 }
7151
7152 // String matchers.
7153
7154 // Matches a string equal to str.
7155 template <typename T = std::string>
7156 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
7157 const internal::StringLike<T>& str) {
7158 return MakePolymorphicMatcher(
7159 internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
7160 }
7161
7162 // Matches a string not equal to str.
7163 template <typename T = std::string>
7164 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
7165 const internal::StringLike<T>& str) {
7166 return MakePolymorphicMatcher(
7167 internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
7168 }
7169
7170 // Matches a string equal to str, ignoring case.
7171 template <typename T = std::string>
7172 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
7173 const internal::StringLike<T>& str) {
7174 return MakePolymorphicMatcher(
7175 internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
7176 }
7177
7178 // Matches a string not equal to str, ignoring case.
7179 template <typename T = std::string>
7180 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
7181 const internal::StringLike<T>& str) {
7182 return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
7183 std::string(str), false, false));
7184 }
7185
7186 // Creates a matcher that matches any string, std::string, or C string
7187 // that contains the given substring.
7188 template <typename T = std::string>
7189 PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
7190 const internal::StringLike<T>& substring) {
7191 return MakePolymorphicMatcher(
7192 internal::HasSubstrMatcher<std::string>(std::string(substring)));
7193 }
7194
7195 // Matches a string that starts with 'prefix' (case-sensitive).
7196 template <typename T = std::string>
7197 PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
7198 const internal::StringLike<T>& prefix) {
7199 return MakePolymorphicMatcher(
7200 internal::StartsWithMatcher<std::string>(std::string(prefix)));
7201 }
7202
7203 // Matches a string that ends with 'suffix' (case-sensitive).
7204 template <typename T = std::string>
7205 PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
7206 const internal::StringLike<T>& suffix) {
7207 return MakePolymorphicMatcher(
7208 internal::EndsWithMatcher<std::string>(std::string(suffix)));
7209 }
7210
7211 #if GTEST_HAS_STD_WSTRING
7212 // Wide string matchers.
7213
7214 // Matches a string equal to str.
7215 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
7216 const std::wstring& str) {
7217 return MakePolymorphicMatcher(
7218 internal::StrEqualityMatcher<std::wstring>(str, true, true));
7219 }
7220
7221 // Matches a string not equal to str.
7222 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
7223 const std::wstring& str) {
7224 return MakePolymorphicMatcher(
7225 internal::StrEqualityMatcher<std::wstring>(str, false, true));
7226 }
7227
7228 // Matches a string equal to str, ignoring case.
7229 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
7230 StrCaseEq(const std::wstring& str) {
7231 return MakePolymorphicMatcher(
7232 internal::StrEqualityMatcher<std::wstring>(str, true, false));
7233 }
7234
7235 // Matches a string not equal to str, ignoring case.
7236 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
7237 StrCaseNe(const std::wstring& str) {
7238 return MakePolymorphicMatcher(
7239 internal::StrEqualityMatcher<std::wstring>(str, false, false));
7240 }
7241
7242 // Creates a matcher that matches any ::wstring, std::wstring, or C wide string
7243 // that contains the given substring.
7244 inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
7245 const std::wstring& substring) {
7246 return MakePolymorphicMatcher(
7247 internal::HasSubstrMatcher<std::wstring>(substring));
7248 }
7249
7250 // Matches a string that starts with 'prefix' (case-sensitive).
7251 inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
7252 StartsWith(const std::wstring& prefix) {
7253 return MakePolymorphicMatcher(
7254 internal::StartsWithMatcher<std::wstring>(prefix));
7255 }
7256
7257 // Matches a string that ends with 'suffix' (case-sensitive).
7258 inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
7259 const std::wstring& suffix) {
7260 return MakePolymorphicMatcher(
7261 internal::EndsWithMatcher<std::wstring>(suffix));
7262 }
7263
7264 #endif // GTEST_HAS_STD_WSTRING
7265
7266 // Creates a polymorphic matcher that matches a 2-tuple where the
7267 // first field == the second field.
7268 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
7269
7270 // Creates a polymorphic matcher that matches a 2-tuple where the
7271 // first field >= the second field.
7272 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
7273
7274 // Creates a polymorphic matcher that matches a 2-tuple where the
7275 // first field > the second field.
7276 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
7277
7278 // Creates a polymorphic matcher that matches a 2-tuple where the
7279 // first field <= the second field.
7280 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
7281
7282 // Creates a polymorphic matcher that matches a 2-tuple where the
7283 // first field < the second field.
7284 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
7285
7286 // Creates a polymorphic matcher that matches a 2-tuple where the
7287 // first field != the second field.
7288 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
7289
7290 // Creates a polymorphic matcher that matches a 2-tuple where
7291 // FloatEq(first field) matches the second field.
7292 inline internal::FloatingEq2Matcher<float> FloatEq() {
7293 return internal::FloatingEq2Matcher<float>();
7294 }
7295
7296 // Creates a polymorphic matcher that matches a 2-tuple where
7297 // DoubleEq(first field) matches the second field.
7298 inline internal::FloatingEq2Matcher<double> DoubleEq() {
7299 return internal::FloatingEq2Matcher<double>();
7300 }
7301
7302 // Creates a polymorphic matcher that matches a 2-tuple where
7303 // FloatEq(first field) matches the second field with NaN equality.
7304 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
7305 return internal::FloatingEq2Matcher<float>(true);
7306 }
7307
7308 // Creates a polymorphic matcher that matches a 2-tuple where
7309 // DoubleEq(first field) matches the second field with NaN equality.
7310 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
7311 return internal::FloatingEq2Matcher<double>(true);
7312 }
7313
7314 // Creates a polymorphic matcher that matches a 2-tuple where
7315 // FloatNear(first field, max_abs_error) matches the second field.
7316 inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
7317 return internal::FloatingEq2Matcher<float>(max_abs_error);
7318 }
7319
7320 // Creates a polymorphic matcher that matches a 2-tuple where
7321 // DoubleNear(first field, max_abs_error) matches the second field.
7322 inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
7323 return internal::FloatingEq2Matcher<double>(max_abs_error);
7324 }
7325
7326 // Creates a polymorphic matcher that matches a 2-tuple where
7327 // FloatNear(first field, max_abs_error) matches the second field with NaN
7328 // equality.
7329 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
7330 float max_abs_error) {
7331 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
7332 }
7333
7334 // Creates a polymorphic matcher that matches a 2-tuple where
7335 // DoubleNear(first field, max_abs_error) matches the second field with NaN
7336 // equality.
7337 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
7338 double max_abs_error) {
7339 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
7340 }
7341
7342 // Creates a matcher that matches any value of type T that m doesn't
7343 // match.
7344 template <typename InnerMatcher>
7345 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
7346 return internal::NotMatcher<InnerMatcher>(m);
7347 }
7348
7349 // Returns a matcher that matches anything that satisfies the given
7350 // predicate. The predicate can be any unary function or functor
7351 // whose return type can be implicitly converted to bool.
7352 template <typename Predicate>
7353 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
7354 Truly(Predicate pred) {
7355 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
7356 }
7357
7358 // Returns a matcher that matches the container size. The container must
7359 // support both size() and size_type which all STL-like containers provide.
7360 // Note that the parameter 'size' can be a value of type size_type as well as
7361 // matcher. For instance:
7362 // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
7363 // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
7364 template <typename SizeMatcher>
7365 inline internal::SizeIsMatcher<SizeMatcher>
7366 SizeIs(const SizeMatcher& size_matcher) {
7367 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
7368 }
7369
7370 // Returns a matcher that matches the distance between the container's begin()
7371 // iterator and its end() iterator, i.e. the size of the container. This matcher
7372 // can be used instead of SizeIs with containers such as std::forward_list which
7373 // do not implement size(). The container must provide const_iterator (with
7374 // valid iterator_traits), begin() and end().
7375 template <typename DistanceMatcher>
7376 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
7377 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
7378 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
7379 }
7380
7381 // Returns a matcher that matches an equal container.
7382 // This matcher behaves like Eq(), but in the event of mismatch lists the
7383 // values that are included in one container but not the other. (Duplicate
7384 // values and order differences are not explained.)
7385 template <typename Container>
7386 inline PolymorphicMatcher<internal::ContainerEqMatcher<
7387 typename std::remove_const<Container>::type>>
7388 ContainerEq(const Container& rhs) {
7389 return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
7390 }
7391
7392 // Returns a matcher that matches a container that, when sorted using
7393 // the given comparator, matches container_matcher.
7394 template <typename Comparator, typename ContainerMatcher>
7395 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
7396 WhenSortedBy(const Comparator& comparator,
7397 const ContainerMatcher& container_matcher) {
7398 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
7399 comparator, container_matcher);
7400 }
7401
7402 // Returns a matcher that matches a container that, when sorted using
7403 // the < operator, matches container_matcher.
7404 template <typename ContainerMatcher>
7405 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
7406 WhenSorted(const ContainerMatcher& container_matcher) {
7407 return
7408 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
7409 internal::LessComparator(), container_matcher);
7410 }
7411
7412 // Matches an STL-style container or a native array that contains the
7413 // same number of elements as in rhs, where its i-th element and rhs's
7414 // i-th element (as a pair) satisfy the given pair matcher, for all i.
7415 // TupleMatcher must be able to be safely cast to Matcher<std::tuple<const
7416 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
7417 // LHS container and the RHS container respectively.
7418 template <typename TupleMatcher, typename Container>
7419 inline internal::PointwiseMatcher<TupleMatcher,
7420 typename std::remove_const<Container>::type>
7421 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
7422 return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,
7423 rhs);
7424 }
7425
7426
7427 // Supports the Pointwise(m, {a, b, c}) syntax.
7428 template <typename TupleMatcher, typename T>
7429 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
7430 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
7431 return Pointwise(tuple_matcher, std::vector<T>(rhs));
7432 }
7433
7434
7435 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
7436 // container or a native array that contains the same number of
7437 // elements as in rhs, where in some permutation of the container, its
7438 // i-th element and rhs's i-th element (as a pair) satisfy the given
7439 // pair matcher, for all i. Tuple2Matcher must be able to be safely
7440 // cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are
7441 // the types of elements in the LHS container and the RHS container
7442 // respectively.
7443 //
7444 // This is like Pointwise(pair_matcher, rhs), except that the element
7445 // order doesn't matter.
7446 template <typename Tuple2Matcher, typename RhsContainer>
7447 inline internal::UnorderedElementsAreArrayMatcher<
7448 typename internal::BoundSecondMatcher<
7449 Tuple2Matcher,
7450 typename internal::StlContainerView<
7451 typename std::remove_const<RhsContainer>::type>::type::value_type>>
7452 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
7453 const RhsContainer& rhs_container) {
7454 // RhsView allows the same code to handle RhsContainer being a
7455 // STL-style container and it being a native C-style array.
7456 typedef typename internal::StlContainerView<RhsContainer> RhsView;
7457 typedef typename RhsView::type RhsStlContainer;
7458 typedef typename RhsStlContainer::value_type Second;
7459 const RhsStlContainer& rhs_stl_container =
7460 RhsView::ConstReference(rhs_container);
7461
7462 // Create a matcher for each element in rhs_container.
7463 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
7464 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
7465 it != rhs_stl_container.end(); ++it) {
7466 matchers.push_back(
7467 internal::MatcherBindSecond(tuple2_matcher, *it));
7468 }
7469
7470 // Delegate the work to UnorderedElementsAreArray().
7471 return UnorderedElementsAreArray(matchers);
7472 }
7473
7474
7475 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
7476 template <typename Tuple2Matcher, typename T>
7477 inline internal::UnorderedElementsAreArrayMatcher<
7478 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
7479 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
7480 std::initializer_list<T> rhs) {
7481 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
7482 }
7483
7484
7485 // Matches an STL-style container or a native array that contains at
7486 // least one element matching the given value or matcher.
7487 //
7488 // Examples:
7489 // ::std::set<int> page_ids;
7490 // page_ids.insert(3);
7491 // page_ids.insert(1);
7492 // EXPECT_THAT(page_ids, Contains(1));
7493 // EXPECT_THAT(page_ids, Contains(Gt(2)));
7494 // EXPECT_THAT(page_ids, Not(Contains(4)));
7495 //
7496 // ::std::map<int, size_t> page_lengths;
7497 // page_lengths[1] = 100;
7498 // EXPECT_THAT(page_lengths,
7499 // Contains(::std::pair<const int, size_t>(1, 100)));
7500 //
7501 // const char* user_ids[] = { "joe", "mike", "tom" };
7502 // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
7503 template <typename M>
7504 inline internal::ContainsMatcher<M> Contains(M matcher) {
7505 return internal::ContainsMatcher<M>(matcher);
7506 }
7507
7508 // IsSupersetOf(iterator_first, iterator_last)
7509 // IsSupersetOf(pointer, count)
7510 // IsSupersetOf(array)
7511 // IsSupersetOf(container)
7512 // IsSupersetOf({e1, e2, ..., en})
7513 //
7514 // IsSupersetOf() verifies that a surjective partial mapping onto a collection
7515 // of matchers exists. In other words, a container matches
7516 // IsSupersetOf({e1, ..., en}) if and only if there is a permutation
7517 // {y1, ..., yn} of some of the container's elements where y1 matches e1,
7518 // ..., and yn matches en. Obviously, the size of the container must be >= n
7519 // in order to have a match. Examples:
7520 //
7521 // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
7522 // 1 matches Ne(0).
7523 // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
7524 // both Eq(1) and Lt(2). The reason is that different matchers must be used
7525 // for elements in different slots of the container.
7526 // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
7527 // Eq(1) and (the second) 1 matches Lt(2).
7528 // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
7529 // Gt(1) and 3 matches (the second) Gt(1).
7530 //
7531 // The matchers can be specified as an array, a pointer and count, a container,
7532 // an initializer list, or an STL iterator range. In each of these cases, the
7533 // underlying matchers can be either values or matchers.
7534
7535 template <typename Iter>
7536 inline internal::UnorderedElementsAreArrayMatcher<
7537 typename ::std::iterator_traits<Iter>::value_type>
7538 IsSupersetOf(Iter first, Iter last) {
7539 typedef typename ::std::iterator_traits<Iter>::value_type T;
7540 return internal::UnorderedElementsAreArrayMatcher<T>(
7541 internal::UnorderedMatcherRequire::Superset, first, last);
7542 }
7543
7544 template <typename T>
7545 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7546 const T* pointer, size_t count) {
7547 return IsSupersetOf(pointer, pointer + count);
7548 }
7549
7550 template <typename T, size_t N>
7551 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7552 const T (&array)[N]) {
7553 return IsSupersetOf(array, N);
7554 }
7555
7556 template <typename Container>
7557 inline internal::UnorderedElementsAreArrayMatcher<
7558 typename Container::value_type>
7559 IsSupersetOf(const Container& container) {
7560 return IsSupersetOf(container.begin(), container.end());
7561 }
7562
7563 template <typename T>
7564 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7565 ::std::initializer_list<T> xs) {
7566 return IsSupersetOf(xs.begin(), xs.end());
7567 }
7568
7569 // IsSubsetOf(iterator_first, iterator_last)
7570 // IsSubsetOf(pointer, count)
7571 // IsSubsetOf(array)
7572 // IsSubsetOf(container)
7573 // IsSubsetOf({e1, e2, ..., en})
7574 //
7575 // IsSubsetOf() verifies that an injective mapping onto a collection of matchers
7576 // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
7577 // only if there is a subset of matchers {m1, ..., mk} which would match the
7578 // container using UnorderedElementsAre. Obviously, the size of the container
7579 // must be <= n in order to have a match. Examples:
7580 //
7581 // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
7582 // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
7583 // matches Lt(0).
7584 // - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
7585 // match Gt(0). The reason is that different matchers must be used for
7586 // elements in different slots of the container.
7587 //
7588 // The matchers can be specified as an array, a pointer and count, a container,
7589 // an initializer list, or an STL iterator range. In each of these cases, the
7590 // underlying matchers can be either values or matchers.
7591
7592 template <typename Iter>
7593 inline internal::UnorderedElementsAreArrayMatcher<
7594 typename ::std::iterator_traits<Iter>::value_type>
7595 IsSubsetOf(Iter first, Iter last) {
7596 typedef typename ::std::iterator_traits<Iter>::value_type T;
7597 return internal::UnorderedElementsAreArrayMatcher<T>(
7598 internal::UnorderedMatcherRequire::Subset, first, last);
7599 }
7600
7601 template <typename T>
7602 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7603 const T* pointer, size_t count) {
7604 return IsSubsetOf(pointer, pointer + count);
7605 }
7606
7607 template <typename T, size_t N>
7608 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7609 const T (&array)[N]) {
7610 return IsSubsetOf(array, N);
7611 }
7612
7613 template <typename Container>
7614 inline internal::UnorderedElementsAreArrayMatcher<
7615 typename Container::value_type>
7616 IsSubsetOf(const Container& container) {
7617 return IsSubsetOf(container.begin(), container.end());
7618 }
7619
7620 template <typename T>
7621 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7622 ::std::initializer_list<T> xs) {
7623 return IsSubsetOf(xs.begin(), xs.end());
7624 }
7625
7626 // Matches an STL-style container or a native array that contains only
7627 // elements matching the given value or matcher.
7628 //
7629 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
7630 // the messages are different.
7631 //
7632 // Examples:
7633 // ::std::set<int> page_ids;
7634 // // Each(m) matches an empty container, regardless of what m is.
7635 // EXPECT_THAT(page_ids, Each(Eq(1)));
7636 // EXPECT_THAT(page_ids, Each(Eq(77)));
7637 //
7638 // page_ids.insert(3);
7639 // EXPECT_THAT(page_ids, Each(Gt(0)));
7640 // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
7641 // page_ids.insert(1);
7642 // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
7643 //
7644 // ::std::map<int, size_t> page_lengths;
7645 // page_lengths[1] = 100;
7646 // page_lengths[2] = 200;
7647 // page_lengths[3] = 300;
7648 // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
7649 // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
7650 //
7651 // const char* user_ids[] = { "joe", "mike", "tom" };
7652 // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
7653 template <typename M>
7654 inline internal::EachMatcher<M> Each(M matcher) {
7655 return internal::EachMatcher<M>(matcher);
7656 }
7657
7658 // Key(inner_matcher) matches an std::pair whose 'first' field matches
7659 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
7660 // std::map that contains at least one element whose key is >= 5.
7661 template <typename M>
7662 inline internal::KeyMatcher<M> Key(M inner_matcher) {
7663 return internal::KeyMatcher<M>(inner_matcher);
7664 }
7665
7666 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
7667 // matches first_matcher and whose 'second' field matches second_matcher. For
7668 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
7669 // to match a std::map<int, string> that contains exactly one element whose key
7670 // is >= 5 and whose value equals "foo".
7671 template <typename FirstMatcher, typename SecondMatcher>
7672 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
7673 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
7674 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
7675 first_matcher, second_matcher);
7676 }
7677
7678 namespace no_adl {
7679 // FieldsAre(matchers...) matches piecewise the fields of compatible structs.
7680 // These include those that support `get<I>(obj)`, and when structured bindings
7681 // are enabled any class that supports them.
7682 // In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.
7683 template <typename... M>
7684 internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(
7685 M&&... matchers) {
7686 return internal::FieldsAreMatcher<typename std::decay<M>::type...>(
7687 std::forward<M>(matchers)...);
7688 }
7689
7690 // Creates a matcher that matches a pointer (raw or smart) that matches
7691 // inner_matcher.
7692 template <typename InnerMatcher>
7693 inline internal::PointerMatcher<InnerMatcher> Pointer(
7694 const InnerMatcher& inner_matcher) {
7695 return internal::PointerMatcher<InnerMatcher>(inner_matcher);
7696 }
7697
7698 // Creates a matcher that matches an object that has an address that matches
7699 // inner_matcher.
7700 template <typename InnerMatcher>
7701 inline internal::AddressMatcher<InnerMatcher> Address(
7702 const InnerMatcher& inner_matcher) {
7703 return internal::AddressMatcher<InnerMatcher>(inner_matcher);
7704 }
7705 } // namespace no_adl
7706
7707 // Returns a predicate that is satisfied by anything that matches the
7708 // given matcher.
7709 template <typename M>
7710 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
7711 return internal::MatcherAsPredicate<M>(matcher);
7712 }
7713
7714 // Returns true if and only if the value matches the matcher.
7715 template <typename T, typename M>
7716 inline bool Value(const T& value, M matcher) {
7717 return testing::Matches(matcher)(value);
7718 }
7719
7720 // Matches the value against the given matcher and explains the match
7721 // result to listener.
7722 template <typename T, typename M>
7723 inline bool ExplainMatchResult(
7724 M matcher, const T& value, MatchResultListener* listener) {
7725 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
7726 }
7727
7728 // Returns a string representation of the given matcher. Useful for description
7729 // strings of matchers defined using MATCHER_P* macros that accept matchers as
7730 // their arguments. For example:
7731 //
7732 // MATCHER_P(XAndYThat, matcher,
7733 // "X that " + DescribeMatcher<int>(matcher, negation) +
7734 // " and Y that " + DescribeMatcher<double>(matcher, negation)) {
7735 // return ExplainMatchResult(matcher, arg.x(), result_listener) &&
7736 // ExplainMatchResult(matcher, arg.y(), result_listener);
7737 // }
7738 template <typename T, typename M>
7739 std::string DescribeMatcher(const M& matcher, bool negation = false) {
7740 ::std::stringstream ss;
7741 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
7742 if (negation) {
7743 monomorphic_matcher.DescribeNegationTo(&ss);
7744 } else {
7745 monomorphic_matcher.DescribeTo(&ss);
7746 }
7747 return ss.str();
7748 }
7749
7750 template <typename... Args>
7751 internal::ElementsAreMatcher<
7752 std::tuple<typename std::decay<const Args&>::type...>>
7753 ElementsAre(const Args&... matchers) {
7754 return internal::ElementsAreMatcher<
7755 std::tuple<typename std::decay<const Args&>::type...>>(
7756 std::make_tuple(matchers...));
7757 }
7758
7759 template <typename... Args>
7760 internal::UnorderedElementsAreMatcher<
7761 std::tuple<typename std::decay<const Args&>::type...>>
7762 UnorderedElementsAre(const Args&... matchers) {
7763 return internal::UnorderedElementsAreMatcher<
7764 std::tuple<typename std::decay<const Args&>::type...>>(
7765 std::make_tuple(matchers...));
7766 }
7767
7768 // Define variadic matcher versions.
7769 template <typename... Args>
7770 internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
7771 const Args&... matchers) {
7772 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
7773 matchers...);
7774 }
7775
7776 template <typename... Args>
7777 internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
7778 const Args&... matchers) {
7779 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
7780 matchers...);
7781 }
7782
7783 // AnyOfArray(array)
7784 // AnyOfArray(pointer, count)
7785 // AnyOfArray(container)
7786 // AnyOfArray({ e1, e2, ..., en })
7787 // AnyOfArray(iterator_first, iterator_last)
7788 //
7789 // AnyOfArray() verifies whether a given value matches any member of a
7790 // collection of matchers.
7791 //
7792 // AllOfArray(array)
7793 // AllOfArray(pointer, count)
7794 // AllOfArray(container)
7795 // AllOfArray({ e1, e2, ..., en })
7796 // AllOfArray(iterator_first, iterator_last)
7797 //
7798 // AllOfArray() verifies whether a given value matches all members of a
7799 // collection of matchers.
7800 //
7801 // The matchers can be specified as an array, a pointer and count, a container,
7802 // an initializer list, or an STL iterator range. In each of these cases, the
7803 // underlying matchers can be either values or matchers.
7804
7805 template <typename Iter>
7806 inline internal::AnyOfArrayMatcher<
7807 typename ::std::iterator_traits<Iter>::value_type>
7808 AnyOfArray(Iter first, Iter last) {
7809 return internal::AnyOfArrayMatcher<
7810 typename ::std::iterator_traits<Iter>::value_type>(first, last);
7811 }
7812
7813 template <typename Iter>
7814 inline internal::AllOfArrayMatcher<
7815 typename ::std::iterator_traits<Iter>::value_type>
7816 AllOfArray(Iter first, Iter last) {
7817 return internal::AllOfArrayMatcher<
7818 typename ::std::iterator_traits<Iter>::value_type>(first, last);
7819 }
7820
7821 template <typename T>
7822 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {
7823 return AnyOfArray(ptr, ptr + count);
7824 }
7825
7826 template <typename T>
7827 inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {
7828 return AllOfArray(ptr, ptr + count);
7829 }
7830
7831 template <typename T, size_t N>
7832 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {
7833 return AnyOfArray(array, N);
7834 }
7835
7836 template <typename T, size_t N>
7837 inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {
7838 return AllOfArray(array, N);
7839 }
7840
7841 template <typename Container>
7842 inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(
7843 const Container& container) {
7844 return AnyOfArray(container.begin(), container.end());
7845 }
7846
7847 template <typename Container>
7848 inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(
7849 const Container& container) {
7850 return AllOfArray(container.begin(), container.end());
7851 }
7852
7853 template <typename T>
7854 inline internal::AnyOfArrayMatcher<T> AnyOfArray(
7855 ::std::initializer_list<T> xs) {
7856 return AnyOfArray(xs.begin(), xs.end());
7857 }
7858
7859 template <typename T>
7860 inline internal::AllOfArrayMatcher<T> AllOfArray(
7861 ::std::initializer_list<T> xs) {
7862 return AllOfArray(xs.begin(), xs.end());
7863 }
7864
7865 // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
7866 // fields of it matches a_matcher. C++ doesn't support default
7867 // arguments for function templates, so we have to overload it.
7868 template <size_t... k, typename InnerMatcher>
7869 internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(
7870 InnerMatcher&& matcher) {
7871 return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(
7872 std::forward<InnerMatcher>(matcher));
7873 }
7874
7875 // AllArgs(m) is a synonym of m. This is useful in
7876 //
7877 // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
7878 //
7879 // which is easier to read than
7880 //
7881 // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
7882 template <typename InnerMatcher>
7883 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
7884
7885 // Returns a matcher that matches the value of an optional<> type variable.
7886 // The matcher implementation only uses '!arg' and requires that the optional<>
7887 // type has a 'value_type' member type and that '*arg' is of type 'value_type'
7888 // and is printable using 'PrintToString'. It is compatible with
7889 // std::optional/std::experimental::optional.
7890 // Note that to compare an optional type variable against nullopt you should
7891 // use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
7892 // optional value contains an optional itself.
7893 template <typename ValueMatcher>
7894 inline internal::OptionalMatcher<ValueMatcher> Optional(
7895 const ValueMatcher& value_matcher) {
7896 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
7897 }
7898
7899 // Returns a matcher that matches the value of a absl::any type variable.
7900 template <typename T>
7901 PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
7902 const Matcher<const T&>& matcher) {
7903 return MakePolymorphicMatcher(
7904 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
7905 }
7906
7907 // Returns a matcher that matches the value of a variant<> type variable.
7908 // The matcher implementation uses ADL to find the holds_alternative and get
7909 // functions.
7910 // It is compatible with std::variant.
7911 template <typename T>
7912 PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
7913 const Matcher<const T&>& matcher) {
7914 return MakePolymorphicMatcher(
7915 internal::variant_matcher::VariantMatcher<T>(matcher));
7916 }
7917
7918 #if GTEST_HAS_EXCEPTIONS
7919
7920 // Anything inside the `internal` namespace is internal to the implementation
7921 // and must not be used in user code!
7922 namespace internal {
7923
7924 class WithWhatMatcherImpl {
7925 public:
7926 WithWhatMatcherImpl(Matcher<std::string> matcher)
7927 : matcher_(std::move(matcher)) {}
7928
7929 void DescribeTo(std::ostream* os) const {
7930 *os << "contains .what() that ";
7931 matcher_.DescribeTo(os);
7932 }
7933
7934 void DescribeNegationTo(std::ostream* os) const {
7935 *os << "contains .what() that does not ";
7936 matcher_.DescribeTo(os);
7937 }
7938
7939 template <typename Err>
7940 bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
7941 *listener << "which contains .what() that ";
7942 return matcher_.MatchAndExplain(err.what(), listener);
7943 }
7944
7945 private:
7946 const Matcher<std::string> matcher_;
7947 };
7948
7949 inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(
7950 Matcher<std::string> m) {
7951 return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));
7952 }
7953
7954 template <typename Err>
7955 class ExceptionMatcherImpl {
7956 class NeverThrown {
7957 public:
7958 const char* what() const noexcept {
7959 return "this exception should never be thrown";
7960 }
7961 };
7962
7963 // If the matchee raises an exception of a wrong type, we'd like to
7964 // catch it and print its message and type. To do that, we add an additional
7965 // catch clause:
7966 //
7967 // try { ... }
7968 // catch (const Err&) { /* an expected exception */ }
7969 // catch (const std::exception&) { /* exception of a wrong type */ }
7970 //
7971 // However, if the `Err` itself is `std::exception`, we'd end up with two
7972 // identical `catch` clauses:
7973 //
7974 // try { ... }
7975 // catch (const std::exception&) { /* an expected exception */ }
7976 // catch (const std::exception&) { /* exception of a wrong type */ }
7977 //
7978 // This can cause a warning or an error in some compilers. To resolve
7979 // the issue, we use a fake error type whenever `Err` is `std::exception`:
7980 //
7981 // try { ... }
7982 // catch (const std::exception&) { /* an expected exception */ }
7983 // catch (const NeverThrown&) { /* exception of a wrong type */ }
7984 using DefaultExceptionType = typename std::conditional<
7985 std::is_same<typename std::remove_cv<
7986 typename std::remove_reference<Err>::type>::type,
7987 std::exception>::value,
7988 const NeverThrown&, const std::exception&>::type;
7989
7990 public:
7991 ExceptionMatcherImpl(Matcher<const Err&> matcher)
7992 : matcher_(std::move(matcher)) {}
7993
7994 void DescribeTo(std::ostream* os) const {
7995 *os << "throws an exception which is a " << GetTypeName<Err>();
7996 *os << " which ";
7997 matcher_.DescribeTo(os);
7998 }
7999
8000 void DescribeNegationTo(std::ostream* os) const {
8001 *os << "throws an exception which is not a " << GetTypeName<Err>();
8002 *os << " which ";
8003 matcher_.DescribeNegationTo(os);
8004 }
8005
8006 template <typename T>
8007 bool MatchAndExplain(T&& x, MatchResultListener* listener) const {
8008 try {
8009 (void)(std::forward<T>(x)());
8010 } catch (const Err& err) {
8011 *listener << "throws an exception which is a " << GetTypeName<Err>();
8012 *listener << " ";
8013 return matcher_.MatchAndExplain(err, listener);
8014 } catch (DefaultExceptionType err) {
8015 #if GTEST_HAS_RTTI
8016 *listener << "throws an exception of type " << GetTypeName(typeid(err));
8017 *listener << " ";
8018 #else
8019 *listener << "throws an std::exception-derived type ";
8020 #endif
8021 *listener << "with description \"" << err.what() << "\"";
8022 return false;
8023 } catch (...) {
8024 *listener << "throws an exception of an unknown type";
8025 return false;
8026 }
8027
8028 *listener << "does not throw any exception";
8029 return false;
8030 }
8031
8032 private:
8033 const Matcher<const Err&> matcher_;
8034 };
8035
8036 } // namespace internal
8037
8038 // Throws()
8039 // Throws(exceptionMatcher)
8040 // ThrowsMessage(messageMatcher)
8041 //
8042 // This matcher accepts a callable and verifies that when invoked, it throws
8043 // an exception with the given type and properties.
8044 //
8045 // Examples:
8046 //
8047 // EXPECT_THAT(
8048 // []() { throw std::runtime_error("message"); },
8049 // Throws<std::runtime_error>());
8050 //
8051 // EXPECT_THAT(
8052 // []() { throw std::runtime_error("message"); },
8053 // ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8054 //
8055 // EXPECT_THAT(
8056 // []() { throw std::runtime_error("message"); },
8057 // Throws<std::runtime_error>(
8058 // Property(&std::runtime_error::what, HasSubstr("message"))));
8059
8060 template <typename Err>
8061 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {
8062 return MakePolymorphicMatcher(
8063 internal::ExceptionMatcherImpl<Err>(A<const Err&>()));
8064 }
8065
8066 template <typename Err, typename ExceptionMatcher>
8067 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(
8068 const ExceptionMatcher& exception_matcher) {
8069 // Using matcher cast allows users to pass a matcher of a more broad type.
8070 // For example user may want to pass Matcher<std::exception>
8071 // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.
8072 return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(
8073 SafeMatcherCast<const Err&>(exception_matcher)));
8074 }
8075
8076 template <typename Err, typename MessageMatcher>
8077 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
8078 MessageMatcher&& message_matcher) {
8079 static_assert(std::is_base_of<std::exception, Err>::value,
8080 "expected an std::exception-derived type");
8081 return Throws<Err>(internal::WithWhat(
8082 MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));
8083 }
8084
8085 #endif // GTEST_HAS_EXCEPTIONS
8086
8087 // These macros allow using matchers to check values in Google Test
8088 // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
8089 // succeed if and only if the value matches the matcher. If the assertion
8090 // fails, the value and the description of the matcher will be printed.
8091 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
8092 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
8093 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
8094 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
8095
8096 // MATCHER* macroses itself are listed below.
8097 #define MATCHER(name, description) \
8098 class name##Matcher \
8099 : public ::testing::internal::MatcherBaseImpl<name##Matcher> { \
8100 public: \
8101 template <typename arg_type> \
8102 class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
8103 public: \
8104 gmock_Impl() {} \
8105 bool MatchAndExplain( \
8106 const arg_type& arg, \
8107 ::testing::MatchResultListener* result_listener) const override; \
8108 void DescribeTo(::std::ostream* gmock_os) const override { \
8109 *gmock_os << FormatDescription(false); \
8110 } \
8111 void DescribeNegationTo(::std::ostream* gmock_os) const override { \
8112 *gmock_os << FormatDescription(true); \
8113 } \
8114 \
8115 private: \
8116 ::std::string FormatDescription(bool negation) const { \
8117 ::std::string gmock_description = (description); \
8118 if (!gmock_description.empty()) { \
8119 return gmock_description; \
8120 } \
8121 return ::testing::internal::FormatMatcherDescription(negation, #name, \
8122 {}); \
8123 } \
8124 }; \
8125 }; \
8126 GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \
8127 template <typename arg_type> \
8128 bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
8129 const arg_type& arg, \
8130 ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
8131 const
8132
8133 #define MATCHER_P(name, p0, description) \
8134 GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (p0))
8135 #define MATCHER_P2(name, p0, p1, description) \
8136 GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (p0, p1))
8137 #define MATCHER_P3(name, p0, p1, p2, description) \
8138 GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (p0, p1, p2))
8139 #define MATCHER_P4(name, p0, p1, p2, p3, description) \
8140 GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, (p0, p1, p2, p3))
8141 #define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \
8142 GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
8143 (p0, p1, p2, p3, p4))
8144 #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
8145 GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \
8146 (p0, p1, p2, p3, p4, p5))
8147 #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
8148 GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \
8149 (p0, p1, p2, p3, p4, p5, p6))
8150 #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
8151 GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \
8152 (p0, p1, p2, p3, p4, p5, p6, p7))
8153 #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
8154 GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \
8155 (p0, p1, p2, p3, p4, p5, p6, p7, p8))
8156 #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
8157 GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \
8158 (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
8159
8160 #define GMOCK_INTERNAL_MATCHER(name, full_name, description, args) \
8161 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8162 class full_name : public ::testing::internal::MatcherBaseImpl< \
8163 full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
8164 public: \
8165 using full_name::MatcherBaseImpl::MatcherBaseImpl; \
8166 template <typename arg_type> \
8167 class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
8168 public: \
8169 explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
8170 : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
8171 bool MatchAndExplain( \
8172 const arg_type& arg, \
8173 ::testing::MatchResultListener* result_listener) const override; \
8174 void DescribeTo(::std::ostream* gmock_os) const override { \
8175 *gmock_os << FormatDescription(false); \
8176 } \
8177 void DescribeNegationTo(::std::ostream* gmock_os) const override { \
8178 *gmock_os << FormatDescription(true); \
8179 } \
8180 GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
8181 \
8182 private: \
8183 ::std::string FormatDescription(bool negation) const { \
8184 ::std::string gmock_description = (description); \
8185 if (!gmock_description.empty()) { \
8186 return gmock_description; \
8187 } \
8188 return ::testing::internal::FormatMatcherDescription( \
8189 negation, #name, \
8190 ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \
8191 ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
8192 GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \
8193 } \
8194 }; \
8195 }; \
8196 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8197 inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
8198 GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
8199 return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
8200 GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
8201 } \
8202 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8203 template <typename arg_type> \
8204 bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
8205 arg_type>::MatchAndExplain(const arg_type& arg, \
8206 ::testing::MatchResultListener* \
8207 result_listener GTEST_ATTRIBUTE_UNUSED_) \
8208 const
8209
8210 #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
8211 GMOCK_PP_TAIL( \
8212 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
8213 #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
8214 , typename arg##_type
8215
8216 #define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
8217 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
8218 #define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
8219 , arg##_type
8220
8221 #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
8222 GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
8223 GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
8224 #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
8225 , arg##_type gmock_p##i
8226
8227 #define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
8228 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
8229 #define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
8230 , arg(::std::forward<arg##_type>(gmock_p##i))
8231
8232 #define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
8233 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
8234 #define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
8235 const arg##_type arg;
8236
8237 #define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
8238 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
8239 #define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
8240
8241 #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
8242 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
8243 #define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
8244 , gmock_p##i
8245
8246 // To prevent ADL on certain functions we put them on a separate namespace.
8247 using namespace no_adl; // NOLINT
8248
8249 } // namespace testing
8250
8251 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
8252
8253 // Include any custom callback matchers added by the local installation.
8254 // We must include this header at the end to make sure it can use the
8255 // declarations from this file.
8256 // Copyright 2015, Google Inc.
8257 // All rights reserved.
8258 //
8259 // Redistribution and use in source and binary forms, with or without
8260 // modification, are permitted provided that the following conditions are
8261 // met:
8262 //
8263 // * Redistributions of source code must retain the above copyright
8264 // notice, this list of conditions and the following disclaimer.
8265 // * Redistributions in binary form must reproduce the above
8266 // copyright notice, this list of conditions and the following disclaimer
8267 // in the documentation and/or other materials provided with the
8268 // distribution.
8269 // * Neither the name of Google Inc. nor the names of its
8270 // contributors may be used to endorse or promote products derived from
8271 // this software without specific prior written permission.
8272 //
8273 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8274 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8275 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8276 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8277 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8278 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8279 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8280 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8281 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8282 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8283 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8284 //
8285 // Injection point for custom user configurations. See README for details
8286 //
8287 // GOOGLETEST_CM0002 DO NOT DELETE
8288
8289 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8290 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8291 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8292
8293 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
8294
8295 #if GTEST_HAS_EXCEPTIONS
8296 # include <stdexcept> // NOLINT
8297 #endif
8298
8299 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
8300 /* class A needs to have dll-interface to be used by clients of class B */)
8301
8302 namespace testing {
8303
8304 // An abstract handle of an expectation.
8305 class Expectation;
8306
8307 // A set of expectation handles.
8308 class ExpectationSet;
8309
8310 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
8311 // and MUST NOT BE USED IN USER CODE!!!
8312 namespace internal {
8313
8314 // Implements a mock function.
8315 template <typename F> class FunctionMocker;
8316
8317 // Base class for expectations.
8318 class ExpectationBase;
8319
8320 // Implements an expectation.
8321 template <typename F> class TypedExpectation;
8322
8323 // Helper class for testing the Expectation class template.
8324 class ExpectationTester;
8325
8326 // Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
8327 template <typename MockClass>
8328 class NiceMockImpl;
8329 template <typename MockClass>
8330 class StrictMockImpl;
8331 template <typename MockClass>
8332 class NaggyMockImpl;
8333
8334 // Protects the mock object registry (in class Mock), all function
8335 // mockers, and all expectations.
8336 //
8337 // The reason we don't use more fine-grained protection is: when a
8338 // mock function Foo() is called, it needs to consult its expectations
8339 // to see which one should be picked. If another thread is allowed to
8340 // call a mock function (either Foo() or a different one) at the same
8341 // time, it could affect the "retired" attributes of Foo()'s
8342 // expectations when InSequence() is used, and thus affect which
8343 // expectation gets picked. Therefore, we sequence all mock function
8344 // calls to ensure the integrity of the mock objects' states.
8345 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
8346
8347 // Untyped base class for ActionResultHolder<R>.
8348 class UntypedActionResultHolderBase;
8349
8350 // Abstract base class of FunctionMocker. This is the
8351 // type-agnostic part of the function mocker interface. Its pure
8352 // virtual methods are implemented by FunctionMocker.
8353 class GTEST_API_ UntypedFunctionMockerBase {
8354 public:
8355 UntypedFunctionMockerBase();
8356 virtual ~UntypedFunctionMockerBase();
8357
8358 // Verifies that all expectations on this mock function have been
8359 // satisfied. Reports one or more Google Test non-fatal failures
8360 // and returns false if not.
8361 bool VerifyAndClearExpectationsLocked()
8362 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
8363
8364 // Clears the ON_CALL()s set on this mock function.
8365 virtual void ClearDefaultActionsLocked()
8366 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
8367
8368 // In all of the following Untyped* functions, it's the caller's
8369 // responsibility to guarantee the correctness of the arguments'
8370 // types.
8371
8372 // Performs the default action with the given arguments and returns
8373 // the action's result. The call description string will be used in
8374 // the error message to describe the call in the case the default
8375 // action fails.
8376 // L = *
8377 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
8378 void* untyped_args, const std::string& call_description) const = 0;
8379
8380 // Performs the given action with the given arguments and returns
8381 // the action's result.
8382 // L = *
8383 virtual UntypedActionResultHolderBase* UntypedPerformAction(
8384 const void* untyped_action, void* untyped_args) const = 0;
8385
8386 // Writes a message that the call is uninteresting (i.e. neither
8387 // explicitly expected nor explicitly unexpected) to the given
8388 // ostream.
8389 virtual void UntypedDescribeUninterestingCall(
8390 const void* untyped_args,
8391 ::std::ostream* os) const
8392 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
8393
8394 // Returns the expectation that matches the given function arguments
8395 // (or NULL is there's no match); when a match is found,
8396 // untyped_action is set to point to the action that should be
8397 // performed (or NULL if the action is "do default"), and
8398 // is_excessive is modified to indicate whether the call exceeds the
8399 // expected number.
8400 virtual const ExpectationBase* UntypedFindMatchingExpectation(
8401 const void* untyped_args,
8402 const void** untyped_action, bool* is_excessive,
8403 ::std::ostream* what, ::std::ostream* why)
8404 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
8405
8406 // Prints the given function arguments to the ostream.
8407 virtual void UntypedPrintArgs(const void* untyped_args,
8408 ::std::ostream* os) const = 0;
8409
8410 // Sets the mock object this mock method belongs to, and registers
8411 // this information in the global mock registry. Will be called
8412 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
8413 // method.
8414 void RegisterOwner(const void* mock_obj)
8415 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8416
8417 // Sets the mock object this mock method belongs to, and sets the
8418 // name of the mock function. Will be called upon each invocation
8419 // of this mock function.
8420 void SetOwnerAndName(const void* mock_obj, const char* name)
8421 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8422
8423 // Returns the mock object this mock method belongs to. Must be
8424 // called after RegisterOwner() or SetOwnerAndName() has been
8425 // called.
8426 const void* MockObject() const
8427 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8428
8429 // Returns the name of this mock method. Must be called after
8430 // SetOwnerAndName() has been called.
8431 const char* Name() const
8432 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8433
8434 // Returns the result of invoking this mock function with the given
8435 // arguments. This function can be safely called from multiple
8436 // threads concurrently. The caller is responsible for deleting the
8437 // result.
8438 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
8439 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8440
8441 protected:
8442 typedef std::vector<const void*> UntypedOnCallSpecs;
8443
8444 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
8445
8446 // Returns an Expectation object that references and co-owns exp,
8447 // which must be an expectation on this mock function.
8448 Expectation GetHandleOf(ExpectationBase* exp);
8449
8450 // Address of the mock object this mock method belongs to. Only
8451 // valid after this mock method has been called or
8452 // ON_CALL/EXPECT_CALL has been invoked on it.
8453 const void* mock_obj_; // Protected by g_gmock_mutex.
8454
8455 // Name of the function being mocked. Only valid after this mock
8456 // method has been called.
8457 const char* name_; // Protected by g_gmock_mutex.
8458
8459 // All default action specs for this function mocker.
8460 UntypedOnCallSpecs untyped_on_call_specs_;
8461
8462 // All expectations for this function mocker.
8463 //
8464 // It's undefined behavior to interleave expectations (EXPECT_CALLs
8465 // or ON_CALLs) and mock function calls. Also, the order of
8466 // expectations is important. Therefore it's a logic race condition
8467 // to read/write untyped_expectations_ concurrently. In order for
8468 // tools like tsan to catch concurrent read/write accesses to
8469 // untyped_expectations, we deliberately leave accesses to it
8470 // unprotected.
8471 UntypedExpectations untyped_expectations_;
8472 }; // class UntypedFunctionMockerBase
8473
8474 // Untyped base class for OnCallSpec<F>.
8475 class UntypedOnCallSpecBase {
8476 public:
8477 // The arguments are the location of the ON_CALL() statement.
8478 UntypedOnCallSpecBase(const char* a_file, int a_line)
8479 : file_(a_file), line_(a_line), last_clause_(kNone) {}
8480
8481 // Where in the source file was the default action spec defined?
8482 const char* file() const { return file_; }
8483 int line() const { return line_; }
8484
8485 protected:
8486 // Gives each clause in the ON_CALL() statement a name.
8487 enum Clause {
8488 // Do not change the order of the enum members! The run-time
8489 // syntax checking relies on it.
8490 kNone,
8491 kWith,
8492 kWillByDefault
8493 };
8494
8495 // Asserts that the ON_CALL() statement has a certain property.
8496 void AssertSpecProperty(bool property,
8497 const std::string& failure_message) const {
8498 Assert(property, file_, line_, failure_message);
8499 }
8500
8501 // Expects that the ON_CALL() statement has a certain property.
8502 void ExpectSpecProperty(bool property,
8503 const std::string& failure_message) const {
8504 Expect(property, file_, line_, failure_message);
8505 }
8506
8507 const char* file_;
8508 int line_;
8509
8510 // The last clause in the ON_CALL() statement as seen so far.
8511 // Initially kNone and changes as the statement is parsed.
8512 Clause last_clause_;
8513 }; // class UntypedOnCallSpecBase
8514
8515 // This template class implements an ON_CALL spec.
8516 template <typename F>
8517 class OnCallSpec : public UntypedOnCallSpecBase {
8518 public:
8519 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
8520 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
8521
8522 // Constructs an OnCallSpec object from the information inside
8523 // the parenthesis of an ON_CALL() statement.
8524 OnCallSpec(const char* a_file, int a_line,
8525 const ArgumentMatcherTuple& matchers)
8526 : UntypedOnCallSpecBase(a_file, a_line),
8527 matchers_(matchers),
8528 // By default, extra_matcher_ should match anything. However,
8529 // we cannot initialize it with _ as that causes ambiguity between
8530 // Matcher's copy and move constructor for some argument types.
8531 extra_matcher_(A<const ArgumentTuple&>()) {}
8532
8533 // Implements the .With() clause.
8534 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
8535 // Makes sure this is called at most once.
8536 ExpectSpecProperty(last_clause_ < kWith,
8537 ".With() cannot appear "
8538 "more than once in an ON_CALL().");
8539 last_clause_ = kWith;
8540
8541 extra_matcher_ = m;
8542 return *this;
8543 }
8544
8545 // Implements the .WillByDefault() clause.
8546 OnCallSpec& WillByDefault(const Action<F>& action) {
8547 ExpectSpecProperty(last_clause_ < kWillByDefault,
8548 ".WillByDefault() must appear "
8549 "exactly once in an ON_CALL().");
8550 last_clause_ = kWillByDefault;
8551
8552 ExpectSpecProperty(!action.IsDoDefault(),
8553 "DoDefault() cannot be used in ON_CALL().");
8554 action_ = action;
8555 return *this;
8556 }
8557
8558 // Returns true if and only if the given arguments match the matchers.
8559 bool Matches(const ArgumentTuple& args) const {
8560 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
8561 }
8562
8563 // Returns the action specified by the user.
8564 const Action<F>& GetAction() const {
8565 AssertSpecProperty(last_clause_ == kWillByDefault,
8566 ".WillByDefault() must appear exactly "
8567 "once in an ON_CALL().");
8568 return action_;
8569 }
8570
8571 private:
8572 // The information in statement
8573 //
8574 // ON_CALL(mock_object, Method(matchers))
8575 // .With(multi-argument-matcher)
8576 // .WillByDefault(action);
8577 //
8578 // is recorded in the data members like this:
8579 //
8580 // source file that contains the statement => file_
8581 // line number of the statement => line_
8582 // matchers => matchers_
8583 // multi-argument-matcher => extra_matcher_
8584 // action => action_
8585 ArgumentMatcherTuple matchers_;
8586 Matcher<const ArgumentTuple&> extra_matcher_;
8587 Action<F> action_;
8588 }; // class OnCallSpec
8589
8590 // Possible reactions on uninteresting calls.
8591 enum CallReaction {
8592 kAllow,
8593 kWarn,
8594 kFail,
8595 };
8596
8597 } // namespace internal
8598
8599 // Utilities for manipulating mock objects.
8600 class GTEST_API_ Mock {
8601 public:
8602 // The following public methods can be called concurrently.
8603
8604 // Tells Google Mock to ignore mock_obj when checking for leaked
8605 // mock objects.
8606 static void AllowLeak(const void* mock_obj)
8607 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8608
8609 // Verifies and clears all expectations on the given mock object.
8610 // If the expectations aren't satisfied, generates one or more
8611 // Google Test non-fatal failures and returns false.
8612 static bool VerifyAndClearExpectations(void* mock_obj)
8613 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8614
8615 // Verifies all expectations on the given mock object and clears its
8616 // default actions and expectations. Returns true if and only if the
8617 // verification was successful.
8618 static bool VerifyAndClear(void* mock_obj)
8619 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8620
8621 // Returns whether the mock was created as a naggy mock (default)
8622 static bool IsNaggy(void* mock_obj)
8623 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8624 // Returns whether the mock was created as a nice mock
8625 static bool IsNice(void* mock_obj)
8626 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8627 // Returns whether the mock was created as a strict mock
8628 static bool IsStrict(void* mock_obj)
8629 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8630
8631 private:
8632 friend class internal::UntypedFunctionMockerBase;
8633
8634 // Needed for a function mocker to register itself (so that we know
8635 // how to clear a mock object).
8636 template <typename F>
8637 friend class internal::FunctionMocker;
8638
8639 template <typename MockClass>
8640 friend class internal::NiceMockImpl;
8641 template <typename MockClass>
8642 friend class internal::NaggyMockImpl;
8643 template <typename MockClass>
8644 friend class internal::StrictMockImpl;
8645
8646 // Tells Google Mock to allow uninteresting calls on the given mock
8647 // object.
8648 static void AllowUninterestingCalls(const void* mock_obj)
8649 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8650
8651 // Tells Google Mock to warn the user about uninteresting calls on
8652 // the given mock object.
8653 static void WarnUninterestingCalls(const void* mock_obj)
8654 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8655
8656 // Tells Google Mock to fail uninteresting calls on the given mock
8657 // object.
8658 static void FailUninterestingCalls(const void* mock_obj)
8659 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8660
8661 // Tells Google Mock the given mock object is being destroyed and
8662 // its entry in the call-reaction table should be removed.
8663 static void UnregisterCallReaction(const void* mock_obj)
8664 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8665
8666 // Returns the reaction Google Mock will have on uninteresting calls
8667 // made on the given mock object.
8668 static internal::CallReaction GetReactionOnUninterestingCalls(
8669 const void* mock_obj)
8670 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8671
8672 // Verifies that all expectations on the given mock object have been
8673 // satisfied. Reports one or more Google Test non-fatal failures
8674 // and returns false if not.
8675 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
8676 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8677
8678 // Clears all ON_CALL()s set on the given mock object.
8679 static void ClearDefaultActionsLocked(void* mock_obj)
8680 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8681
8682 // Registers a mock object and a mock method it owns.
8683 static void Register(
8684 const void* mock_obj,
8685 internal::UntypedFunctionMockerBase* mocker)
8686 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8687
8688 // Tells Google Mock where in the source code mock_obj is used in an
8689 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
8690 // information helps the user identify which object it is.
8691 static void RegisterUseByOnCallOrExpectCall(
8692 const void* mock_obj, const char* file, int line)
8693 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8694
8695 // Unregisters a mock method; removes the owning mock object from
8696 // the registry when the last mock method associated with it has
8697 // been unregistered. This is called only in the destructor of
8698 // FunctionMocker.
8699 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
8700 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8701 }; // class Mock
8702
8703 // An abstract handle of an expectation. Useful in the .After()
8704 // clause of EXPECT_CALL() for setting the (partial) order of
8705 // expectations. The syntax:
8706 //
8707 // Expectation e1 = EXPECT_CALL(...)...;
8708 // EXPECT_CALL(...).After(e1)...;
8709 //
8710 // sets two expectations where the latter can only be matched after
8711 // the former has been satisfied.
8712 //
8713 // Notes:
8714 // - This class is copyable and has value semantics.
8715 // - Constness is shallow: a const Expectation object itself cannot
8716 // be modified, but the mutable methods of the ExpectationBase
8717 // object it references can be called via expectation_base().
8718
8719 class GTEST_API_ Expectation {
8720 public:
8721 // Constructs a null object that doesn't reference any expectation.
8722 Expectation();
8723 Expectation(Expectation&&) = default;
8724 Expectation(const Expectation&) = default;
8725 Expectation& operator=(Expectation&&) = default;
8726 Expectation& operator=(const Expectation&) = default;
8727 ~Expectation();
8728
8729 // This single-argument ctor must not be explicit, in order to support the
8730 // Expectation e = EXPECT_CALL(...);
8731 // syntax.
8732 //
8733 // A TypedExpectation object stores its pre-requisites as
8734 // Expectation objects, and needs to call the non-const Retire()
8735 // method on the ExpectationBase objects they reference. Therefore
8736 // Expectation must receive a *non-const* reference to the
8737 // ExpectationBase object.
8738 Expectation(internal::ExpectationBase& exp); // NOLINT
8739
8740 // The compiler-generated copy ctor and operator= work exactly as
8741 // intended, so we don't need to define our own.
8742
8743 // Returns true if and only if rhs references the same expectation as this
8744 // object does.
8745 bool operator==(const Expectation& rhs) const {
8746 return expectation_base_ == rhs.expectation_base_;
8747 }
8748
8749 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
8750
8751 private:
8752 friend class ExpectationSet;
8753 friend class Sequence;
8754 friend class ::testing::internal::ExpectationBase;
8755 friend class ::testing::internal::UntypedFunctionMockerBase;
8756
8757 template <typename F>
8758 friend class ::testing::internal::FunctionMocker;
8759
8760 template <typename F>
8761 friend class ::testing::internal::TypedExpectation;
8762
8763 // This comparator is needed for putting Expectation objects into a set.
8764 class Less {
8765 public:
8766 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
8767 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
8768 }
8769 };
8770
8771 typedef ::std::set<Expectation, Less> Set;
8772
8773 Expectation(
8774 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
8775
8776 // Returns the expectation this object references.
8777 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
8778 return expectation_base_;
8779 }
8780
8781 // A shared_ptr that co-owns the expectation this handle references.
8782 std::shared_ptr<internal::ExpectationBase> expectation_base_;
8783 };
8784
8785 // A set of expectation handles. Useful in the .After() clause of
8786 // EXPECT_CALL() for setting the (partial) order of expectations. The
8787 // syntax:
8788 //
8789 // ExpectationSet es;
8790 // es += EXPECT_CALL(...)...;
8791 // es += EXPECT_CALL(...)...;
8792 // EXPECT_CALL(...).After(es)...;
8793 //
8794 // sets three expectations where the last one can only be matched
8795 // after the first two have both been satisfied.
8796 //
8797 // This class is copyable and has value semantics.
8798 class ExpectationSet {
8799 public:
8800 // A bidirectional iterator that can read a const element in the set.
8801 typedef Expectation::Set::const_iterator const_iterator;
8802
8803 // An object stored in the set. This is an alias of Expectation.
8804 typedef Expectation::Set::value_type value_type;
8805
8806 // Constructs an empty set.
8807 ExpectationSet() {}
8808
8809 // This single-argument ctor must not be explicit, in order to support the
8810 // ExpectationSet es = EXPECT_CALL(...);
8811 // syntax.
8812 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
8813 *this += Expectation(exp);
8814 }
8815
8816 // This single-argument ctor implements implicit conversion from
8817 // Expectation and thus must not be explicit. This allows either an
8818 // Expectation or an ExpectationSet to be used in .After().
8819 ExpectationSet(const Expectation& e) { // NOLINT
8820 *this += e;
8821 }
8822
8823 // The compiler-generator ctor and operator= works exactly as
8824 // intended, so we don't need to define our own.
8825
8826 // Returns true if and only if rhs contains the same set of Expectation
8827 // objects as this does.
8828 bool operator==(const ExpectationSet& rhs) const {
8829 return expectations_ == rhs.expectations_;
8830 }
8831
8832 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
8833
8834 // Implements the syntax
8835 // expectation_set += EXPECT_CALL(...);
8836 ExpectationSet& operator+=(const Expectation& e) {
8837 expectations_.insert(e);
8838 return *this;
8839 }
8840
8841 int size() const { return static_cast<int>(expectations_.size()); }
8842
8843 const_iterator begin() const { return expectations_.begin(); }
8844 const_iterator end() const { return expectations_.end(); }
8845
8846 private:
8847 Expectation::Set expectations_;
8848 };
8849
8850
8851 // Sequence objects are used by a user to specify the relative order
8852 // in which the expectations should match. They are copyable (we rely
8853 // on the compiler-defined copy constructor and assignment operator).
8854 class GTEST_API_ Sequence {
8855 public:
8856 // Constructs an empty sequence.
8857 Sequence() : last_expectation_(new Expectation) {}
8858
8859 // Adds an expectation to this sequence. The caller must ensure
8860 // that no other thread is accessing this Sequence object.
8861 void AddExpectation(const Expectation& expectation) const;
8862
8863 private:
8864 // The last expectation in this sequence.
8865 std::shared_ptr<Expectation> last_expectation_;
8866 }; // class Sequence
8867
8868 // An object of this type causes all EXPECT_CALL() statements
8869 // encountered in its scope to be put in an anonymous sequence. The
8870 // work is done in the constructor and destructor. You should only
8871 // create an InSequence object on the stack.
8872 //
8873 // The sole purpose for this class is to support easy definition of
8874 // sequential expectations, e.g.
8875 //
8876 // {
8877 // InSequence dummy; // The name of the object doesn't matter.
8878 //
8879 // // The following expectations must match in the order they appear.
8880 // EXPECT_CALL(a, Bar())...;
8881 // EXPECT_CALL(a, Baz())...;
8882 // ...
8883 // EXPECT_CALL(b, Xyz())...;
8884 // }
8885 //
8886 // You can create InSequence objects in multiple threads, as long as
8887 // they are used to affect different mock objects. The idea is that
8888 // each thread can create and set up its own mocks as if it's the only
8889 // thread. However, for clarity of your tests we recommend you to set
8890 // up mocks in the main thread unless you have a good reason not to do
8891 // so.
8892 class GTEST_API_ InSequence {
8893 public:
8894 InSequence();
8895 ~InSequence();
8896 private:
8897 bool sequence_created_;
8898
8899 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
8900 } GTEST_ATTRIBUTE_UNUSED_;
8901
8902 namespace internal {
8903
8904 // Points to the implicit sequence introduced by a living InSequence
8905 // object (if any) in the current thread or NULL.
8906 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
8907
8908 // Base class for implementing expectations.
8909 //
8910 // There are two reasons for having a type-agnostic base class for
8911 // Expectation:
8912 //
8913 // 1. We need to store collections of expectations of different
8914 // types (e.g. all pre-requisites of a particular expectation, all
8915 // expectations in a sequence). Therefore these expectation objects
8916 // must share a common base class.
8917 //
8918 // 2. We can avoid binary code bloat by moving methods not depending
8919 // on the template argument of Expectation to the base class.
8920 //
8921 // This class is internal and mustn't be used by user code directly.
8922 class GTEST_API_ ExpectationBase {
8923 public:
8924 // source_text is the EXPECT_CALL(...) source that created this Expectation.
8925 ExpectationBase(const char* file, int line, const std::string& source_text);
8926
8927 virtual ~ExpectationBase();
8928
8929 // Where in the source file was the expectation spec defined?
8930 const char* file() const { return file_; }
8931 int line() const { return line_; }
8932 const char* source_text() const { return source_text_.c_str(); }
8933 // Returns the cardinality specified in the expectation spec.
8934 const Cardinality& cardinality() const { return cardinality_; }
8935
8936 // Describes the source file location of this expectation.
8937 void DescribeLocationTo(::std::ostream* os) const {
8938 *os << FormatFileLocation(file(), line()) << " ";
8939 }
8940
8941 // Describes how many times a function call matching this
8942 // expectation has occurred.
8943 void DescribeCallCountTo(::std::ostream* os) const
8944 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
8945
8946 // If this mock method has an extra matcher (i.e. .With(matcher)),
8947 // describes it to the ostream.
8948 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
8949
8950 protected:
8951 friend class ::testing::Expectation;
8952 friend class UntypedFunctionMockerBase;
8953
8954 enum Clause {
8955 // Don't change the order of the enum members!
8956 kNone,
8957 kWith,
8958 kTimes,
8959 kInSequence,
8960 kAfter,
8961 kWillOnce,
8962 kWillRepeatedly,
8963 kRetiresOnSaturation
8964 };
8965
8966 typedef std::vector<const void*> UntypedActions;
8967
8968 // Returns an Expectation object that references and co-owns this
8969 // expectation.
8970 virtual Expectation GetHandle() = 0;
8971
8972 // Asserts that the EXPECT_CALL() statement has the given property.
8973 void AssertSpecProperty(bool property,
8974 const std::string& failure_message) const {
8975 Assert(property, file_, line_, failure_message);
8976 }
8977
8978 // Expects that the EXPECT_CALL() statement has the given property.
8979 void ExpectSpecProperty(bool property,
8980 const std::string& failure_message) const {
8981 Expect(property, file_, line_, failure_message);
8982 }
8983
8984 // Explicitly specifies the cardinality of this expectation. Used
8985 // by the subclasses to implement the .Times() clause.
8986 void SpecifyCardinality(const Cardinality& cardinality);
8987
8988 // Returns true if and only if the user specified the cardinality
8989 // explicitly using a .Times().
8990 bool cardinality_specified() const { return cardinality_specified_; }
8991
8992 // Sets the cardinality of this expectation spec.
8993 void set_cardinality(const Cardinality& a_cardinality) {
8994 cardinality_ = a_cardinality;
8995 }
8996
8997 // The following group of methods should only be called after the
8998 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
8999 // the current thread.
9000
9001 // Retires all pre-requisites of this expectation.
9002 void RetireAllPreRequisites()
9003 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9004
9005 // Returns true if and only if this expectation is retired.
9006 bool is_retired() const
9007 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9008 g_gmock_mutex.AssertHeld();
9009 return retired_;
9010 }
9011
9012 // Retires this expectation.
9013 void Retire()
9014 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9015 g_gmock_mutex.AssertHeld();
9016 retired_ = true;
9017 }
9018
9019 // Returns true if and only if this expectation is satisfied.
9020 bool IsSatisfied() const
9021 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9022 g_gmock_mutex.AssertHeld();
9023 return cardinality().IsSatisfiedByCallCount(call_count_);
9024 }
9025
9026 // Returns true if and only if this expectation is saturated.
9027 bool IsSaturated() const
9028 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9029 g_gmock_mutex.AssertHeld();
9030 return cardinality().IsSaturatedByCallCount(call_count_);
9031 }
9032
9033 // Returns true if and only if this expectation is over-saturated.
9034 bool IsOverSaturated() const
9035 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9036 g_gmock_mutex.AssertHeld();
9037 return cardinality().IsOverSaturatedByCallCount(call_count_);
9038 }
9039
9040 // Returns true if and only if all pre-requisites of this expectation are
9041 // satisfied.
9042 bool AllPrerequisitesAreSatisfied() const
9043 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9044
9045 // Adds unsatisfied pre-requisites of this expectation to 'result'.
9046 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
9047 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9048
9049 // Returns the number this expectation has been invoked.
9050 int call_count() const
9051 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9052 g_gmock_mutex.AssertHeld();
9053 return call_count_;
9054 }
9055
9056 // Increments the number this expectation has been invoked.
9057 void IncrementCallCount()
9058 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9059 g_gmock_mutex.AssertHeld();
9060 call_count_++;
9061 }
9062
9063 // Checks the action count (i.e. the number of WillOnce() and
9064 // WillRepeatedly() clauses) against the cardinality if this hasn't
9065 // been done before. Prints a warning if there are too many or too
9066 // few actions.
9067 void CheckActionCountIfNotDone() const
9068 GTEST_LOCK_EXCLUDED_(mutex_);
9069
9070 friend class ::testing::Sequence;
9071 friend class ::testing::internal::ExpectationTester;
9072
9073 template <typename Function>
9074 friend class TypedExpectation;
9075
9076 // Implements the .Times() clause.
9077 void UntypedTimes(const Cardinality& a_cardinality);
9078
9079 // This group of fields are part of the spec and won't change after
9080 // an EXPECT_CALL() statement finishes.
9081 const char* file_; // The file that contains the expectation.
9082 int line_; // The line number of the expectation.
9083 const std::string source_text_; // The EXPECT_CALL(...) source text.
9084 // True if and only if the cardinality is specified explicitly.
9085 bool cardinality_specified_;
9086 Cardinality cardinality_; // The cardinality of the expectation.
9087 // The immediate pre-requisites (i.e. expectations that must be
9088 // satisfied before this expectation can be matched) of this
9089 // expectation. We use std::shared_ptr in the set because we want an
9090 // Expectation object to be co-owned by its FunctionMocker and its
9091 // successors. This allows multiple mock objects to be deleted at
9092 // different times.
9093 ExpectationSet immediate_prerequisites_;
9094
9095 // This group of fields are the current state of the expectation,
9096 // and can change as the mock function is called.
9097 int call_count_; // How many times this expectation has been invoked.
9098 bool retired_; // True if and only if this expectation has retired.
9099 UntypedActions untyped_actions_;
9100 bool extra_matcher_specified_;
9101 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
9102 bool retires_on_saturation_;
9103 Clause last_clause_;
9104 mutable bool action_count_checked_; // Under mutex_.
9105 mutable Mutex mutex_; // Protects action_count_checked_.
9106 }; // class ExpectationBase
9107
9108 // Impements an expectation for the given function type.
9109 template <typename F>
9110 class TypedExpectation : public ExpectationBase {
9111 public:
9112 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
9113 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
9114 typedef typename Function<F>::Result Result;
9115
9116 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
9117 const std::string& a_source_text,
9118 const ArgumentMatcherTuple& m)
9119 : ExpectationBase(a_file, a_line, a_source_text),
9120 owner_(owner),
9121 matchers_(m),
9122 // By default, extra_matcher_ should match anything. However,
9123 // we cannot initialize it with _ as that causes ambiguity between
9124 // Matcher's copy and move constructor for some argument types.
9125 extra_matcher_(A<const ArgumentTuple&>()),
9126 repeated_action_(DoDefault()) {}
9127
9128 ~TypedExpectation() override {
9129 // Check the validity of the action count if it hasn't been done
9130 // yet (for example, if the expectation was never used).
9131 CheckActionCountIfNotDone();
9132 for (UntypedActions::const_iterator it = untyped_actions_.begin();
9133 it != untyped_actions_.end(); ++it) {
9134 delete static_cast<const Action<F>*>(*it);
9135 }
9136 }
9137
9138 // Implements the .With() clause.
9139 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
9140 if (last_clause_ == kWith) {
9141 ExpectSpecProperty(false,
9142 ".With() cannot appear "
9143 "more than once in an EXPECT_CALL().");
9144 } else {
9145 ExpectSpecProperty(last_clause_ < kWith,
9146 ".With() must be the first "
9147 "clause in an EXPECT_CALL().");
9148 }
9149 last_clause_ = kWith;
9150
9151 extra_matcher_ = m;
9152 extra_matcher_specified_ = true;
9153 return *this;
9154 }
9155
9156 // Implements the .Times() clause.
9157 TypedExpectation& Times(const Cardinality& a_cardinality) {
9158 ExpectationBase::UntypedTimes(a_cardinality);
9159 return *this;
9160 }
9161
9162 // Implements the .Times() clause.
9163 TypedExpectation& Times(int n) {
9164 return Times(Exactly(n));
9165 }
9166
9167 // Implements the .InSequence() clause.
9168 TypedExpectation& InSequence(const Sequence& s) {
9169 ExpectSpecProperty(last_clause_ <= kInSequence,
9170 ".InSequence() cannot appear after .After(),"
9171 " .WillOnce(), .WillRepeatedly(), or "
9172 ".RetiresOnSaturation().");
9173 last_clause_ = kInSequence;
9174
9175 s.AddExpectation(GetHandle());
9176 return *this;
9177 }
9178 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
9179 return InSequence(s1).InSequence(s2);
9180 }
9181 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9182 const Sequence& s3) {
9183 return InSequence(s1, s2).InSequence(s3);
9184 }
9185 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9186 const Sequence& s3, const Sequence& s4) {
9187 return InSequence(s1, s2, s3).InSequence(s4);
9188 }
9189 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9190 const Sequence& s3, const Sequence& s4,
9191 const Sequence& s5) {
9192 return InSequence(s1, s2, s3, s4).InSequence(s5);
9193 }
9194
9195 // Implements that .After() clause.
9196 TypedExpectation& After(const ExpectationSet& s) {
9197 ExpectSpecProperty(last_clause_ <= kAfter,
9198 ".After() cannot appear after .WillOnce(),"
9199 " .WillRepeatedly(), or "
9200 ".RetiresOnSaturation().");
9201 last_clause_ = kAfter;
9202
9203 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
9204 immediate_prerequisites_ += *it;
9205 }
9206 return *this;
9207 }
9208 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
9209 return After(s1).After(s2);
9210 }
9211 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9212 const ExpectationSet& s3) {
9213 return After(s1, s2).After(s3);
9214 }
9215 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9216 const ExpectationSet& s3, const ExpectationSet& s4) {
9217 return After(s1, s2, s3).After(s4);
9218 }
9219 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9220 const ExpectationSet& s3, const ExpectationSet& s4,
9221 const ExpectationSet& s5) {
9222 return After(s1, s2, s3, s4).After(s5);
9223 }
9224
9225 // Implements the .WillOnce() clause.
9226 TypedExpectation& WillOnce(const Action<F>& action) {
9227 ExpectSpecProperty(last_clause_ <= kWillOnce,
9228 ".WillOnce() cannot appear after "
9229 ".WillRepeatedly() or .RetiresOnSaturation().");
9230 last_clause_ = kWillOnce;
9231
9232 untyped_actions_.push_back(new Action<F>(action));
9233 if (!cardinality_specified()) {
9234 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
9235 }
9236 return *this;
9237 }
9238
9239 // Implements the .WillRepeatedly() clause.
9240 TypedExpectation& WillRepeatedly(const Action<F>& action) {
9241 if (last_clause_ == kWillRepeatedly) {
9242 ExpectSpecProperty(false,
9243 ".WillRepeatedly() cannot appear "
9244 "more than once in an EXPECT_CALL().");
9245 } else {
9246 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
9247 ".WillRepeatedly() cannot appear "
9248 "after .RetiresOnSaturation().");
9249 }
9250 last_clause_ = kWillRepeatedly;
9251 repeated_action_specified_ = true;
9252
9253 repeated_action_ = action;
9254 if (!cardinality_specified()) {
9255 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
9256 }
9257
9258 // Now that no more action clauses can be specified, we check
9259 // whether their count makes sense.
9260 CheckActionCountIfNotDone();
9261 return *this;
9262 }
9263
9264 // Implements the .RetiresOnSaturation() clause.
9265 TypedExpectation& RetiresOnSaturation() {
9266 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
9267 ".RetiresOnSaturation() cannot appear "
9268 "more than once.");
9269 last_clause_ = kRetiresOnSaturation;
9270 retires_on_saturation_ = true;
9271
9272 // Now that no more action clauses can be specified, we check
9273 // whether their count makes sense.
9274 CheckActionCountIfNotDone();
9275 return *this;
9276 }
9277
9278 // Returns the matchers for the arguments as specified inside the
9279 // EXPECT_CALL() macro.
9280 const ArgumentMatcherTuple& matchers() const {
9281 return matchers_;
9282 }
9283
9284 // Returns the matcher specified by the .With() clause.
9285 const Matcher<const ArgumentTuple&>& extra_matcher() const {
9286 return extra_matcher_;
9287 }
9288
9289 // Returns the action specified by the .WillRepeatedly() clause.
9290 const Action<F>& repeated_action() const { return repeated_action_; }
9291
9292 // If this mock method has an extra matcher (i.e. .With(matcher)),
9293 // describes it to the ostream.
9294 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
9295 if (extra_matcher_specified_) {
9296 *os << " Expected args: ";
9297 extra_matcher_.DescribeTo(os);
9298 *os << "\n";
9299 }
9300 }
9301
9302 private:
9303 template <typename Function>
9304 friend class FunctionMocker;
9305
9306 // Returns an Expectation object that references and co-owns this
9307 // expectation.
9308 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
9309
9310 // The following methods will be called only after the EXPECT_CALL()
9311 // statement finishes and when the current thread holds
9312 // g_gmock_mutex.
9313
9314 // Returns true if and only if this expectation matches the given arguments.
9315 bool Matches(const ArgumentTuple& args) const
9316 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9317 g_gmock_mutex.AssertHeld();
9318 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
9319 }
9320
9321 // Returns true if and only if this expectation should handle the given
9322 // arguments.
9323 bool ShouldHandleArguments(const ArgumentTuple& args) const
9324 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9325 g_gmock_mutex.AssertHeld();
9326
9327 // In case the action count wasn't checked when the expectation
9328 // was defined (e.g. if this expectation has no WillRepeatedly()
9329 // or RetiresOnSaturation() clause), we check it when the
9330 // expectation is used for the first time.
9331 CheckActionCountIfNotDone();
9332 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
9333 }
9334
9335 // Describes the result of matching the arguments against this
9336 // expectation to the given ostream.
9337 void ExplainMatchResultTo(
9338 const ArgumentTuple& args,
9339 ::std::ostream* os) const
9340 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9341 g_gmock_mutex.AssertHeld();
9342
9343 if (is_retired()) {
9344 *os << " Expected: the expectation is active\n"
9345 << " Actual: it is retired\n";
9346 } else if (!Matches(args)) {
9347 if (!TupleMatches(matchers_, args)) {
9348 ExplainMatchFailureTupleTo(matchers_, args, os);
9349 }
9350 StringMatchResultListener listener;
9351 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
9352 *os << " Expected args: ";
9353 extra_matcher_.DescribeTo(os);
9354 *os << "\n Actual: don't match";
9355
9356 internal::PrintIfNotEmpty(listener.str(), os);
9357 *os << "\n";
9358 }
9359 } else if (!AllPrerequisitesAreSatisfied()) {
9360 *os << " Expected: all pre-requisites are satisfied\n"
9361 << " Actual: the following immediate pre-requisites "
9362 << "are not satisfied:\n";
9363 ExpectationSet unsatisfied_prereqs;
9364 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
9365 int i = 0;
9366 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
9367 it != unsatisfied_prereqs.end(); ++it) {
9368 it->expectation_base()->DescribeLocationTo(os);
9369 *os << "pre-requisite #" << i++ << "\n";
9370 }
9371 *os << " (end of pre-requisites)\n";
9372 } else {
9373 // This line is here just for completeness' sake. It will never
9374 // be executed as currently the ExplainMatchResultTo() function
9375 // is called only when the mock function call does NOT match the
9376 // expectation.
9377 *os << "The call matches the expectation.\n";
9378 }
9379 }
9380
9381 // Returns the action that should be taken for the current invocation.
9382 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
9383 const ArgumentTuple& args) const
9384 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9385 g_gmock_mutex.AssertHeld();
9386 const int count = call_count();
9387 Assert(count >= 1, __FILE__, __LINE__,
9388 "call_count() is <= 0 when GetCurrentAction() is "
9389 "called - this should never happen.");
9390
9391 const int action_count = static_cast<int>(untyped_actions_.size());
9392 if (action_count > 0 && !repeated_action_specified_ &&
9393 count > action_count) {
9394 // If there is at least one WillOnce() and no WillRepeatedly(),
9395 // we warn the user when the WillOnce() clauses ran out.
9396 ::std::stringstream ss;
9397 DescribeLocationTo(&ss);
9398 ss << "Actions ran out in " << source_text() << "...\n"
9399 << "Called " << count << " times, but only "
9400 << action_count << " WillOnce()"
9401 << (action_count == 1 ? " is" : "s are") << " specified - ";
9402 mocker->DescribeDefaultActionTo(args, &ss);
9403 Log(kWarning, ss.str(), 1);
9404 }
9405
9406 return count <= action_count
9407 ? *static_cast<const Action<F>*>(
9408 untyped_actions_[static_cast<size_t>(count - 1)])
9409 : repeated_action();
9410 }
9411
9412 // Given the arguments of a mock function call, if the call will
9413 // over-saturate this expectation, returns the default action;
9414 // otherwise, returns the next action in this expectation. Also
9415 // describes *what* happened to 'what', and explains *why* Google
9416 // Mock does it to 'why'. This method is not const as it calls
9417 // IncrementCallCount(). A return value of NULL means the default
9418 // action.
9419 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
9420 const ArgumentTuple& args,
9421 ::std::ostream* what,
9422 ::std::ostream* why)
9423 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9424 g_gmock_mutex.AssertHeld();
9425 if (IsSaturated()) {
9426 // We have an excessive call.
9427 IncrementCallCount();
9428 *what << "Mock function called more times than expected - ";
9429 mocker->DescribeDefaultActionTo(args, what);
9430 DescribeCallCountTo(why);
9431
9432 return nullptr;
9433 }
9434
9435 IncrementCallCount();
9436 RetireAllPreRequisites();
9437
9438 if (retires_on_saturation_ && IsSaturated()) {
9439 Retire();
9440 }
9441
9442 // Must be done after IncrementCount()!
9443 *what << "Mock function call matches " << source_text() <<"...\n";
9444 return &(GetCurrentAction(mocker, args));
9445 }
9446
9447 // All the fields below won't change once the EXPECT_CALL()
9448 // statement finishes.
9449 FunctionMocker<F>* const owner_;
9450 ArgumentMatcherTuple matchers_;
9451 Matcher<const ArgumentTuple&> extra_matcher_;
9452 Action<F> repeated_action_;
9453
9454 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
9455 }; // class TypedExpectation
9456
9457 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
9458 // specifying the default behavior of, or expectation on, a mock
9459 // function.
9460
9461 // Note: class MockSpec really belongs to the ::testing namespace.
9462 // However if we define it in ::testing, MSVC will complain when
9463 // classes in ::testing::internal declare it as a friend class
9464 // template. To workaround this compiler bug, we define MockSpec in
9465 // ::testing::internal and import it into ::testing.
9466
9467 // Logs a message including file and line number information.
9468 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
9469 const char* file, int line,
9470 const std::string& message);
9471
9472 template <typename F>
9473 class MockSpec {
9474 public:
9475 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
9476 typedef typename internal::Function<F>::ArgumentMatcherTuple
9477 ArgumentMatcherTuple;
9478
9479 // Constructs a MockSpec object, given the function mocker object
9480 // that the spec is associated with.
9481 MockSpec(internal::FunctionMocker<F>* function_mocker,
9482 const ArgumentMatcherTuple& matchers)
9483 : function_mocker_(function_mocker), matchers_(matchers) {}
9484
9485 // Adds a new default action spec to the function mocker and returns
9486 // the newly created spec.
9487 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
9488 const char* file, int line, const char* obj, const char* call) {
9489 LogWithLocation(internal::kInfo, file, line,
9490 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
9491 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
9492 }
9493
9494 // Adds a new expectation spec to the function mocker and returns
9495 // the newly created spec.
9496 internal::TypedExpectation<F>& InternalExpectedAt(
9497 const char* file, int line, const char* obj, const char* call) {
9498 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
9499 call + ")");
9500 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
9501 return function_mocker_->AddNewExpectation(
9502 file, line, source_text, matchers_);
9503 }
9504
9505 // This operator overload is used to swallow the superfluous parameter list
9506 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
9507 // explanation.
9508 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
9509 return *this;
9510 }
9511
9512 private:
9513 template <typename Function>
9514 friend class internal::FunctionMocker;
9515
9516 // The function mocker that owns this spec.
9517 internal::FunctionMocker<F>* const function_mocker_;
9518 // The argument matchers specified in the spec.
9519 ArgumentMatcherTuple matchers_;
9520 }; // class MockSpec
9521
9522 // Wrapper type for generically holding an ordinary value or lvalue reference.
9523 // If T is not a reference type, it must be copyable or movable.
9524 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
9525 // T is a move-only value type (which means that it will always be copyable
9526 // if the current platform does not support move semantics).
9527 //
9528 // The primary template defines handling for values, but function header
9529 // comments describe the contract for the whole template (including
9530 // specializations).
9531 template <typename T>
9532 class ReferenceOrValueWrapper {
9533 public:
9534 // Constructs a wrapper from the given value/reference.
9535 explicit ReferenceOrValueWrapper(T value)
9536 : value_(std::move(value)) {
9537 }
9538
9539 // Unwraps and returns the underlying value/reference, exactly as
9540 // originally passed. The behavior of calling this more than once on
9541 // the same object is unspecified.
9542 T Unwrap() { return std::move(value_); }
9543
9544 // Provides nondestructive access to the underlying value/reference.
9545 // Always returns a const reference (more precisely,
9546 // const std::add_lvalue_reference<T>::type). The behavior of calling this
9547 // after calling Unwrap on the same object is unspecified.
9548 const T& Peek() const {
9549 return value_;
9550 }
9551
9552 private:
9553 T value_;
9554 };
9555
9556 // Specialization for lvalue reference types. See primary template
9557 // for documentation.
9558 template <typename T>
9559 class ReferenceOrValueWrapper<T&> {
9560 public:
9561 // Workaround for debatable pass-by-reference lint warning (c-library-team
9562 // policy precludes NOLINT in this context)
9563 typedef T& reference;
9564 explicit ReferenceOrValueWrapper(reference ref)
9565 : value_ptr_(&ref) {}
9566 T& Unwrap() { return *value_ptr_; }
9567 const T& Peek() const { return *value_ptr_; }
9568
9569 private:
9570 T* value_ptr_;
9571 };
9572
9573 // C++ treats the void type specially. For example, you cannot define
9574 // a void-typed variable or pass a void value to a function.
9575 // ActionResultHolder<T> holds a value of type T, where T must be a
9576 // copyable type or void (T doesn't need to be default-constructable).
9577 // It hides the syntactic difference between void and other types, and
9578 // is used to unify the code for invoking both void-returning and
9579 // non-void-returning mock functions.
9580
9581 // Untyped base class for ActionResultHolder<T>.
9582 class UntypedActionResultHolderBase {
9583 public:
9584 virtual ~UntypedActionResultHolderBase() {}
9585
9586 // Prints the held value as an action's result to os.
9587 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
9588 };
9589
9590 // This generic definition is used when T is not void.
9591 template <typename T>
9592 class ActionResultHolder : public UntypedActionResultHolderBase {
9593 public:
9594 // Returns the held value. Must not be called more than once.
9595 T Unwrap() {
9596 return result_.Unwrap();
9597 }
9598
9599 // Prints the held value as an action's result to os.
9600 void PrintAsActionResult(::std::ostream* os) const override {
9601 *os << "\n Returns: ";
9602 // T may be a reference type, so we don't use UniversalPrint().
9603 UniversalPrinter<T>::Print(result_.Peek(), os);
9604 }
9605
9606 // Performs the given mock function's default action and returns the
9607 // result in a new-ed ActionResultHolder.
9608 template <typename F>
9609 static ActionResultHolder* PerformDefaultAction(
9610 const FunctionMocker<F>* func_mocker,
9611 typename Function<F>::ArgumentTuple&& args,
9612 const std::string& call_description) {
9613 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
9614 std::move(args), call_description)));
9615 }
9616
9617 // Performs the given action and returns the result in a new-ed
9618 // ActionResultHolder.
9619 template <typename F>
9620 static ActionResultHolder* PerformAction(
9621 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
9622 return new ActionResultHolder(
9623 Wrapper(action.Perform(std::move(args))));
9624 }
9625
9626 private:
9627 typedef ReferenceOrValueWrapper<T> Wrapper;
9628
9629 explicit ActionResultHolder(Wrapper result)
9630 : result_(std::move(result)) {
9631 }
9632
9633 Wrapper result_;
9634
9635 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
9636 };
9637
9638 // Specialization for T = void.
9639 template <>
9640 class ActionResultHolder<void> : public UntypedActionResultHolderBase {
9641 public:
9642 void Unwrap() { }
9643
9644 void PrintAsActionResult(::std::ostream* /* os */) const override {}
9645
9646 // Performs the given mock function's default action and returns ownership
9647 // of an empty ActionResultHolder*.
9648 template <typename F>
9649 static ActionResultHolder* PerformDefaultAction(
9650 const FunctionMocker<F>* func_mocker,
9651 typename Function<F>::ArgumentTuple&& args,
9652 const std::string& call_description) {
9653 func_mocker->PerformDefaultAction(std::move(args), call_description);
9654 return new ActionResultHolder;
9655 }
9656
9657 // Performs the given action and returns ownership of an empty
9658 // ActionResultHolder*.
9659 template <typename F>
9660 static ActionResultHolder* PerformAction(
9661 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
9662 action.Perform(std::move(args));
9663 return new ActionResultHolder;
9664 }
9665
9666 private:
9667 ActionResultHolder() {}
9668 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
9669 };
9670
9671 template <typename F>
9672 class FunctionMocker;
9673
9674 template <typename R, typename... Args>
9675 class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
9676 using F = R(Args...);
9677
9678 public:
9679 using Result = R;
9680 using ArgumentTuple = std::tuple<Args...>;
9681 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
9682
9683 FunctionMocker() {}
9684
9685 // There is no generally useful and implementable semantics of
9686 // copying a mock object, so copying a mock is usually a user error.
9687 // Thus we disallow copying function mockers. If the user really
9688 // wants to copy a mock object, they should implement their own copy
9689 // operation, for example:
9690 //
9691 // class MockFoo : public Foo {
9692 // public:
9693 // // Defines a copy constructor explicitly.
9694 // MockFoo(const MockFoo& src) {}
9695 // ...
9696 // };
9697 FunctionMocker(const FunctionMocker&) = delete;
9698 FunctionMocker& operator=(const FunctionMocker&) = delete;
9699
9700 // The destructor verifies that all expectations on this mock
9701 // function have been satisfied. If not, it will report Google Test
9702 // non-fatal failures for the violations.
9703 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9704 MutexLock l(&g_gmock_mutex);
9705 VerifyAndClearExpectationsLocked();
9706 Mock::UnregisterLocked(this);
9707 ClearDefaultActionsLocked();
9708 }
9709
9710 // Returns the ON_CALL spec that matches this mock function with the
9711 // given arguments; returns NULL if no matching ON_CALL is found.
9712 // L = *
9713 const OnCallSpec<F>* FindOnCallSpec(
9714 const ArgumentTuple& args) const {
9715 for (UntypedOnCallSpecs::const_reverse_iterator it
9716 = untyped_on_call_specs_.rbegin();
9717 it != untyped_on_call_specs_.rend(); ++it) {
9718 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
9719 if (spec->Matches(args))
9720 return spec;
9721 }
9722
9723 return nullptr;
9724 }
9725
9726 // Performs the default action of this mock function on the given
9727 // arguments and returns the result. Asserts (or throws if
9728 // exceptions are enabled) with a helpful call descrption if there
9729 // is no valid return value. This method doesn't depend on the
9730 // mutable state of this object, and thus can be called concurrently
9731 // without locking.
9732 // L = *
9733 Result PerformDefaultAction(ArgumentTuple&& args,
9734 const std::string& call_description) const {
9735 const OnCallSpec<F>* const spec =
9736 this->FindOnCallSpec(args);
9737 if (spec != nullptr) {
9738 return spec->GetAction().Perform(std::move(args));
9739 }
9740 const std::string message =
9741 call_description +
9742 "\n The mock function has no default action "
9743 "set, and its return type has no default value set.";
9744 #if GTEST_HAS_EXCEPTIONS
9745 if (!DefaultValue<Result>::Exists()) {
9746 throw std::runtime_error(message);
9747 }
9748 #else
9749 Assert(DefaultValue<Result>::Exists(), "", -1, message);
9750 #endif
9751 return DefaultValue<Result>::Get();
9752 }
9753
9754 // Performs the default action with the given arguments and returns
9755 // the action's result. The call description string will be used in
9756 // the error message to describe the call in the case the default
9757 // action fails. The caller is responsible for deleting the result.
9758 // L = *
9759 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
9760 void* untyped_args, // must point to an ArgumentTuple
9761 const std::string& call_description) const override {
9762 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
9763 return ResultHolder::PerformDefaultAction(this, std::move(*args),
9764 call_description);
9765 }
9766
9767 // Performs the given action with the given arguments and returns
9768 // the action's result. The caller is responsible for deleting the
9769 // result.
9770 // L = *
9771 UntypedActionResultHolderBase* UntypedPerformAction(
9772 const void* untyped_action, void* untyped_args) const override {
9773 // Make a copy of the action before performing it, in case the
9774 // action deletes the mock object (and thus deletes itself).
9775 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
9776 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
9777 return ResultHolder::PerformAction(action, std::move(*args));
9778 }
9779
9780 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
9781 // clears the ON_CALL()s set on this mock function.
9782 void ClearDefaultActionsLocked() override
9783 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9784 g_gmock_mutex.AssertHeld();
9785
9786 // Deleting our default actions may trigger other mock objects to be
9787 // deleted, for example if an action contains a reference counted smart
9788 // pointer to that mock object, and that is the last reference. So if we
9789 // delete our actions within the context of the global mutex we may deadlock
9790 // when this method is called again. Instead, make a copy of the set of
9791 // actions to delete, clear our set within the mutex, and then delete the
9792 // actions outside of the mutex.
9793 UntypedOnCallSpecs specs_to_delete;
9794 untyped_on_call_specs_.swap(specs_to_delete);
9795
9796 g_gmock_mutex.Unlock();
9797 for (UntypedOnCallSpecs::const_iterator it =
9798 specs_to_delete.begin();
9799 it != specs_to_delete.end(); ++it) {
9800 delete static_cast<const OnCallSpec<F>*>(*it);
9801 }
9802
9803 // Lock the mutex again, since the caller expects it to be locked when we
9804 // return.
9805 g_gmock_mutex.Lock();
9806 }
9807
9808 // Returns the result of invoking this mock function with the given
9809 // arguments. This function can be safely called from multiple
9810 // threads concurrently.
9811 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9812 ArgumentTuple tuple(std::forward<Args>(args)...);
9813 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
9814 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
9815 return holder->Unwrap();
9816 }
9817
9818 MockSpec<F> With(Matcher<Args>... m) {
9819 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
9820 }
9821
9822 protected:
9823 template <typename Function>
9824 friend class MockSpec;
9825
9826 typedef ActionResultHolder<Result> ResultHolder;
9827
9828 // Adds and returns a default action spec for this mock function.
9829 OnCallSpec<F>& AddNewOnCallSpec(
9830 const char* file, int line,
9831 const ArgumentMatcherTuple& m)
9832 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9833 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
9834 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
9835 untyped_on_call_specs_.push_back(on_call_spec);
9836 return *on_call_spec;
9837 }
9838
9839 // Adds and returns an expectation spec for this mock function.
9840 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
9841 const std::string& source_text,
9842 const ArgumentMatcherTuple& m)
9843 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9844 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
9845 TypedExpectation<F>* const expectation =
9846 new TypedExpectation<F>(this, file, line, source_text, m);
9847 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
9848 // See the definition of untyped_expectations_ for why access to
9849 // it is unprotected here.
9850 untyped_expectations_.push_back(untyped_expectation);
9851
9852 // Adds this expectation into the implicit sequence if there is one.
9853 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
9854 if (implicit_sequence != nullptr) {
9855 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
9856 }
9857
9858 return *expectation;
9859 }
9860
9861 private:
9862 template <typename Func> friend class TypedExpectation;
9863
9864 // Some utilities needed for implementing UntypedInvokeWith().
9865
9866 // Describes what default action will be performed for the given
9867 // arguments.
9868 // L = *
9869 void DescribeDefaultActionTo(const ArgumentTuple& args,
9870 ::std::ostream* os) const {
9871 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
9872
9873 if (spec == nullptr) {
9874 *os << (std::is_void<Result>::value ? "returning directly.\n"
9875 : "returning default value.\n");
9876 } else {
9877 *os << "taking default action specified at:\n"
9878 << FormatFileLocation(spec->file(), spec->line()) << "\n";
9879 }
9880 }
9881
9882 // Writes a message that the call is uninteresting (i.e. neither
9883 // explicitly expected nor explicitly unexpected) to the given
9884 // ostream.
9885 void UntypedDescribeUninterestingCall(const void* untyped_args,
9886 ::std::ostream* os) const override
9887 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9888 const ArgumentTuple& args =
9889 *static_cast<const ArgumentTuple*>(untyped_args);
9890 *os << "Uninteresting mock function call - ";
9891 DescribeDefaultActionTo(args, os);
9892 *os << " Function call: " << Name();
9893 UniversalPrint(args, os);
9894 }
9895
9896 // Returns the expectation that matches the given function arguments
9897 // (or NULL is there's no match); when a match is found,
9898 // untyped_action is set to point to the action that should be
9899 // performed (or NULL if the action is "do default"), and
9900 // is_excessive is modified to indicate whether the call exceeds the
9901 // expected number.
9902 //
9903 // Critical section: We must find the matching expectation and the
9904 // corresponding action that needs to be taken in an ATOMIC
9905 // transaction. Otherwise another thread may call this mock
9906 // method in the middle and mess up the state.
9907 //
9908 // However, performing the action has to be left out of the critical
9909 // section. The reason is that we have no control on what the
9910 // action does (it can invoke an arbitrary user function or even a
9911 // mock function) and excessive locking could cause a dead lock.
9912 const ExpectationBase* UntypedFindMatchingExpectation(
9913 const void* untyped_args, const void** untyped_action, bool* is_excessive,
9914 ::std::ostream* what, ::std::ostream* why) override
9915 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9916 const ArgumentTuple& args =
9917 *static_cast<const ArgumentTuple*>(untyped_args);
9918 MutexLock l(&g_gmock_mutex);
9919 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
9920 if (exp == nullptr) { // A match wasn't found.
9921 this->FormatUnexpectedCallMessageLocked(args, what, why);
9922 return nullptr;
9923 }
9924
9925 // This line must be done before calling GetActionForArguments(),
9926 // which will increment the call count for *exp and thus affect
9927 // its saturation status.
9928 *is_excessive = exp->IsSaturated();
9929 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
9930 if (action != nullptr && action->IsDoDefault())
9931 action = nullptr; // Normalize "do default" to NULL.
9932 *untyped_action = action;
9933 return exp;
9934 }
9935
9936 // Prints the given function arguments to the ostream.
9937 void UntypedPrintArgs(const void* untyped_args,
9938 ::std::ostream* os) const override {
9939 const ArgumentTuple& args =
9940 *static_cast<const ArgumentTuple*>(untyped_args);
9941 UniversalPrint(args, os);
9942 }
9943
9944 // Returns the expectation that matches the arguments, or NULL if no
9945 // expectation matches them.
9946 TypedExpectation<F>* FindMatchingExpectationLocked(
9947 const ArgumentTuple& args) const
9948 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9949 g_gmock_mutex.AssertHeld();
9950 // See the definition of untyped_expectations_ for why access to
9951 // it is unprotected here.
9952 for (typename UntypedExpectations::const_reverse_iterator it =
9953 untyped_expectations_.rbegin();
9954 it != untyped_expectations_.rend(); ++it) {
9955 TypedExpectation<F>* const exp =
9956 static_cast<TypedExpectation<F>*>(it->get());
9957 if (exp->ShouldHandleArguments(args)) {
9958 return exp;
9959 }
9960 }
9961 return nullptr;
9962 }
9963
9964 // Returns a message that the arguments don't match any expectation.
9965 void FormatUnexpectedCallMessageLocked(
9966 const ArgumentTuple& args,
9967 ::std::ostream* os,
9968 ::std::ostream* why) const
9969 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9970 g_gmock_mutex.AssertHeld();
9971 *os << "\nUnexpected mock function call - ";
9972 DescribeDefaultActionTo(args, os);
9973 PrintTriedExpectationsLocked(args, why);
9974 }
9975
9976 // Prints a list of expectations that have been tried against the
9977 // current mock function call.
9978 void PrintTriedExpectationsLocked(
9979 const ArgumentTuple& args,
9980 ::std::ostream* why) const
9981 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9982 g_gmock_mutex.AssertHeld();
9983 const size_t count = untyped_expectations_.size();
9984 *why << "Google Mock tried the following " << count << " "
9985 << (count == 1 ? "expectation, but it didn't match" :
9986 "expectations, but none matched")
9987 << ":\n";
9988 for (size_t i = 0; i < count; i++) {
9989 TypedExpectation<F>* const expectation =
9990 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
9991 *why << "\n";
9992 expectation->DescribeLocationTo(why);
9993 if (count > 1) {
9994 *why << "tried expectation #" << i << ": ";
9995 }
9996 *why << expectation->source_text() << "...\n";
9997 expectation->ExplainMatchResultTo(args, why);
9998 expectation->DescribeCallCountTo(why);
9999 }
10000 }
10001 }; // class FunctionMocker
10002
10003 // Reports an uninteresting call (whose description is in msg) in the
10004 // manner specified by 'reaction'.
10005 void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
10006
10007 } // namespace internal
10008
10009 namespace internal {
10010
10011 template <typename F>
10012 class MockFunction;
10013
10014 template <typename R, typename... Args>
10015 class MockFunction<R(Args...)> {
10016 public:
10017 MockFunction(const MockFunction&) = delete;
10018 MockFunction& operator=(const MockFunction&) = delete;
10019
10020 std::function<R(Args...)> AsStdFunction() {
10021 return [this](Args... args) -> R {
10022 return this->Call(std::forward<Args>(args)...);
10023 };
10024 }
10025
10026 // Implementation detail: the expansion of the MOCK_METHOD macro.
10027 R Call(Args... args) {
10028 mock_.SetOwnerAndName(this, "Call");
10029 return mock_.Invoke(std::forward<Args>(args)...);
10030 }
10031
10032 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
10033 mock_.RegisterOwner(this);
10034 return mock_.With(std::move(m)...);
10035 }
10036
10037 MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
10038 return this->gmock_Call(::testing::A<Args>()...);
10039 }
10040
10041 protected:
10042 MockFunction() = default;
10043 ~MockFunction() = default;
10044
10045 private:
10046 FunctionMocker<R(Args...)> mock_;
10047 };
10048
10049 /*
10050 The SignatureOf<F> struct is a meta-function returning function signature
10051 corresponding to the provided F argument.
10052
10053 It makes use of MockFunction easier by allowing it to accept more F arguments
10054 than just function signatures.
10055
10056 Specializations provided here cover only a signature type itself and
10057 std::function. However, if need be it can be easily extended to cover also other
10058 types (like for example boost::function).
10059 */
10060
10061 template <typename F>
10062 struct SignatureOf;
10063
10064 template <typename R, typename... Args>
10065 struct SignatureOf<R(Args...)> {
10066 using type = R(Args...);
10067 };
10068
10069 template <typename F>
10070 struct SignatureOf<std::function<F>> : SignatureOf<F> {};
10071
10072 template <typename F>
10073 using SignatureOfT = typename SignatureOf<F>::type;
10074
10075 } // namespace internal
10076
10077 // A MockFunction<F> type has one mock method whose type is
10078 // internal::SignatureOfT<F>. It is useful when you just want your
10079 // test code to emit some messages and have Google Mock verify the
10080 // right messages are sent (and perhaps at the right times). For
10081 // example, if you are exercising code:
10082 //
10083 // Foo(1);
10084 // Foo(2);
10085 // Foo(3);
10086 //
10087 // and want to verify that Foo(1) and Foo(3) both invoke
10088 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
10089 //
10090 // TEST(FooTest, InvokesBarCorrectly) {
10091 // MyMock mock;
10092 // MockFunction<void(string check_point_name)> check;
10093 // {
10094 // InSequence s;
10095 //
10096 // EXPECT_CALL(mock, Bar("a"));
10097 // EXPECT_CALL(check, Call("1"));
10098 // EXPECT_CALL(check, Call("2"));
10099 // EXPECT_CALL(mock, Bar("a"));
10100 // }
10101 // Foo(1);
10102 // check.Call("1");
10103 // Foo(2);
10104 // check.Call("2");
10105 // Foo(3);
10106 // }
10107 //
10108 // The expectation spec says that the first Bar("a") must happen
10109 // before check point "1", the second Bar("a") must happen after check
10110 // point "2", and nothing should happen between the two check
10111 // points. The explicit check points make it easy to tell which
10112 // Bar("a") is called by which call to Foo().
10113 //
10114 // MockFunction<F> can also be used to exercise code that accepts
10115 // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
10116 // AsStdFunction() method to create std::function proxy forwarding to
10117 // original object's Call. Example:
10118 //
10119 // TEST(FooTest, RunsCallbackWithBarArgument) {
10120 // MockFunction<int(string)> callback;
10121 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
10122 // Foo(callback.AsStdFunction());
10123 // }
10124 //
10125 // The internal::SignatureOfT<F> indirection allows to use other types
10126 // than just function signature type. This is typically useful when
10127 // providing a mock for a predefined std::function type. Example:
10128 //
10129 // using FilterPredicate = std::function<bool(string)>;
10130 // void MyFilterAlgorithm(FilterPredicate predicate);
10131 //
10132 // TEST(FooTest, FilterPredicateAlwaysAccepts) {
10133 // MockFunction<FilterPredicate> predicateMock;
10134 // EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
10135 // MyFilterAlgorithm(predicateMock.AsStdFunction());
10136 // }
10137 template <typename F>
10138 class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
10139 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
10140
10141 public:
10142 using Base::Base;
10143 };
10144
10145 // The style guide prohibits "using" statements in a namespace scope
10146 // inside a header file. However, the MockSpec class template is
10147 // meant to be defined in the ::testing namespace. The following line
10148 // is just a trick for working around a bug in MSVC 8.0, which cannot
10149 // handle it if we define MockSpec in ::testing.
10150 using internal::MockSpec;
10151
10152 // Const(x) is a convenient function for obtaining a const reference
10153 // to x. This is useful for setting expectations on an overloaded
10154 // const mock method, e.g.
10155 //
10156 // class MockFoo : public FooInterface {
10157 // public:
10158 // MOCK_METHOD0(Bar, int());
10159 // MOCK_CONST_METHOD0(Bar, int&());
10160 // };
10161 //
10162 // MockFoo foo;
10163 // // Expects a call to non-const MockFoo::Bar().
10164 // EXPECT_CALL(foo, Bar());
10165 // // Expects a call to const MockFoo::Bar().
10166 // EXPECT_CALL(Const(foo), Bar());
10167 template <typename T>
10168 inline const T& Const(const T& x) { return x; }
10169
10170 // Constructs an Expectation object that references and co-owns exp.
10171 inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
10172 : expectation_base_(exp.GetHandle().expectation_base()) {}
10173
10174 } // namespace testing
10175
10176 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
10177
10178 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
10179 // required to avoid compile errors when the name of the method used in call is
10180 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
10181 // tests in internal/gmock-spec-builders_test.cc for more details.
10182 //
10183 // This macro supports statements both with and without parameter matchers. If
10184 // the parameter list is omitted, gMock will accept any parameters, which allows
10185 // tests to be written that don't need to encode the number of method
10186 // parameter. This technique may only be used for non-overloaded methods.
10187 //
10188 // // These are the same:
10189 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
10190 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
10191 //
10192 // // As are these:
10193 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
10194 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
10195 //
10196 // // Can also specify args if you want, of course:
10197 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
10198 //
10199 // // Overloads work as long as you specify parameters:
10200 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
10201 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
10202 //
10203 // // Oops! Which overload did you want?
10204 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
10205 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
10206 //
10207 // How this works: The mock class uses two overloads of the gmock_Method
10208 // expectation setter method plus an operator() overload on the MockSpec object.
10209 // In the matcher list form, the macro expands to:
10210 //
10211 // // This statement:
10212 // ON_CALL(mock, TwoArgsMethod(_, 45))...
10213 //
10214 // // ...expands to:
10215 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
10216 // |-------------v---------------||------------v-------------|
10217 // invokes first overload swallowed by operator()
10218 //
10219 // // ...which is essentially:
10220 // mock.gmock_TwoArgsMethod(_, 45)...
10221 //
10222 // Whereas the form without a matcher list:
10223 //
10224 // // This statement:
10225 // ON_CALL(mock, TwoArgsMethod)...
10226 //
10227 // // ...expands to:
10228 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
10229 // |-----------------------v--------------------------|
10230 // invokes second overload
10231 //
10232 // // ...which is essentially:
10233 // mock.gmock_TwoArgsMethod(_, _)...
10234 //
10235 // The WithoutMatchers() argument is used to disambiguate overloads and to
10236 // block the caller from accidentally invoking the second overload directly. The
10237 // second argument is an internal type derived from the method signature. The
10238 // failure to disambiguate two overloads of this method in the ON_CALL statement
10239 // is how we block callers from setting expectations on overloaded methods.
10240 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
10241 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
10242 nullptr) \
10243 .Setter(__FILE__, __LINE__, #mock_expr, #call)
10244
10245 #define ON_CALL(obj, call) \
10246 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
10247
10248 #define EXPECT_CALL(obj, call) \
10249 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
10250
10251 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
10252
10253 namespace testing {
10254 namespace internal {
10255 template <typename T>
10256 using identity_t = T;
10257
10258 template <typename Pattern>
10259 struct ThisRefAdjuster {
10260 template <typename T>
10261 using AdjustT = typename std::conditional<
10262 std::is_const<typename std::remove_reference<Pattern>::type>::value,
10263 typename std::conditional<std::is_lvalue_reference<Pattern>::value,
10264 const T&, const T&&>::type,
10265 typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
10266 T&&>::type>::type;
10267
10268 template <typename MockType>
10269 static AdjustT<MockType> Adjust(const MockType& mock) {
10270 return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
10271 }
10272 };
10273
10274 } // namespace internal
10275
10276 // The style guide prohibits "using" statements in a namespace scope
10277 // inside a header file. However, the FunctionMocker class template
10278 // is meant to be defined in the ::testing namespace. The following
10279 // line is just a trick for working around a bug in MSVC 8.0, which
10280 // cannot handle it if we define FunctionMocker in ::testing.
10281 using internal::FunctionMocker;
10282 } // namespace testing
10283
10284 #define MOCK_METHOD(...) \
10285 GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
10286
10287 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
10288 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10289
10290 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \
10291 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10292
10293 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
10294 GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
10295
10296 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
10297 GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
10298 GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
10299 GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
10300 GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
10301 GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
10302 GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
10303 GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
10304 GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
10305 GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
10306 GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
10307 (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
10308
10309 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
10310 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10311
10312 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \
10313 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10314
10315 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \
10316 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10317
10318 #define GMOCK_INTERNAL_WRONG_ARITY(...) \
10319 static_assert( \
10320 false, \
10321 "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \
10322 "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \
10323 "enclosed in parentheses. If _Ret is a type with unprotected commas, " \
10324 "it must also be enclosed in parentheses.")
10325
10326 #define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \
10327 static_assert( \
10328 GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \
10329 GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.")
10330
10331 #define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \
10332 static_assert( \
10333 std::is_function<__VA_ARGS__>::value, \
10334 "Signature must be a function type, maybe return type contains " \
10335 "unprotected comma."); \
10336 static_assert( \
10337 ::testing::tuple_size<typename ::testing::internal::Function< \
10338 __VA_ARGS__>::ArgumentTuple>::value == _N, \
10339 "This method does not take " GMOCK_PP_STRINGIZE( \
10340 _N) " arguments. Parenthesize all types with unprotected commas.")
10341
10342 #define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
10343 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
10344
10345 #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
10346 _Override, _Final, _NoexceptSpec, \
10347 _CallType, _RefSpec, _Signature) \
10348 typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
10349 _Signature)>::Result \
10350 GMOCK_INTERNAL_EXPAND(_CallType) \
10351 _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
10352 GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
10353 GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
10354 GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10355 .SetOwnerAndName(this, #_MethodName); \
10356 return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10357 .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \
10358 } \
10359 ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
10360 GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
10361 GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
10362 GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
10363 return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10364 .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
10365 } \
10366 ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
10367 const ::testing::internal::WithoutMatchers&, \
10368 GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
10369 GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
10370 return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
10371 _Constness, const, ) int _RefSpec>::Adjust(*this) \
10372 .gmock_##_MethodName(GMOCK_PP_REPEAT( \
10373 GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
10374 } \
10375 mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
10376 GMOCK_MOCKER_(_N, _Constness, _MethodName)
10377
10378 #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
10379
10380 // Five Valid modifiers.
10381 #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
10382 GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
10383
10384 #define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \
10385 GMOCK_PP_HAS_COMMA( \
10386 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple))
10387
10388 #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
10389 GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
10390
10391 #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \
10392 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)
10393
10394 #define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \
10395 GMOCK_PP_IF( \
10396 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
10397 _elem, )
10398
10399 #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
10400 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
10401
10402 #define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
10403 GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
10404 GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
10405
10406 #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
10407 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
10408
10409 #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
10410 static_assert( \
10411 (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \
10412 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
10413 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
10414 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
10415 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \
10416 GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
10417 GMOCK_PP_STRINGIZE( \
10418 _elem) " cannot be recognized as a valid specification modifier.");
10419
10420 // Modifiers implementation.
10421 #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
10422 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem)
10423
10424 #define GMOCK_INTERNAL_DETECT_CONST_I_const ,
10425
10426 #define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \
10427 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem)
10428
10429 #define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override ,
10430
10431 #define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \
10432 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem)
10433
10434 #define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
10435
10436 #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
10437 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
10438
10439 #define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
10440
10441 #define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \
10442 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
10443
10444 #define GMOCK_INTERNAL_DETECT_REF_I_ref ,
10445
10446 #define GMOCK_INTERNAL_UNPACK_ref(x) x
10447
10448 #define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
10449 GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
10450 GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
10451 (_elem)
10452
10453 // TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
10454 // GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
10455 // maybe they can be simplified somehow.
10456 #define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
10457 GMOCK_INTERNAL_IS_CALLTYPE_I( \
10458 GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
10459 #define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
10460
10461 #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \
10462 GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
10463 GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
10464 #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
10465 GMOCK_PP_IDENTITY _arg
10466
10467 #define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
10468
10469 // Note: The use of `identity_t` here allows _Ret to represent return types that
10470 // would normally need to be specified in a different way. For example, a method
10471 // returning a function pointer must be written as
10472 //
10473 // fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)
10474 //
10475 // But we only support placing the return type at the beginning. To handle this,
10476 // we wrap all calls in identity_t, so that a declaration will be expanded to
10477 //
10478 // identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)
10479 //
10480 // This allows us to work around the syntactic oddities of function/method
10481 // types.
10482 #define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
10483 ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \
10484 GMOCK_PP_REMOVE_PARENS, \
10485 GMOCK_PP_IDENTITY)(_Ret)>( \
10486 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
10487
10488 #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
10489 GMOCK_PP_COMMA_IF(_i) \
10490 GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \
10491 GMOCK_PP_IDENTITY) \
10492 (_elem)
10493
10494 #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
10495 GMOCK_PP_COMMA_IF(_i) \
10496 GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
10497 gmock_a##_i
10498
10499 #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
10500 GMOCK_PP_COMMA_IF(_i) \
10501 ::std::forward<GMOCK_INTERNAL_ARG_O( \
10502 _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
10503
10504 #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
10505 GMOCK_PP_COMMA_IF(_i) \
10506 GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
10507 gmock_a##_i
10508
10509 #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
10510 GMOCK_PP_COMMA_IF(_i) \
10511 gmock_a##_i
10512
10513 #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
10514 GMOCK_PP_COMMA_IF(_i) \
10515 ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
10516
10517 #define GMOCK_INTERNAL_ARG_O(_i, ...) \
10518 typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
10519
10520 #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
10521 const ::testing::Matcher<typename ::testing::internal::Function< \
10522 __VA_ARGS__>::template Arg<_i>::type>&
10523
10524 #define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
10525 #define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
10526 #define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
10527 #define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
10528 #define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
10529 #define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
10530 #define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
10531 #define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
10532 #define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
10533 #define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
10534 #define MOCK_METHOD10(m, ...) \
10535 GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
10536
10537 #define MOCK_CONST_METHOD0(m, ...) \
10538 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
10539 #define MOCK_CONST_METHOD1(m, ...) \
10540 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
10541 #define MOCK_CONST_METHOD2(m, ...) \
10542 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
10543 #define MOCK_CONST_METHOD3(m, ...) \
10544 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
10545 #define MOCK_CONST_METHOD4(m, ...) \
10546 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
10547 #define MOCK_CONST_METHOD5(m, ...) \
10548 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
10549 #define MOCK_CONST_METHOD6(m, ...) \
10550 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
10551 #define MOCK_CONST_METHOD7(m, ...) \
10552 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
10553 #define MOCK_CONST_METHOD8(m, ...) \
10554 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
10555 #define MOCK_CONST_METHOD9(m, ...) \
10556 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
10557 #define MOCK_CONST_METHOD10(m, ...) \
10558 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
10559
10560 #define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
10561 #define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
10562 #define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
10563 #define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
10564 #define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
10565 #define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
10566 #define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
10567 #define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
10568 #define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
10569 #define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
10570 #define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
10571
10572 #define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
10573 #define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
10574 #define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
10575 #define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
10576 #define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
10577 #define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
10578 #define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
10579 #define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
10580 #define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
10581 #define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
10582 #define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
10583
10584 #define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
10585 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
10586 #define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
10587 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
10588 #define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
10589 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
10590 #define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
10591 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
10592 #define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
10593 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
10594 #define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
10595 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
10596 #define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
10597 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
10598 #define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
10599 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
10600 #define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
10601 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
10602 #define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
10603 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
10604 #define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
10605 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
10606
10607 #define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
10608 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
10609 #define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
10610 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
10611 #define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
10612 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
10613 #define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
10614 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
10615 #define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
10616 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
10617 #define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
10618 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
10619 #define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
10620 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
10621 #define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
10622 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
10623 #define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
10624 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
10625 #define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
10626 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
10627 #define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
10628 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
10629
10630 #define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
10631 MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10632 #define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
10633 MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10634 #define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
10635 MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10636 #define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
10637 MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10638 #define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
10639 MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10640 #define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
10641 MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10642 #define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
10643 MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10644 #define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
10645 MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10646 #define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
10647 MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10648 #define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
10649 MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10650 #define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
10651 MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10652
10653 #define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
10654 MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10655 #define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
10656 MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10657 #define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
10658 MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10659 #define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
10660 MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10661 #define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
10662 MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10663 #define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
10664 MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10665 #define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
10666 MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10667 #define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
10668 MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10669 #define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
10670 MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10671 #define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
10672 MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10673 #define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
10674 MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10675
10676 #define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
10677 GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
10678 args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
10679 GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
10680 args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
10681 (::testing::internal::identity_t<__VA_ARGS__>))
10682
10683 #define GMOCK_MOCKER_(arity, constness, Method) \
10684 GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
10685
10686 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
10687 // Copyright 2007, Google Inc.
10688 // All rights reserved.
10689 //
10690 // Redistribution and use in source and binary forms, with or without
10691 // modification, are permitted provided that the following conditions are
10692 // met:
10693 //
10694 // * Redistributions of source code must retain the above copyright
10695 // notice, this list of conditions and the following disclaimer.
10696 // * Redistributions in binary form must reproduce the above
10697 // copyright notice, this list of conditions and the following disclaimer
10698 // in the documentation and/or other materials provided with the
10699 // distribution.
10700 // * Neither the name of Google Inc. nor the names of its
10701 // contributors may be used to endorse or promote products derived from
10702 // this software without specific prior written permission.
10703 //
10704 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10705 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10706 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10707 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10708 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10709 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10710 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10711 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10712 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10713 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10714 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10715
10716
10717 // Google Mock - a framework for writing C++ mock classes.
10718 //
10719 // This file implements some commonly used variadic actions.
10720
10721 // GOOGLETEST_CM0002 DO NOT DELETE
10722
10723 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
10724 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
10725
10726 #include <memory>
10727 #include <utility>
10728
10729
10730 // Include any custom callback actions added by the local installation.
10731 // GOOGLETEST_CM0002 DO NOT DELETE
10732
10733 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10734 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10735
10736 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10737
10738 // Sometimes you want to give an action explicit template parameters
10739 // that cannot be inferred from its value parameters. ACTION() and
10740 // ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
10741 // and can be viewed as an extension to ACTION() and ACTION_P*().
10742 //
10743 // The syntax:
10744 //
10745 // ACTION_TEMPLATE(ActionName,
10746 // HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
10747 // AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
10748 //
10749 // defines an action template that takes m explicit template
10750 // parameters and n value parameters. name_i is the name of the i-th
10751 // template parameter, and kind_i specifies whether it's a typename,
10752 // an integral constant, or a template. p_i is the name of the i-th
10753 // value parameter.
10754 //
10755 // Example:
10756 //
10757 // // DuplicateArg<k, T>(output) converts the k-th argument of the mock
10758 // // function to type T and copies it to *output.
10759 // ACTION_TEMPLATE(DuplicateArg,
10760 // HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
10761 // AND_1_VALUE_PARAMS(output)) {
10762 // *output = T(::std::get<k>(args));
10763 // }
10764 // ...
10765 // int n;
10766 // EXPECT_CALL(mock, Foo(_, _))
10767 // .WillOnce(DuplicateArg<1, unsigned char>(&n));
10768 //
10769 // To create an instance of an action template, write:
10770 //
10771 // ActionName<t1, ..., t_m>(v1, ..., v_n)
10772 //
10773 // where the ts are the template arguments and the vs are the value
10774 // arguments. The value argument types are inferred by the compiler.
10775 // If you want to explicitly specify the value argument types, you can
10776 // provide additional template arguments:
10777 //
10778 // ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
10779 //
10780 // where u_i is the desired type of v_i.
10781 //
10782 // ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
10783 // number of value parameters, but not on the number of template
10784 // parameters. Without the restriction, the meaning of the following
10785 // is unclear:
10786 //
10787 // OverloadedAction<int, bool>(x);
10788 //
10789 // Are we using a single-template-parameter action where 'bool' refers
10790 // to the type of x, or are we using a two-template-parameter action
10791 // where the compiler is asked to infer the type of x?
10792 //
10793 // Implementation notes:
10794 //
10795 // GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
10796 // GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
10797 // implementing ACTION_TEMPLATE. The main trick we use is to create
10798 // new macro invocations when expanding a macro. For example, we have
10799 //
10800 // #define ACTION_TEMPLATE(name, template_params, value_params)
10801 // ... GMOCK_INTERNAL_DECL_##template_params ...
10802 //
10803 // which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
10804 // to expand to
10805 //
10806 // ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
10807 //
10808 // Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
10809 // preprocessor will continue to expand it to
10810 //
10811 // ... typename T ...
10812 //
10813 // This technique conforms to the C++ standard and is portable. It
10814 // allows us to implement action templates using O(N) code, where N is
10815 // the maximum number of template/value parameters supported. Without
10816 // using it, we'd have to devote O(N^2) amount of code to implement all
10817 // combinations of m and n.
10818
10819 // Declares the template parameters.
10820 #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
10821 #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
10822 name1) kind0 name0, kind1 name1
10823 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10824 kind2, name2) kind0 name0, kind1 name1, kind2 name2
10825 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10826 kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
10827 kind3 name3
10828 #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10829 kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
10830 kind2 name2, kind3 name3, kind4 name4
10831 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10832 kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
10833 kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
10834 #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10835 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10836 name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
10837 kind5 name5, kind6 name6
10838 #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10839 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10840 kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
10841 kind4 name4, kind5 name5, kind6 name6, kind7 name7
10842 #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10843 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10844 kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
10845 kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
10846 kind8 name8
10847 #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
10848 name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10849 name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
10850 kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
10851 kind6 name6, kind7 name7, kind8 name8, kind9 name9
10852
10853 // Lists the template parameters.
10854 #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
10855 #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
10856 name1) name0, name1
10857 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10858 kind2, name2) name0, name1, name2
10859 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10860 kind2, name2, kind3, name3) name0, name1, name2, name3
10861 #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10862 kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
10863 name4
10864 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10865 kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
10866 name2, name3, name4, name5
10867 #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10868 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10869 name6) name0, name1, name2, name3, name4, name5, name6
10870 #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10871 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10872 kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
10873 #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10874 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10875 kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
10876 name6, name7, name8
10877 #define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
10878 name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10879 name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
10880 name3, name4, name5, name6, name7, name8, name9
10881
10882 // Declares the types of value parameters.
10883 #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
10884 #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
10885 #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
10886 typename p0##_type, typename p1##_type
10887 #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
10888 typename p0##_type, typename p1##_type, typename p2##_type
10889 #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
10890 typename p0##_type, typename p1##_type, typename p2##_type, \
10891 typename p3##_type
10892 #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
10893 typename p0##_type, typename p1##_type, typename p2##_type, \
10894 typename p3##_type, typename p4##_type
10895 #define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
10896 typename p0##_type, typename p1##_type, typename p2##_type, \
10897 typename p3##_type, typename p4##_type, typename p5##_type
10898 #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10899 p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
10900 typename p3##_type, typename p4##_type, typename p5##_type, \
10901 typename p6##_type
10902 #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10903 p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
10904 typename p3##_type, typename p4##_type, typename p5##_type, \
10905 typename p6##_type, typename p7##_type
10906 #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10907 p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
10908 typename p3##_type, typename p4##_type, typename p5##_type, \
10909 typename p6##_type, typename p7##_type, typename p8##_type
10910 #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10911 p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
10912 typename p2##_type, typename p3##_type, typename p4##_type, \
10913 typename p5##_type, typename p6##_type, typename p7##_type, \
10914 typename p8##_type, typename p9##_type
10915
10916 // Initializes the value parameters.
10917 #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
10918 ()
10919 #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
10920 (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
10921 #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
10922 (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
10923 p1(::std::move(gmock_p1))
10924 #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
10925 (p0##_type gmock_p0, p1##_type gmock_p1, \
10926 p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
10927 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
10928 #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
10929 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10930 p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
10931 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10932 p3(::std::move(gmock_p3))
10933 #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
10934 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10935 p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
10936 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10937 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
10938 #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
10939 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10940 p3##_type gmock_p3, p4##_type gmock_p4, \
10941 p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
10942 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10943 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10944 p5(::std::move(gmock_p5))
10945 #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
10946 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10947 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10948 p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
10949 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10950 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10951 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
10952 #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
10953 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10954 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10955 p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
10956 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10957 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10958 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10959 p7(::std::move(gmock_p7))
10960 #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
10961 p7, p8)\
10962 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10963 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10964 p6##_type gmock_p6, p7##_type gmock_p7, \
10965 p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
10966 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10967 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10968 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10969 p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
10970 #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
10971 p7, p8, p9)\
10972 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10973 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10974 p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
10975 p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
10976 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10977 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10978 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10979 p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
10980 p9(::std::move(gmock_p9))
10981
10982 // Defines the copy constructor
10983 #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
10984 {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
10985 #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
10986 #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
10987 #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
10988 #define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;
10989 #define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;
10990 #define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;
10991 #define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;
10992 #define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;
10993 #define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;
10994 #define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default;
10995
10996 // Declares the fields for storing the value parameters.
10997 #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
10998 #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
10999 #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
11000 p1##_type p1;
11001 #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
11002 p1##_type p1; p2##_type p2;
11003 #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
11004 p1##_type p1; p2##_type p2; p3##_type p3;
11005 #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
11006 p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
11007 #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
11008 p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11009 p5##_type p5;
11010 #define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11011 p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11012 p5##_type p5; p6##_type p6;
11013 #define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11014 p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11015 p5##_type p5; p6##_type p6; p7##_type p7;
11016 #define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11017 p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
11018 p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
11019 #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11020 p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
11021 p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
11022 p9##_type p9;
11023
11024 // Lists the value parameters.
11025 #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
11026 #define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
11027 #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
11028 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
11029 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
11030 #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
11031 p2, p3, p4
11032 #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
11033 p1, p2, p3, p4, p5
11034 #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11035 p6) p0, p1, p2, p3, p4, p5, p6
11036 #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11037 p7) p0, p1, p2, p3, p4, p5, p6, p7
11038 #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11039 p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
11040 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11041 p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
11042
11043 // Lists the value parameter types.
11044 #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
11045 #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
11046 #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
11047 p1##_type
11048 #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
11049 p1##_type, p2##_type
11050 #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
11051 p0##_type, p1##_type, p2##_type, p3##_type
11052 #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
11053 p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
11054 #define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
11055 p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
11056 #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11057 p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
11058 p6##_type
11059 #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11060 p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11061 p5##_type, p6##_type, p7##_type
11062 #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11063 p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11064 p5##_type, p6##_type, p7##_type, p8##_type
11065 #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11066 p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11067 p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
11068
11069 // Declares the value parameters.
11070 #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
11071 #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
11072 #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
11073 p1##_type p1
11074 #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
11075 p1##_type p1, p2##_type p2
11076 #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
11077 p1##_type p1, p2##_type p2, p3##_type p3
11078 #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
11079 p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
11080 #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
11081 p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11082 p5##_type p5
11083 #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11084 p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11085 p5##_type p5, p6##_type p6
11086 #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11087 p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11088 p5##_type p5, p6##_type p6, p7##_type p7
11089 #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11090 p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
11091 p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
11092 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11093 p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
11094 p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
11095 p9##_type p9
11096
11097 // The suffix of the class template implementing the action template.
11098 #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
11099 #define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
11100 #define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
11101 #define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
11102 #define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
11103 #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
11104 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
11105 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
11106 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11107 p7) P8
11108 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11109 p7, p8) P9
11110 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11111 p7, p8, p9) P10
11112
11113 // The name of the class template implementing the action template.
11114 #define GMOCK_ACTION_CLASS_(name, value_params)\
11115 GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
11116
11117 #define ACTION_TEMPLATE(name, template_params, value_params) \
11118 template <GMOCK_INTERNAL_DECL_##template_params \
11119 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11120 class GMOCK_ACTION_CLASS_(name, value_params) { \
11121 public: \
11122 explicit GMOCK_ACTION_CLASS_(name, value_params)( \
11123 GMOCK_INTERNAL_DECL_##value_params) \
11124 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11125 = default; , \
11126 : impl_(std::make_shared<gmock_Impl>( \
11127 GMOCK_INTERNAL_LIST_##value_params)) { }) \
11128 GMOCK_ACTION_CLASS_(name, value_params)( \
11129 const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
11130 GMOCK_INTERNAL_DEFN_COPY_##value_params \
11131 GMOCK_ACTION_CLASS_(name, value_params)( \
11132 GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \
11133 GMOCK_INTERNAL_DEFN_COPY_##value_params \
11134 template <typename F> \
11135 operator ::testing::Action<F>() const { \
11136 return GMOCK_PP_IF( \
11137 GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11138 (::testing::internal::MakeAction<F, gmock_Impl>()), \
11139 (::testing::internal::MakeAction<F>(impl_))); \
11140 } \
11141 private: \
11142 class gmock_Impl { \
11143 public: \
11144 explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \
11145 template <typename function_type, typename return_type, \
11146 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
11147 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
11148 GMOCK_INTERNAL_DEFN_##value_params \
11149 }; \
11150 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11151 , std::shared_ptr<const gmock_Impl> impl_;) \
11152 }; \
11153 template <GMOCK_INTERNAL_DECL_##template_params \
11154 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11155 GMOCK_ACTION_CLASS_(name, value_params)< \
11156 GMOCK_INTERNAL_LIST_##template_params \
11157 GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
11158 GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
11159 template <GMOCK_INTERNAL_DECL_##template_params \
11160 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11161 inline GMOCK_ACTION_CLASS_(name, value_params)< \
11162 GMOCK_INTERNAL_LIST_##template_params \
11163 GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
11164 GMOCK_INTERNAL_DECL_##value_params) { \
11165 return GMOCK_ACTION_CLASS_(name, value_params)< \
11166 GMOCK_INTERNAL_LIST_##template_params \
11167 GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
11168 GMOCK_INTERNAL_LIST_##value_params); \
11169 } \
11170 template <GMOCK_INTERNAL_DECL_##template_params \
11171 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11172 template <typename function_type, typename return_type, typename args_type, \
11173 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
11174 return_type GMOCK_ACTION_CLASS_(name, value_params)< \
11175 GMOCK_INTERNAL_LIST_##template_params \
11176 GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
11177 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
11178
11179 namespace testing {
11180
11181 // The ACTION*() macros trigger warning C4100 (unreferenced formal
11182 // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
11183 // the macro definition, as the warnings are generated when the macro
11184 // is expanded and macro expansion cannot contain #pragma. Therefore
11185 // we suppress them here.
11186 #ifdef _MSC_VER
11187 # pragma warning(push)
11188 # pragma warning(disable:4100)
11189 #endif
11190
11191 namespace internal {
11192
11193 // internal::InvokeArgument - a helper for InvokeArgument action.
11194 // The basic overloads are provided here for generic functors.
11195 // Overloads for other custom-callables are provided in the
11196 // internal/custom/gmock-generated-actions.h header.
11197 template <typename F, typename... Args>
11198 auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
11199 return f(args...);
11200 }
11201
11202 template <std::size_t index, typename... Params>
11203 struct InvokeArgumentAction {
11204 template <typename... Args>
11205 auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
11206 std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
11207 std::declval<const Params&>()...)) {
11208 internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
11209 std::forward<Args>(args)...);
11210 return params.Apply([&](const Params&... unpacked_params) {
11211 auto&& callable = args_tuple.template Get<index>();
11212 return internal::InvokeArgument(
11213 std::forward<decltype(callable)>(callable), unpacked_params...);
11214 });
11215 }
11216
11217 internal::FlatTuple<Params...> params;
11218 };
11219
11220 } // namespace internal
11221
11222 // The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
11223 // (0-based) argument, which must be a k-ary callable, of the mock
11224 // function, with arguments a1, a2, ..., a_k.
11225 //
11226 // Notes:
11227 //
11228 // 1. The arguments are passed by value by default. If you need to
11229 // pass an argument by reference, wrap it inside std::ref(). For
11230 // example,
11231 //
11232 // InvokeArgument<1>(5, string("Hello"), std::ref(foo))
11233 //
11234 // passes 5 and string("Hello") by value, and passes foo by
11235 // reference.
11236 //
11237 // 2. If the callable takes an argument by reference but std::ref() is
11238 // not used, it will receive the reference to a copy of the value,
11239 // instead of the original value. For example, when the 0-th
11240 // argument of the mock function takes a const string&, the action
11241 //
11242 // InvokeArgument<0>(string("Hello"))
11243 //
11244 // makes a copy of the temporary string("Hello") object and passes a
11245 // reference of the copy, instead of the original temporary object,
11246 // to the callable. This makes it easy for a user to define an
11247 // InvokeArgument action from temporary values and have it performed
11248 // later.
11249 template <std::size_t index, typename... Params>
11250 internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
11251 InvokeArgument(Params&&... params) {
11252 return {internal::FlatTuple<typename std::decay<Params>::type...>(
11253 internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
11254 }
11255
11256 #ifdef _MSC_VER
11257 # pragma warning(pop)
11258 #endif
11259
11260 } // namespace testing
11261
11262 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
11263 // Copyright 2013, Google Inc.
11264 // All rights reserved.
11265 //
11266 // Redistribution and use in source and binary forms, with or without
11267 // modification, are permitted provided that the following conditions are
11268 // met:
11269 //
11270 // * Redistributions of source code must retain the above copyright
11271 // notice, this list of conditions and the following disclaimer.
11272 // * Redistributions in binary form must reproduce the above
11273 // copyright notice, this list of conditions and the following disclaimer
11274 // in the documentation and/or other materials provided with the
11275 // distribution.
11276 // * Neither the name of Google Inc. nor the names of its
11277 // contributors may be used to endorse or promote products derived from
11278 // this software without specific prior written permission.
11279 //
11280 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11281 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11282 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11283 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11284 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11285 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11286 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11287 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11288 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11289 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11290 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11291
11292
11293 // Google Mock - a framework for writing C++ mock classes.
11294 //
11295 // This file implements some matchers that depend on gmock-matchers.h.
11296 //
11297 // Note that tests are implemented in gmock-matchers_test.cc rather than
11298 // gmock-more-matchers-test.cc.
11299
11300 // GOOGLETEST_CM0002 DO NOT DELETE
11301
11302 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11303 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11304
11305
11306 namespace testing {
11307
11308 // Silence C4100 (unreferenced formal
11309 // parameter) for MSVC
11310 #ifdef _MSC_VER
11311 # pragma warning(push)
11312 # pragma warning(disable:4100)
11313 #if (_MSC_VER == 1900)
11314 // and silence C4800 (C4800: 'int *const ': forcing value
11315 // to bool 'true' or 'false') for MSVC 14
11316 # pragma warning(disable:4800)
11317 #endif
11318 #endif
11319
11320 // Defines a matcher that matches an empty container. The container must
11321 // support both size() and empty(), which all STL-like containers provide.
11322 MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
11323 if (arg.empty()) {
11324 return true;
11325 }
11326 *result_listener << "whose size is " << arg.size();
11327 return false;
11328 }
11329
11330 // Define a matcher that matches a value that evaluates in boolean
11331 // context to true. Useful for types that define "explicit operator
11332 // bool" operators and so can't be compared for equality with true
11333 // and false.
11334 MATCHER(IsTrue, negation ? "is false" : "is true") {
11335 return static_cast<bool>(arg);
11336 }
11337
11338 // Define a matcher that matches a value that evaluates in boolean
11339 // context to false. Useful for types that define "explicit operator
11340 // bool" operators and so can't be compared for equality with true
11341 // and false.
11342 MATCHER(IsFalse, negation ? "is true" : "is false") {
11343 return !static_cast<bool>(arg);
11344 }
11345
11346 #ifdef _MSC_VER
11347 # pragma warning(pop)
11348 #endif
11349
11350
11351 } // namespace testing
11352
11353 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11354 // Copyright 2008, Google Inc.
11355 // All rights reserved.
11356 //
11357 // Redistribution and use in source and binary forms, with or without
11358 // modification, are permitted provided that the following conditions are
11359 // met:
11360 //
11361 // * Redistributions of source code must retain the above copyright
11362 // notice, this list of conditions and the following disclaimer.
11363 // * Redistributions in binary form must reproduce the above
11364 // copyright notice, this list of conditions and the following disclaimer
11365 // in the documentation and/or other materials provided with the
11366 // distribution.
11367 // * Neither the name of Google Inc. nor the names of its
11368 // contributors may be used to endorse or promote products derived from
11369 // this software without specific prior written permission.
11370 //
11371 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11372 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11373 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11374 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11375 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11376 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11377 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11378 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11379 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11380 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11381 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11382
11383
11384 // Implements class templates NiceMock, NaggyMock, and StrictMock.
11385 //
11386 // Given a mock class MockFoo that is created using Google Mock,
11387 // NiceMock<MockFoo> is a subclass of MockFoo that allows
11388 // uninteresting calls (i.e. calls to mock methods that have no
11389 // EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
11390 // that prints a warning when an uninteresting call occurs, and
11391 // StrictMock<MockFoo> is a subclass of MockFoo that treats all
11392 // uninteresting calls as errors.
11393 //
11394 // Currently a mock is naggy by default, so MockFoo and
11395 // NaggyMock<MockFoo> behave like the same. However, we will soon
11396 // switch the default behavior of mocks to be nice, as that in general
11397 // leads to more maintainable tests. When that happens, MockFoo will
11398 // stop behaving like NaggyMock<MockFoo> and start behaving like
11399 // NiceMock<MockFoo>.
11400 //
11401 // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
11402 // their respective base class. Therefore you can write
11403 // NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo
11404 // has a constructor that accepts (int, const char*), for example.
11405 //
11406 // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
11407 // and StrictMock<MockFoo> only works for mock methods defined using
11408 // the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
11409 // If a mock method is defined in a base class of MockFoo, the "nice"
11410 // or "strict" modifier may not affect it, depending on the compiler.
11411 // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
11412 // supported.
11413
11414 // GOOGLETEST_CM0002 DO NOT DELETE
11415
11416 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11417 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11418
11419 #include <type_traits>
11420
11421
11422 namespace testing {
11423 template <class MockClass>
11424 class NiceMock;
11425 template <class MockClass>
11426 class NaggyMock;
11427 template <class MockClass>
11428 class StrictMock;
11429
11430 namespace internal {
11431 template <typename T>
11432 std::true_type StrictnessModifierProbe(const NiceMock<T>&);
11433 template <typename T>
11434 std::true_type StrictnessModifierProbe(const NaggyMock<T>&);
11435 template <typename T>
11436 std::true_type StrictnessModifierProbe(const StrictMock<T>&);
11437 std::false_type StrictnessModifierProbe(...);
11438
11439 template <typename T>
11440 constexpr bool HasStrictnessModifier() {
11441 return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;
11442 }
11443
11444 // Base classes that register and deregister with testing::Mock to alter the
11445 // default behavior around uninteresting calls. Inheriting from one of these
11446 // classes first and then MockClass ensures the MockClass constructor is run
11447 // after registration, and that the MockClass destructor runs before
11448 // deregistration. This guarantees that MockClass's constructor and destructor
11449 // run with the same level of strictness as its instance methods.
11450
11451 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
11452 (defined(_MSC_VER) || defined(__clang__))
11453 // We need to mark these classes with this declspec to ensure that
11454 // the empty base class optimization is performed.
11455 #define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)
11456 #else
11457 #define GTEST_INTERNAL_EMPTY_BASE_CLASS
11458 #endif
11459
11460 template <typename Base>
11461 class NiceMockImpl {
11462 public:
11463 NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); }
11464
11465 ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
11466 };
11467
11468 template <typename Base>
11469 class NaggyMockImpl {
11470 public:
11471 NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); }
11472
11473 ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
11474 };
11475
11476 template <typename Base>
11477 class StrictMockImpl {
11478 public:
11479 StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); }
11480
11481 ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
11482 };
11483
11484 } // namespace internal
11485
11486 template <class MockClass>
11487 class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
11488 : private internal::NiceMockImpl<MockClass>,
11489 public MockClass {
11490 public:
11491 static_assert(!internal::HasStrictnessModifier<MockClass>(),
11492 "Can't apply NiceMock to a class hierarchy that already has a "
11493 "strictness modifier. See "
11494 "https://google.github.io/googletest/"
11495 "gmock_cook_book.html#NiceStrictNaggy");
11496 NiceMock() : MockClass() {
11497 static_assert(sizeof(*this) == sizeof(MockClass),
11498 "The impl subclass shouldn't introduce any padding");
11499 }
11500
11501 // Ideally, we would inherit base class's constructors through a using
11502 // declaration, which would preserve their visibility. However, many existing
11503 // tests rely on the fact that current implementation reexports protected
11504 // constructors as public. These tests would need to be cleaned up first.
11505
11506 // Single argument constructor is special-cased so that it can be
11507 // made explicit.
11508 template <typename A>
11509 explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11510 static_assert(sizeof(*this) == sizeof(MockClass),
11511 "The impl subclass shouldn't introduce any padding");
11512 }
11513
11514 template <typename TArg1, typename TArg2, typename... An>
11515 NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11516 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11517 std::forward<An>(args)...) {
11518 static_assert(sizeof(*this) == sizeof(MockClass),
11519 "The impl subclass shouldn't introduce any padding");
11520 }
11521
11522 private:
11523 GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
11524 };
11525
11526 template <class MockClass>
11527 class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
11528 : private internal::NaggyMockImpl<MockClass>,
11529 public MockClass {
11530 static_assert(!internal::HasStrictnessModifier<MockClass>(),
11531 "Can't apply NaggyMock to a class hierarchy that already has a "
11532 "strictness modifier. See "
11533 "https://google.github.io/googletest/"
11534 "gmock_cook_book.html#NiceStrictNaggy");
11535
11536 public:
11537 NaggyMock() : MockClass() {
11538 static_assert(sizeof(*this) == sizeof(MockClass),
11539 "The impl subclass shouldn't introduce any padding");
11540 }
11541
11542 // Ideally, we would inherit base class's constructors through a using
11543 // declaration, which would preserve their visibility. However, many existing
11544 // tests rely on the fact that current implementation reexports protected
11545 // constructors as public. These tests would need to be cleaned up first.
11546
11547 // Single argument constructor is special-cased so that it can be
11548 // made explicit.
11549 template <typename A>
11550 explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11551 static_assert(sizeof(*this) == sizeof(MockClass),
11552 "The impl subclass shouldn't introduce any padding");
11553 }
11554
11555 template <typename TArg1, typename TArg2, typename... An>
11556 NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11557 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11558 std::forward<An>(args)...) {
11559 static_assert(sizeof(*this) == sizeof(MockClass),
11560 "The impl subclass shouldn't introduce any padding");
11561 }
11562
11563 private:
11564 GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
11565 };
11566
11567 template <class MockClass>
11568 class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
11569 : private internal::StrictMockImpl<MockClass>,
11570 public MockClass {
11571 public:
11572 static_assert(
11573 !internal::HasStrictnessModifier<MockClass>(),
11574 "Can't apply StrictMock to a class hierarchy that already has a "
11575 "strictness modifier. See "
11576 "https://google.github.io/googletest/"
11577 "gmock_cook_book.html#NiceStrictNaggy");
11578 StrictMock() : MockClass() {
11579 static_assert(sizeof(*this) == sizeof(MockClass),
11580 "The impl subclass shouldn't introduce any padding");
11581 }
11582
11583 // Ideally, we would inherit base class's constructors through a using
11584 // declaration, which would preserve their visibility. However, many existing
11585 // tests rely on the fact that current implementation reexports protected
11586 // constructors as public. These tests would need to be cleaned up first.
11587
11588 // Single argument constructor is special-cased so that it can be
11589 // made explicit.
11590 template <typename A>
11591 explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11592 static_assert(sizeof(*this) == sizeof(MockClass),
11593 "The impl subclass shouldn't introduce any padding");
11594 }
11595
11596 template <typename TArg1, typename TArg2, typename... An>
11597 StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11598 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11599 std::forward<An>(args)...) {
11600 static_assert(sizeof(*this) == sizeof(MockClass),
11601 "The impl subclass shouldn't introduce any padding");
11602 }
11603
11604 private:
11605 GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
11606 };
11607
11608 #undef GTEST_INTERNAL_EMPTY_BASE_CLASS
11609
11610 } // namespace testing
11611
11612 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11613
11614 namespace testing {
11615
11616 // Declares Google Mock flags that we want a user to use programmatically.
11617 GMOCK_DECLARE_bool_(catch_leaked_mocks);
11618 GMOCK_DECLARE_string_(verbose);
11619 GMOCK_DECLARE_int32_(default_mock_behavior);
11620
11621 // Initializes Google Mock. This must be called before running the
11622 // tests. In particular, it parses the command line for the flags
11623 // that Google Mock recognizes. Whenever a Google Mock flag is seen,
11624 // it is removed from argv, and *argc is decremented.
11625 //
11626 // No value is returned. Instead, the Google Mock flag variables are
11627 // updated.
11628 //
11629 // Since Google Test is needed for Google Mock to work, this function
11630 // also initializes Google Test and parses its flags, if that hasn't
11631 // been done.
11632 GTEST_API_ void InitGoogleMock(int* argc, char** argv);
11633
11634 // This overloaded version can be used in Windows programs compiled in
11635 // UNICODE mode.
11636 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
11637
11638 // This overloaded version can be used on Arduino/embedded platforms where
11639 // there is no argc/argv.
11640 GTEST_API_ void InitGoogleMock();
11641
11642 } // namespace testing
11643
11644 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
+0
-14434
source/misc/embedded_libs/fmt-8.1.1/test/gtest/gmock-gtest-all.cc less more
0 // Copyright 2008, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 //
30 // Google C++ Testing and Mocking Framework (Google Test)
31 //
32 // Sometimes it's desirable to build Google Test by compiling a single file.
33 // This file serves this purpose.
34
35 // This line ensures that gtest.h can be compiled on its own, even
36 // when it's fused.
37 #include "gtest/gtest.h"
38
39 // The following lines pull in the real gtest *.cc files.
40 // Copyright 2005, Google Inc.
41 // All rights reserved.
42 //
43 // Redistribution and use in source and binary forms, with or without
44 // modification, are permitted provided that the following conditions are
45 // met:
46 //
47 // * Redistributions of source code must retain the above copyright
48 // notice, this list of conditions and the following disclaimer.
49 // * Redistributions in binary form must reproduce the above
50 // copyright notice, this list of conditions and the following disclaimer
51 // in the documentation and/or other materials provided with the
52 // distribution.
53 // * Neither the name of Google Inc. nor the names of its
54 // contributors may be used to endorse or promote products derived from
55 // this software without specific prior written permission.
56 //
57 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
58 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
59 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
60 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
61 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
62 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
63 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
64 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
65 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
66 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
67 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
68
69 //
70 // The Google C++ Testing and Mocking Framework (Google Test)
71
72 // Copyright 2007, Google Inc.
73 // All rights reserved.
74 //
75 // Redistribution and use in source and binary forms, with or without
76 // modification, are permitted provided that the following conditions are
77 // met:
78 //
79 // * Redistributions of source code must retain the above copyright
80 // notice, this list of conditions and the following disclaimer.
81 // * Redistributions in binary form must reproduce the above
82 // copyright notice, this list of conditions and the following disclaimer
83 // in the documentation and/or other materials provided with the
84 // distribution.
85 // * Neither the name of Google Inc. nor the names of its
86 // contributors may be used to endorse or promote products derived from
87 // this software without specific prior written permission.
88 //
89 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
90 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
91 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
92 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
93 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
94 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
95 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
96 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
97 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
98 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
99 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
100
101 //
102 // Utilities for testing Google Test itself and code that uses Google Test
103 // (e.g. frameworks built on top of Google Test).
104
105 // GOOGLETEST_CM0004 DO NOT DELETE
106
107 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
108 #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
109
110
111 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
112 /* class A needs to have dll-interface to be used by clients of class B */)
113
114 namespace testing {
115
116 // This helper class can be used to mock out Google Test failure reporting
117 // so that we can test Google Test or code that builds on Google Test.
118 //
119 // An object of this class appends a TestPartResult object to the
120 // TestPartResultArray object given in the constructor whenever a Google Test
121 // failure is reported. It can either intercept only failures that are
122 // generated in the same thread that created this object or it can intercept
123 // all generated failures. The scope of this mock object can be controlled with
124 // the second argument to the two arguments constructor.
125 class GTEST_API_ ScopedFakeTestPartResultReporter
126 : public TestPartResultReporterInterface {
127 public:
128 // The two possible mocking modes of this object.
129 enum InterceptMode {
130 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
131 INTERCEPT_ALL_THREADS // Intercepts all failures.
132 };
133
134 // The c'tor sets this object as the test part result reporter used
135 // by Google Test. The 'result' parameter specifies where to report the
136 // results. This reporter will only catch failures generated in the current
137 // thread. DEPRECATED
138 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
139
140 // Same as above, but you can choose the interception scope of this object.
141 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
142 TestPartResultArray* result);
143
144 // The d'tor restores the previous test part result reporter.
145 ~ScopedFakeTestPartResultReporter() override;
146
147 // Appends the TestPartResult object to the TestPartResultArray
148 // received in the constructor.
149 //
150 // This method is from the TestPartResultReporterInterface
151 // interface.
152 void ReportTestPartResult(const TestPartResult& result) override;
153
154 private:
155 void Init();
156
157 const InterceptMode intercept_mode_;
158 TestPartResultReporterInterface* old_reporter_;
159 TestPartResultArray* const result_;
160
161 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
162 };
163
164 namespace internal {
165
166 // A helper class for implementing EXPECT_FATAL_FAILURE() and
167 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
168 // TestPartResultArray contains exactly one failure that has the given
169 // type and contains the given substring. If that's not the case, a
170 // non-fatal failure will be generated.
171 class GTEST_API_ SingleFailureChecker {
172 public:
173 // The constructor remembers the arguments.
174 SingleFailureChecker(const TestPartResultArray* results,
175 TestPartResult::Type type, const std::string& substr);
176 ~SingleFailureChecker();
177 private:
178 const TestPartResultArray* const results_;
179 const TestPartResult::Type type_;
180 const std::string substr_;
181
182 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
183 };
184
185 } // namespace internal
186
187 } // namespace testing
188
189 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
190
191 // A set of macros for testing Google Test assertions or code that's expected
192 // to generate Google Test fatal failures. It verifies that the given
193 // statement will cause exactly one fatal Google Test failure with 'substr'
194 // being part of the failure message.
195 //
196 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
197 // affects and considers failures generated in the current thread and
198 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
199 //
200 // The verification of the assertion is done correctly even when the statement
201 // throws an exception or aborts the current function.
202 //
203 // Known restrictions:
204 // - 'statement' cannot reference local non-static variables or
205 // non-static members of the current object.
206 // - 'statement' cannot return a value.
207 // - You cannot stream a failure message to this macro.
208 //
209 // Note that even though the implementations of the following two
210 // macros are much alike, we cannot refactor them to use a common
211 // helper macro, due to some peculiarity in how the preprocessor
212 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
213 // gtest_unittest.cc will fail to compile if we do that.
214 #define EXPECT_FATAL_FAILURE(statement, substr) \
215 do { \
216 class GTestExpectFatalFailureHelper {\
217 public:\
218 static void Execute() { statement; }\
219 };\
220 ::testing::TestPartResultArray gtest_failures;\
221 ::testing::internal::SingleFailureChecker gtest_checker(\
222 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
223 {\
224 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
225 ::testing::ScopedFakeTestPartResultReporter:: \
226 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
227 GTestExpectFatalFailureHelper::Execute();\
228 }\
229 } while (::testing::internal::AlwaysFalse())
230
231 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
232 do { \
233 class GTestExpectFatalFailureHelper {\
234 public:\
235 static void Execute() { statement; }\
236 };\
237 ::testing::TestPartResultArray gtest_failures;\
238 ::testing::internal::SingleFailureChecker gtest_checker(\
239 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
240 {\
241 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
242 ::testing::ScopedFakeTestPartResultReporter:: \
243 INTERCEPT_ALL_THREADS, &gtest_failures);\
244 GTestExpectFatalFailureHelper::Execute();\
245 }\
246 } while (::testing::internal::AlwaysFalse())
247
248 // A macro for testing Google Test assertions or code that's expected to
249 // generate Google Test non-fatal failures. It asserts that the given
250 // statement will cause exactly one non-fatal Google Test failure with 'substr'
251 // being part of the failure message.
252 //
253 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
254 // affects and considers failures generated in the current thread and
255 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
256 //
257 // 'statement' is allowed to reference local variables and members of
258 // the current object.
259 //
260 // The verification of the assertion is done correctly even when the statement
261 // throws an exception or aborts the current function.
262 //
263 // Known restrictions:
264 // - You cannot stream a failure message to this macro.
265 //
266 // Note that even though the implementations of the following two
267 // macros are much alike, we cannot refactor them to use a common
268 // helper macro, due to some peculiarity in how the preprocessor
269 // works. If we do that, the code won't compile when the user gives
270 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
271 // expands to code containing an unprotected comma. The
272 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
273 // catches that.
274 //
275 // For the same reason, we have to write
276 // if (::testing::internal::AlwaysTrue()) { statement; }
277 // instead of
278 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
279 // to avoid an MSVC warning on unreachable code.
280 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
281 do {\
282 ::testing::TestPartResultArray gtest_failures;\
283 ::testing::internal::SingleFailureChecker gtest_checker(\
284 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
285 (substr));\
286 {\
287 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
288 ::testing::ScopedFakeTestPartResultReporter:: \
289 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
290 if (::testing::internal::AlwaysTrue()) { statement; }\
291 }\
292 } while (::testing::internal::AlwaysFalse())
293
294 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
295 do {\
296 ::testing::TestPartResultArray gtest_failures;\
297 ::testing::internal::SingleFailureChecker gtest_checker(\
298 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
299 (substr));\
300 {\
301 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
302 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
303 &gtest_failures);\
304 if (::testing::internal::AlwaysTrue()) { statement; }\
305 }\
306 } while (::testing::internal::AlwaysFalse())
307
308 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
309
310 #include <ctype.h>
311 #include <stdarg.h>
312 #include <stdio.h>
313 #include <stdlib.h>
314 #include <time.h>
315 #include <wchar.h>
316 #include <wctype.h>
317
318 #include <algorithm>
319 #include <chrono> // NOLINT
320 #include <cmath>
321 #include <cstdint>
322 #include <iomanip>
323 #include <limits>
324 #include <list>
325 #include <map>
326 #include <ostream> // NOLINT
327 #include <sstream>
328 #include <vector>
329
330 #if GTEST_OS_LINUX
331
332 # include <fcntl.h> // NOLINT
333 # include <limits.h> // NOLINT
334 # include <sched.h> // NOLINT
335 // Declares vsnprintf(). This header is not available on Windows.
336 # include <strings.h> // NOLINT
337 # include <sys/mman.h> // NOLINT
338 # include <sys/time.h> // NOLINT
339 # include <unistd.h> // NOLINT
340 # include <string>
341
342 #elif GTEST_OS_ZOS
343 # include <sys/time.h> // NOLINT
344
345 // On z/OS we additionally need strings.h for strcasecmp.
346 # include <strings.h> // NOLINT
347
348 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
349
350 # include <windows.h> // NOLINT
351 # undef min
352
353 #elif GTEST_OS_WINDOWS // We are on Windows proper.
354
355 # include <windows.h> // NOLINT
356 # undef min
357
358 #ifdef _MSC_VER
359 # include <crtdbg.h> // NOLINT
360 #endif
361
362 # include <io.h> // NOLINT
363 # include <sys/timeb.h> // NOLINT
364 # include <sys/types.h> // NOLINT
365 # include <sys/stat.h> // NOLINT
366
367 # if GTEST_OS_WINDOWS_MINGW
368 # include <sys/time.h> // NOLINT
369 # endif // GTEST_OS_WINDOWS_MINGW
370
371 #else
372
373 // cpplint thinks that the header is already included, so we want to
374 // silence it.
375 # include <sys/time.h> // NOLINT
376 # include <unistd.h> // NOLINT
377
378 #endif // GTEST_OS_LINUX
379
380 #if GTEST_HAS_EXCEPTIONS
381 # include <stdexcept>
382 #endif
383
384 #if GTEST_CAN_STREAM_RESULTS_
385 # include <arpa/inet.h> // NOLINT
386 # include <netdb.h> // NOLINT
387 # include <sys/socket.h> // NOLINT
388 # include <sys/types.h> // NOLINT
389 #endif
390
391 // Copyright 2005, Google Inc.
392 // All rights reserved.
393 //
394 // Redistribution and use in source and binary forms, with or without
395 // modification, are permitted provided that the following conditions are
396 // met:
397 //
398 // * Redistributions of source code must retain the above copyright
399 // notice, this list of conditions and the following disclaimer.
400 // * Redistributions in binary form must reproduce the above
401 // copyright notice, this list of conditions and the following disclaimer
402 // in the documentation and/or other materials provided with the
403 // distribution.
404 // * Neither the name of Google Inc. nor the names of its
405 // contributors may be used to endorse or promote products derived from
406 // this software without specific prior written permission.
407 //
408 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
409 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
410 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
411 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
412 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
413 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
414 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
415 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
416 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
417 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
418 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
419
420 // Utility functions and classes used by the Google C++ testing framework.//
421 // This file contains purely Google Test's internal implementation. Please
422 // DO NOT #INCLUDE IT IN A USER PROGRAM.
423
424 #ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
425 #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
426
427 #ifndef _WIN32_WCE
428 # include <errno.h>
429 #endif // !_WIN32_WCE
430 #include <stddef.h>
431 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
432 #include <string.h> // For memmove.
433
434 #include <algorithm>
435 #include <cstdint>
436 #include <memory>
437 #include <string>
438 #include <vector>
439
440
441 #if GTEST_CAN_STREAM_RESULTS_
442 # include <arpa/inet.h> // NOLINT
443 # include <netdb.h> // NOLINT
444 #endif
445
446 #if GTEST_OS_WINDOWS
447 # include <windows.h> // NOLINT
448 #endif // GTEST_OS_WINDOWS
449
450
451 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
452 /* class A needs to have dll-interface to be used by clients of class B */)
453
454 namespace testing {
455
456 // Declares the flags.
457 //
458 // We don't want the users to modify this flag in the code, but want
459 // Google Test's own unit tests to be able to access it. Therefore we
460 // declare it here as opposed to in gtest.h.
461 GTEST_DECLARE_bool_(death_test_use_fork);
462
463 namespace internal {
464
465 // The value of GetTestTypeId() as seen from within the Google Test
466 // library. This is solely for testing GetTestTypeId().
467 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
468
469 // Names of the flags (needed for parsing Google Test flags).
470 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
471 const char kBreakOnFailureFlag[] = "break_on_failure";
472 const char kCatchExceptionsFlag[] = "catch_exceptions";
473 const char kColorFlag[] = "color";
474 const char kFailFast[] = "fail_fast";
475 const char kFilterFlag[] = "filter";
476 const char kListTestsFlag[] = "list_tests";
477 const char kOutputFlag[] = "output";
478 const char kBriefFlag[] = "brief";
479 const char kPrintTimeFlag[] = "print_time";
480 const char kPrintUTF8Flag[] = "print_utf8";
481 const char kRandomSeedFlag[] = "random_seed";
482 const char kRepeatFlag[] = "repeat";
483 const char kShuffleFlag[] = "shuffle";
484 const char kStackTraceDepthFlag[] = "stack_trace_depth";
485 const char kStreamResultToFlag[] = "stream_result_to";
486 const char kThrowOnFailureFlag[] = "throw_on_failure";
487 const char kFlagfileFlag[] = "flagfile";
488
489 // A valid random seed must be in [1, kMaxRandomSeed].
490 const int kMaxRandomSeed = 99999;
491
492 // g_help_flag is true if and only if the --help flag or an equivalent form
493 // is specified on the command line.
494 GTEST_API_ extern bool g_help_flag;
495
496 // Returns the current time in milliseconds.
497 GTEST_API_ TimeInMillis GetTimeInMillis();
498
499 // Returns true if and only if Google Test should use colors in the output.
500 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
501
502 // Formats the given time in milliseconds as seconds.
503 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
504
505 // Converts the given time in milliseconds to a date string in the ISO 8601
506 // format, without the timezone information. N.B.: due to the use the
507 // non-reentrant localtime() function, this function is not thread safe. Do
508 // not use it in any code that can be called from multiple threads.
509 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
510
511 // Parses a string for an Int32 flag, in the form of "--flag=value".
512 //
513 // On success, stores the value of the flag in *value, and returns
514 // true. On failure, returns false without changing *value.
515 GTEST_API_ bool ParseInt32Flag(
516 const char* str, const char* flag, int32_t* value);
517
518 // Returns a random seed in range [1, kMaxRandomSeed] based on the
519 // given --gtest_random_seed flag value.
520 inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
521 const unsigned int raw_seed = (random_seed_flag == 0) ?
522 static_cast<unsigned int>(GetTimeInMillis()) :
523 static_cast<unsigned int>(random_seed_flag);
524
525 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
526 // it's easy to type.
527 const int normalized_seed =
528 static_cast<int>((raw_seed - 1U) %
529 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
530 return normalized_seed;
531 }
532
533 // Returns the first valid random seed after 'seed'. The behavior is
534 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
535 // considered to be 1.
536 inline int GetNextRandomSeed(int seed) {
537 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
538 << "Invalid random seed " << seed << " - must be in [1, "
539 << kMaxRandomSeed << "].";
540 const int next_seed = seed + 1;
541 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
542 }
543
544 // This class saves the values of all Google Test flags in its c'tor, and
545 // restores them in its d'tor.
546 class GTestFlagSaver {
547 public:
548 // The c'tor.
549 GTestFlagSaver() {
550 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
551 break_on_failure_ = GTEST_FLAG(break_on_failure);
552 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
553 color_ = GTEST_FLAG(color);
554 death_test_style_ = GTEST_FLAG(death_test_style);
555 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
556 fail_fast_ = GTEST_FLAG(fail_fast);
557 filter_ = GTEST_FLAG(filter);
558 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
559 list_tests_ = GTEST_FLAG(list_tests);
560 output_ = GTEST_FLAG(output);
561 brief_ = GTEST_FLAG(brief);
562 print_time_ = GTEST_FLAG(print_time);
563 print_utf8_ = GTEST_FLAG(print_utf8);
564 random_seed_ = GTEST_FLAG(random_seed);
565 repeat_ = GTEST_FLAG(repeat);
566 shuffle_ = GTEST_FLAG(shuffle);
567 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
568 stream_result_to_ = GTEST_FLAG(stream_result_to);
569 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
570 }
571
572 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
573 ~GTestFlagSaver() {
574 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
575 GTEST_FLAG(break_on_failure) = break_on_failure_;
576 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
577 GTEST_FLAG(color) = color_;
578 GTEST_FLAG(death_test_style) = death_test_style_;
579 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
580 GTEST_FLAG(filter) = filter_;
581 GTEST_FLAG(fail_fast) = fail_fast_;
582 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
583 GTEST_FLAG(list_tests) = list_tests_;
584 GTEST_FLAG(output) = output_;
585 GTEST_FLAG(brief) = brief_;
586 GTEST_FLAG(print_time) = print_time_;
587 GTEST_FLAG(print_utf8) = print_utf8_;
588 GTEST_FLAG(random_seed) = random_seed_;
589 GTEST_FLAG(repeat) = repeat_;
590 GTEST_FLAG(shuffle) = shuffle_;
591 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
592 GTEST_FLAG(stream_result_to) = stream_result_to_;
593 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
594 }
595
596 private:
597 // Fields for saving the original values of flags.
598 bool also_run_disabled_tests_;
599 bool break_on_failure_;
600 bool catch_exceptions_;
601 std::string color_;
602 std::string death_test_style_;
603 bool death_test_use_fork_;
604 bool fail_fast_;
605 std::string filter_;
606 std::string internal_run_death_test_;
607 bool list_tests_;
608 std::string output_;
609 bool brief_;
610 bool print_time_;
611 bool print_utf8_;
612 int32_t random_seed_;
613 int32_t repeat_;
614 bool shuffle_;
615 int32_t stack_trace_depth_;
616 std::string stream_result_to_;
617 bool throw_on_failure_;
618 } GTEST_ATTRIBUTE_UNUSED_;
619
620 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
621 // code_point parameter is of type UInt32 because wchar_t may not be
622 // wide enough to contain a code point.
623 // If the code_point is not a valid Unicode code point
624 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
625 // to "(Invalid Unicode 0xXXXXXXXX)".
626 GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
627
628 // Converts a wide string to a narrow string in UTF-8 encoding.
629 // The wide string is assumed to have the following encoding:
630 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
631 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
632 // Parameter str points to a null-terminated wide string.
633 // Parameter num_chars may additionally limit the number
634 // of wchar_t characters processed. -1 is used when the entire string
635 // should be processed.
636 // If the string contains code points that are not valid Unicode code points
637 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
638 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
639 // and contains invalid UTF-16 surrogate pairs, values in those pairs
640 // will be encoded as individual Unicode characters from Basic Normal Plane.
641 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
642
643 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
644 // if the variable is present. If a file already exists at this location, this
645 // function will write over it. If the variable is present, but the file cannot
646 // be created, prints an error and exits.
647 void WriteToShardStatusFileIfNeeded();
648
649 // Checks whether sharding is enabled by examining the relevant
650 // environment variable values. If the variables are present,
651 // but inconsistent (e.g., shard_index >= total_shards), prints
652 // an error and exits. If in_subprocess_for_death_test, sharding is
653 // disabled because it must only be applied to the original test
654 // process. Otherwise, we could filter out death tests we intended to execute.
655 GTEST_API_ bool ShouldShard(const char* total_shards_str,
656 const char* shard_index_str,
657 bool in_subprocess_for_death_test);
658
659 // Parses the environment variable var as a 32-bit integer. If it is unset,
660 // returns default_val. If it is not a 32-bit integer, prints an error and
661 // and aborts.
662 GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
663
664 // Given the total number of shards, the shard index, and the test id,
665 // returns true if and only if the test should be run on this shard. The test id
666 // is some arbitrary but unique non-negative integer assigned to each test
667 // method. Assumes that 0 <= shard_index < total_shards.
668 GTEST_API_ bool ShouldRunTestOnShard(
669 int total_shards, int shard_index, int test_id);
670
671 // STL container utilities.
672
673 // Returns the number of elements in the given container that satisfy
674 // the given predicate.
675 template <class Container, typename Predicate>
676 inline int CountIf(const Container& c, Predicate predicate) {
677 // Implemented as an explicit loop since std::count_if() in libCstd on
678 // Solaris has a non-standard signature.
679 int count = 0;
680 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
681 if (predicate(*it))
682 ++count;
683 }
684 return count;
685 }
686
687 // Applies a function/functor to each element in the container.
688 template <class Container, typename Functor>
689 void ForEach(const Container& c, Functor functor) {
690 std::for_each(c.begin(), c.end(), functor);
691 }
692
693 // Returns the i-th element of the vector, or default_value if i is not
694 // in range [0, v.size()).
695 template <typename E>
696 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
697 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
698 : v[static_cast<size_t>(i)];
699 }
700
701 // Performs an in-place shuffle of a range of the vector's elements.
702 // 'begin' and 'end' are element indices as an STL-style range;
703 // i.e. [begin, end) are shuffled, where 'end' == size() means to
704 // shuffle to the end of the vector.
705 template <typename E>
706 void ShuffleRange(internal::Random* random, int begin, int end,
707 std::vector<E>* v) {
708 const int size = static_cast<int>(v->size());
709 GTEST_CHECK_(0 <= begin && begin <= size)
710 << "Invalid shuffle range start " << begin << ": must be in range [0, "
711 << size << "].";
712 GTEST_CHECK_(begin <= end && end <= size)
713 << "Invalid shuffle range finish " << end << ": must be in range ["
714 << begin << ", " << size << "].";
715
716 // Fisher-Yates shuffle, from
717 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
718 for (int range_width = end - begin; range_width >= 2; range_width--) {
719 const int last_in_range = begin + range_width - 1;
720 const int selected =
721 begin +
722 static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
723 std::swap((*v)[static_cast<size_t>(selected)],
724 (*v)[static_cast<size_t>(last_in_range)]);
725 }
726 }
727
728 // Performs an in-place shuffle of the vector's elements.
729 template <typename E>
730 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
731 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
732 }
733
734 // A function for deleting an object. Handy for being used as a
735 // functor.
736 template <typename T>
737 static void Delete(T* x) {
738 delete x;
739 }
740
741 // A predicate that checks the key of a TestProperty against a known key.
742 //
743 // TestPropertyKeyIs is copyable.
744 class TestPropertyKeyIs {
745 public:
746 // Constructor.
747 //
748 // TestPropertyKeyIs has NO default constructor.
749 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
750
751 // Returns true if and only if the test name of test property matches on key_.
752 bool operator()(const TestProperty& test_property) const {
753 return test_property.key() == key_;
754 }
755
756 private:
757 std::string key_;
758 };
759
760 // Class UnitTestOptions.
761 //
762 // This class contains functions for processing options the user
763 // specifies when running the tests. It has only static members.
764 //
765 // In most cases, the user can specify an option using either an
766 // environment variable or a command line flag. E.g. you can set the
767 // test filter using either GTEST_FILTER or --gtest_filter. If both
768 // the variable and the flag are present, the latter overrides the
769 // former.
770 class GTEST_API_ UnitTestOptions {
771 public:
772 // Functions for processing the gtest_output flag.
773
774 // Returns the output format, or "" for normal printed output.
775 static std::string GetOutputFormat();
776
777 // Returns the absolute path of the requested output file, or the
778 // default (test_detail.xml in the original working directory) if
779 // none was explicitly specified.
780 static std::string GetAbsolutePathToOutputFile();
781
782 // Functions for processing the gtest_filter flag.
783
784 // Returns true if and only if the user-specified filter matches the test
785 // suite name and the test name.
786 static bool FilterMatchesTest(const std::string& test_suite_name,
787 const std::string& test_name);
788
789 #if GTEST_OS_WINDOWS
790 // Function for supporting the gtest_catch_exception flag.
791
792 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
793 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
794 // This function is useful as an __except condition.
795 static int GTestShouldProcessSEH(DWORD exception_code);
796 #endif // GTEST_OS_WINDOWS
797
798 // Returns true if "name" matches the ':' separated list of glob-style
799 // filters in "filter".
800 static bool MatchesFilter(const std::string& name, const char* filter);
801 };
802
803 // Returns the current application's name, removing directory path if that
804 // is present. Used by UnitTestOptions::GetOutputFile.
805 GTEST_API_ FilePath GetCurrentExecutableName();
806
807 // The role interface for getting the OS stack trace as a string.
808 class OsStackTraceGetterInterface {
809 public:
810 OsStackTraceGetterInterface() {}
811 virtual ~OsStackTraceGetterInterface() {}
812
813 // Returns the current OS stack trace as an std::string. Parameters:
814 //
815 // max_depth - the maximum number of stack frames to be included
816 // in the trace.
817 // skip_count - the number of top frames to be skipped; doesn't count
818 // against max_depth.
819 virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
820
821 // UponLeavingGTest() should be called immediately before Google Test calls
822 // user code. It saves some information about the current stack that
823 // CurrentStackTrace() will use to find and hide Google Test stack frames.
824 virtual void UponLeavingGTest() = 0;
825
826 // This string is inserted in place of stack frames that are part of
827 // Google Test's implementation.
828 static const char* const kElidedFramesMarker;
829
830 private:
831 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
832 };
833
834 // A working implementation of the OsStackTraceGetterInterface interface.
835 class OsStackTraceGetter : public OsStackTraceGetterInterface {
836 public:
837 OsStackTraceGetter() {}
838
839 std::string CurrentStackTrace(int max_depth, int skip_count) override;
840 void UponLeavingGTest() override;
841
842 private:
843 #if GTEST_HAS_ABSL
844 Mutex mutex_; // Protects all internal state.
845
846 // We save the stack frame below the frame that calls user code.
847 // We do this because the address of the frame immediately below
848 // the user code changes between the call to UponLeavingGTest()
849 // and any calls to the stack trace code from within the user code.
850 void* caller_frame_ = nullptr;
851 #endif // GTEST_HAS_ABSL
852
853 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
854 };
855
856 // Information about a Google Test trace point.
857 struct TraceInfo {
858 const char* file;
859 int line;
860 std::string message;
861 };
862
863 // This is the default global test part result reporter used in UnitTestImpl.
864 // This class should only be used by UnitTestImpl.
865 class DefaultGlobalTestPartResultReporter
866 : public TestPartResultReporterInterface {
867 public:
868 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
869 // Implements the TestPartResultReporterInterface. Reports the test part
870 // result in the current test.
871 void ReportTestPartResult(const TestPartResult& result) override;
872
873 private:
874 UnitTestImpl* const unit_test_;
875
876 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
877 };
878
879 // This is the default per thread test part result reporter used in
880 // UnitTestImpl. This class should only be used by UnitTestImpl.
881 class DefaultPerThreadTestPartResultReporter
882 : public TestPartResultReporterInterface {
883 public:
884 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
885 // Implements the TestPartResultReporterInterface. The implementation just
886 // delegates to the current global test part result reporter of *unit_test_.
887 void ReportTestPartResult(const TestPartResult& result) override;
888
889 private:
890 UnitTestImpl* const unit_test_;
891
892 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
893 };
894
895 // The private implementation of the UnitTest class. We don't protect
896 // the methods under a mutex, as this class is not accessible by a
897 // user and the UnitTest class that delegates work to this class does
898 // proper locking.
899 class GTEST_API_ UnitTestImpl {
900 public:
901 explicit UnitTestImpl(UnitTest* parent);
902 virtual ~UnitTestImpl();
903
904 // There are two different ways to register your own TestPartResultReporter.
905 // You can register your own repoter to listen either only for test results
906 // from the current thread or for results from all threads.
907 // By default, each per-thread test result repoter just passes a new
908 // TestPartResult to the global test result reporter, which registers the
909 // test part result for the currently running test.
910
911 // Returns the global test part result reporter.
912 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
913
914 // Sets the global test part result reporter.
915 void SetGlobalTestPartResultReporter(
916 TestPartResultReporterInterface* reporter);
917
918 // Returns the test part result reporter for the current thread.
919 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
920
921 // Sets the test part result reporter for the current thread.
922 void SetTestPartResultReporterForCurrentThread(
923 TestPartResultReporterInterface* reporter);
924
925 // Gets the number of successful test suites.
926 int successful_test_suite_count() const;
927
928 // Gets the number of failed test suites.
929 int failed_test_suite_count() const;
930
931 // Gets the number of all test suites.
932 int total_test_suite_count() const;
933
934 // Gets the number of all test suites that contain at least one test
935 // that should run.
936 int test_suite_to_run_count() const;
937
938 // Gets the number of successful tests.
939 int successful_test_count() const;
940
941 // Gets the number of skipped tests.
942 int skipped_test_count() const;
943
944 // Gets the number of failed tests.
945 int failed_test_count() const;
946
947 // Gets the number of disabled tests that will be reported in the XML report.
948 int reportable_disabled_test_count() const;
949
950 // Gets the number of disabled tests.
951 int disabled_test_count() const;
952
953 // Gets the number of tests to be printed in the XML report.
954 int reportable_test_count() const;
955
956 // Gets the number of all tests.
957 int total_test_count() const;
958
959 // Gets the number of tests that should run.
960 int test_to_run_count() const;
961
962 // Gets the time of the test program start, in ms from the start of the
963 // UNIX epoch.
964 TimeInMillis start_timestamp() const { return start_timestamp_; }
965
966 // Gets the elapsed time, in milliseconds.
967 TimeInMillis elapsed_time() const { return elapsed_time_; }
968
969 // Returns true if and only if the unit test passed (i.e. all test suites
970 // passed).
971 bool Passed() const { return !Failed(); }
972
973 // Returns true if and only if the unit test failed (i.e. some test suite
974 // failed or something outside of all tests failed).
975 bool Failed() const {
976 return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
977 }
978
979 // Gets the i-th test suite among all the test suites. i can range from 0 to
980 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
981 const TestSuite* GetTestSuite(int i) const {
982 const int index = GetElementOr(test_suite_indices_, i, -1);
983 return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
984 }
985
986 // Legacy API is deprecated but still available
987 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
988 const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
989 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
990
991 // Gets the i-th test suite among all the test suites. i can range from 0 to
992 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
993 TestSuite* GetMutableSuiteCase(int i) {
994 const int index = GetElementOr(test_suite_indices_, i, -1);
995 return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
996 }
997
998 // Provides access to the event listener list.
999 TestEventListeners* listeners() { return &listeners_; }
1000
1001 // Returns the TestResult for the test that's currently running, or
1002 // the TestResult for the ad hoc test if no test is running.
1003 TestResult* current_test_result();
1004
1005 // Returns the TestResult for the ad hoc test.
1006 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1007
1008 // Sets the OS stack trace getter.
1009 //
1010 // Does nothing if the input and the current OS stack trace getter
1011 // are the same; otherwise, deletes the old getter and makes the
1012 // input the current getter.
1013 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1014
1015 // Returns the current OS stack trace getter if it is not NULL;
1016 // otherwise, creates an OsStackTraceGetter, makes it the current
1017 // getter, and returns it.
1018 OsStackTraceGetterInterface* os_stack_trace_getter();
1019
1020 // Returns the current OS stack trace as an std::string.
1021 //
1022 // The maximum number of stack frames to be included is specified by
1023 // the gtest_stack_trace_depth flag. The skip_count parameter
1024 // specifies the number of top frames to be skipped, which doesn't
1025 // count against the number of frames to be included.
1026 //
1027 // For example, if Foo() calls Bar(), which in turn calls
1028 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1029 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1030 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1031
1032 // Finds and returns a TestSuite with the given name. If one doesn't
1033 // exist, creates one and returns it.
1034 //
1035 // Arguments:
1036 //
1037 // test_suite_name: name of the test suite
1038 // type_param: the name of the test's type parameter, or NULL if
1039 // this is not a typed or a type-parameterized test.
1040 // set_up_tc: pointer to the function that sets up the test suite
1041 // tear_down_tc: pointer to the function that tears down the test suite
1042 TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
1043 internal::SetUpTestSuiteFunc set_up_tc,
1044 internal::TearDownTestSuiteFunc tear_down_tc);
1045
1046 // Legacy API is deprecated but still available
1047 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1048 TestCase* GetTestCase(const char* test_case_name, const char* type_param,
1049 internal::SetUpTestSuiteFunc set_up_tc,
1050 internal::TearDownTestSuiteFunc tear_down_tc) {
1051 return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
1052 }
1053 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1054
1055 // Adds a TestInfo to the unit test.
1056 //
1057 // Arguments:
1058 //
1059 // set_up_tc: pointer to the function that sets up the test suite
1060 // tear_down_tc: pointer to the function that tears down the test suite
1061 // test_info: the TestInfo object
1062 void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
1063 internal::TearDownTestSuiteFunc tear_down_tc,
1064 TestInfo* test_info) {
1065 #if GTEST_HAS_DEATH_TEST
1066 // In order to support thread-safe death tests, we need to
1067 // remember the original working directory when the test program
1068 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1069 // the user may have changed the current directory before calling
1070 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1071 // AddTestInfo(), which is called to register a TEST or TEST_F
1072 // before main() is reached.
1073 if (original_working_dir_.IsEmpty()) {
1074 original_working_dir_.Set(FilePath::GetCurrentDir());
1075 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1076 << "Failed to get the current working directory.";
1077 }
1078 #endif // GTEST_HAS_DEATH_TEST
1079
1080 GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
1081 set_up_tc, tear_down_tc)
1082 ->AddTestInfo(test_info);
1083 }
1084
1085 // Returns ParameterizedTestSuiteRegistry object used to keep track of
1086 // value-parameterized tests and instantiate and register them.
1087 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
1088 return parameterized_test_registry_;
1089 }
1090
1091 std::set<std::string>* ignored_parameterized_test_suites() {
1092 return &ignored_parameterized_test_suites_;
1093 }
1094
1095 // Returns TypeParameterizedTestSuiteRegistry object used to keep track of
1096 // type-parameterized tests and instantiations of them.
1097 internal::TypeParameterizedTestSuiteRegistry&
1098 type_parameterized_test_registry() {
1099 return type_parameterized_test_registry_;
1100 }
1101
1102 // Sets the TestSuite object for the test that's currently running.
1103 void set_current_test_suite(TestSuite* a_current_test_suite) {
1104 current_test_suite_ = a_current_test_suite;
1105 }
1106
1107 // Sets the TestInfo object for the test that's currently running. If
1108 // current_test_info is NULL, the assertion results will be stored in
1109 // ad_hoc_test_result_.
1110 void set_current_test_info(TestInfo* a_current_test_info) {
1111 current_test_info_ = a_current_test_info;
1112 }
1113
1114 // Registers all parameterized tests defined using TEST_P and
1115 // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
1116 // combination. This method can be called more then once; it has guards
1117 // protecting from registering the tests more then once. If
1118 // value-parameterized tests are disabled, RegisterParameterizedTests is
1119 // present but does nothing.
1120 void RegisterParameterizedTests();
1121
1122 // Runs all tests in this UnitTest object, prints the result, and
1123 // returns true if all tests are successful. If any exception is
1124 // thrown during a test, this test is considered to be failed, but
1125 // the rest of the tests will still be run.
1126 bool RunAllTests();
1127
1128 // Clears the results of all tests, except the ad hoc tests.
1129 void ClearNonAdHocTestResult() {
1130 ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
1131 }
1132
1133 // Clears the results of ad-hoc test assertions.
1134 void ClearAdHocTestResult() {
1135 ad_hoc_test_result_.Clear();
1136 }
1137
1138 // Adds a TestProperty to the current TestResult object when invoked in a
1139 // context of a test or a test suite, or to the global property set. If the
1140 // result already contains a property with the same key, the value will be
1141 // updated.
1142 void RecordProperty(const TestProperty& test_property);
1143
1144 enum ReactionToSharding {
1145 HONOR_SHARDING_PROTOCOL,
1146 IGNORE_SHARDING_PROTOCOL
1147 };
1148
1149 // Matches the full name of each test against the user-specified
1150 // filter to decide whether the test should run, then records the
1151 // result in each TestSuite and TestInfo object.
1152 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1153 // based on sharding variables in the environment.
1154 // Returns the number of tests that should run.
1155 int FilterTests(ReactionToSharding shard_tests);
1156
1157 // Prints the names of the tests matching the user-specified filter flag.
1158 void ListTestsMatchingFilter();
1159
1160 const TestSuite* current_test_suite() const { return current_test_suite_; }
1161 TestInfo* current_test_info() { return current_test_info_; }
1162 const TestInfo* current_test_info() const { return current_test_info_; }
1163
1164 // Returns the vector of environments that need to be set-up/torn-down
1165 // before/after the tests are run.
1166 std::vector<Environment*>& environments() { return environments_; }
1167
1168 // Getters for the per-thread Google Test trace stack.
1169 std::vector<TraceInfo>& gtest_trace_stack() {
1170 return *(gtest_trace_stack_.pointer());
1171 }
1172 const std::vector<TraceInfo>& gtest_trace_stack() const {
1173 return gtest_trace_stack_.get();
1174 }
1175
1176 #if GTEST_HAS_DEATH_TEST
1177 void InitDeathTestSubprocessControlInfo() {
1178 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1179 }
1180 // Returns a pointer to the parsed --gtest_internal_run_death_test
1181 // flag, or NULL if that flag was not specified.
1182 // This information is useful only in a death test child process.
1183 // Must not be called before a call to InitGoogleTest.
1184 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1185 return internal_run_death_test_flag_.get();
1186 }
1187
1188 // Returns a pointer to the current death test factory.
1189 internal::DeathTestFactory* death_test_factory() {
1190 return death_test_factory_.get();
1191 }
1192
1193 void SuppressTestEventsIfInSubprocess();
1194
1195 friend class ReplaceDeathTestFactory;
1196 #endif // GTEST_HAS_DEATH_TEST
1197
1198 // Initializes the event listener performing XML output as specified by
1199 // UnitTestOptions. Must not be called before InitGoogleTest.
1200 void ConfigureXmlOutput();
1201
1202 #if GTEST_CAN_STREAM_RESULTS_
1203 // Initializes the event listener for streaming test results to a socket.
1204 // Must not be called before InitGoogleTest.
1205 void ConfigureStreamingOutput();
1206 #endif
1207
1208 // Performs initialization dependent upon flag values obtained in
1209 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1210 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1211 // this function is also called from RunAllTests. Since this function can be
1212 // called more than once, it has to be idempotent.
1213 void PostFlagParsingInit();
1214
1215 // Gets the random seed used at the start of the current test iteration.
1216 int random_seed() const { return random_seed_; }
1217
1218 // Gets the random number generator.
1219 internal::Random* random() { return &random_; }
1220
1221 // Shuffles all test suites, and the tests within each test suite,
1222 // making sure that death tests are still run first.
1223 void ShuffleTests();
1224
1225 // Restores the test suites and tests to their order before the first shuffle.
1226 void UnshuffleTests();
1227
1228 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1229 // UnitTest::Run() starts.
1230 bool catch_exceptions() const { return catch_exceptions_; }
1231
1232 private:
1233 friend class ::testing::UnitTest;
1234
1235 // Used by UnitTest::Run() to capture the state of
1236 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1237 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1238
1239 // The UnitTest object that owns this implementation object.
1240 UnitTest* const parent_;
1241
1242 // The working directory when the first TEST() or TEST_F() was
1243 // executed.
1244 internal::FilePath original_working_dir_;
1245
1246 // The default test part result reporters.
1247 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1248 DefaultPerThreadTestPartResultReporter
1249 default_per_thread_test_part_result_reporter_;
1250
1251 // Points to (but doesn't own) the global test part result reporter.
1252 TestPartResultReporterInterface* global_test_part_result_repoter_;
1253
1254 // Protects read and write access to global_test_part_result_reporter_.
1255 internal::Mutex global_test_part_result_reporter_mutex_;
1256
1257 // Points to (but doesn't own) the per-thread test part result reporter.
1258 internal::ThreadLocal<TestPartResultReporterInterface*>
1259 per_thread_test_part_result_reporter_;
1260
1261 // The vector of environments that need to be set-up/torn-down
1262 // before/after the tests are run.
1263 std::vector<Environment*> environments_;
1264
1265 // The vector of TestSuites in their original order. It owns the
1266 // elements in the vector.
1267 std::vector<TestSuite*> test_suites_;
1268
1269 // Provides a level of indirection for the test suite list to allow
1270 // easy shuffling and restoring the test suite order. The i-th
1271 // element of this vector is the index of the i-th test suite in the
1272 // shuffled order.
1273 std::vector<int> test_suite_indices_;
1274
1275 // ParameterizedTestRegistry object used to register value-parameterized
1276 // tests.
1277 internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
1278 internal::TypeParameterizedTestSuiteRegistry
1279 type_parameterized_test_registry_;
1280
1281 // The set holding the name of parameterized
1282 // test suites that may go uninstantiated.
1283 std::set<std::string> ignored_parameterized_test_suites_;
1284
1285 // Indicates whether RegisterParameterizedTests() has been called already.
1286 bool parameterized_tests_registered_;
1287
1288 // Index of the last death test suite registered. Initially -1.
1289 int last_death_test_suite_;
1290
1291 // This points to the TestSuite for the currently running test. It
1292 // changes as Google Test goes through one test suite after another.
1293 // When no test is running, this is set to NULL and Google Test
1294 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1295 TestSuite* current_test_suite_;
1296
1297 // This points to the TestInfo for the currently running test. It
1298 // changes as Google Test goes through one test after another. When
1299 // no test is running, this is set to NULL and Google Test stores
1300 // assertion results in ad_hoc_test_result_. Initially NULL.
1301 TestInfo* current_test_info_;
1302
1303 // Normally, a user only writes assertions inside a TEST or TEST_F,
1304 // or inside a function called by a TEST or TEST_F. Since Google
1305 // Test keeps track of which test is current running, it can
1306 // associate such an assertion with the test it belongs to.
1307 //
1308 // If an assertion is encountered when no TEST or TEST_F is running,
1309 // Google Test attributes the assertion result to an imaginary "ad hoc"
1310 // test, and records the result in ad_hoc_test_result_.
1311 TestResult ad_hoc_test_result_;
1312
1313 // The list of event listeners that can be used to track events inside
1314 // Google Test.
1315 TestEventListeners listeners_;
1316
1317 // The OS stack trace getter. Will be deleted when the UnitTest
1318 // object is destructed. By default, an OsStackTraceGetter is used,
1319 // but the user can set this field to use a custom getter if that is
1320 // desired.
1321 OsStackTraceGetterInterface* os_stack_trace_getter_;
1322
1323 // True if and only if PostFlagParsingInit() has been called.
1324 bool post_flag_parse_init_performed_;
1325
1326 // The random number seed used at the beginning of the test run.
1327 int random_seed_;
1328
1329 // Our random number generator.
1330 internal::Random random_;
1331
1332 // The time of the test program start, in ms from the start of the
1333 // UNIX epoch.
1334 TimeInMillis start_timestamp_;
1335
1336 // How long the test took to run, in milliseconds.
1337 TimeInMillis elapsed_time_;
1338
1339 #if GTEST_HAS_DEATH_TEST
1340 // The decomposed components of the gtest_internal_run_death_test flag,
1341 // parsed when RUN_ALL_TESTS is called.
1342 std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1343 std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
1344 #endif // GTEST_HAS_DEATH_TEST
1345
1346 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1347 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1348
1349 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1350 // starts.
1351 bool catch_exceptions_;
1352
1353 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1354 }; // class UnitTestImpl
1355
1356 // Convenience function for accessing the global UnitTest
1357 // implementation object.
1358 inline UnitTestImpl* GetUnitTestImpl() {
1359 return UnitTest::GetInstance()->impl();
1360 }
1361
1362 #if GTEST_USES_SIMPLE_RE
1363
1364 // Internal helper functions for implementing the simple regular
1365 // expression matcher.
1366 GTEST_API_ bool IsInSet(char ch, const char* str);
1367 GTEST_API_ bool IsAsciiDigit(char ch);
1368 GTEST_API_ bool IsAsciiPunct(char ch);
1369 GTEST_API_ bool IsRepeat(char ch);
1370 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1371 GTEST_API_ bool IsAsciiWordChar(char ch);
1372 GTEST_API_ bool IsValidEscape(char ch);
1373 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1374 GTEST_API_ bool ValidateRegex(const char* regex);
1375 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1376 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1377 bool escaped, char ch, char repeat, const char* regex, const char* str);
1378 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1379
1380 #endif // GTEST_USES_SIMPLE_RE
1381
1382 // Parses the command line for Google Test flags, without initializing
1383 // other parts of Google Test.
1384 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1385 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1386
1387 #if GTEST_HAS_DEATH_TEST
1388
1389 // Returns the message describing the last system error, regardless of the
1390 // platform.
1391 GTEST_API_ std::string GetLastErrnoDescription();
1392
1393 // Attempts to parse a string into a positive integer pointed to by the
1394 // number parameter. Returns true if that is possible.
1395 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1396 // it here.
1397 template <typename Integer>
1398 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1399 // Fail fast if the given string does not begin with a digit;
1400 // this bypasses strtoXXX's "optional leading whitespace and plus
1401 // or minus sign" semantics, which are undesirable here.
1402 if (str.empty() || !IsDigit(str[0])) {
1403 return false;
1404 }
1405 errno = 0;
1406
1407 char* end;
1408 // BiggestConvertible is the largest integer type that system-provided
1409 // string-to-number conversion routines can return.
1410 using BiggestConvertible = unsigned long long; // NOLINT
1411
1412 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT
1413 const bool parse_success = *end == '\0' && errno == 0;
1414
1415 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1416
1417 const Integer result = static_cast<Integer>(parsed);
1418 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1419 *number = result;
1420 return true;
1421 }
1422 return false;
1423 }
1424 #endif // GTEST_HAS_DEATH_TEST
1425
1426 // TestResult contains some private methods that should be hidden from
1427 // Google Test user but are required for testing. This class allow our tests
1428 // to access them.
1429 //
1430 // This class is supplied only for the purpose of testing Google Test's own
1431 // constructs. Do not use it in user tests, either directly or indirectly.
1432 class TestResultAccessor {
1433 public:
1434 static void RecordProperty(TestResult* test_result,
1435 const std::string& xml_element,
1436 const TestProperty& property) {
1437 test_result->RecordProperty(xml_element, property);
1438 }
1439
1440 static void ClearTestPartResults(TestResult* test_result) {
1441 test_result->ClearTestPartResults();
1442 }
1443
1444 static const std::vector<testing::TestPartResult>& test_part_results(
1445 const TestResult& test_result) {
1446 return test_result.test_part_results();
1447 }
1448 };
1449
1450 #if GTEST_CAN_STREAM_RESULTS_
1451
1452 // Streams test results to the given port on the given host machine.
1453 class StreamingListener : public EmptyTestEventListener {
1454 public:
1455 // Abstract base class for writing strings to a socket.
1456 class AbstractSocketWriter {
1457 public:
1458 virtual ~AbstractSocketWriter() {}
1459
1460 // Sends a string to the socket.
1461 virtual void Send(const std::string& message) = 0;
1462
1463 // Closes the socket.
1464 virtual void CloseConnection() {}
1465
1466 // Sends a string and a newline to the socket.
1467 void SendLn(const std::string& message) { Send(message + "\n"); }
1468 };
1469
1470 // Concrete class for actually writing strings to a socket.
1471 class SocketWriter : public AbstractSocketWriter {
1472 public:
1473 SocketWriter(const std::string& host, const std::string& port)
1474 : sockfd_(-1), host_name_(host), port_num_(port) {
1475 MakeConnection();
1476 }
1477
1478 ~SocketWriter() override {
1479 if (sockfd_ != -1)
1480 CloseConnection();
1481 }
1482
1483 // Sends a string to the socket.
1484 void Send(const std::string& message) override {
1485 GTEST_CHECK_(sockfd_ != -1)
1486 << "Send() can be called only when there is a connection.";
1487
1488 const auto len = static_cast<size_t>(message.length());
1489 if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
1490 GTEST_LOG_(WARNING)
1491 << "stream_result_to: failed to stream to "
1492 << host_name_ << ":" << port_num_;
1493 }
1494 }
1495
1496 private:
1497 // Creates a client socket and connects to the server.
1498 void MakeConnection();
1499
1500 // Closes the socket.
1501 void CloseConnection() override {
1502 GTEST_CHECK_(sockfd_ != -1)
1503 << "CloseConnection() can be called only when there is a connection.";
1504
1505 close(sockfd_);
1506 sockfd_ = -1;
1507 }
1508
1509 int sockfd_; // socket file descriptor
1510 const std::string host_name_;
1511 const std::string port_num_;
1512
1513 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1514 }; // class SocketWriter
1515
1516 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1517 static std::string UrlEncode(const char* str);
1518
1519 StreamingListener(const std::string& host, const std::string& port)
1520 : socket_writer_(new SocketWriter(host, port)) {
1521 Start();
1522 }
1523
1524 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1525 : socket_writer_(socket_writer) { Start(); }
1526
1527 void OnTestProgramStart(const UnitTest& /* unit_test */) override {
1528 SendLn("event=TestProgramStart");
1529 }
1530
1531 void OnTestProgramEnd(const UnitTest& unit_test) override {
1532 // Note that Google Test current only report elapsed time for each
1533 // test iteration, not for the entire test program.
1534 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1535
1536 // Notify the streaming server to stop.
1537 socket_writer_->CloseConnection();
1538 }
1539
1540 void OnTestIterationStart(const UnitTest& /* unit_test */,
1541 int iteration) override {
1542 SendLn("event=TestIterationStart&iteration=" +
1543 StreamableToString(iteration));
1544 }
1545
1546 void OnTestIterationEnd(const UnitTest& unit_test,
1547 int /* iteration */) override {
1548 SendLn("event=TestIterationEnd&passed=" +
1549 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1550 StreamableToString(unit_test.elapsed_time()) + "ms");
1551 }
1552
1553 // Note that "event=TestCaseStart" is a wire format and has to remain
1554 // "case" for compatibility
1555 void OnTestCaseStart(const TestCase& test_case) override {
1556 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1557 }
1558
1559 // Note that "event=TestCaseEnd" is a wire format and has to remain
1560 // "case" for compatibility
1561 void OnTestCaseEnd(const TestCase& test_case) override {
1562 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
1563 "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
1564 "ms");
1565 }
1566
1567 void OnTestStart(const TestInfo& test_info) override {
1568 SendLn(std::string("event=TestStart&name=") + test_info.name());
1569 }
1570
1571 void OnTestEnd(const TestInfo& test_info) override {
1572 SendLn("event=TestEnd&passed=" +
1573 FormatBool((test_info.result())->Passed()) +
1574 "&elapsed_time=" +
1575 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1576 }
1577
1578 void OnTestPartResult(const TestPartResult& test_part_result) override {
1579 const char* file_name = test_part_result.file_name();
1580 if (file_name == nullptr) file_name = "";
1581 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1582 "&line=" + StreamableToString(test_part_result.line_number()) +
1583 "&message=" + UrlEncode(test_part_result.message()));
1584 }
1585
1586 private:
1587 // Sends the given message and a newline to the socket.
1588 void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1589
1590 // Called at the start of streaming to notify the receiver what
1591 // protocol we are using.
1592 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1593
1594 std::string FormatBool(bool value) { return value ? "1" : "0"; }
1595
1596 const std::unique_ptr<AbstractSocketWriter> socket_writer_;
1597
1598 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1599 }; // class StreamingListener
1600
1601 #endif // GTEST_CAN_STREAM_RESULTS_
1602
1603 } // namespace internal
1604 } // namespace testing
1605
1606 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1607
1608 #endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
1609
1610 #if GTEST_OS_WINDOWS
1611 # define vsnprintf _vsnprintf
1612 #endif // GTEST_OS_WINDOWS
1613
1614 #if GTEST_OS_MAC
1615 #ifndef GTEST_OS_IOS
1616 #include <crt_externs.h>
1617 #endif
1618 #endif
1619
1620 #if GTEST_HAS_ABSL
1621 #include "absl/debugging/failure_signal_handler.h"
1622 #include "absl/debugging/stacktrace.h"
1623 #include "absl/debugging/symbolize.h"
1624 #include "absl/strings/str_cat.h"
1625 #endif // GTEST_HAS_ABSL
1626
1627 namespace testing {
1628
1629 using internal::CountIf;
1630 using internal::ForEach;
1631 using internal::GetElementOr;
1632 using internal::Shuffle;
1633
1634 // Constants.
1635
1636 // A test whose test suite name or test name matches this filter is
1637 // disabled and not run.
1638 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1639
1640 // A test suite whose name matches this filter is considered a death
1641 // test suite and will be run before test suites whose name doesn't
1642 // match this filter.
1643 static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
1644
1645 // A test filter that matches everything.
1646 static const char kUniversalFilter[] = "*";
1647
1648 // The default output format.
1649 static const char kDefaultOutputFormat[] = "xml";
1650 // The default output file.
1651 static const char kDefaultOutputFile[] = "test_detail";
1652
1653 // The environment variable name for the test shard index.
1654 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1655 // The environment variable name for the total number of test shards.
1656 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1657 // The environment variable name for the test shard status file.
1658 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1659
1660 namespace internal {
1661
1662 // The text used in failure messages to indicate the start of the
1663 // stack trace.
1664 const char kStackTraceMarker[] = "\nStack trace:\n";
1665
1666 // g_help_flag is true if and only if the --help flag or an equivalent form
1667 // is specified on the command line.
1668 bool g_help_flag = false;
1669
1670 // Utilty function to Open File for Writing
1671 static FILE* OpenFileForWriting(const std::string& output_file) {
1672 FILE* fileout = nullptr;
1673 FilePath output_file_path(output_file);
1674 FilePath output_dir(output_file_path.RemoveFileName());
1675
1676 if (output_dir.CreateDirectoriesRecursively()) {
1677 fileout = posix::FOpen(output_file.c_str(), "w");
1678 }
1679 if (fileout == nullptr) {
1680 GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
1681 }
1682 return fileout;
1683 }
1684
1685 } // namespace internal
1686
1687 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
1688 // environment variable.
1689 static const char* GetDefaultFilter() {
1690 const char* const testbridge_test_only =
1691 internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
1692 if (testbridge_test_only != nullptr) {
1693 return testbridge_test_only;
1694 }
1695 return kUniversalFilter;
1696 }
1697
1698 // Bazel passes in the argument to '--test_runner_fail_fast' via the
1699 // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
1700 static bool GetDefaultFailFast() {
1701 const char* const testbridge_test_runner_fail_fast =
1702 internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
1703 if (testbridge_test_runner_fail_fast != nullptr) {
1704 return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
1705 }
1706 return false;
1707 }
1708
1709 GTEST_DEFINE_bool_(
1710 fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
1711 "True if and only if a test failure should stop further test execution.");
1712
1713 GTEST_DEFINE_bool_(
1714 also_run_disabled_tests,
1715 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1716 "Run disabled tests too, in addition to the tests normally being run.");
1717
1718 GTEST_DEFINE_bool_(
1719 break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
1720 "True if and only if a failed assertion should be a debugger "
1721 "break-point.");
1722
1723 GTEST_DEFINE_bool_(catch_exceptions,
1724 internal::BoolFromGTestEnv("catch_exceptions", true),
1725 "True if and only if " GTEST_NAME_
1726 " should catch exceptions and treat them as test failures.");
1727
1728 GTEST_DEFINE_string_(
1729 color,
1730 internal::StringFromGTestEnv("color", "auto"),
1731 "Whether to use colors in the output. Valid values: yes, no, "
1732 "and auto. 'auto' means to use colors if the output is "
1733 "being sent to a terminal and the TERM environment variable "
1734 "is set to a terminal type that supports colors.");
1735
1736 GTEST_DEFINE_string_(
1737 filter,
1738 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1739 "A colon-separated list of glob (not regex) patterns "
1740 "for filtering the tests to run, optionally followed by a "
1741 "'-' and a : separated list of negative patterns (tests to "
1742 "exclude). A test is run if it matches one of the positive "
1743 "patterns and does not match any of the negative patterns.");
1744
1745 GTEST_DEFINE_bool_(
1746 install_failure_signal_handler,
1747 internal::BoolFromGTestEnv("install_failure_signal_handler", false),
1748 "If true and supported on the current platform, " GTEST_NAME_ " should "
1749 "install a signal handler that dumps debugging information when fatal "
1750 "signals are raised.");
1751
1752 GTEST_DEFINE_bool_(list_tests, false,
1753 "List all tests without running them.");
1754
1755 // The net priority order after flag processing is thus:
1756 // --gtest_output command line flag
1757 // GTEST_OUTPUT environment variable
1758 // XML_OUTPUT_FILE environment variable
1759 // ''
1760 GTEST_DEFINE_string_(
1761 output,
1762 internal::StringFromGTestEnv("output",
1763 internal::OutputFlagAlsoCheckEnvVar().c_str()),
1764 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
1765 "optionally followed by a colon and an output file name or directory. "
1766 "A directory is indicated by a trailing pathname separator. "
1767 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1768 "If a directory is specified, output files will be created "
1769 "within that directory, with file-names based on the test "
1770 "executable's name and, if necessary, made unique by adding "
1771 "digits.");
1772
1773 GTEST_DEFINE_bool_(
1774 brief, internal::BoolFromGTestEnv("brief", false),
1775 "True if only test failures should be displayed in text output.");
1776
1777 GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
1778 "True if and only if " GTEST_NAME_
1779 " should display elapsed time in text output.");
1780
1781 GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true),
1782 "True if and only if " GTEST_NAME_
1783 " prints UTF8 characters as text.");
1784
1785 GTEST_DEFINE_int32_(
1786 random_seed,
1787 internal::Int32FromGTestEnv("random_seed", 0),
1788 "Random number seed to use when shuffling test orders. Must be in range "
1789 "[1, 99999], or 0 to use a seed based on the current time.");
1790
1791 GTEST_DEFINE_int32_(
1792 repeat,
1793 internal::Int32FromGTestEnv("repeat", 1),
1794 "How many times to repeat each test. Specify a negative number "
1795 "for repeating forever. Useful for shaking out flaky tests.");
1796
1797 GTEST_DEFINE_bool_(show_internal_stack_frames, false,
1798 "True if and only if " GTEST_NAME_
1799 " should include internal stack frames when "
1800 "printing test failure stack traces.");
1801
1802 GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
1803 "True if and only if " GTEST_NAME_
1804 " should randomize tests' order on every run.");
1805
1806 GTEST_DEFINE_int32_(
1807 stack_trace_depth,
1808 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1809 "The maximum number of stack frames to print when an "
1810 "assertion fails. The valid range is 0 through 100, inclusive.");
1811
1812 GTEST_DEFINE_string_(
1813 stream_result_to,
1814 internal::StringFromGTestEnv("stream_result_to", ""),
1815 "This flag specifies the host name and the port number on which to stream "
1816 "test results. Example: \"localhost:555\". The flag is effective only on "
1817 "Linux.");
1818
1819 GTEST_DEFINE_bool_(
1820 throw_on_failure,
1821 internal::BoolFromGTestEnv("throw_on_failure", false),
1822 "When this flag is specified, a failed assertion will throw an exception "
1823 "if exceptions are enabled or exit the program with a non-zero code "
1824 "otherwise. For use with an external test framework.");
1825
1826 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1827 GTEST_DEFINE_string_(
1828 flagfile,
1829 internal::StringFromGTestEnv("flagfile", ""),
1830 "This flag specifies the flagfile to read command-line flags from.");
1831 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
1832
1833 namespace internal {
1834
1835 // Generates a random number from [0, range), using a Linear
1836 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1837 // than kMaxRange.
1838 uint32_t Random::Generate(uint32_t range) {
1839 // These constants are the same as are used in glibc's rand(3).
1840 // Use wider types than necessary to prevent unsigned overflow diagnostics.
1841 state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange;
1842
1843 GTEST_CHECK_(range > 0)
1844 << "Cannot generate a number in the range [0, 0).";
1845 GTEST_CHECK_(range <= kMaxRange)
1846 << "Generation of a number in [0, " << range << ") was requested, "
1847 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1848
1849 // Converting via modulus introduces a bit of downward bias, but
1850 // it's simple, and a linear congruential generator isn't too good
1851 // to begin with.
1852 return state_ % range;
1853 }
1854
1855 // GTestIsInitialized() returns true if and only if the user has initialized
1856 // Google Test. Useful for catching the user mistake of not initializing
1857 // Google Test before calling RUN_ALL_TESTS().
1858 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1859
1860 // Iterates over a vector of TestSuites, keeping a running sum of the
1861 // results of calling a given int-returning method on each.
1862 // Returns the sum.
1863 static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
1864 int (TestSuite::*method)() const) {
1865 int sum = 0;
1866 for (size_t i = 0; i < case_list.size(); i++) {
1867 sum += (case_list[i]->*method)();
1868 }
1869 return sum;
1870 }
1871
1872 // Returns true if and only if the test suite passed.
1873 static bool TestSuitePassed(const TestSuite* test_suite) {
1874 return test_suite->should_run() && test_suite->Passed();
1875 }
1876
1877 // Returns true if and only if the test suite failed.
1878 static bool TestSuiteFailed(const TestSuite* test_suite) {
1879 return test_suite->should_run() && test_suite->Failed();
1880 }
1881
1882 // Returns true if and only if test_suite contains at least one test that
1883 // should run.
1884 static bool ShouldRunTestSuite(const TestSuite* test_suite) {
1885 return test_suite->should_run();
1886 }
1887
1888 // AssertHelper constructor.
1889 AssertHelper::AssertHelper(TestPartResult::Type type,
1890 const char* file,
1891 int line,
1892 const char* message)
1893 : data_(new AssertHelperData(type, file, line, message)) {
1894 }
1895
1896 AssertHelper::~AssertHelper() {
1897 delete data_;
1898 }
1899
1900 // Message assignment, for assertion streaming support.
1901 void AssertHelper::operator=(const Message& message) const {
1902 UnitTest::GetInstance()->
1903 AddTestPartResult(data_->type, data_->file, data_->line,
1904 AppendUserMessage(data_->message, message),
1905 UnitTest::GetInstance()->impl()
1906 ->CurrentOsStackTraceExceptTop(1)
1907 // Skips the stack frame for this function itself.
1908 ); // NOLINT
1909 }
1910
1911 namespace {
1912
1913 // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
1914 // to creates test cases for it, a syntetic test case is
1915 // inserted to report ether an error or a log message.
1916 //
1917 // This configuration bit will likely be removed at some point.
1918 constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
1919 constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
1920
1921 // A test that fails at a given file/line location with a given message.
1922 class FailureTest : public Test {
1923 public:
1924 explicit FailureTest(const CodeLocation& loc, std::string error_message,
1925 bool as_error)
1926 : loc_(loc),
1927 error_message_(std::move(error_message)),
1928 as_error_(as_error) {}
1929
1930 void TestBody() override {
1931 if (as_error_) {
1932 AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
1933 loc_.line, "") = Message() << error_message_;
1934 } else {
1935 std::cout << error_message_ << std::endl;
1936 }
1937 }
1938
1939 private:
1940 const CodeLocation loc_;
1941 const std::string error_message_;
1942 const bool as_error_;
1943 };
1944
1945
1946 } // namespace
1947
1948 std::set<std::string>* GetIgnoredParameterizedTestSuites() {
1949 return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
1950 }
1951
1952 // Add a given test_suit to the list of them allow to go un-instantiated.
1953 MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
1954 GetIgnoredParameterizedTestSuites()->insert(test_suite);
1955 }
1956
1957 // If this parameterized test suite has no instantiations (and that
1958 // has not been marked as okay), emit a test case reporting that.
1959 void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
1960 bool has_test_p) {
1961 const auto& ignored = *GetIgnoredParameterizedTestSuites();
1962 if (ignored.find(name) != ignored.end()) return;
1963
1964 const char kMissingInstantiation[] = //
1965 " is defined via TEST_P, but never instantiated. None of the test cases "
1966 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
1967 "ones provided expand to nothing."
1968 "\n\n"
1969 "Ideally, TEST_P definitions should only ever be included as part of "
1970 "binaries that intend to use them. (As opposed to, for example, being "
1971 "placed in a library that may be linked in to get other utilities.)";
1972
1973 const char kMissingTestCase[] = //
1974 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
1975 "defined via TEST_P . No test cases will run."
1976 "\n\n"
1977 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
1978 "code that always depend on code that provides TEST_P. Failing to do "
1979 "so is often an indication of dead code, e.g. the last TEST_P was "
1980 "removed but the rest got left behind.";
1981
1982 std::string message =
1983 "Parameterized test suite " + name +
1984 (has_test_p ? kMissingInstantiation : kMissingTestCase) +
1985 "\n\n"
1986 "To suppress this error for this test suite, insert the following line "
1987 "(in a non-header) in the namespace it is defined in:"
1988 "\n\n"
1989 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
1990
1991 std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
1992 RegisterTest( //
1993 "GoogleTestVerification", full_name.c_str(),
1994 nullptr, // No type parameter.
1995 nullptr, // No value parameter.
1996 location.file.c_str(), location.line, [message, location] {
1997 return new FailureTest(location, message,
1998 kErrorOnUninstantiatedParameterizedTest);
1999 });
2000 }
2001
2002 void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
2003 CodeLocation code_location) {
2004 GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
2005 test_suite_name, code_location);
2006 }
2007
2008 void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
2009 GetUnitTestImpl()
2010 ->type_parameterized_test_registry()
2011 .RegisterInstantiation(case_name);
2012 }
2013
2014 void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
2015 const char* test_suite_name, CodeLocation code_location) {
2016 suites_.emplace(std::string(test_suite_name),
2017 TypeParameterizedTestSuiteInfo(code_location));
2018 }
2019
2020 void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
2021 const char* test_suite_name) {
2022 auto it = suites_.find(std::string(test_suite_name));
2023 if (it != suites_.end()) {
2024 it->second.instantiated = true;
2025 } else {
2026 GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
2027 << test_suite_name << "'";
2028 }
2029 }
2030
2031 void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
2032 const auto& ignored = *GetIgnoredParameterizedTestSuites();
2033 for (const auto& testcase : suites_) {
2034 if (testcase.second.instantiated) continue;
2035 if (ignored.find(testcase.first) != ignored.end()) continue;
2036
2037 std::string message =
2038 "Type parameterized test suite " + testcase.first +
2039 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
2040 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
2041 "\n\n"
2042 "Ideally, TYPED_TEST_P definitions should only ever be included as "
2043 "part of binaries that intend to use them. (As opposed to, for "
2044 "example, being placed in a library that may be linked in to get other "
2045 "utilities.)"
2046 "\n\n"
2047 "To suppress this error for this test suite, insert the following line "
2048 "(in a non-header) in the namespace it is defined in:"
2049 "\n\n"
2050 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
2051 testcase.first + ");";
2052
2053 std::string full_name =
2054 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
2055 RegisterTest( //
2056 "GoogleTestVerification", full_name.c_str(),
2057 nullptr, // No type parameter.
2058 nullptr, // No value parameter.
2059 testcase.second.code_location.file.c_str(),
2060 testcase.second.code_location.line, [message, testcase] {
2061 return new FailureTest(testcase.second.code_location, message,
2062 kErrorOnUninstantiatedTypeParameterizedTest);
2063 });
2064 }
2065 }
2066
2067 // A copy of all command line arguments. Set by InitGoogleTest().
2068 static ::std::vector<std::string> g_argvs;
2069
2070 ::std::vector<std::string> GetArgvs() {
2071 #if defined(GTEST_CUSTOM_GET_ARGVS_)
2072 // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
2073 // ::string. This code converts it to the appropriate type.
2074 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
2075 return ::std::vector<std::string>(custom.begin(), custom.end());
2076 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
2077 return g_argvs;
2078 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
2079 }
2080
2081 // Returns the current application's name, removing directory path if that
2082 // is present.
2083 FilePath GetCurrentExecutableName() {
2084 FilePath result;
2085
2086 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
2087 result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
2088 #else
2089 result.Set(FilePath(GetArgvs()[0]));
2090 #endif // GTEST_OS_WINDOWS
2091
2092 return result.RemoveDirectoryName();
2093 }
2094
2095 // Functions for processing the gtest_output flag.
2096
2097 // Returns the output format, or "" for normal printed output.
2098 std::string UnitTestOptions::GetOutputFormat() {
2099 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
2100 const char* const colon = strchr(gtest_output_flag, ':');
2101 return (colon == nullptr)
2102 ? std::string(gtest_output_flag)
2103 : std::string(gtest_output_flag,
2104 static_cast<size_t>(colon - gtest_output_flag));
2105 }
2106
2107 // Returns the name of the requested output file, or the default if none
2108 // was explicitly specified.
2109 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
2110 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
2111
2112 std::string format = GetOutputFormat();
2113 if (format.empty())
2114 format = std::string(kDefaultOutputFormat);
2115
2116 const char* const colon = strchr(gtest_output_flag, ':');
2117 if (colon == nullptr)
2118 return internal::FilePath::MakeFileName(
2119 internal::FilePath(
2120 UnitTest::GetInstance()->original_working_dir()),
2121 internal::FilePath(kDefaultOutputFile), 0,
2122 format.c_str()).string();
2123
2124 internal::FilePath output_name(colon + 1);
2125 if (!output_name.IsAbsolutePath())
2126 output_name = internal::FilePath::ConcatPaths(
2127 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
2128 internal::FilePath(colon + 1));
2129
2130 if (!output_name.IsDirectory())
2131 return output_name.string();
2132
2133 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
2134 output_name, internal::GetCurrentExecutableName(),
2135 GetOutputFormat().c_str()));
2136 return result.string();
2137 }
2138
2139 // Returns true if and only if the wildcard pattern matches the string. Each
2140 // pattern consists of regular characters, single-character wildcards (?), and
2141 // multi-character wildcards (*).
2142 //
2143 // This function implements a linear-time string globbing algorithm based on
2144 // https://research.swtch.com/glob.
2145 static bool PatternMatchesString(const std::string& name_str,
2146 const char* pattern, const char* pattern_end) {
2147 const char* name = name_str.c_str();
2148 const char* const name_begin = name;
2149 const char* const name_end = name + name_str.size();
2150
2151 const char* pattern_next = pattern;
2152 const char* name_next = name;
2153
2154 while (pattern < pattern_end || name < name_end) {
2155 if (pattern < pattern_end) {
2156 switch (*pattern) {
2157 default: // Match an ordinary character.
2158 if (name < name_end && *name == *pattern) {
2159 ++pattern;
2160 ++name;
2161 continue;
2162 }
2163 break;
2164 case '?': // Match any single character.
2165 if (name < name_end) {
2166 ++pattern;
2167 ++name;
2168 continue;
2169 }
2170 break;
2171 case '*':
2172 // Match zero or more characters. Start by skipping over the wildcard
2173 // and matching zero characters from name. If that fails, restart and
2174 // match one more character than the last attempt.
2175 pattern_next = pattern;
2176 name_next = name + 1;
2177 ++pattern;
2178 continue;
2179 }
2180 }
2181 // Failed to match a character. Restart if possible.
2182 if (name_begin < name_next && name_next <= name_end) {
2183 pattern = pattern_next;
2184 name = name_next;
2185 continue;
2186 }
2187 return false;
2188 }
2189 return true;
2190 }
2191
2192 bool UnitTestOptions::MatchesFilter(const std::string& name_str,
2193 const char* filter) {
2194 // The filter is a list of patterns separated by colons (:).
2195 const char* pattern = filter;
2196 while (true) {
2197 // Find the bounds of this pattern.
2198 const char* const next_sep = strchr(pattern, ':');
2199 const char* const pattern_end =
2200 next_sep != nullptr ? next_sep : pattern + strlen(pattern);
2201
2202 // Check if this pattern matches name_str.
2203 if (PatternMatchesString(name_str, pattern, pattern_end)) {
2204 return true;
2205 }
2206
2207 // Give up on this pattern. However, if we found a pattern separator (:),
2208 // advance to the next pattern (skipping over the separator) and restart.
2209 if (next_sep == nullptr) {
2210 return false;
2211 }
2212 pattern = next_sep + 1;
2213 }
2214 return true;
2215 }
2216
2217 // Returns true if and only if the user-specified filter matches the test
2218 // suite name and the test name.
2219 bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
2220 const std::string& test_name) {
2221 const std::string& full_name = test_suite_name + "." + test_name.c_str();
2222
2223 // Split --gtest_filter at '-', if there is one, to separate into
2224 // positive filter and negative filter portions
2225 const char* const p = GTEST_FLAG(filter).c_str();
2226 const char* const dash = strchr(p, '-');
2227 std::string positive;
2228 std::string negative;
2229 if (dash == nullptr) {
2230 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
2231 negative = "";
2232 } else {
2233 positive = std::string(p, dash); // Everything up to the dash
2234 negative = std::string(dash + 1); // Everything after the dash
2235 if (positive.empty()) {
2236 // Treat '-test1' as the same as '*-test1'
2237 positive = kUniversalFilter;
2238 }
2239 }
2240
2241 // A filter is a colon-separated list of patterns. It matches a
2242 // test if any pattern in it matches the test.
2243 return (MatchesFilter(full_name, positive.c_str()) &&
2244 !MatchesFilter(full_name, negative.c_str()));
2245 }
2246
2247 #if GTEST_HAS_SEH
2248 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
2249 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
2250 // This function is useful as an __except condition.
2251 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2252 // Google Test should handle a SEH exception if:
2253 // 1. the user wants it to, AND
2254 // 2. this is not a breakpoint exception, AND
2255 // 3. this is not a C++ exception (VC++ implements them via SEH,
2256 // apparently).
2257 //
2258 // SEH exception code for C++ exceptions.
2259 // (see http://support.microsoft.com/kb/185294 for more information).
2260 const DWORD kCxxExceptionCode = 0xe06d7363;
2261
2262 bool should_handle = true;
2263
2264 if (!GTEST_FLAG(catch_exceptions))
2265 should_handle = false;
2266 else if (exception_code == EXCEPTION_BREAKPOINT)
2267 should_handle = false;
2268 else if (exception_code == kCxxExceptionCode)
2269 should_handle = false;
2270
2271 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2272 }
2273 #endif // GTEST_HAS_SEH
2274
2275 } // namespace internal
2276
2277 // The c'tor sets this object as the test part result reporter used by
2278 // Google Test. The 'result' parameter specifies where to report the
2279 // results. Intercepts only failures from the current thread.
2280 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2281 TestPartResultArray* result)
2282 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2283 result_(result) {
2284 Init();
2285 }
2286
2287 // The c'tor sets this object as the test part result reporter used by
2288 // Google Test. The 'result' parameter specifies where to report the
2289 // results.
2290 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2291 InterceptMode intercept_mode, TestPartResultArray* result)
2292 : intercept_mode_(intercept_mode),
2293 result_(result) {
2294 Init();
2295 }
2296
2297 void ScopedFakeTestPartResultReporter::Init() {
2298 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2299 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2300 old_reporter_ = impl->GetGlobalTestPartResultReporter();
2301 impl->SetGlobalTestPartResultReporter(this);
2302 } else {
2303 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2304 impl->SetTestPartResultReporterForCurrentThread(this);
2305 }
2306 }
2307
2308 // The d'tor restores the test part result reporter used by Google Test
2309 // before.
2310 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2311 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2312 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2313 impl->SetGlobalTestPartResultReporter(old_reporter_);
2314 } else {
2315 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2316 }
2317 }
2318
2319 // Increments the test part result count and remembers the result.
2320 // This method is from the TestPartResultReporterInterface interface.
2321 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2322 const TestPartResult& result) {
2323 result_->Append(result);
2324 }
2325
2326 namespace internal {
2327
2328 // Returns the type ID of ::testing::Test. We should always call this
2329 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2330 // testing::Test. This is to work around a suspected linker bug when
2331 // using Google Test as a framework on Mac OS X. The bug causes
2332 // GetTypeId< ::testing::Test>() to return different values depending
2333 // on whether the call is from the Google Test framework itself or
2334 // from user test code. GetTestTypeId() is guaranteed to always
2335 // return the same value, as it always calls GetTypeId<>() from the
2336 // gtest.cc, which is within the Google Test framework.
2337 TypeId GetTestTypeId() {
2338 return GetTypeId<Test>();
2339 }
2340
2341 // The value of GetTestTypeId() as seen from within the Google Test
2342 // library. This is solely for testing GetTestTypeId().
2343 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2344
2345 // This predicate-formatter checks that 'results' contains a test part
2346 // failure of the given type and that the failure message contains the
2347 // given substring.
2348 static AssertionResult HasOneFailure(const char* /* results_expr */,
2349 const char* /* type_expr */,
2350 const char* /* substr_expr */,
2351 const TestPartResultArray& results,
2352 TestPartResult::Type type,
2353 const std::string& substr) {
2354 const std::string expected(type == TestPartResult::kFatalFailure ?
2355 "1 fatal failure" :
2356 "1 non-fatal failure");
2357 Message msg;
2358 if (results.size() != 1) {
2359 msg << "Expected: " << expected << "\n"
2360 << " Actual: " << results.size() << " failures";
2361 for (int i = 0; i < results.size(); i++) {
2362 msg << "\n" << results.GetTestPartResult(i);
2363 }
2364 return AssertionFailure() << msg;
2365 }
2366
2367 const TestPartResult& r = results.GetTestPartResult(0);
2368 if (r.type() != type) {
2369 return AssertionFailure() << "Expected: " << expected << "\n"
2370 << " Actual:\n"
2371 << r;
2372 }
2373
2374 if (strstr(r.message(), substr.c_str()) == nullptr) {
2375 return AssertionFailure() << "Expected: " << expected << " containing \""
2376 << substr << "\"\n"
2377 << " Actual:\n"
2378 << r;
2379 }
2380
2381 return AssertionSuccess();
2382 }
2383
2384 // The constructor of SingleFailureChecker remembers where to look up
2385 // test part results, what type of failure we expect, and what
2386 // substring the failure message should contain.
2387 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2388 TestPartResult::Type type,
2389 const std::string& substr)
2390 : results_(results), type_(type), substr_(substr) {}
2391
2392 // The destructor of SingleFailureChecker verifies that the given
2393 // TestPartResultArray contains exactly one failure that has the given
2394 // type and contains the given substring. If that's not the case, a
2395 // non-fatal failure will be generated.
2396 SingleFailureChecker::~SingleFailureChecker() {
2397 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2398 }
2399
2400 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2401 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2402
2403 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2404 const TestPartResult& result) {
2405 unit_test_->current_test_result()->AddTestPartResult(result);
2406 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2407 }
2408
2409 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2410 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2411
2412 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2413 const TestPartResult& result) {
2414 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2415 }
2416
2417 // Returns the global test part result reporter.
2418 TestPartResultReporterInterface*
2419 UnitTestImpl::GetGlobalTestPartResultReporter() {
2420 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2421 return global_test_part_result_repoter_;
2422 }
2423
2424 // Sets the global test part result reporter.
2425 void UnitTestImpl::SetGlobalTestPartResultReporter(
2426 TestPartResultReporterInterface* reporter) {
2427 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2428 global_test_part_result_repoter_ = reporter;
2429 }
2430
2431 // Returns the test part result reporter for the current thread.
2432 TestPartResultReporterInterface*
2433 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2434 return per_thread_test_part_result_reporter_.get();
2435 }
2436
2437 // Sets the test part result reporter for the current thread.
2438 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2439 TestPartResultReporterInterface* reporter) {
2440 per_thread_test_part_result_reporter_.set(reporter);
2441 }
2442
2443 // Gets the number of successful test suites.
2444 int UnitTestImpl::successful_test_suite_count() const {
2445 return CountIf(test_suites_, TestSuitePassed);
2446 }
2447
2448 // Gets the number of failed test suites.
2449 int UnitTestImpl::failed_test_suite_count() const {
2450 return CountIf(test_suites_, TestSuiteFailed);
2451 }
2452
2453 // Gets the number of all test suites.
2454 int UnitTestImpl::total_test_suite_count() const {
2455 return static_cast<int>(test_suites_.size());
2456 }
2457
2458 // Gets the number of all test suites that contain at least one test
2459 // that should run.
2460 int UnitTestImpl::test_suite_to_run_count() const {
2461 return CountIf(test_suites_, ShouldRunTestSuite);
2462 }
2463
2464 // Gets the number of successful tests.
2465 int UnitTestImpl::successful_test_count() const {
2466 return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
2467 }
2468
2469 // Gets the number of skipped tests.
2470 int UnitTestImpl::skipped_test_count() const {
2471 return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
2472 }
2473
2474 // Gets the number of failed tests.
2475 int UnitTestImpl::failed_test_count() const {
2476 return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
2477 }
2478
2479 // Gets the number of disabled tests that will be reported in the XML report.
2480 int UnitTestImpl::reportable_disabled_test_count() const {
2481 return SumOverTestSuiteList(test_suites_,
2482 &TestSuite::reportable_disabled_test_count);
2483 }
2484
2485 // Gets the number of disabled tests.
2486 int UnitTestImpl::disabled_test_count() const {
2487 return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
2488 }
2489
2490 // Gets the number of tests to be printed in the XML report.
2491 int UnitTestImpl::reportable_test_count() const {
2492 return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
2493 }
2494
2495 // Gets the number of all tests.
2496 int UnitTestImpl::total_test_count() const {
2497 return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
2498 }
2499
2500 // Gets the number of tests that should run.
2501 int UnitTestImpl::test_to_run_count() const {
2502 return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
2503 }
2504
2505 // Returns the current OS stack trace as an std::string.
2506 //
2507 // The maximum number of stack frames to be included is specified by
2508 // the gtest_stack_trace_depth flag. The skip_count parameter
2509 // specifies the number of top frames to be skipped, which doesn't
2510 // count against the number of frames to be included.
2511 //
2512 // For example, if Foo() calls Bar(), which in turn calls
2513 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2514 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2515 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2516 return os_stack_trace_getter()->CurrentStackTrace(
2517 static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2518 skip_count + 1
2519 // Skips the user-specified number of frames plus this function
2520 // itself.
2521 ); // NOLINT
2522 }
2523
2524 // A helper class for measuring elapsed times.
2525 class Timer {
2526 public:
2527 Timer() : start_(std::chrono::steady_clock::now()) {}
2528
2529 // Return time elapsed in milliseconds since the timer was created.
2530 TimeInMillis Elapsed() {
2531 return std::chrono::duration_cast<std::chrono::milliseconds>(
2532 std::chrono::steady_clock::now() - start_)
2533 .count();
2534 }
2535
2536 private:
2537 std::chrono::steady_clock::time_point start_;
2538 };
2539
2540 // Returns a timestamp as milliseconds since the epoch. Note this time may jump
2541 // around subject to adjustments by the system, to measure elapsed time use
2542 // Timer instead.
2543 TimeInMillis GetTimeInMillis() {
2544 return std::chrono::duration_cast<std::chrono::milliseconds>(
2545 std::chrono::system_clock::now() -
2546 std::chrono::system_clock::from_time_t(0))
2547 .count();
2548 }
2549
2550 // Utilities
2551
2552 // class String.
2553
2554 #if GTEST_OS_WINDOWS_MOBILE
2555 // Creates a UTF-16 wide string from the given ANSI string, allocating
2556 // memory using new. The caller is responsible for deleting the return
2557 // value using delete[]. Returns the wide string, or NULL if the
2558 // input is NULL.
2559 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2560 if (!ansi) return nullptr;
2561 const int length = strlen(ansi);
2562 const int unicode_length =
2563 MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
2564 WCHAR* unicode = new WCHAR[unicode_length + 1];
2565 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2566 unicode, unicode_length);
2567 unicode[unicode_length] = 0;
2568 return unicode;
2569 }
2570
2571 // Creates an ANSI string from the given wide string, allocating
2572 // memory using new. The caller is responsible for deleting the return
2573 // value using delete[]. Returns the ANSI string, or NULL if the
2574 // input is NULL.
2575 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2576 if (!utf16_str) return nullptr;
2577 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
2578 0, nullptr, nullptr);
2579 char* ansi = new char[ansi_length + 1];
2580 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
2581 nullptr);
2582 ansi[ansi_length] = 0;
2583 return ansi;
2584 }
2585
2586 #endif // GTEST_OS_WINDOWS_MOBILE
2587
2588 // Compares two C strings. Returns true if and only if they have the same
2589 // content.
2590 //
2591 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2592 // C string is considered different to any non-NULL C string,
2593 // including the empty string.
2594 bool String::CStringEquals(const char * lhs, const char * rhs) {
2595 if (lhs == nullptr) return rhs == nullptr;
2596
2597 if (rhs == nullptr) return false;
2598
2599 return strcmp(lhs, rhs) == 0;
2600 }
2601
2602 #if GTEST_HAS_STD_WSTRING
2603
2604 // Converts an array of wide chars to a narrow string using the UTF-8
2605 // encoding, and streams the result to the given Message object.
2606 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2607 Message* msg) {
2608 for (size_t i = 0; i != length; ) { // NOLINT
2609 if (wstr[i] != L'\0') {
2610 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2611 while (i != length && wstr[i] != L'\0')
2612 i++;
2613 } else {
2614 *msg << '\0';
2615 i++;
2616 }
2617 }
2618 }
2619
2620 #endif // GTEST_HAS_STD_WSTRING
2621
2622 void SplitString(const ::std::string& str, char delimiter,
2623 ::std::vector< ::std::string>* dest) {
2624 ::std::vector< ::std::string> parsed;
2625 ::std::string::size_type pos = 0;
2626 while (::testing::internal::AlwaysTrue()) {
2627 const ::std::string::size_type colon = str.find(delimiter, pos);
2628 if (colon == ::std::string::npos) {
2629 parsed.push_back(str.substr(pos));
2630 break;
2631 } else {
2632 parsed.push_back(str.substr(pos, colon - pos));
2633 pos = colon + 1;
2634 }
2635 }
2636 dest->swap(parsed);
2637 }
2638
2639 } // namespace internal
2640
2641 // Constructs an empty Message.
2642 // We allocate the stringstream separately because otherwise each use of
2643 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2644 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2645 // the stack space.
2646 Message::Message() : ss_(new ::std::stringstream) {
2647 // By default, we want there to be enough precision when printing
2648 // a double to a Message.
2649 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2650 }
2651
2652 // These two overloads allow streaming a wide C string to a Message
2653 // using the UTF-8 encoding.
2654 Message& Message::operator <<(const wchar_t* wide_c_str) {
2655 return *this << internal::String::ShowWideCString(wide_c_str);
2656 }
2657 Message& Message::operator <<(wchar_t* wide_c_str) {
2658 return *this << internal::String::ShowWideCString(wide_c_str);
2659 }
2660
2661 #if GTEST_HAS_STD_WSTRING
2662 // Converts the given wide string to a narrow string using the UTF-8
2663 // encoding, and streams the result to this Message object.
2664 Message& Message::operator <<(const ::std::wstring& wstr) {
2665 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2666 return *this;
2667 }
2668 #endif // GTEST_HAS_STD_WSTRING
2669
2670 // Gets the text streamed to this object so far as an std::string.
2671 // Each '\0' character in the buffer is replaced with "\\0".
2672 std::string Message::GetString() const {
2673 return internal::StringStreamToString(ss_.get());
2674 }
2675
2676 // AssertionResult constructors.
2677 // Used in EXPECT_TRUE/FALSE(assertion_result).
2678 AssertionResult::AssertionResult(const AssertionResult& other)
2679 : success_(other.success_),
2680 message_(other.message_.get() != nullptr
2681 ? new ::std::string(*other.message_)
2682 : static_cast< ::std::string*>(nullptr)) {}
2683
2684 // Swaps two AssertionResults.
2685 void AssertionResult::swap(AssertionResult& other) {
2686 using std::swap;
2687 swap(success_, other.success_);
2688 swap(message_, other.message_);
2689 }
2690
2691 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2692 AssertionResult AssertionResult::operator!() const {
2693 AssertionResult negation(!success_);
2694 if (message_.get() != nullptr) negation << *message_;
2695 return negation;
2696 }
2697
2698 // Makes a successful assertion result.
2699 AssertionResult AssertionSuccess() {
2700 return AssertionResult(true);
2701 }
2702
2703 // Makes a failed assertion result.
2704 AssertionResult AssertionFailure() {
2705 return AssertionResult(false);
2706 }
2707
2708 // Makes a failed assertion result with the given failure message.
2709 // Deprecated; use AssertionFailure() << message.
2710 AssertionResult AssertionFailure(const Message& message) {
2711 return AssertionFailure() << message;
2712 }
2713
2714 namespace internal {
2715
2716 namespace edit_distance {
2717 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2718 const std::vector<size_t>& right) {
2719 std::vector<std::vector<double> > costs(
2720 left.size() + 1, std::vector<double>(right.size() + 1));
2721 std::vector<std::vector<EditType> > best_move(
2722 left.size() + 1, std::vector<EditType>(right.size() + 1));
2723
2724 // Populate for empty right.
2725 for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2726 costs[l_i][0] = static_cast<double>(l_i);
2727 best_move[l_i][0] = kRemove;
2728 }
2729 // Populate for empty left.
2730 for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2731 costs[0][r_i] = static_cast<double>(r_i);
2732 best_move[0][r_i] = kAdd;
2733 }
2734
2735 for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2736 for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2737 if (left[l_i] == right[r_i]) {
2738 // Found a match. Consume it.
2739 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2740 best_move[l_i + 1][r_i + 1] = kMatch;
2741 continue;
2742 }
2743
2744 const double add = costs[l_i + 1][r_i];
2745 const double remove = costs[l_i][r_i + 1];
2746 const double replace = costs[l_i][r_i];
2747 if (add < remove && add < replace) {
2748 costs[l_i + 1][r_i + 1] = add + 1;
2749 best_move[l_i + 1][r_i + 1] = kAdd;
2750 } else if (remove < add && remove < replace) {
2751 costs[l_i + 1][r_i + 1] = remove + 1;
2752 best_move[l_i + 1][r_i + 1] = kRemove;
2753 } else {
2754 // We make replace a little more expensive than add/remove to lower
2755 // their priority.
2756 costs[l_i + 1][r_i + 1] = replace + 1.00001;
2757 best_move[l_i + 1][r_i + 1] = kReplace;
2758 }
2759 }
2760 }
2761
2762 // Reconstruct the best path. We do it in reverse order.
2763 std::vector<EditType> best_path;
2764 for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2765 EditType move = best_move[l_i][r_i];
2766 best_path.push_back(move);
2767 l_i -= move != kAdd;
2768 r_i -= move != kRemove;
2769 }
2770 std::reverse(best_path.begin(), best_path.end());
2771 return best_path;
2772 }
2773
2774 namespace {
2775
2776 // Helper class to convert string into ids with deduplication.
2777 class InternalStrings {
2778 public:
2779 size_t GetId(const std::string& str) {
2780 IdMap::iterator it = ids_.find(str);
2781 if (it != ids_.end()) return it->second;
2782 size_t id = ids_.size();
2783 return ids_[str] = id;
2784 }
2785
2786 private:
2787 typedef std::map<std::string, size_t> IdMap;
2788 IdMap ids_;
2789 };
2790
2791 } // namespace
2792
2793 std::vector<EditType> CalculateOptimalEdits(
2794 const std::vector<std::string>& left,
2795 const std::vector<std::string>& right) {
2796 std::vector<size_t> left_ids, right_ids;
2797 {
2798 InternalStrings intern_table;
2799 for (size_t i = 0; i < left.size(); ++i) {
2800 left_ids.push_back(intern_table.GetId(left[i]));
2801 }
2802 for (size_t i = 0; i < right.size(); ++i) {
2803 right_ids.push_back(intern_table.GetId(right[i]));
2804 }
2805 }
2806 return CalculateOptimalEdits(left_ids, right_ids);
2807 }
2808
2809 namespace {
2810
2811 // Helper class that holds the state for one hunk and prints it out to the
2812 // stream.
2813 // It reorders adds/removes when possible to group all removes before all
2814 // adds. It also adds the hunk header before printint into the stream.
2815 class Hunk {
2816 public:
2817 Hunk(size_t left_start, size_t right_start)
2818 : left_start_(left_start),
2819 right_start_(right_start),
2820 adds_(),
2821 removes_(),
2822 common_() {}
2823
2824 void PushLine(char edit, const char* line) {
2825 switch (edit) {
2826 case ' ':
2827 ++common_;
2828 FlushEdits();
2829 hunk_.push_back(std::make_pair(' ', line));
2830 break;
2831 case '-':
2832 ++removes_;
2833 hunk_removes_.push_back(std::make_pair('-', line));
2834 break;
2835 case '+':
2836 ++adds_;
2837 hunk_adds_.push_back(std::make_pair('+', line));
2838 break;
2839 }
2840 }
2841
2842 void PrintTo(std::ostream* os) {
2843 PrintHeader(os);
2844 FlushEdits();
2845 for (std::list<std::pair<char, const char*> >::const_iterator it =
2846 hunk_.begin();
2847 it != hunk_.end(); ++it) {
2848 *os << it->first << it->second << "\n";
2849 }
2850 }
2851
2852 bool has_edits() const { return adds_ || removes_; }
2853
2854 private:
2855 void FlushEdits() {
2856 hunk_.splice(hunk_.end(), hunk_removes_);
2857 hunk_.splice(hunk_.end(), hunk_adds_);
2858 }
2859
2860 // Print a unified diff header for one hunk.
2861 // The format is
2862 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2863 // where the left/right parts are omitted if unnecessary.
2864 void PrintHeader(std::ostream* ss) const {
2865 *ss << "@@ ";
2866 if (removes_) {
2867 *ss << "-" << left_start_ << "," << (removes_ + common_);
2868 }
2869 if (removes_ && adds_) {
2870 *ss << " ";
2871 }
2872 if (adds_) {
2873 *ss << "+" << right_start_ << "," << (adds_ + common_);
2874 }
2875 *ss << " @@\n";
2876 }
2877
2878 size_t left_start_, right_start_;
2879 size_t adds_, removes_, common_;
2880 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2881 };
2882
2883 } // namespace
2884
2885 // Create a list of diff hunks in Unified diff format.
2886 // Each hunk has a header generated by PrintHeader above plus a body with
2887 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
2888 // addition.
2889 // 'context' represents the desired unchanged prefix/suffix around the diff.
2890 // If two hunks are close enough that their contexts overlap, then they are
2891 // joined into one hunk.
2892 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2893 const std::vector<std::string>& right,
2894 size_t context) {
2895 const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2896
2897 size_t l_i = 0, r_i = 0, edit_i = 0;
2898 std::stringstream ss;
2899 while (edit_i < edits.size()) {
2900 // Find first edit.
2901 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2902 ++l_i;
2903 ++r_i;
2904 ++edit_i;
2905 }
2906
2907 // Find the first line to include in the hunk.
2908 const size_t prefix_context = std::min(l_i, context);
2909 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2910 for (size_t i = prefix_context; i > 0; --i) {
2911 hunk.PushLine(' ', left[l_i - i].c_str());
2912 }
2913
2914 // Iterate the edits until we found enough suffix for the hunk or the input
2915 // is over.
2916 size_t n_suffix = 0;
2917 for (; edit_i < edits.size(); ++edit_i) {
2918 if (n_suffix >= context) {
2919 // Continue only if the next hunk is very close.
2920 auto it = edits.begin() + static_cast<int>(edit_i);
2921 while (it != edits.end() && *it == kMatch) ++it;
2922 if (it == edits.end() ||
2923 static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
2924 // There is no next edit or it is too far away.
2925 break;
2926 }
2927 }
2928
2929 EditType edit = edits[edit_i];
2930 // Reset count when a non match is found.
2931 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2932
2933 if (edit == kMatch || edit == kRemove || edit == kReplace) {
2934 hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2935 }
2936 if (edit == kAdd || edit == kReplace) {
2937 hunk.PushLine('+', right[r_i].c_str());
2938 }
2939
2940 // Advance indices, depending on edit type.
2941 l_i += edit != kAdd;
2942 r_i += edit != kRemove;
2943 }
2944
2945 if (!hunk.has_edits()) {
2946 // We are done. We don't want this hunk.
2947 break;
2948 }
2949
2950 hunk.PrintTo(&ss);
2951 }
2952 return ss.str();
2953 }
2954
2955 } // namespace edit_distance
2956
2957 namespace {
2958
2959 // The string representation of the values received in EqFailure() are already
2960 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2961 // characters the same.
2962 std::vector<std::string> SplitEscapedString(const std::string& str) {
2963 std::vector<std::string> lines;
2964 size_t start = 0, end = str.size();
2965 if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2966 ++start;
2967 --end;
2968 }
2969 bool escaped = false;
2970 for (size_t i = start; i + 1 < end; ++i) {
2971 if (escaped) {
2972 escaped = false;
2973 if (str[i] == 'n') {
2974 lines.push_back(str.substr(start, i - start - 1));
2975 start = i + 1;
2976 }
2977 } else {
2978 escaped = str[i] == '\\';
2979 }
2980 }
2981 lines.push_back(str.substr(start, end - start));
2982 return lines;
2983 }
2984
2985 } // namespace
2986
2987 // Constructs and returns the message for an equality assertion
2988 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2989 //
2990 // The first four parameters are the expressions used in the assertion
2991 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2992 // where foo is 5 and bar is 6, we have:
2993 //
2994 // lhs_expression: "foo"
2995 // rhs_expression: "bar"
2996 // lhs_value: "5"
2997 // rhs_value: "6"
2998 //
2999 // The ignoring_case parameter is true if and only if the assertion is a
3000 // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
3001 // be inserted into the message.
3002 AssertionResult EqFailure(const char* lhs_expression,
3003 const char* rhs_expression,
3004 const std::string& lhs_value,
3005 const std::string& rhs_value,
3006 bool ignoring_case) {
3007 Message msg;
3008 msg << "Expected equality of these values:";
3009 msg << "\n " << lhs_expression;
3010 if (lhs_value != lhs_expression) {
3011 msg << "\n Which is: " << lhs_value;
3012 }
3013 msg << "\n " << rhs_expression;
3014 if (rhs_value != rhs_expression) {
3015 msg << "\n Which is: " << rhs_value;
3016 }
3017
3018 if (ignoring_case) {
3019 msg << "\nIgnoring case";
3020 }
3021
3022 if (!lhs_value.empty() && !rhs_value.empty()) {
3023 const std::vector<std::string> lhs_lines =
3024 SplitEscapedString(lhs_value);
3025 const std::vector<std::string> rhs_lines =
3026 SplitEscapedString(rhs_value);
3027 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
3028 msg << "\nWith diff:\n"
3029 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
3030 }
3031 }
3032
3033 return AssertionFailure() << msg;
3034 }
3035
3036 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
3037 std::string GetBoolAssertionFailureMessage(
3038 const AssertionResult& assertion_result,
3039 const char* expression_text,
3040 const char* actual_predicate_value,
3041 const char* expected_predicate_value) {
3042 const char* actual_message = assertion_result.message();
3043 Message msg;
3044 msg << "Value of: " << expression_text
3045 << "\n Actual: " << actual_predicate_value;
3046 if (actual_message[0] != '\0')
3047 msg << " (" << actual_message << ")";
3048 msg << "\nExpected: " << expected_predicate_value;
3049 return msg.GetString();
3050 }
3051
3052 // Helper function for implementing ASSERT_NEAR.
3053 AssertionResult DoubleNearPredFormat(const char* expr1,
3054 const char* expr2,
3055 const char* abs_error_expr,
3056 double val1,
3057 double val2,
3058 double abs_error) {
3059 const double diff = fabs(val1 - val2);
3060 if (diff <= abs_error) return AssertionSuccess();
3061
3062 // Find the value which is closest to zero.
3063 const double min_abs = std::min(fabs(val1), fabs(val2));
3064 // Find the distance to the next double from that value.
3065 const double epsilon =
3066 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
3067 // Detect the case where abs_error is so small that EXPECT_NEAR is
3068 // effectively the same as EXPECT_EQUAL, and give an informative error
3069 // message so that the situation can be more easily understood without
3070 // requiring exotic floating-point knowledge.
3071 // Don't do an epsilon check if abs_error is zero because that implies
3072 // that an equality check was actually intended.
3073 if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
3074 abs_error < epsilon) {
3075 return AssertionFailure()
3076 << "The difference between " << expr1 << " and " << expr2 << " is "
3077 << diff << ", where\n"
3078 << expr1 << " evaluates to " << val1 << ",\n"
3079 << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
3080 << abs_error_expr << " evaluates to " << abs_error
3081 << " which is smaller than the minimum distance between doubles for "
3082 "numbers of this magnitude which is "
3083 << epsilon
3084 << ", thus making this EXPECT_NEAR check equivalent to "
3085 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
3086 }
3087 return AssertionFailure()
3088 << "The difference between " << expr1 << " and " << expr2
3089 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
3090 << expr1 << " evaluates to " << val1 << ",\n"
3091 << expr2 << " evaluates to " << val2 << ", and\n"
3092 << abs_error_expr << " evaluates to " << abs_error << ".";
3093 }
3094
3095
3096 // Helper template for implementing FloatLE() and DoubleLE().
3097 template <typename RawType>
3098 AssertionResult FloatingPointLE(const char* expr1,
3099 const char* expr2,
3100 RawType val1,
3101 RawType val2) {
3102 // Returns success if val1 is less than val2,
3103 if (val1 < val2) {
3104 return AssertionSuccess();
3105 }
3106
3107 // or if val1 is almost equal to val2.
3108 const FloatingPoint<RawType> lhs(val1), rhs(val2);
3109 if (lhs.AlmostEquals(rhs)) {
3110 return AssertionSuccess();
3111 }
3112
3113 // Note that the above two checks will both fail if either val1 or
3114 // val2 is NaN, as the IEEE floating-point standard requires that
3115 // any predicate involving a NaN must return false.
3116
3117 ::std::stringstream val1_ss;
3118 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
3119 << val1;
3120
3121 ::std::stringstream val2_ss;
3122 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
3123 << val2;
3124
3125 return AssertionFailure()
3126 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
3127 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
3128 << StringStreamToString(&val2_ss);
3129 }
3130
3131 } // namespace internal
3132
3133 // Asserts that val1 is less than, or almost equal to, val2. Fails
3134 // otherwise. In particular, it fails if either val1 or val2 is NaN.
3135 AssertionResult FloatLE(const char* expr1, const char* expr2,
3136 float val1, float val2) {
3137 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
3138 }
3139
3140 // Asserts that val1 is less than, or almost equal to, val2. Fails
3141 // otherwise. In particular, it fails if either val1 or val2 is NaN.
3142 AssertionResult DoubleLE(const char* expr1, const char* expr2,
3143 double val1, double val2) {
3144 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
3145 }
3146
3147 namespace internal {
3148
3149 // The helper function for {ASSERT|EXPECT}_STREQ.
3150 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3151 const char* rhs_expression,
3152 const char* lhs,
3153 const char* rhs) {
3154 if (String::CStringEquals(lhs, rhs)) {
3155 return AssertionSuccess();
3156 }
3157
3158 return EqFailure(lhs_expression,
3159 rhs_expression,
3160 PrintToString(lhs),
3161 PrintToString(rhs),
3162 false);
3163 }
3164
3165 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
3166 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
3167 const char* rhs_expression,
3168 const char* lhs,
3169 const char* rhs) {
3170 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
3171 return AssertionSuccess();
3172 }
3173
3174 return EqFailure(lhs_expression,
3175 rhs_expression,
3176 PrintToString(lhs),
3177 PrintToString(rhs),
3178 true);
3179 }
3180
3181 // The helper function for {ASSERT|EXPECT}_STRNE.
3182 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3183 const char* s2_expression,
3184 const char* s1,
3185 const char* s2) {
3186 if (!String::CStringEquals(s1, s2)) {
3187 return AssertionSuccess();
3188 } else {
3189 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3190 << s2_expression << "), actual: \""
3191 << s1 << "\" vs \"" << s2 << "\"";
3192 }
3193 }
3194
3195 // The helper function for {ASSERT|EXPECT}_STRCASENE.
3196 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
3197 const char* s2_expression,
3198 const char* s1,
3199 const char* s2) {
3200 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3201 return AssertionSuccess();
3202 } else {
3203 return AssertionFailure()
3204 << "Expected: (" << s1_expression << ") != ("
3205 << s2_expression << ") (ignoring case), actual: \""
3206 << s1 << "\" vs \"" << s2 << "\"";
3207 }
3208 }
3209
3210 } // namespace internal
3211
3212 namespace {
3213
3214 // Helper functions for implementing IsSubString() and IsNotSubstring().
3215
3216 // This group of overloaded functions return true if and only if needle
3217 // is a substring of haystack. NULL is considered a substring of
3218 // itself only.
3219
3220 bool IsSubstringPred(const char* needle, const char* haystack) {
3221 if (needle == nullptr || haystack == nullptr) return needle == haystack;
3222
3223 return strstr(haystack, needle) != nullptr;
3224 }
3225
3226 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3227 if (needle == nullptr || haystack == nullptr) return needle == haystack;
3228
3229 return wcsstr(haystack, needle) != nullptr;
3230 }
3231
3232 // StringType here can be either ::std::string or ::std::wstring.
3233 template <typename StringType>
3234 bool IsSubstringPred(const StringType& needle,
3235 const StringType& haystack) {
3236 return haystack.find(needle) != StringType::npos;
3237 }
3238
3239 // This function implements either IsSubstring() or IsNotSubstring(),
3240 // depending on the value of the expected_to_be_substring parameter.
3241 // StringType here can be const char*, const wchar_t*, ::std::string,
3242 // or ::std::wstring.
3243 template <typename StringType>
3244 AssertionResult IsSubstringImpl(
3245 bool expected_to_be_substring,
3246 const char* needle_expr, const char* haystack_expr,
3247 const StringType& needle, const StringType& haystack) {
3248 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3249 return AssertionSuccess();
3250
3251 const bool is_wide_string = sizeof(needle[0]) > 1;
3252 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3253 return AssertionFailure()
3254 << "Value of: " << needle_expr << "\n"
3255 << " Actual: " << begin_string_quote << needle << "\"\n"
3256 << "Expected: " << (expected_to_be_substring ? "" : "not ")
3257 << "a substring of " << haystack_expr << "\n"
3258 << "Which is: " << begin_string_quote << haystack << "\"";
3259 }
3260
3261 } // namespace
3262
3263 // IsSubstring() and IsNotSubstring() check whether needle is a
3264 // substring of haystack (NULL is considered a substring of itself
3265 // only), and return an appropriate error message when they fail.
3266
3267 AssertionResult IsSubstring(
3268 const char* needle_expr, const char* haystack_expr,
3269 const char* needle, const char* haystack) {
3270 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3271 }
3272
3273 AssertionResult IsSubstring(
3274 const char* needle_expr, const char* haystack_expr,
3275 const wchar_t* needle, const wchar_t* haystack) {
3276 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3277 }
3278
3279 AssertionResult IsNotSubstring(
3280 const char* needle_expr, const char* haystack_expr,
3281 const char* needle, const char* haystack) {
3282 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3283 }
3284
3285 AssertionResult IsNotSubstring(
3286 const char* needle_expr, const char* haystack_expr,
3287 const wchar_t* needle, const wchar_t* haystack) {
3288 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3289 }
3290
3291 AssertionResult IsSubstring(
3292 const char* needle_expr, const char* haystack_expr,
3293 const ::std::string& needle, const ::std::string& haystack) {
3294 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3295 }
3296
3297 AssertionResult IsNotSubstring(
3298 const char* needle_expr, const char* haystack_expr,
3299 const ::std::string& needle, const ::std::string& haystack) {
3300 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3301 }
3302
3303 #if GTEST_HAS_STD_WSTRING
3304 AssertionResult IsSubstring(
3305 const char* needle_expr, const char* haystack_expr,
3306 const ::std::wstring& needle, const ::std::wstring& haystack) {
3307 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3308 }
3309
3310 AssertionResult IsNotSubstring(
3311 const char* needle_expr, const char* haystack_expr,
3312 const ::std::wstring& needle, const ::std::wstring& haystack) {
3313 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3314 }
3315 #endif // GTEST_HAS_STD_WSTRING
3316
3317 namespace internal {
3318
3319 #if GTEST_OS_WINDOWS
3320
3321 namespace {
3322
3323 // Helper function for IsHRESULT{SuccessFailure} predicates
3324 AssertionResult HRESULTFailureHelper(const char* expr,
3325 const char* expected,
3326 long hr) { // NOLINT
3327 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
3328
3329 // Windows CE doesn't support FormatMessage.
3330 const char error_text[] = "";
3331
3332 # else
3333
3334 // Looks up the human-readable system message for the HRESULT code
3335 // and since we're not passing any params to FormatMessage, we don't
3336 // want inserts expanded.
3337 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3338 FORMAT_MESSAGE_IGNORE_INSERTS;
3339 const DWORD kBufSize = 4096;
3340 // Gets the system's human readable message string for this HRESULT.
3341 char error_text[kBufSize] = { '\0' };
3342 DWORD message_length = ::FormatMessageA(kFlags,
3343 0, // no source, we're asking system
3344 static_cast<DWORD>(hr), // the error
3345 0, // no line width restrictions
3346 error_text, // output buffer
3347 kBufSize, // buf size
3348 nullptr); // no arguments for inserts
3349 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3350 for (; message_length && IsSpace(error_text[message_length - 1]);
3351 --message_length) {
3352 error_text[message_length - 1] = '\0';
3353 }
3354
3355 # endif // GTEST_OS_WINDOWS_MOBILE
3356
3357 const std::string error_hex("0x" + String::FormatHexInt(hr));
3358 return ::testing::AssertionFailure()
3359 << "Expected: " << expr << " " << expected << ".\n"
3360 << " Actual: " << error_hex << " " << error_text << "\n";
3361 }
3362
3363 } // namespace
3364
3365 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
3366 if (SUCCEEDED(hr)) {
3367 return AssertionSuccess();
3368 }
3369 return HRESULTFailureHelper(expr, "succeeds", hr);
3370 }
3371
3372 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
3373 if (FAILED(hr)) {
3374 return AssertionSuccess();
3375 }
3376 return HRESULTFailureHelper(expr, "fails", hr);
3377 }
3378
3379 #endif // GTEST_OS_WINDOWS
3380
3381 // Utility functions for encoding Unicode text (wide strings) in
3382 // UTF-8.
3383
3384 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
3385 // like this:
3386 //
3387 // Code-point length Encoding
3388 // 0 - 7 bits 0xxxxxxx
3389 // 8 - 11 bits 110xxxxx 10xxxxxx
3390 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
3391 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3392
3393 // The maximum code-point a one-byte UTF-8 sequence can represent.
3394 constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
3395
3396 // The maximum code-point a two-byte UTF-8 sequence can represent.
3397 constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
3398
3399 // The maximum code-point a three-byte UTF-8 sequence can represent.
3400 constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1;
3401
3402 // The maximum code-point a four-byte UTF-8 sequence can represent.
3403 constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1;
3404
3405 // Chops off the n lowest bits from a bit pattern. Returns the n
3406 // lowest bits. As a side effect, the original bit pattern will be
3407 // shifted to the right by n bits.
3408 inline uint32_t ChopLowBits(uint32_t* bits, int n) {
3409 const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
3410 *bits >>= n;
3411 return low_bits;
3412 }
3413
3414 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
3415 // code_point parameter is of type uint32_t because wchar_t may not be
3416 // wide enough to contain a code point.
3417 // If the code_point is not a valid Unicode code point
3418 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3419 // to "(Invalid Unicode 0xXXXXXXXX)".
3420 std::string CodePointToUtf8(uint32_t code_point) {
3421 if (code_point > kMaxCodePoint4) {
3422 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
3423 }
3424
3425 char str[5]; // Big enough for the largest valid code point.
3426 if (code_point <= kMaxCodePoint1) {
3427 str[1] = '\0';
3428 str[0] = static_cast<char>(code_point); // 0xxxxxxx
3429 } else if (code_point <= kMaxCodePoint2) {
3430 str[2] = '\0';
3431 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3432 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
3433 } else if (code_point <= kMaxCodePoint3) {
3434 str[3] = '\0';
3435 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3436 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3437 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
3438 } else { // code_point <= kMaxCodePoint4
3439 str[4] = '\0';
3440 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3441 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3442 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3443 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
3444 }
3445 return str;
3446 }
3447
3448 // The following two functions only make sense if the system
3449 // uses UTF-16 for wide string encoding. All supported systems
3450 // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
3451
3452 // Determines if the arguments constitute UTF-16 surrogate pair
3453 // and thus should be combined into a single Unicode code point
3454 // using CreateCodePointFromUtf16SurrogatePair.
3455 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3456 return sizeof(wchar_t) == 2 &&
3457 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3458 }
3459
3460 // Creates a Unicode code point from UTF16 surrogate pair.
3461 inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3462 wchar_t second) {
3463 const auto first_u = static_cast<uint32_t>(first);
3464 const auto second_u = static_cast<uint32_t>(second);
3465 const uint32_t mask = (1 << 10) - 1;
3466 return (sizeof(wchar_t) == 2)
3467 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
3468 :
3469 // This function should not be called when the condition is
3470 // false, but we provide a sensible default in case it is.
3471 first_u;
3472 }
3473
3474 // Converts a wide string to a narrow string in UTF-8 encoding.
3475 // The wide string is assumed to have the following encoding:
3476 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
3477 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3478 // Parameter str points to a null-terminated wide string.
3479 // Parameter num_chars may additionally limit the number
3480 // of wchar_t characters processed. -1 is used when the entire string
3481 // should be processed.
3482 // If the string contains code points that are not valid Unicode code points
3483 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3484 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3485 // and contains invalid UTF-16 surrogate pairs, values in those pairs
3486 // will be encoded as individual Unicode characters from Basic Normal Plane.
3487 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3488 if (num_chars == -1)
3489 num_chars = static_cast<int>(wcslen(str));
3490
3491 ::std::stringstream stream;
3492 for (int i = 0; i < num_chars; ++i) {
3493 uint32_t unicode_code_point;
3494
3495 if (str[i] == L'\0') {
3496 break;
3497 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3498 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3499 str[i + 1]);
3500 i++;
3501 } else {
3502 unicode_code_point = static_cast<uint32_t>(str[i]);
3503 }
3504
3505 stream << CodePointToUtf8(unicode_code_point);
3506 }
3507 return StringStreamToString(&stream);
3508 }
3509
3510 // Converts a wide C string to an std::string using the UTF-8 encoding.
3511 // NULL will be converted to "(null)".
3512 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3513 if (wide_c_str == nullptr) return "(null)";
3514
3515 return internal::WideStringToUtf8(wide_c_str, -1);
3516 }
3517
3518 // Compares two wide C strings. Returns true if and only if they have the
3519 // same content.
3520 //
3521 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3522 // C string is considered different to any non-NULL C string,
3523 // including the empty string.
3524 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3525 if (lhs == nullptr) return rhs == nullptr;
3526
3527 if (rhs == nullptr) return false;
3528
3529 return wcscmp(lhs, rhs) == 0;
3530 }
3531
3532 // Helper function for *_STREQ on wide strings.
3533 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3534 const char* rhs_expression,
3535 const wchar_t* lhs,
3536 const wchar_t* rhs) {
3537 if (String::WideCStringEquals(lhs, rhs)) {
3538 return AssertionSuccess();
3539 }
3540
3541 return EqFailure(lhs_expression,
3542 rhs_expression,
3543 PrintToString(lhs),
3544 PrintToString(rhs),
3545 false);
3546 }
3547
3548 // Helper function for *_STRNE on wide strings.
3549 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3550 const char* s2_expression,
3551 const wchar_t* s1,
3552 const wchar_t* s2) {
3553 if (!String::WideCStringEquals(s1, s2)) {
3554 return AssertionSuccess();
3555 }
3556
3557 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3558 << s2_expression << "), actual: "
3559 << PrintToString(s1)
3560 << " vs " << PrintToString(s2);
3561 }
3562
3563 // Compares two C strings, ignoring case. Returns true if and only if they have
3564 // the same content.
3565 //
3566 // Unlike strcasecmp(), this function can handle NULL argument(s). A
3567 // NULL C string is considered different to any non-NULL C string,
3568 // including the empty string.
3569 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3570 if (lhs == nullptr) return rhs == nullptr;
3571 if (rhs == nullptr) return false;
3572 return posix::StrCaseCmp(lhs, rhs) == 0;
3573 }
3574
3575 // Compares two wide C strings, ignoring case. Returns true if and only if they
3576 // have the same content.
3577 //
3578 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3579 // A NULL C string is considered different to any non-NULL wide C string,
3580 // including the empty string.
3581 // NB: The implementations on different platforms slightly differ.
3582 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3583 // environment variable. On GNU platform this method uses wcscasecmp
3584 // which compares according to LC_CTYPE category of the current locale.
3585 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3586 // current locale.
3587 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3588 const wchar_t* rhs) {
3589 if (lhs == nullptr) return rhs == nullptr;
3590
3591 if (rhs == nullptr) return false;
3592
3593 #if GTEST_OS_WINDOWS
3594 return _wcsicmp(lhs, rhs) == 0;
3595 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3596 return wcscasecmp(lhs, rhs) == 0;
3597 #else
3598 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3599 // Other unknown OSes may not define it either.
3600 wint_t left, right;
3601 do {
3602 left = towlower(static_cast<wint_t>(*lhs++));
3603 right = towlower(static_cast<wint_t>(*rhs++));
3604 } while (left && left == right);
3605 return left == right;
3606 #endif // OS selector
3607 }
3608
3609 // Returns true if and only if str ends with the given suffix, ignoring case.
3610 // Any string is considered to end with an empty suffix.
3611 bool String::EndsWithCaseInsensitive(
3612 const std::string& str, const std::string& suffix) {
3613 const size_t str_len = str.length();
3614 const size_t suffix_len = suffix.length();
3615 return (str_len >= suffix_len) &&
3616 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3617 suffix.c_str());
3618 }
3619
3620 // Formats an int value as "%02d".
3621 std::string String::FormatIntWidth2(int value) {
3622 return FormatIntWidthN(value, 2);
3623 }
3624
3625 // Formats an int value to given width with leading zeros.
3626 std::string String::FormatIntWidthN(int value, int width) {
3627 std::stringstream ss;
3628 ss << std::setfill('0') << std::setw(width) << value;
3629 return ss.str();
3630 }
3631
3632 // Formats an int value as "%X".
3633 std::string String::FormatHexUInt32(uint32_t value) {
3634 std::stringstream ss;
3635 ss << std::hex << std::uppercase << value;
3636 return ss.str();
3637 }
3638
3639 // Formats an int value as "%X".
3640 std::string String::FormatHexInt(int value) {
3641 return FormatHexUInt32(static_cast<uint32_t>(value));
3642 }
3643
3644 // Formats a byte as "%02X".
3645 std::string String::FormatByte(unsigned char value) {
3646 std::stringstream ss;
3647 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3648 << static_cast<unsigned int>(value);
3649 return ss.str();
3650 }
3651
3652 // Converts the buffer in a stringstream to an std::string, converting NUL
3653 // bytes to "\\0" along the way.
3654 std::string StringStreamToString(::std::stringstream* ss) {
3655 const ::std::string& str = ss->str();
3656 const char* const start = str.c_str();
3657 const char* const end = start + str.length();
3658
3659 std::string result;
3660 result.reserve(static_cast<size_t>(2 * (end - start)));
3661 for (const char* ch = start; ch != end; ++ch) {
3662 if (*ch == '\0') {
3663 result += "\\0"; // Replaces NUL with "\\0";
3664 } else {
3665 result += *ch;
3666 }
3667 }
3668
3669 return result;
3670 }
3671
3672 // Appends the user-supplied message to the Google-Test-generated message.
3673 std::string AppendUserMessage(const std::string& gtest_msg,
3674 const Message& user_msg) {
3675 // Appends the user message if it's non-empty.
3676 const std::string user_msg_string = user_msg.GetString();
3677 if (user_msg_string.empty()) {
3678 return gtest_msg;
3679 }
3680 if (gtest_msg.empty()) {
3681 return user_msg_string;
3682 }
3683 return gtest_msg + "\n" + user_msg_string;
3684 }
3685
3686 } // namespace internal
3687
3688 // class TestResult
3689
3690 // Creates an empty TestResult.
3691 TestResult::TestResult()
3692 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
3693
3694 // D'tor.
3695 TestResult::~TestResult() {
3696 }
3697
3698 // Returns the i-th test part result among all the results. i can
3699 // range from 0 to total_part_count() - 1. If i is not in that range,
3700 // aborts the program.
3701 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3702 if (i < 0 || i >= total_part_count())
3703 internal::posix::Abort();
3704 return test_part_results_.at(static_cast<size_t>(i));
3705 }
3706
3707 // Returns the i-th test property. i can range from 0 to
3708 // test_property_count() - 1. If i is not in that range, aborts the
3709 // program.
3710 const TestProperty& TestResult::GetTestProperty(int i) const {
3711 if (i < 0 || i >= test_property_count())
3712 internal::posix::Abort();
3713 return test_properties_.at(static_cast<size_t>(i));
3714 }
3715
3716 // Clears the test part results.
3717 void TestResult::ClearTestPartResults() {
3718 test_part_results_.clear();
3719 }
3720
3721 // Adds a test part result to the list.
3722 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3723 test_part_results_.push_back(test_part_result);
3724 }
3725
3726 // Adds a test property to the list. If a property with the same key as the
3727 // supplied property is already represented, the value of this test_property
3728 // replaces the old value for that key.
3729 void TestResult::RecordProperty(const std::string& xml_element,
3730 const TestProperty& test_property) {
3731 if (!ValidateTestProperty(xml_element, test_property)) {
3732 return;
3733 }
3734 internal::MutexLock lock(&test_properties_mutex_);
3735 const std::vector<TestProperty>::iterator property_with_matching_key =
3736 std::find_if(test_properties_.begin(), test_properties_.end(),
3737 internal::TestPropertyKeyIs(test_property.key()));
3738 if (property_with_matching_key == test_properties_.end()) {
3739 test_properties_.push_back(test_property);
3740 return;
3741 }
3742 property_with_matching_key->SetValue(test_property.value());
3743 }
3744
3745 // The list of reserved attributes used in the <testsuites> element of XML
3746 // output.
3747 static const char* const kReservedTestSuitesAttributes[] = {
3748 "disabled",
3749 "errors",
3750 "failures",
3751 "name",
3752 "random_seed",
3753 "tests",
3754 "time",
3755 "timestamp"
3756 };
3757
3758 // The list of reserved attributes used in the <testsuite> element of XML
3759 // output.
3760 static const char* const kReservedTestSuiteAttributes[] = {
3761 "disabled", "errors", "failures", "name",
3762 "tests", "time", "timestamp", "skipped"};
3763
3764 // The list of reserved attributes used in the <testcase> element of XML output.
3765 static const char* const kReservedTestCaseAttributes[] = {
3766 "classname", "name", "status", "time", "type_param",
3767 "value_param", "file", "line"};
3768
3769 // Use a slightly different set for allowed output to ensure existing tests can
3770 // still RecordProperty("result") or "RecordProperty(timestamp")
3771 static const char* const kReservedOutputTestCaseAttributes[] = {
3772 "classname", "name", "status", "time", "type_param",
3773 "value_param", "file", "line", "result", "timestamp"};
3774
3775 template <size_t kSize>
3776 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3777 return std::vector<std::string>(array, array + kSize);
3778 }
3779
3780 static std::vector<std::string> GetReservedAttributesForElement(
3781 const std::string& xml_element) {
3782 if (xml_element == "testsuites") {
3783 return ArrayAsVector(kReservedTestSuitesAttributes);
3784 } else if (xml_element == "testsuite") {
3785 return ArrayAsVector(kReservedTestSuiteAttributes);
3786 } else if (xml_element == "testcase") {
3787 return ArrayAsVector(kReservedTestCaseAttributes);
3788 } else {
3789 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3790 }
3791 // This code is unreachable but some compilers may not realizes that.
3792 return std::vector<std::string>();
3793 }
3794
3795 // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
3796 static std::vector<std::string> GetReservedOutputAttributesForElement(
3797 const std::string& xml_element) {
3798 if (xml_element == "testsuites") {
3799 return ArrayAsVector(kReservedTestSuitesAttributes);
3800 } else if (xml_element == "testsuite") {
3801 return ArrayAsVector(kReservedTestSuiteAttributes);
3802 } else if (xml_element == "testcase") {
3803 return ArrayAsVector(kReservedOutputTestCaseAttributes);
3804 } else {
3805 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3806 }
3807 // This code is unreachable but some compilers may not realizes that.
3808 return std::vector<std::string>();
3809 }
3810
3811 static std::string FormatWordList(const std::vector<std::string>& words) {
3812 Message word_list;
3813 for (size_t i = 0; i < words.size(); ++i) {
3814 if (i > 0 && words.size() > 2) {
3815 word_list << ", ";
3816 }
3817 if (i == words.size() - 1) {
3818 word_list << "and ";
3819 }
3820 word_list << "'" << words[i] << "'";
3821 }
3822 return word_list.GetString();
3823 }
3824
3825 static bool ValidateTestPropertyName(
3826 const std::string& property_name,
3827 const std::vector<std::string>& reserved_names) {
3828 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3829 reserved_names.end()) {
3830 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3831 << " (" << FormatWordList(reserved_names)
3832 << " are reserved by " << GTEST_NAME_ << ")";
3833 return false;
3834 }
3835 return true;
3836 }
3837
3838 // Adds a failure if the key is a reserved attribute of the element named
3839 // xml_element. Returns true if the property is valid.
3840 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3841 const TestProperty& test_property) {
3842 return ValidateTestPropertyName(test_property.key(),
3843 GetReservedAttributesForElement(xml_element));
3844 }
3845
3846 // Clears the object.
3847 void TestResult::Clear() {
3848 test_part_results_.clear();
3849 test_properties_.clear();
3850 death_test_count_ = 0;
3851 elapsed_time_ = 0;
3852 }
3853
3854 // Returns true off the test part was skipped.
3855 static bool TestPartSkipped(const TestPartResult& result) {
3856 return result.skipped();
3857 }
3858
3859 // Returns true if and only if the test was skipped.
3860 bool TestResult::Skipped() const {
3861 return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
3862 }
3863
3864 // Returns true if and only if the test failed.
3865 bool TestResult::Failed() const {
3866 for (int i = 0; i < total_part_count(); ++i) {
3867 if (GetTestPartResult(i).failed())
3868 return true;
3869 }
3870 return false;
3871 }
3872
3873 // Returns true if and only if the test part fatally failed.
3874 static bool TestPartFatallyFailed(const TestPartResult& result) {
3875 return result.fatally_failed();
3876 }
3877
3878 // Returns true if and only if the test fatally failed.
3879 bool TestResult::HasFatalFailure() const {
3880 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3881 }
3882
3883 // Returns true if and only if the test part non-fatally failed.
3884 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3885 return result.nonfatally_failed();
3886 }
3887
3888 // Returns true if and only if the test has a non-fatal failure.
3889 bool TestResult::HasNonfatalFailure() const {
3890 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3891 }
3892
3893 // Gets the number of all test parts. This is the sum of the number
3894 // of successful test parts and the number of failed test parts.
3895 int TestResult::total_part_count() const {
3896 return static_cast<int>(test_part_results_.size());
3897 }
3898
3899 // Returns the number of the test properties.
3900 int TestResult::test_property_count() const {
3901 return static_cast<int>(test_properties_.size());
3902 }
3903
3904 // class Test
3905
3906 // Creates a Test object.
3907
3908 // The c'tor saves the states of all flags.
3909 Test::Test()
3910 : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3911 }
3912
3913 // The d'tor restores the states of all flags. The actual work is
3914 // done by the d'tor of the gtest_flag_saver_ field, and thus not
3915 // visible here.
3916 Test::~Test() {
3917 }
3918
3919 // Sets up the test fixture.
3920 //
3921 // A sub-class may override this.
3922 void Test::SetUp() {
3923 }
3924
3925 // Tears down the test fixture.
3926 //
3927 // A sub-class may override this.
3928 void Test::TearDown() {
3929 }
3930
3931 // Allows user supplied key value pairs to be recorded for later output.
3932 void Test::RecordProperty(const std::string& key, const std::string& value) {
3933 UnitTest::GetInstance()->RecordProperty(key, value);
3934 }
3935
3936 // Allows user supplied key value pairs to be recorded for later output.
3937 void Test::RecordProperty(const std::string& key, int value) {
3938 Message value_message;
3939 value_message << value;
3940 RecordProperty(key, value_message.GetString().c_str());
3941 }
3942
3943 namespace internal {
3944
3945 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3946 const std::string& message) {
3947 // This function is a friend of UnitTest and as such has access to
3948 // AddTestPartResult.
3949 UnitTest::GetInstance()->AddTestPartResult(
3950 result_type,
3951 nullptr, // No info about the source file where the exception occurred.
3952 -1, // We have no info on which line caused the exception.
3953 message,
3954 ""); // No stack trace, either.
3955 }
3956
3957 } // namespace internal
3958
3959 // Google Test requires all tests in the same test suite to use the same test
3960 // fixture class. This function checks if the current test has the
3961 // same fixture class as the first test in the current test suite. If
3962 // yes, it returns true; otherwise it generates a Google Test failure and
3963 // returns false.
3964 bool Test::HasSameFixtureClass() {
3965 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3966 const TestSuite* const test_suite = impl->current_test_suite();
3967
3968 // Info about the first test in the current test suite.
3969 const TestInfo* const first_test_info = test_suite->test_info_list()[0];
3970 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3971 const char* const first_test_name = first_test_info->name();
3972
3973 // Info about the current test.
3974 const TestInfo* const this_test_info = impl->current_test_info();
3975 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3976 const char* const this_test_name = this_test_info->name();
3977
3978 if (this_fixture_id != first_fixture_id) {
3979 // Is the first test defined using TEST?
3980 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3981 // Is this test defined using TEST?
3982 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3983
3984 if (first_is_TEST || this_is_TEST) {
3985 // Both TEST and TEST_F appear in same test suite, which is incorrect.
3986 // Tell the user how to fix this.
3987
3988 // Gets the name of the TEST and the name of the TEST_F. Note
3989 // that first_is_TEST and this_is_TEST cannot both be true, as
3990 // the fixture IDs are different for the two tests.
3991 const char* const TEST_name =
3992 first_is_TEST ? first_test_name : this_test_name;
3993 const char* const TEST_F_name =
3994 first_is_TEST ? this_test_name : first_test_name;
3995
3996 ADD_FAILURE()
3997 << "All tests in the same test suite must use the same test fixture\n"
3998 << "class, so mixing TEST_F and TEST in the same test suite is\n"
3999 << "illegal. In test suite " << this_test_info->test_suite_name()
4000 << ",\n"
4001 << "test " << TEST_F_name << " is defined using TEST_F but\n"
4002 << "test " << TEST_name << " is defined using TEST. You probably\n"
4003 << "want to change the TEST to TEST_F or move it to another test\n"
4004 << "case.";
4005 } else {
4006 // Two fixture classes with the same name appear in two different
4007 // namespaces, which is not allowed. Tell the user how to fix this.
4008 ADD_FAILURE()
4009 << "All tests in the same test suite must use the same test fixture\n"
4010 << "class. However, in test suite "
4011 << this_test_info->test_suite_name() << ",\n"
4012 << "you defined test " << first_test_name << " and test "
4013 << this_test_name << "\n"
4014 << "using two different test fixture classes. This can happen if\n"
4015 << "the two classes are from different namespaces or translation\n"
4016 << "units and have the same name. You should probably rename one\n"
4017 << "of the classes to put the tests into different test suites.";
4018 }
4019 return false;
4020 }
4021
4022 return true;
4023 }
4024
4025 #if GTEST_HAS_SEH
4026
4027 // Adds an "exception thrown" fatal failure to the current test. This
4028 // function returns its result via an output parameter pointer because VC++
4029 // prohibits creation of objects with destructors on stack in functions
4030 // using __try (see error C2712).
4031 static std::string* FormatSehExceptionMessage(DWORD exception_code,
4032 const char* location) {
4033 Message message;
4034 message << "SEH exception with code 0x" << std::setbase(16) <<
4035 exception_code << std::setbase(10) << " thrown in " << location << ".";
4036
4037 return new std::string(message.GetString());
4038 }
4039
4040 #endif // GTEST_HAS_SEH
4041
4042 namespace internal {
4043
4044 #if GTEST_HAS_EXCEPTIONS
4045
4046 // Adds an "exception thrown" fatal failure to the current test.
4047 static std::string FormatCxxExceptionMessage(const char* description,
4048 const char* location) {
4049 Message message;
4050 if (description != nullptr) {
4051 message << "C++ exception with description \"" << description << "\"";
4052 } else {
4053 message << "Unknown C++ exception";
4054 }
4055 message << " thrown in " << location << ".";
4056
4057 return message.GetString();
4058 }
4059
4060 static std::string PrintTestPartResultToString(
4061 const TestPartResult& test_part_result);
4062
4063 GoogleTestFailureException::GoogleTestFailureException(
4064 const TestPartResult& failure)
4065 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
4066
4067 #endif // GTEST_HAS_EXCEPTIONS
4068
4069 // We put these helper functions in the internal namespace as IBM's xlC
4070 // compiler rejects the code if they were declared static.
4071
4072 // Runs the given method and handles SEH exceptions it throws, when
4073 // SEH is supported; returns the 0-value for type Result in case of an
4074 // SEH exception. (Microsoft compilers cannot handle SEH and C++
4075 // exceptions in the same function. Therefore, we provide a separate
4076 // wrapper function for handling SEH exceptions.)
4077 template <class T, typename Result>
4078 Result HandleSehExceptionsInMethodIfSupported(
4079 T* object, Result (T::*method)(), const char* location) {
4080 #if GTEST_HAS_SEH
4081 __try {
4082 return (object->*method)();
4083 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
4084 GetExceptionCode())) {
4085 // We create the exception message on the heap because VC++ prohibits
4086 // creation of objects with destructors on stack in functions using __try
4087 // (see error C2712).
4088 std::string* exception_message = FormatSehExceptionMessage(
4089 GetExceptionCode(), location);
4090 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
4091 *exception_message);
4092 delete exception_message;
4093 return static_cast<Result>(0);
4094 }
4095 #else
4096 (void)location;
4097 return (object->*method)();
4098 #endif // GTEST_HAS_SEH
4099 }
4100
4101 // Runs the given method and catches and reports C++ and/or SEH-style
4102 // exceptions, if they are supported; returns the 0-value for type
4103 // Result in case of an SEH exception.
4104 template <class T, typename Result>
4105 Result HandleExceptionsInMethodIfSupported(
4106 T* object, Result (T::*method)(), const char* location) {
4107 // NOTE: The user code can affect the way in which Google Test handles
4108 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
4109 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
4110 // after the exception is caught and either report or re-throw the
4111 // exception based on the flag's value:
4112 //
4113 // try {
4114 // // Perform the test method.
4115 // } catch (...) {
4116 // if (GTEST_FLAG(catch_exceptions))
4117 // // Report the exception as failure.
4118 // else
4119 // throw; // Re-throws the original exception.
4120 // }
4121 //
4122 // However, the purpose of this flag is to allow the program to drop into
4123 // the debugger when the exception is thrown. On most platforms, once the
4124 // control enters the catch block, the exception origin information is
4125 // lost and the debugger will stop the program at the point of the
4126 // re-throw in this function -- instead of at the point of the original
4127 // throw statement in the code under test. For this reason, we perform
4128 // the check early, sacrificing the ability to affect Google Test's
4129 // exception handling in the method where the exception is thrown.
4130 if (internal::GetUnitTestImpl()->catch_exceptions()) {
4131 #if GTEST_HAS_EXCEPTIONS
4132 try {
4133 return HandleSehExceptionsInMethodIfSupported(object, method, location);
4134 } catch (const AssertionException&) { // NOLINT
4135 // This failure was reported already.
4136 } catch (const internal::GoogleTestFailureException&) { // NOLINT
4137 // This exception type can only be thrown by a failed Google
4138 // Test assertion with the intention of letting another testing
4139 // framework catch it. Therefore we just re-throw it.
4140 throw;
4141 } catch (const std::exception& e) { // NOLINT
4142 internal::ReportFailureInUnknownLocation(
4143 TestPartResult::kFatalFailure,
4144 FormatCxxExceptionMessage(e.what(), location));
4145 } catch (...) { // NOLINT
4146 internal::ReportFailureInUnknownLocation(
4147 TestPartResult::kFatalFailure,
4148 FormatCxxExceptionMessage(nullptr, location));
4149 }
4150 return static_cast<Result>(0);
4151 #else
4152 return HandleSehExceptionsInMethodIfSupported(object, method, location);
4153 #endif // GTEST_HAS_EXCEPTIONS
4154 } else {
4155 return (object->*method)();
4156 }
4157 }
4158
4159 } // namespace internal
4160
4161 // Runs the test and updates the test result.
4162 void Test::Run() {
4163 if (!HasSameFixtureClass()) return;
4164
4165 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4166 impl->os_stack_trace_getter()->UponLeavingGTest();
4167 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
4168 // We will run the test only if SetUp() was successful and didn't call
4169 // GTEST_SKIP().
4170 if (!HasFatalFailure() && !IsSkipped()) {
4171 impl->os_stack_trace_getter()->UponLeavingGTest();
4172 internal::HandleExceptionsInMethodIfSupported(
4173 this, &Test::TestBody, "the test body");
4174 }
4175
4176 // However, we want to clean up as much as possible. Hence we will
4177 // always call TearDown(), even if SetUp() or the test body has
4178 // failed.
4179 impl->os_stack_trace_getter()->UponLeavingGTest();
4180 internal::HandleExceptionsInMethodIfSupported(
4181 this, &Test::TearDown, "TearDown()");
4182 }
4183
4184 // Returns true if and only if the current test has a fatal failure.
4185 bool Test::HasFatalFailure() {
4186 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
4187 }
4188
4189 // Returns true if and only if the current test has a non-fatal failure.
4190 bool Test::HasNonfatalFailure() {
4191 return internal::GetUnitTestImpl()->current_test_result()->
4192 HasNonfatalFailure();
4193 }
4194
4195 // Returns true if and only if the current test was skipped.
4196 bool Test::IsSkipped() {
4197 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
4198 }
4199
4200 // class TestInfo
4201
4202 // Constructs a TestInfo object. It assumes ownership of the test factory
4203 // object.
4204 TestInfo::TestInfo(const std::string& a_test_suite_name,
4205 const std::string& a_name, const char* a_type_param,
4206 const char* a_value_param,
4207 internal::CodeLocation a_code_location,
4208 internal::TypeId fixture_class_id,
4209 internal::TestFactoryBase* factory)
4210 : test_suite_name_(a_test_suite_name),
4211 name_(a_name),
4212 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4213 value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
4214 location_(a_code_location),
4215 fixture_class_id_(fixture_class_id),
4216 should_run_(false),
4217 is_disabled_(false),
4218 matches_filter_(false),
4219 is_in_another_shard_(false),
4220 factory_(factory),
4221 result_() {}
4222
4223 // Destructs a TestInfo object.
4224 TestInfo::~TestInfo() { delete factory_; }
4225
4226 namespace internal {
4227
4228 // Creates a new TestInfo object and registers it with Google Test;
4229 // returns the created object.
4230 //
4231 // Arguments:
4232 //
4233 // test_suite_name: name of the test suite
4234 // name: name of the test
4235 // type_param: the name of the test's type parameter, or NULL if
4236 // this is not a typed or a type-parameterized test.
4237 // value_param: text representation of the test's value parameter,
4238 // or NULL if this is not a value-parameterized test.
4239 // code_location: code location where the test is defined
4240 // fixture_class_id: ID of the test fixture class
4241 // set_up_tc: pointer to the function that sets up the test suite
4242 // tear_down_tc: pointer to the function that tears down the test suite
4243 // factory: pointer to the factory that creates a test object.
4244 // The newly created TestInfo instance will assume
4245 // ownership of the factory object.
4246 TestInfo* MakeAndRegisterTestInfo(
4247 const char* test_suite_name, const char* name, const char* type_param,
4248 const char* value_param, CodeLocation code_location,
4249 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
4250 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
4251 TestInfo* const test_info =
4252 new TestInfo(test_suite_name, name, type_param, value_param,
4253 code_location, fixture_class_id, factory);
4254 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4255 return test_info;
4256 }
4257
4258 void ReportInvalidTestSuiteType(const char* test_suite_name,
4259 CodeLocation code_location) {
4260 Message errors;
4261 errors
4262 << "Attempted redefinition of test suite " << test_suite_name << ".\n"
4263 << "All tests in the same test suite must use the same test fixture\n"
4264 << "class. However, in test suite " << test_suite_name << ", you tried\n"
4265 << "to define a test using a fixture class different from the one\n"
4266 << "used earlier. This can happen if the two fixture classes are\n"
4267 << "from different namespaces and have the same name. You should\n"
4268 << "probably rename one of the classes to put the tests into different\n"
4269 << "test suites.";
4270
4271 GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
4272 code_location.line)
4273 << " " << errors.GetString();
4274 }
4275 } // namespace internal
4276
4277 namespace {
4278
4279 // A predicate that checks the test name of a TestInfo against a known
4280 // value.
4281 //
4282 // This is used for implementation of the TestSuite class only. We put
4283 // it in the anonymous namespace to prevent polluting the outer
4284 // namespace.
4285 //
4286 // TestNameIs is copyable.
4287 class TestNameIs {
4288 public:
4289 // Constructor.
4290 //
4291 // TestNameIs has NO default constructor.
4292 explicit TestNameIs(const char* name)
4293 : name_(name) {}
4294
4295 // Returns true if and only if the test name of test_info matches name_.
4296 bool operator()(const TestInfo * test_info) const {
4297 return test_info && test_info->name() == name_;
4298 }
4299
4300 private:
4301 std::string name_;
4302 };
4303
4304 } // namespace
4305
4306 namespace internal {
4307
4308 // This method expands all parameterized tests registered with macros TEST_P
4309 // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
4310 // This will be done just once during the program runtime.
4311 void UnitTestImpl::RegisterParameterizedTests() {
4312 if (!parameterized_tests_registered_) {
4313 parameterized_test_registry_.RegisterTests();
4314 type_parameterized_test_registry_.CheckForInstantiations();
4315 parameterized_tests_registered_ = true;
4316 }
4317 }
4318
4319 } // namespace internal
4320
4321 // Creates the test object, runs it, records its result, and then
4322 // deletes it.
4323 void TestInfo::Run() {
4324 if (!should_run_) return;
4325
4326 // Tells UnitTest where to store test result.
4327 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4328 impl->set_current_test_info(this);
4329
4330 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4331
4332 // Notifies the unit test event listeners that a test is about to start.
4333 repeater->OnTestStart(*this);
4334
4335 result_.set_start_timestamp(internal::GetTimeInMillis());
4336 internal::Timer timer;
4337
4338 impl->os_stack_trace_getter()->UponLeavingGTest();
4339
4340 // Creates the test object.
4341 Test* const test = internal::HandleExceptionsInMethodIfSupported(
4342 factory_, &internal::TestFactoryBase::CreateTest,
4343 "the test fixture's constructor");
4344
4345 // Runs the test if the constructor didn't generate a fatal failure or invoke
4346 // GTEST_SKIP().
4347 // Note that the object will not be null
4348 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
4349 // This doesn't throw as all user code that can throw are wrapped into
4350 // exception handling code.
4351 test->Run();
4352 }
4353
4354 if (test != nullptr) {
4355 // Deletes the test object.
4356 impl->os_stack_trace_getter()->UponLeavingGTest();
4357 internal::HandleExceptionsInMethodIfSupported(
4358 test, &Test::DeleteSelf_, "the test fixture's destructor");
4359 }
4360
4361 result_.set_elapsed_time(timer.Elapsed());
4362
4363 // Notifies the unit test event listener that a test has just finished.
4364 repeater->OnTestEnd(*this);
4365
4366 // Tells UnitTest to stop associating assertion results to this
4367 // test.
4368 impl->set_current_test_info(nullptr);
4369 }
4370
4371 // Skip and records a skipped test result for this object.
4372 void TestInfo::Skip() {
4373 if (!should_run_) return;
4374
4375 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4376 impl->set_current_test_info(this);
4377
4378 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4379
4380 // Notifies the unit test event listeners that a test is about to start.
4381 repeater->OnTestStart(*this);
4382
4383 const TestPartResult test_part_result =
4384 TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
4385 impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
4386 test_part_result);
4387
4388 // Notifies the unit test event listener that a test has just finished.
4389 repeater->OnTestEnd(*this);
4390 impl->set_current_test_info(nullptr);
4391 }
4392
4393 // class TestSuite
4394
4395 // Gets the number of successful tests in this test suite.
4396 int TestSuite::successful_test_count() const {
4397 return CountIf(test_info_list_, TestPassed);
4398 }
4399
4400 // Gets the number of successful tests in this test suite.
4401 int TestSuite::skipped_test_count() const {
4402 return CountIf(test_info_list_, TestSkipped);
4403 }
4404
4405 // Gets the number of failed tests in this test suite.
4406 int TestSuite::failed_test_count() const {
4407 return CountIf(test_info_list_, TestFailed);
4408 }
4409
4410 // Gets the number of disabled tests that will be reported in the XML report.
4411 int TestSuite::reportable_disabled_test_count() const {
4412 return CountIf(test_info_list_, TestReportableDisabled);
4413 }
4414
4415 // Gets the number of disabled tests in this test suite.
4416 int TestSuite::disabled_test_count() const {
4417 return CountIf(test_info_list_, TestDisabled);
4418 }
4419
4420 // Gets the number of tests to be printed in the XML report.
4421 int TestSuite::reportable_test_count() const {
4422 return CountIf(test_info_list_, TestReportable);
4423 }
4424
4425 // Get the number of tests in this test suite that should run.
4426 int TestSuite::test_to_run_count() const {
4427 return CountIf(test_info_list_, ShouldRunTest);
4428 }
4429
4430 // Gets the number of all tests.
4431 int TestSuite::total_test_count() const {
4432 return static_cast<int>(test_info_list_.size());
4433 }
4434
4435 // Creates a TestSuite with the given name.
4436 //
4437 // Arguments:
4438 //
4439 // a_name: name of the test suite
4440 // a_type_param: the name of the test suite's type parameter, or NULL if
4441 // this is not a typed or a type-parameterized test suite.
4442 // set_up_tc: pointer to the function that sets up the test suite
4443 // tear_down_tc: pointer to the function that tears down the test suite
4444 TestSuite::TestSuite(const char* a_name, const char* a_type_param,
4445 internal::SetUpTestSuiteFunc set_up_tc,
4446 internal::TearDownTestSuiteFunc tear_down_tc)
4447 : name_(a_name),
4448 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4449 set_up_tc_(set_up_tc),
4450 tear_down_tc_(tear_down_tc),
4451 should_run_(false),
4452 start_timestamp_(0),
4453 elapsed_time_(0) {}
4454
4455 // Destructor of TestSuite.
4456 TestSuite::~TestSuite() {
4457 // Deletes every Test in the collection.
4458 ForEach(test_info_list_, internal::Delete<TestInfo>);
4459 }
4460
4461 // Returns the i-th test among all the tests. i can range from 0 to
4462 // total_test_count() - 1. If i is not in that range, returns NULL.
4463 const TestInfo* TestSuite::GetTestInfo(int i) const {
4464 const int index = GetElementOr(test_indices_, i, -1);
4465 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
4466 }
4467
4468 // Returns the i-th test among all the tests. i can range from 0 to
4469 // total_test_count() - 1. If i is not in that range, returns NULL.
4470 TestInfo* TestSuite::GetMutableTestInfo(int i) {
4471 const int index = GetElementOr(test_indices_, i, -1);
4472 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
4473 }
4474
4475 // Adds a test to this test suite. Will delete the test upon
4476 // destruction of the TestSuite object.
4477 void TestSuite::AddTestInfo(TestInfo* test_info) {
4478 test_info_list_.push_back(test_info);
4479 test_indices_.push_back(static_cast<int>(test_indices_.size()));
4480 }
4481
4482 // Runs every test in this TestSuite.
4483 void TestSuite::Run() {
4484 if (!should_run_) return;
4485
4486 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4487 impl->set_current_test_suite(this);
4488
4489 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4490
4491 // Call both legacy and the new API
4492 repeater->OnTestSuiteStart(*this);
4493 // Legacy API is deprecated but still available
4494 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4495 repeater->OnTestCaseStart(*this);
4496 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4497
4498 impl->os_stack_trace_getter()->UponLeavingGTest();
4499 internal::HandleExceptionsInMethodIfSupported(
4500 this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
4501
4502 start_timestamp_ = internal::GetTimeInMillis();
4503 internal::Timer timer;
4504 for (int i = 0; i < total_test_count(); i++) {
4505 GetMutableTestInfo(i)->Run();
4506 if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {
4507 for (int j = i + 1; j < total_test_count(); j++) {
4508 GetMutableTestInfo(j)->Skip();
4509 }
4510 break;
4511 }
4512 }
4513 elapsed_time_ = timer.Elapsed();
4514
4515 impl->os_stack_trace_getter()->UponLeavingGTest();
4516 internal::HandleExceptionsInMethodIfSupported(
4517 this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
4518
4519 // Call both legacy and the new API
4520 repeater->OnTestSuiteEnd(*this);
4521 // Legacy API is deprecated but still available
4522 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4523 repeater->OnTestCaseEnd(*this);
4524 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4525
4526 impl->set_current_test_suite(nullptr);
4527 }
4528
4529 // Skips all tests under this TestSuite.
4530 void TestSuite::Skip() {
4531 if (!should_run_) return;
4532
4533 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4534 impl->set_current_test_suite(this);
4535
4536 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4537
4538 // Call both legacy and the new API
4539 repeater->OnTestSuiteStart(*this);
4540 // Legacy API is deprecated but still available
4541 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4542 repeater->OnTestCaseStart(*this);
4543 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4544
4545 for (int i = 0; i < total_test_count(); i++) {
4546 GetMutableTestInfo(i)->Skip();
4547 }
4548
4549 // Call both legacy and the new API
4550 repeater->OnTestSuiteEnd(*this);
4551 // Legacy API is deprecated but still available
4552 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4553 repeater->OnTestCaseEnd(*this);
4554 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4555
4556 impl->set_current_test_suite(nullptr);
4557 }
4558
4559 // Clears the results of all tests in this test suite.
4560 void TestSuite::ClearResult() {
4561 ad_hoc_test_result_.Clear();
4562 ForEach(test_info_list_, TestInfo::ClearTestResult);
4563 }
4564
4565 // Shuffles the tests in this test suite.
4566 void TestSuite::ShuffleTests(internal::Random* random) {
4567 Shuffle(random, &test_indices_);
4568 }
4569
4570 // Restores the test order to before the first shuffle.
4571 void TestSuite::UnshuffleTests() {
4572 for (size_t i = 0; i < test_indices_.size(); i++) {
4573 test_indices_[i] = static_cast<int>(i);
4574 }
4575 }
4576
4577 // Formats a countable noun. Depending on its quantity, either the
4578 // singular form or the plural form is used. e.g.
4579 //
4580 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4581 // FormatCountableNoun(5, "book", "books") returns "5 books".
4582 static std::string FormatCountableNoun(int count,
4583 const char * singular_form,
4584 const char * plural_form) {
4585 return internal::StreamableToString(count) + " " +
4586 (count == 1 ? singular_form : plural_form);
4587 }
4588
4589 // Formats the count of tests.
4590 static std::string FormatTestCount(int test_count) {
4591 return FormatCountableNoun(test_count, "test", "tests");
4592 }
4593
4594 // Formats the count of test suites.
4595 static std::string FormatTestSuiteCount(int test_suite_count) {
4596 return FormatCountableNoun(test_suite_count, "test suite", "test suites");
4597 }
4598
4599 // Converts a TestPartResult::Type enum to human-friendly string
4600 // representation. Both kNonFatalFailure and kFatalFailure are translated
4601 // to "Failure", as the user usually doesn't care about the difference
4602 // between the two when viewing the test result.
4603 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4604 switch (type) {
4605 case TestPartResult::kSkip:
4606 return "Skipped\n";
4607 case TestPartResult::kSuccess:
4608 return "Success";
4609
4610 case TestPartResult::kNonFatalFailure:
4611 case TestPartResult::kFatalFailure:
4612 #ifdef _MSC_VER
4613 return "error: ";
4614 #else
4615 return "Failure\n";
4616 #endif
4617 default:
4618 return "Unknown result type";
4619 }
4620 }
4621
4622 namespace internal {
4623 namespace {
4624 enum class GTestColor { kDefault, kRed, kGreen, kYellow };
4625 } // namespace
4626
4627 // Prints a TestPartResult to an std::string.
4628 static std::string PrintTestPartResultToString(
4629 const TestPartResult& test_part_result) {
4630 return (Message()
4631 << internal::FormatFileLocation(test_part_result.file_name(),
4632 test_part_result.line_number())
4633 << " " << TestPartResultTypeToString(test_part_result.type())
4634 << test_part_result.message()).GetString();
4635 }
4636
4637 // Prints a TestPartResult.
4638 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4639 const std::string& result =
4640 PrintTestPartResultToString(test_part_result);
4641 printf("%s\n", result.c_str());
4642 fflush(stdout);
4643 // If the test program runs in Visual Studio or a debugger, the
4644 // following statements add the test part result message to the Output
4645 // window such that the user can double-click on it to jump to the
4646 // corresponding source code location; otherwise they do nothing.
4647 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4648 // We don't call OutputDebugString*() on Windows Mobile, as printing
4649 // to stdout is done by OutputDebugString() there already - we don't
4650 // want the same message printed twice.
4651 ::OutputDebugStringA(result.c_str());
4652 ::OutputDebugStringA("\n");
4653 #endif
4654 }
4655
4656 // class PrettyUnitTestResultPrinter
4657 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4658 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4659
4660 // Returns the character attribute for the given color.
4661 static WORD GetColorAttribute(GTestColor color) {
4662 switch (color) {
4663 case GTestColor::kRed:
4664 return FOREGROUND_RED;
4665 case GTestColor::kGreen:
4666 return FOREGROUND_GREEN;
4667 case GTestColor::kYellow:
4668 return FOREGROUND_RED | FOREGROUND_GREEN;
4669 default: return 0;
4670 }
4671 }
4672
4673 static int GetBitOffset(WORD color_mask) {
4674 if (color_mask == 0) return 0;
4675
4676 int bitOffset = 0;
4677 while ((color_mask & 1) == 0) {
4678 color_mask >>= 1;
4679 ++bitOffset;
4680 }
4681 return bitOffset;
4682 }
4683
4684 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
4685 // Let's reuse the BG
4686 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4687 BACKGROUND_RED | BACKGROUND_INTENSITY;
4688 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4689 FOREGROUND_RED | FOREGROUND_INTENSITY;
4690 const WORD existing_bg = old_color_attrs & background_mask;
4691
4692 WORD new_color =
4693 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4694 static const int bg_bitOffset = GetBitOffset(background_mask);
4695 static const int fg_bitOffset = GetBitOffset(foreground_mask);
4696
4697 if (((new_color & background_mask) >> bg_bitOffset) ==
4698 ((new_color & foreground_mask) >> fg_bitOffset)) {
4699 new_color ^= FOREGROUND_INTENSITY; // invert intensity
4700 }
4701 return new_color;
4702 }
4703
4704 #else
4705
4706 // Returns the ANSI color code for the given color. GTestColor::kDefault is
4707 // an invalid input.
4708 static const char* GetAnsiColorCode(GTestColor color) {
4709 switch (color) {
4710 case GTestColor::kRed:
4711 return "1";
4712 case GTestColor::kGreen:
4713 return "2";
4714 case GTestColor::kYellow:
4715 return "3";
4716 default:
4717 return nullptr;
4718 }
4719 }
4720
4721 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4722
4723 // Returns true if and only if Google Test should use colors in the output.
4724 bool ShouldUseColor(bool stdout_is_tty) {
4725 const char* const gtest_color = GTEST_FLAG(color).c_str();
4726
4727 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4728 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
4729 // On Windows the TERM variable is usually not set, but the
4730 // console there does support colors.
4731 return stdout_is_tty;
4732 #else
4733 // On non-Windows platforms, we rely on the TERM variable.
4734 const char* const term = posix::GetEnv("TERM");
4735 const bool term_supports_color =
4736 String::CStringEquals(term, "xterm") ||
4737 String::CStringEquals(term, "xterm-color") ||
4738 String::CStringEquals(term, "xterm-256color") ||
4739 String::CStringEquals(term, "screen") ||
4740 String::CStringEquals(term, "screen-256color") ||
4741 String::CStringEquals(term, "tmux") ||
4742 String::CStringEquals(term, "tmux-256color") ||
4743 String::CStringEquals(term, "rxvt-unicode") ||
4744 String::CStringEquals(term, "rxvt-unicode-256color") ||
4745 String::CStringEquals(term, "linux") ||
4746 String::CStringEquals(term, "cygwin");
4747 return stdout_is_tty && term_supports_color;
4748 #endif // GTEST_OS_WINDOWS
4749 }
4750
4751 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4752 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4753 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4754 String::CStringEquals(gtest_color, "1");
4755 // We take "yes", "true", "t", and "1" as meaning "yes". If the
4756 // value is neither one of these nor "auto", we treat it as "no" to
4757 // be conservative.
4758 }
4759
4760 // Helpers for printing colored strings to stdout. Note that on Windows, we
4761 // cannot simply emit special characters and have the terminal change colors.
4762 // This routine must actually emit the characters rather than return a string
4763 // that would be colored when printed, as can be done on Linux.
4764
4765 GTEST_ATTRIBUTE_PRINTF_(2, 3)
4766 static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
4767 va_list args;
4768 va_start(args, fmt);
4769
4770 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
4771 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
4772 const bool use_color = AlwaysFalse();
4773 #else
4774 static const bool in_color_mode =
4775 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4776 const bool use_color = in_color_mode && (color != GTestColor::kDefault);
4777 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
4778
4779 if (!use_color) {
4780 vprintf(fmt, args);
4781 va_end(args);
4782 return;
4783 }
4784
4785 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4786 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4787 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4788
4789 // Gets the current text color.
4790 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4791 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4792 const WORD old_color_attrs = buffer_info.wAttributes;
4793 const WORD new_color = GetNewColor(color, old_color_attrs);
4794
4795 // We need to flush the stream buffers into the console before each
4796 // SetConsoleTextAttribute call lest it affect the text that is already
4797 // printed but has not yet reached the console.
4798 fflush(stdout);
4799 SetConsoleTextAttribute(stdout_handle, new_color);
4800
4801 vprintf(fmt, args);
4802
4803 fflush(stdout);
4804 // Restores the text color.
4805 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4806 #else
4807 printf("\033[0;3%sm", GetAnsiColorCode(color));
4808 vprintf(fmt, args);
4809 printf("\033[m"); // Resets the terminal to default.
4810 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4811 va_end(args);
4812 }
4813
4814 // Text printed in Google Test's text output and --gtest_list_tests
4815 // output to label the type parameter and value parameter for a test.
4816 static const char kTypeParamLabel[] = "TypeParam";
4817 static const char kValueParamLabel[] = "GetParam()";
4818
4819 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4820 const char* const type_param = test_info.type_param();
4821 const char* const value_param = test_info.value_param();
4822
4823 if (type_param != nullptr || value_param != nullptr) {
4824 printf(", where ");
4825 if (type_param != nullptr) {
4826 printf("%s = %s", kTypeParamLabel, type_param);
4827 if (value_param != nullptr) printf(" and ");
4828 }
4829 if (value_param != nullptr) {
4830 printf("%s = %s", kValueParamLabel, value_param);
4831 }
4832 }
4833 }
4834
4835 // This class implements the TestEventListener interface.
4836 //
4837 // Class PrettyUnitTestResultPrinter is copyable.
4838 class PrettyUnitTestResultPrinter : public TestEventListener {
4839 public:
4840 PrettyUnitTestResultPrinter() {}
4841 static void PrintTestName(const char* test_suite, const char* test) {
4842 printf("%s.%s", test_suite, test);
4843 }
4844
4845 // The following methods override what's in the TestEventListener class.
4846 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
4847 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4848 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
4849 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
4850 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4851 void OnTestCaseStart(const TestCase& test_case) override;
4852 #else
4853 void OnTestSuiteStart(const TestSuite& test_suite) override;
4854 #endif // OnTestCaseStart
4855
4856 void OnTestStart(const TestInfo& test_info) override;
4857
4858 void OnTestPartResult(const TestPartResult& result) override;
4859 void OnTestEnd(const TestInfo& test_info) override;
4860 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4861 void OnTestCaseEnd(const TestCase& test_case) override;
4862 #else
4863 void OnTestSuiteEnd(const TestSuite& test_suite) override;
4864 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4865
4866 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
4867 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
4868 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4869 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
4870
4871 private:
4872 static void PrintFailedTests(const UnitTest& unit_test);
4873 static void PrintFailedTestSuites(const UnitTest& unit_test);
4874 static void PrintSkippedTests(const UnitTest& unit_test);
4875 };
4876
4877 // Fired before each iteration of tests starts.
4878 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4879 const UnitTest& unit_test, int iteration) {
4880 if (GTEST_FLAG(repeat) != 1)
4881 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4882
4883 const char* const filter = GTEST_FLAG(filter).c_str();
4884
4885 // Prints the filter if it's not *. This reminds the user that some
4886 // tests may be skipped.
4887 if (!String::CStringEquals(filter, kUniversalFilter)) {
4888 ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
4889 filter);
4890 }
4891
4892 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4893 const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4894 ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
4895 static_cast<int>(shard_index) + 1,
4896 internal::posix::GetEnv(kTestTotalShards));
4897 }
4898
4899 if (GTEST_FLAG(shuffle)) {
4900 ColoredPrintf(GTestColor::kYellow,
4901 "Note: Randomizing tests' orders with a seed of %d .\n",
4902 unit_test.random_seed());
4903 }
4904
4905 ColoredPrintf(GTestColor::kGreen, "[==========] ");
4906 printf("Running %s from %s.\n",
4907 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4908 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4909 fflush(stdout);
4910 }
4911
4912 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4913 const UnitTest& /*unit_test*/) {
4914 ColoredPrintf(GTestColor::kGreen, "[----------] ");
4915 printf("Global test environment set-up.\n");
4916 fflush(stdout);
4917 }
4918
4919 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4920 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4921 const std::string counts =
4922 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4923 ColoredPrintf(GTestColor::kGreen, "[----------] ");
4924 printf("%s from %s", counts.c_str(), test_case.name());
4925 if (test_case.type_param() == nullptr) {
4926 printf("\n");
4927 } else {
4928 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4929 }
4930 fflush(stdout);
4931 }
4932 #else
4933 void PrettyUnitTestResultPrinter::OnTestSuiteStart(
4934 const TestSuite& test_suite) {
4935 const std::string counts =
4936 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
4937 ColoredPrintf(GTestColor::kGreen, "[----------] ");
4938 printf("%s from %s", counts.c_str(), test_suite.name());
4939 if (test_suite.type_param() == nullptr) {
4940 printf("\n");
4941 } else {
4942 printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
4943 }
4944 fflush(stdout);
4945 }
4946 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4947
4948 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4949 ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
4950 PrintTestName(test_info.test_suite_name(), test_info.name());
4951 printf("\n");
4952 fflush(stdout);
4953 }
4954
4955 // Called after an assertion failure.
4956 void PrettyUnitTestResultPrinter::OnTestPartResult(
4957 const TestPartResult& result) {
4958 switch (result.type()) {
4959 // If the test part succeeded, we don't need to do anything.
4960 case TestPartResult::kSuccess:
4961 return;
4962 default:
4963 // Print failure message from the assertion
4964 // (e.g. expected this and got that).
4965 PrintTestPartResult(result);
4966 fflush(stdout);
4967 }
4968 }
4969
4970 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4971 if (test_info.result()->Passed()) {
4972 ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
4973 } else if (test_info.result()->Skipped()) {
4974 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
4975 } else {
4976 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
4977 }
4978 PrintTestName(test_info.test_suite_name(), test_info.name());
4979 if (test_info.result()->Failed())
4980 PrintFullTestCommentIfPresent(test_info);
4981
4982 if (GTEST_FLAG(print_time)) {
4983 printf(" (%s ms)\n", internal::StreamableToString(
4984 test_info.result()->elapsed_time()).c_str());
4985 } else {
4986 printf("\n");
4987 }
4988 fflush(stdout);
4989 }
4990
4991 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4992 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4993 if (!GTEST_FLAG(print_time)) return;
4994
4995 const std::string counts =
4996 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4997 ColoredPrintf(GTestColor::kGreen, "[----------] ");
4998 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
4999 internal::StreamableToString(test_case.elapsed_time()).c_str());
5000 fflush(stdout);
5001 }
5002 #else
5003 void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
5004 if (!GTEST_FLAG(print_time)) return;
5005
5006 const std::string counts =
5007 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
5008 ColoredPrintf(GTestColor::kGreen, "[----------] ");
5009 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
5010 internal::StreamableToString(test_suite.elapsed_time()).c_str());
5011 fflush(stdout);
5012 }
5013 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5014
5015 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
5016 const UnitTest& /*unit_test*/) {
5017 ColoredPrintf(GTestColor::kGreen, "[----------] ");
5018 printf("Global test environment tear-down\n");
5019 fflush(stdout);
5020 }
5021
5022 // Internal helper for printing the list of failed tests.
5023 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
5024 const int failed_test_count = unit_test.failed_test_count();
5025 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
5026 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
5027
5028 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5029 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
5030 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
5031 continue;
5032 }
5033 for (int j = 0; j < test_suite.total_test_count(); ++j) {
5034 const TestInfo& test_info = *test_suite.GetTestInfo(j);
5035 if (!test_info.should_run() || !test_info.result()->Failed()) {
5036 continue;
5037 }
5038 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
5039 printf("%s.%s", test_suite.name(), test_info.name());
5040 PrintFullTestCommentIfPresent(test_info);
5041 printf("\n");
5042 }
5043 }
5044 printf("\n%2d FAILED %s\n", failed_test_count,
5045 failed_test_count == 1 ? "TEST" : "TESTS");
5046 }
5047
5048 // Internal helper for printing the list of test suite failures not covered by
5049 // PrintFailedTests.
5050 void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
5051 const UnitTest& unit_test) {
5052 int suite_failure_count = 0;
5053 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5054 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
5055 if (!test_suite.should_run()) {
5056 continue;
5057 }
5058 if (test_suite.ad_hoc_test_result().Failed()) {
5059 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
5060 printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
5061 ++suite_failure_count;
5062 }
5063 }
5064 if (suite_failure_count > 0) {
5065 printf("\n%2d FAILED TEST %s\n", suite_failure_count,
5066 suite_failure_count == 1 ? "SUITE" : "SUITES");
5067 }
5068 }
5069
5070 // Internal helper for printing the list of skipped tests.
5071 void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
5072 const int skipped_test_count = unit_test.skipped_test_count();
5073 if (skipped_test_count == 0) {
5074 return;
5075 }
5076
5077 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5078 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
5079 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
5080 continue;
5081 }
5082 for (int j = 0; j < test_suite.total_test_count(); ++j) {
5083 const TestInfo& test_info = *test_suite.GetTestInfo(j);
5084 if (!test_info.should_run() || !test_info.result()->Skipped()) {
5085 continue;
5086 }
5087 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
5088 printf("%s.%s", test_suite.name(), test_info.name());
5089 printf("\n");
5090 }
5091 }
5092 }
5093
5094 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5095 int /*iteration*/) {
5096 ColoredPrintf(GTestColor::kGreen, "[==========] ");
5097 printf("%s from %s ran.",
5098 FormatTestCount(unit_test.test_to_run_count()).c_str(),
5099 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
5100 if (GTEST_FLAG(print_time)) {
5101 printf(" (%s ms total)",
5102 internal::StreamableToString(unit_test.elapsed_time()).c_str());
5103 }
5104 printf("\n");
5105 ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
5106 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
5107
5108 const int skipped_test_count = unit_test.skipped_test_count();
5109 if (skipped_test_count > 0) {
5110 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
5111 printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
5112 PrintSkippedTests(unit_test);
5113 }
5114
5115 if (!unit_test.Passed()) {
5116 PrintFailedTests(unit_test);
5117 PrintFailedTestSuites(unit_test);
5118 }
5119
5120 int num_disabled = unit_test.reportable_disabled_test_count();
5121 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
5122 if (unit_test.Passed()) {
5123 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
5124 }
5125 ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
5126 num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
5127 }
5128 // Ensure that Google Test output is printed before, e.g., heapchecker output.
5129 fflush(stdout);
5130 }
5131
5132 // End PrettyUnitTestResultPrinter
5133
5134 // This class implements the TestEventListener interface.
5135 //
5136 // Class BriefUnitTestResultPrinter is copyable.
5137 class BriefUnitTestResultPrinter : public TestEventListener {
5138 public:
5139 BriefUnitTestResultPrinter() {}
5140 static void PrintTestName(const char* test_suite, const char* test) {
5141 printf("%s.%s", test_suite, test);
5142 }
5143
5144 // The following methods override what's in the TestEventListener class.
5145 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
5146 void OnTestIterationStart(const UnitTest& /*unit_test*/,
5147 int /*iteration*/) override {}
5148 void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
5149 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
5150 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5151 void OnTestCaseStart(const TestCase& /*test_case*/) override {}
5152 #else
5153 void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
5154 #endif // OnTestCaseStart
5155
5156 void OnTestStart(const TestInfo& /*test_info*/) override {}
5157
5158 void OnTestPartResult(const TestPartResult& result) override;
5159 void OnTestEnd(const TestInfo& test_info) override;
5160 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5161 void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
5162 #else
5163 void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
5164 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5165
5166 void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
5167 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
5168 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5169 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
5170 };
5171
5172 // Called after an assertion failure.
5173 void BriefUnitTestResultPrinter::OnTestPartResult(
5174 const TestPartResult& result) {
5175 switch (result.type()) {
5176 // If the test part succeeded, we don't need to do anything.
5177 case TestPartResult::kSuccess:
5178 return;
5179 default:
5180 // Print failure message from the assertion
5181 // (e.g. expected this and got that).
5182 PrintTestPartResult(result);
5183 fflush(stdout);
5184 }
5185 }
5186
5187 void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
5188 if (test_info.result()->Failed()) {
5189 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
5190 PrintTestName(test_info.test_suite_name(), test_info.name());
5191 PrintFullTestCommentIfPresent(test_info);
5192
5193 if (GTEST_FLAG(print_time)) {
5194 printf(" (%s ms)\n",
5195 internal::StreamableToString(test_info.result()->elapsed_time())
5196 .c_str());
5197 } else {
5198 printf("\n");
5199 }
5200 fflush(stdout);
5201 }
5202 }
5203
5204 void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5205 int /*iteration*/) {
5206 ColoredPrintf(GTestColor::kGreen, "[==========] ");
5207 printf("%s from %s ran.",
5208 FormatTestCount(unit_test.test_to_run_count()).c_str(),
5209 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
5210 if (GTEST_FLAG(print_time)) {
5211 printf(" (%s ms total)",
5212 internal::StreamableToString(unit_test.elapsed_time()).c_str());
5213 }
5214 printf("\n");
5215 ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
5216 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
5217
5218 const int skipped_test_count = unit_test.skipped_test_count();
5219 if (skipped_test_count > 0) {
5220 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
5221 printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
5222 }
5223
5224 int num_disabled = unit_test.reportable_disabled_test_count();
5225 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
5226 if (unit_test.Passed()) {
5227 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
5228 }
5229 ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
5230 num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
5231 }
5232 // Ensure that Google Test output is printed before, e.g., heapchecker output.
5233 fflush(stdout);
5234 }
5235
5236 // End BriefUnitTestResultPrinter
5237
5238 // class TestEventRepeater
5239 //
5240 // This class forwards events to other event listeners.
5241 class TestEventRepeater : public TestEventListener {
5242 public:
5243 TestEventRepeater() : forwarding_enabled_(true) {}
5244 ~TestEventRepeater() override;
5245 void Append(TestEventListener *listener);
5246 TestEventListener* Release(TestEventListener* listener);
5247
5248 // Controls whether events will be forwarded to listeners_. Set to false
5249 // in death test child processes.
5250 bool forwarding_enabled() const { return forwarding_enabled_; }
5251 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
5252
5253 void OnTestProgramStart(const UnitTest& unit_test) override;
5254 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
5255 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
5256 void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
5257 // Legacy API is deprecated but still available
5258 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5259 void OnTestCaseStart(const TestSuite& parameter) override;
5260 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5261 void OnTestSuiteStart(const TestSuite& parameter) override;
5262 void OnTestStart(const TestInfo& test_info) override;
5263 void OnTestPartResult(const TestPartResult& result) override;
5264 void OnTestEnd(const TestInfo& test_info) override;
5265 // Legacy API is deprecated but still available
5266 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5267 void OnTestCaseEnd(const TestCase& parameter) override;
5268 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5269 void OnTestSuiteEnd(const TestSuite& parameter) override;
5270 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
5271 void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
5272 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5273 void OnTestProgramEnd(const UnitTest& unit_test) override;
5274
5275 private:
5276 // Controls whether events will be forwarded to listeners_. Set to false
5277 // in death test child processes.
5278 bool forwarding_enabled_;
5279 // The list of listeners that receive events.
5280 std::vector<TestEventListener*> listeners_;
5281
5282 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
5283 };
5284
5285 TestEventRepeater::~TestEventRepeater() {
5286 ForEach(listeners_, Delete<TestEventListener>);
5287 }
5288
5289 void TestEventRepeater::Append(TestEventListener *listener) {
5290 listeners_.push_back(listener);
5291 }
5292
5293 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
5294 for (size_t i = 0; i < listeners_.size(); ++i) {
5295 if (listeners_[i] == listener) {
5296 listeners_.erase(listeners_.begin() + static_cast<int>(i));
5297 return listener;
5298 }
5299 }
5300
5301 return nullptr;
5302 }
5303
5304 // Since most methods are very similar, use macros to reduce boilerplate.
5305 // This defines a member that forwards the call to all listeners.
5306 #define GTEST_REPEATER_METHOD_(Name, Type) \
5307 void TestEventRepeater::Name(const Type& parameter) { \
5308 if (forwarding_enabled_) { \
5309 for (size_t i = 0; i < listeners_.size(); i++) { \
5310 listeners_[i]->Name(parameter); \
5311 } \
5312 } \
5313 }
5314 // This defines a member that forwards the call to all listeners in reverse
5315 // order.
5316 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
5317 void TestEventRepeater::Name(const Type& parameter) { \
5318 if (forwarding_enabled_) { \
5319 for (size_t i = listeners_.size(); i != 0; i--) { \
5320 listeners_[i - 1]->Name(parameter); \
5321 } \
5322 } \
5323 }
5324
5325 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
5326 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
5327 // Legacy API is deprecated but still available
5328 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5329 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
5330 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5331 GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
5332 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
5333 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
5334 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
5335 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
5336 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
5337 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
5338 // Legacy API is deprecated but still available
5339 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5340 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
5341 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5342 GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
5343 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
5344
5345 #undef GTEST_REPEATER_METHOD_
5346 #undef GTEST_REVERSE_REPEATER_METHOD_
5347
5348 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
5349 int iteration) {
5350 if (forwarding_enabled_) {
5351 for (size_t i = 0; i < listeners_.size(); i++) {
5352 listeners_[i]->OnTestIterationStart(unit_test, iteration);
5353 }
5354 }
5355 }
5356
5357 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
5358 int iteration) {
5359 if (forwarding_enabled_) {
5360 for (size_t i = listeners_.size(); i > 0; i--) {
5361 listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
5362 }
5363 }
5364 }
5365
5366 // End TestEventRepeater
5367
5368 // This class generates an XML output file.
5369 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
5370 public:
5371 explicit XmlUnitTestResultPrinter(const char* output_file);
5372
5373 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5374 void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
5375
5376 // Prints an XML summary of all unit tests.
5377 static void PrintXmlTestsList(std::ostream* stream,
5378 const std::vector<TestSuite*>& test_suites);
5379
5380 private:
5381 // Is c a whitespace character that is normalized to a space character
5382 // when it appears in an XML attribute value?
5383 static bool IsNormalizableWhitespace(char c) {
5384 return c == 0x9 || c == 0xA || c == 0xD;
5385 }
5386
5387 // May c appear in a well-formed XML document?
5388 static bool IsValidXmlCharacter(char c) {
5389 return IsNormalizableWhitespace(c) || c >= 0x20;
5390 }
5391
5392 // Returns an XML-escaped copy of the input string str. If
5393 // is_attribute is true, the text is meant to appear as an attribute
5394 // value, and normalizable whitespace is preserved by replacing it
5395 // with character references.
5396 static std::string EscapeXml(const std::string& str, bool is_attribute);
5397
5398 // Returns the given string with all characters invalid in XML removed.
5399 static std::string RemoveInvalidXmlCharacters(const std::string& str);
5400
5401 // Convenience wrapper around EscapeXml when str is an attribute value.
5402 static std::string EscapeXmlAttribute(const std::string& str) {
5403 return EscapeXml(str, true);
5404 }
5405
5406 // Convenience wrapper around EscapeXml when str is not an attribute value.
5407 static std::string EscapeXmlText(const char* str) {
5408 return EscapeXml(str, false);
5409 }
5410
5411 // Verifies that the given attribute belongs to the given element and
5412 // streams the attribute as XML.
5413 static void OutputXmlAttribute(std::ostream* stream,
5414 const std::string& element_name,
5415 const std::string& name,
5416 const std::string& value);
5417
5418 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5419 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
5420
5421 // Streams a test suite XML stanza containing the given test result.
5422 //
5423 // Requires: result.Failed()
5424 static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
5425 const TestResult& result);
5426
5427 // Streams an XML representation of a TestResult object.
5428 static void OutputXmlTestResult(::std::ostream* stream,
5429 const TestResult& result);
5430
5431 // Streams an XML representation of a TestInfo object.
5432 static void OutputXmlTestInfo(::std::ostream* stream,
5433 const char* test_suite_name,
5434 const TestInfo& test_info);
5435
5436 // Prints an XML representation of a TestSuite object
5437 static void PrintXmlTestSuite(::std::ostream* stream,
5438 const TestSuite& test_suite);
5439
5440 // Prints an XML summary of unit_test to output stream out.
5441 static void PrintXmlUnitTest(::std::ostream* stream,
5442 const UnitTest& unit_test);
5443
5444 // Produces a string representing the test properties in a result as space
5445 // delimited XML attributes based on the property key="value" pairs.
5446 // When the std::string is not empty, it includes a space at the beginning,
5447 // to delimit this attribute from prior attributes.
5448 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
5449
5450 // Streams an XML representation of the test properties of a TestResult
5451 // object.
5452 static void OutputXmlTestProperties(std::ostream* stream,
5453 const TestResult& result);
5454
5455 // The output file.
5456 const std::string output_file_;
5457
5458 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
5459 };
5460
5461 // Creates a new XmlUnitTestResultPrinter.
5462 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
5463 : output_file_(output_file) {
5464 if (output_file_.empty()) {
5465 GTEST_LOG_(FATAL) << "XML output file may not be null";
5466 }
5467 }
5468
5469 // Called after the unit test ends.
5470 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5471 int /*iteration*/) {
5472 FILE* xmlout = OpenFileForWriting(output_file_);
5473 std::stringstream stream;
5474 PrintXmlUnitTest(&stream, unit_test);
5475 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5476 fclose(xmlout);
5477 }
5478
5479 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
5480 const std::vector<TestSuite*>& test_suites) {
5481 FILE* xmlout = OpenFileForWriting(output_file_);
5482 std::stringstream stream;
5483 PrintXmlTestsList(&stream, test_suites);
5484 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5485 fclose(xmlout);
5486 }
5487
5488 // Returns an XML-escaped copy of the input string str. If is_attribute
5489 // is true, the text is meant to appear as an attribute value, and
5490 // normalizable whitespace is preserved by replacing it with character
5491 // references.
5492 //
5493 // Invalid XML characters in str, if any, are stripped from the output.
5494 // It is expected that most, if not all, of the text processed by this
5495 // module will consist of ordinary English text.
5496 // If this module is ever modified to produce version 1.1 XML output,
5497 // most invalid characters can be retained using character references.
5498 std::string XmlUnitTestResultPrinter::EscapeXml(
5499 const std::string& str, bool is_attribute) {
5500 Message m;
5501
5502 for (size_t i = 0; i < str.size(); ++i) {
5503 const char ch = str[i];
5504 switch (ch) {
5505 case '<':
5506 m << "&lt;";
5507 break;
5508 case '>':
5509 m << "&gt;";
5510 break;
5511 case '&':
5512 m << "&amp;";
5513 break;
5514 case '\'':
5515 if (is_attribute)
5516 m << "&apos;";
5517 else
5518 m << '\'';
5519 break;
5520 case '"':
5521 if (is_attribute)
5522 m << "&quot;";
5523 else
5524 m << '"';
5525 break;
5526 default:
5527 if (IsValidXmlCharacter(ch)) {
5528 if (is_attribute && IsNormalizableWhitespace(ch))
5529 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5530 << ";";
5531 else
5532 m << ch;
5533 }
5534 break;
5535 }
5536 }
5537
5538 return m.GetString();
5539 }
5540
5541 // Returns the given string with all characters invalid in XML removed.
5542 // Currently invalid characters are dropped from the string. An
5543 // alternative is to replace them with certain characters such as . or ?.
5544 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5545 const std::string& str) {
5546 std::string output;
5547 output.reserve(str.size());
5548 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5549 if (IsValidXmlCharacter(*it))
5550 output.push_back(*it);
5551
5552 return output;
5553 }
5554
5555 // The following routines generate an XML representation of a UnitTest
5556 // object.
5557 // GOOGLETEST_CM0009 DO NOT DELETE
5558 //
5559 // This is how Google Test concepts map to the DTD:
5560 //
5561 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
5562 // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
5563 // <testcase name="test-name"> <-- corresponds to a TestInfo object
5564 // <failure message="...">...</failure>
5565 // <failure message="...">...</failure>
5566 // <failure message="...">...</failure>
5567 // <-- individual assertion failures
5568 // </testcase>
5569 // </testsuite>
5570 // </testsuites>
5571
5572 // Formats the given time in milliseconds as seconds.
5573 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5574 ::std::stringstream ss;
5575 ss << (static_cast<double>(ms) * 1e-3);
5576 return ss.str();
5577 }
5578
5579 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5580 #if defined(_MSC_VER)
5581 return localtime_s(out, &seconds) == 0;
5582 #elif defined(__MINGW32__) || defined(__MINGW64__)
5583 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5584 // Windows' localtime(), which has a thread-local tm buffer.
5585 struct tm* tm_ptr = localtime(&seconds); // NOLINT
5586 if (tm_ptr == nullptr) return false;
5587 *out = *tm_ptr;
5588 return true;
5589 #elif defined(__STDC_LIB_EXT1__)
5590 // Uses localtime_s when available as localtime_r is only available from
5591 // C23 standard.
5592 return localtime_s(&seconds, out) != nullptr;
5593 #else
5594 return localtime_r(&seconds, out) != nullptr;
5595 #endif
5596 }
5597
5598 // Converts the given epoch time in milliseconds to a date string in the ISO
5599 // 8601 format, without the timezone information.
5600 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5601 struct tm time_struct;
5602 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5603 return "";
5604 // YYYY-MM-DDThh:mm:ss.sss
5605 return StreamableToString(time_struct.tm_year + 1900) + "-" +
5606 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5607 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5608 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5609 String::FormatIntWidth2(time_struct.tm_min) + ":" +
5610 String::FormatIntWidth2(time_struct.tm_sec) + "." +
5611 String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
5612 }
5613
5614 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5615 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5616 const char* data) {
5617 const char* segment = data;
5618 *stream << "<![CDATA[";
5619 for (;;) {
5620 const char* const next_segment = strstr(segment, "]]>");
5621 if (next_segment != nullptr) {
5622 stream->write(
5623 segment, static_cast<std::streamsize>(next_segment - segment));
5624 *stream << "]]>]]&gt;<![CDATA[";
5625 segment = next_segment + strlen("]]>");
5626 } else {
5627 *stream << segment;
5628 break;
5629 }
5630 }
5631 *stream << "]]>";
5632 }
5633
5634 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5635 std::ostream* stream,
5636 const std::string& element_name,
5637 const std::string& name,
5638 const std::string& value) {
5639 const std::vector<std::string>& allowed_names =
5640 GetReservedOutputAttributesForElement(element_name);
5641
5642 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5643 allowed_names.end())
5644 << "Attribute " << name << " is not allowed for element <" << element_name
5645 << ">.";
5646
5647 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5648 }
5649
5650 // Streams a test suite XML stanza containing the given test result.
5651 void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
5652 ::std::ostream* stream, const TestResult& result) {
5653 // Output the boilerplate for a minimal test suite with one test.
5654 *stream << " <testsuite";
5655 OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
5656 OutputXmlAttribute(stream, "testsuite", "tests", "1");
5657 OutputXmlAttribute(stream, "testsuite", "failures", "1");
5658 OutputXmlAttribute(stream, "testsuite", "disabled", "0");
5659 OutputXmlAttribute(stream, "testsuite", "skipped", "0");
5660 OutputXmlAttribute(stream, "testsuite", "errors", "0");
5661 OutputXmlAttribute(stream, "testsuite", "time",
5662 FormatTimeInMillisAsSeconds(result.elapsed_time()));
5663 OutputXmlAttribute(
5664 stream, "testsuite", "timestamp",
5665 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
5666 *stream << ">";
5667
5668 // Output the boilerplate for a minimal test case with a single test.
5669 *stream << " <testcase";
5670 OutputXmlAttribute(stream, "testcase", "name", "");
5671 OutputXmlAttribute(stream, "testcase", "status", "run");
5672 OutputXmlAttribute(stream, "testcase", "result", "completed");
5673 OutputXmlAttribute(stream, "testcase", "classname", "");
5674 OutputXmlAttribute(stream, "testcase", "time",
5675 FormatTimeInMillisAsSeconds(result.elapsed_time()));
5676 OutputXmlAttribute(
5677 stream, "testcase", "timestamp",
5678 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
5679
5680 // Output the actual test result.
5681 OutputXmlTestResult(stream, result);
5682
5683 // Complete the test suite.
5684 *stream << " </testsuite>\n";
5685 }
5686
5687 // Prints an XML representation of a TestInfo object.
5688 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5689 const char* test_suite_name,
5690 const TestInfo& test_info) {
5691 const TestResult& result = *test_info.result();
5692 const std::string kTestsuite = "testcase";
5693
5694 if (test_info.is_in_another_shard()) {
5695 return;
5696 }
5697
5698 *stream << " <testcase";
5699 OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
5700
5701 if (test_info.value_param() != nullptr) {
5702 OutputXmlAttribute(stream, kTestsuite, "value_param",
5703 test_info.value_param());
5704 }
5705 if (test_info.type_param() != nullptr) {
5706 OutputXmlAttribute(stream, kTestsuite, "type_param",
5707 test_info.type_param());
5708 }
5709 if (GTEST_FLAG(list_tests)) {
5710 OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
5711 OutputXmlAttribute(stream, kTestsuite, "line",
5712 StreamableToString(test_info.line()));
5713 *stream << " />\n";
5714 return;
5715 }
5716
5717 OutputXmlAttribute(stream, kTestsuite, "status",
5718 test_info.should_run() ? "run" : "notrun");
5719 OutputXmlAttribute(stream, kTestsuite, "result",
5720 test_info.should_run()
5721 ? (result.Skipped() ? "skipped" : "completed")
5722 : "suppressed");
5723 OutputXmlAttribute(stream, kTestsuite, "time",
5724 FormatTimeInMillisAsSeconds(result.elapsed_time()));
5725 OutputXmlAttribute(
5726 stream, kTestsuite, "timestamp",
5727 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
5728 OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
5729
5730 OutputXmlTestResult(stream, result);
5731 }
5732
5733 void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
5734 const TestResult& result) {
5735 int failures = 0;
5736 int skips = 0;
5737 for (int i = 0; i < result.total_part_count(); ++i) {
5738 const TestPartResult& part = result.GetTestPartResult(i);
5739 if (part.failed()) {
5740 if (++failures == 1 && skips == 0) {
5741 *stream << ">\n";
5742 }
5743 const std::string location =
5744 internal::FormatCompilerIndependentFileLocation(part.file_name(),
5745 part.line_number());
5746 const std::string summary = location + "\n" + part.summary();
5747 *stream << " <failure message=\""
5748 << EscapeXmlAttribute(summary)
5749 << "\" type=\"\">";
5750 const std::string detail = location + "\n" + part.message();
5751 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5752 *stream << "</failure>\n";
5753 } else if (part.skipped()) {
5754 if (++skips == 1 && failures == 0) {
5755 *stream << ">\n";
5756 }
5757 const std::string location =
5758 internal::FormatCompilerIndependentFileLocation(part.file_name(),
5759 part.line_number());
5760 const std::string summary = location + "\n" + part.summary();
5761 *stream << " <skipped message=\""
5762 << EscapeXmlAttribute(summary.c_str()) << "\">";
5763 const std::string detail = location + "\n" + part.message();
5764 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5765 *stream << "</skipped>\n";
5766 }
5767 }
5768
5769 if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
5770 *stream << " />\n";
5771 } else {
5772 if (failures == 0 && skips == 0) {
5773 *stream << ">\n";
5774 }
5775 OutputXmlTestProperties(stream, result);
5776 *stream << " </testcase>\n";
5777 }
5778 }
5779
5780 // Prints an XML representation of a TestSuite object
5781 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
5782 const TestSuite& test_suite) {
5783 const std::string kTestsuite = "testsuite";
5784 *stream << " <" << kTestsuite;
5785 OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
5786 OutputXmlAttribute(stream, kTestsuite, "tests",
5787 StreamableToString(test_suite.reportable_test_count()));
5788 if (!GTEST_FLAG(list_tests)) {
5789 OutputXmlAttribute(stream, kTestsuite, "failures",
5790 StreamableToString(test_suite.failed_test_count()));
5791 OutputXmlAttribute(
5792 stream, kTestsuite, "disabled",
5793 StreamableToString(test_suite.reportable_disabled_test_count()));
5794 OutputXmlAttribute(stream, kTestsuite, "skipped",
5795 StreamableToString(test_suite.skipped_test_count()));
5796
5797 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5798
5799 OutputXmlAttribute(stream, kTestsuite, "time",
5800 FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
5801 OutputXmlAttribute(
5802 stream, kTestsuite, "timestamp",
5803 FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
5804 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
5805 }
5806 *stream << ">\n";
5807 for (int i = 0; i < test_suite.total_test_count(); ++i) {
5808 if (test_suite.GetTestInfo(i)->is_reportable())
5809 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5810 }
5811 *stream << " </" << kTestsuite << ">\n";
5812 }
5813
5814 // Prints an XML summary of unit_test to output stream out.
5815 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5816 const UnitTest& unit_test) {
5817 const std::string kTestsuites = "testsuites";
5818
5819 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5820 *stream << "<" << kTestsuites;
5821
5822 OutputXmlAttribute(stream, kTestsuites, "tests",
5823 StreamableToString(unit_test.reportable_test_count()));
5824 OutputXmlAttribute(stream, kTestsuites, "failures",
5825 StreamableToString(unit_test.failed_test_count()));
5826 OutputXmlAttribute(
5827 stream, kTestsuites, "disabled",
5828 StreamableToString(unit_test.reportable_disabled_test_count()));
5829 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5830 OutputXmlAttribute(stream, kTestsuites, "time",
5831 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5832 OutputXmlAttribute(
5833 stream, kTestsuites, "timestamp",
5834 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5835
5836 if (GTEST_FLAG(shuffle)) {
5837 OutputXmlAttribute(stream, kTestsuites, "random_seed",
5838 StreamableToString(unit_test.random_seed()));
5839 }
5840 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5841
5842 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5843 *stream << ">\n";
5844
5845 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5846 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
5847 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
5848 }
5849
5850 // If there was a test failure outside of one of the test suites (like in a
5851 // test environment) include that in the output.
5852 if (unit_test.ad_hoc_test_result().Failed()) {
5853 OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
5854 }
5855
5856 *stream << "</" << kTestsuites << ">\n";
5857 }
5858
5859 void XmlUnitTestResultPrinter::PrintXmlTestsList(
5860 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5861 const std::string kTestsuites = "testsuites";
5862
5863 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5864 *stream << "<" << kTestsuites;
5865
5866 int total_tests = 0;
5867 for (auto test_suite : test_suites) {
5868 total_tests += test_suite->total_test_count();
5869 }
5870 OutputXmlAttribute(stream, kTestsuites, "tests",
5871 StreamableToString(total_tests));
5872 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5873 *stream << ">\n";
5874
5875 for (auto test_suite : test_suites) {
5876 PrintXmlTestSuite(stream, *test_suite);
5877 }
5878 *stream << "</" << kTestsuites << ">\n";
5879 }
5880
5881 // Produces a string representing the test properties in a result as space
5882 // delimited XML attributes based on the property key="value" pairs.
5883 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5884 const TestResult& result) {
5885 Message attributes;
5886 for (int i = 0; i < result.test_property_count(); ++i) {
5887 const TestProperty& property = result.GetTestProperty(i);
5888 attributes << " " << property.key() << "="
5889 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5890 }
5891 return attributes.GetString();
5892 }
5893
5894 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5895 std::ostream* stream, const TestResult& result) {
5896 const std::string kProperties = "properties";
5897 const std::string kProperty = "property";
5898
5899 if (result.test_property_count() <= 0) {
5900 return;
5901 }
5902
5903 *stream << "<" << kProperties << ">\n";
5904 for (int i = 0; i < result.test_property_count(); ++i) {
5905 const TestProperty& property = result.GetTestProperty(i);
5906 *stream << "<" << kProperty;
5907 *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
5908 *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
5909 *stream << "/>\n";
5910 }
5911 *stream << "</" << kProperties << ">\n";
5912 }
5913
5914 // End XmlUnitTestResultPrinter
5915
5916 // This class generates an JSON output file.
5917 class JsonUnitTestResultPrinter : public EmptyTestEventListener {
5918 public:
5919 explicit JsonUnitTestResultPrinter(const char* output_file);
5920
5921 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5922
5923 // Prints an JSON summary of all unit tests.
5924 static void PrintJsonTestList(::std::ostream* stream,
5925 const std::vector<TestSuite*>& test_suites);
5926
5927 private:
5928 // Returns an JSON-escaped copy of the input string str.
5929 static std::string EscapeJson(const std::string& str);
5930
5931 //// Verifies that the given attribute belongs to the given element and
5932 //// streams the attribute as JSON.
5933 static void OutputJsonKey(std::ostream* stream,
5934 const std::string& element_name,
5935 const std::string& name,
5936 const std::string& value,
5937 const std::string& indent,
5938 bool comma = true);
5939 static void OutputJsonKey(std::ostream* stream,
5940 const std::string& element_name,
5941 const std::string& name,
5942 int value,
5943 const std::string& indent,
5944 bool comma = true);
5945
5946 // Streams a test suite JSON stanza containing the given test result.
5947 //
5948 // Requires: result.Failed()
5949 static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
5950 const TestResult& result);
5951
5952 // Streams a JSON representation of a TestResult object.
5953 static void OutputJsonTestResult(::std::ostream* stream,
5954 const TestResult& result);
5955
5956 // Streams a JSON representation of a TestInfo object.
5957 static void OutputJsonTestInfo(::std::ostream* stream,
5958 const char* test_suite_name,
5959 const TestInfo& test_info);
5960
5961 // Prints a JSON representation of a TestSuite object
5962 static void PrintJsonTestSuite(::std::ostream* stream,
5963 const TestSuite& test_suite);
5964
5965 // Prints a JSON summary of unit_test to output stream out.
5966 static void PrintJsonUnitTest(::std::ostream* stream,
5967 const UnitTest& unit_test);
5968
5969 // Produces a string representing the test properties in a result as
5970 // a JSON dictionary.
5971 static std::string TestPropertiesAsJson(const TestResult& result,
5972 const std::string& indent);
5973
5974 // The output file.
5975 const std::string output_file_;
5976
5977 GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
5978 };
5979
5980 // Creates a new JsonUnitTestResultPrinter.
5981 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
5982 : output_file_(output_file) {
5983 if (output_file_.empty()) {
5984 GTEST_LOG_(FATAL) << "JSON output file may not be null";
5985 }
5986 }
5987
5988 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5989 int /*iteration*/) {
5990 FILE* jsonout = OpenFileForWriting(output_file_);
5991 std::stringstream stream;
5992 PrintJsonUnitTest(&stream, unit_test);
5993 fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
5994 fclose(jsonout);
5995 }
5996
5997 // Returns an JSON-escaped copy of the input string str.
5998 std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
5999 Message m;
6000
6001 for (size_t i = 0; i < str.size(); ++i) {
6002 const char ch = str[i];
6003 switch (ch) {
6004 case '\\':
6005 case '"':
6006 case '/':
6007 m << '\\' << ch;
6008 break;
6009 case '\b':
6010 m << "\\b";
6011 break;
6012 case '\t':
6013 m << "\\t";
6014 break;
6015 case '\n':
6016 m << "\\n";
6017 break;
6018 case '\f':
6019 m << "\\f";
6020 break;
6021 case '\r':
6022 m << "\\r";
6023 break;
6024 default:
6025 if (ch < ' ') {
6026 m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
6027 } else {
6028 m << ch;
6029 }
6030 break;
6031 }
6032 }
6033
6034 return m.GetString();
6035 }
6036
6037 // The following routines generate an JSON representation of a UnitTest
6038 // object.
6039
6040 // Formats the given time in milliseconds as seconds.
6041 static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
6042 ::std::stringstream ss;
6043 ss << (static_cast<double>(ms) * 1e-3) << "s";
6044 return ss.str();
6045 }
6046
6047 // Converts the given epoch time in milliseconds to a date string in the
6048 // RFC3339 format, without the timezone information.
6049 static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
6050 struct tm time_struct;
6051 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
6052 return "";
6053 // YYYY-MM-DDThh:mm:ss
6054 return StreamableToString(time_struct.tm_year + 1900) + "-" +
6055 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
6056 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
6057 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
6058 String::FormatIntWidth2(time_struct.tm_min) + ":" +
6059 String::FormatIntWidth2(time_struct.tm_sec) + "Z";
6060 }
6061
6062 static inline std::string Indent(size_t width) {
6063 return std::string(width, ' ');
6064 }
6065
6066 void JsonUnitTestResultPrinter::OutputJsonKey(
6067 std::ostream* stream,
6068 const std::string& element_name,
6069 const std::string& name,
6070 const std::string& value,
6071 const std::string& indent,
6072 bool comma) {
6073 const std::vector<std::string>& allowed_names =
6074 GetReservedOutputAttributesForElement(element_name);
6075
6076 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
6077 allowed_names.end())
6078 << "Key \"" << name << "\" is not allowed for value \"" << element_name
6079 << "\".";
6080
6081 *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
6082 if (comma)
6083 *stream << ",\n";
6084 }
6085
6086 void JsonUnitTestResultPrinter::OutputJsonKey(
6087 std::ostream* stream,
6088 const std::string& element_name,
6089 const std::string& name,
6090 int value,
6091 const std::string& indent,
6092 bool comma) {
6093 const std::vector<std::string>& allowed_names =
6094 GetReservedOutputAttributesForElement(element_name);
6095
6096 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
6097 allowed_names.end())
6098 << "Key \"" << name << "\" is not allowed for value \"" << element_name
6099 << "\".";
6100
6101 *stream << indent << "\"" << name << "\": " << StreamableToString(value);
6102 if (comma)
6103 *stream << ",\n";
6104 }
6105
6106 // Streams a test suite JSON stanza containing the given test result.
6107 void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
6108 ::std::ostream* stream, const TestResult& result) {
6109 // Output the boilerplate for a new test suite.
6110 *stream << Indent(4) << "{\n";
6111 OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
6112 OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
6113 if (!GTEST_FLAG(list_tests)) {
6114 OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
6115 OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
6116 OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
6117 OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
6118 OutputJsonKey(stream, "testsuite", "time",
6119 FormatTimeInMillisAsDuration(result.elapsed_time()),
6120 Indent(6));
6121 OutputJsonKey(stream, "testsuite", "timestamp",
6122 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
6123 Indent(6));
6124 }
6125 *stream << Indent(6) << "\"testsuite\": [\n";
6126
6127 // Output the boilerplate for a new test case.
6128 *stream << Indent(8) << "{\n";
6129 OutputJsonKey(stream, "testcase", "name", "", Indent(10));
6130 OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
6131 OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
6132 OutputJsonKey(stream, "testcase", "timestamp",
6133 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
6134 Indent(10));
6135 OutputJsonKey(stream, "testcase", "time",
6136 FormatTimeInMillisAsDuration(result.elapsed_time()),
6137 Indent(10));
6138 OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
6139 *stream << TestPropertiesAsJson(result, Indent(10));
6140
6141 // Output the actual test result.
6142 OutputJsonTestResult(stream, result);
6143
6144 // Finish the test suite.
6145 *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
6146 }
6147
6148 // Prints a JSON representation of a TestInfo object.
6149 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
6150 const char* test_suite_name,
6151 const TestInfo& test_info) {
6152 const TestResult& result = *test_info.result();
6153 const std::string kTestsuite = "testcase";
6154 const std::string kIndent = Indent(10);
6155
6156 *stream << Indent(8) << "{\n";
6157 OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
6158
6159 if (test_info.value_param() != nullptr) {
6160 OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
6161 kIndent);
6162 }
6163 if (test_info.type_param() != nullptr) {
6164 OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
6165 kIndent);
6166 }
6167 if (GTEST_FLAG(list_tests)) {
6168 OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
6169 OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
6170 *stream << "\n" << Indent(8) << "}";
6171 return;
6172 }
6173
6174 OutputJsonKey(stream, kTestsuite, "status",
6175 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
6176 OutputJsonKey(stream, kTestsuite, "result",
6177 test_info.should_run()
6178 ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
6179 : "SUPPRESSED",
6180 kIndent);
6181 OutputJsonKey(stream, kTestsuite, "timestamp",
6182 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
6183 kIndent);
6184 OutputJsonKey(stream, kTestsuite, "time",
6185 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
6186 OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
6187 false);
6188 *stream << TestPropertiesAsJson(result, kIndent);
6189
6190 OutputJsonTestResult(stream, result);
6191 }
6192
6193 void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
6194 const TestResult& result) {
6195 const std::string kIndent = Indent(10);
6196
6197 int failures = 0;
6198 for (int i = 0; i < result.total_part_count(); ++i) {
6199 const TestPartResult& part = result.GetTestPartResult(i);
6200 if (part.failed()) {
6201 *stream << ",\n";
6202 if (++failures == 1) {
6203 *stream << kIndent << "\"" << "failures" << "\": [\n";
6204 }
6205 const std::string location =
6206 internal::FormatCompilerIndependentFileLocation(part.file_name(),
6207 part.line_number());
6208 const std::string message = EscapeJson(location + "\n" + part.message());
6209 *stream << kIndent << " {\n"
6210 << kIndent << " \"failure\": \"" << message << "\",\n"
6211 << kIndent << " \"type\": \"\"\n"
6212 << kIndent << " }";
6213 }
6214 }
6215
6216 if (failures > 0)
6217 *stream << "\n" << kIndent << "]";
6218 *stream << "\n" << Indent(8) << "}";
6219 }
6220
6221 // Prints an JSON representation of a TestSuite object
6222 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
6223 std::ostream* stream, const TestSuite& test_suite) {
6224 const std::string kTestsuite = "testsuite";
6225 const std::string kIndent = Indent(6);
6226
6227 *stream << Indent(4) << "{\n";
6228 OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
6229 OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
6230 kIndent);
6231 if (!GTEST_FLAG(list_tests)) {
6232 OutputJsonKey(stream, kTestsuite, "failures",
6233 test_suite.failed_test_count(), kIndent);
6234 OutputJsonKey(stream, kTestsuite, "disabled",
6235 test_suite.reportable_disabled_test_count(), kIndent);
6236 OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
6237 OutputJsonKey(
6238 stream, kTestsuite, "timestamp",
6239 FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
6240 kIndent);
6241 OutputJsonKey(stream, kTestsuite, "time",
6242 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
6243 kIndent, false);
6244 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
6245 << ",\n";
6246 }
6247
6248 *stream << kIndent << "\"" << kTestsuite << "\": [\n";
6249
6250 bool comma = false;
6251 for (int i = 0; i < test_suite.total_test_count(); ++i) {
6252 if (test_suite.GetTestInfo(i)->is_reportable()) {
6253 if (comma) {
6254 *stream << ",\n";
6255 } else {
6256 comma = true;
6257 }
6258 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
6259 }
6260 }
6261 *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
6262 }
6263
6264 // Prints a JSON summary of unit_test to output stream out.
6265 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
6266 const UnitTest& unit_test) {
6267 const std::string kTestsuites = "testsuites";
6268 const std::string kIndent = Indent(2);
6269 *stream << "{\n";
6270
6271 OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
6272 kIndent);
6273 OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
6274 kIndent);
6275 OutputJsonKey(stream, kTestsuites, "disabled",
6276 unit_test.reportable_disabled_test_count(), kIndent);
6277 OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
6278 if (GTEST_FLAG(shuffle)) {
6279 OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
6280 kIndent);
6281 }
6282 OutputJsonKey(stream, kTestsuites, "timestamp",
6283 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
6284 kIndent);
6285 OutputJsonKey(stream, kTestsuites, "time",
6286 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
6287 false);
6288
6289 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
6290 << ",\n";
6291
6292 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
6293 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
6294
6295 bool comma = false;
6296 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
6297 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
6298 if (comma) {
6299 *stream << ",\n";
6300 } else {
6301 comma = true;
6302 }
6303 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
6304 }
6305 }
6306
6307 // If there was a test failure outside of one of the test suites (like in a
6308 // test environment) include that in the output.
6309 if (unit_test.ad_hoc_test_result().Failed()) {
6310 OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
6311 }
6312
6313 *stream << "\n" << kIndent << "]\n" << "}\n";
6314 }
6315
6316 void JsonUnitTestResultPrinter::PrintJsonTestList(
6317 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
6318 const std::string kTestsuites = "testsuites";
6319 const std::string kIndent = Indent(2);
6320 *stream << "{\n";
6321 int total_tests = 0;
6322 for (auto test_suite : test_suites) {
6323 total_tests += test_suite->total_test_count();
6324 }
6325 OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
6326
6327 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
6328 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
6329
6330 for (size_t i = 0; i < test_suites.size(); ++i) {
6331 if (i != 0) {
6332 *stream << ",\n";
6333 }
6334 PrintJsonTestSuite(stream, *test_suites[i]);
6335 }
6336
6337 *stream << "\n"
6338 << kIndent << "]\n"
6339 << "}\n";
6340 }
6341 // Produces a string representing the test properties in a result as
6342 // a JSON dictionary.
6343 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
6344 const TestResult& result, const std::string& indent) {
6345 Message attributes;
6346 for (int i = 0; i < result.test_property_count(); ++i) {
6347 const TestProperty& property = result.GetTestProperty(i);
6348 attributes << ",\n" << indent << "\"" << property.key() << "\": "
6349 << "\"" << EscapeJson(property.value()) << "\"";
6350 }
6351 return attributes.GetString();
6352 }
6353
6354 // End JsonUnitTestResultPrinter
6355
6356 #if GTEST_CAN_STREAM_RESULTS_
6357
6358 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
6359 // replaces them by "%xx" where xx is their hexadecimal value. For
6360 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
6361 // in both time and space -- important as the input str may contain an
6362 // arbitrarily long test failure message and stack trace.
6363 std::string StreamingListener::UrlEncode(const char* str) {
6364 std::string result;
6365 result.reserve(strlen(str) + 1);
6366 for (char ch = *str; ch != '\0'; ch = *++str) {
6367 switch (ch) {
6368 case '%':
6369 case '=':
6370 case '&':
6371 case '\n':
6372 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
6373 break;
6374 default:
6375 result.push_back(ch);
6376 break;
6377 }
6378 }
6379 return result;
6380 }
6381
6382 void StreamingListener::SocketWriter::MakeConnection() {
6383 GTEST_CHECK_(sockfd_ == -1)
6384 << "MakeConnection() can't be called when there is already a connection.";
6385
6386 addrinfo hints;
6387 memset(&hints, 0, sizeof(hints));
6388 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
6389 hints.ai_socktype = SOCK_STREAM;
6390 addrinfo* servinfo = nullptr;
6391
6392 // Use the getaddrinfo() to get a linked list of IP addresses for
6393 // the given host name.
6394 const int error_num = getaddrinfo(
6395 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
6396 if (error_num != 0) {
6397 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
6398 << gai_strerror(error_num);
6399 }
6400
6401 // Loop through all the results and connect to the first we can.
6402 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
6403 cur_addr = cur_addr->ai_next) {
6404 sockfd_ = socket(
6405 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
6406 if (sockfd_ != -1) {
6407 // Connect the client socket to the server socket.
6408 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
6409 close(sockfd_);
6410 sockfd_ = -1;
6411 }
6412 }
6413 }
6414
6415 freeaddrinfo(servinfo); // all done with this structure
6416
6417 if (sockfd_ == -1) {
6418 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
6419 << host_name_ << ":" << port_num_;
6420 }
6421 }
6422
6423 // End of class Streaming Listener
6424 #endif // GTEST_CAN_STREAM_RESULTS__
6425
6426 // class OsStackTraceGetter
6427
6428 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
6429 "... " GTEST_NAME_ " internal frames ...";
6430
6431 std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
6432 GTEST_LOCK_EXCLUDED_(mutex_) {
6433 #if GTEST_HAS_ABSL
6434 std::string result;
6435
6436 if (max_depth <= 0) {
6437 return result;
6438 }
6439
6440 max_depth = std::min(max_depth, kMaxStackTraceDepth);
6441
6442 std::vector<void*> raw_stack(max_depth);
6443 // Skips the frames requested by the caller, plus this function.
6444 const int raw_stack_size =
6445 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
6446
6447 void* caller_frame = nullptr;
6448 {
6449 MutexLock lock(&mutex_);
6450 caller_frame = caller_frame_;
6451 }
6452
6453 for (int i = 0; i < raw_stack_size; ++i) {
6454 if (raw_stack[i] == caller_frame &&
6455 !GTEST_FLAG(show_internal_stack_frames)) {
6456 // Add a marker to the trace and stop adding frames.
6457 absl::StrAppend(&result, kElidedFramesMarker, "\n");
6458 break;
6459 }
6460
6461 char tmp[1024];
6462 const char* symbol = "(unknown)";
6463 if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
6464 symbol = tmp;
6465 }
6466
6467 char line[1024];
6468 snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
6469 result += line;
6470 }
6471
6472 return result;
6473
6474 #else // !GTEST_HAS_ABSL
6475 static_cast<void>(max_depth);
6476 static_cast<void>(skip_count);
6477 return "";
6478 #endif // GTEST_HAS_ABSL
6479 }
6480
6481 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
6482 #if GTEST_HAS_ABSL
6483 void* caller_frame = nullptr;
6484 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
6485 caller_frame = nullptr;
6486 }
6487
6488 MutexLock lock(&mutex_);
6489 caller_frame_ = caller_frame;
6490 #endif // GTEST_HAS_ABSL
6491 }
6492
6493 // A helper class that creates the premature-exit file in its
6494 // constructor and deletes the file in its destructor.
6495 class ScopedPrematureExitFile {
6496 public:
6497 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
6498 : premature_exit_filepath_(premature_exit_filepath ?
6499 premature_exit_filepath : "") {
6500 // If a path to the premature-exit file is specified...
6501 if (!premature_exit_filepath_.empty()) {
6502 // create the file with a single "0" character in it. I/O
6503 // errors are ignored as there's nothing better we can do and we
6504 // don't want to fail the test because of this.
6505 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
6506 fwrite("0", 1, 1, pfile);
6507 fclose(pfile);
6508 }
6509 }
6510
6511 ~ScopedPrematureExitFile() {
6512 #if !defined GTEST_OS_ESP8266
6513 if (!premature_exit_filepath_.empty()) {
6514 int retval = remove(premature_exit_filepath_.c_str());
6515 if (retval) {
6516 GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
6517 << premature_exit_filepath_ << "\" with error "
6518 << retval;
6519 }
6520 }
6521 #endif
6522 }
6523
6524 private:
6525 const std::string premature_exit_filepath_;
6526
6527 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
6528 };
6529
6530 } // namespace internal
6531
6532 // class TestEventListeners
6533
6534 TestEventListeners::TestEventListeners()
6535 : repeater_(new internal::TestEventRepeater()),
6536 default_result_printer_(nullptr),
6537 default_xml_generator_(nullptr) {}
6538
6539 TestEventListeners::~TestEventListeners() { delete repeater_; }
6540
6541 // Returns the standard listener responsible for the default console
6542 // output. Can be removed from the listeners list to shut down default
6543 // console output. Note that removing this object from the listener list
6544 // with Release transfers its ownership to the user.
6545 void TestEventListeners::Append(TestEventListener* listener) {
6546 repeater_->Append(listener);
6547 }
6548
6549 // Removes the given event listener from the list and returns it. It then
6550 // becomes the caller's responsibility to delete the listener. Returns
6551 // NULL if the listener is not found in the list.
6552 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
6553 if (listener == default_result_printer_)
6554 default_result_printer_ = nullptr;
6555 else if (listener == default_xml_generator_)
6556 default_xml_generator_ = nullptr;
6557 return repeater_->Release(listener);
6558 }
6559
6560 // Returns repeater that broadcasts the TestEventListener events to all
6561 // subscribers.
6562 TestEventListener* TestEventListeners::repeater() { return repeater_; }
6563
6564 // Sets the default_result_printer attribute to the provided listener.
6565 // The listener is also added to the listener list and previous
6566 // default_result_printer is removed from it and deleted. The listener can
6567 // also be NULL in which case it will not be added to the list. Does
6568 // nothing if the previous and the current listener objects are the same.
6569 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
6570 if (default_result_printer_ != listener) {
6571 // It is an error to pass this method a listener that is already in the
6572 // list.
6573 delete Release(default_result_printer_);
6574 default_result_printer_ = listener;
6575 if (listener != nullptr) Append(listener);
6576 }
6577 }
6578
6579 // Sets the default_xml_generator attribute to the provided listener. The
6580 // listener is also added to the listener list and previous
6581 // default_xml_generator is removed from it and deleted. The listener can
6582 // also be NULL in which case it will not be added to the list. Does
6583 // nothing if the previous and the current listener objects are the same.
6584 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
6585 if (default_xml_generator_ != listener) {
6586 // It is an error to pass this method a listener that is already in the
6587 // list.
6588 delete Release(default_xml_generator_);
6589 default_xml_generator_ = listener;
6590 if (listener != nullptr) Append(listener);
6591 }
6592 }
6593
6594 // Controls whether events will be forwarded by the repeater to the
6595 // listeners in the list.
6596 bool TestEventListeners::EventForwardingEnabled() const {
6597 return repeater_->forwarding_enabled();
6598 }
6599
6600 void TestEventListeners::SuppressEventForwarding() {
6601 repeater_->set_forwarding_enabled(false);
6602 }
6603
6604 // class UnitTest
6605
6606 // Gets the singleton UnitTest object. The first time this method is
6607 // called, a UnitTest object is constructed and returned. Consecutive
6608 // calls will return the same object.
6609 //
6610 // We don't protect this under mutex_ as a user is not supposed to
6611 // call this before main() starts, from which point on the return
6612 // value will never change.
6613 UnitTest* UnitTest::GetInstance() {
6614 // CodeGear C++Builder insists on a public destructor for the
6615 // default implementation. Use this implementation to keep good OO
6616 // design with private destructor.
6617
6618 #if defined(__BORLANDC__)
6619 static UnitTest* const instance = new UnitTest;
6620 return instance;
6621 #else
6622 static UnitTest instance;
6623 return &instance;
6624 #endif // defined(__BORLANDC__)
6625 }
6626
6627 // Gets the number of successful test suites.
6628 int UnitTest::successful_test_suite_count() const {
6629 return impl()->successful_test_suite_count();
6630 }
6631
6632 // Gets the number of failed test suites.
6633 int UnitTest::failed_test_suite_count() const {
6634 return impl()->failed_test_suite_count();
6635 }
6636
6637 // Gets the number of all test suites.
6638 int UnitTest::total_test_suite_count() const {
6639 return impl()->total_test_suite_count();
6640 }
6641
6642 // Gets the number of all test suites that contain at least one test
6643 // that should run.
6644 int UnitTest::test_suite_to_run_count() const {
6645 return impl()->test_suite_to_run_count();
6646 }
6647
6648 // Legacy API is deprecated but still available
6649 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6650 int UnitTest::successful_test_case_count() const {
6651 return impl()->successful_test_suite_count();
6652 }
6653 int UnitTest::failed_test_case_count() const {
6654 return impl()->failed_test_suite_count();
6655 }
6656 int UnitTest::total_test_case_count() const {
6657 return impl()->total_test_suite_count();
6658 }
6659 int UnitTest::test_case_to_run_count() const {
6660 return impl()->test_suite_to_run_count();
6661 }
6662 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6663
6664 // Gets the number of successful tests.
6665 int UnitTest::successful_test_count() const {
6666 return impl()->successful_test_count();
6667 }
6668
6669 // Gets the number of skipped tests.
6670 int UnitTest::skipped_test_count() const {
6671 return impl()->skipped_test_count();
6672 }
6673
6674 // Gets the number of failed tests.
6675 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
6676
6677 // Gets the number of disabled tests that will be reported in the XML report.
6678 int UnitTest::reportable_disabled_test_count() const {
6679 return impl()->reportable_disabled_test_count();
6680 }
6681
6682 // Gets the number of disabled tests.
6683 int UnitTest::disabled_test_count() const {
6684 return impl()->disabled_test_count();
6685 }
6686
6687 // Gets the number of tests to be printed in the XML report.
6688 int UnitTest::reportable_test_count() const {
6689 return impl()->reportable_test_count();
6690 }
6691
6692 // Gets the number of all tests.
6693 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
6694
6695 // Gets the number of tests that should run.
6696 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
6697
6698 // Gets the time of the test program start, in ms from the start of the
6699 // UNIX epoch.
6700 internal::TimeInMillis UnitTest::start_timestamp() const {
6701 return impl()->start_timestamp();
6702 }
6703
6704 // Gets the elapsed time, in milliseconds.
6705 internal::TimeInMillis UnitTest::elapsed_time() const {
6706 return impl()->elapsed_time();
6707 }
6708
6709 // Returns true if and only if the unit test passed (i.e. all test suites
6710 // passed).
6711 bool UnitTest::Passed() const { return impl()->Passed(); }
6712
6713 // Returns true if and only if the unit test failed (i.e. some test suite
6714 // failed or something outside of all tests failed).
6715 bool UnitTest::Failed() const { return impl()->Failed(); }
6716
6717 // Gets the i-th test suite among all the test suites. i can range from 0 to
6718 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
6719 const TestSuite* UnitTest::GetTestSuite(int i) const {
6720 return impl()->GetTestSuite(i);
6721 }
6722
6723 // Legacy API is deprecated but still available
6724 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6725 const TestCase* UnitTest::GetTestCase(int i) const {
6726 return impl()->GetTestCase(i);
6727 }
6728 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6729
6730 // Returns the TestResult containing information on test failures and
6731 // properties logged outside of individual test suites.
6732 const TestResult& UnitTest::ad_hoc_test_result() const {
6733 return *impl()->ad_hoc_test_result();
6734 }
6735
6736 // Gets the i-th test suite among all the test suites. i can range from 0 to
6737 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
6738 TestSuite* UnitTest::GetMutableTestSuite(int i) {
6739 return impl()->GetMutableSuiteCase(i);
6740 }
6741
6742 // Returns the list of event listeners that can be used to track events
6743 // inside Google Test.
6744 TestEventListeners& UnitTest::listeners() {
6745 return *impl()->listeners();
6746 }
6747
6748 // Registers and returns a global test environment. When a test
6749 // program is run, all global test environments will be set-up in the
6750 // order they were registered. After all tests in the program have
6751 // finished, all global test environments will be torn-down in the
6752 // *reverse* order they were registered.
6753 //
6754 // The UnitTest object takes ownership of the given environment.
6755 //
6756 // We don't protect this under mutex_, as we only support calling it
6757 // from the main thread.
6758 Environment* UnitTest::AddEnvironment(Environment* env) {
6759 if (env == nullptr) {
6760 return nullptr;
6761 }
6762
6763 impl_->environments().push_back(env);
6764 return env;
6765 }
6766
6767 // Adds a TestPartResult to the current TestResult object. All Google Test
6768 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
6769 // this to report their results. The user code should use the
6770 // assertion macros instead of calling this directly.
6771 void UnitTest::AddTestPartResult(
6772 TestPartResult::Type result_type,
6773 const char* file_name,
6774 int line_number,
6775 const std::string& message,
6776 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
6777 Message msg;
6778 msg << message;
6779
6780 internal::MutexLock lock(&mutex_);
6781 if (impl_->gtest_trace_stack().size() > 0) {
6782 msg << "\n" << GTEST_NAME_ << " trace:";
6783
6784 for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
6785 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6786 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
6787 << " " << trace.message;
6788 }
6789 }
6790
6791 if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
6792 msg << internal::kStackTraceMarker << os_stack_trace;
6793 }
6794
6795 const TestPartResult result = TestPartResult(
6796 result_type, file_name, line_number, msg.GetString().c_str());
6797 impl_->GetTestPartResultReporterForCurrentThread()->
6798 ReportTestPartResult(result);
6799
6800 if (result_type != TestPartResult::kSuccess &&
6801 result_type != TestPartResult::kSkip) {
6802 // gtest_break_on_failure takes precedence over
6803 // gtest_throw_on_failure. This allows a user to set the latter
6804 // in the code (perhaps in order to use Google Test assertions
6805 // with another testing framework) and specify the former on the
6806 // command line for debugging.
6807 if (GTEST_FLAG(break_on_failure)) {
6808 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6809 // Using DebugBreak on Windows allows gtest to still break into a debugger
6810 // when a failure happens and both the --gtest_break_on_failure and
6811 // the --gtest_catch_exceptions flags are specified.
6812 DebugBreak();
6813 #elif (!defined(__native_client__)) && \
6814 ((defined(__clang__) || defined(__GNUC__)) && \
6815 (defined(__x86_64__) || defined(__i386__)))
6816 // with clang/gcc we can achieve the same effect on x86 by invoking int3
6817 asm("int3");
6818 #else
6819 // Dereference nullptr through a volatile pointer to prevent the compiler
6820 // from removing. We use this rather than abort() or __builtin_trap() for
6821 // portability: some debuggers don't correctly trap abort().
6822 *static_cast<volatile int*>(nullptr) = 1;
6823 #endif // GTEST_OS_WINDOWS
6824 } else if (GTEST_FLAG(throw_on_failure)) {
6825 #if GTEST_HAS_EXCEPTIONS
6826 throw internal::GoogleTestFailureException(result);
6827 #else
6828 // We cannot call abort() as it generates a pop-up in debug mode
6829 // that cannot be suppressed in VC 7.1 or below.
6830 exit(1);
6831 #endif
6832 }
6833 }
6834 }
6835
6836 // Adds a TestProperty to the current TestResult object when invoked from
6837 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
6838 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
6839 // when invoked elsewhere. If the result already contains a property with
6840 // the same key, the value will be updated.
6841 void UnitTest::RecordProperty(const std::string& key,
6842 const std::string& value) {
6843 impl_->RecordProperty(TestProperty(key, value));
6844 }
6845
6846 // Runs all tests in this UnitTest object and prints the result.
6847 // Returns 0 if successful, or 1 otherwise.
6848 //
6849 // We don't protect this under mutex_, as we only support calling it
6850 // from the main thread.
6851 int UnitTest::Run() {
6852 const bool in_death_test_child_process =
6853 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
6854
6855 // Google Test implements this protocol for catching that a test
6856 // program exits before returning control to Google Test:
6857 //
6858 // 1. Upon start, Google Test creates a file whose absolute path
6859 // is specified by the environment variable
6860 // TEST_PREMATURE_EXIT_FILE.
6861 // 2. When Google Test has finished its work, it deletes the file.
6862 //
6863 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
6864 // running a Google-Test-based test program and check the existence
6865 // of the file at the end of the test execution to see if it has
6866 // exited prematurely.
6867
6868 // If we are in the child process of a death test, don't
6869 // create/delete the premature exit file, as doing so is unnecessary
6870 // and will confuse the parent process. Otherwise, create/delete
6871 // the file upon entering/leaving this function. If the program
6872 // somehow exits before this function has a chance to return, the
6873 // premature-exit file will be left undeleted, causing a test runner
6874 // that understands the premature-exit-file protocol to report the
6875 // test as having failed.
6876 const internal::ScopedPrematureExitFile premature_exit_file(
6877 in_death_test_child_process
6878 ? nullptr
6879 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
6880
6881 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
6882 // used for the duration of the program.
6883 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
6884
6885 #if GTEST_OS_WINDOWS
6886 // Either the user wants Google Test to catch exceptions thrown by the
6887 // tests or this is executing in the context of death test child
6888 // process. In either case the user does not want to see pop-up dialogs
6889 // about crashes - they are expected.
6890 if (impl()->catch_exceptions() || in_death_test_child_process) {
6891 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6892 // SetErrorMode doesn't exist on CE.
6893 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6894 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6895 # endif // !GTEST_OS_WINDOWS_MOBILE
6896
6897 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
6898 // Death test children can be terminated with _abort(). On Windows,
6899 // _abort() can show a dialog with a warning message. This forces the
6900 // abort message to go to stderr instead.
6901 _set_error_mode(_OUT_TO_STDERR);
6902 # endif
6903
6904 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
6905 // In the debug version, Visual Studio pops up a separate dialog
6906 // offering a choice to debug the aborted program. We need to suppress
6907 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
6908 // executed. Google Test will notify the user of any unexpected
6909 // failure via stderr.
6910 if (!GTEST_FLAG(break_on_failure))
6911 _set_abort_behavior(
6912 0x0, // Clear the following flags:
6913 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
6914
6915 // In debug mode, the Windows CRT can crash with an assertion over invalid
6916 // input (e.g. passing an invalid file descriptor). The default handling
6917 // for these assertions is to pop up a dialog and wait for user input.
6918 // Instead ask the CRT to dump such assertions to stderr non-interactively.
6919 if (!IsDebuggerPresent()) {
6920 (void)_CrtSetReportMode(_CRT_ASSERT,
6921 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
6922 (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
6923 }
6924 # endif
6925 }
6926 #endif // GTEST_OS_WINDOWS
6927
6928 return internal::HandleExceptionsInMethodIfSupported(
6929 impl(),
6930 &internal::UnitTestImpl::RunAllTests,
6931 "auxiliary test code (environments or event listeners)") ? 0 : 1;
6932 }
6933
6934 // Returns the working directory when the first TEST() or TEST_F() was
6935 // executed.
6936 const char* UnitTest::original_working_dir() const {
6937 return impl_->original_working_dir_.c_str();
6938 }
6939
6940 // Returns the TestSuite object for the test that's currently running,
6941 // or NULL if no test is running.
6942 const TestSuite* UnitTest::current_test_suite() const
6943 GTEST_LOCK_EXCLUDED_(mutex_) {
6944 internal::MutexLock lock(&mutex_);
6945 return impl_->current_test_suite();
6946 }
6947
6948 // Legacy API is still available but deprecated
6949 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6950 const TestCase* UnitTest::current_test_case() const
6951 GTEST_LOCK_EXCLUDED_(mutex_) {
6952 internal::MutexLock lock(&mutex_);
6953 return impl_->current_test_suite();
6954 }
6955 #endif
6956
6957 // Returns the TestInfo object for the test that's currently running,
6958 // or NULL if no test is running.
6959 const TestInfo* UnitTest::current_test_info() const
6960 GTEST_LOCK_EXCLUDED_(mutex_) {
6961 internal::MutexLock lock(&mutex_);
6962 return impl_->current_test_info();
6963 }
6964
6965 // Returns the random seed used at the start of the current test run.
6966 int UnitTest::random_seed() const { return impl_->random_seed(); }
6967
6968 // Returns ParameterizedTestSuiteRegistry object used to keep track of
6969 // value-parameterized tests and instantiate and register them.
6970 internal::ParameterizedTestSuiteRegistry&
6971 UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
6972 return impl_->parameterized_test_registry();
6973 }
6974
6975 // Creates an empty UnitTest.
6976 UnitTest::UnitTest() {
6977 impl_ = new internal::UnitTestImpl(this);
6978 }
6979
6980 // Destructor of UnitTest.
6981 UnitTest::~UnitTest() {
6982 delete impl_;
6983 }
6984
6985 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
6986 // Google Test trace stack.
6987 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
6988 GTEST_LOCK_EXCLUDED_(mutex_) {
6989 internal::MutexLock lock(&mutex_);
6990 impl_->gtest_trace_stack().push_back(trace);
6991 }
6992
6993 // Pops a trace from the per-thread Google Test trace stack.
6994 void UnitTest::PopGTestTrace()
6995 GTEST_LOCK_EXCLUDED_(mutex_) {
6996 internal::MutexLock lock(&mutex_);
6997 impl_->gtest_trace_stack().pop_back();
6998 }
6999
7000 namespace internal {
7001
7002 UnitTestImpl::UnitTestImpl(UnitTest* parent)
7003 : parent_(parent),
7004 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
7005 default_global_test_part_result_reporter_(this),
7006 default_per_thread_test_part_result_reporter_(this),
7007 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
7008 &default_global_test_part_result_reporter_),
7009 per_thread_test_part_result_reporter_(
7010 &default_per_thread_test_part_result_reporter_),
7011 parameterized_test_registry_(),
7012 parameterized_tests_registered_(false),
7013 last_death_test_suite_(-1),
7014 current_test_suite_(nullptr),
7015 current_test_info_(nullptr),
7016 ad_hoc_test_result_(),
7017 os_stack_trace_getter_(nullptr),
7018 post_flag_parse_init_performed_(false),
7019 random_seed_(0), // Will be overridden by the flag before first use.
7020 random_(0), // Will be reseeded before first use.
7021 start_timestamp_(0),
7022 elapsed_time_(0),
7023 #if GTEST_HAS_DEATH_TEST
7024 death_test_factory_(new DefaultDeathTestFactory),
7025 #endif
7026 // Will be overridden by the flag before first use.
7027 catch_exceptions_(false) {
7028 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
7029 }
7030
7031 UnitTestImpl::~UnitTestImpl() {
7032 // Deletes every TestSuite.
7033 ForEach(test_suites_, internal::Delete<TestSuite>);
7034
7035 // Deletes every Environment.
7036 ForEach(environments_, internal::Delete<Environment>);
7037
7038 delete os_stack_trace_getter_;
7039 }
7040
7041 // Adds a TestProperty to the current TestResult object when invoked in a
7042 // context of a test, to current test suite's ad_hoc_test_result when invoke
7043 // from SetUpTestSuite/TearDownTestSuite, or to the global property set
7044 // otherwise. If the result already contains a property with the same key,
7045 // the value will be updated.
7046 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
7047 std::string xml_element;
7048 TestResult* test_result; // TestResult appropriate for property recording.
7049
7050 if (current_test_info_ != nullptr) {
7051 xml_element = "testcase";
7052 test_result = &(current_test_info_->result_);
7053 } else if (current_test_suite_ != nullptr) {
7054 xml_element = "testsuite";
7055 test_result = &(current_test_suite_->ad_hoc_test_result_);
7056 } else {
7057 xml_element = "testsuites";
7058 test_result = &ad_hoc_test_result_;
7059 }
7060 test_result->RecordProperty(xml_element, test_property);
7061 }
7062
7063 #if GTEST_HAS_DEATH_TEST
7064 // Disables event forwarding if the control is currently in a death test
7065 // subprocess. Must not be called before InitGoogleTest.
7066 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
7067 if (internal_run_death_test_flag_.get() != nullptr)
7068 listeners()->SuppressEventForwarding();
7069 }
7070 #endif // GTEST_HAS_DEATH_TEST
7071
7072 // Initializes event listeners performing XML output as specified by
7073 // UnitTestOptions. Must not be called before InitGoogleTest.
7074 void UnitTestImpl::ConfigureXmlOutput() {
7075 const std::string& output_format = UnitTestOptions::GetOutputFormat();
7076 if (output_format == "xml") {
7077 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
7078 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
7079 } else if (output_format == "json") {
7080 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
7081 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
7082 } else if (output_format != "") {
7083 GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
7084 << output_format << "\" ignored.";
7085 }
7086 }
7087
7088 #if GTEST_CAN_STREAM_RESULTS_
7089 // Initializes event listeners for streaming test results in string form.
7090 // Must not be called before InitGoogleTest.
7091 void UnitTestImpl::ConfigureStreamingOutput() {
7092 const std::string& target = GTEST_FLAG(stream_result_to);
7093 if (!target.empty()) {
7094 const size_t pos = target.find(':');
7095 if (pos != std::string::npos) {
7096 listeners()->Append(new StreamingListener(target.substr(0, pos),
7097 target.substr(pos+1)));
7098 } else {
7099 GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
7100 << "\" ignored.";
7101 }
7102 }
7103 }
7104 #endif // GTEST_CAN_STREAM_RESULTS_
7105
7106 // Performs initialization dependent upon flag values obtained in
7107 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
7108 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
7109 // this function is also called from RunAllTests. Since this function can be
7110 // called more than once, it has to be idempotent.
7111 void UnitTestImpl::PostFlagParsingInit() {
7112 // Ensures that this function does not execute more than once.
7113 if (!post_flag_parse_init_performed_) {
7114 post_flag_parse_init_performed_ = true;
7115
7116 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
7117 // Register to send notifications about key process state changes.
7118 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
7119 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
7120
7121 #if GTEST_HAS_DEATH_TEST
7122 InitDeathTestSubprocessControlInfo();
7123 SuppressTestEventsIfInSubprocess();
7124 #endif // GTEST_HAS_DEATH_TEST
7125
7126 // Registers parameterized tests. This makes parameterized tests
7127 // available to the UnitTest reflection API without running
7128 // RUN_ALL_TESTS.
7129 RegisterParameterizedTests();
7130
7131 // Configures listeners for XML output. This makes it possible for users
7132 // to shut down the default XML output before invoking RUN_ALL_TESTS.
7133 ConfigureXmlOutput();
7134
7135 if (GTEST_FLAG(brief)) {
7136 listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
7137 }
7138
7139 #if GTEST_CAN_STREAM_RESULTS_
7140 // Configures listeners for streaming test results to the specified server.
7141 ConfigureStreamingOutput();
7142 #endif // GTEST_CAN_STREAM_RESULTS_
7143
7144 #if GTEST_HAS_ABSL
7145 if (GTEST_FLAG(install_failure_signal_handler)) {
7146 absl::FailureSignalHandlerOptions options;
7147 absl::InstallFailureSignalHandler(options);
7148 }
7149 #endif // GTEST_HAS_ABSL
7150 }
7151 }
7152
7153 // A predicate that checks the name of a TestSuite against a known
7154 // value.
7155 //
7156 // This is used for implementation of the UnitTest class only. We put
7157 // it in the anonymous namespace to prevent polluting the outer
7158 // namespace.
7159 //
7160 // TestSuiteNameIs is copyable.
7161 class TestSuiteNameIs {
7162 public:
7163 // Constructor.
7164 explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
7165
7166 // Returns true if and only if the name of test_suite matches name_.
7167 bool operator()(const TestSuite* test_suite) const {
7168 return test_suite != nullptr &&
7169 strcmp(test_suite->name(), name_.c_str()) == 0;
7170 }
7171
7172 private:
7173 std::string name_;
7174 };
7175
7176 // Finds and returns a TestSuite with the given name. If one doesn't
7177 // exist, creates one and returns it. It's the CALLER'S
7178 // RESPONSIBILITY to ensure that this function is only called WHEN THE
7179 // TESTS ARE NOT SHUFFLED.
7180 //
7181 // Arguments:
7182 //
7183 // test_suite_name: name of the test suite
7184 // type_param: the name of the test suite's type parameter, or NULL if
7185 // this is not a typed or a type-parameterized test suite.
7186 // set_up_tc: pointer to the function that sets up the test suite
7187 // tear_down_tc: pointer to the function that tears down the test suite
7188 TestSuite* UnitTestImpl::GetTestSuite(
7189 const char* test_suite_name, const char* type_param,
7190 internal::SetUpTestSuiteFunc set_up_tc,
7191 internal::TearDownTestSuiteFunc tear_down_tc) {
7192 // Can we find a TestSuite with the given name?
7193 const auto test_suite =
7194 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
7195 TestSuiteNameIs(test_suite_name));
7196
7197 if (test_suite != test_suites_.rend()) return *test_suite;
7198
7199 // No. Let's create one.
7200 auto* const new_test_suite =
7201 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
7202
7203 // Is this a death test suite?
7204 if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
7205 kDeathTestSuiteFilter)) {
7206 // Yes. Inserts the test suite after the last death test suite
7207 // defined so far. This only works when the test suites haven't
7208 // been shuffled. Otherwise we may end up running a death test
7209 // after a non-death test.
7210 ++last_death_test_suite_;
7211 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
7212 new_test_suite);
7213 } else {
7214 // No. Appends to the end of the list.
7215 test_suites_.push_back(new_test_suite);
7216 }
7217
7218 test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
7219 return new_test_suite;
7220 }
7221
7222 // Helpers for setting up / tearing down the given environment. They
7223 // are for use in the ForEach() function.
7224 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
7225 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
7226
7227 // Runs all tests in this UnitTest object, prints the result, and
7228 // returns true if all tests are successful. If any exception is
7229 // thrown during a test, the test is considered to be failed, but the
7230 // rest of the tests will still be run.
7231 //
7232 // When parameterized tests are enabled, it expands and registers
7233 // parameterized tests first in RegisterParameterizedTests().
7234 // All other functions called from RunAllTests() may safely assume that
7235 // parameterized tests are ready to be counted and run.
7236 bool UnitTestImpl::RunAllTests() {
7237 // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
7238 // called.
7239 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
7240
7241 // Do not run any test if the --help flag was specified.
7242 if (g_help_flag)
7243 return true;
7244
7245 // Repeats the call to the post-flag parsing initialization in case the
7246 // user didn't call InitGoogleTest.
7247 PostFlagParsingInit();
7248
7249 // Even if sharding is not on, test runners may want to use the
7250 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
7251 // protocol.
7252 internal::WriteToShardStatusFileIfNeeded();
7253
7254 // True if and only if we are in a subprocess for running a thread-safe-style
7255 // death test.
7256 bool in_subprocess_for_death_test = false;
7257
7258 #if GTEST_HAS_DEATH_TEST
7259 in_subprocess_for_death_test =
7260 (internal_run_death_test_flag_.get() != nullptr);
7261 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
7262 if (in_subprocess_for_death_test) {
7263 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
7264 }
7265 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
7266 #endif // GTEST_HAS_DEATH_TEST
7267
7268 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
7269 in_subprocess_for_death_test);
7270
7271 // Compares the full test names with the filter to decide which
7272 // tests to run.
7273 const bool has_tests_to_run = FilterTests(should_shard
7274 ? HONOR_SHARDING_PROTOCOL
7275 : IGNORE_SHARDING_PROTOCOL) > 0;
7276
7277 // Lists the tests and exits if the --gtest_list_tests flag was specified.
7278 if (GTEST_FLAG(list_tests)) {
7279 // This must be called *after* FilterTests() has been called.
7280 ListTestsMatchingFilter();
7281 return true;
7282 }
7283
7284 random_seed_ = GTEST_FLAG(shuffle) ?
7285 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
7286
7287 // True if and only if at least one test has failed.
7288 bool failed = false;
7289
7290 TestEventListener* repeater = listeners()->repeater();
7291
7292 start_timestamp_ = GetTimeInMillis();
7293 repeater->OnTestProgramStart(*parent_);
7294
7295 // How many times to repeat the tests? We don't want to repeat them
7296 // when we are inside the subprocess of a death test.
7297 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
7298 // Repeats forever if the repeat count is negative.
7299 const bool gtest_repeat_forever = repeat < 0;
7300 for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
7301 // We want to preserve failures generated by ad-hoc test
7302 // assertions executed before RUN_ALL_TESTS().
7303 ClearNonAdHocTestResult();
7304
7305 Timer timer;
7306
7307 // Shuffles test suites and tests if requested.
7308 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
7309 random()->Reseed(static_cast<uint32_t>(random_seed_));
7310 // This should be done before calling OnTestIterationStart(),
7311 // such that a test event listener can see the actual test order
7312 // in the event.
7313 ShuffleTests();
7314 }
7315
7316 // Tells the unit test event listeners that the tests are about to start.
7317 repeater->OnTestIterationStart(*parent_, i);
7318
7319 // Runs each test suite if there is at least one test to run.
7320 if (has_tests_to_run) {
7321 // Sets up all environments beforehand.
7322 repeater->OnEnvironmentsSetUpStart(*parent_);
7323 ForEach(environments_, SetUpEnvironment);
7324 repeater->OnEnvironmentsSetUpEnd(*parent_);
7325
7326 // Runs the tests only if there was no fatal failure or skip triggered
7327 // during global set-up.
7328 if (Test::IsSkipped()) {
7329 // Emit diagnostics when global set-up calls skip, as it will not be
7330 // emitted by default.
7331 TestResult& test_result =
7332 *internal::GetUnitTestImpl()->current_test_result();
7333 for (int j = 0; j < test_result.total_part_count(); ++j) {
7334 const TestPartResult& test_part_result =
7335 test_result.GetTestPartResult(j);
7336 if (test_part_result.type() == TestPartResult::kSkip) {
7337 const std::string& result = test_part_result.message();
7338 printf("%s\n", result.c_str());
7339 }
7340 }
7341 fflush(stdout);
7342 } else if (!Test::HasFatalFailure()) {
7343 for (int test_index = 0; test_index < total_test_suite_count();
7344 test_index++) {
7345 GetMutableSuiteCase(test_index)->Run();
7346 if (GTEST_FLAG(fail_fast) &&
7347 GetMutableSuiteCase(test_index)->Failed()) {
7348 for (int j = test_index + 1; j < total_test_suite_count(); j++) {
7349 GetMutableSuiteCase(j)->Skip();
7350 }
7351 break;
7352 }
7353 }
7354 } else if (Test::HasFatalFailure()) {
7355 // If there was a fatal failure during the global setup then we know we
7356 // aren't going to run any tests. Explicitly mark all of the tests as
7357 // skipped to make this obvious in the output.
7358 for (int test_index = 0; test_index < total_test_suite_count();
7359 test_index++) {
7360 GetMutableSuiteCase(test_index)->Skip();
7361 }
7362 }
7363
7364 // Tears down all environments in reverse order afterwards.
7365 repeater->OnEnvironmentsTearDownStart(*parent_);
7366 std::for_each(environments_.rbegin(), environments_.rend(),
7367 TearDownEnvironment);
7368 repeater->OnEnvironmentsTearDownEnd(*parent_);
7369 }
7370
7371 elapsed_time_ = timer.Elapsed();
7372
7373 // Tells the unit test event listener that the tests have just finished.
7374 repeater->OnTestIterationEnd(*parent_, i);
7375
7376 // Gets the result and clears it.
7377 if (!Passed()) {
7378 failed = true;
7379 }
7380
7381 // Restores the original test order after the iteration. This
7382 // allows the user to quickly repro a failure that happens in the
7383 // N-th iteration without repeating the first (N - 1) iterations.
7384 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
7385 // case the user somehow changes the value of the flag somewhere
7386 // (it's always safe to unshuffle the tests).
7387 UnshuffleTests();
7388
7389 if (GTEST_FLAG(shuffle)) {
7390 // Picks a new random seed for each iteration.
7391 random_seed_ = GetNextRandomSeed(random_seed_);
7392 }
7393 }
7394
7395 repeater->OnTestProgramEnd(*parent_);
7396
7397 if (!gtest_is_initialized_before_run_all_tests) {
7398 ColoredPrintf(
7399 GTestColor::kRed,
7400 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
7401 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
7402 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
7403 " will start to enforce the valid usage. "
7404 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
7405 #if GTEST_FOR_GOOGLE_
7406 ColoredPrintf(GTestColor::kRed,
7407 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
7408 #endif // GTEST_FOR_GOOGLE_
7409 }
7410
7411 return !failed;
7412 }
7413
7414 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
7415 // if the variable is present. If a file already exists at this location, this
7416 // function will write over it. If the variable is present, but the file cannot
7417 // be created, prints an error and exits.
7418 void WriteToShardStatusFileIfNeeded() {
7419 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
7420 if (test_shard_file != nullptr) {
7421 FILE* const file = posix::FOpen(test_shard_file, "w");
7422 if (file == nullptr) {
7423 ColoredPrintf(GTestColor::kRed,
7424 "Could not write to the test shard status file \"%s\" "
7425 "specified by the %s environment variable.\n",
7426 test_shard_file, kTestShardStatusFile);
7427 fflush(stdout);
7428 exit(EXIT_FAILURE);
7429 }
7430 fclose(file);
7431 }
7432 }
7433
7434 // Checks whether sharding is enabled by examining the relevant
7435 // environment variable values. If the variables are present,
7436 // but inconsistent (i.e., shard_index >= total_shards), prints
7437 // an error and exits. If in_subprocess_for_death_test, sharding is
7438 // disabled because it must only be applied to the original test
7439 // process. Otherwise, we could filter out death tests we intended to execute.
7440 bool ShouldShard(const char* total_shards_env,
7441 const char* shard_index_env,
7442 bool in_subprocess_for_death_test) {
7443 if (in_subprocess_for_death_test) {
7444 return false;
7445 }
7446
7447 const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
7448 const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
7449
7450 if (total_shards == -1 && shard_index == -1) {
7451 return false;
7452 } else if (total_shards == -1 && shard_index != -1) {
7453 const Message msg = Message()
7454 << "Invalid environment variables: you have "
7455 << kTestShardIndex << " = " << shard_index
7456 << ", but have left " << kTestTotalShards << " unset.\n";
7457 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
7458 fflush(stdout);
7459 exit(EXIT_FAILURE);
7460 } else if (total_shards != -1 && shard_index == -1) {
7461 const Message msg = Message()
7462 << "Invalid environment variables: you have "
7463 << kTestTotalShards << " = " << total_shards
7464 << ", but have left " << kTestShardIndex << " unset.\n";
7465 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
7466 fflush(stdout);
7467 exit(EXIT_FAILURE);
7468 } else if (shard_index < 0 || shard_index >= total_shards) {
7469 const Message msg = Message()
7470 << "Invalid environment variables: we require 0 <= "
7471 << kTestShardIndex << " < " << kTestTotalShards
7472 << ", but you have " << kTestShardIndex << "=" << shard_index
7473 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
7474 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
7475 fflush(stdout);
7476 exit(EXIT_FAILURE);
7477 }
7478
7479 return total_shards > 1;
7480 }
7481
7482 // Parses the environment variable var as an Int32. If it is unset,
7483 // returns default_val. If it is not an Int32, prints an error
7484 // and aborts.
7485 int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
7486 const char* str_val = posix::GetEnv(var);
7487 if (str_val == nullptr) {
7488 return default_val;
7489 }
7490
7491 int32_t result;
7492 if (!ParseInt32(Message() << "The value of environment variable " << var,
7493 str_val, &result)) {
7494 exit(EXIT_FAILURE);
7495 }
7496 return result;
7497 }
7498
7499 // Given the total number of shards, the shard index, and the test id,
7500 // returns true if and only if the test should be run on this shard. The test id
7501 // is some arbitrary but unique non-negative integer assigned to each test
7502 // method. Assumes that 0 <= shard_index < total_shards.
7503 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
7504 return (test_id % total_shards) == shard_index;
7505 }
7506
7507 // Compares the name of each test with the user-specified filter to
7508 // decide whether the test should be run, then records the result in
7509 // each TestSuite and TestInfo object.
7510 // If shard_tests == true, further filters tests based on sharding
7511 // variables in the environment - see
7512 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
7513 // . Returns the number of tests that should run.
7514 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
7515 const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
7516 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
7517 const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
7518 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
7519
7520 // num_runnable_tests are the number of tests that will
7521 // run across all shards (i.e., match filter and are not disabled).
7522 // num_selected_tests are the number of tests to be run on
7523 // this shard.
7524 int num_runnable_tests = 0;
7525 int num_selected_tests = 0;
7526 for (auto* test_suite : test_suites_) {
7527 const std::string& test_suite_name = test_suite->name();
7528 test_suite->set_should_run(false);
7529
7530 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
7531 TestInfo* const test_info = test_suite->test_info_list()[j];
7532 const std::string test_name(test_info->name());
7533 // A test is disabled if test suite name or test name matches
7534 // kDisableTestFilter.
7535 const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
7536 test_suite_name, kDisableTestFilter) ||
7537 internal::UnitTestOptions::MatchesFilter(
7538 test_name, kDisableTestFilter);
7539 test_info->is_disabled_ = is_disabled;
7540
7541 const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
7542 test_suite_name, test_name);
7543 test_info->matches_filter_ = matches_filter;
7544
7545 const bool is_runnable =
7546 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
7547 matches_filter;
7548
7549 const bool is_in_another_shard =
7550 shard_tests != IGNORE_SHARDING_PROTOCOL &&
7551 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
7552 test_info->is_in_another_shard_ = is_in_another_shard;
7553 const bool is_selected = is_runnable && !is_in_another_shard;
7554
7555 num_runnable_tests += is_runnable;
7556 num_selected_tests += is_selected;
7557
7558 test_info->should_run_ = is_selected;
7559 test_suite->set_should_run(test_suite->should_run() || is_selected);
7560 }
7561 }
7562 return num_selected_tests;
7563 }
7564
7565 // Prints the given C-string on a single line by replacing all '\n'
7566 // characters with string "\\n". If the output takes more than
7567 // max_length characters, only prints the first max_length characters
7568 // and "...".
7569 static void PrintOnOneLine(const char* str, int max_length) {
7570 if (str != nullptr) {
7571 for (int i = 0; *str != '\0'; ++str) {
7572 if (i >= max_length) {
7573 printf("...");
7574 break;
7575 }
7576 if (*str == '\n') {
7577 printf("\\n");
7578 i += 2;
7579 } else {
7580 printf("%c", *str);
7581 ++i;
7582 }
7583 }
7584 }
7585 }
7586
7587 // Prints the names of the tests matching the user-specified filter flag.
7588 void UnitTestImpl::ListTestsMatchingFilter() {
7589 // Print at most this many characters for each type/value parameter.
7590 const int kMaxParamLength = 250;
7591
7592 for (auto* test_suite : test_suites_) {
7593 bool printed_test_suite_name = false;
7594
7595 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
7596 const TestInfo* const test_info = test_suite->test_info_list()[j];
7597 if (test_info->matches_filter_) {
7598 if (!printed_test_suite_name) {
7599 printed_test_suite_name = true;
7600 printf("%s.", test_suite->name());
7601 if (test_suite->type_param() != nullptr) {
7602 printf(" # %s = ", kTypeParamLabel);
7603 // We print the type parameter on a single line to make
7604 // the output easy to parse by a program.
7605 PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
7606 }
7607 printf("\n");
7608 }
7609 printf(" %s", test_info->name());
7610 if (test_info->value_param() != nullptr) {
7611 printf(" # %s = ", kValueParamLabel);
7612 // We print the value parameter on a single line to make the
7613 // output easy to parse by a program.
7614 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
7615 }
7616 printf("\n");
7617 }
7618 }
7619 }
7620 fflush(stdout);
7621 const std::string& output_format = UnitTestOptions::GetOutputFormat();
7622 if (output_format == "xml" || output_format == "json") {
7623 FILE* fileout = OpenFileForWriting(
7624 UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
7625 std::stringstream stream;
7626 if (output_format == "xml") {
7627 XmlUnitTestResultPrinter(
7628 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
7629 .PrintXmlTestsList(&stream, test_suites_);
7630 } else if (output_format == "json") {
7631 JsonUnitTestResultPrinter(
7632 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
7633 .PrintJsonTestList(&stream, test_suites_);
7634 }
7635 fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
7636 fclose(fileout);
7637 }
7638 }
7639
7640 // Sets the OS stack trace getter.
7641 //
7642 // Does nothing if the input and the current OS stack trace getter are
7643 // the same; otherwise, deletes the old getter and makes the input the
7644 // current getter.
7645 void UnitTestImpl::set_os_stack_trace_getter(
7646 OsStackTraceGetterInterface* getter) {
7647 if (os_stack_trace_getter_ != getter) {
7648 delete os_stack_trace_getter_;
7649 os_stack_trace_getter_ = getter;
7650 }
7651 }
7652
7653 // Returns the current OS stack trace getter if it is not NULL;
7654 // otherwise, creates an OsStackTraceGetter, makes it the current
7655 // getter, and returns it.
7656 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
7657 if (os_stack_trace_getter_ == nullptr) {
7658 #ifdef GTEST_OS_STACK_TRACE_GETTER_
7659 os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
7660 #else
7661 os_stack_trace_getter_ = new OsStackTraceGetter;
7662 #endif // GTEST_OS_STACK_TRACE_GETTER_
7663 }
7664
7665 return os_stack_trace_getter_;
7666 }
7667
7668 // Returns the most specific TestResult currently running.
7669 TestResult* UnitTestImpl::current_test_result() {
7670 if (current_test_info_ != nullptr) {
7671 return &current_test_info_->result_;
7672 }
7673 if (current_test_suite_ != nullptr) {
7674 return &current_test_suite_->ad_hoc_test_result_;
7675 }
7676 return &ad_hoc_test_result_;
7677 }
7678
7679 // Shuffles all test suites, and the tests within each test suite,
7680 // making sure that death tests are still run first.
7681 void UnitTestImpl::ShuffleTests() {
7682 // Shuffles the death test suites.
7683 ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
7684
7685 // Shuffles the non-death test suites.
7686 ShuffleRange(random(), last_death_test_suite_ + 1,
7687 static_cast<int>(test_suites_.size()), &test_suite_indices_);
7688
7689 // Shuffles the tests inside each test suite.
7690 for (auto& test_suite : test_suites_) {
7691 test_suite->ShuffleTests(random());
7692 }
7693 }
7694
7695 // Restores the test suites and tests to their order before the first shuffle.
7696 void UnitTestImpl::UnshuffleTests() {
7697 for (size_t i = 0; i < test_suites_.size(); i++) {
7698 // Unshuffles the tests in each test suite.
7699 test_suites_[i]->UnshuffleTests();
7700 // Resets the index of each test suite.
7701 test_suite_indices_[i] = static_cast<int>(i);
7702 }
7703 }
7704
7705 // Returns the current OS stack trace as an std::string.
7706 //
7707 // The maximum number of stack frames to be included is specified by
7708 // the gtest_stack_trace_depth flag. The skip_count parameter
7709 // specifies the number of top frames to be skipped, which doesn't
7710 // count against the number of frames to be included.
7711 //
7712 // For example, if Foo() calls Bar(), which in turn calls
7713 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
7714 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
7715 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
7716 int skip_count) {
7717 // We pass skip_count + 1 to skip this wrapper function in addition
7718 // to what the user really wants to skip.
7719 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
7720 }
7721
7722 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
7723 // suppress unreachable code warnings.
7724 namespace {
7725 class ClassUniqueToAlwaysTrue {};
7726 }
7727
7728 bool IsTrue(bool condition) { return condition; }
7729
7730 bool AlwaysTrue() {
7731 #if GTEST_HAS_EXCEPTIONS
7732 // This condition is always false so AlwaysTrue() never actually throws,
7733 // but it makes the compiler think that it may throw.
7734 if (IsTrue(false))
7735 throw ClassUniqueToAlwaysTrue();
7736 #endif // GTEST_HAS_EXCEPTIONS
7737 return true;
7738 }
7739
7740 // If *pstr starts with the given prefix, modifies *pstr to be right
7741 // past the prefix and returns true; otherwise leaves *pstr unchanged
7742 // and returns false. None of pstr, *pstr, and prefix can be NULL.
7743 bool SkipPrefix(const char* prefix, const char** pstr) {
7744 const size_t prefix_len = strlen(prefix);
7745 if (strncmp(*pstr, prefix, prefix_len) == 0) {
7746 *pstr += prefix_len;
7747 return true;
7748 }
7749 return false;
7750 }
7751
7752 // Parses a string as a command line flag. The string should have
7753 // the format "--flag=value". When def_optional is true, the "=value"
7754 // part can be omitted.
7755 //
7756 // Returns the value of the flag, or NULL if the parsing failed.
7757 static const char* ParseFlagValue(const char* str, const char* flag,
7758 bool def_optional) {
7759 // str and flag must not be NULL.
7760 if (str == nullptr || flag == nullptr) return nullptr;
7761
7762 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
7763 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
7764 const size_t flag_len = flag_str.length();
7765 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
7766
7767 // Skips the flag name.
7768 const char* flag_end = str + flag_len;
7769
7770 // When def_optional is true, it's OK to not have a "=value" part.
7771 if (def_optional && (flag_end[0] == '\0')) {
7772 return flag_end;
7773 }
7774
7775 // If def_optional is true and there are more characters after the
7776 // flag name, or if def_optional is false, there must be a '=' after
7777 // the flag name.
7778 if (flag_end[0] != '=') return nullptr;
7779
7780 // Returns the string after "=".
7781 return flag_end + 1;
7782 }
7783
7784 // Parses a string for a bool flag, in the form of either
7785 // "--flag=value" or "--flag".
7786 //
7787 // In the former case, the value is taken as true as long as it does
7788 // not start with '0', 'f', or 'F'.
7789 //
7790 // In the latter case, the value is taken as true.
7791 //
7792 // On success, stores the value of the flag in *value, and returns
7793 // true. On failure, returns false without changing *value.
7794 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
7795 // Gets the value of the flag as a string.
7796 const char* const value_str = ParseFlagValue(str, flag, true);
7797
7798 // Aborts if the parsing failed.
7799 if (value_str == nullptr) return false;
7800
7801 // Converts the string value to a bool.
7802 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
7803 return true;
7804 }
7805
7806 // Parses a string for an int32_t flag, in the form of "--flag=value".
7807 //
7808 // On success, stores the value of the flag in *value, and returns
7809 // true. On failure, returns false without changing *value.
7810 bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {
7811 // Gets the value of the flag as a string.
7812 const char* const value_str = ParseFlagValue(str, flag, false);
7813
7814 // Aborts if the parsing failed.
7815 if (value_str == nullptr) return false;
7816
7817 // Sets *value to the value of the flag.
7818 return ParseInt32(Message() << "The value of flag --" << flag,
7819 value_str, value);
7820 }
7821
7822 // Parses a string for a string flag, in the form of "--flag=value".
7823 //
7824 // On success, stores the value of the flag in *value, and returns
7825 // true. On failure, returns false without changing *value.
7826 template <typename String>
7827 static bool ParseStringFlag(const char* str, const char* flag, String* value) {
7828 // Gets the value of the flag as a string.
7829 const char* const value_str = ParseFlagValue(str, flag, false);
7830
7831 // Aborts if the parsing failed.
7832 if (value_str == nullptr) return false;
7833
7834 // Sets *value to the value of the flag.
7835 *value = value_str;
7836 return true;
7837 }
7838
7839 // Determines whether a string has a prefix that Google Test uses for its
7840 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
7841 // If Google Test detects that a command line flag has its prefix but is not
7842 // recognized, it will print its help message. Flags starting with
7843 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
7844 // internal flags and do not trigger the help message.
7845 static bool HasGoogleTestFlagPrefix(const char* str) {
7846 return (SkipPrefix("--", &str) ||
7847 SkipPrefix("-", &str) ||
7848 SkipPrefix("/", &str)) &&
7849 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
7850 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
7851 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
7852 }
7853
7854 // Prints a string containing code-encoded text. The following escape
7855 // sequences can be used in the string to control the text color:
7856 //
7857 // @@ prints a single '@' character.
7858 // @R changes the color to red.
7859 // @G changes the color to green.
7860 // @Y changes the color to yellow.
7861 // @D changes to the default terminal text color.
7862 //
7863 static void PrintColorEncoded(const char* str) {
7864 GTestColor color = GTestColor::kDefault; // The current color.
7865
7866 // Conceptually, we split the string into segments divided by escape
7867 // sequences. Then we print one segment at a time. At the end of
7868 // each iteration, the str pointer advances to the beginning of the
7869 // next segment.
7870 for (;;) {
7871 const char* p = strchr(str, '@');
7872 if (p == nullptr) {
7873 ColoredPrintf(color, "%s", str);
7874 return;
7875 }
7876
7877 ColoredPrintf(color, "%s", std::string(str, p).c_str());
7878
7879 const char ch = p[1];
7880 str = p + 2;
7881 if (ch == '@') {
7882 ColoredPrintf(color, "@");
7883 } else if (ch == 'D') {
7884 color = GTestColor::kDefault;
7885 } else if (ch == 'R') {
7886 color = GTestColor::kRed;
7887 } else if (ch == 'G') {
7888 color = GTestColor::kGreen;
7889 } else if (ch == 'Y') {
7890 color = GTestColor::kYellow;
7891 } else {
7892 --str;
7893 }
7894 }
7895 }
7896
7897 static const char kColorEncodedHelpMessage[] =
7898 "This program contains tests written using " GTEST_NAME_
7899 ". You can use the\n"
7900 "following command line flags to control its behavior:\n"
7901 "\n"
7902 "Test Selection:\n"
7903 " @G--" GTEST_FLAG_PREFIX_
7904 "list_tests@D\n"
7905 " List the names of all tests instead of running them. The name of\n"
7906 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
7907 " @G--" GTEST_FLAG_PREFIX_
7908 "filter=@YPOSITIVE_PATTERNS"
7909 "[@G-@YNEGATIVE_PATTERNS]@D\n"
7910 " Run only the tests whose name matches one of the positive patterns "
7911 "but\n"
7912 " none of the negative patterns. '?' matches any single character; "
7913 "'*'\n"
7914 " matches any substring; ':' separates two patterns.\n"
7915 " @G--" GTEST_FLAG_PREFIX_
7916 "also_run_disabled_tests@D\n"
7917 " Run all disabled tests too.\n"
7918 "\n"
7919 "Test Execution:\n"
7920 " @G--" GTEST_FLAG_PREFIX_
7921 "repeat=@Y[COUNT]@D\n"
7922 " Run the tests repeatedly; use a negative count to repeat forever.\n"
7923 " @G--" GTEST_FLAG_PREFIX_
7924 "shuffle@D\n"
7925 " Randomize tests' orders on every iteration.\n"
7926 " @G--" GTEST_FLAG_PREFIX_
7927 "random_seed=@Y[NUMBER]@D\n"
7928 " Random number seed to use for shuffling test orders (between 1 and\n"
7929 " 99999, or 0 to use a seed based on the current time).\n"
7930 "\n"
7931 "Test Output:\n"
7932 " @G--" GTEST_FLAG_PREFIX_
7933 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
7934 " Enable/disable colored output. The default is @Gauto@D.\n"
7935 " @G--" GTEST_FLAG_PREFIX_
7936 "brief=1@D\n"
7937 " Only print test failures.\n"
7938 " @G--" GTEST_FLAG_PREFIX_
7939 "print_time=0@D\n"
7940 " Don't print the elapsed time of each test.\n"
7941 " @G--" GTEST_FLAG_PREFIX_
7942 "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
7943 "@Y|@G:@YFILE_PATH]@D\n"
7944 " Generate a JSON or XML report in the given directory or with the "
7945 "given\n"
7946 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
7947 # if GTEST_CAN_STREAM_RESULTS_
7948 " @G--" GTEST_FLAG_PREFIX_
7949 "stream_result_to=@YHOST@G:@YPORT@D\n"
7950 " Stream test results to the given server.\n"
7951 # endif // GTEST_CAN_STREAM_RESULTS_
7952 "\n"
7953 "Assertion Behavior:\n"
7954 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7955 " @G--" GTEST_FLAG_PREFIX_
7956 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
7957 " Set the default death test style.\n"
7958 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7959 " @G--" GTEST_FLAG_PREFIX_
7960 "break_on_failure@D\n"
7961 " Turn assertion failures into debugger break-points.\n"
7962 " @G--" GTEST_FLAG_PREFIX_
7963 "throw_on_failure@D\n"
7964 " Turn assertion failures into C++ exceptions for use by an external\n"
7965 " test framework.\n"
7966 " @G--" GTEST_FLAG_PREFIX_
7967 "catch_exceptions=0@D\n"
7968 " Do not report exceptions as test failures. Instead, allow them\n"
7969 " to crash the program or throw a pop-up (on Windows).\n"
7970 "\n"
7971 "Except for @G--" GTEST_FLAG_PREFIX_
7972 "list_tests@D, you can alternatively set "
7973 "the corresponding\n"
7974 "environment variable of a flag (all letters in upper-case). For example, "
7975 "to\n"
7976 "disable colored text output, you can either specify "
7977 "@G--" GTEST_FLAG_PREFIX_
7978 "color=no@D or set\n"
7979 "the @G" GTEST_FLAG_PREFIX_UPPER_
7980 "COLOR@D environment variable to @Gno@D.\n"
7981 "\n"
7982 "For more information, please read the " GTEST_NAME_
7983 " documentation at\n"
7984 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
7985 "\n"
7986 "(not one in your own code or tests), please report it to\n"
7987 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
7988
7989 static bool ParseGoogleTestFlag(const char* const arg) {
7990 return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7991 &GTEST_FLAG(also_run_disabled_tests)) ||
7992 ParseBoolFlag(arg, kBreakOnFailureFlag,
7993 &GTEST_FLAG(break_on_failure)) ||
7994 ParseBoolFlag(arg, kCatchExceptionsFlag,
7995 &GTEST_FLAG(catch_exceptions)) ||
7996 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
7997 ParseStringFlag(arg, kDeathTestStyleFlag,
7998 &GTEST_FLAG(death_test_style)) ||
7999 ParseBoolFlag(arg, kDeathTestUseFork,
8000 &GTEST_FLAG(death_test_use_fork)) ||
8001 ParseBoolFlag(arg, kFailFast, &GTEST_FLAG(fail_fast)) ||
8002 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
8003 ParseStringFlag(arg, kInternalRunDeathTestFlag,
8004 &GTEST_FLAG(internal_run_death_test)) ||
8005 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
8006 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
8007 ParseBoolFlag(arg, kBriefFlag, &GTEST_FLAG(brief)) ||
8008 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
8009 ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
8010 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
8011 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
8012 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
8013 ParseInt32Flag(arg, kStackTraceDepthFlag,
8014 &GTEST_FLAG(stack_trace_depth)) ||
8015 ParseStringFlag(arg, kStreamResultToFlag,
8016 &GTEST_FLAG(stream_result_to)) ||
8017 ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure));
8018 }
8019
8020 #if GTEST_USE_OWN_FLAGFILE_FLAG_
8021 static void LoadFlagsFromFile(const std::string& path) {
8022 FILE* flagfile = posix::FOpen(path.c_str(), "r");
8023 if (!flagfile) {
8024 GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
8025 << "\"";
8026 }
8027 std::string contents(ReadEntireFile(flagfile));
8028 posix::FClose(flagfile);
8029 std::vector<std::string> lines;
8030 SplitString(contents, '\n', &lines);
8031 for (size_t i = 0; i < lines.size(); ++i) {
8032 if (lines[i].empty())
8033 continue;
8034 if (!ParseGoogleTestFlag(lines[i].c_str()))
8035 g_help_flag = true;
8036 }
8037 }
8038 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
8039
8040 // Parses the command line for Google Test flags, without initializing
8041 // other parts of Google Test. The type parameter CharType can be
8042 // instantiated to either char or wchar_t.
8043 template <typename CharType>
8044 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
8045 for (int i = 1; i < *argc; i++) {
8046 const std::string arg_string = StreamableToString(argv[i]);
8047 const char* const arg = arg_string.c_str();
8048
8049 using internal::ParseBoolFlag;
8050 using internal::ParseInt32Flag;
8051 using internal::ParseStringFlag;
8052
8053 bool remove_flag = false;
8054 if (ParseGoogleTestFlag(arg)) {
8055 remove_flag = true;
8056 #if GTEST_USE_OWN_FLAGFILE_FLAG_
8057 } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
8058 LoadFlagsFromFile(GTEST_FLAG(flagfile));
8059 remove_flag = true;
8060 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
8061 } else if (arg_string == "--help" || arg_string == "-h" ||
8062 arg_string == "-?" || arg_string == "/?" ||
8063 HasGoogleTestFlagPrefix(arg)) {
8064 // Both help flag and unrecognized Google Test flags (excluding
8065 // internal ones) trigger help display.
8066 g_help_flag = true;
8067 }
8068
8069 if (remove_flag) {
8070 // Shift the remainder of the argv list left by one. Note
8071 // that argv has (*argc + 1) elements, the last one always being
8072 // NULL. The following loop moves the trailing NULL element as
8073 // well.
8074 for (int j = i; j != *argc; j++) {
8075 argv[j] = argv[j + 1];
8076 }
8077
8078 // Decrements the argument count.
8079 (*argc)--;
8080
8081 // We also need to decrement the iterator as we just removed
8082 // an element.
8083 i--;
8084 }
8085 }
8086
8087 if (g_help_flag) {
8088 // We print the help here instead of in RUN_ALL_TESTS(), as the
8089 // latter may not be called at all if the user is using Google
8090 // Test with another testing framework.
8091 PrintColorEncoded(kColorEncodedHelpMessage);
8092 }
8093 }
8094
8095 // Parses the command line for Google Test flags, without initializing
8096 // other parts of Google Test.
8097 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
8098 ParseGoogleTestFlagsOnlyImpl(argc, argv);
8099
8100 // Fix the value of *_NSGetArgc() on macOS, but if and only if
8101 // *_NSGetArgv() == argv
8102 // Only applicable to char** version of argv
8103 #if GTEST_OS_MAC
8104 #ifndef GTEST_OS_IOS
8105 if (*_NSGetArgv() == argv) {
8106 *_NSGetArgc() = *argc;
8107 }
8108 #endif
8109 #endif
8110 }
8111 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
8112 ParseGoogleTestFlagsOnlyImpl(argc, argv);
8113 }
8114
8115 // The internal implementation of InitGoogleTest().
8116 //
8117 // The type parameter CharType can be instantiated to either char or
8118 // wchar_t.
8119 template <typename CharType>
8120 void InitGoogleTestImpl(int* argc, CharType** argv) {
8121 // We don't want to run the initialization code twice.
8122 if (GTestIsInitialized()) return;
8123
8124 if (*argc <= 0) return;
8125
8126 g_argvs.clear();
8127 for (int i = 0; i != *argc; i++) {
8128 g_argvs.push_back(StreamableToString(argv[i]));
8129 }
8130
8131 #if GTEST_HAS_ABSL
8132 absl::InitializeSymbolizer(g_argvs[0].c_str());
8133 #endif // GTEST_HAS_ABSL
8134
8135 ParseGoogleTestFlagsOnly(argc, argv);
8136 GetUnitTestImpl()->PostFlagParsingInit();
8137 }
8138
8139 } // namespace internal
8140
8141 // Initializes Google Test. This must be called before calling
8142 // RUN_ALL_TESTS(). In particular, it parses a command line for the
8143 // flags that Google Test recognizes. Whenever a Google Test flag is
8144 // seen, it is removed from argv, and *argc is decremented.
8145 //
8146 // No value is returned. Instead, the Google Test flag variables are
8147 // updated.
8148 //
8149 // Calling the function for the second time has no user-visible effect.
8150 void InitGoogleTest(int* argc, char** argv) {
8151 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8152 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
8153 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8154 internal::InitGoogleTestImpl(argc, argv);
8155 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8156 }
8157
8158 // This overloaded version can be used in Windows programs compiled in
8159 // UNICODE mode.
8160 void InitGoogleTest(int* argc, wchar_t** argv) {
8161 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8162 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
8163 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8164 internal::InitGoogleTestImpl(argc, argv);
8165 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8166 }
8167
8168 // This overloaded version can be used on Arduino/embedded platforms where
8169 // there is no argc/argv.
8170 void InitGoogleTest() {
8171 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
8172 int argc = 1;
8173 const auto arg0 = "dummy";
8174 char* argv0 = const_cast<char*>(arg0);
8175 char** argv = &argv0;
8176
8177 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8178 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
8179 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8180 internal::InitGoogleTestImpl(&argc, argv);
8181 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8182 }
8183
8184 std::string TempDir() {
8185 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
8186 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
8187 #elif GTEST_OS_WINDOWS_MOBILE
8188 return "\\temp\\";
8189 #elif GTEST_OS_WINDOWS
8190 const char* temp_dir = internal::posix::GetEnv("TEMP");
8191 if (temp_dir == nullptr || temp_dir[0] == '\0') {
8192 return "\\temp\\";
8193 } else if (temp_dir[strlen(temp_dir) - 1] == '\\') {
8194 return temp_dir;
8195 } else {
8196 return std::string(temp_dir) + "\\";
8197 }
8198 #elif GTEST_OS_LINUX_ANDROID
8199 const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
8200 if (temp_dir == nullptr || temp_dir[0] == '\0') {
8201 return "/data/local/tmp/";
8202 } else {
8203 return temp_dir;
8204 }
8205 #elif GTEST_OS_LINUX
8206 const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
8207 if (temp_dir == nullptr || temp_dir[0] == '\0') {
8208 return "/tmp/";
8209 } else {
8210 return temp_dir;
8211 }
8212 #else
8213 return "/tmp/";
8214 #endif // GTEST_OS_WINDOWS_MOBILE
8215 }
8216
8217 // Class ScopedTrace
8218
8219 // Pushes the given source file location and message onto a per-thread
8220 // trace stack maintained by Google Test.
8221 void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
8222 internal::TraceInfo trace;
8223 trace.file = file;
8224 trace.line = line;
8225 trace.message.swap(message);
8226
8227 UnitTest::GetInstance()->PushGTestTrace(trace);
8228 }
8229
8230 // Pops the info pushed by the c'tor.
8231 ScopedTrace::~ScopedTrace()
8232 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
8233 UnitTest::GetInstance()->PopGTestTrace();
8234 }
8235
8236 } // namespace testing
8237 // Copyright 2005, Google Inc.
8238 // All rights reserved.
8239 //
8240 // Redistribution and use in source and binary forms, with or without
8241 // modification, are permitted provided that the following conditions are
8242 // met:
8243 //
8244 // * Redistributions of source code must retain the above copyright
8245 // notice, this list of conditions and the following disclaimer.
8246 // * Redistributions in binary form must reproduce the above
8247 // copyright notice, this list of conditions and the following disclaimer
8248 // in the documentation and/or other materials provided with the
8249 // distribution.
8250 // * Neither the name of Google Inc. nor the names of its
8251 // contributors may be used to endorse or promote products derived from
8252 // this software without specific prior written permission.
8253 //
8254 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8255 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8256 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8257 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8258 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8259 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8260 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8261 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8262 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8263 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8264 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8265
8266 //
8267 // This file implements death tests.
8268
8269
8270 #include <functional>
8271 #include <utility>
8272
8273
8274 #if GTEST_HAS_DEATH_TEST
8275
8276 # if GTEST_OS_MAC
8277 # include <crt_externs.h>
8278 # endif // GTEST_OS_MAC
8279
8280 # include <errno.h>
8281 # include <fcntl.h>
8282 # include <limits.h>
8283
8284 # if GTEST_OS_LINUX
8285 # include <signal.h>
8286 # endif // GTEST_OS_LINUX
8287
8288 # include <stdarg.h>
8289
8290 # if GTEST_OS_WINDOWS
8291 # include <windows.h>
8292 # else
8293 # include <sys/mman.h>
8294 # include <sys/wait.h>
8295 # endif // GTEST_OS_WINDOWS
8296
8297 # if GTEST_OS_QNX
8298 # include <spawn.h>
8299 # endif // GTEST_OS_QNX
8300
8301 # if GTEST_OS_FUCHSIA
8302 # include <lib/fdio/fd.h>
8303 # include <lib/fdio/io.h>
8304 # include <lib/fdio/spawn.h>
8305 # include <lib/zx/channel.h>
8306 # include <lib/zx/port.h>
8307 # include <lib/zx/process.h>
8308 # include <lib/zx/socket.h>
8309 # include <zircon/processargs.h>
8310 # include <zircon/syscalls.h>
8311 # include <zircon/syscalls/policy.h>
8312 # include <zircon/syscalls/port.h>
8313 # endif // GTEST_OS_FUCHSIA
8314
8315 #endif // GTEST_HAS_DEATH_TEST
8316
8317
8318 namespace testing {
8319
8320 // Constants.
8321
8322 // The default death test style.
8323 //
8324 // This is defined in internal/gtest-port.h as "fast", but can be overridden by
8325 // a definition in internal/custom/gtest-port.h. The recommended value, which is
8326 // used internally at Google, is "threadsafe".
8327 static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
8328
8329 GTEST_DEFINE_string_(
8330 death_test_style,
8331 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
8332 "Indicates how to run a death test in a forked child process: "
8333 "\"threadsafe\" (child process re-executes the test binary "
8334 "from the beginning, running only the specific death test) or "
8335 "\"fast\" (child process runs the death test immediately "
8336 "after forking).");
8337
8338 GTEST_DEFINE_bool_(
8339 death_test_use_fork,
8340 internal::BoolFromGTestEnv("death_test_use_fork", false),
8341 "Instructs to use fork()/_exit() instead of clone() in death tests. "
8342 "Ignored and always uses fork() on POSIX systems where clone() is not "
8343 "implemented. Useful when running under valgrind or similar tools if "
8344 "those do not support clone(). Valgrind 3.3.1 will just fail if "
8345 "it sees an unsupported combination of clone() flags. "
8346 "It is not recommended to use this flag w/o valgrind though it will "
8347 "work in 99% of the cases. Once valgrind is fixed, this flag will "
8348 "most likely be removed.");
8349
8350 namespace internal {
8351 GTEST_DEFINE_string_(
8352 internal_run_death_test, "",
8353 "Indicates the file, line number, temporal index of "
8354 "the single death test to run, and a file descriptor to "
8355 "which a success code may be sent, all separated by "
8356 "the '|' characters. This flag is specified if and only if the "
8357 "current process is a sub-process launched for running a thread-safe "
8358 "death test. FOR INTERNAL USE ONLY.");
8359 } // namespace internal
8360
8361 #if GTEST_HAS_DEATH_TEST
8362
8363 namespace internal {
8364
8365 // Valid only for fast death tests. Indicates the code is running in the
8366 // child process of a fast style death test.
8367 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8368 static bool g_in_fast_death_test_child = false;
8369 # endif
8370
8371 // Returns a Boolean value indicating whether the caller is currently
8372 // executing in the context of the death test child process. Tools such as
8373 // Valgrind heap checkers may need this to modify their behavior in death
8374 // tests. IMPORTANT: This is an internal utility. Using it may break the
8375 // implementation of death tests. User code MUST NOT use it.
8376 bool InDeathTestChild() {
8377 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8378
8379 // On Windows and Fuchsia, death tests are thread-safe regardless of the value
8380 // of the death_test_style flag.
8381 return !GTEST_FLAG(internal_run_death_test).empty();
8382
8383 # else
8384
8385 if (GTEST_FLAG(death_test_style) == "threadsafe")
8386 return !GTEST_FLAG(internal_run_death_test).empty();
8387 else
8388 return g_in_fast_death_test_child;
8389 #endif
8390 }
8391
8392 } // namespace internal
8393
8394 // ExitedWithCode constructor.
8395 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
8396 }
8397
8398 // ExitedWithCode function-call operator.
8399 bool ExitedWithCode::operator()(int exit_status) const {
8400 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8401
8402 return exit_status == exit_code_;
8403
8404 # else
8405
8406 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
8407
8408 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8409 }
8410
8411 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8412 // KilledBySignal constructor.
8413 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
8414 }
8415
8416 // KilledBySignal function-call operator.
8417 bool KilledBySignal::operator()(int exit_status) const {
8418 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
8419 {
8420 bool result;
8421 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
8422 return result;
8423 }
8424 }
8425 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
8426 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
8427 }
8428 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8429
8430 namespace internal {
8431
8432 // Utilities needed for death tests.
8433
8434 // Generates a textual description of a given exit code, in the format
8435 // specified by wait(2).
8436 static std::string ExitSummary(int exit_code) {
8437 Message m;
8438
8439 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8440
8441 m << "Exited with exit status " << exit_code;
8442
8443 # else
8444
8445 if (WIFEXITED(exit_code)) {
8446 m << "Exited with exit status " << WEXITSTATUS(exit_code);
8447 } else if (WIFSIGNALED(exit_code)) {
8448 m << "Terminated by signal " << WTERMSIG(exit_code);
8449 }
8450 # ifdef WCOREDUMP
8451 if (WCOREDUMP(exit_code)) {
8452 m << " (core dumped)";
8453 }
8454 # endif
8455 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8456
8457 return m.GetString();
8458 }
8459
8460 // Returns true if exit_status describes a process that was terminated
8461 // by a signal, or exited normally with a nonzero exit code.
8462 bool ExitedUnsuccessfully(int exit_status) {
8463 return !ExitedWithCode(0)(exit_status);
8464 }
8465
8466 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8467 // Generates a textual failure message when a death test finds more than
8468 // one thread running, or cannot determine the number of threads, prior
8469 // to executing the given statement. It is the responsibility of the
8470 // caller not to pass a thread_count of 1.
8471 static std::string DeathTestThreadWarning(size_t thread_count) {
8472 Message msg;
8473 msg << "Death tests use fork(), which is unsafe particularly"
8474 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
8475 if (thread_count == 0) {
8476 msg << "couldn't detect the number of threads.";
8477 } else {
8478 msg << "detected " << thread_count << " threads.";
8479 }
8480 msg << " See "
8481 "https://github.com/google/googletest/blob/master/docs/"
8482 "advanced.md#death-tests-and-threads"
8483 << " for more explanation and suggested solutions, especially if"
8484 << " this is the last message you see before your test times out.";
8485 return msg.GetString();
8486 }
8487 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8488
8489 // Flag characters for reporting a death test that did not die.
8490 static const char kDeathTestLived = 'L';
8491 static const char kDeathTestReturned = 'R';
8492 static const char kDeathTestThrew = 'T';
8493 static const char kDeathTestInternalError = 'I';
8494
8495 #if GTEST_OS_FUCHSIA
8496
8497 // File descriptor used for the pipe in the child process.
8498 static const int kFuchsiaReadPipeFd = 3;
8499
8500 #endif
8501
8502 // An enumeration describing all of the possible ways that a death test can
8503 // conclude. DIED means that the process died while executing the test
8504 // code; LIVED means that process lived beyond the end of the test code;
8505 // RETURNED means that the test statement attempted to execute a return
8506 // statement, which is not allowed; THREW means that the test statement
8507 // returned control by throwing an exception. IN_PROGRESS means the test
8508 // has not yet concluded.
8509 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
8510
8511 // Routine for aborting the program which is safe to call from an
8512 // exec-style death test child process, in which case the error
8513 // message is propagated back to the parent process. Otherwise, the
8514 // message is simply printed to stderr. In either case, the program
8515 // then exits with status 1.
8516 static void DeathTestAbort(const std::string& message) {
8517 // On a POSIX system, this function may be called from a threadsafe-style
8518 // death test child process, which operates on a very small stack. Use
8519 // the heap for any additional non-minuscule memory requirements.
8520 const InternalRunDeathTestFlag* const flag =
8521 GetUnitTestImpl()->internal_run_death_test_flag();
8522 if (flag != nullptr) {
8523 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
8524 fputc(kDeathTestInternalError, parent);
8525 fprintf(parent, "%s", message.c_str());
8526 fflush(parent);
8527 _exit(1);
8528 } else {
8529 fprintf(stderr, "%s", message.c_str());
8530 fflush(stderr);
8531 posix::Abort();
8532 }
8533 }
8534
8535 // A replacement for CHECK that calls DeathTestAbort if the assertion
8536 // fails.
8537 # define GTEST_DEATH_TEST_CHECK_(expression) \
8538 do { \
8539 if (!::testing::internal::IsTrue(expression)) { \
8540 DeathTestAbort( \
8541 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
8542 + ::testing::internal::StreamableToString(__LINE__) + ": " \
8543 + #expression); \
8544 } \
8545 } while (::testing::internal::AlwaysFalse())
8546
8547 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
8548 // evaluating any system call that fulfills two conditions: it must return
8549 // -1 on failure, and set errno to EINTR when it is interrupted and
8550 // should be tried again. The macro expands to a loop that repeatedly
8551 // evaluates the expression as long as it evaluates to -1 and sets
8552 // errno to EINTR. If the expression evaluates to -1 but errno is
8553 // something other than EINTR, DeathTestAbort is called.
8554 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
8555 do { \
8556 int gtest_retval; \
8557 do { \
8558 gtest_retval = (expression); \
8559 } while (gtest_retval == -1 && errno == EINTR); \
8560 if (gtest_retval == -1) { \
8561 DeathTestAbort( \
8562 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
8563 + ::testing::internal::StreamableToString(__LINE__) + ": " \
8564 + #expression + " != -1"); \
8565 } \
8566 } while (::testing::internal::AlwaysFalse())
8567
8568 // Returns the message describing the last system error in errno.
8569 std::string GetLastErrnoDescription() {
8570 return errno == 0 ? "" : posix::StrError(errno);
8571 }
8572
8573 // This is called from a death test parent process to read a failure
8574 // message from the death test child process and log it with the FATAL
8575 // severity. On Windows, the message is read from a pipe handle. On other
8576 // platforms, it is read from a file descriptor.
8577 static void FailFromInternalError(int fd) {
8578 Message error;
8579 char buffer[256];
8580 int num_read;
8581
8582 do {
8583 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
8584 buffer[num_read] = '\0';
8585 error << buffer;
8586 }
8587 } while (num_read == -1 && errno == EINTR);
8588
8589 if (num_read == 0) {
8590 GTEST_LOG_(FATAL) << error.GetString();
8591 } else {
8592 const int last_error = errno;
8593 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
8594 << GetLastErrnoDescription() << " [" << last_error << "]";
8595 }
8596 }
8597
8598 // Death test constructor. Increments the running death test count
8599 // for the current test.
8600 DeathTest::DeathTest() {
8601 TestInfo* const info = GetUnitTestImpl()->current_test_info();
8602 if (info == nullptr) {
8603 DeathTestAbort("Cannot run a death test outside of a TEST or "
8604 "TEST_F construct");
8605 }
8606 }
8607
8608 // Creates and returns a death test by dispatching to the current
8609 // death test factory.
8610 bool DeathTest::Create(const char* statement,
8611 Matcher<const std::string&> matcher, const char* file,
8612 int line, DeathTest** test) {
8613 return GetUnitTestImpl()->death_test_factory()->Create(
8614 statement, std::move(matcher), file, line, test);
8615 }
8616
8617 const char* DeathTest::LastMessage() {
8618 return last_death_test_message_.c_str();
8619 }
8620
8621 void DeathTest::set_last_death_test_message(const std::string& message) {
8622 last_death_test_message_ = message;
8623 }
8624
8625 std::string DeathTest::last_death_test_message_;
8626
8627 // Provides cross platform implementation for some death functionality.
8628 class DeathTestImpl : public DeathTest {
8629 protected:
8630 DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
8631 : statement_(a_statement),
8632 matcher_(std::move(matcher)),
8633 spawned_(false),
8634 status_(-1),
8635 outcome_(IN_PROGRESS),
8636 read_fd_(-1),
8637 write_fd_(-1) {}
8638
8639 // read_fd_ is expected to be closed and cleared by a derived class.
8640 ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
8641
8642 void Abort(AbortReason reason) override;
8643 bool Passed(bool status_ok) override;
8644
8645 const char* statement() const { return statement_; }
8646 bool spawned() const { return spawned_; }
8647 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
8648 int status() const { return status_; }
8649 void set_status(int a_status) { status_ = a_status; }
8650 DeathTestOutcome outcome() const { return outcome_; }
8651 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
8652 int read_fd() const { return read_fd_; }
8653 void set_read_fd(int fd) { read_fd_ = fd; }
8654 int write_fd() const { return write_fd_; }
8655 void set_write_fd(int fd) { write_fd_ = fd; }
8656
8657 // Called in the parent process only. Reads the result code of the death
8658 // test child process via a pipe, interprets it to set the outcome_
8659 // member, and closes read_fd_. Outputs diagnostics and terminates in
8660 // case of unexpected codes.
8661 void ReadAndInterpretStatusByte();
8662
8663 // Returns stderr output from the child process.
8664 virtual std::string GetErrorLogs();
8665
8666 private:
8667 // The textual content of the code this object is testing. This class
8668 // doesn't own this string and should not attempt to delete it.
8669 const char* const statement_;
8670 // A matcher that's expected to match the stderr output by the child process.
8671 Matcher<const std::string&> matcher_;
8672 // True if the death test child process has been successfully spawned.
8673 bool spawned_;
8674 // The exit status of the child process.
8675 int status_;
8676 // How the death test concluded.
8677 DeathTestOutcome outcome_;
8678 // Descriptor to the read end of the pipe to the child process. It is
8679 // always -1 in the child process. The child keeps its write end of the
8680 // pipe in write_fd_.
8681 int read_fd_;
8682 // Descriptor to the child's write end of the pipe to the parent process.
8683 // It is always -1 in the parent process. The parent keeps its end of the
8684 // pipe in read_fd_.
8685 int write_fd_;
8686 };
8687
8688 // Called in the parent process only. Reads the result code of the death
8689 // test child process via a pipe, interprets it to set the outcome_
8690 // member, and closes read_fd_. Outputs diagnostics and terminates in
8691 // case of unexpected codes.
8692 void DeathTestImpl::ReadAndInterpretStatusByte() {
8693 char flag;
8694 int bytes_read;
8695
8696 // The read() here blocks until data is available (signifying the
8697 // failure of the death test) or until the pipe is closed (signifying
8698 // its success), so it's okay to call this in the parent before
8699 // the child process has exited.
8700 do {
8701 bytes_read = posix::Read(read_fd(), &flag, 1);
8702 } while (bytes_read == -1 && errno == EINTR);
8703
8704 if (bytes_read == 0) {
8705 set_outcome(DIED);
8706 } else if (bytes_read == 1) {
8707 switch (flag) {
8708 case kDeathTestReturned:
8709 set_outcome(RETURNED);
8710 break;
8711 case kDeathTestThrew:
8712 set_outcome(THREW);
8713 break;
8714 case kDeathTestLived:
8715 set_outcome(LIVED);
8716 break;
8717 case kDeathTestInternalError:
8718 FailFromInternalError(read_fd()); // Does not return.
8719 break;
8720 default:
8721 GTEST_LOG_(FATAL) << "Death test child process reported "
8722 << "unexpected status byte ("
8723 << static_cast<unsigned int>(flag) << ")";
8724 }
8725 } else {
8726 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
8727 << GetLastErrnoDescription();
8728 }
8729 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
8730 set_read_fd(-1);
8731 }
8732
8733 std::string DeathTestImpl::GetErrorLogs() {
8734 return GetCapturedStderr();
8735 }
8736
8737 // Signals that the death test code which should have exited, didn't.
8738 // Should be called only in a death test child process.
8739 // Writes a status byte to the child's status file descriptor, then
8740 // calls _exit(1).
8741 void DeathTestImpl::Abort(AbortReason reason) {
8742 // The parent process considers the death test to be a failure if
8743 // it finds any data in our pipe. So, here we write a single flag byte
8744 // to the pipe, then exit.
8745 const char status_ch =
8746 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
8747 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
8748
8749 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
8750 // We are leaking the descriptor here because on some platforms (i.e.,
8751 // when built as Windows DLL), destructors of global objects will still
8752 // run after calling _exit(). On such systems, write_fd_ will be
8753 // indirectly closed from the destructor of UnitTestImpl, causing double
8754 // close if it is also closed here. On debug configurations, double close
8755 // may assert. As there are no in-process buffers to flush here, we are
8756 // relying on the OS to close the descriptor after the process terminates
8757 // when the destructors are not run.
8758 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
8759 }
8760
8761 // Returns an indented copy of stderr output for a death test.
8762 // This makes distinguishing death test output lines from regular log lines
8763 // much easier.
8764 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
8765 ::std::string ret;
8766 for (size_t at = 0; ; ) {
8767 const size_t line_end = output.find('\n', at);
8768 ret += "[ DEATH ] ";
8769 if (line_end == ::std::string::npos) {
8770 ret += output.substr(at);
8771 break;
8772 }
8773 ret += output.substr(at, line_end + 1 - at);
8774 at = line_end + 1;
8775 }
8776 return ret;
8777 }
8778
8779 // Assesses the success or failure of a death test, using both private
8780 // members which have previously been set, and one argument:
8781 //
8782 // Private data members:
8783 // outcome: An enumeration describing how the death test
8784 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
8785 // fails in the latter three cases.
8786 // status: The exit status of the child process. On *nix, it is in the
8787 // in the format specified by wait(2). On Windows, this is the
8788 // value supplied to the ExitProcess() API or a numeric code
8789 // of the exception that terminated the program.
8790 // matcher_: A matcher that's expected to match the stderr output by the child
8791 // process.
8792 //
8793 // Argument:
8794 // status_ok: true if exit_status is acceptable in the context of
8795 // this particular death test, which fails if it is false
8796 //
8797 // Returns true if and only if all of the above conditions are met. Otherwise,
8798 // the first failing condition, in the order given above, is the one that is
8799 // reported. Also sets the last death test message string.
8800 bool DeathTestImpl::Passed(bool status_ok) {
8801 if (!spawned())
8802 return false;
8803
8804 const std::string error_message = GetErrorLogs();
8805
8806 bool success = false;
8807 Message buffer;
8808
8809 buffer << "Death test: " << statement() << "\n";
8810 switch (outcome()) {
8811 case LIVED:
8812 buffer << " Result: failed to die.\n"
8813 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8814 break;
8815 case THREW:
8816 buffer << " Result: threw an exception.\n"
8817 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8818 break;
8819 case RETURNED:
8820 buffer << " Result: illegal return in test statement.\n"
8821 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8822 break;
8823 case DIED:
8824 if (status_ok) {
8825 if (matcher_.Matches(error_message)) {
8826 success = true;
8827 } else {
8828 std::ostringstream stream;
8829 matcher_.DescribeTo(&stream);
8830 buffer << " Result: died but not with expected error.\n"
8831 << " Expected: " << stream.str() << "\n"
8832 << "Actual msg:\n"
8833 << FormatDeathTestOutput(error_message);
8834 }
8835 } else {
8836 buffer << " Result: died but not with expected exit code:\n"
8837 << " " << ExitSummary(status()) << "\n"
8838 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
8839 }
8840 break;
8841 case IN_PROGRESS:
8842 default:
8843 GTEST_LOG_(FATAL)
8844 << "DeathTest::Passed somehow called before conclusion of test";
8845 }
8846
8847 DeathTest::set_last_death_test_message(buffer.GetString());
8848 return success;
8849 }
8850
8851 # if GTEST_OS_WINDOWS
8852 // WindowsDeathTest implements death tests on Windows. Due to the
8853 // specifics of starting new processes on Windows, death tests there are
8854 // always threadsafe, and Google Test considers the
8855 // --gtest_death_test_style=fast setting to be equivalent to
8856 // --gtest_death_test_style=threadsafe there.
8857 //
8858 // A few implementation notes: Like the Linux version, the Windows
8859 // implementation uses pipes for child-to-parent communication. But due to
8860 // the specifics of pipes on Windows, some extra steps are required:
8861 //
8862 // 1. The parent creates a communication pipe and stores handles to both
8863 // ends of it.
8864 // 2. The parent starts the child and provides it with the information
8865 // necessary to acquire the handle to the write end of the pipe.
8866 // 3. The child acquires the write end of the pipe and signals the parent
8867 // using a Windows event.
8868 // 4. Now the parent can release the write end of the pipe on its side. If
8869 // this is done before step 3, the object's reference count goes down to
8870 // 0 and it is destroyed, preventing the child from acquiring it. The
8871 // parent now has to release it, or read operations on the read end of
8872 // the pipe will not return when the child terminates.
8873 // 5. The parent reads child's output through the pipe (outcome code and
8874 // any possible error messages) from the pipe, and its stderr and then
8875 // determines whether to fail the test.
8876 //
8877 // Note: to distinguish Win32 API calls from the local method and function
8878 // calls, the former are explicitly resolved in the global namespace.
8879 //
8880 class WindowsDeathTest : public DeathTestImpl {
8881 public:
8882 WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8883 const char* file, int line)
8884 : DeathTestImpl(a_statement, std::move(matcher)),
8885 file_(file),
8886 line_(line) {}
8887
8888 // All of these virtual functions are inherited from DeathTest.
8889 virtual int Wait();
8890 virtual TestRole AssumeRole();
8891
8892 private:
8893 // The name of the file in which the death test is located.
8894 const char* const file_;
8895 // The line number on which the death test is located.
8896 const int line_;
8897 // Handle to the write end of the pipe to the child process.
8898 AutoHandle write_handle_;
8899 // Child process handle.
8900 AutoHandle child_handle_;
8901 // Event the child process uses to signal the parent that it has
8902 // acquired the handle to the write end of the pipe. After seeing this
8903 // event the parent can release its own handles to make sure its
8904 // ReadFile() calls return when the child terminates.
8905 AutoHandle event_handle_;
8906 };
8907
8908 // Waits for the child in a death test to exit, returning its exit
8909 // status, or 0 if no child process exists. As a side effect, sets the
8910 // outcome data member.
8911 int WindowsDeathTest::Wait() {
8912 if (!spawned())
8913 return 0;
8914
8915 // Wait until the child either signals that it has acquired the write end
8916 // of the pipe or it dies.
8917 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8918 switch (::WaitForMultipleObjects(2,
8919 wait_handles,
8920 FALSE, // Waits for any of the handles.
8921 INFINITE)) {
8922 case WAIT_OBJECT_0:
8923 case WAIT_OBJECT_0 + 1:
8924 break;
8925 default:
8926 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
8927 }
8928
8929 // The child has acquired the write end of the pipe or exited.
8930 // We release the handle on our side and continue.
8931 write_handle_.Reset();
8932 event_handle_.Reset();
8933
8934 ReadAndInterpretStatusByte();
8935
8936 // Waits for the child process to exit if it haven't already. This
8937 // returns immediately if the child has already exited, regardless of
8938 // whether previous calls to WaitForMultipleObjects synchronized on this
8939 // handle or not.
8940 GTEST_DEATH_TEST_CHECK_(
8941 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8942 INFINITE));
8943 DWORD status_code;
8944 GTEST_DEATH_TEST_CHECK_(
8945 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8946 child_handle_.Reset();
8947 set_status(static_cast<int>(status_code));
8948 return status();
8949 }
8950
8951 // The AssumeRole process for a Windows death test. It creates a child
8952 // process with the same executable as the current process to run the
8953 // death test. The child process is given the --gtest_filter and
8954 // --gtest_internal_run_death_test flags such that it knows to run the
8955 // current death test only.
8956 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8957 const UnitTestImpl* const impl = GetUnitTestImpl();
8958 const InternalRunDeathTestFlag* const flag =
8959 impl->internal_run_death_test_flag();
8960 const TestInfo* const info = impl->current_test_info();
8961 const int death_test_index = info->result()->death_test_count();
8962
8963 if (flag != nullptr) {
8964 // ParseInternalRunDeathTestFlag() has performed all the necessary
8965 // processing.
8966 set_write_fd(flag->write_fd());
8967 return EXECUTE_TEST;
8968 }
8969
8970 // WindowsDeathTest uses an anonymous pipe to communicate results of
8971 // a death test.
8972 SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
8973 nullptr, TRUE};
8974 HANDLE read_handle, write_handle;
8975 GTEST_DEATH_TEST_CHECK_(
8976 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8977 0) // Default buffer size.
8978 != FALSE);
8979 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8980 O_RDONLY));
8981 write_handle_.Reset(write_handle);
8982 event_handle_.Reset(::CreateEvent(
8983 &handles_are_inheritable,
8984 TRUE, // The event will automatically reset to non-signaled state.
8985 FALSE, // The initial state is non-signalled.
8986 nullptr)); // The even is unnamed.
8987 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
8988 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8989 kFilterFlag + "=" + info->test_suite_name() +
8990 "." + info->name();
8991 const std::string internal_flag =
8992 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
8993 "=" + file_ + "|" + StreamableToString(line_) + "|" +
8994 StreamableToString(death_test_index) + "|" +
8995 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
8996 // size_t has the same width as pointers on both 32-bit and 64-bit
8997 // Windows platforms.
8998 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
8999 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
9000 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
9001
9002 char executable_path[_MAX_PATH + 1]; // NOLINT
9003 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
9004 executable_path,
9005 _MAX_PATH));
9006
9007 std::string command_line =
9008 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
9009 internal_flag + "\"";
9010
9011 DeathTest::set_last_death_test_message("");
9012
9013 CaptureStderr();
9014 // Flush the log buffers since the log streams are shared with the child.
9015 FlushInfoLog();
9016
9017 // The child process will share the standard handles with the parent.
9018 STARTUPINFOA startup_info;
9019 memset(&startup_info, 0, sizeof(STARTUPINFO));
9020 startup_info.dwFlags = STARTF_USESTDHANDLES;
9021 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
9022 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
9023 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
9024
9025 PROCESS_INFORMATION process_info;
9026 GTEST_DEATH_TEST_CHECK_(
9027 ::CreateProcessA(
9028 executable_path, const_cast<char*>(command_line.c_str()),
9029 nullptr, // Retuned process handle is not inheritable.
9030 nullptr, // Retuned thread handle is not inheritable.
9031 TRUE, // Child inherits all inheritable handles (for write_handle_).
9032 0x0, // Default creation flags.
9033 nullptr, // Inherit the parent's environment.
9034 UnitTest::GetInstance()->original_working_dir(), &startup_info,
9035 &process_info) != FALSE);
9036 child_handle_.Reset(process_info.hProcess);
9037 ::CloseHandle(process_info.hThread);
9038 set_spawned(true);
9039 return OVERSEE_TEST;
9040 }
9041
9042 # elif GTEST_OS_FUCHSIA
9043
9044 class FuchsiaDeathTest : public DeathTestImpl {
9045 public:
9046 FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
9047 const char* file, int line)
9048 : DeathTestImpl(a_statement, std::move(matcher)),
9049 file_(file),
9050 line_(line) {}
9051
9052 // All of these virtual functions are inherited from DeathTest.
9053 int Wait() override;
9054 TestRole AssumeRole() override;
9055 std::string GetErrorLogs() override;
9056
9057 private:
9058 // The name of the file in which the death test is located.
9059 const char* const file_;
9060 // The line number on which the death test is located.
9061 const int line_;
9062 // The stderr data captured by the child process.
9063 std::string captured_stderr_;
9064
9065 zx::process child_process_;
9066 zx::channel exception_channel_;
9067 zx::socket stderr_socket_;
9068 };
9069
9070 // Utility class for accumulating command-line arguments.
9071 class Arguments {
9072 public:
9073 Arguments() { args_.push_back(nullptr); }
9074
9075 ~Arguments() {
9076 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
9077 ++i) {
9078 free(*i);
9079 }
9080 }
9081 void AddArgument(const char* argument) {
9082 args_.insert(args_.end() - 1, posix::StrDup(argument));
9083 }
9084
9085 template <typename Str>
9086 void AddArguments(const ::std::vector<Str>& arguments) {
9087 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
9088 i != arguments.end();
9089 ++i) {
9090 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
9091 }
9092 }
9093 char* const* Argv() {
9094 return &args_[0];
9095 }
9096
9097 int size() {
9098 return static_cast<int>(args_.size()) - 1;
9099 }
9100
9101 private:
9102 std::vector<char*> args_;
9103 };
9104
9105 // Waits for the child in a death test to exit, returning its exit
9106 // status, or 0 if no child process exists. As a side effect, sets the
9107 // outcome data member.
9108 int FuchsiaDeathTest::Wait() {
9109 const int kProcessKey = 0;
9110 const int kSocketKey = 1;
9111 const int kExceptionKey = 2;
9112
9113 if (!spawned())
9114 return 0;
9115
9116 // Create a port to wait for socket/task/exception events.
9117 zx_status_t status_zx;
9118 zx::port port;
9119 status_zx = zx::port::create(0, &port);
9120 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9121
9122 // Register to wait for the child process to terminate.
9123 status_zx = child_process_.wait_async(
9124 port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
9125 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9126
9127 // Register to wait for the socket to be readable or closed.
9128 status_zx = stderr_socket_.wait_async(
9129 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
9130 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9131
9132 // Register to wait for an exception.
9133 status_zx = exception_channel_.wait_async(
9134 port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
9135 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9136
9137 bool process_terminated = false;
9138 bool socket_closed = false;
9139 do {
9140 zx_port_packet_t packet = {};
9141 status_zx = port.wait(zx::time::infinite(), &packet);
9142 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9143
9144 if (packet.key == kExceptionKey) {
9145 // Process encountered an exception. Kill it directly rather than
9146 // letting other handlers process the event. We will get a kProcessKey
9147 // event when the process actually terminates.
9148 status_zx = child_process_.kill();
9149 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9150 } else if (packet.key == kProcessKey) {
9151 // Process terminated.
9152 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
9153 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
9154 process_terminated = true;
9155 } else if (packet.key == kSocketKey) {
9156 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
9157 if (packet.signal.observed & ZX_SOCKET_READABLE) {
9158 // Read data from the socket.
9159 constexpr size_t kBufferSize = 1024;
9160 do {
9161 size_t old_length = captured_stderr_.length();
9162 size_t bytes_read = 0;
9163 captured_stderr_.resize(old_length + kBufferSize);
9164 status_zx = stderr_socket_.read(
9165 0, &captured_stderr_.front() + old_length, kBufferSize,
9166 &bytes_read);
9167 captured_stderr_.resize(old_length + bytes_read);
9168 } while (status_zx == ZX_OK);
9169 if (status_zx == ZX_ERR_PEER_CLOSED) {
9170 socket_closed = true;
9171 } else {
9172 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
9173 status_zx = stderr_socket_.wait_async(
9174 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
9175 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9176 }
9177 } else {
9178 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
9179 socket_closed = true;
9180 }
9181 }
9182 } while (!process_terminated && !socket_closed);
9183
9184 ReadAndInterpretStatusByte();
9185
9186 zx_info_process_v2_t buffer;
9187 status_zx = child_process_.get_info(
9188 ZX_INFO_PROCESS_V2, &buffer, sizeof(buffer), nullptr, nullptr);
9189 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9190
9191 GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
9192 set_status(static_cast<int>(buffer.return_code));
9193 return status();
9194 }
9195
9196 // The AssumeRole process for a Fuchsia death test. It creates a child
9197 // process with the same executable as the current process to run the
9198 // death test. The child process is given the --gtest_filter and
9199 // --gtest_internal_run_death_test flags such that it knows to run the
9200 // current death test only.
9201 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
9202 const UnitTestImpl* const impl = GetUnitTestImpl();
9203 const InternalRunDeathTestFlag* const flag =
9204 impl->internal_run_death_test_flag();
9205 const TestInfo* const info = impl->current_test_info();
9206 const int death_test_index = info->result()->death_test_count();
9207
9208 if (flag != nullptr) {
9209 // ParseInternalRunDeathTestFlag() has performed all the necessary
9210 // processing.
9211 set_write_fd(kFuchsiaReadPipeFd);
9212 return EXECUTE_TEST;
9213 }
9214
9215 // Flush the log buffers since the log streams are shared with the child.
9216 FlushInfoLog();
9217
9218 // Build the child process command line.
9219 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
9220 kFilterFlag + "=" + info->test_suite_name() +
9221 "." + info->name();
9222 const std::string internal_flag =
9223 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
9224 + file_ + "|"
9225 + StreamableToString(line_) + "|"
9226 + StreamableToString(death_test_index);
9227 Arguments args;
9228 args.AddArguments(GetInjectableArgvs());
9229 args.AddArgument(filter_flag.c_str());
9230 args.AddArgument(internal_flag.c_str());
9231
9232 // Build the pipe for communication with the child.
9233 zx_status_t status;
9234 zx_handle_t child_pipe_handle;
9235 int child_pipe_fd;
9236 status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);
9237 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9238 set_read_fd(child_pipe_fd);
9239
9240 // Set the pipe handle for the child.
9241 fdio_spawn_action_t spawn_actions[2] = {};
9242 fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
9243 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
9244 add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
9245 add_handle_action->h.handle = child_pipe_handle;
9246
9247 // Create a socket pair will be used to receive the child process' stderr.
9248 zx::socket stderr_producer_socket;
9249 status =
9250 zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
9251 GTEST_DEATH_TEST_CHECK_(status >= 0);
9252 int stderr_producer_fd = -1;
9253 status =
9254 fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
9255 GTEST_DEATH_TEST_CHECK_(status >= 0);
9256
9257 // Make the stderr socket nonblocking.
9258 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
9259
9260 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
9261 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
9262 add_stderr_action->fd.local_fd = stderr_producer_fd;
9263 add_stderr_action->fd.target_fd = STDERR_FILENO;
9264
9265 // Create a child job.
9266 zx_handle_t child_job = ZX_HANDLE_INVALID;
9267 status = zx_job_create(zx_job_default(), 0, & child_job);
9268 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9269 zx_policy_basic_t policy;
9270 policy.condition = ZX_POL_NEW_ANY;
9271 policy.policy = ZX_POL_ACTION_ALLOW;
9272 status = zx_job_set_policy(
9273 child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
9274 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9275
9276 // Create an exception channel attached to the |child_job|, to allow
9277 // us to suppress the system default exception handler from firing.
9278 status =
9279 zx_task_create_exception_channel(
9280 child_job, 0, exception_channel_.reset_and_get_address());
9281 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9282
9283 // Spawn the child process.
9284 status = fdio_spawn_etc(
9285 child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
9286 2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
9287 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9288
9289 set_spawned(true);
9290 return OVERSEE_TEST;
9291 }
9292
9293 std::string FuchsiaDeathTest::GetErrorLogs() {
9294 return captured_stderr_;
9295 }
9296
9297 #else // We are neither on Windows, nor on Fuchsia.
9298
9299 // ForkingDeathTest provides implementations for most of the abstract
9300 // methods of the DeathTest interface. Only the AssumeRole method is
9301 // left undefined.
9302 class ForkingDeathTest : public DeathTestImpl {
9303 public:
9304 ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
9305
9306 // All of these virtual functions are inherited from DeathTest.
9307 int Wait() override;
9308
9309 protected:
9310 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
9311
9312 private:
9313 // PID of child process during death test; 0 in the child process itself.
9314 pid_t child_pid_;
9315 };
9316
9317 // Constructs a ForkingDeathTest.
9318 ForkingDeathTest::ForkingDeathTest(const char* a_statement,
9319 Matcher<const std::string&> matcher)
9320 : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
9321
9322 // Waits for the child in a death test to exit, returning its exit
9323 // status, or 0 if no child process exists. As a side effect, sets the
9324 // outcome data member.
9325 int ForkingDeathTest::Wait() {
9326 if (!spawned())
9327 return 0;
9328
9329 ReadAndInterpretStatusByte();
9330
9331 int status_value;
9332 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
9333 set_status(status_value);
9334 return status_value;
9335 }
9336
9337 // A concrete death test class that forks, then immediately runs the test
9338 // in the child process.
9339 class NoExecDeathTest : public ForkingDeathTest {
9340 public:
9341 NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
9342 : ForkingDeathTest(a_statement, std::move(matcher)) {}
9343 TestRole AssumeRole() override;
9344 };
9345
9346 // The AssumeRole process for a fork-and-run death test. It implements a
9347 // straightforward fork, with a simple pipe to transmit the status byte.
9348 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
9349 const size_t thread_count = GetThreadCount();
9350 if (thread_count != 1) {
9351 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
9352 }
9353
9354 int pipe_fd[2];
9355 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
9356
9357 DeathTest::set_last_death_test_message("");
9358 CaptureStderr();
9359 // When we fork the process below, the log file buffers are copied, but the
9360 // file descriptors are shared. We flush all log files here so that closing
9361 // the file descriptors in the child process doesn't throw off the
9362 // synchronization between descriptors and buffers in the parent process.
9363 // This is as close to the fork as possible to avoid a race condition in case
9364 // there are multiple threads running before the death test, and another
9365 // thread writes to the log file.
9366 FlushInfoLog();
9367
9368 const pid_t child_pid = fork();
9369 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
9370 set_child_pid(child_pid);
9371 if (child_pid == 0) {
9372 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
9373 set_write_fd(pipe_fd[1]);
9374 // Redirects all logging to stderr in the child process to prevent
9375 // concurrent writes to the log files. We capture stderr in the parent
9376 // process and append the child process' output to a log.
9377 LogToStderr();
9378 // Event forwarding to the listeners of event listener API mush be shut
9379 // down in death test subprocesses.
9380 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
9381 g_in_fast_death_test_child = true;
9382 return EXECUTE_TEST;
9383 } else {
9384 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
9385 set_read_fd(pipe_fd[0]);
9386 set_spawned(true);
9387 return OVERSEE_TEST;
9388 }
9389 }
9390
9391 // A concrete death test class that forks and re-executes the main
9392 // program from the beginning, with command-line flags set that cause
9393 // only this specific death test to be run.
9394 class ExecDeathTest : public ForkingDeathTest {
9395 public:
9396 ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
9397 const char* file, int line)
9398 : ForkingDeathTest(a_statement, std::move(matcher)),
9399 file_(file),
9400 line_(line) {}
9401 TestRole AssumeRole() override;
9402
9403 private:
9404 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
9405 ::std::vector<std::string> args = GetInjectableArgvs();
9406 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
9407 ::std::vector<std::string> extra_args =
9408 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
9409 args.insert(args.end(), extra_args.begin(), extra_args.end());
9410 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
9411 return args;
9412 }
9413 // The name of the file in which the death test is located.
9414 const char* const file_;
9415 // The line number on which the death test is located.
9416 const int line_;
9417 };
9418
9419 // Utility class for accumulating command-line arguments.
9420 class Arguments {
9421 public:
9422 Arguments() { args_.push_back(nullptr); }
9423
9424 ~Arguments() {
9425 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
9426 ++i) {
9427 free(*i);
9428 }
9429 }
9430 void AddArgument(const char* argument) {
9431 args_.insert(args_.end() - 1, posix::StrDup(argument));
9432 }
9433
9434 template <typename Str>
9435 void AddArguments(const ::std::vector<Str>& arguments) {
9436 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
9437 i != arguments.end();
9438 ++i) {
9439 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
9440 }
9441 }
9442 char* const* Argv() {
9443 return &args_[0];
9444 }
9445
9446 private:
9447 std::vector<char*> args_;
9448 };
9449
9450 // A struct that encompasses the arguments to the child process of a
9451 // threadsafe-style death test process.
9452 struct ExecDeathTestArgs {
9453 char* const* argv; // Command-line arguments for the child's call to exec
9454 int close_fd; // File descriptor to close; the read end of a pipe
9455 };
9456
9457 # if GTEST_OS_QNX
9458 extern "C" char** environ;
9459 # else // GTEST_OS_QNX
9460 // The main function for a threadsafe-style death test child process.
9461 // This function is called in a clone()-ed process and thus must avoid
9462 // any potentially unsafe operations like malloc or libc functions.
9463 static int ExecDeathTestChildMain(void* child_arg) {
9464 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
9465 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
9466
9467 // We need to execute the test program in the same environment where
9468 // it was originally invoked. Therefore we change to the original
9469 // working directory first.
9470 const char* const original_dir =
9471 UnitTest::GetInstance()->original_working_dir();
9472 // We can safely call chdir() as it's a direct system call.
9473 if (chdir(original_dir) != 0) {
9474 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
9475 GetLastErrnoDescription());
9476 return EXIT_FAILURE;
9477 }
9478
9479 // We can safely call execv() as it's almost a direct system call. We
9480 // cannot use execvp() as it's a libc function and thus potentially
9481 // unsafe. Since execv() doesn't search the PATH, the user must
9482 // invoke the test program via a valid path that contains at least
9483 // one path separator.
9484 execv(args->argv[0], args->argv);
9485 DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
9486 original_dir + " failed: " +
9487 GetLastErrnoDescription());
9488 return EXIT_FAILURE;
9489 }
9490 # endif // GTEST_OS_QNX
9491
9492 # if GTEST_HAS_CLONE
9493 // Two utility routines that together determine the direction the stack
9494 // grows.
9495 // This could be accomplished more elegantly by a single recursive
9496 // function, but we want to guard against the unlikely possibility of
9497 // a smart compiler optimizing the recursion away.
9498 //
9499 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
9500 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
9501 // correct answer.
9502 static void StackLowerThanAddress(const void* ptr,
9503 bool* result) GTEST_NO_INLINE_;
9504 // Make sure sanitizers do not tamper with the stack here.
9505 // Ideally, we want to use `__builtin_frame_address` instead of a local variable
9506 // address with sanitizer disabled, but it does not work when the
9507 // compiler optimizes the stack frame out, which happens on PowerPC targets.
9508 // HWAddressSanitizer add a random tag to the MSB of the local variable address,
9509 // making comparison result unpredictable.
9510 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
9511 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
9512 static void StackLowerThanAddress(const void* ptr, bool* result) {
9513 int dummy = 0;
9514 *result = std::less<const void*>()(&dummy, ptr);
9515 }
9516
9517 // Make sure AddressSanitizer does not tamper with the stack here.
9518 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
9519 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
9520 static bool StackGrowsDown() {
9521 int dummy = 0;
9522 bool result;
9523 StackLowerThanAddress(&dummy, &result);
9524 return result;
9525 }
9526 # endif // GTEST_HAS_CLONE
9527
9528 // Spawns a child process with the same executable as the current process in
9529 // a thread-safe manner and instructs it to run the death test. The
9530 // implementation uses fork(2) + exec. On systems where clone(2) is
9531 // available, it is used instead, being slightly more thread-safe. On QNX,
9532 // fork supports only single-threaded environments, so this function uses
9533 // spawn(2) there instead. The function dies with an error message if
9534 // anything goes wrong.
9535 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
9536 ExecDeathTestArgs args = { argv, close_fd };
9537 pid_t child_pid = -1;
9538
9539 # if GTEST_OS_QNX
9540 // Obtains the current directory and sets it to be closed in the child
9541 // process.
9542 const int cwd_fd = open(".", O_RDONLY);
9543 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
9544 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
9545 // We need to execute the test program in the same environment where
9546 // it was originally invoked. Therefore we change to the original
9547 // working directory first.
9548 const char* const original_dir =
9549 UnitTest::GetInstance()->original_working_dir();
9550 // We can safely call chdir() as it's a direct system call.
9551 if (chdir(original_dir) != 0) {
9552 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
9553 GetLastErrnoDescription());
9554 return EXIT_FAILURE;
9555 }
9556
9557 int fd_flags;
9558 // Set close_fd to be closed after spawn.
9559 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
9560 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
9561 fd_flags | FD_CLOEXEC));
9562 struct inheritance inherit = {0};
9563 // spawn is a system call.
9564 child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
9565 // Restores the current working directory.
9566 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
9567 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
9568
9569 # else // GTEST_OS_QNX
9570 # if GTEST_OS_LINUX
9571 // When a SIGPROF signal is received while fork() or clone() are executing,
9572 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
9573 // it after the call to fork()/clone() is complete.
9574 struct sigaction saved_sigprof_action;
9575 struct sigaction ignore_sigprof_action;
9576 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
9577 sigemptyset(&ignore_sigprof_action.sa_mask);
9578 ignore_sigprof_action.sa_handler = SIG_IGN;
9579 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
9580 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
9581 # endif // GTEST_OS_LINUX
9582
9583 # if GTEST_HAS_CLONE
9584 const bool use_fork = GTEST_FLAG(death_test_use_fork);
9585
9586 if (!use_fork) {
9587 static const bool stack_grows_down = StackGrowsDown();
9588 const auto stack_size = static_cast<size_t>(getpagesize() * 2);
9589 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
9590 void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
9591 MAP_ANON | MAP_PRIVATE, -1, 0);
9592 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
9593
9594 // Maximum stack alignment in bytes: For a downward-growing stack, this
9595 // amount is subtracted from size of the stack space to get an address
9596 // that is within the stack space and is aligned on all systems we care
9597 // about. As far as I know there is no ABI with stack alignment greater
9598 // than 64. We assume stack and stack_size already have alignment of
9599 // kMaxStackAlignment.
9600 const size_t kMaxStackAlignment = 64;
9601 void* const stack_top =
9602 static_cast<char*>(stack) +
9603 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
9604 GTEST_DEATH_TEST_CHECK_(
9605 static_cast<size_t>(stack_size) > kMaxStackAlignment &&
9606 reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);
9607
9608 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
9609
9610 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
9611 }
9612 # else
9613 const bool use_fork = true;
9614 # endif // GTEST_HAS_CLONE
9615
9616 if (use_fork && (child_pid = fork()) == 0) {
9617 ExecDeathTestChildMain(&args);
9618 _exit(0);
9619 }
9620 # endif // GTEST_OS_QNX
9621 # if GTEST_OS_LINUX
9622 GTEST_DEATH_TEST_CHECK_SYSCALL_(
9623 sigaction(SIGPROF, &saved_sigprof_action, nullptr));
9624 # endif // GTEST_OS_LINUX
9625
9626 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
9627 return child_pid;
9628 }
9629
9630 // The AssumeRole process for a fork-and-exec death test. It re-executes the
9631 // main program from the beginning, setting the --gtest_filter
9632 // and --gtest_internal_run_death_test flags to cause only the current
9633 // death test to be re-run.
9634 DeathTest::TestRole ExecDeathTest::AssumeRole() {
9635 const UnitTestImpl* const impl = GetUnitTestImpl();
9636 const InternalRunDeathTestFlag* const flag =
9637 impl->internal_run_death_test_flag();
9638 const TestInfo* const info = impl->current_test_info();
9639 const int death_test_index = info->result()->death_test_count();
9640
9641 if (flag != nullptr) {
9642 set_write_fd(flag->write_fd());
9643 return EXECUTE_TEST;
9644 }
9645
9646 int pipe_fd[2];
9647 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
9648 // Clear the close-on-exec flag on the write end of the pipe, lest
9649 // it be closed when the child process does an exec:
9650 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
9651
9652 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
9653 kFilterFlag + "=" + info->test_suite_name() +
9654 "." + info->name();
9655 const std::string internal_flag =
9656 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
9657 + file_ + "|" + StreamableToString(line_) + "|"
9658 + StreamableToString(death_test_index) + "|"
9659 + StreamableToString(pipe_fd[1]);
9660 Arguments args;
9661 args.AddArguments(GetArgvsForDeathTestChildProcess());
9662 args.AddArgument(filter_flag.c_str());
9663 args.AddArgument(internal_flag.c_str());
9664
9665 DeathTest::set_last_death_test_message("");
9666
9667 CaptureStderr();
9668 // See the comment in NoExecDeathTest::AssumeRole for why the next line
9669 // is necessary.
9670 FlushInfoLog();
9671
9672 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
9673 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
9674 set_child_pid(child_pid);
9675 set_read_fd(pipe_fd[0]);
9676 set_spawned(true);
9677 return OVERSEE_TEST;
9678 }
9679
9680 # endif // !GTEST_OS_WINDOWS
9681
9682 // Creates a concrete DeathTest-derived class that depends on the
9683 // --gtest_death_test_style flag, and sets the pointer pointed to
9684 // by the "test" argument to its address. If the test should be
9685 // skipped, sets that pointer to NULL. Returns true, unless the
9686 // flag is set to an invalid value.
9687 bool DefaultDeathTestFactory::Create(const char* statement,
9688 Matcher<const std::string&> matcher,
9689 const char* file, int line,
9690 DeathTest** test) {
9691 UnitTestImpl* const impl = GetUnitTestImpl();
9692 const InternalRunDeathTestFlag* const flag =
9693 impl->internal_run_death_test_flag();
9694 const int death_test_index = impl->current_test_info()
9695 ->increment_death_test_count();
9696
9697 if (flag != nullptr) {
9698 if (death_test_index > flag->index()) {
9699 DeathTest::set_last_death_test_message(
9700 "Death test count (" + StreamableToString(death_test_index)
9701 + ") somehow exceeded expected maximum ("
9702 + StreamableToString(flag->index()) + ")");
9703 return false;
9704 }
9705
9706 if (!(flag->file() == file && flag->line() == line &&
9707 flag->index() == death_test_index)) {
9708 *test = nullptr;
9709 return true;
9710 }
9711 }
9712
9713 # if GTEST_OS_WINDOWS
9714
9715 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9716 GTEST_FLAG(death_test_style) == "fast") {
9717 *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
9718 }
9719
9720 # elif GTEST_OS_FUCHSIA
9721
9722 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9723 GTEST_FLAG(death_test_style) == "fast") {
9724 *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
9725 }
9726
9727 # else
9728
9729 if (GTEST_FLAG(death_test_style) == "threadsafe") {
9730 *test = new ExecDeathTest(statement, std::move(matcher), file, line);
9731 } else if (GTEST_FLAG(death_test_style) == "fast") {
9732 *test = new NoExecDeathTest(statement, std::move(matcher));
9733 }
9734
9735 # endif // GTEST_OS_WINDOWS
9736
9737 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
9738 DeathTest::set_last_death_test_message(
9739 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
9740 + "\" encountered");
9741 return false;
9742 }
9743
9744 return true;
9745 }
9746
9747 # if GTEST_OS_WINDOWS
9748 // Recreates the pipe and event handles from the provided parameters,
9749 // signals the event, and returns a file descriptor wrapped around the pipe
9750 // handle. This function is called in the child process only.
9751 static int GetStatusFileDescriptor(unsigned int parent_process_id,
9752 size_t write_handle_as_size_t,
9753 size_t event_handle_as_size_t) {
9754 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
9755 FALSE, // Non-inheritable.
9756 parent_process_id));
9757 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
9758 DeathTestAbort("Unable to open parent process " +
9759 StreamableToString(parent_process_id));
9760 }
9761
9762 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
9763
9764 const HANDLE write_handle =
9765 reinterpret_cast<HANDLE>(write_handle_as_size_t);
9766 HANDLE dup_write_handle;
9767
9768 // The newly initialized handle is accessible only in the parent
9769 // process. To obtain one accessible within the child, we need to use
9770 // DuplicateHandle.
9771 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
9772 ::GetCurrentProcess(), &dup_write_handle,
9773 0x0, // Requested privileges ignored since
9774 // DUPLICATE_SAME_ACCESS is used.
9775 FALSE, // Request non-inheritable handler.
9776 DUPLICATE_SAME_ACCESS)) {
9777 DeathTestAbort("Unable to duplicate the pipe handle " +
9778 StreamableToString(write_handle_as_size_t) +
9779 " from the parent process " +
9780 StreamableToString(parent_process_id));
9781 }
9782
9783 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
9784 HANDLE dup_event_handle;
9785
9786 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
9787 ::GetCurrentProcess(), &dup_event_handle,
9788 0x0,
9789 FALSE,
9790 DUPLICATE_SAME_ACCESS)) {
9791 DeathTestAbort("Unable to duplicate the event handle " +
9792 StreamableToString(event_handle_as_size_t) +
9793 " from the parent process " +
9794 StreamableToString(parent_process_id));
9795 }
9796
9797 const int write_fd =
9798 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
9799 if (write_fd == -1) {
9800 DeathTestAbort("Unable to convert pipe handle " +
9801 StreamableToString(write_handle_as_size_t) +
9802 " to a file descriptor");
9803 }
9804
9805 // Signals the parent that the write end of the pipe has been acquired
9806 // so the parent can release its own write end.
9807 ::SetEvent(dup_event_handle);
9808
9809 return write_fd;
9810 }
9811 # endif // GTEST_OS_WINDOWS
9812
9813 // Returns a newly created InternalRunDeathTestFlag object with fields
9814 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
9815 // the flag is specified; otherwise returns NULL.
9816 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
9817 if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
9818
9819 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
9820 // can use it here.
9821 int line = -1;
9822 int index = -1;
9823 ::std::vector< ::std::string> fields;
9824 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
9825 int write_fd = -1;
9826
9827 # if GTEST_OS_WINDOWS
9828
9829 unsigned int parent_process_id = 0;
9830 size_t write_handle_as_size_t = 0;
9831 size_t event_handle_as_size_t = 0;
9832
9833 if (fields.size() != 6
9834 || !ParseNaturalNumber(fields[1], &line)
9835 || !ParseNaturalNumber(fields[2], &index)
9836 || !ParseNaturalNumber(fields[3], &parent_process_id)
9837 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
9838 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
9839 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
9840 GTEST_FLAG(internal_run_death_test));
9841 }
9842 write_fd = GetStatusFileDescriptor(parent_process_id,
9843 write_handle_as_size_t,
9844 event_handle_as_size_t);
9845
9846 # elif GTEST_OS_FUCHSIA
9847
9848 if (fields.size() != 3
9849 || !ParseNaturalNumber(fields[1], &line)
9850 || !ParseNaturalNumber(fields[2], &index)) {
9851 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9852 + GTEST_FLAG(internal_run_death_test));
9853 }
9854
9855 # else
9856
9857 if (fields.size() != 4
9858 || !ParseNaturalNumber(fields[1], &line)
9859 || !ParseNaturalNumber(fields[2], &index)
9860 || !ParseNaturalNumber(fields[3], &write_fd)) {
9861 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9862 + GTEST_FLAG(internal_run_death_test));
9863 }
9864
9865 # endif // GTEST_OS_WINDOWS
9866
9867 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9868 }
9869
9870 } // namespace internal
9871
9872 #endif // GTEST_HAS_DEATH_TEST
9873
9874 } // namespace testing
9875 // Copyright 2008, Google Inc.
9876 // All rights reserved.
9877 //
9878 // Redistribution and use in source and binary forms, with or without
9879 // modification, are permitted provided that the following conditions are
9880 // met:
9881 //
9882 // * Redistributions of source code must retain the above copyright
9883 // notice, this list of conditions and the following disclaimer.
9884 // * Redistributions in binary form must reproduce the above
9885 // copyright notice, this list of conditions and the following disclaimer
9886 // in the documentation and/or other materials provided with the
9887 // distribution.
9888 // * Neither the name of Google Inc. nor the names of its
9889 // contributors may be used to endorse or promote products derived from
9890 // this software without specific prior written permission.
9891 //
9892 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9893 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9894 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9895 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9896 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9897 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9898 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9899 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9900 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9901 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9902 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9903
9904
9905 #include <stdlib.h>
9906
9907 #if GTEST_OS_WINDOWS_MOBILE
9908 # include <windows.h>
9909 #elif GTEST_OS_WINDOWS
9910 # include <direct.h>
9911 # include <io.h>
9912 #else
9913 # include <limits.h>
9914 # include <climits> // Some Linux distributions define PATH_MAX here.
9915 #endif // GTEST_OS_WINDOWS_MOBILE
9916
9917
9918 #if GTEST_OS_WINDOWS
9919 # define GTEST_PATH_MAX_ _MAX_PATH
9920 #elif defined(PATH_MAX)
9921 # define GTEST_PATH_MAX_ PATH_MAX
9922 #elif defined(_XOPEN_PATH_MAX)
9923 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
9924 #else
9925 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
9926 #endif // GTEST_OS_WINDOWS
9927
9928 namespace testing {
9929 namespace internal {
9930
9931 #if GTEST_OS_WINDOWS
9932 // On Windows, '\\' is the standard path separator, but many tools and the
9933 // Windows API also accept '/' as an alternate path separator. Unless otherwise
9934 // noted, a file path can contain either kind of path separators, or a mixture
9935 // of them.
9936 const char kPathSeparator = '\\';
9937 const char kAlternatePathSeparator = '/';
9938 const char kAlternatePathSeparatorString[] = "/";
9939 # if GTEST_OS_WINDOWS_MOBILE
9940 // Windows CE doesn't have a current directory. You should not use
9941 // the current directory in tests on Windows CE, but this at least
9942 // provides a reasonable fallback.
9943 const char kCurrentDirectoryString[] = "\\";
9944 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
9945 const DWORD kInvalidFileAttributes = 0xffffffff;
9946 # else
9947 const char kCurrentDirectoryString[] = ".\\";
9948 # endif // GTEST_OS_WINDOWS_MOBILE
9949 #else
9950 const char kPathSeparator = '/';
9951 const char kCurrentDirectoryString[] = "./";
9952 #endif // GTEST_OS_WINDOWS
9953
9954 // Returns whether the given character is a valid path separator.
9955 static bool IsPathSeparator(char c) {
9956 #if GTEST_HAS_ALT_PATH_SEP_
9957 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
9958 #else
9959 return c == kPathSeparator;
9960 #endif
9961 }
9962
9963 // Returns the current working directory, or "" if unsuccessful.
9964 FilePath FilePath::GetCurrentDir() {
9965 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
9966 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
9967 GTEST_OS_XTENSA
9968 // These platforms do not have a current directory, so we just return
9969 // something reasonable.
9970 return FilePath(kCurrentDirectoryString);
9971 #elif GTEST_OS_WINDOWS
9972 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9973 return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
9974 #else
9975 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9976 char* result = getcwd(cwd, sizeof(cwd));
9977 # if GTEST_OS_NACL
9978 // getcwd will likely fail in NaCl due to the sandbox, so return something
9979 // reasonable. The user may have provided a shim implementation for getcwd,
9980 // however, so fallback only when failure is detected.
9981 return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
9982 # endif // GTEST_OS_NACL
9983 return FilePath(result == nullptr ? "" : cwd);
9984 #endif // GTEST_OS_WINDOWS_MOBILE
9985 }
9986
9987 // Returns a copy of the FilePath with the case-insensitive extension removed.
9988 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
9989 // FilePath("dir/file"). If a case-insensitive extension is not
9990 // found, returns a copy of the original FilePath.
9991 FilePath FilePath::RemoveExtension(const char* extension) const {
9992 const std::string dot_extension = std::string(".") + extension;
9993 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9994 return FilePath(pathname_.substr(
9995 0, pathname_.length() - dot_extension.length()));
9996 }
9997 return *this;
9998 }
9999
10000 // Returns a pointer to the last occurrence of a valid path separator in
10001 // the FilePath. On Windows, for example, both '/' and '\' are valid path
10002 // separators. Returns NULL if no path separator was found.
10003 const char* FilePath::FindLastPathSeparator() const {
10004 const char* const last_sep = strrchr(c_str(), kPathSeparator);
10005 #if GTEST_HAS_ALT_PATH_SEP_
10006 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
10007 // Comparing two pointers of which only one is NULL is undefined.
10008 if (last_alt_sep != nullptr &&
10009 (last_sep == nullptr || last_alt_sep > last_sep)) {
10010 return last_alt_sep;
10011 }
10012 #endif
10013 return last_sep;
10014 }
10015
10016 // Returns a copy of the FilePath with the directory part removed.
10017 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
10018 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
10019 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
10020 // returns an empty FilePath ("").
10021 // On Windows platform, '\' is the path separator, otherwise it is '/'.
10022 FilePath FilePath::RemoveDirectoryName() const {
10023 const char* const last_sep = FindLastPathSeparator();
10024 return last_sep ? FilePath(last_sep + 1) : *this;
10025 }
10026
10027 // RemoveFileName returns the directory path with the filename removed.
10028 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
10029 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
10030 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
10031 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
10032 // On Windows platform, '\' is the path separator, otherwise it is '/'.
10033 FilePath FilePath::RemoveFileName() const {
10034 const char* const last_sep = FindLastPathSeparator();
10035 std::string dir;
10036 if (last_sep) {
10037 dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
10038 } else {
10039 dir = kCurrentDirectoryString;
10040 }
10041 return FilePath(dir);
10042 }
10043
10044 // Helper functions for naming files in a directory for xml output.
10045
10046 // Given directory = "dir", base_name = "test", number = 0,
10047 // extension = "xml", returns "dir/test.xml". If number is greater
10048 // than zero (e.g., 12), returns "dir/test_12.xml".
10049 // On Windows platform, uses \ as the separator rather than /.
10050 FilePath FilePath::MakeFileName(const FilePath& directory,
10051 const FilePath& base_name,
10052 int number,
10053 const char* extension) {
10054 std::string file;
10055 if (number == 0) {
10056 file = base_name.string() + "." + extension;
10057 } else {
10058 file = base_name.string() + "_" + StreamableToString(number)
10059 + "." + extension;
10060 }
10061 return ConcatPaths(directory, FilePath(file));
10062 }
10063
10064 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
10065 // On Windows, uses \ as the separator rather than /.
10066 FilePath FilePath::ConcatPaths(const FilePath& directory,
10067 const FilePath& relative_path) {
10068 if (directory.IsEmpty())
10069 return relative_path;
10070 const FilePath dir(directory.RemoveTrailingPathSeparator());
10071 return FilePath(dir.string() + kPathSeparator + relative_path.string());
10072 }
10073
10074 // Returns true if pathname describes something findable in the file-system,
10075 // either a file, directory, or whatever.
10076 bool FilePath::FileOrDirectoryExists() const {
10077 #if GTEST_OS_WINDOWS_MOBILE
10078 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
10079 const DWORD attributes = GetFileAttributes(unicode);
10080 delete [] unicode;
10081 return attributes != kInvalidFileAttributes;
10082 #else
10083 posix::StatStruct file_stat;
10084 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
10085 #endif // GTEST_OS_WINDOWS_MOBILE
10086 }
10087
10088 // Returns true if pathname describes a directory in the file-system
10089 // that exists.
10090 bool FilePath::DirectoryExists() const {
10091 bool result = false;
10092 #if GTEST_OS_WINDOWS
10093 // Don't strip off trailing separator if path is a root directory on
10094 // Windows (like "C:\\").
10095 const FilePath& path(IsRootDirectory() ? *this :
10096 RemoveTrailingPathSeparator());
10097 #else
10098 const FilePath& path(*this);
10099 #endif
10100
10101 #if GTEST_OS_WINDOWS_MOBILE
10102 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
10103 const DWORD attributes = GetFileAttributes(unicode);
10104 delete [] unicode;
10105 if ((attributes != kInvalidFileAttributes) &&
10106 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
10107 result = true;
10108 }
10109 #else
10110 posix::StatStruct file_stat;
10111 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
10112 posix::IsDir(file_stat);
10113 #endif // GTEST_OS_WINDOWS_MOBILE
10114
10115 return result;
10116 }
10117
10118 // Returns true if pathname describes a root directory. (Windows has one
10119 // root directory per disk drive.)
10120 bool FilePath::IsRootDirectory() const {
10121 #if GTEST_OS_WINDOWS
10122 return pathname_.length() == 3 && IsAbsolutePath();
10123 #else
10124 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
10125 #endif
10126 }
10127
10128 // Returns true if pathname describes an absolute path.
10129 bool FilePath::IsAbsolutePath() const {
10130 const char* const name = pathname_.c_str();
10131 #if GTEST_OS_WINDOWS
10132 return pathname_.length() >= 3 &&
10133 ((name[0] >= 'a' && name[0] <= 'z') ||
10134 (name[0] >= 'A' && name[0] <= 'Z')) &&
10135 name[1] == ':' &&
10136 IsPathSeparator(name[2]);
10137 #else
10138 return IsPathSeparator(name[0]);
10139 #endif
10140 }
10141
10142 // Returns a pathname for a file that does not currently exist. The pathname
10143 // will be directory/base_name.extension or
10144 // directory/base_name_<number>.extension if directory/base_name.extension
10145 // already exists. The number will be incremented until a pathname is found
10146 // that does not already exist.
10147 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
10148 // There could be a race condition if two or more processes are calling this
10149 // function at the same time -- they could both pick the same filename.
10150 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
10151 const FilePath& base_name,
10152 const char* extension) {
10153 FilePath full_pathname;
10154 int number = 0;
10155 do {
10156 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
10157 } while (full_pathname.FileOrDirectoryExists());
10158 return full_pathname;
10159 }
10160
10161 // Returns true if FilePath ends with a path separator, which indicates that
10162 // it is intended to represent a directory. Returns false otherwise.
10163 // This does NOT check that a directory (or file) actually exists.
10164 bool FilePath::IsDirectory() const {
10165 return !pathname_.empty() &&
10166 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
10167 }
10168
10169 // Create directories so that path exists. Returns true if successful or if
10170 // the directories already exist; returns false if unable to create directories
10171 // for any reason.
10172 bool FilePath::CreateDirectoriesRecursively() const {
10173 if (!this->IsDirectory()) {
10174 return false;
10175 }
10176
10177 if (pathname_.length() == 0 || this->DirectoryExists()) {
10178 return true;
10179 }
10180
10181 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
10182 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
10183 }
10184
10185 // Create the directory so that path exists. Returns true if successful or
10186 // if the directory already exists; returns false if unable to create the
10187 // directory for any reason, including if the parent directory does not
10188 // exist. Not named "CreateDirectory" because that's a macro on Windows.
10189 bool FilePath::CreateFolder() const {
10190 #if GTEST_OS_WINDOWS_MOBILE
10191 FilePath removed_sep(this->RemoveTrailingPathSeparator());
10192 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
10193 int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
10194 delete [] unicode;
10195 #elif GTEST_OS_WINDOWS
10196 int result = _mkdir(pathname_.c_str());
10197 #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
10198 // do nothing
10199 int result = 0;
10200 #else
10201 int result = mkdir(pathname_.c_str(), 0777);
10202 #endif // GTEST_OS_WINDOWS_MOBILE
10203
10204 if (result == -1) {
10205 return this->DirectoryExists(); // An error is OK if the directory exists.
10206 }
10207 return true; // No error.
10208 }
10209
10210 // If input name has a trailing separator character, remove it and return the
10211 // name, otherwise return the name string unmodified.
10212 // On Windows platform, uses \ as the separator, other platforms use /.
10213 FilePath FilePath::RemoveTrailingPathSeparator() const {
10214 return IsDirectory()
10215 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
10216 : *this;
10217 }
10218
10219 // Removes any redundant separators that might be in the pathname.
10220 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
10221 // redundancies that might be in a pathname involving "." or "..".
10222 void FilePath::Normalize() {
10223 auto out = pathname_.begin();
10224
10225 for (const char character : pathname_) {
10226 if (!IsPathSeparator(character)) {
10227 *(out++) = character;
10228 } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
10229 *(out++) = kPathSeparator;
10230 } else {
10231 continue;
10232 }
10233 }
10234
10235 pathname_.erase(out, pathname_.end());
10236 }
10237
10238 } // namespace internal
10239 } // namespace testing
10240 // Copyright 2007, Google Inc.
10241 // All rights reserved.
10242 //
10243 // Redistribution and use in source and binary forms, with or without
10244 // modification, are permitted provided that the following conditions are
10245 // met:
10246 //
10247 // * Redistributions of source code must retain the above copyright
10248 // notice, this list of conditions and the following disclaimer.
10249 // * Redistributions in binary form must reproduce the above
10250 // copyright notice, this list of conditions and the following disclaimer
10251 // in the documentation and/or other materials provided with the
10252 // distribution.
10253 // * Neither the name of Google Inc. nor the names of its
10254 // contributors may be used to endorse or promote products derived from
10255 // this software without specific prior written permission.
10256 //
10257 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10258 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10259 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10260 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10261 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10262 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10263 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10264 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10265 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10266 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10267 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10268
10269 // The Google C++ Testing and Mocking Framework (Google Test)
10270 //
10271 // This file implements just enough of the matcher interface to allow
10272 // EXPECT_DEATH and friends to accept a matcher argument.
10273
10274
10275 #include <string>
10276
10277 namespace testing {
10278
10279 // Constructs a matcher that matches a const std::string& whose value is
10280 // equal to s.
10281 Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
10282
10283 // Constructs a matcher that matches a const std::string& whose value is
10284 // equal to s.
10285 Matcher<const std::string&>::Matcher(const char* s) {
10286 *this = Eq(std::string(s));
10287 }
10288
10289 // Constructs a matcher that matches a std::string whose value is equal to
10290 // s.
10291 Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
10292
10293 // Constructs a matcher that matches a std::string whose value is equal to
10294 // s.
10295 Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
10296
10297 #if GTEST_INTERNAL_HAS_STRING_VIEW
10298 // Constructs a matcher that matches a const StringView& whose value is
10299 // equal to s.
10300 Matcher<const internal::StringView&>::Matcher(const std::string& s) {
10301 *this = Eq(s);
10302 }
10303
10304 // Constructs a matcher that matches a const StringView& whose value is
10305 // equal to s.
10306 Matcher<const internal::StringView&>::Matcher(const char* s) {
10307 *this = Eq(std::string(s));
10308 }
10309
10310 // Constructs a matcher that matches a const StringView& whose value is
10311 // equal to s.
10312 Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
10313 *this = Eq(std::string(s));
10314 }
10315
10316 // Constructs a matcher that matches a StringView whose value is equal to
10317 // s.
10318 Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
10319
10320 // Constructs a matcher that matches a StringView whose value is equal to
10321 // s.
10322 Matcher<internal::StringView>::Matcher(const char* s) {
10323 *this = Eq(std::string(s));
10324 }
10325
10326 // Constructs a matcher that matches a StringView whose value is equal to
10327 // s.
10328 Matcher<internal::StringView>::Matcher(internal::StringView s) {
10329 *this = Eq(std::string(s));
10330 }
10331 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
10332
10333 } // namespace testing
10334 // Copyright 2008, Google Inc.
10335 // All rights reserved.
10336 //
10337 // Redistribution and use in source and binary forms, with or without
10338 // modification, are permitted provided that the following conditions are
10339 // met:
10340 //
10341 // * Redistributions of source code must retain the above copyright
10342 // notice, this list of conditions and the following disclaimer.
10343 // * Redistributions in binary form must reproduce the above
10344 // copyright notice, this list of conditions and the following disclaimer
10345 // in the documentation and/or other materials provided with the
10346 // distribution.
10347 // * Neither the name of Google Inc. nor the names of its
10348 // contributors may be used to endorse or promote products derived from
10349 // this software without specific prior written permission.
10350 //
10351 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10352 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10353 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10354 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10355 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10356 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10357 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10358 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10359 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10360 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10361 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10362
10363
10364
10365 #include <limits.h>
10366 #include <stdio.h>
10367 #include <stdlib.h>
10368 #include <string.h>
10369 #include <cstdint>
10370 #include <fstream>
10371 #include <memory>
10372
10373 #if GTEST_OS_WINDOWS
10374 # include <windows.h>
10375 # include <io.h>
10376 # include <sys/stat.h>
10377 # include <map> // Used in ThreadLocal.
10378 # ifdef _MSC_VER
10379 # include <crtdbg.h>
10380 # endif // _MSC_VER
10381 #else
10382 # include <unistd.h>
10383 #endif // GTEST_OS_WINDOWS
10384
10385 #if GTEST_OS_MAC
10386 # include <mach/mach_init.h>
10387 # include <mach/task.h>
10388 # include <mach/vm_map.h>
10389 #endif // GTEST_OS_MAC
10390
10391 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
10392 GTEST_OS_NETBSD || GTEST_OS_OPENBSD
10393 # include <sys/sysctl.h>
10394 # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
10395 # include <sys/user.h>
10396 # endif
10397 #endif
10398
10399 #if GTEST_OS_QNX
10400 # include <devctl.h>
10401 # include <fcntl.h>
10402 # include <sys/procfs.h>
10403 #endif // GTEST_OS_QNX
10404
10405 #if GTEST_OS_AIX
10406 # include <procinfo.h>
10407 # include <sys/types.h>
10408 #endif // GTEST_OS_AIX
10409
10410 #if GTEST_OS_FUCHSIA
10411 # include <zircon/process.h>
10412 # include <zircon/syscalls.h>
10413 #endif // GTEST_OS_FUCHSIA
10414
10415
10416 namespace testing {
10417 namespace internal {
10418
10419 #if defined(_MSC_VER) || defined(__BORLANDC__)
10420 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
10421 const int kStdOutFileno = 1;
10422 const int kStdErrFileno = 2;
10423 #else
10424 const int kStdOutFileno = STDOUT_FILENO;
10425 const int kStdErrFileno = STDERR_FILENO;
10426 #endif // _MSC_VER
10427
10428 #if GTEST_OS_LINUX
10429
10430 namespace {
10431 template <typename T>
10432 T ReadProcFileField(const std::string& filename, int field) {
10433 std::string dummy;
10434 std::ifstream file(filename.c_str());
10435 while (field-- > 0) {
10436 file >> dummy;
10437 }
10438 T output = 0;
10439 file >> output;
10440 return output;
10441 }
10442 } // namespace
10443
10444 // Returns the number of active threads, or 0 when there is an error.
10445 size_t GetThreadCount() {
10446 const std::string filename =
10447 (Message() << "/proc/" << getpid() << "/stat").GetString();
10448 return ReadProcFileField<size_t>(filename, 19);
10449 }
10450
10451 #elif GTEST_OS_MAC
10452
10453 size_t GetThreadCount() {
10454 const task_t task = mach_task_self();
10455 mach_msg_type_number_t thread_count;
10456 thread_act_array_t thread_list;
10457 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
10458 if (status == KERN_SUCCESS) {
10459 // task_threads allocates resources in thread_list and we need to free them
10460 // to avoid leaks.
10461 vm_deallocate(task,
10462 reinterpret_cast<vm_address_t>(thread_list),
10463 sizeof(thread_t) * thread_count);
10464 return static_cast<size_t>(thread_count);
10465 } else {
10466 return 0;
10467 }
10468 }
10469
10470 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
10471 GTEST_OS_NETBSD
10472
10473 #if GTEST_OS_NETBSD
10474 #undef KERN_PROC
10475 #define KERN_PROC KERN_PROC2
10476 #define kinfo_proc kinfo_proc2
10477 #endif
10478
10479 #if GTEST_OS_DRAGONFLY
10480 #define KP_NLWP(kp) (kp.kp_nthreads)
10481 #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
10482 #define KP_NLWP(kp) (kp.ki_numthreads)
10483 #elif GTEST_OS_NETBSD
10484 #define KP_NLWP(kp) (kp.p_nlwps)
10485 #endif
10486
10487 // Returns the number of threads running in the process, or 0 to indicate that
10488 // we cannot detect it.
10489 size_t GetThreadCount() {
10490 int mib[] = {
10491 CTL_KERN,
10492 KERN_PROC,
10493 KERN_PROC_PID,
10494 getpid(),
10495 #if GTEST_OS_NETBSD
10496 sizeof(struct kinfo_proc),
10497 1,
10498 #endif
10499 };
10500 u_int miblen = sizeof(mib) / sizeof(mib[0]);
10501 struct kinfo_proc info;
10502 size_t size = sizeof(info);
10503 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
10504 return 0;
10505 }
10506 return static_cast<size_t>(KP_NLWP(info));
10507 }
10508 #elif GTEST_OS_OPENBSD
10509
10510 // Returns the number of threads running in the process, or 0 to indicate that
10511 // we cannot detect it.
10512 size_t GetThreadCount() {
10513 int mib[] = {
10514 CTL_KERN,
10515 KERN_PROC,
10516 KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
10517 getpid(),
10518 sizeof(struct kinfo_proc),
10519 0,
10520 };
10521 u_int miblen = sizeof(mib) / sizeof(mib[0]);
10522
10523 // get number of structs
10524 size_t size;
10525 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
10526 return 0;
10527 }
10528
10529 mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
10530
10531 // populate array of structs
10532 struct kinfo_proc info[mib[5]];
10533 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
10534 return 0;
10535 }
10536
10537 // exclude empty members
10538 size_t nthreads = 0;
10539 for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
10540 if (info[i].p_tid != -1)
10541 nthreads++;
10542 }
10543 return nthreads;
10544 }
10545
10546 #elif GTEST_OS_QNX
10547
10548 // Returns the number of threads running in the process, or 0 to indicate that
10549 // we cannot detect it.
10550 size_t GetThreadCount() {
10551 const int fd = open("/proc/self/as", O_RDONLY);
10552 if (fd < 0) {
10553 return 0;
10554 }
10555 procfs_info process_info;
10556 const int status =
10557 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
10558 close(fd);
10559 if (status == EOK) {
10560 return static_cast<size_t>(process_info.num_threads);
10561 } else {
10562 return 0;
10563 }
10564 }
10565
10566 #elif GTEST_OS_AIX
10567
10568 size_t GetThreadCount() {
10569 struct procentry64 entry;
10570 pid_t pid = getpid();
10571 int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
10572 if (status == 1) {
10573 return entry.pi_thcount;
10574 } else {
10575 return 0;
10576 }
10577 }
10578
10579 #elif GTEST_OS_FUCHSIA
10580
10581 size_t GetThreadCount() {
10582 int dummy_buffer;
10583 size_t avail;
10584 zx_status_t status = zx_object_get_info(
10585 zx_process_self(),
10586 ZX_INFO_PROCESS_THREADS,
10587 &dummy_buffer,
10588 0,
10589 nullptr,
10590 &avail);
10591 if (status == ZX_OK) {
10592 return avail;
10593 } else {
10594 return 0;
10595 }
10596 }
10597
10598 #else
10599
10600 size_t GetThreadCount() {
10601 // There's no portable way to detect the number of threads, so we just
10602 // return 0 to indicate that we cannot detect it.
10603 return 0;
10604 }
10605
10606 #endif // GTEST_OS_LINUX
10607
10608 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
10609
10610 void SleepMilliseconds(int n) {
10611 ::Sleep(static_cast<DWORD>(n));
10612 }
10613
10614 AutoHandle::AutoHandle()
10615 : handle_(INVALID_HANDLE_VALUE) {}
10616
10617 AutoHandle::AutoHandle(Handle handle)
10618 : handle_(handle) {}
10619
10620 AutoHandle::~AutoHandle() {
10621 Reset();
10622 }
10623
10624 AutoHandle::Handle AutoHandle::Get() const {
10625 return handle_;
10626 }
10627
10628 void AutoHandle::Reset() {
10629 Reset(INVALID_HANDLE_VALUE);
10630 }
10631
10632 void AutoHandle::Reset(HANDLE handle) {
10633 // Resetting with the same handle we already own is invalid.
10634 if (handle_ != handle) {
10635 if (IsCloseable()) {
10636 ::CloseHandle(handle_);
10637 }
10638 handle_ = handle;
10639 } else {
10640 GTEST_CHECK_(!IsCloseable())
10641 << "Resetting a valid handle to itself is likely a programmer error "
10642 "and thus not allowed.";
10643 }
10644 }
10645
10646 bool AutoHandle::IsCloseable() const {
10647 // Different Windows APIs may use either of these values to represent an
10648 // invalid handle.
10649 return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
10650 }
10651
10652 Notification::Notification()
10653 : event_(::CreateEvent(nullptr, // Default security attributes.
10654 TRUE, // Do not reset automatically.
10655 FALSE, // Initially unset.
10656 nullptr)) { // Anonymous event.
10657 GTEST_CHECK_(event_.Get() != nullptr);
10658 }
10659
10660 void Notification::Notify() {
10661 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
10662 }
10663
10664 void Notification::WaitForNotification() {
10665 GTEST_CHECK_(
10666 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
10667 }
10668
10669 Mutex::Mutex()
10670 : owner_thread_id_(0),
10671 type_(kDynamic),
10672 critical_section_init_phase_(0),
10673 critical_section_(new CRITICAL_SECTION) {
10674 ::InitializeCriticalSection(critical_section_);
10675 }
10676
10677 Mutex::~Mutex() {
10678 // Static mutexes are leaked intentionally. It is not thread-safe to try
10679 // to clean them up.
10680 if (type_ == kDynamic) {
10681 ::DeleteCriticalSection(critical_section_);
10682 delete critical_section_;
10683 critical_section_ = nullptr;
10684 }
10685 }
10686
10687 void Mutex::Lock() {
10688 ThreadSafeLazyInit();
10689 ::EnterCriticalSection(critical_section_);
10690 owner_thread_id_ = ::GetCurrentThreadId();
10691 }
10692
10693 void Mutex::Unlock() {
10694 ThreadSafeLazyInit();
10695 // We don't protect writing to owner_thread_id_ here, as it's the
10696 // caller's responsibility to ensure that the current thread holds the
10697 // mutex when this is called.
10698 owner_thread_id_ = 0;
10699 ::LeaveCriticalSection(critical_section_);
10700 }
10701
10702 // Does nothing if the current thread holds the mutex. Otherwise, crashes
10703 // with high probability.
10704 void Mutex::AssertHeld() {
10705 ThreadSafeLazyInit();
10706 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
10707 << "The current thread is not holding the mutex @" << this;
10708 }
10709
10710 namespace {
10711
10712 #ifdef _MSC_VER
10713 // Use the RAII idiom to flag mem allocs that are intentionally never
10714 // deallocated. The motivation is to silence the false positive mem leaks
10715 // that are reported by the debug version of MS's CRT which can only detect
10716 // if an alloc is missing a matching deallocation.
10717 // Example:
10718 // MemoryIsNotDeallocated memory_is_not_deallocated;
10719 // critical_section_ = new CRITICAL_SECTION;
10720 //
10721 class MemoryIsNotDeallocated
10722 {
10723 public:
10724 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
10725 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10726 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
10727 // doesn't report mem leak if there's no matching deallocation.
10728 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
10729 }
10730
10731 ~MemoryIsNotDeallocated() {
10732 // Restore the original _CRTDBG_ALLOC_MEM_DF flag
10733 _CrtSetDbgFlag(old_crtdbg_flag_);
10734 }
10735
10736 private:
10737 int old_crtdbg_flag_;
10738
10739 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
10740 };
10741 #endif // _MSC_VER
10742
10743 } // namespace
10744
10745 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
10746 void Mutex::ThreadSafeLazyInit() {
10747 // Dynamic mutexes are initialized in the constructor.
10748 if (type_ == kStatic) {
10749 switch (
10750 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
10751 case 0:
10752 // If critical_section_init_phase_ was 0 before the exchange, we
10753 // are the first to test it and need to perform the initialization.
10754 owner_thread_id_ = 0;
10755 {
10756 // Use RAII to flag that following mem alloc is never deallocated.
10757 #ifdef _MSC_VER
10758 MemoryIsNotDeallocated memory_is_not_deallocated;
10759 #endif // _MSC_VER
10760 critical_section_ = new CRITICAL_SECTION;
10761 }
10762 ::InitializeCriticalSection(critical_section_);
10763 // Updates the critical_section_init_phase_ to 2 to signal
10764 // initialization complete.
10765 GTEST_CHECK_(::InterlockedCompareExchange(
10766 &critical_section_init_phase_, 2L, 1L) ==
10767 1L);
10768 break;
10769 case 1:
10770 // Somebody else is already initializing the mutex; spin until they
10771 // are done.
10772 while (::InterlockedCompareExchange(&critical_section_init_phase_,
10773 2L,
10774 2L) != 2L) {
10775 // Possibly yields the rest of the thread's time slice to other
10776 // threads.
10777 ::Sleep(0);
10778 }
10779 break;
10780
10781 case 2:
10782 break; // The mutex is already initialized and ready for use.
10783
10784 default:
10785 GTEST_CHECK_(false)
10786 << "Unexpected value of critical_section_init_phase_ "
10787 << "while initializing a static mutex.";
10788 }
10789 }
10790 }
10791
10792 namespace {
10793
10794 class ThreadWithParamSupport : public ThreadWithParamBase {
10795 public:
10796 static HANDLE CreateThread(Runnable* runnable,
10797 Notification* thread_can_start) {
10798 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
10799 DWORD thread_id;
10800 HANDLE thread_handle = ::CreateThread(
10801 nullptr, // Default security.
10802 0, // Default stack size.
10803 &ThreadWithParamSupport::ThreadMain,
10804 param, // Parameter to ThreadMainStatic
10805 0x0, // Default creation flags.
10806 &thread_id); // Need a valid pointer for the call to work under Win98.
10807 GTEST_CHECK_(thread_handle != nullptr)
10808 << "CreateThread failed with error " << ::GetLastError() << ".";
10809 if (thread_handle == nullptr) {
10810 delete param;
10811 }
10812 return thread_handle;
10813 }
10814
10815 private:
10816 struct ThreadMainParam {
10817 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
10818 : runnable_(runnable),
10819 thread_can_start_(thread_can_start) {
10820 }
10821 std::unique_ptr<Runnable> runnable_;
10822 // Does not own.
10823 Notification* thread_can_start_;
10824 };
10825
10826 static DWORD WINAPI ThreadMain(void* ptr) {
10827 // Transfers ownership.
10828 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
10829 if (param->thread_can_start_ != nullptr)
10830 param->thread_can_start_->WaitForNotification();
10831 param->runnable_->Run();
10832 return 0;
10833 }
10834
10835 // Prohibit instantiation.
10836 ThreadWithParamSupport();
10837
10838 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
10839 };
10840
10841 } // namespace
10842
10843 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
10844 Notification* thread_can_start)
10845 : thread_(ThreadWithParamSupport::CreateThread(runnable,
10846 thread_can_start)) {
10847 }
10848
10849 ThreadWithParamBase::~ThreadWithParamBase() {
10850 Join();
10851 }
10852
10853 void ThreadWithParamBase::Join() {
10854 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
10855 << "Failed to join the thread with error " << ::GetLastError() << ".";
10856 }
10857
10858 // Maps a thread to a set of ThreadIdToThreadLocals that have values
10859 // instantiated on that thread and notifies them when the thread exits. A
10860 // ThreadLocal instance is expected to persist until all threads it has
10861 // values on have terminated.
10862 class ThreadLocalRegistryImpl {
10863 public:
10864 // Registers thread_local_instance as having value on the current thread.
10865 // Returns a value that can be used to identify the thread from other threads.
10866 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
10867 const ThreadLocalBase* thread_local_instance) {
10868 #ifdef _MSC_VER
10869 MemoryIsNotDeallocated memory_is_not_deallocated;
10870 #endif // _MSC_VER
10871 DWORD current_thread = ::GetCurrentThreadId();
10872 MutexLock lock(&mutex_);
10873 ThreadIdToThreadLocals* const thread_to_thread_locals =
10874 GetThreadLocalsMapLocked();
10875 ThreadIdToThreadLocals::iterator thread_local_pos =
10876 thread_to_thread_locals->find(current_thread);
10877 if (thread_local_pos == thread_to_thread_locals->end()) {
10878 thread_local_pos = thread_to_thread_locals->insert(
10879 std::make_pair(current_thread, ThreadLocalValues())).first;
10880 StartWatcherThreadFor(current_thread);
10881 }
10882 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10883 ThreadLocalValues::iterator value_pos =
10884 thread_local_values.find(thread_local_instance);
10885 if (value_pos == thread_local_values.end()) {
10886 value_pos =
10887 thread_local_values
10888 .insert(std::make_pair(
10889 thread_local_instance,
10890 std::shared_ptr<ThreadLocalValueHolderBase>(
10891 thread_local_instance->NewValueForCurrentThread())))
10892 .first;
10893 }
10894 return value_pos->second.get();
10895 }
10896
10897 static void OnThreadLocalDestroyed(
10898 const ThreadLocalBase* thread_local_instance) {
10899 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10900 // Clean up the ThreadLocalValues data structure while holding the lock, but
10901 // defer the destruction of the ThreadLocalValueHolderBases.
10902 {
10903 MutexLock lock(&mutex_);
10904 ThreadIdToThreadLocals* const thread_to_thread_locals =
10905 GetThreadLocalsMapLocked();
10906 for (ThreadIdToThreadLocals::iterator it =
10907 thread_to_thread_locals->begin();
10908 it != thread_to_thread_locals->end();
10909 ++it) {
10910 ThreadLocalValues& thread_local_values = it->second;
10911 ThreadLocalValues::iterator value_pos =
10912 thread_local_values.find(thread_local_instance);
10913 if (value_pos != thread_local_values.end()) {
10914 value_holders.push_back(value_pos->second);
10915 thread_local_values.erase(value_pos);
10916 // This 'if' can only be successful at most once, so theoretically we
10917 // could break out of the loop here, but we don't bother doing so.
10918 }
10919 }
10920 }
10921 // Outside the lock, let the destructor for 'value_holders' deallocate the
10922 // ThreadLocalValueHolderBases.
10923 }
10924
10925 static void OnThreadExit(DWORD thread_id) {
10926 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
10927 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10928 // Clean up the ThreadIdToThreadLocals data structure while holding the
10929 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
10930 {
10931 MutexLock lock(&mutex_);
10932 ThreadIdToThreadLocals* const thread_to_thread_locals =
10933 GetThreadLocalsMapLocked();
10934 ThreadIdToThreadLocals::iterator thread_local_pos =
10935 thread_to_thread_locals->find(thread_id);
10936 if (thread_local_pos != thread_to_thread_locals->end()) {
10937 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10938 for (ThreadLocalValues::iterator value_pos =
10939 thread_local_values.begin();
10940 value_pos != thread_local_values.end();
10941 ++value_pos) {
10942 value_holders.push_back(value_pos->second);
10943 }
10944 thread_to_thread_locals->erase(thread_local_pos);
10945 }
10946 }
10947 // Outside the lock, let the destructor for 'value_holders' deallocate the
10948 // ThreadLocalValueHolderBases.
10949 }
10950
10951 private:
10952 // In a particular thread, maps a ThreadLocal object to its value.
10953 typedef std::map<const ThreadLocalBase*,
10954 std::shared_ptr<ThreadLocalValueHolderBase> >
10955 ThreadLocalValues;
10956 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
10957 // thread's ID.
10958 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
10959
10960 // Holds the thread id and thread handle that we pass from
10961 // StartWatcherThreadFor to WatcherThreadFunc.
10962 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
10963
10964 static void StartWatcherThreadFor(DWORD thread_id) {
10965 // The returned handle will be kept in thread_map and closed by
10966 // watcher_thread in WatcherThreadFunc.
10967 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
10968 FALSE,
10969 thread_id);
10970 GTEST_CHECK_(thread != nullptr);
10971 // We need to pass a valid thread ID pointer into CreateThread for it
10972 // to work correctly under Win98.
10973 DWORD watcher_thread_id;
10974 HANDLE watcher_thread = ::CreateThread(
10975 nullptr, // Default security.
10976 0, // Default stack size
10977 &ThreadLocalRegistryImpl::WatcherThreadFunc,
10978 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
10979 CREATE_SUSPENDED, &watcher_thread_id);
10980 GTEST_CHECK_(watcher_thread != nullptr);
10981 // Give the watcher thread the same priority as ours to avoid being
10982 // blocked by it.
10983 ::SetThreadPriority(watcher_thread,
10984 ::GetThreadPriority(::GetCurrentThread()));
10985 ::ResumeThread(watcher_thread);
10986 ::CloseHandle(watcher_thread);
10987 }
10988
10989 // Monitors exit from a given thread and notifies those
10990 // ThreadIdToThreadLocals about thread termination.
10991 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
10992 const ThreadIdAndHandle* tah =
10993 reinterpret_cast<const ThreadIdAndHandle*>(param);
10994 GTEST_CHECK_(
10995 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
10996 OnThreadExit(tah->first);
10997 ::CloseHandle(tah->second);
10998 delete tah;
10999 return 0;
11000 }
11001
11002 // Returns map of thread local instances.
11003 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
11004 mutex_.AssertHeld();
11005 #ifdef _MSC_VER
11006 MemoryIsNotDeallocated memory_is_not_deallocated;
11007 #endif // _MSC_VER
11008 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
11009 return map;
11010 }
11011
11012 // Protects access to GetThreadLocalsMapLocked() and its return value.
11013 static Mutex mutex_;
11014 // Protects access to GetThreadMapLocked() and its return value.
11015 static Mutex thread_map_mutex_;
11016 };
11017
11018 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
11019 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
11020
11021 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
11022 const ThreadLocalBase* thread_local_instance) {
11023 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
11024 thread_local_instance);
11025 }
11026
11027 void ThreadLocalRegistry::OnThreadLocalDestroyed(
11028 const ThreadLocalBase* thread_local_instance) {
11029 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
11030 }
11031
11032 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
11033
11034 #if GTEST_USES_POSIX_RE
11035
11036 // Implements RE. Currently only needed for death tests.
11037
11038 RE::~RE() {
11039 if (is_valid_) {
11040 // regfree'ing an invalid regex might crash because the content
11041 // of the regex is undefined. Since the regex's are essentially
11042 // the same, one cannot be valid (or invalid) without the other
11043 // being so too.
11044 regfree(&partial_regex_);
11045 regfree(&full_regex_);
11046 }
11047 free(const_cast<char*>(pattern_));
11048 }
11049
11050 // Returns true if and only if regular expression re matches the entire str.
11051 bool RE::FullMatch(const char* str, const RE& re) {
11052 if (!re.is_valid_) return false;
11053
11054 regmatch_t match;
11055 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
11056 }
11057
11058 // Returns true if and only if regular expression re matches a substring of
11059 // str (including str itself).
11060 bool RE::PartialMatch(const char* str, const RE& re) {
11061 if (!re.is_valid_) return false;
11062
11063 regmatch_t match;
11064 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
11065 }
11066
11067 // Initializes an RE from its string representation.
11068 void RE::Init(const char* regex) {
11069 pattern_ = posix::StrDup(regex);
11070
11071 // Reserves enough bytes to hold the regular expression used for a
11072 // full match.
11073 const size_t full_regex_len = strlen(regex) + 10;
11074 char* const full_pattern = new char[full_regex_len];
11075
11076 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
11077 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
11078 // We want to call regcomp(&partial_regex_, ...) even if the
11079 // previous expression returns false. Otherwise partial_regex_ may
11080 // not be properly initialized can may cause trouble when it's
11081 // freed.
11082 //
11083 // Some implementation of POSIX regex (e.g. on at least some
11084 // versions of Cygwin) doesn't accept the empty string as a valid
11085 // regex. We change it to an equivalent form "()" to be safe.
11086 if (is_valid_) {
11087 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
11088 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
11089 }
11090 EXPECT_TRUE(is_valid_)
11091 << "Regular expression \"" << regex
11092 << "\" is not a valid POSIX Extended regular expression.";
11093
11094 delete[] full_pattern;
11095 }
11096
11097 #elif GTEST_USES_SIMPLE_RE
11098
11099 // Returns true if and only if ch appears anywhere in str (excluding the
11100 // terminating '\0' character).
11101 bool IsInSet(char ch, const char* str) {
11102 return ch != '\0' && strchr(str, ch) != nullptr;
11103 }
11104
11105 // Returns true if and only if ch belongs to the given classification.
11106 // Unlike similar functions in <ctype.h>, these aren't affected by the
11107 // current locale.
11108 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
11109 bool IsAsciiPunct(char ch) {
11110 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
11111 }
11112 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
11113 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
11114 bool IsAsciiWordChar(char ch) {
11115 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
11116 ('0' <= ch && ch <= '9') || ch == '_';
11117 }
11118
11119 // Returns true if and only if "\\c" is a supported escape sequence.
11120 bool IsValidEscape(char c) {
11121 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
11122 }
11123
11124 // Returns true if and only if the given atom (specified by escaped and
11125 // pattern) matches ch. The result is undefined if the atom is invalid.
11126 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
11127 if (escaped) { // "\\p" where p is pattern_char.
11128 switch (pattern_char) {
11129 case 'd': return IsAsciiDigit(ch);
11130 case 'D': return !IsAsciiDigit(ch);
11131 case 'f': return ch == '\f';
11132 case 'n': return ch == '\n';
11133 case 'r': return ch == '\r';
11134 case 's': return IsAsciiWhiteSpace(ch);
11135 case 'S': return !IsAsciiWhiteSpace(ch);
11136 case 't': return ch == '\t';
11137 case 'v': return ch == '\v';
11138 case 'w': return IsAsciiWordChar(ch);
11139 case 'W': return !IsAsciiWordChar(ch);
11140 }
11141 return IsAsciiPunct(pattern_char) && pattern_char == ch;
11142 }
11143
11144 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
11145 }
11146
11147 // Helper function used by ValidateRegex() to format error messages.
11148 static std::string FormatRegexSyntaxError(const char* regex, int index) {
11149 return (Message() << "Syntax error at index " << index
11150 << " in simple regular expression \"" << regex << "\": ").GetString();
11151 }
11152
11153 // Generates non-fatal failures and returns false if regex is invalid;
11154 // otherwise returns true.
11155 bool ValidateRegex(const char* regex) {
11156 if (regex == nullptr) {
11157 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
11158 return false;
11159 }
11160
11161 bool is_valid = true;
11162
11163 // True if and only if ?, *, or + can follow the previous atom.
11164 bool prev_repeatable = false;
11165 for (int i = 0; regex[i]; i++) {
11166 if (regex[i] == '\\') { // An escape sequence
11167 i++;
11168 if (regex[i] == '\0') {
11169 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
11170 << "'\\' cannot appear at the end.";
11171 return false;
11172 }
11173
11174 if (!IsValidEscape(regex[i])) {
11175 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
11176 << "invalid escape sequence \"\\" << regex[i] << "\".";
11177 is_valid = false;
11178 }
11179 prev_repeatable = true;
11180 } else { // Not an escape sequence.
11181 const char ch = regex[i];
11182
11183 if (ch == '^' && i > 0) {
11184 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11185 << "'^' can only appear at the beginning.";
11186 is_valid = false;
11187 } else if (ch == '$' && regex[i + 1] != '\0') {
11188 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11189 << "'$' can only appear at the end.";
11190 is_valid = false;
11191 } else if (IsInSet(ch, "()[]{}|")) {
11192 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11193 << "'" << ch << "' is unsupported.";
11194 is_valid = false;
11195 } else if (IsRepeat(ch) && !prev_repeatable) {
11196 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11197 << "'" << ch << "' can only follow a repeatable token.";
11198 is_valid = false;
11199 }
11200
11201 prev_repeatable = !IsInSet(ch, "^$?*+");
11202 }
11203 }
11204
11205 return is_valid;
11206 }
11207
11208 // Matches a repeated regex atom followed by a valid simple regular
11209 // expression. The regex atom is defined as c if escaped is false,
11210 // or \c otherwise. repeat is the repetition meta character (?, *,
11211 // or +). The behavior is undefined if str contains too many
11212 // characters to be indexable by size_t, in which case the test will
11213 // probably time out anyway. We are fine with this limitation as
11214 // std::string has it too.
11215 bool MatchRepetitionAndRegexAtHead(
11216 bool escaped, char c, char repeat, const char* regex,
11217 const char* str) {
11218 const size_t min_count = (repeat == '+') ? 1 : 0;
11219 const size_t max_count = (repeat == '?') ? 1 :
11220 static_cast<size_t>(-1) - 1;
11221 // We cannot call numeric_limits::max() as it conflicts with the
11222 // max() macro on Windows.
11223
11224 for (size_t i = 0; i <= max_count; ++i) {
11225 // We know that the atom matches each of the first i characters in str.
11226 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
11227 // We have enough matches at the head, and the tail matches too.
11228 // Since we only care about *whether* the pattern matches str
11229 // (as opposed to *how* it matches), there is no need to find a
11230 // greedy match.
11231 return true;
11232 }
11233 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
11234 return false;
11235 }
11236 return false;
11237 }
11238
11239 // Returns true if and only if regex matches a prefix of str. regex must
11240 // be a valid simple regular expression and not start with "^", or the
11241 // result is undefined.
11242 bool MatchRegexAtHead(const char* regex, const char* str) {
11243 if (*regex == '\0') // An empty regex matches a prefix of anything.
11244 return true;
11245
11246 // "$" only matches the end of a string. Note that regex being
11247 // valid guarantees that there's nothing after "$" in it.
11248 if (*regex == '$')
11249 return *str == '\0';
11250
11251 // Is the first thing in regex an escape sequence?
11252 const bool escaped = *regex == '\\';
11253 if (escaped)
11254 ++regex;
11255 if (IsRepeat(regex[1])) {
11256 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
11257 // here's an indirect recursion. It terminates as the regex gets
11258 // shorter in each recursion.
11259 return MatchRepetitionAndRegexAtHead(
11260 escaped, regex[0], regex[1], regex + 2, str);
11261 } else {
11262 // regex isn't empty, isn't "$", and doesn't start with a
11263 // repetition. We match the first atom of regex with the first
11264 // character of str and recurse.
11265 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
11266 MatchRegexAtHead(regex + 1, str + 1);
11267 }
11268 }
11269
11270 // Returns true if and only if regex matches any substring of str. regex must
11271 // be a valid simple regular expression, or the result is undefined.
11272 //
11273 // The algorithm is recursive, but the recursion depth doesn't exceed
11274 // the regex length, so we won't need to worry about running out of
11275 // stack space normally. In rare cases the time complexity can be
11276 // exponential with respect to the regex length + the string length,
11277 // but usually it's must faster (often close to linear).
11278 bool MatchRegexAnywhere(const char* regex, const char* str) {
11279 if (regex == nullptr || str == nullptr) return false;
11280
11281 if (*regex == '^')
11282 return MatchRegexAtHead(regex + 1, str);
11283
11284 // A successful match can be anywhere in str.
11285 do {
11286 if (MatchRegexAtHead(regex, str))
11287 return true;
11288 } while (*str++ != '\0');
11289 return false;
11290 }
11291
11292 // Implements the RE class.
11293
11294 RE::~RE() {
11295 free(const_cast<char*>(pattern_));
11296 free(const_cast<char*>(full_pattern_));
11297 }
11298
11299 // Returns true if and only if regular expression re matches the entire str.
11300 bool RE::FullMatch(const char* str, const RE& re) {
11301 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
11302 }
11303
11304 // Returns true if and only if regular expression re matches a substring of
11305 // str (including str itself).
11306 bool RE::PartialMatch(const char* str, const RE& re) {
11307 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
11308 }
11309
11310 // Initializes an RE from its string representation.
11311 void RE::Init(const char* regex) {
11312 pattern_ = full_pattern_ = nullptr;
11313 if (regex != nullptr) {
11314 pattern_ = posix::StrDup(regex);
11315 }
11316
11317 is_valid_ = ValidateRegex(regex);
11318 if (!is_valid_) {
11319 // No need to calculate the full pattern when the regex is invalid.
11320 return;
11321 }
11322
11323 const size_t len = strlen(regex);
11324 // Reserves enough bytes to hold the regular expression used for a
11325 // full match: we need space to prepend a '^', append a '$', and
11326 // terminate the string with '\0'.
11327 char* buffer = static_cast<char*>(malloc(len + 3));
11328 full_pattern_ = buffer;
11329
11330 if (*regex != '^')
11331 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
11332
11333 // We don't use snprintf or strncpy, as they trigger a warning when
11334 // compiled with VC++ 8.0.
11335 memcpy(buffer, regex, len);
11336 buffer += len;
11337
11338 if (len == 0 || regex[len - 1] != '$')
11339 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
11340
11341 *buffer = '\0';
11342 }
11343
11344 #endif // GTEST_USES_POSIX_RE
11345
11346 const char kUnknownFile[] = "unknown file";
11347
11348 // Formats a source file path and a line number as they would appear
11349 // in an error message from the compiler used to compile this code.
11350 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
11351 const std::string file_name(file == nullptr ? kUnknownFile : file);
11352
11353 if (line < 0) {
11354 return file_name + ":";
11355 }
11356 #ifdef _MSC_VER
11357 return file_name + "(" + StreamableToString(line) + "):";
11358 #else
11359 return file_name + ":" + StreamableToString(line) + ":";
11360 #endif // _MSC_VER
11361 }
11362
11363 // Formats a file location for compiler-independent XML output.
11364 // Although this function is not platform dependent, we put it next to
11365 // FormatFileLocation in order to contrast the two functions.
11366 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
11367 // to the file location it produces, unlike FormatFileLocation().
11368 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
11369 const char* file, int line) {
11370 const std::string file_name(file == nullptr ? kUnknownFile : file);
11371
11372 if (line < 0)
11373 return file_name;
11374 else
11375 return file_name + ":" + StreamableToString(line);
11376 }
11377
11378 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
11379 : severity_(severity) {
11380 const char* const marker =
11381 severity == GTEST_INFO ? "[ INFO ]" :
11382 severity == GTEST_WARNING ? "[WARNING]" :
11383 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
11384 GetStream() << ::std::endl << marker << " "
11385 << FormatFileLocation(file, line).c_str() << ": ";
11386 }
11387
11388 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
11389 GTestLog::~GTestLog() {
11390 GetStream() << ::std::endl;
11391 if (severity_ == GTEST_FATAL) {
11392 fflush(stderr);
11393 posix::Abort();
11394 }
11395 }
11396
11397 // Disable Microsoft deprecation warnings for POSIX functions called from
11398 // this class (creat, dup, dup2, and close)
11399 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
11400
11401 #if GTEST_HAS_STREAM_REDIRECTION
11402
11403 // Object that captures an output stream (stdout/stderr).
11404 class CapturedStream {
11405 public:
11406 // The ctor redirects the stream to a temporary file.
11407 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
11408 # if GTEST_OS_WINDOWS
11409 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
11410 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
11411
11412 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
11413 const UINT success = ::GetTempFileNameA(temp_dir_path,
11414 "gtest_redir",
11415 0, // Generate unique file name.
11416 temp_file_path);
11417 GTEST_CHECK_(success != 0)
11418 << "Unable to create a temporary file in " << temp_dir_path;
11419 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
11420 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
11421 << temp_file_path;
11422 filename_ = temp_file_path;
11423 # else
11424 // There's no guarantee that a test has write access to the current
11425 // directory, so we create the temporary file in the /tmp directory
11426 // instead. We use /tmp on most systems, and /sdcard on Android.
11427 // That's because Android doesn't have /tmp.
11428 # if GTEST_OS_LINUX_ANDROID
11429 // Note: Android applications are expected to call the framework's
11430 // Context.getExternalStorageDirectory() method through JNI to get
11431 // the location of the world-writable SD Card directory. However,
11432 // this requires a Context handle, which cannot be retrieved
11433 // globally from native code. Doing so also precludes running the
11434 // code as part of a regular standalone executable, which doesn't
11435 // run in a Dalvik process (e.g. when running it through 'adb shell').
11436 //
11437 // The location /data/local/tmp is directly accessible from native code.
11438 // '/sdcard' and other variants cannot be relied on, as they are not
11439 // guaranteed to be mounted, or may have a delay in mounting.
11440 char name_template[] = "/data/local/tmp/gtest_captured_stream.XXXXXX";
11441 # else
11442 char name_template[] = "/tmp/captured_stream.XXXXXX";
11443 # endif // GTEST_OS_LINUX_ANDROID
11444 const int captured_fd = mkstemp(name_template);
11445 if (captured_fd == -1) {
11446 GTEST_LOG_(WARNING)
11447 << "Failed to create tmp file " << name_template
11448 << " for test; does the test have access to the /tmp directory?";
11449 }
11450 filename_ = name_template;
11451 # endif // GTEST_OS_WINDOWS
11452 fflush(nullptr);
11453 dup2(captured_fd, fd_);
11454 close(captured_fd);
11455 }
11456
11457 ~CapturedStream() {
11458 remove(filename_.c_str());
11459 }
11460
11461 std::string GetCapturedString() {
11462 if (uncaptured_fd_ != -1) {
11463 // Restores the original stream.
11464 fflush(nullptr);
11465 dup2(uncaptured_fd_, fd_);
11466 close(uncaptured_fd_);
11467 uncaptured_fd_ = -1;
11468 }
11469
11470 FILE* const file = posix::FOpen(filename_.c_str(), "r");
11471 if (file == nullptr) {
11472 GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
11473 << " for capturing stream.";
11474 }
11475 const std::string content = ReadEntireFile(file);
11476 posix::FClose(file);
11477 return content;
11478 }
11479
11480 private:
11481 const int fd_; // A stream to capture.
11482 int uncaptured_fd_;
11483 // Name of the temporary file holding the stderr output.
11484 ::std::string filename_;
11485
11486 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
11487 };
11488
11489 GTEST_DISABLE_MSC_DEPRECATED_POP_()
11490
11491 static CapturedStream* g_captured_stderr = nullptr;
11492 static CapturedStream* g_captured_stdout = nullptr;
11493
11494 // Starts capturing an output stream (stdout/stderr).
11495 static void CaptureStream(int fd, const char* stream_name,
11496 CapturedStream** stream) {
11497 if (*stream != nullptr) {
11498 GTEST_LOG_(FATAL) << "Only one " << stream_name
11499 << " capturer can exist at a time.";
11500 }
11501 *stream = new CapturedStream(fd);
11502 }
11503
11504 // Stops capturing the output stream and returns the captured string.
11505 static std::string GetCapturedStream(CapturedStream** captured_stream) {
11506 const std::string content = (*captured_stream)->GetCapturedString();
11507
11508 delete *captured_stream;
11509 *captured_stream = nullptr;
11510
11511 return content;
11512 }
11513
11514 // Starts capturing stdout.
11515 void CaptureStdout() {
11516 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
11517 }
11518
11519 // Starts capturing stderr.
11520 void CaptureStderr() {
11521 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
11522 }
11523
11524 // Stops capturing stdout and returns the captured string.
11525 std::string GetCapturedStdout() {
11526 return GetCapturedStream(&g_captured_stdout);
11527 }
11528
11529 // Stops capturing stderr and returns the captured string.
11530 std::string GetCapturedStderr() {
11531 return GetCapturedStream(&g_captured_stderr);
11532 }
11533
11534 #endif // GTEST_HAS_STREAM_REDIRECTION
11535
11536
11537
11538
11539
11540 size_t GetFileSize(FILE* file) {
11541 fseek(file, 0, SEEK_END);
11542 return static_cast<size_t>(ftell(file));
11543 }
11544
11545 std::string ReadEntireFile(FILE* file) {
11546 const size_t file_size = GetFileSize(file);
11547 char* const buffer = new char[file_size];
11548
11549 size_t bytes_last_read = 0; // # of bytes read in the last fread()
11550 size_t bytes_read = 0; // # of bytes read so far
11551
11552 fseek(file, 0, SEEK_SET);
11553
11554 // Keeps reading the file until we cannot read further or the
11555 // pre-determined file size is reached.
11556 do {
11557 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
11558 bytes_read += bytes_last_read;
11559 } while (bytes_last_read > 0 && bytes_read < file_size);
11560
11561 const std::string content(buffer, bytes_read);
11562 delete[] buffer;
11563
11564 return content;
11565 }
11566
11567 #if GTEST_HAS_DEATH_TEST
11568 static const std::vector<std::string>* g_injected_test_argvs =
11569 nullptr; // Owned.
11570
11571 std::vector<std::string> GetInjectableArgvs() {
11572 if (g_injected_test_argvs != nullptr) {
11573 return *g_injected_test_argvs;
11574 }
11575 return GetArgvs();
11576 }
11577
11578 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
11579 if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
11580 g_injected_test_argvs = new_argvs;
11581 }
11582
11583 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
11584 SetInjectableArgvs(
11585 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
11586 }
11587
11588 void ClearInjectableArgvs() {
11589 delete g_injected_test_argvs;
11590 g_injected_test_argvs = nullptr;
11591 }
11592 #endif // GTEST_HAS_DEATH_TEST
11593
11594 #if GTEST_OS_WINDOWS_MOBILE
11595 namespace posix {
11596 void Abort() {
11597 DebugBreak();
11598 TerminateProcess(GetCurrentProcess(), 1);
11599 }
11600 } // namespace posix
11601 #endif // GTEST_OS_WINDOWS_MOBILE
11602
11603 // Returns the name of the environment variable corresponding to the
11604 // given flag. For example, FlagToEnvVar("foo") will return
11605 // "GTEST_FOO" in the open-source version.
11606 static std::string FlagToEnvVar(const char* flag) {
11607 const std::string full_flag =
11608 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
11609
11610 Message env_var;
11611 for (size_t i = 0; i != full_flag.length(); i++) {
11612 env_var << ToUpper(full_flag.c_str()[i]);
11613 }
11614
11615 return env_var.GetString();
11616 }
11617
11618 // Parses 'str' for a 32-bit signed integer. If successful, writes
11619 // the result to *value and returns true; otherwise leaves *value
11620 // unchanged and returns false.
11621 bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
11622 // Parses the environment variable as a decimal integer.
11623 char* end = nullptr;
11624 const long long_value = strtol(str, &end, 10); // NOLINT
11625
11626 // Has strtol() consumed all characters in the string?
11627 if (*end != '\0') {
11628 // No - an invalid character was encountered.
11629 Message msg;
11630 msg << "WARNING: " << src_text
11631 << " is expected to be a 32-bit integer, but actually"
11632 << " has value \"" << str << "\".\n";
11633 printf("%s", msg.GetString().c_str());
11634 fflush(stdout);
11635 return false;
11636 }
11637
11638 // Is the parsed value in the range of an int32_t?
11639 const auto result = static_cast<int32_t>(long_value);
11640 if (long_value == LONG_MAX || long_value == LONG_MIN ||
11641 // The parsed value overflows as a long. (strtol() returns
11642 // LONG_MAX or LONG_MIN when the input overflows.)
11643 result != long_value
11644 // The parsed value overflows as an int32_t.
11645 ) {
11646 Message msg;
11647 msg << "WARNING: " << src_text
11648 << " is expected to be a 32-bit integer, but actually"
11649 << " has value " << str << ", which overflows.\n";
11650 printf("%s", msg.GetString().c_str());
11651 fflush(stdout);
11652 return false;
11653 }
11654
11655 *value = result;
11656 return true;
11657 }
11658
11659 // Reads and returns the Boolean environment variable corresponding to
11660 // the given flag; if it's not set, returns default_value.
11661 //
11662 // The value is considered true if and only if it's not "0".
11663 bool BoolFromGTestEnv(const char* flag, bool default_value) {
11664 #if defined(GTEST_GET_BOOL_FROM_ENV_)
11665 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
11666 #else
11667 const std::string env_var = FlagToEnvVar(flag);
11668 const char* const string_value = posix::GetEnv(env_var.c_str());
11669 return string_value == nullptr ? default_value
11670 : strcmp(string_value, "0") != 0;
11671 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
11672 }
11673
11674 // Reads and returns a 32-bit integer stored in the environment
11675 // variable corresponding to the given flag; if it isn't set or
11676 // doesn't represent a valid 32-bit integer, returns default_value.
11677 int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
11678 #if defined(GTEST_GET_INT32_FROM_ENV_)
11679 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
11680 #else
11681 const std::string env_var = FlagToEnvVar(flag);
11682 const char* const string_value = posix::GetEnv(env_var.c_str());
11683 if (string_value == nullptr) {
11684 // The environment variable is not set.
11685 return default_value;
11686 }
11687
11688 int32_t result = default_value;
11689 if (!ParseInt32(Message() << "Environment variable " << env_var,
11690 string_value, &result)) {
11691 printf("The default value %s is used.\n",
11692 (Message() << default_value).GetString().c_str());
11693 fflush(stdout);
11694 return default_value;
11695 }
11696
11697 return result;
11698 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
11699 }
11700
11701 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
11702 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
11703 // system. The value of XML_OUTPUT_FILE is a filename without the
11704 // "xml:" prefix of GTEST_OUTPUT.
11705 // Note that this is meant to be called at the call site so it does
11706 // not check that the flag is 'output'
11707 // In essence this checks an env variable called XML_OUTPUT_FILE
11708 // and if it is set we prepend "xml:" to its value, if it not set we return ""
11709 std::string OutputFlagAlsoCheckEnvVar(){
11710 std::string default_value_for_output_flag = "";
11711 const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
11712 if (nullptr != xml_output_file_env) {
11713 default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
11714 }
11715 return default_value_for_output_flag;
11716 }
11717
11718 // Reads and returns the string environment variable corresponding to
11719 // the given flag; if it's not set, returns default_value.
11720 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
11721 #if defined(GTEST_GET_STRING_FROM_ENV_)
11722 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
11723 #else
11724 const std::string env_var = FlagToEnvVar(flag);
11725 const char* const value = posix::GetEnv(env_var.c_str());
11726 return value == nullptr ? default_value : value;
11727 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
11728 }
11729
11730 } // namespace internal
11731 } // namespace testing
11732 // Copyright 2007, Google Inc.
11733 // All rights reserved.
11734 //
11735 // Redistribution and use in source and binary forms, with or without
11736 // modification, are permitted provided that the following conditions are
11737 // met:
11738 //
11739 // * Redistributions of source code must retain the above copyright
11740 // notice, this list of conditions and the following disclaimer.
11741 // * Redistributions in binary form must reproduce the above
11742 // copyright notice, this list of conditions and the following disclaimer
11743 // in the documentation and/or other materials provided with the
11744 // distribution.
11745 // * Neither the name of Google Inc. nor the names of its
11746 // contributors may be used to endorse or promote products derived from
11747 // this software without specific prior written permission.
11748 //
11749 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11750 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11751 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11752 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11753 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11754 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11755 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11756 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11757 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11758 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11759 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11760
11761
11762 // Google Test - The Google C++ Testing and Mocking Framework
11763 //
11764 // This file implements a universal value printer that can print a
11765 // value of any type T:
11766 //
11767 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
11768 //
11769 // It uses the << operator when possible, and prints the bytes in the
11770 // object otherwise. A user can override its behavior for a class
11771 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
11772 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
11773 // defines Foo.
11774
11775
11776 #include <stdio.h>
11777
11778 #include <cctype>
11779 #include <cstdint>
11780 #include <cwchar>
11781 #include <ostream> // NOLINT
11782 #include <string>
11783 #include <type_traits>
11784
11785
11786 namespace testing {
11787
11788 namespace {
11789
11790 using ::std::ostream;
11791
11792 // Prints a segment of bytes in the given object.
11793 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11794 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11795 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
11796 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
11797 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
11798 size_t count, ostream* os) {
11799 char text[5] = "";
11800 for (size_t i = 0; i != count; i++) {
11801 const size_t j = start + i;
11802 if (i != 0) {
11803 // Organizes the bytes into groups of 2 for easy parsing by
11804 // human.
11805 if ((j % 2) == 0)
11806 *os << ' ';
11807 else
11808 *os << '-';
11809 }
11810 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
11811 *os << text;
11812 }
11813 }
11814
11815 // Prints the bytes in the given value to the given ostream.
11816 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
11817 ostream* os) {
11818 // Tells the user how big the object is.
11819 *os << count << "-byte object <";
11820
11821 const size_t kThreshold = 132;
11822 const size_t kChunkSize = 64;
11823 // If the object size is bigger than kThreshold, we'll have to omit
11824 // some details by printing only the first and the last kChunkSize
11825 // bytes.
11826 if (count < kThreshold) {
11827 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
11828 } else {
11829 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
11830 *os << " ... ";
11831 // Rounds up to 2-byte boundary.
11832 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
11833 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
11834 }
11835 *os << ">";
11836 }
11837
11838 // Helpers for widening a character to char32_t. Since the standard does not
11839 // specify if char / wchar_t is signed or unsigned, it is important to first
11840 // convert it to the unsigned type of the same width before widening it to
11841 // char32_t.
11842 template <typename CharType>
11843 char32_t ToChar32(CharType in) {
11844 return static_cast<char32_t>(
11845 static_cast<typename std::make_unsigned<CharType>::type>(in));
11846 }
11847
11848 } // namespace
11849
11850 namespace internal {
11851
11852 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
11853 // given object. The delegation simplifies the implementation, which
11854 // uses the << operator and thus is easier done outside of the
11855 // ::testing::internal namespace, which contains a << operator that
11856 // sometimes conflicts with the one in STL.
11857 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
11858 ostream* os) {
11859 PrintBytesInObjectToImpl(obj_bytes, count, os);
11860 }
11861
11862 // Depending on the value of a char (or wchar_t), we print it in one
11863 // of three formats:
11864 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
11865 // - as a hexadecimal escape sequence (e.g. '\x7F'), or
11866 // - as a special escape sequence (e.g. '\r', '\n').
11867 enum CharFormat {
11868 kAsIs,
11869 kHexEscape,
11870 kSpecialEscape
11871 };
11872
11873 // Returns true if c is a printable ASCII character. We test the
11874 // value of c directly instead of calling isprint(), which is buggy on
11875 // Windows Mobile.
11876 inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
11877
11878 // Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
11879 // character literal without the quotes, escaping it when necessary; returns how
11880 // c was formatted.
11881 template <typename Char>
11882 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
11883 const char32_t u_c = ToChar32(c);
11884 switch (u_c) {
11885 case L'\0':
11886 *os << "\\0";
11887 break;
11888 case L'\'':
11889 *os << "\\'";
11890 break;
11891 case L'\\':
11892 *os << "\\\\";
11893 break;
11894 case L'\a':
11895 *os << "\\a";
11896 break;
11897 case L'\b':
11898 *os << "\\b";
11899 break;
11900 case L'\f':
11901 *os << "\\f";
11902 break;
11903 case L'\n':
11904 *os << "\\n";
11905 break;
11906 case L'\r':
11907 *os << "\\r";
11908 break;
11909 case L'\t':
11910 *os << "\\t";
11911 break;
11912 case L'\v':
11913 *os << "\\v";
11914 break;
11915 default:
11916 if (IsPrintableAscii(u_c)) {
11917 *os << static_cast<char>(c);
11918 return kAsIs;
11919 } else {
11920 ostream::fmtflags flags = os->flags();
11921 *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
11922 os->flags(flags);
11923 return kHexEscape;
11924 }
11925 }
11926 return kSpecialEscape;
11927 }
11928
11929 // Prints a char32_t c as if it's part of a string literal, escaping it when
11930 // necessary; returns how c was formatted.
11931 static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
11932 switch (c) {
11933 case L'\'':
11934 *os << "'";
11935 return kAsIs;
11936 case L'"':
11937 *os << "\\\"";
11938 return kSpecialEscape;
11939 default:
11940 return PrintAsCharLiteralTo(c, os);
11941 }
11942 }
11943
11944 static const char* GetCharWidthPrefix(char) {
11945 return "";
11946 }
11947
11948 static const char* GetCharWidthPrefix(signed char) {
11949 return "";
11950 }
11951
11952 static const char* GetCharWidthPrefix(unsigned char) {
11953 return "";
11954 }
11955
11956 #ifdef __cpp_char8_t
11957 static const char* GetCharWidthPrefix(char8_t) {
11958 return "u8";
11959 }
11960 #endif
11961
11962 static const char* GetCharWidthPrefix(char16_t) {
11963 return "u";
11964 }
11965
11966 static const char* GetCharWidthPrefix(char32_t) {
11967 return "U";
11968 }
11969
11970 static const char* GetCharWidthPrefix(wchar_t) {
11971 return "L";
11972 }
11973
11974 // Prints a char c as if it's part of a string literal, escaping it when
11975 // necessary; returns how c was formatted.
11976 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
11977 return PrintAsStringLiteralTo(ToChar32(c), os);
11978 }
11979
11980 #ifdef __cpp_char8_t
11981 static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
11982 return PrintAsStringLiteralTo(ToChar32(c), os);
11983 }
11984 #endif
11985
11986 static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
11987 return PrintAsStringLiteralTo(ToChar32(c), os);
11988 }
11989
11990 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
11991 return PrintAsStringLiteralTo(ToChar32(c), os);
11992 }
11993
11994 // Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
11995 // and its code. '\0' is printed as "'\\0'", other unprintable characters are
11996 // also properly escaped using the standard C++ escape sequence.
11997 template <typename Char>
11998 void PrintCharAndCodeTo(Char c, ostream* os) {
11999 // First, print c as a literal in the most readable form we can find.
12000 *os << GetCharWidthPrefix(c) << "'";
12001 const CharFormat format = PrintAsCharLiteralTo(c, os);
12002 *os << "'";
12003
12004 // To aid user debugging, we also print c's code in decimal, unless
12005 // it's 0 (in which case c was printed as '\\0', making the code
12006 // obvious).
12007 if (c == 0)
12008 return;
12009 *os << " (" << static_cast<int>(c);
12010
12011 // For more convenience, we print c's code again in hexadecimal,
12012 // unless c was already printed in the form '\x##' or the code is in
12013 // [1, 9].
12014 if (format == kHexEscape || (1 <= c && c <= 9)) {
12015 // Do nothing.
12016 } else {
12017 *os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
12018 }
12019 *os << ")";
12020 }
12021
12022 void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
12023 void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
12024
12025 // Prints a wchar_t as a symbol if it is printable or as its internal
12026 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
12027 void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
12028
12029 // TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
12030 void PrintTo(char32_t c, ::std::ostream* os) {
12031 *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
12032 << static_cast<uint32_t>(c);
12033 }
12034
12035 // Prints the given array of characters to the ostream. CharType must be either
12036 // char, char8_t, char16_t, char32_t, or wchar_t.
12037 // The array starts at begin, the length is len, it may include '\0' characters
12038 // and may not be NUL-terminated.
12039 template <typename CharType>
12040 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
12041 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
12042 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
12043 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
12044 static CharFormat PrintCharsAsStringTo(
12045 const CharType* begin, size_t len, ostream* os) {
12046 const char* const quote_prefix = GetCharWidthPrefix(*begin);
12047 *os << quote_prefix << "\"";
12048 bool is_previous_hex = false;
12049 CharFormat print_format = kAsIs;
12050 for (size_t index = 0; index < len; ++index) {
12051 const CharType cur = begin[index];
12052 if (is_previous_hex && IsXDigit(cur)) {
12053 // Previous character is of '\x..' form and this character can be
12054 // interpreted as another hexadecimal digit in its number. Break string to
12055 // disambiguate.
12056 *os << "\" " << quote_prefix << "\"";
12057 }
12058 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
12059 // Remember if any characters required hex escaping.
12060 if (is_previous_hex) {
12061 print_format = kHexEscape;
12062 }
12063 }
12064 *os << "\"";
12065 return print_format;
12066 }
12067
12068 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
12069 // 'begin'. CharType must be either char or wchar_t.
12070 template <typename CharType>
12071 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
12072 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
12073 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
12074 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
12075 static void UniversalPrintCharArray(
12076 const CharType* begin, size_t len, ostream* os) {
12077 // The code
12078 // const char kFoo[] = "foo";
12079 // generates an array of 4, not 3, elements, with the last one being '\0'.
12080 //
12081 // Therefore when printing a char array, we don't print the last element if
12082 // it's '\0', such that the output matches the string literal as it's
12083 // written in the source code.
12084 if (len > 0 && begin[len - 1] == '\0') {
12085 PrintCharsAsStringTo(begin, len - 1, os);
12086 return;
12087 }
12088
12089 // If, however, the last element in the array is not '\0', e.g.
12090 // const char kFoo[] = { 'f', 'o', 'o' };
12091 // we must print the entire array. We also print a message to indicate
12092 // that the array is not NUL-terminated.
12093 PrintCharsAsStringTo(begin, len, os);
12094 *os << " (no terminating NUL)";
12095 }
12096
12097 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
12098 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
12099 UniversalPrintCharArray(begin, len, os);
12100 }
12101
12102 #ifdef __cpp_char8_t
12103 // Prints a (const) char8_t array of 'len' elements, starting at address
12104 // 'begin'.
12105 void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
12106 UniversalPrintCharArray(begin, len, os);
12107 }
12108 #endif
12109
12110 // Prints a (const) char16_t array of 'len' elements, starting at address
12111 // 'begin'.
12112 void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
12113 UniversalPrintCharArray(begin, len, os);
12114 }
12115
12116 // Prints a (const) char32_t array of 'len' elements, starting at address
12117 // 'begin'.
12118 void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
12119 UniversalPrintCharArray(begin, len, os);
12120 }
12121
12122 // Prints a (const) wchar_t array of 'len' elements, starting at address
12123 // 'begin'.
12124 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
12125 UniversalPrintCharArray(begin, len, os);
12126 }
12127
12128 namespace {
12129
12130 // Prints a null-terminated C-style string to the ostream.
12131 template <typename Char>
12132 void PrintCStringTo(const Char* s, ostream* os) {
12133 if (s == nullptr) {
12134 *os << "NULL";
12135 } else {
12136 *os << ImplicitCast_<const void*>(s) << " pointing to ";
12137 PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
12138 }
12139 }
12140
12141 } // anonymous namespace
12142
12143 void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
12144
12145 #ifdef __cpp_char8_t
12146 void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
12147 #endif
12148
12149 void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
12150
12151 void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
12152
12153 // MSVC compiler can be configured to define whar_t as a typedef
12154 // of unsigned short. Defining an overload for const wchar_t* in that case
12155 // would cause pointers to unsigned shorts be printed as wide strings,
12156 // possibly accessing more memory than intended and causing invalid
12157 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
12158 // wchar_t is implemented as a native type.
12159 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
12160 // Prints the given wide C string to the ostream.
12161 void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
12162 #endif // wchar_t is native
12163
12164 namespace {
12165
12166 bool ContainsUnprintableControlCodes(const char* str, size_t length) {
12167 const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
12168
12169 for (size_t i = 0; i < length; i++) {
12170 unsigned char ch = *s++;
12171 if (std::iscntrl(ch)) {
12172 switch (ch) {
12173 case '\t':
12174 case '\n':
12175 case '\r':
12176 break;
12177 default:
12178 return true;
12179 }
12180 }
12181 }
12182 return false;
12183 }
12184
12185 bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
12186
12187 bool IsValidUTF8(const char* str, size_t length) {
12188 const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
12189
12190 for (size_t i = 0; i < length;) {
12191 unsigned char lead = s[i++];
12192
12193 if (lead <= 0x7f) {
12194 continue; // single-byte character (ASCII) 0..7F
12195 }
12196 if (lead < 0xc2) {
12197 return false; // trail byte or non-shortest form
12198 } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
12199 ++i; // 2-byte character
12200 } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
12201 IsUTF8TrailByte(s[i]) &&
12202 IsUTF8TrailByte(s[i + 1]) &&
12203 // check for non-shortest form and surrogate
12204 (lead != 0xe0 || s[i] >= 0xa0) &&
12205 (lead != 0xed || s[i] < 0xa0)) {
12206 i += 2; // 3-byte character
12207 } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
12208 IsUTF8TrailByte(s[i]) &&
12209 IsUTF8TrailByte(s[i + 1]) &&
12210 IsUTF8TrailByte(s[i + 2]) &&
12211 // check for non-shortest form
12212 (lead != 0xf0 || s[i] >= 0x90) &&
12213 (lead != 0xf4 || s[i] < 0x90)) {
12214 i += 3; // 4-byte character
12215 } else {
12216 return false;
12217 }
12218 }
12219 return true;
12220 }
12221
12222 void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
12223 if (!ContainsUnprintableControlCodes(str, length) &&
12224 IsValidUTF8(str, length)) {
12225 *os << "\n As Text: \"" << str << "\"";
12226 }
12227 }
12228
12229 } // anonymous namespace
12230
12231 void PrintStringTo(const ::std::string& s, ostream* os) {
12232 if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
12233 if (GTEST_FLAG(print_utf8)) {
12234 ConditionalPrintAsText(s.data(), s.size(), os);
12235 }
12236 }
12237 }
12238
12239 #ifdef __cpp_char8_t
12240 void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
12241 PrintCharsAsStringTo(s.data(), s.size(), os);
12242 }
12243 #endif
12244
12245 void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
12246 PrintCharsAsStringTo(s.data(), s.size(), os);
12247 }
12248
12249 void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
12250 PrintCharsAsStringTo(s.data(), s.size(), os);
12251 }
12252
12253 #if GTEST_HAS_STD_WSTRING
12254 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
12255 PrintCharsAsStringTo(s.data(), s.size(), os);
12256 }
12257 #endif // GTEST_HAS_STD_WSTRING
12258
12259 } // namespace internal
12260
12261 } // namespace testing
12262 // Copyright 2008, Google Inc.
12263 // All rights reserved.
12264 //
12265 // Redistribution and use in source and binary forms, with or without
12266 // modification, are permitted provided that the following conditions are
12267 // met:
12268 //
12269 // * Redistributions of source code must retain the above copyright
12270 // notice, this list of conditions and the following disclaimer.
12271 // * Redistributions in binary form must reproduce the above
12272 // copyright notice, this list of conditions and the following disclaimer
12273 // in the documentation and/or other materials provided with the
12274 // distribution.
12275 // * Neither the name of Google Inc. nor the names of its
12276 // contributors may be used to endorse or promote products derived from
12277 // this software without specific prior written permission.
12278 //
12279 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12280 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12281 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12282 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12283 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12284 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12285 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12286 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12287 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12288 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12289 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12290
12291 //
12292 // The Google C++ Testing and Mocking Framework (Google Test)
12293
12294
12295
12296 namespace testing {
12297
12298 using internal::GetUnitTestImpl;
12299
12300 // Gets the summary of the failure message by omitting the stack trace
12301 // in it.
12302 std::string TestPartResult::ExtractSummary(const char* message) {
12303 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
12304 return stack_trace == nullptr ? message : std::string(message, stack_trace);
12305 }
12306
12307 // Prints a TestPartResult object.
12308 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
12309 return os << internal::FormatFileLocation(result.file_name(),
12310 result.line_number())
12311 << " "
12312 << (result.type() == TestPartResult::kSuccess
12313 ? "Success"
12314 : result.type() == TestPartResult::kSkip
12315 ? "Skipped"
12316 : result.type() == TestPartResult::kFatalFailure
12317 ? "Fatal failure"
12318 : "Non-fatal failure")
12319 << ":\n"
12320 << result.message() << std::endl;
12321 }
12322
12323 // Appends a TestPartResult to the array.
12324 void TestPartResultArray::Append(const TestPartResult& result) {
12325 array_.push_back(result);
12326 }
12327
12328 // Returns the TestPartResult at the given index (0-based).
12329 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
12330 if (index < 0 || index >= size()) {
12331 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
12332 internal::posix::Abort();
12333 }
12334
12335 return array_[static_cast<size_t>(index)];
12336 }
12337
12338 // Returns the number of TestPartResult objects in the array.
12339 int TestPartResultArray::size() const {
12340 return static_cast<int>(array_.size());
12341 }
12342
12343 namespace internal {
12344
12345 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
12346 : has_new_fatal_failure_(false),
12347 original_reporter_(GetUnitTestImpl()->
12348 GetTestPartResultReporterForCurrentThread()) {
12349 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
12350 }
12351
12352 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
12353 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
12354 original_reporter_);
12355 }
12356
12357 void HasNewFatalFailureHelper::ReportTestPartResult(
12358 const TestPartResult& result) {
12359 if (result.fatally_failed())
12360 has_new_fatal_failure_ = true;
12361 original_reporter_->ReportTestPartResult(result);
12362 }
12363
12364 } // namespace internal
12365
12366 } // namespace testing
12367 // Copyright 2008 Google Inc.
12368 // All Rights Reserved.
12369 //
12370 // Redistribution and use in source and binary forms, with or without
12371 // modification, are permitted provided that the following conditions are
12372 // met:
12373 //
12374 // * Redistributions of source code must retain the above copyright
12375 // notice, this list of conditions and the following disclaimer.
12376 // * Redistributions in binary form must reproduce the above
12377 // copyright notice, this list of conditions and the following disclaimer
12378 // in the documentation and/or other materials provided with the
12379 // distribution.
12380 // * Neither the name of Google Inc. nor the names of its
12381 // contributors may be used to endorse or promote products derived from
12382 // this software without specific prior written permission.
12383 //
12384 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12385 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12386 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12387 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12388 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12389 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12390 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12391 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12392 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12393 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12394 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12395
12396
12397
12398
12399 namespace testing {
12400 namespace internal {
12401
12402 // Skips to the first non-space char in str. Returns an empty string if str
12403 // contains only whitespace characters.
12404 static const char* SkipSpaces(const char* str) {
12405 while (IsSpace(*str))
12406 str++;
12407 return str;
12408 }
12409
12410 static std::vector<std::string> SplitIntoTestNames(const char* src) {
12411 std::vector<std::string> name_vec;
12412 src = SkipSpaces(src);
12413 for (; src != nullptr; src = SkipComma(src)) {
12414 name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
12415 }
12416 return name_vec;
12417 }
12418
12419 // Verifies that registered_tests match the test names in
12420 // registered_tests_; returns registered_tests if successful, or
12421 // aborts the program otherwise.
12422 const char* TypedTestSuitePState::VerifyRegisteredTestNames(
12423 const char* test_suite_name, const char* file, int line,
12424 const char* registered_tests) {
12425 RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));
12426
12427 typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
12428 registered_ = true;
12429
12430 std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
12431
12432 Message errors;
12433
12434 std::set<std::string> tests;
12435 for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
12436 name_it != name_vec.end(); ++name_it) {
12437 const std::string& name = *name_it;
12438 if (tests.count(name) != 0) {
12439 errors << "Test " << name << " is listed more than once.\n";
12440 continue;
12441 }
12442
12443 if (registered_tests_.count(name) != 0) {
12444 tests.insert(name);
12445 } else {
12446 errors << "No test named " << name
12447 << " can be found in this test suite.\n";
12448 }
12449 }
12450
12451 for (RegisteredTestIter it = registered_tests_.begin();
12452 it != registered_tests_.end();
12453 ++it) {
12454 if (tests.count(it->first) == 0) {
12455 errors << "You forgot to list test " << it->first << ".\n";
12456 }
12457 }
12458
12459 const std::string& errors_str = errors.GetString();
12460 if (errors_str != "") {
12461 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
12462 errors_str.c_str());
12463 fflush(stderr);
12464 posix::Abort();
12465 }
12466
12467 return registered_tests;
12468 }
12469
12470 } // namespace internal
12471 } // namespace testing
12472 // Copyright 2008, Google Inc.
12473 // All rights reserved.
12474 //
12475 // Redistribution and use in source and binary forms, with or without
12476 // modification, are permitted provided that the following conditions are
12477 // met:
12478 //
12479 // * Redistributions of source code must retain the above copyright
12480 // notice, this list of conditions and the following disclaimer.
12481 // * Redistributions in binary form must reproduce the above
12482 // copyright notice, this list of conditions and the following disclaimer
12483 // in the documentation and/or other materials provided with the
12484 // distribution.
12485 // * Neither the name of Google Inc. nor the names of its
12486 // contributors may be used to endorse or promote products derived from
12487 // this software without specific prior written permission.
12488 //
12489 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12490 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12491 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12492 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12493 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12494 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12495 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12496 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12497 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12498 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12499 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12500
12501 //
12502 // Google C++ Mocking Framework (Google Mock)
12503 //
12504 // This file #includes all Google Mock implementation .cc files. The
12505 // purpose is to allow a user to build Google Mock by compiling this
12506 // file alone.
12507
12508 // This line ensures that gmock.h can be compiled on its own, even
12509 // when it's fused.
12510 #include "gmock/gmock.h"
12511
12512 // The following lines pull in the real gmock *.cc files.
12513 // Copyright 2007, Google Inc.
12514 // All rights reserved.
12515 //
12516 // Redistribution and use in source and binary forms, with or without
12517 // modification, are permitted provided that the following conditions are
12518 // met:
12519 //
12520 // * Redistributions of source code must retain the above copyright
12521 // notice, this list of conditions and the following disclaimer.
12522 // * Redistributions in binary form must reproduce the above
12523 // copyright notice, this list of conditions and the following disclaimer
12524 // in the documentation and/or other materials provided with the
12525 // distribution.
12526 // * Neither the name of Google Inc. nor the names of its
12527 // contributors may be used to endorse or promote products derived from
12528 // this software without specific prior written permission.
12529 //
12530 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12531 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12532 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12533 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12534 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12535 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12536 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12537 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12538 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12539 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12540 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12541
12542
12543 // Google Mock - a framework for writing C++ mock classes.
12544 //
12545 // This file implements cardinalities.
12546
12547
12548 #include <limits.h>
12549 #include <ostream> // NOLINT
12550 #include <sstream>
12551 #include <string>
12552
12553 namespace testing {
12554
12555 namespace {
12556
12557 // Implements the Between(m, n) cardinality.
12558 class BetweenCardinalityImpl : public CardinalityInterface {
12559 public:
12560 BetweenCardinalityImpl(int min, int max)
12561 : min_(min >= 0 ? min : 0),
12562 max_(max >= min_ ? max : min_) {
12563 std::stringstream ss;
12564 if (min < 0) {
12565 ss << "The invocation lower bound must be >= 0, "
12566 << "but is actually " << min << ".";
12567 internal::Expect(false, __FILE__, __LINE__, ss.str());
12568 } else if (max < 0) {
12569 ss << "The invocation upper bound must be >= 0, "
12570 << "but is actually " << max << ".";
12571 internal::Expect(false, __FILE__, __LINE__, ss.str());
12572 } else if (min > max) {
12573 ss << "The invocation upper bound (" << max
12574 << ") must be >= the invocation lower bound (" << min
12575 << ").";
12576 internal::Expect(false, __FILE__, __LINE__, ss.str());
12577 }
12578 }
12579
12580 // Conservative estimate on the lower/upper bound of the number of
12581 // calls allowed.
12582 int ConservativeLowerBound() const override { return min_; }
12583 int ConservativeUpperBound() const override { return max_; }
12584
12585 bool IsSatisfiedByCallCount(int call_count) const override {
12586 return min_ <= call_count && call_count <= max_;
12587 }
12588
12589 bool IsSaturatedByCallCount(int call_count) const override {
12590 return call_count >= max_;
12591 }
12592
12593 void DescribeTo(::std::ostream* os) const override;
12594
12595 private:
12596 const int min_;
12597 const int max_;
12598
12599 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
12600 };
12601
12602 // Formats "n times" in a human-friendly way.
12603 inline std::string FormatTimes(int n) {
12604 if (n == 1) {
12605 return "once";
12606 } else if (n == 2) {
12607 return "twice";
12608 } else {
12609 std::stringstream ss;
12610 ss << n << " times";
12611 return ss.str();
12612 }
12613 }
12614
12615 // Describes the Between(m, n) cardinality in human-friendly text.
12616 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
12617 if (min_ == 0) {
12618 if (max_ == 0) {
12619 *os << "never called";
12620 } else if (max_ == INT_MAX) {
12621 *os << "called any number of times";
12622 } else {
12623 *os << "called at most " << FormatTimes(max_);
12624 }
12625 } else if (min_ == max_) {
12626 *os << "called " << FormatTimes(min_);
12627 } else if (max_ == INT_MAX) {
12628 *os << "called at least " << FormatTimes(min_);
12629 } else {
12630 // 0 < min_ < max_ < INT_MAX
12631 *os << "called between " << min_ << " and " << max_ << " times";
12632 }
12633 }
12634
12635 } // Unnamed namespace
12636
12637 // Describes the given call count to an ostream.
12638 void Cardinality::DescribeActualCallCountTo(int actual_call_count,
12639 ::std::ostream* os) {
12640 if (actual_call_count > 0) {
12641 *os << "called " << FormatTimes(actual_call_count);
12642 } else {
12643 *os << "never called";
12644 }
12645 }
12646
12647 // Creates a cardinality that allows at least n calls.
12648 GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
12649
12650 // Creates a cardinality that allows at most n calls.
12651 GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
12652
12653 // Creates a cardinality that allows any number of calls.
12654 GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
12655
12656 // Creates a cardinality that allows between min and max calls.
12657 GTEST_API_ Cardinality Between(int min, int max) {
12658 return Cardinality(new BetweenCardinalityImpl(min, max));
12659 }
12660
12661 // Creates a cardinality that allows exactly n calls.
12662 GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
12663
12664 } // namespace testing
12665 // Copyright 2007, Google Inc.
12666 // All rights reserved.
12667 //
12668 // Redistribution and use in source and binary forms, with or without
12669 // modification, are permitted provided that the following conditions are
12670 // met:
12671 //
12672 // * Redistributions of source code must retain the above copyright
12673 // notice, this list of conditions and the following disclaimer.
12674 // * Redistributions in binary form must reproduce the above
12675 // copyright notice, this list of conditions and the following disclaimer
12676 // in the documentation and/or other materials provided with the
12677 // distribution.
12678 // * Neither the name of Google Inc. nor the names of its
12679 // contributors may be used to endorse or promote products derived from
12680 // this software without specific prior written permission.
12681 //
12682 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12683 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12684 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12685 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12686 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12687 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12688 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12689 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12690 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12691 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12692 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12693
12694
12695 // Google Mock - a framework for writing C++ mock classes.
12696 //
12697 // This file defines some utilities useful for implementing Google
12698 // Mock. They are subject to change without notice, so please DO NOT
12699 // USE THEM IN USER CODE.
12700
12701
12702 #include <ctype.h>
12703 #include <ostream> // NOLINT
12704 #include <string>
12705
12706 namespace testing {
12707 namespace internal {
12708
12709 // Joins a vector of strings as if they are fields of a tuple; returns
12710 // the joined string.
12711 GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
12712 switch (fields.size()) {
12713 case 0:
12714 return "";
12715 case 1:
12716 return fields[0];
12717 default:
12718 std::string result = "(" + fields[0];
12719 for (size_t i = 1; i < fields.size(); i++) {
12720 result += ", ";
12721 result += fields[i];
12722 }
12723 result += ")";
12724 return result;
12725 }
12726 }
12727
12728 // Converts an identifier name to a space-separated list of lower-case
12729 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
12730 // treated as one word. For example, both "FooBar123" and
12731 // "foo_bar_123" are converted to "foo bar 123".
12732 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
12733 std::string result;
12734 char prev_char = '\0';
12735 for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
12736 // We don't care about the current locale as the input is
12737 // guaranteed to be a valid C++ identifier name.
12738 const bool starts_new_word = IsUpper(*p) ||
12739 (!IsAlpha(prev_char) && IsLower(*p)) ||
12740 (!IsDigit(prev_char) && IsDigit(*p));
12741
12742 if (IsAlNum(*p)) {
12743 if (starts_new_word && result != "")
12744 result += ' ';
12745 result += ToLower(*p);
12746 }
12747 }
12748 return result;
12749 }
12750
12751 // This class reports Google Mock failures as Google Test failures. A
12752 // user can define another class in a similar fashion if they intend to
12753 // use Google Mock with a testing framework other than Google Test.
12754 class GoogleTestFailureReporter : public FailureReporterInterface {
12755 public:
12756 void ReportFailure(FailureType type, const char* file, int line,
12757 const std::string& message) override {
12758 AssertHelper(type == kFatal ?
12759 TestPartResult::kFatalFailure :
12760 TestPartResult::kNonFatalFailure,
12761 file,
12762 line,
12763 message.c_str()) = Message();
12764 if (type == kFatal) {
12765 posix::Abort();
12766 }
12767 }
12768 };
12769
12770 // Returns the global failure reporter. Will create a
12771 // GoogleTestFailureReporter and return it the first time called.
12772 GTEST_API_ FailureReporterInterface* GetFailureReporter() {
12773 // Points to the global failure reporter used by Google Mock. gcc
12774 // guarantees that the following use of failure_reporter is
12775 // thread-safe. We may need to add additional synchronization to
12776 // protect failure_reporter if we port Google Mock to other
12777 // compilers.
12778 static FailureReporterInterface* const failure_reporter =
12779 new GoogleTestFailureReporter();
12780 return failure_reporter;
12781 }
12782
12783 // Protects global resources (stdout in particular) used by Log().
12784 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
12785
12786 // Returns true if and only if a log with the given severity is visible
12787 // according to the --gmock_verbose flag.
12788 GTEST_API_ bool LogIsVisible(LogSeverity severity) {
12789 if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
12790 // Always show the log if --gmock_verbose=info.
12791 return true;
12792 } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
12793 // Always hide it if --gmock_verbose=error.
12794 return false;
12795 } else {
12796 // If --gmock_verbose is neither "info" nor "error", we treat it
12797 // as "warning" (its default value).
12798 return severity == kWarning;
12799 }
12800 }
12801
12802 // Prints the given message to stdout if and only if 'severity' >= the level
12803 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
12804 // 0, also prints the stack trace excluding the top
12805 // stack_frames_to_skip frames. In opt mode, any positive
12806 // stack_frames_to_skip is treated as 0, since we don't know which
12807 // function calls will be inlined by the compiler and need to be
12808 // conservative.
12809 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
12810 int stack_frames_to_skip) {
12811 if (!LogIsVisible(severity))
12812 return;
12813
12814 // Ensures that logs from different threads don't interleave.
12815 MutexLock l(&g_log_mutex);
12816
12817 if (severity == kWarning) {
12818 // Prints a GMOCK WARNING marker to make the warnings easily searchable.
12819 std::cout << "\nGMOCK WARNING:";
12820 }
12821 // Pre-pends a new-line to message if it doesn't start with one.
12822 if (message.empty() || message[0] != '\n') {
12823 std::cout << "\n";
12824 }
12825 std::cout << message;
12826 if (stack_frames_to_skip >= 0) {
12827 #ifdef NDEBUG
12828 // In opt mode, we have to be conservative and skip no stack frame.
12829 const int actual_to_skip = 0;
12830 #else
12831 // In dbg mode, we can do what the caller tell us to do (plus one
12832 // for skipping this function's stack frame).
12833 const int actual_to_skip = stack_frames_to_skip + 1;
12834 #endif // NDEBUG
12835
12836 // Appends a new-line to message if it doesn't end with one.
12837 if (!message.empty() && *message.rbegin() != '\n') {
12838 std::cout << "\n";
12839 }
12840 std::cout << "Stack trace:\n"
12841 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
12842 ::testing::UnitTest::GetInstance(), actual_to_skip);
12843 }
12844 std::cout << ::std::flush;
12845 }
12846
12847 GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
12848
12849 GTEST_API_ void IllegalDoDefault(const char* file, int line) {
12850 internal::Assert(
12851 false, file, line,
12852 "You are using DoDefault() inside a composite action like "
12853 "DoAll() or WithArgs(). This is not supported for technical "
12854 "reasons. Please instead spell out the default action, or "
12855 "assign the default action to an Action variable and use "
12856 "the variable in various places.");
12857 }
12858
12859 } // namespace internal
12860 } // namespace testing
12861 // Copyright 2007, Google Inc.
12862 // All rights reserved.
12863 //
12864 // Redistribution and use in source and binary forms, with or without
12865 // modification, are permitted provided that the following conditions are
12866 // met:
12867 //
12868 // * Redistributions of source code must retain the above copyright
12869 // notice, this list of conditions and the following disclaimer.
12870 // * Redistributions in binary form must reproduce the above
12871 // copyright notice, this list of conditions and the following disclaimer
12872 // in the documentation and/or other materials provided with the
12873 // distribution.
12874 // * Neither the name of Google Inc. nor the names of its
12875 // contributors may be used to endorse or promote products derived from
12876 // this software without specific prior written permission.
12877 //
12878 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12879 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12880 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12881 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12882 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12883 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12884 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12885 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12886 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12887 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12888 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12889
12890
12891 // Google Mock - a framework for writing C++ mock classes.
12892 //
12893 // This file implements Matcher<const string&>, Matcher<string>, and
12894 // utilities for defining matchers.
12895
12896
12897 #include <string.h>
12898 #include <iostream>
12899 #include <sstream>
12900 #include <string>
12901
12902 namespace testing {
12903 namespace internal {
12904
12905 // Returns the description for a matcher defined using the MATCHER*()
12906 // macro where the user-supplied description string is "", if
12907 // 'negation' is false; otherwise returns the description of the
12908 // negation of the matcher. 'param_values' contains a list of strings
12909 // that are the print-out of the matcher's parameters.
12910 GTEST_API_ std::string FormatMatcherDescription(bool negation,
12911 const char* matcher_name,
12912 const Strings& param_values) {
12913 std::string result = ConvertIdentifierNameToWords(matcher_name);
12914 if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
12915 return negation ? "not (" + result + ")" : result;
12916 }
12917
12918 // FindMaxBipartiteMatching and its helper class.
12919 //
12920 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
12921 // bipartite matching. Flow is considered to be from left to right.
12922 // There is an implicit source node that is connected to all of the left
12923 // nodes, and an implicit sink node that is connected to all of the
12924 // right nodes. All edges have unit capacity.
12925 //
12926 // Neither the flow graph nor the residual flow graph are represented
12927 // explicitly. Instead, they are implied by the information in 'graph' and
12928 // a vector<int> called 'left_' whose elements are initialized to the
12929 // value kUnused. This represents the initial state of the algorithm,
12930 // where the flow graph is empty, and the residual flow graph has the
12931 // following edges:
12932 // - An edge from source to each left_ node
12933 // - An edge from each right_ node to sink
12934 // - An edge from each left_ node to each right_ node, if the
12935 // corresponding edge exists in 'graph'.
12936 //
12937 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
12938 // nodes l and r. This induces the following changes:
12939 // - The edges (source, l), (l, r), and (r, sink) are added to the
12940 // flow graph.
12941 // - The same three edges are removed from the residual flow graph.
12942 // - The reverse edges (l, source), (r, l), and (sink, r) are added
12943 // to the residual flow graph, which is a directional graph
12944 // representing unused flow capacity.
12945 //
12946 // When the method augments a flow (moving left_[l] from some r1 to some
12947 // other r2), this can be thought of as "undoing" the above steps with
12948 // respect to r1 and "redoing" them with respect to r2.
12949 //
12950 // It bears repeating that the flow graph and residual flow graph are
12951 // never represented explicitly, but can be derived by looking at the
12952 // information in 'graph' and in left_.
12953 //
12954 // As an optimization, there is a second vector<int> called right_ which
12955 // does not provide any new information. Instead, it enables more
12956 // efficient queries about edges entering or leaving the right-side nodes
12957 // of the flow or residual flow graphs. The following invariants are
12958 // maintained:
12959 //
12960 // left[l] == kUnused or right[left[l]] == l
12961 // right[r] == kUnused or left[right[r]] == r
12962 //
12963 // . [ source ] .
12964 // . ||| .
12965 // . ||| .
12966 // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
12967 // . || | | .
12968 // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
12969 // . | || .
12970 // . \----> left[2]=2 ------> right[2]=2 --\|| .
12971 // . ||| .
12972 // . elements matchers vvv .
12973 // . [ sink ] .
12974 //
12975 // See Also:
12976 // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
12977 // "Introduction to Algorithms (Second ed.)", pp. 651-664.
12978 // [2] "Ford-Fulkerson algorithm", Wikipedia,
12979 // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
12980 class MaxBipartiteMatchState {
12981 public:
12982 explicit MaxBipartiteMatchState(const MatchMatrix& graph)
12983 : graph_(&graph),
12984 left_(graph_->LhsSize(), kUnused),
12985 right_(graph_->RhsSize(), kUnused) {}
12986
12987 // Returns the edges of a maximal match, each in the form {left, right}.
12988 ElementMatcherPairs Compute() {
12989 // 'seen' is used for path finding { 0: unseen, 1: seen }.
12990 ::std::vector<char> seen;
12991 // Searches the residual flow graph for a path from each left node to
12992 // the sink in the residual flow graph, and if one is found, add flow
12993 // to the graph. It's okay to search through the left nodes once. The
12994 // edge from the implicit source node to each previously-visited left
12995 // node will have flow if that left node has any path to the sink
12996 // whatsoever. Subsequent augmentations can only add flow to the
12997 // network, and cannot take away that previous flow unit from the source.
12998 // Since the source-to-left edge can only carry one flow unit (or,
12999 // each element can be matched to only one matcher), there is no need
13000 // to visit the left nodes more than once looking for augmented paths.
13001 // The flow is known to be possible or impossible by looking at the
13002 // node once.
13003 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
13004 // Reset the path-marking vector and try to find a path from
13005 // source to sink starting at the left_[ilhs] node.
13006 GTEST_CHECK_(left_[ilhs] == kUnused)
13007 << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
13008 // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
13009 seen.assign(graph_->RhsSize(), 0);
13010 TryAugment(ilhs, &seen);
13011 }
13012 ElementMatcherPairs result;
13013 for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
13014 size_t irhs = left_[ilhs];
13015 if (irhs == kUnused) continue;
13016 result.push_back(ElementMatcherPair(ilhs, irhs));
13017 }
13018 return result;
13019 }
13020
13021 private:
13022 static const size_t kUnused = static_cast<size_t>(-1);
13023
13024 // Perform a depth-first search from left node ilhs to the sink. If a
13025 // path is found, flow is added to the network by linking the left and
13026 // right vector elements corresponding each segment of the path.
13027 // Returns true if a path to sink was found, which means that a unit of
13028 // flow was added to the network. The 'seen' vector elements correspond
13029 // to right nodes and are marked to eliminate cycles from the search.
13030 //
13031 // Left nodes will only be explored at most once because they
13032 // are accessible from at most one right node in the residual flow
13033 // graph.
13034 //
13035 // Note that left_[ilhs] is the only element of left_ that TryAugment will
13036 // potentially transition from kUnused to another value. Any other
13037 // left_ element holding kUnused before TryAugment will be holding it
13038 // when TryAugment returns.
13039 //
13040 bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
13041 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
13042 if ((*seen)[irhs]) continue;
13043 if (!graph_->HasEdge(ilhs, irhs)) continue;
13044 // There's an available edge from ilhs to irhs.
13045 (*seen)[irhs] = 1;
13046 // Next a search is performed to determine whether
13047 // this edge is a dead end or leads to the sink.
13048 //
13049 // right_[irhs] == kUnused means that there is residual flow from
13050 // right node irhs to the sink, so we can use that to finish this
13051 // flow path and return success.
13052 //
13053 // Otherwise there is residual flow to some ilhs. We push flow
13054 // along that path and call ourselves recursively to see if this
13055 // ultimately leads to sink.
13056 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
13057 // Add flow from left_[ilhs] to right_[irhs].
13058 left_[ilhs] = irhs;
13059 right_[irhs] = ilhs;
13060 return true;
13061 }
13062 }
13063 return false;
13064 }
13065
13066 const MatchMatrix* graph_; // not owned
13067 // Each element of the left_ vector represents a left hand side node
13068 // (i.e. an element) and each element of right_ is a right hand side
13069 // node (i.e. a matcher). The values in the left_ vector indicate
13070 // outflow from that node to a node on the right_ side. The values
13071 // in the right_ indicate inflow, and specify which left_ node is
13072 // feeding that right_ node, if any. For example, left_[3] == 1 means
13073 // there's a flow from element #3 to matcher #1. Such a flow would also
13074 // be redundantly represented in the right_ vector as right_[1] == 3.
13075 // Elements of left_ and right_ are either kUnused or mutually
13076 // referent. Mutually referent means that left_[right_[i]] = i and
13077 // right_[left_[i]] = i.
13078 ::std::vector<size_t> left_;
13079 ::std::vector<size_t> right_;
13080 };
13081
13082 const size_t MaxBipartiteMatchState::kUnused;
13083
13084 GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
13085 return MaxBipartiteMatchState(g).Compute();
13086 }
13087
13088 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
13089 ::std::ostream* stream) {
13090 typedef ElementMatcherPairs::const_iterator Iter;
13091 ::std::ostream& os = *stream;
13092 os << "{";
13093 const char* sep = "";
13094 for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
13095 os << sep << "\n ("
13096 << "element #" << it->first << ", "
13097 << "matcher #" << it->second << ")";
13098 sep = ",";
13099 }
13100 os << "\n}";
13101 }
13102
13103 bool MatchMatrix::NextGraph() {
13104 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
13105 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
13106 char& b = matched_[SpaceIndex(ilhs, irhs)];
13107 if (!b) {
13108 b = 1;
13109 return true;
13110 }
13111 b = 0;
13112 }
13113 }
13114 return false;
13115 }
13116
13117 void MatchMatrix::Randomize() {
13118 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
13119 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
13120 char& b = matched_[SpaceIndex(ilhs, irhs)];
13121 b = static_cast<char>(rand() & 1); // NOLINT
13122 }
13123 }
13124 }
13125
13126 std::string MatchMatrix::DebugString() const {
13127 ::std::stringstream ss;
13128 const char* sep = "";
13129 for (size_t i = 0; i < LhsSize(); ++i) {
13130 ss << sep;
13131 for (size_t j = 0; j < RhsSize(); ++j) {
13132 ss << HasEdge(i, j);
13133 }
13134 sep = ";";
13135 }
13136 return ss.str();
13137 }
13138
13139 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
13140 ::std::ostream* os) const {
13141 switch (match_flags()) {
13142 case UnorderedMatcherRequire::ExactMatch:
13143 if (matcher_describers_.empty()) {
13144 *os << "is empty";
13145 return;
13146 }
13147 if (matcher_describers_.size() == 1) {
13148 *os << "has " << Elements(1) << " and that element ";
13149 matcher_describers_[0]->DescribeTo(os);
13150 return;
13151 }
13152 *os << "has " << Elements(matcher_describers_.size())
13153 << " and there exists some permutation of elements such that:\n";
13154 break;
13155 case UnorderedMatcherRequire::Superset:
13156 *os << "a surjection from elements to requirements exists such that:\n";
13157 break;
13158 case UnorderedMatcherRequire::Subset:
13159 *os << "an injection from elements to requirements exists such that:\n";
13160 break;
13161 }
13162
13163 const char* sep = "";
13164 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
13165 *os << sep;
13166 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
13167 *os << " - element #" << i << " ";
13168 } else {
13169 *os << " - an element ";
13170 }
13171 matcher_describers_[i]->DescribeTo(os);
13172 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
13173 sep = ", and\n";
13174 } else {
13175 sep = "\n";
13176 }
13177 }
13178 }
13179
13180 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
13181 ::std::ostream* os) const {
13182 switch (match_flags()) {
13183 case UnorderedMatcherRequire::ExactMatch:
13184 if (matcher_describers_.empty()) {
13185 *os << "isn't empty";
13186 return;
13187 }
13188 if (matcher_describers_.size() == 1) {
13189 *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
13190 << " that ";
13191 matcher_describers_[0]->DescribeNegationTo(os);
13192 return;
13193 }
13194 *os << "doesn't have " << Elements(matcher_describers_.size())
13195 << ", or there exists no permutation of elements such that:\n";
13196 break;
13197 case UnorderedMatcherRequire::Superset:
13198 *os << "no surjection from elements to requirements exists such that:\n";
13199 break;
13200 case UnorderedMatcherRequire::Subset:
13201 *os << "no injection from elements to requirements exists such that:\n";
13202 break;
13203 }
13204 const char* sep = "";
13205 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
13206 *os << sep;
13207 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
13208 *os << " - element #" << i << " ";
13209 } else {
13210 *os << " - an element ";
13211 }
13212 matcher_describers_[i]->DescribeTo(os);
13213 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
13214 sep = ", and\n";
13215 } else {
13216 sep = "\n";
13217 }
13218 }
13219 }
13220
13221 // Checks that all matchers match at least one element, and that all
13222 // elements match at least one matcher. This enables faster matching
13223 // and better error reporting.
13224 // Returns false, writing an explanation to 'listener', if and only
13225 // if the success criteria are not met.
13226 bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
13227 const ::std::vector<std::string>& element_printouts,
13228 const MatchMatrix& matrix, MatchResultListener* listener) const {
13229 bool result = true;
13230 ::std::vector<char> element_matched(matrix.LhsSize(), 0);
13231 ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
13232
13233 for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
13234 for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
13235 char matched = matrix.HasEdge(ilhs, irhs);
13236 element_matched[ilhs] |= matched;
13237 matcher_matched[irhs] |= matched;
13238 }
13239 }
13240
13241 if (match_flags() & UnorderedMatcherRequire::Superset) {
13242 const char* sep =
13243 "where the following matchers don't match any elements:\n";
13244 for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
13245 if (matcher_matched[mi]) continue;
13246 result = false;
13247 if (listener->IsInterested()) {
13248 *listener << sep << "matcher #" << mi << ": ";
13249 matcher_describers_[mi]->DescribeTo(listener->stream());
13250 sep = ",\n";
13251 }
13252 }
13253 }
13254
13255 if (match_flags() & UnorderedMatcherRequire::Subset) {
13256 const char* sep =
13257 "where the following elements don't match any matchers:\n";
13258 const char* outer_sep = "";
13259 if (!result) {
13260 outer_sep = "\nand ";
13261 }
13262 for (size_t ei = 0; ei < element_matched.size(); ++ei) {
13263 if (element_matched[ei]) continue;
13264 result = false;
13265 if (listener->IsInterested()) {
13266 *listener << outer_sep << sep << "element #" << ei << ": "
13267 << element_printouts[ei];
13268 sep = ",\n";
13269 outer_sep = "";
13270 }
13271 }
13272 }
13273 return result;
13274 }
13275
13276 bool UnorderedElementsAreMatcherImplBase::FindPairing(
13277 const MatchMatrix& matrix, MatchResultListener* listener) const {
13278 ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
13279
13280 size_t max_flow = matches.size();
13281 if ((match_flags() & UnorderedMatcherRequire::Superset) &&
13282 max_flow < matrix.RhsSize()) {
13283 if (listener->IsInterested()) {
13284 *listener << "where no permutation of the elements can satisfy all "
13285 "matchers, and the closest match is "
13286 << max_flow << " of " << matrix.RhsSize()
13287 << " matchers with the pairings:\n";
13288 LogElementMatcherPairVec(matches, listener->stream());
13289 }
13290 return false;
13291 }
13292 if ((match_flags() & UnorderedMatcherRequire::Subset) &&
13293 max_flow < matrix.LhsSize()) {
13294 if (listener->IsInterested()) {
13295 *listener
13296 << "where not all elements can be matched, and the closest match is "
13297 << max_flow << " of " << matrix.RhsSize()
13298 << " matchers with the pairings:\n";
13299 LogElementMatcherPairVec(matches, listener->stream());
13300 }
13301 return false;
13302 }
13303
13304 if (matches.size() > 1) {
13305 if (listener->IsInterested()) {
13306 const char* sep = "where:\n";
13307 for (size_t mi = 0; mi < matches.size(); ++mi) {
13308 *listener << sep << " - element #" << matches[mi].first
13309 << " is matched by matcher #" << matches[mi].second;
13310 sep = ",\n";
13311 }
13312 }
13313 }
13314 return true;
13315 }
13316
13317 } // namespace internal
13318 } // namespace testing
13319 // Copyright 2007, Google Inc.
13320 // All rights reserved.
13321 //
13322 // Redistribution and use in source and binary forms, with or without
13323 // modification, are permitted provided that the following conditions are
13324 // met:
13325 //
13326 // * Redistributions of source code must retain the above copyright
13327 // notice, this list of conditions and the following disclaimer.
13328 // * Redistributions in binary form must reproduce the above
13329 // copyright notice, this list of conditions and the following disclaimer
13330 // in the documentation and/or other materials provided with the
13331 // distribution.
13332 // * Neither the name of Google Inc. nor the names of its
13333 // contributors may be used to endorse or promote products derived from
13334 // this software without specific prior written permission.
13335 //
13336 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
13337 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
13338 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
13339 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
13340 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
13341 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
13342 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
13343 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13344 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13345 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13346 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13347
13348
13349 // Google Mock - a framework for writing C++ mock classes.
13350 //
13351 // This file implements the spec builder syntax (ON_CALL and
13352 // EXPECT_CALL).
13353
13354
13355 #include <stdlib.h>
13356
13357 #include <iostream> // NOLINT
13358 #include <map>
13359 #include <memory>
13360 #include <set>
13361 #include <string>
13362 #include <vector>
13363
13364
13365 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
13366 # include <unistd.h> // NOLINT
13367 #endif
13368
13369 // Silence C4800 (C4800: 'int *const ': forcing value
13370 // to bool 'true' or 'false') for MSVC 15
13371 #ifdef _MSC_VER
13372 #if _MSC_VER == 1900
13373 # pragma warning(push)
13374 # pragma warning(disable:4800)
13375 #endif
13376 #endif
13377
13378 namespace testing {
13379 namespace internal {
13380
13381 // Protects the mock object registry (in class Mock), all function
13382 // mockers, and all expectations.
13383 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
13384
13385 // Logs a message including file and line number information.
13386 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
13387 const char* file, int line,
13388 const std::string& message) {
13389 ::std::ostringstream s;
13390 s << internal::FormatFileLocation(file, line) << " " << message
13391 << ::std::endl;
13392 Log(severity, s.str(), 0);
13393 }
13394
13395 // Constructs an ExpectationBase object.
13396 ExpectationBase::ExpectationBase(const char* a_file, int a_line,
13397 const std::string& a_source_text)
13398 : file_(a_file),
13399 line_(a_line),
13400 source_text_(a_source_text),
13401 cardinality_specified_(false),
13402 cardinality_(Exactly(1)),
13403 call_count_(0),
13404 retired_(false),
13405 extra_matcher_specified_(false),
13406 repeated_action_specified_(false),
13407 retires_on_saturation_(false),
13408 last_clause_(kNone),
13409 action_count_checked_(false) {}
13410
13411 // Destructs an ExpectationBase object.
13412 ExpectationBase::~ExpectationBase() {}
13413
13414 // Explicitly specifies the cardinality of this expectation. Used by
13415 // the subclasses to implement the .Times() clause.
13416 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
13417 cardinality_specified_ = true;
13418 cardinality_ = a_cardinality;
13419 }
13420
13421 // Retires all pre-requisites of this expectation.
13422 void ExpectationBase::RetireAllPreRequisites()
13423 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
13424 if (is_retired()) {
13425 // We can take this short-cut as we never retire an expectation
13426 // until we have retired all its pre-requisites.
13427 return;
13428 }
13429
13430 ::std::vector<ExpectationBase*> expectations(1, this);
13431 while (!expectations.empty()) {
13432 ExpectationBase* exp = expectations.back();
13433 expectations.pop_back();
13434
13435 for (ExpectationSet::const_iterator it =
13436 exp->immediate_prerequisites_.begin();
13437 it != exp->immediate_prerequisites_.end(); ++it) {
13438 ExpectationBase* next = it->expectation_base().get();
13439 if (!next->is_retired()) {
13440 next->Retire();
13441 expectations.push_back(next);
13442 }
13443 }
13444 }
13445 }
13446
13447 // Returns true if and only if all pre-requisites of this expectation
13448 // have been satisfied.
13449 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
13450 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
13451 g_gmock_mutex.AssertHeld();
13452 ::std::vector<const ExpectationBase*> expectations(1, this);
13453 while (!expectations.empty()) {
13454 const ExpectationBase* exp = expectations.back();
13455 expectations.pop_back();
13456
13457 for (ExpectationSet::const_iterator it =
13458 exp->immediate_prerequisites_.begin();
13459 it != exp->immediate_prerequisites_.end(); ++it) {
13460 const ExpectationBase* next = it->expectation_base().get();
13461 if (!next->IsSatisfied()) return false;
13462 expectations.push_back(next);
13463 }
13464 }
13465 return true;
13466 }
13467
13468 // Adds unsatisfied pre-requisites of this expectation to 'result'.
13469 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
13470 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
13471 g_gmock_mutex.AssertHeld();
13472 ::std::vector<const ExpectationBase*> expectations(1, this);
13473 while (!expectations.empty()) {
13474 const ExpectationBase* exp = expectations.back();
13475 expectations.pop_back();
13476
13477 for (ExpectationSet::const_iterator it =
13478 exp->immediate_prerequisites_.begin();
13479 it != exp->immediate_prerequisites_.end(); ++it) {
13480 const ExpectationBase* next = it->expectation_base().get();
13481
13482 if (next->IsSatisfied()) {
13483 // If *it is satisfied and has a call count of 0, some of its
13484 // pre-requisites may not be satisfied yet.
13485 if (next->call_count_ == 0) {
13486 expectations.push_back(next);
13487 }
13488 } else {
13489 // Now that we know next is unsatisfied, we are not so interested
13490 // in whether its pre-requisites are satisfied. Therefore we
13491 // don't iterate into it here.
13492 *result += *it;
13493 }
13494 }
13495 }
13496 }
13497
13498 // Describes how many times a function call matching this
13499 // expectation has occurred.
13500 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
13501 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
13502 g_gmock_mutex.AssertHeld();
13503
13504 // Describes how many times the function is expected to be called.
13505 *os << " Expected: to be ";
13506 cardinality().DescribeTo(os);
13507 *os << "\n Actual: ";
13508 Cardinality::DescribeActualCallCountTo(call_count(), os);
13509
13510 // Describes the state of the expectation (e.g. is it satisfied?
13511 // is it active?).
13512 *os << " - " << (IsOverSaturated() ? "over-saturated" :
13513 IsSaturated() ? "saturated" :
13514 IsSatisfied() ? "satisfied" : "unsatisfied")
13515 << " and "
13516 << (is_retired() ? "retired" : "active");
13517 }
13518
13519 // Checks the action count (i.e. the number of WillOnce() and
13520 // WillRepeatedly() clauses) against the cardinality if this hasn't
13521 // been done before. Prints a warning if there are too many or too
13522 // few actions.
13523 void ExpectationBase::CheckActionCountIfNotDone() const
13524 GTEST_LOCK_EXCLUDED_(mutex_) {
13525 bool should_check = false;
13526 {
13527 MutexLock l(&mutex_);
13528 if (!action_count_checked_) {
13529 action_count_checked_ = true;
13530 should_check = true;
13531 }
13532 }
13533
13534 if (should_check) {
13535 if (!cardinality_specified_) {
13536 // The cardinality was inferred - no need to check the action
13537 // count against it.
13538 return;
13539 }
13540
13541 // The cardinality was explicitly specified.
13542 const int action_count = static_cast<int>(untyped_actions_.size());
13543 const int upper_bound = cardinality().ConservativeUpperBound();
13544 const int lower_bound = cardinality().ConservativeLowerBound();
13545 bool too_many; // True if there are too many actions, or false
13546 // if there are too few.
13547 if (action_count > upper_bound ||
13548 (action_count == upper_bound && repeated_action_specified_)) {
13549 too_many = true;
13550 } else if (0 < action_count && action_count < lower_bound &&
13551 !repeated_action_specified_) {
13552 too_many = false;
13553 } else {
13554 return;
13555 }
13556
13557 ::std::stringstream ss;
13558 DescribeLocationTo(&ss);
13559 ss << "Too " << (too_many ? "many" : "few")
13560 << " actions specified in " << source_text() << "...\n"
13561 << "Expected to be ";
13562 cardinality().DescribeTo(&ss);
13563 ss << ", but has " << (too_many ? "" : "only ")
13564 << action_count << " WillOnce()"
13565 << (action_count == 1 ? "" : "s");
13566 if (repeated_action_specified_) {
13567 ss << " and a WillRepeatedly()";
13568 }
13569 ss << ".";
13570 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
13571 }
13572 }
13573
13574 // Implements the .Times() clause.
13575 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
13576 if (last_clause_ == kTimes) {
13577 ExpectSpecProperty(false,
13578 ".Times() cannot appear "
13579 "more than once in an EXPECT_CALL().");
13580 } else {
13581 ExpectSpecProperty(last_clause_ < kTimes,
13582 ".Times() cannot appear after "
13583 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
13584 "or .RetiresOnSaturation().");
13585 }
13586 last_clause_ = kTimes;
13587
13588 SpecifyCardinality(a_cardinality);
13589 }
13590
13591 // Points to the implicit sequence introduced by a living InSequence
13592 // object (if any) in the current thread or NULL.
13593 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
13594
13595 // Reports an uninteresting call (whose description is in msg) in the
13596 // manner specified by 'reaction'.
13597 void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
13598 // Include a stack trace only if --gmock_verbose=info is specified.
13599 const int stack_frames_to_skip =
13600 GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
13601 switch (reaction) {
13602 case kAllow:
13603 Log(kInfo, msg, stack_frames_to_skip);
13604 break;
13605 case kWarn:
13606 Log(kWarning,
13607 msg +
13608 "\nNOTE: You can safely ignore the above warning unless this "
13609 "call should not happen. Do not suppress it by blindly adding "
13610 "an EXPECT_CALL() if you don't mean to enforce the call. "
13611 "See "
13612 "https://github.com/google/googletest/blob/master/docs/"
13613 "gmock_cook_book.md#"
13614 "knowing-when-to-expect for details.\n",
13615 stack_frames_to_skip);
13616 break;
13617 default: // FAIL
13618 Expect(false, nullptr, -1, msg);
13619 }
13620 }
13621
13622 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
13623 : mock_obj_(nullptr), name_("") {}
13624
13625 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
13626
13627 // Sets the mock object this mock method belongs to, and registers
13628 // this information in the global mock registry. Will be called
13629 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
13630 // method.
13631 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
13632 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
13633 {
13634 MutexLock l(&g_gmock_mutex);
13635 mock_obj_ = mock_obj;
13636 }
13637 Mock::Register(mock_obj, this);
13638 }
13639
13640 // Sets the mock object this mock method belongs to, and sets the name
13641 // of the mock function. Will be called upon each invocation of this
13642 // mock function.
13643 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
13644 const char* name)
13645 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
13646 // We protect name_ under g_gmock_mutex in case this mock function
13647 // is called from two threads concurrently.
13648 MutexLock l(&g_gmock_mutex);
13649 mock_obj_ = mock_obj;
13650 name_ = name;
13651 }
13652
13653 // Returns the name of the function being mocked. Must be called
13654 // after RegisterOwner() or SetOwnerAndName() has been called.
13655 const void* UntypedFunctionMockerBase::MockObject() const
13656 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
13657 const void* mock_obj;
13658 {
13659 // We protect mock_obj_ under g_gmock_mutex in case this mock
13660 // function is called from two threads concurrently.
13661 MutexLock l(&g_gmock_mutex);
13662 Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
13663 "MockObject() must not be called before RegisterOwner() or "
13664 "SetOwnerAndName() has been called.");
13665 mock_obj = mock_obj_;
13666 }
13667 return mock_obj;
13668 }
13669
13670 // Returns the name of this mock method. Must be called after
13671 // SetOwnerAndName() has been called.
13672 const char* UntypedFunctionMockerBase::Name() const
13673 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
13674 const char* name;
13675 {
13676 // We protect name_ under g_gmock_mutex in case this mock
13677 // function is called from two threads concurrently.
13678 MutexLock l(&g_gmock_mutex);
13679 Assert(name_ != nullptr, __FILE__, __LINE__,
13680 "Name() must not be called before SetOwnerAndName() has "
13681 "been called.");
13682 name = name_;
13683 }
13684 return name;
13685 }
13686
13687 // Calculates the result of invoking this mock function with the given
13688 // arguments, prints it, and returns it. The caller is responsible
13689 // for deleting the result.
13690 UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
13691 void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
13692 // See the definition of untyped_expectations_ for why access to it
13693 // is unprotected here.
13694 if (untyped_expectations_.size() == 0) {
13695 // No expectation is set on this mock method - we have an
13696 // uninteresting call.
13697
13698 // We must get Google Mock's reaction on uninteresting calls
13699 // made on this mock object BEFORE performing the action,
13700 // because the action may DELETE the mock object and make the
13701 // following expression meaningless.
13702 const CallReaction reaction =
13703 Mock::GetReactionOnUninterestingCalls(MockObject());
13704
13705 // True if and only if we need to print this call's arguments and return
13706 // value. This definition must be kept in sync with
13707 // the behavior of ReportUninterestingCall().
13708 const bool need_to_report_uninteresting_call =
13709 // If the user allows this uninteresting call, we print it
13710 // only when they want informational messages.
13711 reaction == kAllow ? LogIsVisible(kInfo) :
13712 // If the user wants this to be a warning, we print
13713 // it only when they want to see warnings.
13714 reaction == kWarn
13715 ? LogIsVisible(kWarning)
13716 :
13717 // Otherwise, the user wants this to be an error, and we
13718 // should always print detailed information in the error.
13719 true;
13720
13721 if (!need_to_report_uninteresting_call) {
13722 // Perform the action without printing the call information.
13723 return this->UntypedPerformDefaultAction(
13724 untyped_args, "Function call: " + std::string(Name()));
13725 }
13726
13727 // Warns about the uninteresting call.
13728 ::std::stringstream ss;
13729 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
13730
13731 // Calculates the function result.
13732 UntypedActionResultHolderBase* const result =
13733 this->UntypedPerformDefaultAction(untyped_args, ss.str());
13734
13735 // Prints the function result.
13736 if (result != nullptr) result->PrintAsActionResult(&ss);
13737
13738 ReportUninterestingCall(reaction, ss.str());
13739 return result;
13740 }
13741
13742 bool is_excessive = false;
13743 ::std::stringstream ss;
13744 ::std::stringstream why;
13745 ::std::stringstream loc;
13746 const void* untyped_action = nullptr;
13747
13748 // The UntypedFindMatchingExpectation() function acquires and
13749 // releases g_gmock_mutex.
13750
13751 const ExpectationBase* const untyped_expectation =
13752 this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
13753 &is_excessive, &ss, &why);
13754 const bool found = untyped_expectation != nullptr;
13755
13756 // True if and only if we need to print the call's arguments
13757 // and return value.
13758 // This definition must be kept in sync with the uses of Expect()
13759 // and Log() in this function.
13760 const bool need_to_report_call =
13761 !found || is_excessive || LogIsVisible(kInfo);
13762 if (!need_to_report_call) {
13763 // Perform the action without printing the call information.
13764 return untyped_action == nullptr
13765 ? this->UntypedPerformDefaultAction(untyped_args, "")
13766 : this->UntypedPerformAction(untyped_action, untyped_args);
13767 }
13768
13769 ss << " Function call: " << Name();
13770 this->UntypedPrintArgs(untyped_args, &ss);
13771
13772 // In case the action deletes a piece of the expectation, we
13773 // generate the message beforehand.
13774 if (found && !is_excessive) {
13775 untyped_expectation->DescribeLocationTo(&loc);
13776 }
13777
13778 UntypedActionResultHolderBase* result = nullptr;
13779
13780 auto perform_action = [&] {
13781 return untyped_action == nullptr
13782 ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
13783 : this->UntypedPerformAction(untyped_action, untyped_args);
13784 };
13785 auto handle_failures = [&] {
13786 ss << "\n" << why.str();
13787
13788 if (!found) {
13789 // No expectation matches this call - reports a failure.
13790 Expect(false, nullptr, -1, ss.str());
13791 } else if (is_excessive) {
13792 // We had an upper-bound violation and the failure message is in ss.
13793 Expect(false, untyped_expectation->file(), untyped_expectation->line(),
13794 ss.str());
13795 } else {
13796 // We had an expected call and the matching expectation is
13797 // described in ss.
13798 Log(kInfo, loc.str() + ss.str(), 2);
13799 }
13800 };
13801 #if GTEST_HAS_EXCEPTIONS
13802 try {
13803 result = perform_action();
13804 } catch (...) {
13805 handle_failures();
13806 throw;
13807 }
13808 #else
13809 result = perform_action();
13810 #endif
13811
13812 if (result != nullptr) result->PrintAsActionResult(&ss);
13813 handle_failures();
13814 return result;
13815 }
13816
13817 // Returns an Expectation object that references and co-owns exp,
13818 // which must be an expectation on this mock function.
13819 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
13820 // See the definition of untyped_expectations_ for why access to it
13821 // is unprotected here.
13822 for (UntypedExpectations::const_iterator it =
13823 untyped_expectations_.begin();
13824 it != untyped_expectations_.end(); ++it) {
13825 if (it->get() == exp) {
13826 return Expectation(*it);
13827 }
13828 }
13829
13830 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
13831 return Expectation();
13832 // The above statement is just to make the code compile, and will
13833 // never be executed.
13834 }
13835
13836 // Verifies that all expectations on this mock function have been
13837 // satisfied. Reports one or more Google Test non-fatal failures
13838 // and returns false if not.
13839 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
13840 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
13841 g_gmock_mutex.AssertHeld();
13842 bool expectations_met = true;
13843 for (UntypedExpectations::const_iterator it =
13844 untyped_expectations_.begin();
13845 it != untyped_expectations_.end(); ++it) {
13846 ExpectationBase* const untyped_expectation = it->get();
13847 if (untyped_expectation->IsOverSaturated()) {
13848 // There was an upper-bound violation. Since the error was
13849 // already reported when it occurred, there is no need to do
13850 // anything here.
13851 expectations_met = false;
13852 } else if (!untyped_expectation->IsSatisfied()) {
13853 expectations_met = false;
13854 ::std::stringstream ss;
13855 ss << "Actual function call count doesn't match "
13856 << untyped_expectation->source_text() << "...\n";
13857 // No need to show the source file location of the expectation
13858 // in the description, as the Expect() call that follows already
13859 // takes care of it.
13860 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
13861 untyped_expectation->DescribeCallCountTo(&ss);
13862 Expect(false, untyped_expectation->file(),
13863 untyped_expectation->line(), ss.str());
13864 }
13865 }
13866
13867 // Deleting our expectations may trigger other mock objects to be deleted, for
13868 // example if an action contains a reference counted smart pointer to that
13869 // mock object, and that is the last reference. So if we delete our
13870 // expectations within the context of the global mutex we may deadlock when
13871 // this method is called again. Instead, make a copy of the set of
13872 // expectations to delete, clear our set within the mutex, and then clear the
13873 // copied set outside of it.
13874 UntypedExpectations expectations_to_delete;
13875 untyped_expectations_.swap(expectations_to_delete);
13876
13877 g_gmock_mutex.Unlock();
13878 expectations_to_delete.clear();
13879 g_gmock_mutex.Lock();
13880
13881 return expectations_met;
13882 }
13883
13884 CallReaction intToCallReaction(int mock_behavior) {
13885 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
13886 return static_cast<internal::CallReaction>(mock_behavior);
13887 }
13888 return kWarn;
13889 }
13890
13891 } // namespace internal
13892
13893 // Class Mock.
13894
13895 namespace {
13896
13897 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
13898
13899 // The current state of a mock object. Such information is needed for
13900 // detecting leaked mock objects and explicitly verifying a mock's
13901 // expectations.
13902 struct MockObjectState {
13903 MockObjectState()
13904 : first_used_file(nullptr), first_used_line(-1), leakable(false) {}
13905
13906 // Where in the source file an ON_CALL or EXPECT_CALL is first
13907 // invoked on this mock object.
13908 const char* first_used_file;
13909 int first_used_line;
13910 ::std::string first_used_test_suite;
13911 ::std::string first_used_test;
13912 bool leakable; // true if and only if it's OK to leak the object.
13913 FunctionMockers function_mockers; // All registered methods of the object.
13914 };
13915
13916 // A global registry holding the state of all mock objects that are
13917 // alive. A mock object is added to this registry the first time
13918 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
13919 // is removed from the registry in the mock object's destructor.
13920 class MockObjectRegistry {
13921 public:
13922 // Maps a mock object (identified by its address) to its state.
13923 typedef std::map<const void*, MockObjectState> StateMap;
13924
13925 // This destructor will be called when a program exits, after all
13926 // tests in it have been run. By then, there should be no mock
13927 // object alive. Therefore we report any living object as test
13928 // failure, unless the user explicitly asked us to ignore it.
13929 ~MockObjectRegistry() {
13930 if (!GMOCK_FLAG(catch_leaked_mocks))
13931 return;
13932
13933 int leaked_count = 0;
13934 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
13935 ++it) {
13936 if (it->second.leakable) // The user said it's fine to leak this object.
13937 continue;
13938
13939 // FIXME: Print the type of the leaked object.
13940 // This can help the user identify the leaked object.
13941 std::cout << "\n";
13942 const MockObjectState& state = it->second;
13943 std::cout << internal::FormatFileLocation(state.first_used_file,
13944 state.first_used_line);
13945 std::cout << " ERROR: this mock object";
13946 if (state.first_used_test != "") {
13947 std::cout << " (used in test " << state.first_used_test_suite << "."
13948 << state.first_used_test << ")";
13949 }
13950 std::cout << " should be deleted but never is. Its address is @"
13951 << it->first << ".";
13952 leaked_count++;
13953 }
13954 if (leaked_count > 0) {
13955 std::cout << "\nERROR: " << leaked_count << " leaked mock "
13956 << (leaked_count == 1 ? "object" : "objects")
13957 << " found at program exit. Expectations on a mock object are "
13958 "verified when the object is destructed. Leaking a mock "
13959 "means that its expectations aren't verified, which is "
13960 "usually a test bug. If you really intend to leak a mock, "
13961 "you can suppress this error using "
13962 "testing::Mock::AllowLeak(mock_object), or you may use a "
13963 "fake or stub instead of a mock.\n";
13964 std::cout.flush();
13965 ::std::cerr.flush();
13966 // RUN_ALL_TESTS() has already returned when this destructor is
13967 // called. Therefore we cannot use the normal Google Test
13968 // failure reporting mechanism.
13969 _exit(1); // We cannot call exit() as it is not reentrant and
13970 // may already have been called.
13971 }
13972 }
13973
13974 StateMap& states() { return states_; }
13975
13976 private:
13977 StateMap states_;
13978 };
13979
13980 // Protected by g_gmock_mutex.
13981 MockObjectRegistry g_mock_object_registry;
13982
13983 // Maps a mock object to the reaction Google Mock should have when an
13984 // uninteresting method is called. Protected by g_gmock_mutex.
13985 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
13986
13987 // Sets the reaction Google Mock should have when an uninteresting
13988 // method of the given mock object is called.
13989 void SetReactionOnUninterestingCalls(const void* mock_obj,
13990 internal::CallReaction reaction)
13991 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13992 internal::MutexLock l(&internal::g_gmock_mutex);
13993 g_uninteresting_call_reaction[mock_obj] = reaction;
13994 }
13995
13996 } // namespace
13997
13998 // Tells Google Mock to allow uninteresting calls on the given mock
13999 // object.
14000 void Mock::AllowUninterestingCalls(const void* mock_obj)
14001 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14002 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
14003 }
14004
14005 // Tells Google Mock to warn the user about uninteresting calls on the
14006 // given mock object.
14007 void Mock::WarnUninterestingCalls(const void* mock_obj)
14008 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14009 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
14010 }
14011
14012 // Tells Google Mock to fail uninteresting calls on the given mock
14013 // object.
14014 void Mock::FailUninterestingCalls(const void* mock_obj)
14015 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14016 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
14017 }
14018
14019 // Tells Google Mock the given mock object is being destroyed and its
14020 // entry in the call-reaction table should be removed.
14021 void Mock::UnregisterCallReaction(const void* mock_obj)
14022 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14023 internal::MutexLock l(&internal::g_gmock_mutex);
14024 g_uninteresting_call_reaction.erase(mock_obj);
14025 }
14026
14027 // Returns the reaction Google Mock will have on uninteresting calls
14028 // made on the given mock object.
14029 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
14030 const void* mock_obj)
14031 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14032 internal::MutexLock l(&internal::g_gmock_mutex);
14033 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
14034 internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
14035 g_uninteresting_call_reaction[mock_obj];
14036 }
14037
14038 // Tells Google Mock to ignore mock_obj when checking for leaked mock
14039 // objects.
14040 void Mock::AllowLeak(const void* mock_obj)
14041 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14042 internal::MutexLock l(&internal::g_gmock_mutex);
14043 g_mock_object_registry.states()[mock_obj].leakable = true;
14044 }
14045
14046 // Verifies and clears all expectations on the given mock object. If
14047 // the expectations aren't satisfied, generates one or more Google
14048 // Test non-fatal failures and returns false.
14049 bool Mock::VerifyAndClearExpectations(void* mock_obj)
14050 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14051 internal::MutexLock l(&internal::g_gmock_mutex);
14052 return VerifyAndClearExpectationsLocked(mock_obj);
14053 }
14054
14055 // Verifies all expectations on the given mock object and clears its
14056 // default actions and expectations. Returns true if and only if the
14057 // verification was successful.
14058 bool Mock::VerifyAndClear(void* mock_obj)
14059 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14060 internal::MutexLock l(&internal::g_gmock_mutex);
14061 ClearDefaultActionsLocked(mock_obj);
14062 return VerifyAndClearExpectationsLocked(mock_obj);
14063 }
14064
14065 // Verifies and clears all expectations on the given mock object. If
14066 // the expectations aren't satisfied, generates one or more Google
14067 // Test non-fatal failures and returns false.
14068 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
14069 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
14070 internal::g_gmock_mutex.AssertHeld();
14071 if (g_mock_object_registry.states().count(mock_obj) == 0) {
14072 // No EXPECT_CALL() was set on the given mock object.
14073 return true;
14074 }
14075
14076 // Verifies and clears the expectations on each mock method in the
14077 // given mock object.
14078 bool expectations_met = true;
14079 FunctionMockers& mockers =
14080 g_mock_object_registry.states()[mock_obj].function_mockers;
14081 for (FunctionMockers::const_iterator it = mockers.begin();
14082 it != mockers.end(); ++it) {
14083 if (!(*it)->VerifyAndClearExpectationsLocked()) {
14084 expectations_met = false;
14085 }
14086 }
14087
14088 // We don't clear the content of mockers, as they may still be
14089 // needed by ClearDefaultActionsLocked().
14090 return expectations_met;
14091 }
14092
14093 bool Mock::IsNaggy(void* mock_obj)
14094 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14095 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
14096 }
14097 bool Mock::IsNice(void* mock_obj)
14098 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14099 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
14100 }
14101 bool Mock::IsStrict(void* mock_obj)
14102 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14103 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
14104 }
14105
14106 // Registers a mock object and a mock method it owns.
14107 void Mock::Register(const void* mock_obj,
14108 internal::UntypedFunctionMockerBase* mocker)
14109 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14110 internal::MutexLock l(&internal::g_gmock_mutex);
14111 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
14112 }
14113
14114 // Tells Google Mock where in the source code mock_obj is used in an
14115 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
14116 // information helps the user identify which object it is.
14117 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
14118 const char* file, int line)
14119 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
14120 internal::MutexLock l(&internal::g_gmock_mutex);
14121 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
14122 if (state.first_used_file == nullptr) {
14123 state.first_used_file = file;
14124 state.first_used_line = line;
14125 const TestInfo* const test_info =
14126 UnitTest::GetInstance()->current_test_info();
14127 if (test_info != nullptr) {
14128 state.first_used_test_suite = test_info->test_suite_name();
14129 state.first_used_test = test_info->name();
14130 }
14131 }
14132 }
14133
14134 // Unregisters a mock method; removes the owning mock object from the
14135 // registry when the last mock method associated with it has been
14136 // unregistered. This is called only in the destructor of
14137 // FunctionMockerBase.
14138 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
14139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
14140 internal::g_gmock_mutex.AssertHeld();
14141 for (MockObjectRegistry::StateMap::iterator it =
14142 g_mock_object_registry.states().begin();
14143 it != g_mock_object_registry.states().end(); ++it) {
14144 FunctionMockers& mockers = it->second.function_mockers;
14145 if (mockers.erase(mocker) > 0) {
14146 // mocker was in mockers and has been just removed.
14147 if (mockers.empty()) {
14148 g_mock_object_registry.states().erase(it);
14149 }
14150 return;
14151 }
14152 }
14153 }
14154
14155 // Clears all ON_CALL()s set on the given mock object.
14156 void Mock::ClearDefaultActionsLocked(void* mock_obj)
14157 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
14158 internal::g_gmock_mutex.AssertHeld();
14159
14160 if (g_mock_object_registry.states().count(mock_obj) == 0) {
14161 // No ON_CALL() was set on the given mock object.
14162 return;
14163 }
14164
14165 // Clears the default actions for each mock method in the given mock
14166 // object.
14167 FunctionMockers& mockers =
14168 g_mock_object_registry.states()[mock_obj].function_mockers;
14169 for (FunctionMockers::const_iterator it = mockers.begin();
14170 it != mockers.end(); ++it) {
14171 (*it)->ClearDefaultActionsLocked();
14172 }
14173
14174 // We don't clear the content of mockers, as they may still be
14175 // needed by VerifyAndClearExpectationsLocked().
14176 }
14177
14178 Expectation::Expectation() {}
14179
14180 Expectation::Expectation(
14181 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
14182 : expectation_base_(an_expectation_base) {}
14183
14184 Expectation::~Expectation() {}
14185
14186 // Adds an expectation to a sequence.
14187 void Sequence::AddExpectation(const Expectation& expectation) const {
14188 if (*last_expectation_ != expectation) {
14189 if (last_expectation_->expectation_base() != nullptr) {
14190 expectation.expectation_base()->immediate_prerequisites_
14191 += *last_expectation_;
14192 }
14193 *last_expectation_ = expectation;
14194 }
14195 }
14196
14197 // Creates the implicit sequence if there isn't one.
14198 InSequence::InSequence() {
14199 if (internal::g_gmock_implicit_sequence.get() == nullptr) {
14200 internal::g_gmock_implicit_sequence.set(new Sequence);
14201 sequence_created_ = true;
14202 } else {
14203 sequence_created_ = false;
14204 }
14205 }
14206
14207 // Deletes the implicit sequence if it was created by the constructor
14208 // of this object.
14209 InSequence::~InSequence() {
14210 if (sequence_created_) {
14211 delete internal::g_gmock_implicit_sequence.get();
14212 internal::g_gmock_implicit_sequence.set(nullptr);
14213 }
14214 }
14215
14216 } // namespace testing
14217
14218 #ifdef _MSC_VER
14219 #if _MSC_VER == 1900
14220 # pragma warning(pop)
14221 #endif
14222 #endif
14223 // Copyright 2008, Google Inc.
14224 // All rights reserved.
14225 //
14226 // Redistribution and use in source and binary forms, with or without
14227 // modification, are permitted provided that the following conditions are
14228 // met:
14229 //
14230 // * Redistributions of source code must retain the above copyright
14231 // notice, this list of conditions and the following disclaimer.
14232 // * Redistributions in binary form must reproduce the above
14233 // copyright notice, this list of conditions and the following disclaimer
14234 // in the documentation and/or other materials provided with the
14235 // distribution.
14236 // * Neither the name of Google Inc. nor the names of its
14237 // contributors may be used to endorse or promote products derived from
14238 // this software without specific prior written permission.
14239 //
14240 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
14241 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
14242 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
14243 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
14244 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
14245 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
14246 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
14247 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
14248 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14249 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14250 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14251
14252
14253
14254 namespace testing {
14255
14256 GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
14257 "true if and only if Google Mock should report leaked "
14258 "mock objects as failures.");
14259
14260 GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
14261 "Controls how verbose Google Mock's output is."
14262 " Valid values:\n"
14263 " info - prints all messages.\n"
14264 " warning - prints warnings and errors.\n"
14265 " error - prints errors only.");
14266
14267 GMOCK_DEFINE_int32_(default_mock_behavior, 1,
14268 "Controls the default behavior of mocks."
14269 " Valid values:\n"
14270 " 0 - by default, mocks act as NiceMocks.\n"
14271 " 1 - by default, mocks act as NaggyMocks.\n"
14272 " 2 - by default, mocks act as StrictMocks.");
14273
14274 namespace internal {
14275
14276 // Parses a string as a command line flag. The string should have the
14277 // format "--gmock_flag=value". When def_optional is true, the
14278 // "=value" part can be omitted.
14279 //
14280 // Returns the value of the flag, or NULL if the parsing failed.
14281 static const char* ParseGoogleMockFlagValue(const char* str,
14282 const char* flag,
14283 bool def_optional) {
14284 // str and flag must not be NULL.
14285 if (str == nullptr || flag == nullptr) return nullptr;
14286
14287 // The flag must start with "--gmock_".
14288 const std::string flag_str = std::string("--gmock_") + flag;
14289 const size_t flag_len = flag_str.length();
14290 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
14291
14292 // Skips the flag name.
14293 const char* flag_end = str + flag_len;
14294
14295 // When def_optional is true, it's OK to not have a "=value" part.
14296 if (def_optional && (flag_end[0] == '\0')) {
14297 return flag_end;
14298 }
14299
14300 // If def_optional is true and there are more characters after the
14301 // flag name, or if def_optional is false, there must be a '=' after
14302 // the flag name.
14303 if (flag_end[0] != '=') return nullptr;
14304
14305 // Returns the string after "=".
14306 return flag_end + 1;
14307 }
14308
14309 // Parses a string for a Google Mock bool flag, in the form of
14310 // "--gmock_flag=value".
14311 //
14312 // On success, stores the value of the flag in *value, and returns
14313 // true. On failure, returns false without changing *value.
14314 static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
14315 bool* value) {
14316 // Gets the value of the flag as a string.
14317 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
14318
14319 // Aborts if the parsing failed.
14320 if (value_str == nullptr) return false;
14321
14322 // Converts the string value to a bool.
14323 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
14324 return true;
14325 }
14326
14327 // Parses a string for a Google Mock string flag, in the form of
14328 // "--gmock_flag=value".
14329 //
14330 // On success, stores the value of the flag in *value, and returns
14331 // true. On failure, returns false without changing *value.
14332 template <typename String>
14333 static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
14334 String* value) {
14335 // Gets the value of the flag as a string.
14336 const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
14337
14338 // Aborts if the parsing failed.
14339 if (value_str == nullptr) return false;
14340
14341 // Sets *value to the value of the flag.
14342 *value = value_str;
14343 return true;
14344 }
14345
14346 static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
14347 int32_t* value) {
14348 // Gets the value of the flag as a string.
14349 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
14350
14351 // Aborts if the parsing failed.
14352 if (value_str == nullptr) return false;
14353
14354 // Sets *value to the value of the flag.
14355 return ParseInt32(Message() << "The value of flag --" << flag,
14356 value_str, value);
14357 }
14358
14359 // The internal implementation of InitGoogleMock().
14360 //
14361 // The type parameter CharType can be instantiated to either char or
14362 // wchar_t.
14363 template <typename CharType>
14364 void InitGoogleMockImpl(int* argc, CharType** argv) {
14365 // Makes sure Google Test is initialized. InitGoogleTest() is
14366 // idempotent, so it's fine if the user has already called it.
14367 InitGoogleTest(argc, argv);
14368 if (*argc <= 0) return;
14369
14370 for (int i = 1; i != *argc; i++) {
14371 const std::string arg_string = StreamableToString(argv[i]);
14372 const char* const arg = arg_string.c_str();
14373
14374 // Do we see a Google Mock flag?
14375 if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
14376 &GMOCK_FLAG(catch_leaked_mocks)) ||
14377 ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) ||
14378 ParseGoogleMockIntFlag(arg, "default_mock_behavior",
14379 &GMOCK_FLAG(default_mock_behavior))) {
14380 // Yes. Shift the remainder of the argv list left by one. Note
14381 // that argv has (*argc + 1) elements, the last one always being
14382 // NULL. The following loop moves the trailing NULL element as
14383 // well.
14384 for (int j = i; j != *argc; j++) {
14385 argv[j] = argv[j + 1];
14386 }
14387
14388 // Decrements the argument count.
14389 (*argc)--;
14390
14391 // We also need to decrement the iterator as we just removed
14392 // an element.
14393 i--;
14394 }
14395 }
14396 }
14397
14398 } // namespace internal
14399
14400 // Initializes Google Mock. This must be called before running the
14401 // tests. In particular, it parses a command line for the flags that
14402 // Google Mock recognizes. Whenever a Google Mock flag is seen, it is
14403 // removed from argv, and *argc is decremented.
14404 //
14405 // No value is returned. Instead, the Google Mock flag variables are
14406 // updated.
14407 //
14408 // Since Google Test is needed for Google Mock to work, this function
14409 // also initializes Google Test and parses its flags, if that hasn't
14410 // been done.
14411 GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
14412 internal::InitGoogleMockImpl(argc, argv);
14413 }
14414
14415 // This overloaded version can be used in Windows programs compiled in
14416 // UNICODE mode.
14417 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
14418 internal::InitGoogleMockImpl(argc, argv);
14419 }
14420
14421 // This overloaded version can be used on Arduino/embedded platforms where
14422 // there is no argc/argv.
14423 GTEST_API_ void InitGoogleMock() {
14424 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
14425 int argc = 1;
14426 const auto arg0 = "dummy";
14427 char* argv0 = const_cast<char*>(arg0);
14428 char** argv = &argv0;
14429
14430 internal::InitGoogleMockImpl(&argc, argv);
14431 }
14432
14433 } // namespace testing
+0
-238
source/misc/embedded_libs/fmt-8.1.1/test/gtest/gtest/gtest-spi.h less more
0 // Copyright 2007, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 //
30 // Utilities for testing Google Test itself and code that uses Google Test
31 // (e.g. frameworks built on top of Google Test).
32
33 // GOOGLETEST_CM0004 DO NOT DELETE
34
35 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
36 #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
37
38 #include "gtest/gtest.h"
39
40 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
41 /* class A needs to have dll-interface to be used by clients of class B */)
42
43 namespace testing {
44
45 // This helper class can be used to mock out Google Test failure reporting
46 // so that we can test Google Test or code that builds on Google Test.
47 //
48 // An object of this class appends a TestPartResult object to the
49 // TestPartResultArray object given in the constructor whenever a Google Test
50 // failure is reported. It can either intercept only failures that are
51 // generated in the same thread that created this object or it can intercept
52 // all generated failures. The scope of this mock object can be controlled with
53 // the second argument to the two arguments constructor.
54 class GTEST_API_ ScopedFakeTestPartResultReporter
55 : public TestPartResultReporterInterface {
56 public:
57 // The two possible mocking modes of this object.
58 enum InterceptMode {
59 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
60 INTERCEPT_ALL_THREADS // Intercepts all failures.
61 };
62
63 // The c'tor sets this object as the test part result reporter used
64 // by Google Test. The 'result' parameter specifies where to report the
65 // results. This reporter will only catch failures generated in the current
66 // thread. DEPRECATED
67 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
68
69 // Same as above, but you can choose the interception scope of this object.
70 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
71 TestPartResultArray* result);
72
73 // The d'tor restores the previous test part result reporter.
74 ~ScopedFakeTestPartResultReporter() override;
75
76 // Appends the TestPartResult object to the TestPartResultArray
77 // received in the constructor.
78 //
79 // This method is from the TestPartResultReporterInterface
80 // interface.
81 void ReportTestPartResult(const TestPartResult& result) override;
82
83 private:
84 void Init();
85
86 const InterceptMode intercept_mode_;
87 TestPartResultReporterInterface* old_reporter_;
88 TestPartResultArray* const result_;
89
90 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
91 };
92
93 namespace internal {
94
95 // A helper class for implementing EXPECT_FATAL_FAILURE() and
96 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
97 // TestPartResultArray contains exactly one failure that has the given
98 // type and contains the given substring. If that's not the case, a
99 // non-fatal failure will be generated.
100 class GTEST_API_ SingleFailureChecker {
101 public:
102 // The constructor remembers the arguments.
103 SingleFailureChecker(const TestPartResultArray* results,
104 TestPartResult::Type type, const std::string& substr);
105 ~SingleFailureChecker();
106 private:
107 const TestPartResultArray* const results_;
108 const TestPartResult::Type type_;
109 const std::string substr_;
110
111 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
112 };
113
114 } // namespace internal
115
116 } // namespace testing
117
118 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
119
120 // A set of macros for testing Google Test assertions or code that's expected
121 // to generate Google Test fatal failures. It verifies that the given
122 // statement will cause exactly one fatal Google Test failure with 'substr'
123 // being part of the failure message.
124 //
125 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
126 // affects and considers failures generated in the current thread and
127 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
128 //
129 // The verification of the assertion is done correctly even when the statement
130 // throws an exception or aborts the current function.
131 //
132 // Known restrictions:
133 // - 'statement' cannot reference local non-static variables or
134 // non-static members of the current object.
135 // - 'statement' cannot return a value.
136 // - You cannot stream a failure message to this macro.
137 //
138 // Note that even though the implementations of the following two
139 // macros are much alike, we cannot refactor them to use a common
140 // helper macro, due to some peculiarity in how the preprocessor
141 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
142 // gtest_unittest.cc will fail to compile if we do that.
143 #define EXPECT_FATAL_FAILURE(statement, substr) \
144 do { \
145 class GTestExpectFatalFailureHelper {\
146 public:\
147 static void Execute() { statement; }\
148 };\
149 ::testing::TestPartResultArray gtest_failures;\
150 ::testing::internal::SingleFailureChecker gtest_checker(\
151 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
152 {\
153 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
154 ::testing::ScopedFakeTestPartResultReporter:: \
155 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
156 GTestExpectFatalFailureHelper::Execute();\
157 }\
158 } while (::testing::internal::AlwaysFalse())
159
160 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
161 do { \
162 class GTestExpectFatalFailureHelper {\
163 public:\
164 static void Execute() { statement; }\
165 };\
166 ::testing::TestPartResultArray gtest_failures;\
167 ::testing::internal::SingleFailureChecker gtest_checker(\
168 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
169 {\
170 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
171 ::testing::ScopedFakeTestPartResultReporter:: \
172 INTERCEPT_ALL_THREADS, &gtest_failures);\
173 GTestExpectFatalFailureHelper::Execute();\
174 }\
175 } while (::testing::internal::AlwaysFalse())
176
177 // A macro for testing Google Test assertions or code that's expected to
178 // generate Google Test non-fatal failures. It asserts that the given
179 // statement will cause exactly one non-fatal Google Test failure with 'substr'
180 // being part of the failure message.
181 //
182 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
183 // affects and considers failures generated in the current thread and
184 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
185 //
186 // 'statement' is allowed to reference local variables and members of
187 // the current object.
188 //
189 // The verification of the assertion is done correctly even when the statement
190 // throws an exception or aborts the current function.
191 //
192 // Known restrictions:
193 // - You cannot stream a failure message to this macro.
194 //
195 // Note that even though the implementations of the following two
196 // macros are much alike, we cannot refactor them to use a common
197 // helper macro, due to some peculiarity in how the preprocessor
198 // works. If we do that, the code won't compile when the user gives
199 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
200 // expands to code containing an unprotected comma. The
201 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
202 // catches that.
203 //
204 // For the same reason, we have to write
205 // if (::testing::internal::AlwaysTrue()) { statement; }
206 // instead of
207 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
208 // to avoid an MSVC warning on unreachable code.
209 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
210 do {\
211 ::testing::TestPartResultArray gtest_failures;\
212 ::testing::internal::SingleFailureChecker gtest_checker(\
213 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
214 (substr));\
215 {\
216 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
217 ::testing::ScopedFakeTestPartResultReporter:: \
218 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
219 if (::testing::internal::AlwaysTrue()) { statement; }\
220 }\
221 } while (::testing::internal::AlwaysFalse())
222
223 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
224 do {\
225 ::testing::TestPartResultArray gtest_failures;\
226 ::testing::internal::SingleFailureChecker gtest_checker(\
227 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
228 (substr));\
229 {\
230 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
231 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
232 &gtest_failures);\
233 if (::testing::internal::AlwaysTrue()) { statement; }\
234 }\
235 } while (::testing::internal::AlwaysFalse())
236
237 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
+0
-12398
source/misc/embedded_libs/fmt-8.1.1/test/gtest/gtest/gtest.h less more
0 // Copyright 2005, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 //
30 // The Google C++ Testing and Mocking Framework (Google Test)
31 //
32 // This header file defines the public API for Google Test. It should be
33 // included by any test program that uses Google Test.
34 //
35 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
36 // leave some internal implementation details in this header file.
37 // They are clearly marked by comments like this:
38 //
39 // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
40 //
41 // Such code is NOT meant to be used by a user directly, and is subject
42 // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
43 // program!
44 //
45 // Acknowledgment: Google Test borrowed the idea of automatic test
46 // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
47 // easyUnit framework.
48
49 // GOOGLETEST_CM0001 DO NOT DELETE
50
51 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
52 #define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
53
54 #include <cstddef>
55 #include <limits>
56 #include <memory>
57 #include <ostream>
58 #include <type_traits>
59 #include <vector>
60
61 // Copyright 2005, Google Inc.
62 // All rights reserved.
63 //
64 // Redistribution and use in source and binary forms, with or without
65 // modification, are permitted provided that the following conditions are
66 // met:
67 //
68 // * Redistributions of source code must retain the above copyright
69 // notice, this list of conditions and the following disclaimer.
70 // * Redistributions in binary form must reproduce the above
71 // copyright notice, this list of conditions and the following disclaimer
72 // in the documentation and/or other materials provided with the
73 // distribution.
74 // * Neither the name of Google Inc. nor the names of its
75 // contributors may be used to endorse or promote products derived from
76 // this software without specific prior written permission.
77 //
78 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
79 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
80 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
81 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
82 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
83 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
84 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
85 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
86 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
87 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
88 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
89 //
90 // The Google C++ Testing and Mocking Framework (Google Test)
91 //
92 // This header file declares functions and macros used internally by
93 // Google Test. They are subject to change without notice.
94
95 // GOOGLETEST_CM0001 DO NOT DELETE
96
97 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
98 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
99
100 // Copyright 2005, Google Inc.
101 // All rights reserved.
102 //
103 // Redistribution and use in source and binary forms, with or without
104 // modification, are permitted provided that the following conditions are
105 // met:
106 //
107 // * Redistributions of source code must retain the above copyright
108 // notice, this list of conditions and the following disclaimer.
109 // * Redistributions in binary form must reproduce the above
110 // copyright notice, this list of conditions and the following disclaimer
111 // in the documentation and/or other materials provided with the
112 // distribution.
113 // * Neither the name of Google Inc. nor the names of its
114 // contributors may be used to endorse or promote products derived from
115 // this software without specific prior written permission.
116 //
117 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
118 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
119 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
120 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
121 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
122 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
123 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
124 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
125 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
126 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
127 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
128 //
129 // Low-level types and utilities for porting Google Test to various
130 // platforms. All macros ending with _ and symbols defined in an
131 // internal namespace are subject to change without notice. Code
132 // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't
133 // end with _ are part of Google Test's public API and can be used by
134 // code outside Google Test.
135 //
136 // This file is fundamental to Google Test. All other Google Test source
137 // files are expected to #include this. Therefore, it cannot #include
138 // any other Google Test header.
139
140 // GOOGLETEST_CM0001 DO NOT DELETE
141
142 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
143 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
144
145 // Environment-describing macros
146 // -----------------------------
147 //
148 // Google Test can be used in many different environments. Macros in
149 // this section tell Google Test what kind of environment it is being
150 // used in, such that Google Test can provide environment-specific
151 // features and implementations.
152 //
153 // Google Test tries to automatically detect the properties of its
154 // environment, so users usually don't need to worry about these
155 // macros. However, the automatic detection is not perfect.
156 // Sometimes it's necessary for a user to define some of the following
157 // macros in the build script to override Google Test's decisions.
158 //
159 // If the user doesn't define a macro in the list, Google Test will
160 // provide a default definition. After this header is #included, all
161 // macros in this list will be defined to either 1 or 0.
162 //
163 // Notes to maintainers:
164 // - Each macro here is a user-tweakable knob; do not grow the list
165 // lightly.
166 // - Use #if to key off these macros. Don't use #ifdef or "#if
167 // defined(...)", which will not work as these macros are ALWAYS
168 // defined.
169 //
170 // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2)
171 // is/isn't available.
172 // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
173 // are enabled.
174 // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
175 // expressions are/aren't available.
176 // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
177 // is/isn't available.
178 // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't
179 // enabled.
180 // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
181 // std::wstring does/doesn't work (Google Test can
182 // be used where std::wstring is unavailable).
183 // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
184 // compiler supports Microsoft's "Structured
185 // Exception Handling".
186 // GTEST_HAS_STREAM_REDIRECTION
187 // - Define it to 1/0 to indicate whether the
188 // platform supports I/O stream redirection using
189 // dup() and dup2().
190 // GTEST_LINKED_AS_SHARED_LIBRARY
191 // - Define to 1 when compiling tests that use
192 // Google Test as a shared library (known as
193 // DLL on Windows).
194 // GTEST_CREATE_SHARED_LIBRARY
195 // - Define to 1 when compiling Google Test itself
196 // as a shared library.
197 // GTEST_DEFAULT_DEATH_TEST_STYLE
198 // - The default value of --gtest_death_test_style.
199 // The legacy default has been "fast" in the open
200 // source version since 2008. The recommended value
201 // is "threadsafe", and can be set in
202 // custom/gtest-port.h.
203
204 // Platform-indicating macros
205 // --------------------------
206 //
207 // Macros indicating the platform on which Google Test is being used
208 // (a macro is defined to 1 if compiled on the given platform;
209 // otherwise UNDEFINED -- it's never defined to 0.). Google Test
210 // defines these macros automatically. Code outside Google Test MUST
211 // NOT define them.
212 //
213 // GTEST_OS_AIX - IBM AIX
214 // GTEST_OS_CYGWIN - Cygwin
215 // GTEST_OS_DRAGONFLY - DragonFlyBSD
216 // GTEST_OS_FREEBSD - FreeBSD
217 // GTEST_OS_FUCHSIA - Fuchsia
218 // GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD
219 // GTEST_OS_HAIKU - Haiku
220 // GTEST_OS_HPUX - HP-UX
221 // GTEST_OS_LINUX - Linux
222 // GTEST_OS_LINUX_ANDROID - Google Android
223 // GTEST_OS_MAC - Mac OS X
224 // GTEST_OS_IOS - iOS
225 // GTEST_OS_NACL - Google Native Client (NaCl)
226 // GTEST_OS_NETBSD - NetBSD
227 // GTEST_OS_OPENBSD - OpenBSD
228 // GTEST_OS_OS2 - OS/2
229 // GTEST_OS_QNX - QNX
230 // GTEST_OS_SOLARIS - Sun Solaris
231 // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
232 // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
233 // GTEST_OS_WINDOWS_MINGW - MinGW
234 // GTEST_OS_WINDOWS_MOBILE - Windows Mobile
235 // GTEST_OS_WINDOWS_PHONE - Windows Phone
236 // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
237 // GTEST_OS_ZOS - z/OS
238 //
239 // Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the
240 // most stable support. Since core members of the Google Test project
241 // don't have access to other platforms, support for them may be less
242 // stable. If you notice any problems on your platform, please notify
243 // googletestframework@googlegroups.com (patches for fixing them are
244 // even more welcome!).
245 //
246 // It is possible that none of the GTEST_OS_* macros are defined.
247
248 // Feature-indicating macros
249 // -------------------------
250 //
251 // Macros indicating which Google Test features are available (a macro
252 // is defined to 1 if the corresponding feature is supported;
253 // otherwise UNDEFINED -- it's never defined to 0.). Google Test
254 // defines these macros automatically. Code outside Google Test MUST
255 // NOT define them.
256 //
257 // These macros are public so that portable tests can be written.
258 // Such tests typically surround code using a feature with an #if
259 // which controls that code. For example:
260 //
261 // #if GTEST_HAS_DEATH_TEST
262 // EXPECT_DEATH(DoSomethingDeadly());
263 // #endif
264 //
265 // GTEST_HAS_DEATH_TEST - death tests
266 // GTEST_HAS_TYPED_TEST - typed tests
267 // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
268 // GTEST_IS_THREADSAFE - Google Test is thread-safe.
269 // GOOGLETEST_CM0007 DO NOT DELETE
270 // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
271 // GTEST_HAS_POSIX_RE (see above) which users can
272 // define themselves.
273 // GTEST_USES_SIMPLE_RE - our own simple regex is used;
274 // the above RE\b(s) are mutually exclusive.
275
276 // Misc public macros
277 // ------------------
278 //
279 // GTEST_FLAG(flag_name) - references the variable corresponding to
280 // the given Google Test flag.
281
282 // Internal utilities
283 // ------------------
284 //
285 // The following macros and utilities are for Google Test's INTERNAL
286 // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY.
287 //
288 // Macros for basic C++ coding:
289 // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
290 // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
291 // variable don't have to be used.
292 // GTEST_DISALLOW_ASSIGN_ - disables copy operator=.
293 // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
294 // GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=.
295 // GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
296 // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
297 // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
298 // suppressed (constant conditional).
299 // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
300 // is suppressed.
301 // GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
302 // UniversalPrinter<absl::any> specializations.
303 // GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
304 // or
305 // UniversalPrinter<absl::optional>
306 // specializations.
307 // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
308 // Matcher<absl::string_view>
309 // specializations.
310 // GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
311 // UniversalPrinter<absl::variant>
312 // specializations.
313 //
314 // Synchronization:
315 // Mutex, MutexLock, ThreadLocal, GetThreadCount()
316 // - synchronization primitives.
317 //
318 // Regular expressions:
319 // RE - a simple regular expression class using the POSIX
320 // Extended Regular Expression syntax on UNIX-like platforms
321 // GOOGLETEST_CM0008 DO NOT DELETE
322 // or a reduced regular exception syntax on other
323 // platforms, including Windows.
324 // Logging:
325 // GTEST_LOG_() - logs messages at the specified severity level.
326 // LogToStderr() - directs all log messages to stderr.
327 // FlushInfoLog() - flushes informational log messages.
328 //
329 // Stdout and stderr capturing:
330 // CaptureStdout() - starts capturing stdout.
331 // GetCapturedStdout() - stops capturing stdout and returns the captured
332 // string.
333 // CaptureStderr() - starts capturing stderr.
334 // GetCapturedStderr() - stops capturing stderr and returns the captured
335 // string.
336 //
337 // Integer types:
338 // TypeWithSize - maps an integer to a int type.
339 // TimeInMillis - integers of known sizes.
340 // BiggestInt - the biggest signed integer type.
341 //
342 // Command-line utilities:
343 // GTEST_DECLARE_*() - declares a flag.
344 // GTEST_DEFINE_*() - defines a flag.
345 // GetInjectableArgvs() - returns the command line as a vector of strings.
346 //
347 // Environment variable utilities:
348 // GetEnv() - gets the value of an environment variable.
349 // BoolFromGTestEnv() - parses a bool environment variable.
350 // Int32FromGTestEnv() - parses an int32_t environment variable.
351 // StringFromGTestEnv() - parses a string environment variable.
352 //
353 // Deprecation warnings:
354 // GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
355 // deprecated; calling a marked function
356 // should generate a compiler warning
357
358 #include <ctype.h> // for isspace, etc
359 #include <stddef.h> // for ptrdiff_t
360 #include <stdio.h>
361 #include <stdlib.h>
362 #include <string.h>
363
364 #include <cerrno>
365 #include <cstdint>
366 #include <limits>
367 #include <type_traits>
368
369 #ifndef _WIN32_WCE
370 # include <sys/types.h>
371 # include <sys/stat.h>
372 #endif // !_WIN32_WCE
373
374 #if defined __APPLE__
375 # include <AvailabilityMacros.h>
376 # include <TargetConditionals.h>
377 #endif
378
379 #include <iostream> // NOLINT
380 #include <locale>
381 #include <memory>
382 #include <string> // NOLINT
383 #include <tuple>
384 #include <vector> // NOLINT
385
386 // Copyright 2015, Google Inc.
387 // All rights reserved.
388 //
389 // Redistribution and use in source and binary forms, with or without
390 // modification, are permitted provided that the following conditions are
391 // met:
392 //
393 // * Redistributions of source code must retain the above copyright
394 // notice, this list of conditions and the following disclaimer.
395 // * Redistributions in binary form must reproduce the above
396 // copyright notice, this list of conditions and the following disclaimer
397 // in the documentation and/or other materials provided with the
398 // distribution.
399 // * Neither the name of Google Inc. nor the names of its
400 // contributors may be used to endorse or promote products derived from
401 // this software without specific prior written permission.
402 //
403 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
404 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
405 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
406 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
407 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
408 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
409 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
410 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
411 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
412 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
413 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
414 //
415 // Injection point for custom user configurations. See README for details
416 //
417 // ** Custom implementation starts here **
418
419 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
420 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
421
422 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
423 // Copyright 2015, Google Inc.
424 // All rights reserved.
425 //
426 // Redistribution and use in source and binary forms, with or without
427 // modification, are permitted provided that the following conditions are
428 // met:
429 //
430 // * Redistributions of source code must retain the above copyright
431 // notice, this list of conditions and the following disclaimer.
432 // * Redistributions in binary form must reproduce the above
433 // copyright notice, this list of conditions and the following disclaimer
434 // in the documentation and/or other materials provided with the
435 // distribution.
436 // * Neither the name of Google Inc. nor the names of its
437 // contributors may be used to endorse or promote products derived from
438 // this software without specific prior written permission.
439 //
440 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
441 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
442 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
443 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
444 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
445 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
446 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
447 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
448 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
449 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
450 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
451 //
452 // The Google C++ Testing and Mocking Framework (Google Test)
453 //
454 // This header file defines the GTEST_OS_* macro.
455 // It is separate from gtest-port.h so that custom/gtest-port.h can include it.
456
457 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
458 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
459
460 // Determines the platform on which Google Test is compiled.
461 #ifdef __CYGWIN__
462 # define GTEST_OS_CYGWIN 1
463 # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
464 # define GTEST_OS_WINDOWS_MINGW 1
465 # define GTEST_OS_WINDOWS 1
466 #elif defined _WIN32
467 # define GTEST_OS_WINDOWS 1
468 # ifdef _WIN32_WCE
469 # define GTEST_OS_WINDOWS_MOBILE 1
470 # elif defined(WINAPI_FAMILY)
471 # include <winapifamily.h>
472 # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
473 # define GTEST_OS_WINDOWS_DESKTOP 1
474 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
475 # define GTEST_OS_WINDOWS_PHONE 1
476 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
477 # define GTEST_OS_WINDOWS_RT 1
478 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
479 # define GTEST_OS_WINDOWS_PHONE 1
480 # define GTEST_OS_WINDOWS_TV_TITLE 1
481 # else
482 // WINAPI_FAMILY defined but no known partition matched.
483 // Default to desktop.
484 # define GTEST_OS_WINDOWS_DESKTOP 1
485 # endif
486 # else
487 # define GTEST_OS_WINDOWS_DESKTOP 1
488 # endif // _WIN32_WCE
489 #elif defined __OS2__
490 # define GTEST_OS_OS2 1
491 #elif defined __APPLE__
492 # define GTEST_OS_MAC 1
493 # include <TargetConditionals.h>
494 # if TARGET_OS_IPHONE
495 # define GTEST_OS_IOS 1
496 # endif
497 #elif defined __DragonFly__
498 # define GTEST_OS_DRAGONFLY 1
499 #elif defined __FreeBSD__
500 # define GTEST_OS_FREEBSD 1
501 #elif defined __Fuchsia__
502 # define GTEST_OS_FUCHSIA 1
503 #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
504 # define GTEST_OS_GNU_KFREEBSD 1
505 #elif defined __linux__
506 # define GTEST_OS_LINUX 1
507 # if defined __ANDROID__
508 # define GTEST_OS_LINUX_ANDROID 1
509 # endif
510 #elif defined __MVS__
511 # define GTEST_OS_ZOS 1
512 #elif defined(__sun) && defined(__SVR4)
513 # define GTEST_OS_SOLARIS 1
514 #elif defined(_AIX)
515 # define GTEST_OS_AIX 1
516 #elif defined(__hpux)
517 # define GTEST_OS_HPUX 1
518 #elif defined __native_client__
519 # define GTEST_OS_NACL 1
520 #elif defined __NetBSD__
521 # define GTEST_OS_NETBSD 1
522 #elif defined __OpenBSD__
523 # define GTEST_OS_OPENBSD 1
524 #elif defined __QNX__
525 # define GTEST_OS_QNX 1
526 #elif defined(__HAIKU__)
527 #define GTEST_OS_HAIKU 1
528 #elif defined ESP8266
529 #define GTEST_OS_ESP8266 1
530 #elif defined ESP32
531 #define GTEST_OS_ESP32 1
532 #elif defined(__XTENSA__)
533 #define GTEST_OS_XTENSA 1
534 #endif // __CYGWIN__
535
536 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
537
538 #if !defined(GTEST_DEV_EMAIL_)
539 # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
540 # define GTEST_FLAG_PREFIX_ "gtest_"
541 # define GTEST_FLAG_PREFIX_DASH_ "gtest-"
542 # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
543 # define GTEST_NAME_ "Google Test"
544 # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
545 #endif // !defined(GTEST_DEV_EMAIL_)
546
547 #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
548 # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
549 #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
550
551 // Determines the version of gcc that is used to compile this.
552 #ifdef __GNUC__
553 // 40302 means version 4.3.2.
554 # define GTEST_GCC_VER_ \
555 (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
556 #endif // __GNUC__
557
558 // Macros for disabling Microsoft Visual C++ warnings.
559 //
560 // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
561 // /* code that triggers warnings C4800 and C4385 */
562 // GTEST_DISABLE_MSC_WARNINGS_POP_()
563 #if defined(_MSC_VER)
564 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
565 __pragma(warning(push)) \
566 __pragma(warning(disable: warnings))
567 # define GTEST_DISABLE_MSC_WARNINGS_POP_() \
568 __pragma(warning(pop))
569 #else
570 // Not all compilers are MSVC
571 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
572 # define GTEST_DISABLE_MSC_WARNINGS_POP_()
573 #endif
574
575 // Clang on Windows does not understand MSVC's pragma warning.
576 // We need clang-specific way to disable function deprecation warning.
577 #ifdef __clang__
578 # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
579 _Pragma("clang diagnostic push") \
580 _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
581 _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
582 #define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
583 _Pragma("clang diagnostic pop")
584 #else
585 # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
586 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
587 # define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
588 GTEST_DISABLE_MSC_WARNINGS_POP_()
589 #endif
590
591 // Brings in definitions for functions used in the testing::internal::posix
592 // namespace (read, write, close, chdir, isatty, stat). We do not currently
593 // use them on Windows Mobile.
594 #if GTEST_OS_WINDOWS
595 # if !GTEST_OS_WINDOWS_MOBILE
596 # include <direct.h>
597 # include <io.h>
598 # endif
599 // In order to avoid having to include <windows.h>, use forward declaration
600 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
601 // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
602 // separate (equivalent) structs, instead of using typedef
603 typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
604 #else
605 // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
606 // This assumption is verified by
607 // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
608 typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
609 #endif
610 #elif GTEST_OS_XTENSA
611 #include <unistd.h>
612 // Xtensa toolchains define strcasecmp in the string.h header instead of
613 // strings.h. string.h is already included.
614 #else
615 // This assumes that non-Windows OSes provide unistd.h. For OSes where this
616 // is not the case, we need to include headers that provide the functions
617 // mentioned above.
618 # include <unistd.h>
619 # include <strings.h>
620 #endif // GTEST_OS_WINDOWS
621
622 #if GTEST_OS_LINUX_ANDROID
623 // Used to define __ANDROID_API__ matching the target NDK API level.
624 # include <android/api-level.h> // NOLINT
625 #endif
626
627 // Defines this to true if and only if Google Test can use POSIX regular
628 // expressions.
629 #ifndef GTEST_HAS_POSIX_RE
630 # if GTEST_OS_LINUX_ANDROID
631 // On Android, <regex.h> is only available starting with Gingerbread.
632 # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
633 # else
634 #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
635 # endif
636 #endif
637
638 #if GTEST_USES_PCRE
639 // The appropriate headers have already been included.
640
641 #elif GTEST_HAS_POSIX_RE
642
643 // On some platforms, <regex.h> needs someone to define size_t, and
644 // won't compile otherwise. We can #include it here as we already
645 // included <stdlib.h>, which is guaranteed to define size_t through
646 // <stddef.h>.
647 # include <regex.h> // NOLINT
648
649 # define GTEST_USES_POSIX_RE 1
650
651 #elif GTEST_OS_WINDOWS
652
653 // <regex.h> is not available on Windows. Use our own simple regex
654 // implementation instead.
655 # define GTEST_USES_SIMPLE_RE 1
656
657 #else
658
659 // <regex.h> may not be available on this platform. Use our own
660 // simple regex implementation instead.
661 # define GTEST_USES_SIMPLE_RE 1
662
663 #endif // GTEST_USES_PCRE
664
665 #ifndef GTEST_HAS_EXCEPTIONS
666 // The user didn't tell us whether exceptions are enabled, so we need
667 // to figure it out.
668 # if defined(_MSC_VER) && defined(_CPPUNWIND)
669 // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.
670 # define GTEST_HAS_EXCEPTIONS 1
671 # elif defined(__BORLANDC__)
672 // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS
673 // macro to enable exceptions, so we'll do the same.
674 // Assumes that exceptions are enabled by default.
675 # ifndef _HAS_EXCEPTIONS
676 # define _HAS_EXCEPTIONS 1
677 # endif // _HAS_EXCEPTIONS
678 # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
679 # elif defined(__clang__)
680 // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
681 // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
682 // there can be cleanups for ObjC exceptions which also need cleanups, even if
683 // C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which
684 // checks for C++ exceptions starting at clang r206352, but which checked for
685 // cleanups prior to that. To reliably check for C++ exception availability with
686 // clang, check for
687 // __EXCEPTIONS && __has_feature(cxx_exceptions).
688 # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
689 # elif defined(__GNUC__) && __EXCEPTIONS
690 // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
691 # define GTEST_HAS_EXCEPTIONS 1
692 # elif defined(__SUNPRO_CC)
693 // Sun Pro CC supports exceptions. However, there is no compile-time way of
694 // detecting whether they are enabled or not. Therefore, we assume that
695 // they are enabled unless the user tells us otherwise.
696 # define GTEST_HAS_EXCEPTIONS 1
697 # elif defined(__IBMCPP__) && __EXCEPTIONS
698 // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
699 # define GTEST_HAS_EXCEPTIONS 1
700 # elif defined(__HP_aCC)
701 // Exception handling is in effect by default in HP aCC compiler. It has to
702 // be turned of by +noeh compiler option if desired.
703 # define GTEST_HAS_EXCEPTIONS 1
704 # else
705 // For other compilers, we assume exceptions are disabled to be
706 // conservative.
707 # define GTEST_HAS_EXCEPTIONS 0
708 # endif // defined(_MSC_VER) || defined(__BORLANDC__)
709 #endif // GTEST_HAS_EXCEPTIONS
710
711 #ifndef GTEST_HAS_STD_WSTRING
712 // The user didn't tell us whether ::std::wstring is available, so we need
713 // to figure it out.
714 // Cygwin 1.7 and below doesn't support ::std::wstring.
715 // Solaris' libc++ doesn't support it either. Android has
716 // no support for it at least as recent as Froyo (2.2).
717 #define GTEST_HAS_STD_WSTRING \
718 (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
719 GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
720
721 #endif // GTEST_HAS_STD_WSTRING
722
723 // Determines whether RTTI is available.
724 #ifndef GTEST_HAS_RTTI
725 // The user didn't tell us whether RTTI is enabled, so we need to
726 // figure it out.
727
728 # ifdef _MSC_VER
729
730 #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled.
731 # define GTEST_HAS_RTTI 1
732 # else
733 # define GTEST_HAS_RTTI 0
734 # endif
735
736 // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
737 // enabled.
738 # elif defined(__GNUC__)
739
740 # ifdef __GXX_RTTI
741 // When building against STLport with the Android NDK and with
742 // -frtti -fno-exceptions, the build fails at link time with undefined
743 // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
744 // so disable RTTI when detected.
745 # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
746 !defined(__EXCEPTIONS)
747 # define GTEST_HAS_RTTI 0
748 # else
749 # define GTEST_HAS_RTTI 1
750 # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
751 # else
752 # define GTEST_HAS_RTTI 0
753 # endif // __GXX_RTTI
754
755 // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
756 // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
757 // first version with C++ support.
758 # elif defined(__clang__)
759
760 # define GTEST_HAS_RTTI __has_feature(cxx_rtti)
761
762 // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
763 // both the typeid and dynamic_cast features are present.
764 # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
765
766 # ifdef __RTTI_ALL__
767 # define GTEST_HAS_RTTI 1
768 # else
769 # define GTEST_HAS_RTTI 0
770 # endif
771
772 # else
773
774 // For all other compilers, we assume RTTI is enabled.
775 # define GTEST_HAS_RTTI 1
776
777 # endif // _MSC_VER
778
779 #endif // GTEST_HAS_RTTI
780
781 // It's this header's responsibility to #include <typeinfo> when RTTI
782 // is enabled.
783 #if GTEST_HAS_RTTI
784 # include <typeinfo>
785 #endif
786
787 // Determines whether Google Test can use the pthreads library.
788 #ifndef GTEST_HAS_PTHREAD
789 // The user didn't tell us explicitly, so we make reasonable assumptions about
790 // which platforms have pthreads support.
791 //
792 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
793 // to your compiler flags.
794 #define GTEST_HAS_PTHREAD \
795 (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
796 GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
797 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
798 GTEST_OS_HAIKU)
799 #endif // GTEST_HAS_PTHREAD
800
801 #if GTEST_HAS_PTHREAD
802 // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
803 // true.
804 # include <pthread.h> // NOLINT
805
806 // For timespec and nanosleep, used below.
807 # include <time.h> // NOLINT
808 #endif
809
810 // Determines whether clone(2) is supported.
811 // Usually it will only be available on Linux, excluding
812 // Linux on the Itanium architecture.
813 // Also see http://linux.die.net/man/2/clone.
814 #ifndef GTEST_HAS_CLONE
815 // The user didn't tell us, so we need to figure it out.
816
817 # if GTEST_OS_LINUX && !defined(__ia64__)
818 # if GTEST_OS_LINUX_ANDROID
819 // On Android, clone() became available at different API levels for each 32-bit
820 // architecture.
821 # if defined(__LP64__) || \
822 (defined(__arm__) && __ANDROID_API__ >= 9) || \
823 (defined(__mips__) && __ANDROID_API__ >= 12) || \
824 (defined(__i386__) && __ANDROID_API__ >= 17)
825 # define GTEST_HAS_CLONE 1
826 # else
827 # define GTEST_HAS_CLONE 0
828 # endif
829 # else
830 # define GTEST_HAS_CLONE 1
831 # endif
832 # else
833 # define GTEST_HAS_CLONE 0
834 # endif // GTEST_OS_LINUX && !defined(__ia64__)
835
836 #endif // GTEST_HAS_CLONE
837
838 // Determines whether to support stream redirection. This is used to test
839 // output correctness and to implement death tests.
840 #ifndef GTEST_HAS_STREAM_REDIRECTION
841 // By default, we assume that stream redirection is supported on all
842 // platforms except known mobile ones.
843 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
844 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
845 # define GTEST_HAS_STREAM_REDIRECTION 0
846 # else
847 # define GTEST_HAS_STREAM_REDIRECTION 1
848 # endif // !GTEST_OS_WINDOWS_MOBILE
849 #endif // GTEST_HAS_STREAM_REDIRECTION
850
851 // Determines whether to support death tests.
852 // pops up a dialog window that cannot be suppressed programmatically.
853 #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
854 (GTEST_OS_MAC && !GTEST_OS_IOS) || \
855 (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
856 GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
857 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
858 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU)
859 # define GTEST_HAS_DEATH_TEST 1
860 #endif
861
862 // Determines whether to support type-driven tests.
863
864 // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
865 // Sun Pro CC, IBM Visual Age, and HP aCC support.
866 #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
867 defined(__IBMCPP__) || defined(__HP_aCC)
868 # define GTEST_HAS_TYPED_TEST 1
869 # define GTEST_HAS_TYPED_TEST_P 1
870 #endif
871
872 // Determines whether the system compiler uses UTF-16 for encoding wide strings.
873 #define GTEST_WIDE_STRING_USES_UTF16_ \
874 (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
875
876 // Determines whether test results can be streamed to a socket.
877 #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
878 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD
879 # define GTEST_CAN_STREAM_RESULTS_ 1
880 #endif
881
882 // Defines some utility macros.
883
884 // The GNU compiler emits a warning if nested "if" statements are followed by
885 // an "else" statement and braces are not used to explicitly disambiguate the
886 // "else" binding. This leads to problems with code like:
887 //
888 // if (gate)
889 // ASSERT_*(condition) << "Some message";
890 //
891 // The "switch (0) case 0:" idiom is used to suppress this.
892 #ifdef __INTEL_COMPILER
893 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
894 #else
895 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
896 #endif
897
898 // Use this annotation at the end of a struct/class definition to
899 // prevent the compiler from optimizing away instances that are never
900 // used. This is useful when all interesting logic happens inside the
901 // c'tor and / or d'tor. Example:
902 //
903 // struct Foo {
904 // Foo() { ... }
905 // } GTEST_ATTRIBUTE_UNUSED_;
906 //
907 // Also use it after a variable or parameter declaration to tell the
908 // compiler the variable/parameter does not have to be used.
909 #if defined(__GNUC__) && !defined(COMPILER_ICC)
910 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
911 #elif defined(__clang__)
912 # if __has_attribute(unused)
913 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
914 # endif
915 #endif
916 #ifndef GTEST_ATTRIBUTE_UNUSED_
917 # define GTEST_ATTRIBUTE_UNUSED_
918 #endif
919
920 // Use this annotation before a function that takes a printf format string.
921 #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
922 # if defined(__MINGW_PRINTF_FORMAT)
923 // MinGW has two different printf implementations. Ensure the format macro
924 // matches the selected implementation. See
925 // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
926 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
927 __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
928 first_to_check)))
929 # else
930 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
931 __attribute__((__format__(__printf__, string_index, first_to_check)))
932 # endif
933 #else
934 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
935 #endif
936
937
938 // A macro to disallow copy operator=
939 // This should be used in the private: declarations for a class.
940 #define GTEST_DISALLOW_ASSIGN_(type) \
941 type& operator=(type const &) = delete
942
943 // A macro to disallow copy constructor and operator=
944 // This should be used in the private: declarations for a class.
945 #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
946 type(type const&) = delete; \
947 type& operator=(type const&) = delete
948
949 // A macro to disallow move operator=
950 // This should be used in the private: declarations for a class.
951 #define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
952 type& operator=(type &&) noexcept = delete
953
954 // A macro to disallow move constructor and operator=
955 // This should be used in the private: declarations for a class.
956 #define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
957 type(type&&) noexcept = delete; \
958 type& operator=(type&&) noexcept = delete
959
960 // Tell the compiler to warn about unused return values for functions declared
961 // with this macro. The macro should be used on function declarations
962 // following the argument list:
963 //
964 // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
965 #if defined(__GNUC__) && !defined(COMPILER_ICC)
966 # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
967 #else
968 # define GTEST_MUST_USE_RESULT_
969 #endif // __GNUC__ && !COMPILER_ICC
970
971 // MS C++ compiler emits warning when a conditional expression is compile time
972 // constant. In some contexts this warning is false positive and needs to be
973 // suppressed. Use the following two macros in such cases:
974 //
975 // GTEST_INTENTIONAL_CONST_COND_PUSH_()
976 // while (true) {
977 // GTEST_INTENTIONAL_CONST_COND_POP_()
978 // }
979 # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
980 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
981 # define GTEST_INTENTIONAL_CONST_COND_POP_() \
982 GTEST_DISABLE_MSC_WARNINGS_POP_()
983
984 // Determine whether the compiler supports Microsoft's Structured Exception
985 // Handling. This is supported by several Windows compilers but generally
986 // does not exist on any other system.
987 #ifndef GTEST_HAS_SEH
988 // The user didn't tell us, so we need to figure it out.
989
990 # if defined(_MSC_VER) || defined(__BORLANDC__)
991 // These two compilers are known to support SEH.
992 # define GTEST_HAS_SEH 1
993 # else
994 // Assume no SEH.
995 # define GTEST_HAS_SEH 0
996 # endif
997
998 #endif // GTEST_HAS_SEH
999
1000 #ifndef GTEST_IS_THREADSAFE
1001
1002 #define GTEST_IS_THREADSAFE \
1003 (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
1004 (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
1005 GTEST_HAS_PTHREAD)
1006
1007 #endif // GTEST_IS_THREADSAFE
1008
1009 // GTEST_API_ qualifies all symbols that must be exported. The definitions below
1010 // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in
1011 // gtest/internal/custom/gtest-port.h
1012 #ifndef GTEST_API_
1013
1014 #ifdef _MSC_VER
1015 # if GTEST_LINKED_AS_SHARED_LIBRARY
1016 # define GTEST_API_ __declspec(dllimport)
1017 # elif GTEST_CREATE_SHARED_LIBRARY
1018 # define GTEST_API_ __declspec(dllexport)
1019 # endif
1020 #elif __GNUC__ >= 4 || defined(__clang__)
1021 # define GTEST_API_ __attribute__((visibility ("default")))
1022 #endif // _MSC_VER
1023
1024 #endif // GTEST_API_
1025
1026 #ifndef GTEST_API_
1027 # define GTEST_API_
1028 #endif // GTEST_API_
1029
1030 #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
1031 # define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
1032 #endif // GTEST_DEFAULT_DEATH_TEST_STYLE
1033
1034 #ifdef __GNUC__
1035 // Ask the compiler to never inline a given function.
1036 # define GTEST_NO_INLINE_ __attribute__((noinline))
1037 #else
1038 # define GTEST_NO_INLINE_
1039 #endif
1040
1041 // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
1042 #if !defined(GTEST_HAS_CXXABI_H_)
1043 # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
1044 # define GTEST_HAS_CXXABI_H_ 1
1045 # else
1046 # define GTEST_HAS_CXXABI_H_ 0
1047 # endif
1048 #endif
1049
1050 // A function level attribute to disable checking for use of uninitialized
1051 // memory when built with MemorySanitizer.
1052 #if defined(__clang__)
1053 # if __has_feature(memory_sanitizer)
1054 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
1055 __attribute__((no_sanitize_memory))
1056 # else
1057 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1058 # endif // __has_feature(memory_sanitizer)
1059 #else
1060 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1061 #endif // __clang__
1062
1063 // A function level attribute to disable AddressSanitizer instrumentation.
1064 #if defined(__clang__)
1065 # if __has_feature(address_sanitizer)
1066 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
1067 __attribute__((no_sanitize_address))
1068 # else
1069 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1070 # endif // __has_feature(address_sanitizer)
1071 #else
1072 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1073 #endif // __clang__
1074
1075 // A function level attribute to disable HWAddressSanitizer instrumentation.
1076 #if defined(__clang__)
1077 # if __has_feature(hwaddress_sanitizer)
1078 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
1079 __attribute__((no_sanitize("hwaddress")))
1080 # else
1081 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1082 # endif // __has_feature(hwaddress_sanitizer)
1083 #else
1084 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1085 #endif // __clang__
1086
1087 // A function level attribute to disable ThreadSanitizer instrumentation.
1088 #if defined(__clang__)
1089 # if __has_feature(thread_sanitizer)
1090 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
1091 __attribute__((no_sanitize_thread))
1092 # else
1093 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1094 # endif // __has_feature(thread_sanitizer)
1095 #else
1096 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1097 #endif // __clang__
1098
1099 namespace testing {
1100
1101 class Message;
1102
1103 // Legacy imports for backwards compatibility.
1104 // New code should use std:: names directly.
1105 using std::get;
1106 using std::make_tuple;
1107 using std::tuple;
1108 using std::tuple_element;
1109 using std::tuple_size;
1110
1111 namespace internal {
1112
1113 // A secret type that Google Test users don't know about. It has no
1114 // definition on purpose. Therefore it's impossible to create a
1115 // Secret object, which is what we want.
1116 class Secret;
1117
1118 // The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
1119 // time expression is true (in new code, use static_assert instead). For
1120 // example, you could use it to verify the size of a static array:
1121 //
1122 // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
1123 // names_incorrect_size);
1124 //
1125 // The second argument to the macro must be a valid C++ identifier. If the
1126 // expression is false, compiler will issue an error containing this identifier.
1127 #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
1128
1129 // A helper for suppressing warnings on constant condition. It just
1130 // returns 'condition'.
1131 GTEST_API_ bool IsTrue(bool condition);
1132
1133 // Defines RE.
1134
1135 #if GTEST_USES_PCRE
1136 // if used, PCRE is injected by custom/gtest-port.h
1137 #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
1138
1139 // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
1140 // Regular Expression syntax.
1141 class GTEST_API_ RE {
1142 public:
1143 // A copy constructor is required by the Standard to initialize object
1144 // references from r-values.
1145 RE(const RE& other) { Init(other.pattern()); }
1146
1147 // Constructs an RE from a string.
1148 RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
1149
1150 RE(const char* regex) { Init(regex); } // NOLINT
1151 ~RE();
1152
1153 // Returns the string representation of the regex.
1154 const char* pattern() const { return pattern_; }
1155
1156 // FullMatch(str, re) returns true if and only if regular expression re
1157 // matches the entire str.
1158 // PartialMatch(str, re) returns true if and only if regular expression re
1159 // matches a substring of str (including str itself).
1160 static bool FullMatch(const ::std::string& str, const RE& re) {
1161 return FullMatch(str.c_str(), re);
1162 }
1163 static bool PartialMatch(const ::std::string& str, const RE& re) {
1164 return PartialMatch(str.c_str(), re);
1165 }
1166
1167 static bool FullMatch(const char* str, const RE& re);
1168 static bool PartialMatch(const char* str, const RE& re);
1169
1170 private:
1171 void Init(const char* regex);
1172 const char* pattern_;
1173 bool is_valid_;
1174
1175 # if GTEST_USES_POSIX_RE
1176
1177 regex_t full_regex_; // For FullMatch().
1178 regex_t partial_regex_; // For PartialMatch().
1179
1180 # else // GTEST_USES_SIMPLE_RE
1181
1182 const char* full_pattern_; // For FullMatch();
1183
1184 # endif
1185 };
1186
1187 #endif // GTEST_USES_PCRE
1188
1189 // Formats a source file path and a line number as they would appear
1190 // in an error message from the compiler used to compile this code.
1191 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
1192
1193 // Formats a file location for compiler-independent XML output.
1194 // Although this function is not platform dependent, we put it next to
1195 // FormatFileLocation in order to contrast the two functions.
1196 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
1197 int line);
1198
1199 // Defines logging utilities:
1200 // GTEST_LOG_(severity) - logs messages at the specified severity level. The
1201 // message itself is streamed into the macro.
1202 // LogToStderr() - directs all log messages to stderr.
1203 // FlushInfoLog() - flushes informational log messages.
1204
1205 enum GTestLogSeverity {
1206 GTEST_INFO,
1207 GTEST_WARNING,
1208 GTEST_ERROR,
1209 GTEST_FATAL
1210 };
1211
1212 // Formats log entry severity, provides a stream object for streaming the
1213 // log message, and terminates the message with a newline when going out of
1214 // scope.
1215 class GTEST_API_ GTestLog {
1216 public:
1217 GTestLog(GTestLogSeverity severity, const char* file, int line);
1218
1219 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1220 ~GTestLog();
1221
1222 ::std::ostream& GetStream() { return ::std::cerr; }
1223
1224 private:
1225 const GTestLogSeverity severity_;
1226
1227 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
1228 };
1229
1230 #if !defined(GTEST_LOG_)
1231
1232 # define GTEST_LOG_(severity) \
1233 ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
1234 __FILE__, __LINE__).GetStream()
1235
1236 inline void LogToStderr() {}
1237 inline void FlushInfoLog() { fflush(nullptr); }
1238
1239 #endif // !defined(GTEST_LOG_)
1240
1241 #if !defined(GTEST_CHECK_)
1242 // INTERNAL IMPLEMENTATION - DO NOT USE.
1243 //
1244 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
1245 // is not satisfied.
1246 // Synopsys:
1247 // GTEST_CHECK_(boolean_condition);
1248 // or
1249 // GTEST_CHECK_(boolean_condition) << "Additional message";
1250 //
1251 // This checks the condition and if the condition is not satisfied
1252 // it prints message about the condition violation, including the
1253 // condition itself, plus additional message streamed into it, if any,
1254 // and then it aborts the program. It aborts the program irrespective of
1255 // whether it is built in the debug mode or not.
1256 # define GTEST_CHECK_(condition) \
1257 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1258 if (::testing::internal::IsTrue(condition)) \
1259 ; \
1260 else \
1261 GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
1262 #endif // !defined(GTEST_CHECK_)
1263
1264 // An all-mode assert to verify that the given POSIX-style function
1265 // call returns 0 (indicating success). Known limitation: this
1266 // doesn't expand to a balanced 'if' statement, so enclose the macro
1267 // in {} if you need to use it as the only statement in an 'if'
1268 // branch.
1269 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
1270 if (const int gtest_error = (posix_call)) \
1271 GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
1272 << gtest_error
1273
1274 // Transforms "T" into "const T&" according to standard reference collapsing
1275 // rules (this is only needed as a backport for C++98 compilers that do not
1276 // support reference collapsing). Specifically, it transforms:
1277 //
1278 // char ==> const char&
1279 // const char ==> const char&
1280 // char& ==> char&
1281 // const char& ==> const char&
1282 //
1283 // Note that the non-const reference will not have "const" added. This is
1284 // standard, and necessary so that "T" can always bind to "const T&".
1285 template <typename T>
1286 struct ConstRef { typedef const T& type; };
1287 template <typename T>
1288 struct ConstRef<T&> { typedef T& type; };
1289
1290 // The argument T must depend on some template parameters.
1291 #define GTEST_REFERENCE_TO_CONST_(T) \
1292 typename ::testing::internal::ConstRef<T>::type
1293
1294 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1295 //
1296 // Use ImplicitCast_ as a safe version of static_cast for upcasting in
1297 // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
1298 // const Foo*). When you use ImplicitCast_, the compiler checks that
1299 // the cast is safe. Such explicit ImplicitCast_s are necessary in
1300 // surprisingly many situations where C++ demands an exact type match
1301 // instead of an argument type convertable to a target type.
1302 //
1303 // The syntax for using ImplicitCast_ is the same as for static_cast:
1304 //
1305 // ImplicitCast_<ToType>(expr)
1306 //
1307 // ImplicitCast_ would have been part of the C++ standard library,
1308 // but the proposal was submitted too late. It will probably make
1309 // its way into the language in the future.
1310 //
1311 // This relatively ugly name is intentional. It prevents clashes with
1312 // similar functions users may have (e.g., implicit_cast). The internal
1313 // namespace alone is not enough because the function can be found by ADL.
1314 template<typename To>
1315 inline To ImplicitCast_(To x) { return x; }
1316
1317 // When you upcast (that is, cast a pointer from type Foo to type
1318 // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
1319 // always succeed. When you downcast (that is, cast a pointer from
1320 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
1321 // how do you know the pointer is really of type SubclassOfFoo? It
1322 // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
1323 // when you downcast, you should use this macro. In debug mode, we
1324 // use dynamic_cast<> to double-check the downcast is legal (we die
1325 // if it's not). In normal mode, we do the efficient static_cast<>
1326 // instead. Thus, it's important to test in debug mode to make sure
1327 // the cast is legal!
1328 // This is the only place in the code we should use dynamic_cast<>.
1329 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
1330 // do RTTI (eg code like this:
1331 // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
1332 // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
1333 // You should design the code some other way not to need this.
1334 //
1335 // This relatively ugly name is intentional. It prevents clashes with
1336 // similar functions users may have (e.g., down_cast). The internal
1337 // namespace alone is not enough because the function can be found by ADL.
1338 template<typename To, typename From> // use like this: DownCast_<T*>(foo);
1339 inline To DownCast_(From* f) { // so we only accept pointers
1340 // Ensures that To is a sub-type of From *. This test is here only
1341 // for compile-time type checking, and has no overhead in an
1342 // optimized build at run-time, as it will be optimized away
1343 // completely.
1344 GTEST_INTENTIONAL_CONST_COND_PUSH_()
1345 if (false) {
1346 GTEST_INTENTIONAL_CONST_COND_POP_()
1347 const To to = nullptr;
1348 ::testing::internal::ImplicitCast_<From*>(to);
1349 }
1350
1351 #if GTEST_HAS_RTTI
1352 // RTTI: debug mode only!
1353 GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
1354 #endif
1355 return static_cast<To>(f);
1356 }
1357
1358 // Downcasts the pointer of type Base to Derived.
1359 // Derived must be a subclass of Base. The parameter MUST
1360 // point to a class of type Derived, not any subclass of it.
1361 // When RTTI is available, the function performs a runtime
1362 // check to enforce this.
1363 template <class Derived, class Base>
1364 Derived* CheckedDowncastToActualType(Base* base) {
1365 #if GTEST_HAS_RTTI
1366 GTEST_CHECK_(typeid(*base) == typeid(Derived));
1367 #endif
1368
1369 #if GTEST_HAS_DOWNCAST_
1370 return ::down_cast<Derived*>(base);
1371 #elif GTEST_HAS_RTTI
1372 return dynamic_cast<Derived*>(base); // NOLINT
1373 #else
1374 return static_cast<Derived*>(base); // Poor man's downcast.
1375 #endif
1376 }
1377
1378 #if GTEST_HAS_STREAM_REDIRECTION
1379
1380 // Defines the stderr capturer:
1381 // CaptureStdout - starts capturing stdout.
1382 // GetCapturedStdout - stops capturing stdout and returns the captured string.
1383 // CaptureStderr - starts capturing stderr.
1384 // GetCapturedStderr - stops capturing stderr and returns the captured string.
1385 //
1386 GTEST_API_ void CaptureStdout();
1387 GTEST_API_ std::string GetCapturedStdout();
1388 GTEST_API_ void CaptureStderr();
1389 GTEST_API_ std::string GetCapturedStderr();
1390
1391 #endif // GTEST_HAS_STREAM_REDIRECTION
1392 // Returns the size (in bytes) of a file.
1393 GTEST_API_ size_t GetFileSize(FILE* file);
1394
1395 // Reads the entire content of a file as a string.
1396 GTEST_API_ std::string ReadEntireFile(FILE* file);
1397
1398 // All command line arguments.
1399 GTEST_API_ std::vector<std::string> GetArgvs();
1400
1401 #if GTEST_HAS_DEATH_TEST
1402
1403 std::vector<std::string> GetInjectableArgvs();
1404 // Deprecated: pass the args vector by value instead.
1405 void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
1406 void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
1407 void ClearInjectableArgvs();
1408
1409 #endif // GTEST_HAS_DEATH_TEST
1410
1411 // Defines synchronization primitives.
1412 #if GTEST_IS_THREADSAFE
1413 # if GTEST_HAS_PTHREAD
1414 // Sleeps for (roughly) n milliseconds. This function is only for testing
1415 // Google Test's own constructs. Don't use it in user tests, either
1416 // directly or indirectly.
1417 inline void SleepMilliseconds(int n) {
1418 const timespec time = {
1419 0, // 0 seconds.
1420 n * 1000L * 1000L, // And n ms.
1421 };
1422 nanosleep(&time, nullptr);
1423 }
1424 # endif // GTEST_HAS_PTHREAD
1425
1426 # if GTEST_HAS_NOTIFICATION_
1427 // Notification has already been imported into the namespace.
1428 // Nothing to do here.
1429
1430 # elif GTEST_HAS_PTHREAD
1431 // Allows a controller thread to pause execution of newly created
1432 // threads until notified. Instances of this class must be created
1433 // and destroyed in the controller thread.
1434 //
1435 // This class is only for testing Google Test's own constructs. Do not
1436 // use it in user tests, either directly or indirectly.
1437 class Notification {
1438 public:
1439 Notification() : notified_(false) {
1440 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
1441 }
1442 ~Notification() {
1443 pthread_mutex_destroy(&mutex_);
1444 }
1445
1446 // Notifies all threads created with this notification to start. Must
1447 // be called from the controller thread.
1448 void Notify() {
1449 pthread_mutex_lock(&mutex_);
1450 notified_ = true;
1451 pthread_mutex_unlock(&mutex_);
1452 }
1453
1454 // Blocks until the controller thread notifies. Must be called from a test
1455 // thread.
1456 void WaitForNotification() {
1457 for (;;) {
1458 pthread_mutex_lock(&mutex_);
1459 const bool notified = notified_;
1460 pthread_mutex_unlock(&mutex_);
1461 if (notified)
1462 break;
1463 SleepMilliseconds(10);
1464 }
1465 }
1466
1467 private:
1468 pthread_mutex_t mutex_;
1469 bool notified_;
1470
1471 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1472 };
1473
1474 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1475
1476 GTEST_API_ void SleepMilliseconds(int n);
1477
1478 // Provides leak-safe Windows kernel handle ownership.
1479 // Used in death tests and in threading support.
1480 class GTEST_API_ AutoHandle {
1481 public:
1482 // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
1483 // avoid including <windows.h> in this header file. Including <windows.h> is
1484 // undesirable because it defines a lot of symbols and macros that tend to
1485 // conflict with client code. This assumption is verified by
1486 // WindowsTypesTest.HANDLEIsVoidStar.
1487 typedef void* Handle;
1488 AutoHandle();
1489 explicit AutoHandle(Handle handle);
1490
1491 ~AutoHandle();
1492
1493 Handle Get() const;
1494 void Reset();
1495 void Reset(Handle handle);
1496
1497 private:
1498 // Returns true if and only if the handle is a valid handle object that can be
1499 // closed.
1500 bool IsCloseable() const;
1501
1502 Handle handle_;
1503
1504 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1505 };
1506
1507 // Allows a controller thread to pause execution of newly created
1508 // threads until notified. Instances of this class must be created
1509 // and destroyed in the controller thread.
1510 //
1511 // This class is only for testing Google Test's own constructs. Do not
1512 // use it in user tests, either directly or indirectly.
1513 class GTEST_API_ Notification {
1514 public:
1515 Notification();
1516 void Notify();
1517 void WaitForNotification();
1518
1519 private:
1520 AutoHandle event_;
1521
1522 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1523 };
1524 # endif // GTEST_HAS_NOTIFICATION_
1525
1526 // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
1527 // defined, but we don't want to use MinGW's pthreads implementation, which
1528 // has conformance problems with some versions of the POSIX standard.
1529 # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1530
1531 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
1532 // Consequently, it cannot select a correct instantiation of ThreadWithParam
1533 // in order to call its Run(). Introducing ThreadWithParamBase as a
1534 // non-templated base class for ThreadWithParam allows us to bypass this
1535 // problem.
1536 class ThreadWithParamBase {
1537 public:
1538 virtual ~ThreadWithParamBase() {}
1539 virtual void Run() = 0;
1540 };
1541
1542 // pthread_create() accepts a pointer to a function type with the C linkage.
1543 // According to the Standard (7.5/1), function types with different linkages
1544 // are different even if they are otherwise identical. Some compilers (for
1545 // example, SunStudio) treat them as different types. Since class methods
1546 // cannot be defined with C-linkage we need to define a free C-function to
1547 // pass into pthread_create().
1548 extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
1549 static_cast<ThreadWithParamBase*>(thread)->Run();
1550 return nullptr;
1551 }
1552
1553 // Helper class for testing Google Test's multi-threading constructs.
1554 // To use it, write:
1555 //
1556 // void ThreadFunc(int param) { /* Do things with param */ }
1557 // Notification thread_can_start;
1558 // ...
1559 // // The thread_can_start parameter is optional; you can supply NULL.
1560 // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
1561 // thread_can_start.Notify();
1562 //
1563 // These classes are only for testing Google Test's own constructs. Do
1564 // not use them in user tests, either directly or indirectly.
1565 template <typename T>
1566 class ThreadWithParam : public ThreadWithParamBase {
1567 public:
1568 typedef void UserThreadFunc(T);
1569
1570 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1571 : func_(func),
1572 param_(param),
1573 thread_can_start_(thread_can_start),
1574 finished_(false) {
1575 ThreadWithParamBase* const base = this;
1576 // The thread can be created only after all fields except thread_
1577 // have been initialized.
1578 GTEST_CHECK_POSIX_SUCCESS_(
1579 pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));
1580 }
1581 ~ThreadWithParam() override { Join(); }
1582
1583 void Join() {
1584 if (!finished_) {
1585 GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));
1586 finished_ = true;
1587 }
1588 }
1589
1590 void Run() override {
1591 if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();
1592 func_(param_);
1593 }
1594
1595 private:
1596 UserThreadFunc* const func_; // User-supplied thread function.
1597 const T param_; // User-supplied parameter to the thread function.
1598 // When non-NULL, used to block execution until the controller thread
1599 // notifies.
1600 Notification* const thread_can_start_;
1601 bool finished_; // true if and only if we know that the thread function has
1602 // finished.
1603 pthread_t thread_; // The native thread object.
1604
1605 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1606 };
1607 # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
1608 // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1609
1610 # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1611 // Mutex and ThreadLocal have already been imported into the namespace.
1612 // Nothing to do here.
1613
1614 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1615
1616 // Mutex implements mutex on Windows platforms. It is used in conjunction
1617 // with class MutexLock:
1618 //
1619 // Mutex mutex;
1620 // ...
1621 // MutexLock lock(&mutex); // Acquires the mutex and releases it at the
1622 // // end of the current scope.
1623 //
1624 // A static Mutex *must* be defined or declared using one of the following
1625 // macros:
1626 // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
1627 // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
1628 //
1629 // (A non-static Mutex is defined/declared in the usual way).
1630 class GTEST_API_ Mutex {
1631 public:
1632 enum MutexType { kStatic = 0, kDynamic = 1 };
1633 // We rely on kStaticMutex being 0 as it is to what the linker initializes
1634 // type_ in static mutexes. critical_section_ will be initialized lazily
1635 // in ThreadSafeLazyInit().
1636 enum StaticConstructorSelector { kStaticMutex = 0 };
1637
1638 // This constructor intentionally does nothing. It relies on type_ being
1639 // statically initialized to 0 (effectively setting it to kStatic) and on
1640 // ThreadSafeLazyInit() to lazily initialize the rest of the members.
1641 explicit Mutex(StaticConstructorSelector /*dummy*/) {}
1642
1643 Mutex();
1644 ~Mutex();
1645
1646 void Lock();
1647
1648 void Unlock();
1649
1650 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1651 // with high probability.
1652 void AssertHeld();
1653
1654 private:
1655 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
1656 void ThreadSafeLazyInit();
1657
1658 // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
1659 // we assume that 0 is an invalid value for thread IDs.
1660 unsigned int owner_thread_id_;
1661
1662 // For static mutexes, we rely on these members being initialized to zeros
1663 // by the linker.
1664 MutexType type_;
1665 long critical_section_init_phase_; // NOLINT
1666 GTEST_CRITICAL_SECTION* critical_section_;
1667
1668 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1669 };
1670
1671 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1672 extern ::testing::internal::Mutex mutex
1673
1674 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1675 ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
1676
1677 // We cannot name this class MutexLock because the ctor declaration would
1678 // conflict with a macro named MutexLock, which is defined on some
1679 // platforms. That macro is used as a defensive measure to prevent against
1680 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1681 // "MutexLock l(&mu)". Hence the typedef trick below.
1682 class GTestMutexLock {
1683 public:
1684 explicit GTestMutexLock(Mutex* mutex)
1685 : mutex_(mutex) { mutex_->Lock(); }
1686
1687 ~GTestMutexLock() { mutex_->Unlock(); }
1688
1689 private:
1690 Mutex* const mutex_;
1691
1692 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1693 };
1694
1695 typedef GTestMutexLock MutexLock;
1696
1697 // Base class for ValueHolder<T>. Allows a caller to hold and delete a value
1698 // without knowing its type.
1699 class ThreadLocalValueHolderBase {
1700 public:
1701 virtual ~ThreadLocalValueHolderBase() {}
1702 };
1703
1704 // Provides a way for a thread to send notifications to a ThreadLocal
1705 // regardless of its parameter type.
1706 class ThreadLocalBase {
1707 public:
1708 // Creates a new ValueHolder<T> object holding a default value passed to
1709 // this ThreadLocal<T>'s constructor and returns it. It is the caller's
1710 // responsibility not to call this when the ThreadLocal<T> instance already
1711 // has a value on the current thread.
1712 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
1713
1714 protected:
1715 ThreadLocalBase() {}
1716 virtual ~ThreadLocalBase() {}
1717
1718 private:
1719 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
1720 };
1721
1722 // Maps a thread to a set of ThreadLocals that have values instantiated on that
1723 // thread and notifies them when the thread exits. A ThreadLocal instance is
1724 // expected to persist until all threads it has values on have terminated.
1725 class GTEST_API_ ThreadLocalRegistry {
1726 public:
1727 // Registers thread_local_instance as having value on the current thread.
1728 // Returns a value that can be used to identify the thread from other threads.
1729 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
1730 const ThreadLocalBase* thread_local_instance);
1731
1732 // Invoked when a ThreadLocal instance is destroyed.
1733 static void OnThreadLocalDestroyed(
1734 const ThreadLocalBase* thread_local_instance);
1735 };
1736
1737 class GTEST_API_ ThreadWithParamBase {
1738 public:
1739 void Join();
1740
1741 protected:
1742 class Runnable {
1743 public:
1744 virtual ~Runnable() {}
1745 virtual void Run() = 0;
1746 };
1747
1748 ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
1749 virtual ~ThreadWithParamBase();
1750
1751 private:
1752 AutoHandle thread_;
1753 };
1754
1755 // Helper class for testing Google Test's multi-threading constructs.
1756 template <typename T>
1757 class ThreadWithParam : public ThreadWithParamBase {
1758 public:
1759 typedef void UserThreadFunc(T);
1760
1761 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1762 : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
1763 }
1764 virtual ~ThreadWithParam() {}
1765
1766 private:
1767 class RunnableImpl : public Runnable {
1768 public:
1769 RunnableImpl(UserThreadFunc* func, T param)
1770 : func_(func),
1771 param_(param) {
1772 }
1773 virtual ~RunnableImpl() {}
1774 virtual void Run() {
1775 func_(param_);
1776 }
1777
1778 private:
1779 UserThreadFunc* const func_;
1780 const T param_;
1781
1782 GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
1783 };
1784
1785 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1786 };
1787
1788 // Implements thread-local storage on Windows systems.
1789 //
1790 // // Thread 1
1791 // ThreadLocal<int> tl(100); // 100 is the default value for each thread.
1792 //
1793 // // Thread 2
1794 // tl.set(150); // Changes the value for thread 2 only.
1795 // EXPECT_EQ(150, tl.get());
1796 //
1797 // // Thread 1
1798 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
1799 // tl.set(200);
1800 // EXPECT_EQ(200, tl.get());
1801 //
1802 // The template type argument T must have a public copy constructor.
1803 // In addition, the default ThreadLocal constructor requires T to have
1804 // a public default constructor.
1805 //
1806 // The users of a TheadLocal instance have to make sure that all but one
1807 // threads (including the main one) using that instance have exited before
1808 // destroying it. Otherwise, the per-thread objects managed for them by the
1809 // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
1810 //
1811 // Google Test only uses global ThreadLocal objects. That means they
1812 // will die after main() has returned. Therefore, no per-thread
1813 // object managed by Google Test will be leaked as long as all threads
1814 // using Google Test have exited when main() returns.
1815 template <typename T>
1816 class ThreadLocal : public ThreadLocalBase {
1817 public:
1818 ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
1819 explicit ThreadLocal(const T& value)
1820 : default_factory_(new InstanceValueHolderFactory(value)) {}
1821
1822 ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
1823
1824 T* pointer() { return GetOrCreateValue(); }
1825 const T* pointer() const { return GetOrCreateValue(); }
1826 const T& get() const { return *pointer(); }
1827 void set(const T& value) { *pointer() = value; }
1828
1829 private:
1830 // Holds a value of T. Can be deleted via its base class without the caller
1831 // knowing the type of T.
1832 class ValueHolder : public ThreadLocalValueHolderBase {
1833 public:
1834 ValueHolder() : value_() {}
1835 explicit ValueHolder(const T& value) : value_(value) {}
1836
1837 T* pointer() { return &value_; }
1838
1839 private:
1840 T value_;
1841 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1842 };
1843
1844
1845 T* GetOrCreateValue() const {
1846 return static_cast<ValueHolder*>(
1847 ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
1848 }
1849
1850 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
1851 return default_factory_->MakeNewHolder();
1852 }
1853
1854 class ValueHolderFactory {
1855 public:
1856 ValueHolderFactory() {}
1857 virtual ~ValueHolderFactory() {}
1858 virtual ValueHolder* MakeNewHolder() const = 0;
1859
1860 private:
1861 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
1862 };
1863
1864 class DefaultValueHolderFactory : public ValueHolderFactory {
1865 public:
1866 DefaultValueHolderFactory() {}
1867 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
1868
1869 private:
1870 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
1871 };
1872
1873 class InstanceValueHolderFactory : public ValueHolderFactory {
1874 public:
1875 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
1876 ValueHolder* MakeNewHolder() const override {
1877 return new ValueHolder(value_);
1878 }
1879
1880 private:
1881 const T value_; // The value for each thread.
1882
1883 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
1884 };
1885
1886 std::unique_ptr<ValueHolderFactory> default_factory_;
1887
1888 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1889 };
1890
1891 # elif GTEST_HAS_PTHREAD
1892
1893 // MutexBase and Mutex implement mutex on pthreads-based platforms.
1894 class MutexBase {
1895 public:
1896 // Acquires this mutex.
1897 void Lock() {
1898 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
1899 owner_ = pthread_self();
1900 has_owner_ = true;
1901 }
1902
1903 // Releases this mutex.
1904 void Unlock() {
1905 // Since the lock is being released the owner_ field should no longer be
1906 // considered valid. We don't protect writing to has_owner_ here, as it's
1907 // the caller's responsibility to ensure that the current thread holds the
1908 // mutex when this is called.
1909 has_owner_ = false;
1910 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
1911 }
1912
1913 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1914 // with high probability.
1915 void AssertHeld() const {
1916 GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
1917 << "The current thread is not holding the mutex @" << this;
1918 }
1919
1920 // A static mutex may be used before main() is entered. It may even
1921 // be used before the dynamic initialization stage. Therefore we
1922 // must be able to initialize a static mutex object at link time.
1923 // This means MutexBase has to be a POD and its member variables
1924 // have to be public.
1925 public:
1926 pthread_mutex_t mutex_; // The underlying pthread mutex.
1927 // has_owner_ indicates whether the owner_ field below contains a valid thread
1928 // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
1929 // accesses to the owner_ field should be protected by a check of this field.
1930 // An alternative might be to memset() owner_ to all zeros, but there's no
1931 // guarantee that a zero'd pthread_t is necessarily invalid or even different
1932 // from pthread_self().
1933 bool has_owner_;
1934 pthread_t owner_; // The thread holding the mutex.
1935 };
1936
1937 // Forward-declares a static mutex.
1938 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1939 extern ::testing::internal::MutexBase mutex
1940
1941 // Defines and statically (i.e. at link time) initializes a static mutex.
1942 // The initialization list here does not explicitly initialize each field,
1943 // instead relying on default initialization for the unspecified fields. In
1944 // particular, the owner_ field (a pthread_t) is not explicitly initialized.
1945 // This allows initialization to work whether pthread_t is a scalar or struct.
1946 // The flag -Wmissing-field-initializers must not be specified for this to work.
1947 #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1948 ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}
1949
1950 // The Mutex class can only be used for mutexes created at runtime. It
1951 // shares its API with MutexBase otherwise.
1952 class Mutex : public MutexBase {
1953 public:
1954 Mutex() {
1955 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
1956 has_owner_ = false;
1957 }
1958 ~Mutex() {
1959 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
1960 }
1961
1962 private:
1963 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1964 };
1965
1966 // We cannot name this class MutexLock because the ctor declaration would
1967 // conflict with a macro named MutexLock, which is defined on some
1968 // platforms. That macro is used as a defensive measure to prevent against
1969 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1970 // "MutexLock l(&mu)". Hence the typedef trick below.
1971 class GTestMutexLock {
1972 public:
1973 explicit GTestMutexLock(MutexBase* mutex)
1974 : mutex_(mutex) { mutex_->Lock(); }
1975
1976 ~GTestMutexLock() { mutex_->Unlock(); }
1977
1978 private:
1979 MutexBase* const mutex_;
1980
1981 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1982 };
1983
1984 typedef GTestMutexLock MutexLock;
1985
1986 // Helpers for ThreadLocal.
1987
1988 // pthread_key_create() requires DeleteThreadLocalValue() to have
1989 // C-linkage. Therefore it cannot be templatized to access
1990 // ThreadLocal<T>. Hence the need for class
1991 // ThreadLocalValueHolderBase.
1992 class ThreadLocalValueHolderBase {
1993 public:
1994 virtual ~ThreadLocalValueHolderBase() {}
1995 };
1996
1997 // Called by pthread to delete thread-local data stored by
1998 // pthread_setspecific().
1999 extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
2000 delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
2001 }
2002
2003 // Implements thread-local storage on pthreads-based systems.
2004 template <typename T>
2005 class GTEST_API_ ThreadLocal {
2006 public:
2007 ThreadLocal()
2008 : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
2009 explicit ThreadLocal(const T& value)
2010 : key_(CreateKey()),
2011 default_factory_(new InstanceValueHolderFactory(value)) {}
2012
2013 ~ThreadLocal() {
2014 // Destroys the managed object for the current thread, if any.
2015 DeleteThreadLocalValue(pthread_getspecific(key_));
2016
2017 // Releases resources associated with the key. This will *not*
2018 // delete managed objects for other threads.
2019 GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
2020 }
2021
2022 T* pointer() { return GetOrCreateValue(); }
2023 const T* pointer() const { return GetOrCreateValue(); }
2024 const T& get() const { return *pointer(); }
2025 void set(const T& value) { *pointer() = value; }
2026
2027 private:
2028 // Holds a value of type T.
2029 class ValueHolder : public ThreadLocalValueHolderBase {
2030 public:
2031 ValueHolder() : value_() {}
2032 explicit ValueHolder(const T& value) : value_(value) {}
2033
2034 T* pointer() { return &value_; }
2035
2036 private:
2037 T value_;
2038 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
2039 };
2040
2041 static pthread_key_t CreateKey() {
2042 pthread_key_t key;
2043 // When a thread exits, DeleteThreadLocalValue() will be called on
2044 // the object managed for that thread.
2045 GTEST_CHECK_POSIX_SUCCESS_(
2046 pthread_key_create(&key, &DeleteThreadLocalValue));
2047 return key;
2048 }
2049
2050 T* GetOrCreateValue() const {
2051 ThreadLocalValueHolderBase* const holder =
2052 static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
2053 if (holder != nullptr) {
2054 return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
2055 }
2056
2057 ValueHolder* const new_holder = default_factory_->MakeNewHolder();
2058 ThreadLocalValueHolderBase* const holder_base = new_holder;
2059 GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
2060 return new_holder->pointer();
2061 }
2062
2063 class ValueHolderFactory {
2064 public:
2065 ValueHolderFactory() {}
2066 virtual ~ValueHolderFactory() {}
2067 virtual ValueHolder* MakeNewHolder() const = 0;
2068
2069 private:
2070 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
2071 };
2072
2073 class DefaultValueHolderFactory : public ValueHolderFactory {
2074 public:
2075 DefaultValueHolderFactory() {}
2076 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
2077
2078 private:
2079 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
2080 };
2081
2082 class InstanceValueHolderFactory : public ValueHolderFactory {
2083 public:
2084 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
2085 ValueHolder* MakeNewHolder() const override {
2086 return new ValueHolder(value_);
2087 }
2088
2089 private:
2090 const T value_; // The value for each thread.
2091
2092 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
2093 };
2094
2095 // A key pthreads uses for looking up per-thread values.
2096 const pthread_key_t key_;
2097 std::unique_ptr<ValueHolderFactory> default_factory_;
2098
2099 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
2100 };
2101
2102 # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
2103
2104 #else // GTEST_IS_THREADSAFE
2105
2106 // A dummy implementation of synchronization primitives (mutex, lock,
2107 // and thread-local variable). Necessary for compiling Google Test where
2108 // mutex is not supported - using Google Test in multiple threads is not
2109 // supported on such platforms.
2110
2111 class Mutex {
2112 public:
2113 Mutex() {}
2114 void Lock() {}
2115 void Unlock() {}
2116 void AssertHeld() const {}
2117 };
2118
2119 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2120 extern ::testing::internal::Mutex mutex
2121
2122 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
2123
2124 // We cannot name this class MutexLock because the ctor declaration would
2125 // conflict with a macro named MutexLock, which is defined on some
2126 // platforms. That macro is used as a defensive measure to prevent against
2127 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2128 // "MutexLock l(&mu)". Hence the typedef trick below.
2129 class GTestMutexLock {
2130 public:
2131 explicit GTestMutexLock(Mutex*) {} // NOLINT
2132 };
2133
2134 typedef GTestMutexLock MutexLock;
2135
2136 template <typename T>
2137 class GTEST_API_ ThreadLocal {
2138 public:
2139 ThreadLocal() : value_() {}
2140 explicit ThreadLocal(const T& value) : value_(value) {}
2141 T* pointer() { return &value_; }
2142 const T* pointer() const { return &value_; }
2143 const T& get() const { return value_; }
2144 void set(const T& value) { value_ = value; }
2145 private:
2146 T value_;
2147 };
2148
2149 #endif // GTEST_IS_THREADSAFE
2150
2151 // Returns the number of threads running in the process, or 0 to indicate that
2152 // we cannot detect it.
2153 GTEST_API_ size_t GetThreadCount();
2154
2155 #if GTEST_OS_WINDOWS
2156 # define GTEST_PATH_SEP_ "\\"
2157 # define GTEST_HAS_ALT_PATH_SEP_ 1
2158 #else
2159 # define GTEST_PATH_SEP_ "/"
2160 # define GTEST_HAS_ALT_PATH_SEP_ 0
2161 #endif // GTEST_OS_WINDOWS
2162
2163 // Utilities for char.
2164
2165 // isspace(int ch) and friends accept an unsigned char or EOF. char
2166 // may be signed, depending on the compiler (or compiler flags).
2167 // Therefore we need to cast a char to unsigned char before calling
2168 // isspace(), etc.
2169
2170 inline bool IsAlpha(char ch) {
2171 return isalpha(static_cast<unsigned char>(ch)) != 0;
2172 }
2173 inline bool IsAlNum(char ch) {
2174 return isalnum(static_cast<unsigned char>(ch)) != 0;
2175 }
2176 inline bool IsDigit(char ch) {
2177 return isdigit(static_cast<unsigned char>(ch)) != 0;
2178 }
2179 inline bool IsLower(char ch) {
2180 return islower(static_cast<unsigned char>(ch)) != 0;
2181 }
2182 inline bool IsSpace(char ch) {
2183 return isspace(static_cast<unsigned char>(ch)) != 0;
2184 }
2185 inline bool IsUpper(char ch) {
2186 return isupper(static_cast<unsigned char>(ch)) != 0;
2187 }
2188 inline bool IsXDigit(char ch) {
2189 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2190 }
2191 #ifdef __cpp_char8_t
2192 inline bool IsXDigit(char8_t ch) {
2193 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2194 }
2195 #endif
2196 inline bool IsXDigit(char16_t ch) {
2197 const unsigned char low_byte = static_cast<unsigned char>(ch);
2198 return ch == low_byte && isxdigit(low_byte) != 0;
2199 }
2200 inline bool IsXDigit(char32_t ch) {
2201 const unsigned char low_byte = static_cast<unsigned char>(ch);
2202 return ch == low_byte && isxdigit(low_byte) != 0;
2203 }
2204 inline bool IsXDigit(wchar_t ch) {
2205 const unsigned char low_byte = static_cast<unsigned char>(ch);
2206 return ch == low_byte && isxdigit(low_byte) != 0;
2207 }
2208
2209 inline char ToLower(char ch) {
2210 return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
2211 }
2212 inline char ToUpper(char ch) {
2213 return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
2214 }
2215
2216 inline std::string StripTrailingSpaces(std::string str) {
2217 std::string::iterator it = str.end();
2218 while (it != str.begin() && IsSpace(*--it))
2219 it = str.erase(it);
2220 return str;
2221 }
2222
2223 // The testing::internal::posix namespace holds wrappers for common
2224 // POSIX functions. These wrappers hide the differences between
2225 // Windows/MSVC and POSIX systems. Since some compilers define these
2226 // standard functions as macros, the wrapper cannot have the same name
2227 // as the wrapped function.
2228
2229 namespace posix {
2230
2231 // Functions with a different name on Windows.
2232
2233 #if GTEST_OS_WINDOWS
2234
2235 typedef struct _stat StatStruct;
2236
2237 # ifdef __BORLANDC__
2238 inline int DoIsATTY(int fd) { return isatty(fd); }
2239 inline int StrCaseCmp(const char* s1, const char* s2) {
2240 return stricmp(s1, s2);
2241 }
2242 inline char* StrDup(const char* src) { return strdup(src); }
2243 # else // !__BORLANDC__
2244 # if GTEST_OS_WINDOWS_MOBILE
2245 inline int DoIsATTY(int /* fd */) { return 0; }
2246 # else
2247 inline int DoIsATTY(int fd) { return _isatty(fd); }
2248 # endif // GTEST_OS_WINDOWS_MOBILE
2249 inline int StrCaseCmp(const char* s1, const char* s2) {
2250 return _stricmp(s1, s2);
2251 }
2252 inline char* StrDup(const char* src) { return _strdup(src); }
2253 # endif // __BORLANDC__
2254
2255 # if GTEST_OS_WINDOWS_MOBILE
2256 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
2257 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
2258 // time and thus not defined there.
2259 # else
2260 inline int FileNo(FILE* file) { return _fileno(file); }
2261 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
2262 inline int RmDir(const char* dir) { return _rmdir(dir); }
2263 inline bool IsDir(const StatStruct& st) {
2264 return (_S_IFDIR & st.st_mode) != 0;
2265 }
2266 # endif // GTEST_OS_WINDOWS_MOBILE
2267
2268 #elif GTEST_OS_ESP8266
2269 typedef struct stat StatStruct;
2270
2271 inline int FileNo(FILE* file) { return fileno(file); }
2272 inline int DoIsATTY(int fd) { return isatty(fd); }
2273 inline int Stat(const char* path, StatStruct* buf) {
2274 // stat function not implemented on ESP8266
2275 return 0;
2276 }
2277 inline int StrCaseCmp(const char* s1, const char* s2) {
2278 return strcasecmp(s1, s2);
2279 }
2280 inline char* StrDup(const char* src) { return strdup(src); }
2281 inline int RmDir(const char* dir) { return rmdir(dir); }
2282 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2283
2284 #else
2285
2286 typedef struct stat StatStruct;
2287
2288 inline int FileNo(FILE* file) { return fileno(file); }
2289 inline int DoIsATTY(int fd) { return isatty(fd); }
2290 inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
2291 inline int StrCaseCmp(const char* s1, const char* s2) {
2292 return strcasecmp(s1, s2);
2293 }
2294 inline char* StrDup(const char* src) { return strdup(src); }
2295 inline int RmDir(const char* dir) { return rmdir(dir); }
2296 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2297
2298 #endif // GTEST_OS_WINDOWS
2299
2300 inline int IsATTY(int fd) {
2301 // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
2302 // to a file on Linux), which is unexpected, so save the previous value, and
2303 // restore it after the call.
2304 int savedErrno = errno;
2305 int isAttyValue = DoIsATTY(fd);
2306 errno = savedErrno;
2307
2308 return isAttyValue;
2309 }
2310
2311 // Functions deprecated by MSVC 8.0.
2312
2313 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
2314
2315 // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
2316 // StrError() aren't needed on Windows CE at this time and thus not
2317 // defined there.
2318
2319 #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
2320 !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
2321 inline int ChDir(const char* dir) { return chdir(dir); }
2322 #endif
2323 inline FILE* FOpen(const char* path, const char* mode) {
2324 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2325 struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
2326 std::wstring_convert<wchar_codecvt> converter;
2327 std::wstring wide_path = converter.from_bytes(path);
2328 std::wstring wide_mode = converter.from_bytes(mode);
2329 return _wfopen(wide_path.c_str(), wide_mode.c_str());
2330 #else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2331 return fopen(path, mode);
2332 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2333 }
2334 #if !GTEST_OS_WINDOWS_MOBILE
2335 inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
2336 return freopen(path, mode, stream);
2337 }
2338 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
2339 #endif
2340 inline int FClose(FILE* fp) { return fclose(fp); }
2341 #if !GTEST_OS_WINDOWS_MOBILE
2342 inline int Read(int fd, void* buf, unsigned int count) {
2343 return static_cast<int>(read(fd, buf, count));
2344 }
2345 inline int Write(int fd, const void* buf, unsigned int count) {
2346 return static_cast<int>(write(fd, buf, count));
2347 }
2348 inline int Close(int fd) { return close(fd); }
2349 inline const char* StrError(int errnum) { return strerror(errnum); }
2350 #endif
2351 inline const char* GetEnv(const char* name) {
2352 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
2353 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
2354 // We are on an embedded platform, which has no environment variables.
2355 static_cast<void>(name); // To prevent 'unused argument' warning.
2356 return nullptr;
2357 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
2358 // Environment variables which we programmatically clear will be set to the
2359 // empty string rather than unset (NULL). Handle that case.
2360 const char* const env = getenv(name);
2361 return (env != nullptr && env[0] != '\0') ? env : nullptr;
2362 #else
2363 return getenv(name);
2364 #endif
2365 }
2366
2367 GTEST_DISABLE_MSC_DEPRECATED_POP_()
2368
2369 #if GTEST_OS_WINDOWS_MOBILE
2370 // Windows CE has no C library. The abort() function is used in
2371 // several places in Google Test. This implementation provides a reasonable
2372 // imitation of standard behaviour.
2373 [[noreturn]] void Abort();
2374 #else
2375 [[noreturn]] inline void Abort() { abort(); }
2376 #endif // GTEST_OS_WINDOWS_MOBILE
2377
2378 } // namespace posix
2379
2380 // MSVC "deprecates" snprintf and issues warnings wherever it is used. In
2381 // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
2382 // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
2383 // function in order to achieve that. We use macro definition here because
2384 // snprintf is a variadic function.
2385 #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
2386 // MSVC 2005 and above support variadic macros.
2387 # define GTEST_SNPRINTF_(buffer, size, format, ...) \
2388 _snprintf_s(buffer, size, size, format, __VA_ARGS__)
2389 #elif defined(_MSC_VER)
2390 // Windows CE does not define _snprintf_s
2391 # define GTEST_SNPRINTF_ _snprintf
2392 #else
2393 # define GTEST_SNPRINTF_ snprintf
2394 #endif
2395
2396 // The biggest signed integer type the compiler supports.
2397 //
2398 // long long is guaranteed to be at least 64-bits in C++11.
2399 using BiggestInt = long long; // NOLINT
2400
2401 // The maximum number a BiggestInt can represent.
2402 constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
2403
2404 // This template class serves as a compile-time function from size to
2405 // type. It maps a size in bytes to a primitive type with that
2406 // size. e.g.
2407 //
2408 // TypeWithSize<4>::UInt
2409 //
2410 // is typedef-ed to be unsigned int (unsigned integer made up of 4
2411 // bytes).
2412 //
2413 // Such functionality should belong to STL, but I cannot find it
2414 // there.
2415 //
2416 // Google Test uses this class in the implementation of floating-point
2417 // comparison.
2418 //
2419 // For now it only handles UInt (unsigned int) as that's all Google Test
2420 // needs. Other types can be easily added in the future if need
2421 // arises.
2422 template <size_t size>
2423 class TypeWithSize {
2424 public:
2425 // This prevents the user from using TypeWithSize<N> with incorrect
2426 // values of N.
2427 using UInt = void;
2428 };
2429
2430 // The specialization for size 4.
2431 template <>
2432 class TypeWithSize<4> {
2433 public:
2434 using Int = std::int32_t;
2435 using UInt = std::uint32_t;
2436 };
2437
2438 // The specialization for size 8.
2439 template <>
2440 class TypeWithSize<8> {
2441 public:
2442 using Int = std::int64_t;
2443 using UInt = std::uint64_t;
2444 };
2445
2446 // Integer types of known sizes.
2447 using TimeInMillis = int64_t; // Represents time in milliseconds.
2448
2449 // Utilities for command line flags and environment variables.
2450
2451 // Macro for referencing flags.
2452 #if !defined(GTEST_FLAG)
2453 # define GTEST_FLAG(name) FLAGS_gtest_##name
2454 #endif // !defined(GTEST_FLAG)
2455
2456 #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2457 # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
2458 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2459
2460 #if !defined(GTEST_DECLARE_bool_)
2461 # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
2462
2463 // Macros for declaring flags.
2464 # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
2465 # define GTEST_DECLARE_int32_(name) \
2466 GTEST_API_ extern std::int32_t GTEST_FLAG(name)
2467 # define GTEST_DECLARE_string_(name) \
2468 GTEST_API_ extern ::std::string GTEST_FLAG(name)
2469
2470 // Macros for defining flags.
2471 # define GTEST_DEFINE_bool_(name, default_val, doc) \
2472 GTEST_API_ bool GTEST_FLAG(name) = (default_val)
2473 # define GTEST_DEFINE_int32_(name, default_val, doc) \
2474 GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val)
2475 # define GTEST_DEFINE_string_(name, default_val, doc) \
2476 GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
2477
2478 #endif // !defined(GTEST_DECLARE_bool_)
2479
2480 // Thread annotations
2481 #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2482 # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
2483 # define GTEST_LOCK_EXCLUDED_(locks)
2484 #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2485
2486 // Parses 'str' for a 32-bit signed integer. If successful, writes the result
2487 // to *value and returns true; otherwise leaves *value unchanged and returns
2488 // false.
2489 GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
2490 int32_t* value);
2491
2492 // Parses a bool/int32_t/string from the environment variable
2493 // corresponding to the given Google Test flag.
2494 bool BoolFromGTestEnv(const char* flag, bool default_val);
2495 GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);
2496 std::string OutputFlagAlsoCheckEnvVar();
2497 const char* StringFromGTestEnv(const char* flag, const char* default_val);
2498
2499 } // namespace internal
2500 } // namespace testing
2501
2502 #if !defined(GTEST_INTERNAL_DEPRECATED)
2503
2504 // Internal Macro to mark an API deprecated, for googletest usage only
2505 // Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
2506 // GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
2507 // a deprecated entity will trigger a warning when compiled with
2508 // `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
2509 // For msvc /W3 option will need to be used
2510 // Note that for 'other' compilers this macro evaluates to nothing to prevent
2511 // compilations errors.
2512 #if defined(_MSC_VER)
2513 #define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
2514 #elif defined(__GNUC__)
2515 #define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
2516 #else
2517 #define GTEST_INTERNAL_DEPRECATED(message)
2518 #endif
2519
2520 #endif // !defined(GTEST_INTERNAL_DEPRECATED)
2521
2522 #if GTEST_HAS_ABSL
2523 // Always use absl::any for UniversalPrinter<> specializations if googletest
2524 // is built with absl support.
2525 #define GTEST_INTERNAL_HAS_ANY 1
2526 #include "absl/types/any.h"
2527 namespace testing {
2528 namespace internal {
2529 using Any = ::absl::any;
2530 } // namespace internal
2531 } // namespace testing
2532 #else
2533 #ifdef __has_include
2534 #if __has_include(<any>) && __cplusplus >= 201703L
2535 // Otherwise for C++17 and higher use std::any for UniversalPrinter<>
2536 // specializations.
2537 #define GTEST_INTERNAL_HAS_ANY 1
2538 #include <any>
2539 namespace testing {
2540 namespace internal {
2541 using Any = ::std::any;
2542 } // namespace internal
2543 } // namespace testing
2544 // The case where absl is configured NOT to alias std::any is not
2545 // supported.
2546 #endif // __has_include(<any>) && __cplusplus >= 201703L
2547 #endif // __has_include
2548 #endif // GTEST_HAS_ABSL
2549
2550 #if GTEST_HAS_ABSL
2551 // Always use absl::optional for UniversalPrinter<> specializations if
2552 // googletest is built with absl support.
2553 #define GTEST_INTERNAL_HAS_OPTIONAL 1
2554 #include "absl/types/optional.h"
2555 namespace testing {
2556 namespace internal {
2557 template <typename T>
2558 using Optional = ::absl::optional<T>;
2559 } // namespace internal
2560 } // namespace testing
2561 #else
2562 #ifdef __has_include
2563 #if __has_include(<optional>) && __cplusplus >= 201703L
2564 // Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
2565 // specializations.
2566 #define GTEST_INTERNAL_HAS_OPTIONAL 1
2567 #include <optional>
2568 namespace testing {
2569 namespace internal {
2570 template <typename T>
2571 using Optional = ::std::optional<T>;
2572 } // namespace internal
2573 } // namespace testing
2574 // The case where absl is configured NOT to alias std::optional is not
2575 // supported.
2576 #endif // __has_include(<optional>) && __cplusplus >= 201703L
2577 #endif // __has_include
2578 #endif // GTEST_HAS_ABSL
2579
2580 #if GTEST_HAS_ABSL
2581 // Always use absl::string_view for Matcher<> specializations if googletest
2582 // is built with absl support.
2583 # define GTEST_INTERNAL_HAS_STRING_VIEW 1
2584 #include "absl/strings/string_view.h"
2585 namespace testing {
2586 namespace internal {
2587 using StringView = ::absl::string_view;
2588 } // namespace internal
2589 } // namespace testing
2590 #else
2591 # ifdef __has_include
2592 # if __has_include(<string_view>) && __cplusplus >= 201703L
2593 // Otherwise for C++17 and higher use std::string_view for Matcher<>
2594 // specializations.
2595 # define GTEST_INTERNAL_HAS_STRING_VIEW 1
2596 #include <string_view>
2597 namespace testing {
2598 namespace internal {
2599 using StringView = ::std::string_view;
2600 } // namespace internal
2601 } // namespace testing
2602 // The case where absl is configured NOT to alias std::string_view is not
2603 // supported.
2604 # endif // __has_include(<string_view>) && __cplusplus >= 201703L
2605 # endif // __has_include
2606 #endif // GTEST_HAS_ABSL
2607
2608 #if GTEST_HAS_ABSL
2609 // Always use absl::variant for UniversalPrinter<> specializations if googletest
2610 // is built with absl support.
2611 #define GTEST_INTERNAL_HAS_VARIANT 1
2612 #include "absl/types/variant.h"
2613 namespace testing {
2614 namespace internal {
2615 template <typename... T>
2616 using Variant = ::absl::variant<T...>;
2617 } // namespace internal
2618 } // namespace testing
2619 #else
2620 #ifdef __has_include
2621 #if __has_include(<variant>) && __cplusplus >= 201703L
2622 // Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
2623 // specializations.
2624 #define GTEST_INTERNAL_HAS_VARIANT 1
2625 #include <variant>
2626 namespace testing {
2627 namespace internal {
2628 template <typename... T>
2629 using Variant = ::std::variant<T...>;
2630 } // namespace internal
2631 } // namespace testing
2632 // The case where absl is configured NOT to alias std::variant is not supported.
2633 #endif // __has_include(<variant>) && __cplusplus >= 201703L
2634 #endif // __has_include
2635 #endif // GTEST_HAS_ABSL
2636
2637 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
2638
2639 #if GTEST_OS_LINUX
2640 # include <stdlib.h>
2641 # include <sys/types.h>
2642 # include <sys/wait.h>
2643 # include <unistd.h>
2644 #endif // GTEST_OS_LINUX
2645
2646 #if GTEST_HAS_EXCEPTIONS
2647 # include <stdexcept>
2648 #endif
2649
2650 #include <ctype.h>
2651 #include <float.h>
2652 #include <string.h>
2653 #include <cstdint>
2654 #include <iomanip>
2655 #include <limits>
2656 #include <map>
2657 #include <set>
2658 #include <string>
2659 #include <type_traits>
2660 #include <vector>
2661
2662 // Copyright 2005, Google Inc.
2663 // All rights reserved.
2664 //
2665 // Redistribution and use in source and binary forms, with or without
2666 // modification, are permitted provided that the following conditions are
2667 // met:
2668 //
2669 // * Redistributions of source code must retain the above copyright
2670 // notice, this list of conditions and the following disclaimer.
2671 // * Redistributions in binary form must reproduce the above
2672 // copyright notice, this list of conditions and the following disclaimer
2673 // in the documentation and/or other materials provided with the
2674 // distribution.
2675 // * Neither the name of Google Inc. nor the names of its
2676 // contributors may be used to endorse or promote products derived from
2677 // this software without specific prior written permission.
2678 //
2679 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2680 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2681 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2682 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2683 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2684 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2685 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2686 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2687 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2688 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2689 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2690
2691 //
2692 // The Google C++ Testing and Mocking Framework (Google Test)
2693 //
2694 // This header file defines the Message class.
2695 //
2696 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
2697 // leave some internal implementation details in this header file.
2698 // They are clearly marked by comments like this:
2699 //
2700 // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2701 //
2702 // Such code is NOT meant to be used by a user directly, and is subject
2703 // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
2704 // program!
2705
2706 // GOOGLETEST_CM0001 DO NOT DELETE
2707
2708 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2709 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2710
2711 #include <limits>
2712 #include <memory>
2713 #include <sstream>
2714
2715
2716 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
2717 /* class A needs to have dll-interface to be used by clients of class B */)
2718
2719 // Ensures that there is at least one operator<< in the global namespace.
2720 // See Message& operator<<(...) below for why.
2721 void operator<<(const testing::internal::Secret&, int);
2722
2723 namespace testing {
2724
2725 // The Message class works like an ostream repeater.
2726 //
2727 // Typical usage:
2728 //
2729 // 1. You stream a bunch of values to a Message object.
2730 // It will remember the text in a stringstream.
2731 // 2. Then you stream the Message object to an ostream.
2732 // This causes the text in the Message to be streamed
2733 // to the ostream.
2734 //
2735 // For example;
2736 //
2737 // testing::Message foo;
2738 // foo << 1 << " != " << 2;
2739 // std::cout << foo;
2740 //
2741 // will print "1 != 2".
2742 //
2743 // Message is not intended to be inherited from. In particular, its
2744 // destructor is not virtual.
2745 //
2746 // Note that stringstream behaves differently in gcc and in MSVC. You
2747 // can stream a NULL char pointer to it in the former, but not in the
2748 // latter (it causes an access violation if you do). The Message
2749 // class hides this difference by treating a NULL char pointer as
2750 // "(null)".
2751 class GTEST_API_ Message {
2752 private:
2753 // The type of basic IO manipulators (endl, ends, and flush) for
2754 // narrow streams.
2755 typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
2756
2757 public:
2758 // Constructs an empty Message.
2759 Message();
2760
2761 // Copy constructor.
2762 Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
2763 *ss_ << msg.GetString();
2764 }
2765
2766 // Constructs a Message from a C-string.
2767 explicit Message(const char* str) : ss_(new ::std::stringstream) {
2768 *ss_ << str;
2769 }
2770
2771 // Streams a non-pointer value to this object.
2772 template <typename T>
2773 inline Message& operator <<(const T& val) {
2774 // Some libraries overload << for STL containers. These
2775 // overloads are defined in the global namespace instead of ::std.
2776 //
2777 // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
2778 // overloads are visible in either the std namespace or the global
2779 // namespace, but not other namespaces, including the testing
2780 // namespace which Google Test's Message class is in.
2781 //
2782 // To allow STL containers (and other types that has a << operator
2783 // defined in the global namespace) to be used in Google Test
2784 // assertions, testing::Message must access the custom << operator
2785 // from the global namespace. With this using declaration,
2786 // overloads of << defined in the global namespace and those
2787 // visible via Koenig lookup are both exposed in this function.
2788 using ::operator <<;
2789 *ss_ << val;
2790 return *this;
2791 }
2792
2793 // Streams a pointer value to this object.
2794 //
2795 // This function is an overload of the previous one. When you
2796 // stream a pointer to a Message, this definition will be used as it
2797 // is more specialized. (The C++ Standard, section
2798 // [temp.func.order].) If you stream a non-pointer, then the
2799 // previous definition will be used.
2800 //
2801 // The reason for this overload is that streaming a NULL pointer to
2802 // ostream is undefined behavior. Depending on the compiler, you
2803 // may get "0", "(nil)", "(null)", or an access violation. To
2804 // ensure consistent result across compilers, we always treat NULL
2805 // as "(null)".
2806 template <typename T>
2807 inline Message& operator <<(T* const& pointer) { // NOLINT
2808 if (pointer == nullptr) {
2809 *ss_ << "(null)";
2810 } else {
2811 *ss_ << pointer;
2812 }
2813 return *this;
2814 }
2815
2816 // Since the basic IO manipulators are overloaded for both narrow
2817 // and wide streams, we have to provide this specialized definition
2818 // of operator <<, even though its body is the same as the
2819 // templatized version above. Without this definition, streaming
2820 // endl or other basic IO manipulators to Message will confuse the
2821 // compiler.
2822 Message& operator <<(BasicNarrowIoManip val) {
2823 *ss_ << val;
2824 return *this;
2825 }
2826
2827 // Instead of 1/0, we want to see true/false for bool values.
2828 Message& operator <<(bool b) {
2829 return *this << (b ? "true" : "false");
2830 }
2831
2832 // These two overloads allow streaming a wide C string to a Message
2833 // using the UTF-8 encoding.
2834 Message& operator <<(const wchar_t* wide_c_str);
2835 Message& operator <<(wchar_t* wide_c_str);
2836
2837 #if GTEST_HAS_STD_WSTRING
2838 // Converts the given wide string to a narrow string using the UTF-8
2839 // encoding, and streams the result to this Message object.
2840 Message& operator <<(const ::std::wstring& wstr);
2841 #endif // GTEST_HAS_STD_WSTRING
2842
2843 // Gets the text streamed to this object so far as an std::string.
2844 // Each '\0' character in the buffer is replaced with "\\0".
2845 //
2846 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2847 std::string GetString() const;
2848
2849 private:
2850 // We'll hold the text streamed to this object here.
2851 const std::unique_ptr< ::std::stringstream> ss_;
2852
2853 // We declare (but don't implement) this to prevent the compiler
2854 // from implementing the assignment operator.
2855 void operator=(const Message&);
2856 };
2857
2858 // Streams a Message to an ostream.
2859 inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
2860 return os << sb.GetString();
2861 }
2862
2863 namespace internal {
2864
2865 // Converts a streamable value to an std::string. A NULL pointer is
2866 // converted to "(null)". When the input value is a ::string,
2867 // ::std::string, ::wstring, or ::std::wstring object, each NUL
2868 // character in it is replaced with "\\0".
2869 template <typename T>
2870 std::string StreamableToString(const T& streamable) {
2871 return (Message() << streamable).GetString();
2872 }
2873
2874 } // namespace internal
2875 } // namespace testing
2876
2877 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2878
2879 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2880 // Copyright 2008, Google Inc.
2881 // All rights reserved.
2882 //
2883 // Redistribution and use in source and binary forms, with or without
2884 // modification, are permitted provided that the following conditions are
2885 // met:
2886 //
2887 // * Redistributions of source code must retain the above copyright
2888 // notice, this list of conditions and the following disclaimer.
2889 // * Redistributions in binary form must reproduce the above
2890 // copyright notice, this list of conditions and the following disclaimer
2891 // in the documentation and/or other materials provided with the
2892 // distribution.
2893 // * Neither the name of Google Inc. nor the names of its
2894 // contributors may be used to endorse or promote products derived from
2895 // this software without specific prior written permission.
2896 //
2897 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2898 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2899 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2900 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2901 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2902 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2903 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2904 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2905 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2906 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2907 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2908 //
2909 // Google Test filepath utilities
2910 //
2911 // This header file declares classes and functions used internally by
2912 // Google Test. They are subject to change without notice.
2913 //
2914 // This file is #included in gtest/internal/gtest-internal.h.
2915 // Do not include this header file separately!
2916
2917 // GOOGLETEST_CM0001 DO NOT DELETE
2918
2919 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
2920 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
2921
2922 // Copyright 2005, Google Inc.
2923 // All rights reserved.
2924 //
2925 // Redistribution and use in source and binary forms, with or without
2926 // modification, are permitted provided that the following conditions are
2927 // met:
2928 //
2929 // * Redistributions of source code must retain the above copyright
2930 // notice, this list of conditions and the following disclaimer.
2931 // * Redistributions in binary form must reproduce the above
2932 // copyright notice, this list of conditions and the following disclaimer
2933 // in the documentation and/or other materials provided with the
2934 // distribution.
2935 // * Neither the name of Google Inc. nor the names of its
2936 // contributors may be used to endorse or promote products derived from
2937 // this software without specific prior written permission.
2938 //
2939 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2940 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2941 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2942 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2943 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2944 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2945 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2946 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2947 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2948 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2949 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2950 //
2951 // The Google C++ Testing and Mocking Framework (Google Test)
2952 //
2953 // This header file declares the String class and functions used internally by
2954 // Google Test. They are subject to change without notice. They should not used
2955 // by code external to Google Test.
2956 //
2957 // This header file is #included by gtest-internal.h.
2958 // It should not be #included by other files.
2959
2960 // GOOGLETEST_CM0001 DO NOT DELETE
2961
2962 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
2963 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
2964
2965 #ifdef __BORLANDC__
2966 // string.h is not guaranteed to provide strcpy on C++ Builder.
2967 # include <mem.h>
2968 #endif
2969
2970 #include <string.h>
2971 #include <cstdint>
2972 #include <string>
2973
2974
2975 namespace testing {
2976 namespace internal {
2977
2978 // String - an abstract class holding static string utilities.
2979 class GTEST_API_ String {
2980 public:
2981 // Static utility methods
2982
2983 // Clones a 0-terminated C string, allocating memory using new. The
2984 // caller is responsible for deleting the return value using
2985 // delete[]. Returns the cloned string, or NULL if the input is
2986 // NULL.
2987 //
2988 // This is different from strdup() in string.h, which allocates
2989 // memory using malloc().
2990 static const char* CloneCString(const char* c_str);
2991
2992 #if GTEST_OS_WINDOWS_MOBILE
2993 // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
2994 // able to pass strings to Win32 APIs on CE we need to convert them
2995 // to 'Unicode', UTF-16.
2996
2997 // Creates a UTF-16 wide string from the given ANSI string, allocating
2998 // memory using new. The caller is responsible for deleting the return
2999 // value using delete[]. Returns the wide string, or NULL if the
3000 // input is NULL.
3001 //
3002 // The wide string is created using the ANSI codepage (CP_ACP) to
3003 // match the behaviour of the ANSI versions of Win32 calls and the
3004 // C runtime.
3005 static LPCWSTR AnsiToUtf16(const char* c_str);
3006
3007 // Creates an ANSI string from the given wide string, allocating
3008 // memory using new. The caller is responsible for deleting the return
3009 // value using delete[]. Returns the ANSI string, or NULL if the
3010 // input is NULL.
3011 //
3012 // The returned string is created using the ANSI codepage (CP_ACP) to
3013 // match the behaviour of the ANSI versions of Win32 calls and the
3014 // C runtime.
3015 static const char* Utf16ToAnsi(LPCWSTR utf16_str);
3016 #endif
3017
3018 // Compares two C strings. Returns true if and only if they have the same
3019 // content.
3020 //
3021 // Unlike strcmp(), this function can handle NULL argument(s). A
3022 // NULL C string is considered different to any non-NULL C string,
3023 // including the empty string.
3024 static bool CStringEquals(const char* lhs, const char* rhs);
3025
3026 // Converts a wide C string to a String using the UTF-8 encoding.
3027 // NULL will be converted to "(null)". If an error occurred during
3028 // the conversion, "(failed to convert from wide string)" is
3029 // returned.
3030 static std::string ShowWideCString(const wchar_t* wide_c_str);
3031
3032 // Compares two wide C strings. Returns true if and only if they have the
3033 // same content.
3034 //
3035 // Unlike wcscmp(), this function can handle NULL argument(s). A
3036 // NULL C string is considered different to any non-NULL C string,
3037 // including the empty string.
3038 static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
3039
3040 // Compares two C strings, ignoring case. Returns true if and only if
3041 // they have the same content.
3042 //
3043 // Unlike strcasecmp(), this function can handle NULL argument(s).
3044 // A NULL C string is considered different to any non-NULL C string,
3045 // including the empty string.
3046 static bool CaseInsensitiveCStringEquals(const char* lhs,
3047 const char* rhs);
3048
3049 // Compares two wide C strings, ignoring case. Returns true if and only if
3050 // they have the same content.
3051 //
3052 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3053 // A NULL C string is considered different to any non-NULL wide C string,
3054 // including the empty string.
3055 // NB: The implementations on different platforms slightly differ.
3056 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3057 // environment variable. On GNU platform this method uses wcscasecmp
3058 // which compares according to LC_CTYPE category of the current locale.
3059 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3060 // current locale.
3061 static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3062 const wchar_t* rhs);
3063
3064 // Returns true if and only if the given string ends with the given suffix,
3065 // ignoring case. Any string is considered to end with an empty suffix.
3066 static bool EndsWithCaseInsensitive(
3067 const std::string& str, const std::string& suffix);
3068
3069 // Formats an int value as "%02d".
3070 static std::string FormatIntWidth2(int value); // "%02d" for width == 2
3071
3072 // Formats an int value to given width with leading zeros.
3073 static std::string FormatIntWidthN(int value, int width);
3074
3075 // Formats an int value as "%X".
3076 static std::string FormatHexInt(int value);
3077
3078 // Formats an int value as "%X".
3079 static std::string FormatHexUInt32(uint32_t value);
3080
3081 // Formats a byte as "%02X".
3082 static std::string FormatByte(unsigned char value);
3083
3084 private:
3085 String(); // Not meant to be instantiated.
3086 }; // class String
3087
3088 // Gets the content of the stringstream's buffer as an std::string. Each '\0'
3089 // character in the buffer is replaced with "\\0".
3090 GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
3091
3092 } // namespace internal
3093 } // namespace testing
3094
3095 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
3096
3097 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3098 /* class A needs to have dll-interface to be used by clients of class B */)
3099
3100 namespace testing {
3101 namespace internal {
3102
3103 // FilePath - a class for file and directory pathname manipulation which
3104 // handles platform-specific conventions (like the pathname separator).
3105 // Used for helper functions for naming files in a directory for xml output.
3106 // Except for Set methods, all methods are const or static, which provides an
3107 // "immutable value object" -- useful for peace of mind.
3108 // A FilePath with a value ending in a path separator ("like/this/") represents
3109 // a directory, otherwise it is assumed to represent a file. In either case,
3110 // it may or may not represent an actual file or directory in the file system.
3111 // Names are NOT checked for syntax correctness -- no checking for illegal
3112 // characters, malformed paths, etc.
3113
3114 class GTEST_API_ FilePath {
3115 public:
3116 FilePath() : pathname_("") { }
3117 FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
3118
3119 explicit FilePath(const std::string& pathname) : pathname_(pathname) {
3120 Normalize();
3121 }
3122
3123 FilePath& operator=(const FilePath& rhs) {
3124 Set(rhs);
3125 return *this;
3126 }
3127
3128 void Set(const FilePath& rhs) {
3129 pathname_ = rhs.pathname_;
3130 }
3131
3132 const std::string& string() const { return pathname_; }
3133 const char* c_str() const { return pathname_.c_str(); }
3134
3135 // Returns the current working directory, or "" if unsuccessful.
3136 static FilePath GetCurrentDir();
3137
3138 // Given directory = "dir", base_name = "test", number = 0,
3139 // extension = "xml", returns "dir/test.xml". If number is greater
3140 // than zero (e.g., 12), returns "dir/test_12.xml".
3141 // On Windows platform, uses \ as the separator rather than /.
3142 static FilePath MakeFileName(const FilePath& directory,
3143 const FilePath& base_name,
3144 int number,
3145 const char* extension);
3146
3147 // Given directory = "dir", relative_path = "test.xml",
3148 // returns "dir/test.xml".
3149 // On Windows, uses \ as the separator rather than /.
3150 static FilePath ConcatPaths(const FilePath& directory,
3151 const FilePath& relative_path);
3152
3153 // Returns a pathname for a file that does not currently exist. The pathname
3154 // will be directory/base_name.extension or
3155 // directory/base_name_<number>.extension if directory/base_name.extension
3156 // already exists. The number will be incremented until a pathname is found
3157 // that does not already exist.
3158 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
3159 // There could be a race condition if two or more processes are calling this
3160 // function at the same time -- they could both pick the same filename.
3161 static FilePath GenerateUniqueFileName(const FilePath& directory,
3162 const FilePath& base_name,
3163 const char* extension);
3164
3165 // Returns true if and only if the path is "".
3166 bool IsEmpty() const { return pathname_.empty(); }
3167
3168 // If input name has a trailing separator character, removes it and returns
3169 // the name, otherwise return the name string unmodified.
3170 // On Windows platform, uses \ as the separator, other platforms use /.
3171 FilePath RemoveTrailingPathSeparator() const;
3172
3173 // Returns a copy of the FilePath with the directory part removed.
3174 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
3175 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
3176 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
3177 // returns an empty FilePath ("").
3178 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3179 FilePath RemoveDirectoryName() const;
3180
3181 // RemoveFileName returns the directory path with the filename removed.
3182 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
3183 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
3184 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
3185 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
3186 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3187 FilePath RemoveFileName() const;
3188
3189 // Returns a copy of the FilePath with the case-insensitive extension removed.
3190 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
3191 // FilePath("dir/file"). If a case-insensitive extension is not
3192 // found, returns a copy of the original FilePath.
3193 FilePath RemoveExtension(const char* extension) const;
3194
3195 // Creates directories so that path exists. Returns true if successful or if
3196 // the directories already exist; returns false if unable to create
3197 // directories for any reason. Will also return false if the FilePath does
3198 // not represent a directory (that is, it doesn't end with a path separator).
3199 bool CreateDirectoriesRecursively() const;
3200
3201 // Create the directory so that path exists. Returns true if successful or
3202 // if the directory already exists; returns false if unable to create the
3203 // directory for any reason, including if the parent directory does not
3204 // exist. Not named "CreateDirectory" because that's a macro on Windows.
3205 bool CreateFolder() const;
3206
3207 // Returns true if FilePath describes something in the file-system,
3208 // either a file, directory, or whatever, and that something exists.
3209 bool FileOrDirectoryExists() const;
3210
3211 // Returns true if pathname describes a directory in the file-system
3212 // that exists.
3213 bool DirectoryExists() const;
3214
3215 // Returns true if FilePath ends with a path separator, which indicates that
3216 // it is intended to represent a directory. Returns false otherwise.
3217 // This does NOT check that a directory (or file) actually exists.
3218 bool IsDirectory() const;
3219
3220 // Returns true if pathname describes a root directory. (Windows has one
3221 // root directory per disk drive.)
3222 bool IsRootDirectory() const;
3223
3224 // Returns true if pathname describes an absolute path.
3225 bool IsAbsolutePath() const;
3226
3227 private:
3228 // Replaces multiple consecutive separators with a single separator.
3229 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
3230 // redundancies that might be in a pathname involving "." or "..".
3231 //
3232 // A pathname with multiple consecutive separators may occur either through
3233 // user error or as a result of some scripts or APIs that generate a pathname
3234 // with a trailing separator. On other platforms the same API or script
3235 // may NOT generate a pathname with a trailing "/". Then elsewhere that
3236 // pathname may have another "/" and pathname components added to it,
3237 // without checking for the separator already being there.
3238 // The script language and operating system may allow paths like "foo//bar"
3239 // but some of the functions in FilePath will not handle that correctly. In
3240 // particular, RemoveTrailingPathSeparator() only removes one separator, and
3241 // it is called in CreateDirectoriesRecursively() assuming that it will change
3242 // a pathname from directory syntax (trailing separator) to filename syntax.
3243 //
3244 // On Windows this method also replaces the alternate path separator '/' with
3245 // the primary path separator '\\', so that for example "bar\\/\\foo" becomes
3246 // "bar\\foo".
3247
3248 void Normalize();
3249
3250 // Returns a pointer to the last occurrence of a valid path separator in
3251 // the FilePath. On Windows, for example, both '/' and '\' are valid path
3252 // separators. Returns NULL if no path separator was found.
3253 const char* FindLastPathSeparator() const;
3254
3255 std::string pathname_;
3256 }; // class FilePath
3257
3258 } // namespace internal
3259 } // namespace testing
3260
3261 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
3262
3263 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
3264 // Copyright 2008 Google Inc.
3265 // All Rights Reserved.
3266 //
3267 // Redistribution and use in source and binary forms, with or without
3268 // modification, are permitted provided that the following conditions are
3269 // met:
3270 //
3271 // * Redistributions of source code must retain the above copyright
3272 // notice, this list of conditions and the following disclaimer.
3273 // * Redistributions in binary form must reproduce the above
3274 // copyright notice, this list of conditions and the following disclaimer
3275 // in the documentation and/or other materials provided with the
3276 // distribution.
3277 // * Neither the name of Google Inc. nor the names of its
3278 // contributors may be used to endorse or promote products derived from
3279 // this software without specific prior written permission.
3280 //
3281 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3282 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3283 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3284 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3285 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3286 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3287 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3288 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3289 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3290 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3291 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3292
3293 // Type utilities needed for implementing typed and type-parameterized
3294 // tests.
3295
3296 // GOOGLETEST_CM0001 DO NOT DELETE
3297
3298 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3299 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3300
3301
3302 // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
3303 // libstdc++ (which is where cxxabi.h comes from).
3304 # if GTEST_HAS_CXXABI_H_
3305 # include <cxxabi.h>
3306 # elif defined(__HP_aCC)
3307 # include <acxx_demangle.h>
3308 # endif // GTEST_HASH_CXXABI_H_
3309
3310 namespace testing {
3311 namespace internal {
3312
3313 // Canonicalizes a given name with respect to the Standard C++ Library.
3314 // This handles removing the inline namespace within `std` that is
3315 // used by various standard libraries (e.g., `std::__1`). Names outside
3316 // of namespace std are returned unmodified.
3317 inline std::string CanonicalizeForStdLibVersioning(std::string s) {
3318 static const char prefix[] = "std::__";
3319 if (s.compare(0, strlen(prefix), prefix) == 0) {
3320 std::string::size_type end = s.find("::", strlen(prefix));
3321 if (end != s.npos) {
3322 // Erase everything between the initial `std` and the second `::`.
3323 s.erase(strlen("std"), end - strlen("std"));
3324 }
3325 }
3326 return s;
3327 }
3328
3329 #if GTEST_HAS_RTTI
3330 // GetTypeName(const std::type_info&) returns a human-readable name of type T.
3331 inline std::string GetTypeName(const std::type_info& type) {
3332 const char* const name = type.name();
3333 #if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
3334 int status = 0;
3335 // gcc's implementation of typeid(T).name() mangles the type name,
3336 // so we have to demangle it.
3337 #if GTEST_HAS_CXXABI_H_
3338 using abi::__cxa_demangle;
3339 #endif // GTEST_HAS_CXXABI_H_
3340 char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
3341 const std::string name_str(status == 0 ? readable_name : name);
3342 free(readable_name);
3343 return CanonicalizeForStdLibVersioning(name_str);
3344 #else
3345 return name;
3346 #endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
3347 }
3348 #endif // GTEST_HAS_RTTI
3349
3350 // GetTypeName<T>() returns a human-readable name of type T if and only if
3351 // RTTI is enabled, otherwise it returns a dummy type name.
3352 // NB: This function is also used in Google Mock, so don't move it inside of
3353 // the typed-test-only section below.
3354 template <typename T>
3355 std::string GetTypeName() {
3356 #if GTEST_HAS_RTTI
3357 return GetTypeName(typeid(T));
3358 #else
3359 return "<type>";
3360 #endif // GTEST_HAS_RTTI
3361 }
3362
3363 // A unique type indicating an empty node
3364 struct None {};
3365
3366 # define GTEST_TEMPLATE_ template <typename T> class
3367
3368 // The template "selector" struct TemplateSel<Tmpl> is used to
3369 // represent Tmpl, which must be a class template with one type
3370 // parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
3371 // as the type Tmpl<T>. This allows us to actually instantiate the
3372 // template "selected" by TemplateSel<Tmpl>.
3373 //
3374 // This trick is necessary for simulating typedef for class templates,
3375 // which C++ doesn't support directly.
3376 template <GTEST_TEMPLATE_ Tmpl>
3377 struct TemplateSel {
3378 template <typename T>
3379 struct Bind {
3380 typedef Tmpl<T> type;
3381 };
3382 };
3383
3384 # define GTEST_BIND_(TmplSel, T) \
3385 TmplSel::template Bind<T>::type
3386
3387 template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
3388 struct Templates {
3389 using Head = TemplateSel<Head_>;
3390 using Tail = Templates<Tail_...>;
3391 };
3392
3393 template <GTEST_TEMPLATE_ Head_>
3394 struct Templates<Head_> {
3395 using Head = TemplateSel<Head_>;
3396 using Tail = None;
3397 };
3398
3399 // Tuple-like type lists
3400 template <typename Head_, typename... Tail_>
3401 struct Types {
3402 using Head = Head_;
3403 using Tail = Types<Tail_...>;
3404 };
3405
3406 template <typename Head_>
3407 struct Types<Head_> {
3408 using Head = Head_;
3409 using Tail = None;
3410 };
3411
3412 // Helper metafunctions to tell apart a single type from types
3413 // generated by ::testing::Types
3414 template <typename... Ts>
3415 struct ProxyTypeList {
3416 using type = Types<Ts...>;
3417 };
3418
3419 template <typename>
3420 struct is_proxy_type_list : std::false_type {};
3421
3422 template <typename... Ts>
3423 struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};
3424
3425 // Generator which conditionally creates type lists.
3426 // It recognizes if a requested type list should be created
3427 // and prevents creating a new type list nested within another one.
3428 template <typename T>
3429 struct GenerateTypeList {
3430 private:
3431 using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,
3432 ProxyTypeList<T>>::type;
3433
3434 public:
3435 using type = typename proxy::type;
3436 };
3437
3438 } // namespace internal
3439
3440 template <typename... Ts>
3441 using Types = internal::ProxyTypeList<Ts...>;
3442
3443 } // namespace testing
3444
3445 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3446
3447 // Due to C++ preprocessor weirdness, we need double indirection to
3448 // concatenate two tokens when one of them is __LINE__. Writing
3449 //
3450 // foo ## __LINE__
3451 //
3452 // will result in the token foo__LINE__, instead of foo followed by
3453 // the current line number. For more details, see
3454 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
3455 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
3456 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
3457
3458 // Stringifies its argument.
3459 // Work around a bug in visual studio which doesn't accept code like this:
3460 //
3461 // #define GTEST_STRINGIFY_(name) #name
3462 // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
3463 // MACRO(, x, y)
3464 //
3465 // Complaining about the argument to GTEST_STRINGIFY_ being empty.
3466 // This is allowed by the spec.
3467 #define GTEST_STRINGIFY_HELPER_(name, ...) #name
3468 #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
3469
3470 namespace proto2 {
3471 class MessageLite;
3472 }
3473
3474 namespace testing {
3475
3476 // Forward declarations.
3477
3478 class AssertionResult; // Result of an assertion.
3479 class Message; // Represents a failure message.
3480 class Test; // Represents a test.
3481 class TestInfo; // Information about a test.
3482 class TestPartResult; // Result of a test part.
3483 class UnitTest; // A collection of test suites.
3484
3485 template <typename T>
3486 ::std::string PrintToString(const T& value);
3487
3488 namespace internal {
3489
3490 struct TraceInfo; // Information about a trace point.
3491 class TestInfoImpl; // Opaque implementation of TestInfo
3492 class UnitTestImpl; // Opaque implementation of UnitTest
3493
3494 // The text used in failure messages to indicate the start of the
3495 // stack trace.
3496 GTEST_API_ extern const char kStackTraceMarker[];
3497
3498 // An IgnoredValue object can be implicitly constructed from ANY value.
3499 class IgnoredValue {
3500 struct Sink {};
3501 public:
3502 // This constructor template allows any value to be implicitly
3503 // converted to IgnoredValue. The object has no data member and
3504 // doesn't try to remember anything about the argument. We
3505 // deliberately omit the 'explicit' keyword in order to allow the
3506 // conversion to be implicit.
3507 // Disable the conversion if T already has a magical conversion operator.
3508 // Otherwise we get ambiguity.
3509 template <typename T,
3510 typename std::enable_if<!std::is_convertible<T, Sink>::value,
3511 int>::type = 0>
3512 IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
3513 };
3514
3515 // Appends the user-supplied message to the Google-Test-generated message.
3516 GTEST_API_ std::string AppendUserMessage(
3517 const std::string& gtest_msg, const Message& user_msg);
3518
3519 #if GTEST_HAS_EXCEPTIONS
3520
3521 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
3522 /* an exported class was derived from a class that was not exported */)
3523
3524 // This exception is thrown by (and only by) a failed Google Test
3525 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
3526 // are enabled). We derive it from std::runtime_error, which is for
3527 // errors presumably detectable only at run time. Since
3528 // std::runtime_error inherits from std::exception, many testing
3529 // frameworks know how to extract and print the message inside it.
3530 class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
3531 public:
3532 explicit GoogleTestFailureException(const TestPartResult& failure);
3533 };
3534
3535 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
3536
3537 #endif // GTEST_HAS_EXCEPTIONS
3538
3539 namespace edit_distance {
3540 // Returns the optimal edits to go from 'left' to 'right'.
3541 // All edits cost the same, with replace having lower priority than
3542 // add/remove.
3543 // Simple implementation of the Wagner-Fischer algorithm.
3544 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
3545 enum EditType { kMatch, kAdd, kRemove, kReplace };
3546 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3547 const std::vector<size_t>& left, const std::vector<size_t>& right);
3548
3549 // Same as above, but the input is represented as strings.
3550 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3551 const std::vector<std::string>& left,
3552 const std::vector<std::string>& right);
3553
3554 // Create a diff of the input strings in Unified diff format.
3555 GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
3556 const std::vector<std::string>& right,
3557 size_t context = 2);
3558
3559 } // namespace edit_distance
3560
3561 // Calculate the diff between 'left' and 'right' and return it in unified diff
3562 // format.
3563 // If not null, stores in 'total_line_count' the total number of lines found
3564 // in left + right.
3565 GTEST_API_ std::string DiffStrings(const std::string& left,
3566 const std::string& right,
3567 size_t* total_line_count);
3568
3569 // Constructs and returns the message for an equality assertion
3570 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
3571 //
3572 // The first four parameters are the expressions used in the assertion
3573 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
3574 // where foo is 5 and bar is 6, we have:
3575 //
3576 // expected_expression: "foo"
3577 // actual_expression: "bar"
3578 // expected_value: "5"
3579 // actual_value: "6"
3580 //
3581 // The ignoring_case parameter is true if and only if the assertion is a
3582 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
3583 // be inserted into the message.
3584 GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
3585 const char* actual_expression,
3586 const std::string& expected_value,
3587 const std::string& actual_value,
3588 bool ignoring_case);
3589
3590 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
3591 GTEST_API_ std::string GetBoolAssertionFailureMessage(
3592 const AssertionResult& assertion_result,
3593 const char* expression_text,
3594 const char* actual_predicate_value,
3595 const char* expected_predicate_value);
3596
3597 // This template class represents an IEEE floating-point number
3598 // (either single-precision or double-precision, depending on the
3599 // template parameters).
3600 //
3601 // The purpose of this class is to do more sophisticated number
3602 // comparison. (Due to round-off error, etc, it's very unlikely that
3603 // two floating-points will be equal exactly. Hence a naive
3604 // comparison by the == operation often doesn't work.)
3605 //
3606 // Format of IEEE floating-point:
3607 //
3608 // The most-significant bit being the leftmost, an IEEE
3609 // floating-point looks like
3610 //
3611 // sign_bit exponent_bits fraction_bits
3612 //
3613 // Here, sign_bit is a single bit that designates the sign of the
3614 // number.
3615 //
3616 // For float, there are 8 exponent bits and 23 fraction bits.
3617 //
3618 // For double, there are 11 exponent bits and 52 fraction bits.
3619 //
3620 // More details can be found at
3621 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
3622 //
3623 // Template parameter:
3624 //
3625 // RawType: the raw floating-point type (either float or double)
3626 template <typename RawType>
3627 class FloatingPoint {
3628 public:
3629 // Defines the unsigned integer type that has the same size as the
3630 // floating point number.
3631 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
3632
3633 // Constants.
3634
3635 // # of bits in a number.
3636 static const size_t kBitCount = 8*sizeof(RawType);
3637
3638 // # of fraction bits in a number.
3639 static const size_t kFractionBitCount =
3640 std::numeric_limits<RawType>::digits - 1;
3641
3642 // # of exponent bits in a number.
3643 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
3644
3645 // The mask for the sign bit.
3646 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
3647
3648 // The mask for the fraction bits.
3649 static const Bits kFractionBitMask =
3650 ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
3651
3652 // The mask for the exponent bits.
3653 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
3654
3655 // How many ULP's (Units in the Last Place) we want to tolerate when
3656 // comparing two numbers. The larger the value, the more error we
3657 // allow. A 0 value means that two numbers must be exactly the same
3658 // to be considered equal.
3659 //
3660 // The maximum error of a single floating-point operation is 0.5
3661 // units in the last place. On Intel CPU's, all floating-point
3662 // calculations are done with 80-bit precision, while double has 64
3663 // bits. Therefore, 4 should be enough for ordinary use.
3664 //
3665 // See the following article for more details on ULP:
3666 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
3667 static const uint32_t kMaxUlps = 4;
3668
3669 // Constructs a FloatingPoint from a raw floating-point number.
3670 //
3671 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
3672 // around may change its bits, although the new value is guaranteed
3673 // to be also a NAN. Therefore, don't expect this constructor to
3674 // preserve the bits in x when x is a NAN.
3675 explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
3676
3677 // Static methods
3678
3679 // Reinterprets a bit pattern as a floating-point number.
3680 //
3681 // This function is needed to test the AlmostEquals() method.
3682 static RawType ReinterpretBits(const Bits bits) {
3683 FloatingPoint fp(0);
3684 fp.u_.bits_ = bits;
3685 return fp.u_.value_;
3686 }
3687
3688 // Returns the floating-point number that represent positive infinity.
3689 static RawType Infinity() {
3690 return ReinterpretBits(kExponentBitMask);
3691 }
3692
3693 // Returns the maximum representable finite floating-point number.
3694 static RawType Max();
3695
3696 // Non-static methods
3697
3698 // Returns the bits that represents this number.
3699 const Bits &bits() const { return u_.bits_; }
3700
3701 // Returns the exponent bits of this number.
3702 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
3703
3704 // Returns the fraction bits of this number.
3705 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
3706
3707 // Returns the sign bit of this number.
3708 Bits sign_bit() const { return kSignBitMask & u_.bits_; }
3709
3710 // Returns true if and only if this is NAN (not a number).
3711 bool is_nan() const {
3712 // It's a NAN if the exponent bits are all ones and the fraction
3713 // bits are not entirely zeros.
3714 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
3715 }
3716
3717 // Returns true if and only if this number is at most kMaxUlps ULP's away
3718 // from rhs. In particular, this function:
3719 //
3720 // - returns false if either number is (or both are) NAN.
3721 // - treats really large numbers as almost equal to infinity.
3722 // - thinks +0.0 and -0.0 are 0 DLP's apart.
3723 bool AlmostEquals(const FloatingPoint& rhs) const {
3724 // The IEEE standard says that any comparison operation involving
3725 // a NAN must return false.
3726 if (is_nan() || rhs.is_nan()) return false;
3727
3728 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
3729 <= kMaxUlps;
3730 }
3731
3732 private:
3733 // The data type used to store the actual floating-point number.
3734 union FloatingPointUnion {
3735 RawType value_; // The raw floating-point number.
3736 Bits bits_; // The bits that represent the number.
3737 };
3738
3739 // Converts an integer from the sign-and-magnitude representation to
3740 // the biased representation. More precisely, let N be 2 to the
3741 // power of (kBitCount - 1), an integer x is represented by the
3742 // unsigned number x + N.
3743 //
3744 // For instance,
3745 //
3746 // -N + 1 (the most negative number representable using
3747 // sign-and-magnitude) is represented by 1;
3748 // 0 is represented by N; and
3749 // N - 1 (the biggest number representable using
3750 // sign-and-magnitude) is represented by 2N - 1.
3751 //
3752 // Read http://en.wikipedia.org/wiki/Signed_number_representations
3753 // for more details on signed number representations.
3754 static Bits SignAndMagnitudeToBiased(const Bits &sam) {
3755 if (kSignBitMask & sam) {
3756 // sam represents a negative number.
3757 return ~sam + 1;
3758 } else {
3759 // sam represents a positive number.
3760 return kSignBitMask | sam;
3761 }
3762 }
3763
3764 // Given two numbers in the sign-and-magnitude representation,
3765 // returns the distance between them as an unsigned number.
3766 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
3767 const Bits &sam2) {
3768 const Bits biased1 = SignAndMagnitudeToBiased(sam1);
3769 const Bits biased2 = SignAndMagnitudeToBiased(sam2);
3770 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
3771 }
3772
3773 FloatingPointUnion u_;
3774 };
3775
3776 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
3777 // macro defined by <windows.h>.
3778 template <>
3779 inline float FloatingPoint<float>::Max() { return FLT_MAX; }
3780 template <>
3781 inline double FloatingPoint<double>::Max() { return DBL_MAX; }
3782
3783 // Typedefs the instances of the FloatingPoint template class that we
3784 // care to use.
3785 typedef FloatingPoint<float> Float;
3786 typedef FloatingPoint<double> Double;
3787
3788 // In order to catch the mistake of putting tests that use different
3789 // test fixture classes in the same test suite, we need to assign
3790 // unique IDs to fixture classes and compare them. The TypeId type is
3791 // used to hold such IDs. The user should treat TypeId as an opaque
3792 // type: the only operation allowed on TypeId values is to compare
3793 // them for equality using the == operator.
3794 typedef const void* TypeId;
3795
3796 template <typename T>
3797 class TypeIdHelper {
3798 public:
3799 // dummy_ must not have a const type. Otherwise an overly eager
3800 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
3801 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
3802 static bool dummy_;
3803 };
3804
3805 template <typename T>
3806 bool TypeIdHelper<T>::dummy_ = false;
3807
3808 // GetTypeId<T>() returns the ID of type T. Different values will be
3809 // returned for different types. Calling the function twice with the
3810 // same type argument is guaranteed to return the same ID.
3811 template <typename T>
3812 TypeId GetTypeId() {
3813 // The compiler is required to allocate a different
3814 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
3815 // the template. Therefore, the address of dummy_ is guaranteed to
3816 // be unique.
3817 return &(TypeIdHelper<T>::dummy_);
3818 }
3819
3820 // Returns the type ID of ::testing::Test. Always call this instead
3821 // of GetTypeId< ::testing::Test>() to get the type ID of
3822 // ::testing::Test, as the latter may give the wrong result due to a
3823 // suspected linker bug when compiling Google Test as a Mac OS X
3824 // framework.
3825 GTEST_API_ TypeId GetTestTypeId();
3826
3827 // Defines the abstract factory interface that creates instances
3828 // of a Test object.
3829 class TestFactoryBase {
3830 public:
3831 virtual ~TestFactoryBase() {}
3832
3833 // Creates a test instance to run. The instance is both created and destroyed
3834 // within TestInfoImpl::Run()
3835 virtual Test* CreateTest() = 0;
3836
3837 protected:
3838 TestFactoryBase() {}
3839
3840 private:
3841 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
3842 };
3843
3844 // This class provides implementation of TeastFactoryBase interface.
3845 // It is used in TEST and TEST_F macros.
3846 template <class TestClass>
3847 class TestFactoryImpl : public TestFactoryBase {
3848 public:
3849 Test* CreateTest() override { return new TestClass; }
3850 };
3851
3852 #if GTEST_OS_WINDOWS
3853
3854 // Predicate-formatters for implementing the HRESULT checking macros
3855 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
3856 // We pass a long instead of HRESULT to avoid causing an
3857 // include dependency for the HRESULT type.
3858 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
3859 long hr); // NOLINT
3860 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
3861 long hr); // NOLINT
3862
3863 #endif // GTEST_OS_WINDOWS
3864
3865 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
3866 using SetUpTestSuiteFunc = void (*)();
3867 using TearDownTestSuiteFunc = void (*)();
3868
3869 struct CodeLocation {
3870 CodeLocation(const std::string& a_file, int a_line)
3871 : file(a_file), line(a_line) {}
3872
3873 std::string file;
3874 int line;
3875 };
3876
3877 // Helper to identify which setup function for TestCase / TestSuite to call.
3878 // Only one function is allowed, either TestCase or TestSute but not both.
3879
3880 // Utility functions to help SuiteApiResolver
3881 using SetUpTearDownSuiteFuncType = void (*)();
3882
3883 inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
3884 SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
3885 return a == def ? nullptr : a;
3886 }
3887
3888 template <typename T>
3889 // Note that SuiteApiResolver inherits from T because
3890 // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
3891 // SuiteApiResolver can access them.
3892 struct SuiteApiResolver : T {
3893 // testing::Test is only forward declared at this point. So we make it a
3894 // dependend class for the compiler to be OK with it.
3895 using Test =
3896 typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
3897
3898 static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
3899 int line_num) {
3900 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3901 SetUpTearDownSuiteFuncType test_case_fp =
3902 GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
3903 SetUpTearDownSuiteFuncType test_suite_fp =
3904 GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
3905
3906 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3907 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
3908 "make sure there is only one present at "
3909 << filename << ":" << line_num;
3910
3911 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
3912 #else
3913 (void)(filename);
3914 (void)(line_num);
3915 return &T::SetUpTestSuite;
3916 #endif
3917 }
3918
3919 static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
3920 int line_num) {
3921 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3922 SetUpTearDownSuiteFuncType test_case_fp =
3923 GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
3924 SetUpTearDownSuiteFuncType test_suite_fp =
3925 GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
3926
3927 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3928 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
3929 " please make sure there is only one present at"
3930 << filename << ":" << line_num;
3931
3932 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
3933 #else
3934 (void)(filename);
3935 (void)(line_num);
3936 return &T::TearDownTestSuite;
3937 #endif
3938 }
3939 };
3940
3941 // Creates a new TestInfo object and registers it with Google Test;
3942 // returns the created object.
3943 //
3944 // Arguments:
3945 //
3946 // test_suite_name: name of the test suite
3947 // name: name of the test
3948 // type_param: the name of the test's type parameter, or NULL if
3949 // this is not a typed or a type-parameterized test.
3950 // value_param: text representation of the test's value parameter,
3951 // or NULL if this is not a type-parameterized test.
3952 // code_location: code location where the test is defined
3953 // fixture_class_id: ID of the test fixture class
3954 // set_up_tc: pointer to the function that sets up the test suite
3955 // tear_down_tc: pointer to the function that tears down the test suite
3956 // factory: pointer to the factory that creates a test object.
3957 // The newly created TestInfo instance will assume
3958 // ownership of the factory object.
3959 GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
3960 const char* test_suite_name, const char* name, const char* type_param,
3961 const char* value_param, CodeLocation code_location,
3962 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
3963 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
3964
3965 // If *pstr starts with the given prefix, modifies *pstr to be right
3966 // past the prefix and returns true; otherwise leaves *pstr unchanged
3967 // and returns false. None of pstr, *pstr, and prefix can be NULL.
3968 GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
3969
3970 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3971 /* class A needs to have dll-interface to be used by clients of class B */)
3972
3973 // State of the definition of a type-parameterized test suite.
3974 class GTEST_API_ TypedTestSuitePState {
3975 public:
3976 TypedTestSuitePState() : registered_(false) {}
3977
3978 // Adds the given test name to defined_test_names_ and return true
3979 // if the test suite hasn't been registered; otherwise aborts the
3980 // program.
3981 bool AddTestName(const char* file, int line, const char* case_name,
3982 const char* test_name) {
3983 if (registered_) {
3984 fprintf(stderr,
3985 "%s Test %s must be defined before "
3986 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
3987 FormatFileLocation(file, line).c_str(), test_name, case_name);
3988 fflush(stderr);
3989 posix::Abort();
3990 }
3991 registered_tests_.insert(
3992 ::std::make_pair(test_name, CodeLocation(file, line)));
3993 return true;
3994 }
3995
3996 bool TestExists(const std::string& test_name) const {
3997 return registered_tests_.count(test_name) > 0;
3998 }
3999
4000 const CodeLocation& GetCodeLocation(const std::string& test_name) const {
4001 RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
4002 GTEST_CHECK_(it != registered_tests_.end());
4003 return it->second;
4004 }
4005
4006 // Verifies that registered_tests match the test names in
4007 // defined_test_names_; returns registered_tests if successful, or
4008 // aborts the program otherwise.
4009 const char* VerifyRegisteredTestNames(const char* test_suite_name,
4010 const char* file, int line,
4011 const char* registered_tests);
4012
4013 private:
4014 typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
4015
4016 bool registered_;
4017 RegisteredTestsMap registered_tests_;
4018 };
4019
4020 // Legacy API is deprecated but still available
4021 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4022 using TypedTestCasePState = TypedTestSuitePState;
4023 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4024
4025 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
4026
4027 // Skips to the first non-space char after the first comma in 'str';
4028 // returns NULL if no comma is found in 'str'.
4029 inline const char* SkipComma(const char* str) {
4030 const char* comma = strchr(str, ',');
4031 if (comma == nullptr) {
4032 return nullptr;
4033 }
4034 while (IsSpace(*(++comma))) {}
4035 return comma;
4036 }
4037
4038 // Returns the prefix of 'str' before the first comma in it; returns
4039 // the entire string if it contains no comma.
4040 inline std::string GetPrefixUntilComma(const char* str) {
4041 const char* comma = strchr(str, ',');
4042 return comma == nullptr ? str : std::string(str, comma);
4043 }
4044
4045 // Splits a given string on a given delimiter, populating a given
4046 // vector with the fields.
4047 void SplitString(const ::std::string& str, char delimiter,
4048 ::std::vector< ::std::string>* dest);
4049
4050 // The default argument to the template below for the case when the user does
4051 // not provide a name generator.
4052 struct DefaultNameGenerator {
4053 template <typename T>
4054 static std::string GetName(int i) {
4055 return StreamableToString(i);
4056 }
4057 };
4058
4059 template <typename Provided = DefaultNameGenerator>
4060 struct NameGeneratorSelector {
4061 typedef Provided type;
4062 };
4063
4064 template <typename NameGenerator>
4065 void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
4066
4067 template <typename NameGenerator, typename Types>
4068 void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
4069 result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
4070 GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
4071 i + 1);
4072 }
4073
4074 template <typename NameGenerator, typename Types>
4075 std::vector<std::string> GenerateNames() {
4076 std::vector<std::string> result;
4077 GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
4078 return result;
4079 }
4080
4081 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
4082 // registers a list of type-parameterized tests with Google Test. The
4083 // return value is insignificant - we just need to return something
4084 // such that we can call this function in a namespace scope.
4085 //
4086 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
4087 // template parameter. It's defined in gtest-type-util.h.
4088 template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
4089 class TypeParameterizedTest {
4090 public:
4091 // 'index' is the index of the test in the type list 'Types'
4092 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
4093 // Types). Valid values for 'index' are [0, N - 1] where N is the
4094 // length of Types.
4095 static bool Register(const char* prefix, const CodeLocation& code_location,
4096 const char* case_name, const char* test_names, int index,
4097 const std::vector<std::string>& type_names =
4098 GenerateNames<DefaultNameGenerator, Types>()) {
4099 typedef typename Types::Head Type;
4100 typedef Fixture<Type> FixtureClass;
4101 typedef typename GTEST_BIND_(TestSel, Type) TestClass;
4102
4103 // First, registers the first type-parameterized test in the type
4104 // list.
4105 MakeAndRegisterTestInfo(
4106 (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
4107 "/" + type_names[static_cast<size_t>(index)])
4108 .c_str(),
4109 StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
4110 GetTypeName<Type>().c_str(),
4111 nullptr, // No value parameter.
4112 code_location, GetTypeId<FixtureClass>(),
4113 SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
4114 code_location.file.c_str(), code_location.line),
4115 SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
4116 code_location.file.c_str(), code_location.line),
4117 new TestFactoryImpl<TestClass>);
4118
4119 // Next, recurses (at compile time) with the tail of the type list.
4120 return TypeParameterizedTest<Fixture, TestSel,
4121 typename Types::Tail>::Register(prefix,
4122 code_location,
4123 case_name,
4124 test_names,
4125 index + 1,
4126 type_names);
4127 }
4128 };
4129
4130 // The base case for the compile time recursion.
4131 template <GTEST_TEMPLATE_ Fixture, class TestSel>
4132 class TypeParameterizedTest<Fixture, TestSel, internal::None> {
4133 public:
4134 static bool Register(const char* /*prefix*/, const CodeLocation&,
4135 const char* /*case_name*/, const char* /*test_names*/,
4136 int /*index*/,
4137 const std::vector<std::string>& =
4138 std::vector<std::string>() /*type_names*/) {
4139 return true;
4140 }
4141 };
4142
4143 GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
4144 CodeLocation code_location);
4145 GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
4146 const char* case_name);
4147
4148 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
4149 // registers *all combinations* of 'Tests' and 'Types' with Google
4150 // Test. The return value is insignificant - we just need to return
4151 // something such that we can call this function in a namespace scope.
4152 template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
4153 class TypeParameterizedTestSuite {
4154 public:
4155 static bool Register(const char* prefix, CodeLocation code_location,
4156 const TypedTestSuitePState* state, const char* case_name,
4157 const char* test_names,
4158 const std::vector<std::string>& type_names =
4159 GenerateNames<DefaultNameGenerator, Types>()) {
4160 RegisterTypeParameterizedTestSuiteInstantiation(case_name);
4161 std::string test_name = StripTrailingSpaces(
4162 GetPrefixUntilComma(test_names));
4163 if (!state->TestExists(test_name)) {
4164 fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
4165 case_name, test_name.c_str(),
4166 FormatFileLocation(code_location.file.c_str(),
4167 code_location.line).c_str());
4168 fflush(stderr);
4169 posix::Abort();
4170 }
4171 const CodeLocation& test_location = state->GetCodeLocation(test_name);
4172
4173 typedef typename Tests::Head Head;
4174
4175 // First, register the first test in 'Test' for each type in 'Types'.
4176 TypeParameterizedTest<Fixture, Head, Types>::Register(
4177 prefix, test_location, case_name, test_names, 0, type_names);
4178
4179 // Next, recurses (at compile time) with the tail of the test list.
4180 return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
4181 Types>::Register(prefix, code_location,
4182 state, case_name,
4183 SkipComma(test_names),
4184 type_names);
4185 }
4186 };
4187
4188 // The base case for the compile time recursion.
4189 template <GTEST_TEMPLATE_ Fixture, typename Types>
4190 class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
4191 public:
4192 static bool Register(const char* /*prefix*/, const CodeLocation&,
4193 const TypedTestSuitePState* /*state*/,
4194 const char* /*case_name*/, const char* /*test_names*/,
4195 const std::vector<std::string>& =
4196 std::vector<std::string>() /*type_names*/) {
4197 return true;
4198 }
4199 };
4200
4201 // Returns the current OS stack trace as an std::string.
4202 //
4203 // The maximum number of stack frames to be included is specified by
4204 // the gtest_stack_trace_depth flag. The skip_count parameter
4205 // specifies the number of top frames to be skipped, which doesn't
4206 // count against the number of frames to be included.
4207 //
4208 // For example, if Foo() calls Bar(), which in turn calls
4209 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4210 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4211 GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
4212 UnitTest* unit_test, int skip_count);
4213
4214 // Helpers for suppressing warnings on unreachable code or constant
4215 // condition.
4216
4217 // Always returns true.
4218 GTEST_API_ bool AlwaysTrue();
4219
4220 // Always returns false.
4221 inline bool AlwaysFalse() { return !AlwaysTrue(); }
4222
4223 // Helper for suppressing false warning from Clang on a const char*
4224 // variable declared in a conditional expression always being NULL in
4225 // the else branch.
4226 struct GTEST_API_ ConstCharPtr {
4227 ConstCharPtr(const char* str) : value(str) {}
4228 operator bool() const { return true; }
4229 const char* value;
4230 };
4231
4232 // Helper for declaring std::string within 'if' statement
4233 // in pre C++17 build environment.
4234 struct TrueWithString {
4235 TrueWithString() = default;
4236 explicit TrueWithString(const char* str) : value(str) {}
4237 explicit TrueWithString(const std::string& str) : value(str) {}
4238 explicit operator bool() const { return true; }
4239 std::string value;
4240 };
4241
4242 // A simple Linear Congruential Generator for generating random
4243 // numbers with a uniform distribution. Unlike rand() and srand(), it
4244 // doesn't use global state (and therefore can't interfere with user
4245 // code). Unlike rand_r(), it's portable. An LCG isn't very random,
4246 // but it's good enough for our purposes.
4247 class GTEST_API_ Random {
4248 public:
4249 static const uint32_t kMaxRange = 1u << 31;
4250
4251 explicit Random(uint32_t seed) : state_(seed) {}
4252
4253 void Reseed(uint32_t seed) { state_ = seed; }
4254
4255 // Generates a random number from [0, range). Crashes if 'range' is
4256 // 0 or greater than kMaxRange.
4257 uint32_t Generate(uint32_t range);
4258
4259 private:
4260 uint32_t state_;
4261 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
4262 };
4263
4264 // Turns const U&, U&, const U, and U all into U.
4265 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
4266 typename std::remove_const<typename std::remove_reference<T>::type>::type
4267
4268 // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
4269 // that's true if and only if T has methods DebugString() and ShortDebugString()
4270 // that return std::string.
4271 template <typename T>
4272 class HasDebugStringAndShortDebugString {
4273 private:
4274 template <typename C>
4275 static auto CheckDebugString(C*) -> typename std::is_same<
4276 std::string, decltype(std::declval<const C>().DebugString())>::type;
4277 template <typename>
4278 static std::false_type CheckDebugString(...);
4279
4280 template <typename C>
4281 static auto CheckShortDebugString(C*) -> typename std::is_same<
4282 std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
4283 template <typename>
4284 static std::false_type CheckShortDebugString(...);
4285
4286 using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
4287 using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
4288
4289 public:
4290 static constexpr bool value =
4291 HasDebugStringType::value && HasShortDebugStringType::value;
4292 };
4293
4294 template <typename T>
4295 constexpr bool HasDebugStringAndShortDebugString<T>::value;
4296
4297 // When the compiler sees expression IsContainerTest<C>(0), if C is an
4298 // STL-style container class, the first overload of IsContainerTest
4299 // will be viable (since both C::iterator* and C::const_iterator* are
4300 // valid types and NULL can be implicitly converted to them). It will
4301 // be picked over the second overload as 'int' is a perfect match for
4302 // the type of argument 0. If C::iterator or C::const_iterator is not
4303 // a valid type, the first overload is not viable, and the second
4304 // overload will be picked. Therefore, we can determine whether C is
4305 // a container class by checking the type of IsContainerTest<C>(0).
4306 // The value of the expression is insignificant.
4307 //
4308 // In C++11 mode we check the existence of a const_iterator and that an
4309 // iterator is properly implemented for the container.
4310 //
4311 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
4312 // The reason is that C++ injects the name of a class as a member of the
4313 // class itself (e.g. you can refer to class iterator as either
4314 // 'iterator' or 'iterator::iterator'). If we look for C::iterator
4315 // only, for example, we would mistakenly think that a class named
4316 // iterator is an STL container.
4317 //
4318 // Also note that the simpler approach of overloading
4319 // IsContainerTest(typename C::const_iterator*) and
4320 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
4321 typedef int IsContainer;
4322 template <class C,
4323 class Iterator = decltype(::std::declval<const C&>().begin()),
4324 class = decltype(::std::declval<const C&>().end()),
4325 class = decltype(++::std::declval<Iterator&>()),
4326 class = decltype(*::std::declval<Iterator>()),
4327 class = typename C::const_iterator>
4328 IsContainer IsContainerTest(int /* dummy */) {
4329 return 0;
4330 }
4331
4332 typedef char IsNotContainer;
4333 template <class C>
4334 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
4335
4336 // Trait to detect whether a type T is a hash table.
4337 // The heuristic used is that the type contains an inner type `hasher` and does
4338 // not contain an inner type `reverse_iterator`.
4339 // If the container is iterable in reverse, then order might actually matter.
4340 template <typename T>
4341 struct IsHashTable {
4342 private:
4343 template <typename U>
4344 static char test(typename U::hasher*, typename U::reverse_iterator*);
4345 template <typename U>
4346 static int test(typename U::hasher*, ...);
4347 template <typename U>
4348 static char test(...);
4349
4350 public:
4351 static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
4352 };
4353
4354 template <typename T>
4355 const bool IsHashTable<T>::value;
4356
4357 template <typename C,
4358 bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
4359 struct IsRecursiveContainerImpl;
4360
4361 template <typename C>
4362 struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
4363
4364 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
4365 // obey the same inconsistencies as the IsContainerTest, namely check if
4366 // something is a container is relying on only const_iterator in C++11 and
4367 // is relying on both const_iterator and iterator otherwise
4368 template <typename C>
4369 struct IsRecursiveContainerImpl<C, true> {
4370 using value_type = decltype(*std::declval<typename C::const_iterator>());
4371 using type =
4372 std::is_same<typename std::remove_const<
4373 typename std::remove_reference<value_type>::type>::type,
4374 C>;
4375 };
4376
4377 // IsRecursiveContainer<Type> is a unary compile-time predicate that
4378 // evaluates whether C is a recursive container type. A recursive container
4379 // type is a container type whose value_type is equal to the container type
4380 // itself. An example for a recursive container type is
4381 // boost::filesystem::path, whose iterator has a value_type that is equal to
4382 // boost::filesystem::path.
4383 template <typename C>
4384 struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
4385
4386 // Utilities for native arrays.
4387
4388 // ArrayEq() compares two k-dimensional native arrays using the
4389 // elements' operator==, where k can be any integer >= 0. When k is
4390 // 0, ArrayEq() degenerates into comparing a single pair of values.
4391
4392 template <typename T, typename U>
4393 bool ArrayEq(const T* lhs, size_t size, const U* rhs);
4394
4395 // This generic version is used when k is 0.
4396 template <typename T, typename U>
4397 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
4398
4399 // This overload is used when k >= 1.
4400 template <typename T, typename U, size_t N>
4401 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
4402 return internal::ArrayEq(lhs, N, rhs);
4403 }
4404
4405 // This helper reduces code bloat. If we instead put its logic inside
4406 // the previous ArrayEq() function, arrays with different sizes would
4407 // lead to different copies of the template code.
4408 template <typename T, typename U>
4409 bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
4410 for (size_t i = 0; i != size; i++) {
4411 if (!internal::ArrayEq(lhs[i], rhs[i]))
4412 return false;
4413 }
4414 return true;
4415 }
4416
4417 // Finds the first element in the iterator range [begin, end) that
4418 // equals elem. Element may be a native array type itself.
4419 template <typename Iter, typename Element>
4420 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
4421 for (Iter it = begin; it != end; ++it) {
4422 if (internal::ArrayEq(*it, elem))
4423 return it;
4424 }
4425 return end;
4426 }
4427
4428 // CopyArray() copies a k-dimensional native array using the elements'
4429 // operator=, where k can be any integer >= 0. When k is 0,
4430 // CopyArray() degenerates into copying a single value.
4431
4432 template <typename T, typename U>
4433 void CopyArray(const T* from, size_t size, U* to);
4434
4435 // This generic version is used when k is 0.
4436 template <typename T, typename U>
4437 inline void CopyArray(const T& from, U* to) { *to = from; }
4438
4439 // This overload is used when k >= 1.
4440 template <typename T, typename U, size_t N>
4441 inline void CopyArray(const T(&from)[N], U(*to)[N]) {
4442 internal::CopyArray(from, N, *to);
4443 }
4444
4445 // This helper reduces code bloat. If we instead put its logic inside
4446 // the previous CopyArray() function, arrays with different sizes
4447 // would lead to different copies of the template code.
4448 template <typename T, typename U>
4449 void CopyArray(const T* from, size_t size, U* to) {
4450 for (size_t i = 0; i != size; i++) {
4451 internal::CopyArray(from[i], to + i);
4452 }
4453 }
4454
4455 // The relation between an NativeArray object (see below) and the
4456 // native array it represents.
4457 // We use 2 different structs to allow non-copyable types to be used, as long
4458 // as RelationToSourceReference() is passed.
4459 struct RelationToSourceReference {};
4460 struct RelationToSourceCopy {};
4461
4462 // Adapts a native array to a read-only STL-style container. Instead
4463 // of the complete STL container concept, this adaptor only implements
4464 // members useful for Google Mock's container matchers. New members
4465 // should be added as needed. To simplify the implementation, we only
4466 // support Element being a raw type (i.e. having no top-level const or
4467 // reference modifier). It's the client's responsibility to satisfy
4468 // this requirement. Element can be an array type itself (hence
4469 // multi-dimensional arrays are supported).
4470 template <typename Element>
4471 class NativeArray {
4472 public:
4473 // STL-style container typedefs.
4474 typedef Element value_type;
4475 typedef Element* iterator;
4476 typedef const Element* const_iterator;
4477
4478 // Constructs from a native array. References the source.
4479 NativeArray(const Element* array, size_t count, RelationToSourceReference) {
4480 InitRef(array, count);
4481 }
4482
4483 // Constructs from a native array. Copies the source.
4484 NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
4485 InitCopy(array, count);
4486 }
4487
4488 // Copy constructor.
4489 NativeArray(const NativeArray& rhs) {
4490 (this->*rhs.clone_)(rhs.array_, rhs.size_);
4491 }
4492
4493 ~NativeArray() {
4494 if (clone_ != &NativeArray::InitRef)
4495 delete[] array_;
4496 }
4497
4498 // STL-style container methods.
4499 size_t size() const { return size_; }
4500 const_iterator begin() const { return array_; }
4501 const_iterator end() const { return array_ + size_; }
4502 bool operator==(const NativeArray& rhs) const {
4503 return size() == rhs.size() &&
4504 ArrayEq(begin(), size(), rhs.begin());
4505 }
4506
4507 private:
4508 static_assert(!std::is_const<Element>::value, "Type must not be const");
4509 static_assert(!std::is_reference<Element>::value,
4510 "Type must not be a reference");
4511
4512 // Initializes this object with a copy of the input.
4513 void InitCopy(const Element* array, size_t a_size) {
4514 Element* const copy = new Element[a_size];
4515 CopyArray(array, a_size, copy);
4516 array_ = copy;
4517 size_ = a_size;
4518 clone_ = &NativeArray::InitCopy;
4519 }
4520
4521 // Initializes this object with a reference of the input.
4522 void InitRef(const Element* array, size_t a_size) {
4523 array_ = array;
4524 size_ = a_size;
4525 clone_ = &NativeArray::InitRef;
4526 }
4527
4528 const Element* array_;
4529 size_t size_;
4530 void (NativeArray::*clone_)(const Element*, size_t);
4531 };
4532
4533 // Backport of std::index_sequence.
4534 template <size_t... Is>
4535 struct IndexSequence {
4536 using type = IndexSequence;
4537 };
4538
4539 // Double the IndexSequence, and one if plus_one is true.
4540 template <bool plus_one, typename T, size_t sizeofT>
4541 struct DoubleSequence;
4542 template <size_t... I, size_t sizeofT>
4543 struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
4544 using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
4545 };
4546 template <size_t... I, size_t sizeofT>
4547 struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
4548 using type = IndexSequence<I..., (sizeofT + I)...>;
4549 };
4550
4551 // Backport of std::make_index_sequence.
4552 // It uses O(ln(N)) instantiation depth.
4553 template <size_t N>
4554 struct MakeIndexSequenceImpl
4555 : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
4556 N / 2>::type {};
4557
4558 template <>
4559 struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
4560
4561 template <size_t N>
4562 using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
4563
4564 template <typename... T>
4565 using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
4566
4567 template <size_t>
4568 struct Ignore {
4569 Ignore(...); // NOLINT
4570 };
4571
4572 template <typename>
4573 struct ElemFromListImpl;
4574 template <size_t... I>
4575 struct ElemFromListImpl<IndexSequence<I...>> {
4576 // We make Ignore a template to solve a problem with MSVC.
4577 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
4578 // MSVC doesn't understand how to deal with that pack expansion.
4579 // Use `0 * I` to have a single instantiation of Ignore.
4580 template <typename R>
4581 static R Apply(Ignore<0 * I>..., R (*)(), ...);
4582 };
4583
4584 template <size_t N, typename... T>
4585 struct ElemFromList {
4586 using type =
4587 decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
4588 static_cast<T (*)()>(nullptr)...));
4589 };
4590
4591 struct FlatTupleConstructTag {};
4592
4593 template <typename... T>
4594 class FlatTuple;
4595
4596 template <typename Derived, size_t I>
4597 struct FlatTupleElemBase;
4598
4599 template <typename... T, size_t I>
4600 struct FlatTupleElemBase<FlatTuple<T...>, I> {
4601 using value_type = typename ElemFromList<I, T...>::type;
4602 FlatTupleElemBase() = default;
4603 template <typename Arg>
4604 explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
4605 : value(std::forward<Arg>(t)) {}
4606 value_type value;
4607 };
4608
4609 template <typename Derived, typename Idx>
4610 struct FlatTupleBase;
4611
4612 template <size_t... Idx, typename... T>
4613 struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
4614 : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
4615 using Indices = IndexSequence<Idx...>;
4616 FlatTupleBase() = default;
4617 template <typename... Args>
4618 explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
4619 : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
4620 std::forward<Args>(args))... {}
4621
4622 template <size_t I>
4623 const typename ElemFromList<I, T...>::type& Get() const {
4624 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4625 }
4626
4627 template <size_t I>
4628 typename ElemFromList<I, T...>::type& Get() {
4629 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4630 }
4631
4632 template <typename F>
4633 auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4634 return std::forward<F>(f)(Get<Idx>()...);
4635 }
4636
4637 template <typename F>
4638 auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4639 return std::forward<F>(f)(Get<Idx>()...);
4640 }
4641 };
4642
4643 // Analog to std::tuple but with different tradeoffs.
4644 // This class minimizes the template instantiation depth, thus allowing more
4645 // elements than std::tuple would. std::tuple has been seen to require an
4646 // instantiation depth of more than 10x the number of elements in some
4647 // implementations.
4648 // FlatTuple and ElemFromList are not recursive and have a fixed depth
4649 // regardless of T...
4650 // MakeIndexSequence, on the other hand, it is recursive but with an
4651 // instantiation depth of O(ln(N)).
4652 template <typename... T>
4653 class FlatTuple
4654 : private FlatTupleBase<FlatTuple<T...>,
4655 typename MakeIndexSequence<sizeof...(T)>::type> {
4656 using Indices = typename FlatTupleBase<
4657 FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
4658
4659 public:
4660 FlatTuple() = default;
4661 template <typename... Args>
4662 explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
4663 : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
4664
4665 using FlatTuple::FlatTupleBase::Apply;
4666 using FlatTuple::FlatTupleBase::Get;
4667 };
4668
4669 // Utility functions to be called with static_assert to induce deprecation
4670 // warnings.
4671 GTEST_INTERNAL_DEPRECATED(
4672 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
4673 "INSTANTIATE_TEST_SUITE_P")
4674 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
4675
4676 GTEST_INTERNAL_DEPRECATED(
4677 "TYPED_TEST_CASE_P is deprecated, please use "
4678 "TYPED_TEST_SUITE_P")
4679 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
4680
4681 GTEST_INTERNAL_DEPRECATED(
4682 "TYPED_TEST_CASE is deprecated, please use "
4683 "TYPED_TEST_SUITE")
4684 constexpr bool TypedTestCaseIsDeprecated() { return true; }
4685
4686 GTEST_INTERNAL_DEPRECATED(
4687 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
4688 "REGISTER_TYPED_TEST_SUITE_P")
4689 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
4690
4691 GTEST_INTERNAL_DEPRECATED(
4692 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
4693 "INSTANTIATE_TYPED_TEST_SUITE_P")
4694 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
4695
4696 } // namespace internal
4697 } // namespace testing
4698
4699 namespace std {
4700 // Some standard library implementations use `struct tuple_size` and some use
4701 // `class tuple_size`. Clang warns about the mismatch.
4702 // https://reviews.llvm.org/D55466
4703 #ifdef __clang__
4704 #pragma clang diagnostic push
4705 #pragma clang diagnostic ignored "-Wmismatched-tags"
4706 #endif
4707 template <typename... Ts>
4708 struct tuple_size<testing::internal::FlatTuple<Ts...>>
4709 : std::integral_constant<size_t, sizeof...(Ts)> {};
4710 #ifdef __clang__
4711 #pragma clang diagnostic pop
4712 #endif
4713 } // namespace std
4714
4715 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
4716 ::testing::internal::AssertHelper(result_type, file, line, message) \
4717 = ::testing::Message()
4718
4719 #define GTEST_MESSAGE_(message, result_type) \
4720 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
4721
4722 #define GTEST_FATAL_FAILURE_(message) \
4723 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
4724
4725 #define GTEST_NONFATAL_FAILURE_(message) \
4726 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
4727
4728 #define GTEST_SUCCESS_(message) \
4729 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
4730
4731 #define GTEST_SKIP_(message) \
4732 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
4733
4734 // Suppress MSVC warning 4072 (unreachable code) for the code following
4735 // statement if it returns or throws (or doesn't return or throw in some
4736 // situations).
4737 // NOTE: The "else" is important to keep this expansion to prevent a top-level
4738 // "else" from attaching to our "if".
4739 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
4740 if (::testing::internal::AlwaysTrue()) { \
4741 statement; \
4742 } else /* NOLINT */ \
4743 static_assert(true, "") // User must have a semicolon after expansion.
4744
4745 #if GTEST_HAS_EXCEPTIONS
4746
4747 namespace testing {
4748 namespace internal {
4749
4750 class NeverThrown {
4751 public:
4752 const char* what() const noexcept {
4753 return "this exception should never be thrown";
4754 }
4755 };
4756
4757 } // namespace internal
4758 } // namespace testing
4759
4760 #if GTEST_HAS_RTTI
4761
4762 #define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
4763
4764 #else // GTEST_HAS_RTTI
4765
4766 #define GTEST_EXCEPTION_TYPE_(e) \
4767 std::string { "an std::exception-derived error" }
4768
4769 #endif // GTEST_HAS_RTTI
4770
4771 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4772 catch (typename std::conditional< \
4773 std::is_same<typename std::remove_cv<typename std::remove_reference< \
4774 expected_exception>::type>::type, \
4775 std::exception>::value, \
4776 const ::testing::internal::NeverThrown&, const std::exception&>::type \
4777 e) { \
4778 gtest_msg.value = "Expected: " #statement \
4779 " throws an exception of type " #expected_exception \
4780 ".\n Actual: it throws "; \
4781 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4782 gtest_msg.value += " with description \""; \
4783 gtest_msg.value += e.what(); \
4784 gtest_msg.value += "\"."; \
4785 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4786 }
4787
4788 #else // GTEST_HAS_EXCEPTIONS
4789
4790 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
4791
4792 #endif // GTEST_HAS_EXCEPTIONS
4793
4794 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
4795 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4796 if (::testing::internal::TrueWithString gtest_msg{}) { \
4797 bool gtest_caught_expected = false; \
4798 try { \
4799 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4800 } catch (expected_exception const&) { \
4801 gtest_caught_expected = true; \
4802 } \
4803 GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4804 catch (...) { \
4805 gtest_msg.value = "Expected: " #statement \
4806 " throws an exception of type " #expected_exception \
4807 ".\n Actual: it throws a different type."; \
4808 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4809 } \
4810 if (!gtest_caught_expected) { \
4811 gtest_msg.value = "Expected: " #statement \
4812 " throws an exception of type " #expected_exception \
4813 ".\n Actual: it throws nothing."; \
4814 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4815 } \
4816 } else /*NOLINT*/ \
4817 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
4818 : fail(gtest_msg.value.c_str())
4819
4820 #if GTEST_HAS_EXCEPTIONS
4821
4822 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
4823 catch (std::exception const& e) { \
4824 gtest_msg.value = "it throws "; \
4825 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4826 gtest_msg.value += " with description \""; \
4827 gtest_msg.value += e.what(); \
4828 gtest_msg.value += "\"."; \
4829 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4830 }
4831
4832 #else // GTEST_HAS_EXCEPTIONS
4833
4834 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
4835
4836 #endif // GTEST_HAS_EXCEPTIONS
4837
4838 #define GTEST_TEST_NO_THROW_(statement, fail) \
4839 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4840 if (::testing::internal::TrueWithString gtest_msg{}) { \
4841 try { \
4842 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4843 } \
4844 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
4845 catch (...) { \
4846 gtest_msg.value = "it throws."; \
4847 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4848 } \
4849 } else \
4850 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
4851 fail(("Expected: " #statement " doesn't throw an exception.\n" \
4852 " Actual: " + gtest_msg.value).c_str())
4853
4854 #define GTEST_TEST_ANY_THROW_(statement, fail) \
4855 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4856 if (::testing::internal::AlwaysTrue()) { \
4857 bool gtest_caught_any = false; \
4858 try { \
4859 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4860 } \
4861 catch (...) { \
4862 gtest_caught_any = true; \
4863 } \
4864 if (!gtest_caught_any) { \
4865 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
4866 } \
4867 } else \
4868 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
4869 fail("Expected: " #statement " throws an exception.\n" \
4870 " Actual: it doesn't.")
4871
4872
4873 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
4874 // either a boolean expression or an AssertionResult. text is a textual
4875 // representation of expression as it was passed into the EXPECT_TRUE.
4876 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
4877 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4878 if (const ::testing::AssertionResult gtest_ar_ = \
4879 ::testing::AssertionResult(expression)) \
4880 ; \
4881 else \
4882 fail(::testing::internal::GetBoolAssertionFailureMessage(\
4883 gtest_ar_, text, #actual, #expected).c_str())
4884
4885 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
4886 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4887 if (::testing::internal::AlwaysTrue()) { \
4888 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
4889 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4890 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
4891 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
4892 } \
4893 } else \
4894 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
4895 fail("Expected: " #statement " doesn't generate new fatal " \
4896 "failures in the current thread.\n" \
4897 " Actual: it does.")
4898
4899 // Expands to the name of the class that implements the given test.
4900 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4901 test_suite_name##_##test_name##_Test
4902
4903 // Helper macro for defining tests.
4904 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
4905 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
4906 "test_suite_name must not be empty"); \
4907 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
4908 "test_name must not be empty"); \
4909 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4910 : public parent_class { \
4911 public: \
4912 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
4913 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
4914 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4915 test_name)); \
4916 GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4917 test_name)); \
4918 \
4919 private: \
4920 void TestBody() override; \
4921 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
4922 }; \
4923 \
4924 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
4925 test_name)::test_info_ = \
4926 ::testing::internal::MakeAndRegisterTestInfo( \
4927 #test_suite_name, #test_name, nullptr, nullptr, \
4928 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
4929 ::testing::internal::SuiteApiResolver< \
4930 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
4931 ::testing::internal::SuiteApiResolver< \
4932 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
4933 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
4934 test_suite_name, test_name)>); \
4935 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
4936
4937 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
4938 // Copyright 2005, Google Inc.
4939 // All rights reserved.
4940 //
4941 // Redistribution and use in source and binary forms, with or without
4942 // modification, are permitted provided that the following conditions are
4943 // met:
4944 //
4945 // * Redistributions of source code must retain the above copyright
4946 // notice, this list of conditions and the following disclaimer.
4947 // * Redistributions in binary form must reproduce the above
4948 // copyright notice, this list of conditions and the following disclaimer
4949 // in the documentation and/or other materials provided with the
4950 // distribution.
4951 // * Neither the name of Google Inc. nor the names of its
4952 // contributors may be used to endorse or promote products derived from
4953 // this software without specific prior written permission.
4954 //
4955 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4956 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4957 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4958 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
4959 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
4960 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
4961 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
4962 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
4963 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4964 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
4965 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4966
4967 //
4968 // The Google C++ Testing and Mocking Framework (Google Test)
4969 //
4970 // This header file defines the public API for death tests. It is
4971 // #included by gtest.h so a user doesn't need to include this
4972 // directly.
4973 // GOOGLETEST_CM0001 DO NOT DELETE
4974
4975 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
4976 #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
4977
4978 // Copyright 2005, Google Inc.
4979 // All rights reserved.
4980 //
4981 // Redistribution and use in source and binary forms, with or without
4982 // modification, are permitted provided that the following conditions are
4983 // met:
4984 //
4985 // * Redistributions of source code must retain the above copyright
4986 // notice, this list of conditions and the following disclaimer.
4987 // * Redistributions in binary form must reproduce the above
4988 // copyright notice, this list of conditions and the following disclaimer
4989 // in the documentation and/or other materials provided with the
4990 // distribution.
4991 // * Neither the name of Google Inc. nor the names of its
4992 // contributors may be used to endorse or promote products derived from
4993 // this software without specific prior written permission.
4994 //
4995 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4996 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4997 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4998 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
4999 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5000 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5001 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5002 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5003 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5004 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5005 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5006 //
5007 // The Google C++ Testing and Mocking Framework (Google Test)
5008 //
5009 // This header file defines internal utilities needed for implementing
5010 // death tests. They are subject to change without notice.
5011 // GOOGLETEST_CM0001 DO NOT DELETE
5012
5013 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
5014 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
5015
5016 // Copyright 2007, Google Inc.
5017 // All rights reserved.
5018 //
5019 // Redistribution and use in source and binary forms, with or without
5020 // modification, are permitted provided that the following conditions are
5021 // met:
5022 //
5023 // * Redistributions of source code must retain the above copyright
5024 // notice, this list of conditions and the following disclaimer.
5025 // * Redistributions in binary form must reproduce the above
5026 // copyright notice, this list of conditions and the following disclaimer
5027 // in the documentation and/or other materials provided with the
5028 // distribution.
5029 // * Neither the name of Google Inc. nor the names of its
5030 // contributors may be used to endorse or promote products derived from
5031 // this software without specific prior written permission.
5032 //
5033 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5034 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5035 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5036 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5037 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5038 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5039 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5040 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5041 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5042 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5043 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5044
5045 // The Google C++ Testing and Mocking Framework (Google Test)
5046 //
5047 // This file implements just enough of the matcher interface to allow
5048 // EXPECT_DEATH and friends to accept a matcher argument.
5049
5050 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
5051 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
5052
5053 #include <atomic>
5054 #include <memory>
5055 #include <ostream>
5056 #include <string>
5057 #include <type_traits>
5058
5059 // Copyright 2007, Google Inc.
5060 // All rights reserved.
5061 //
5062 // Redistribution and use in source and binary forms, with or without
5063 // modification, are permitted provided that the following conditions are
5064 // met:
5065 //
5066 // * Redistributions of source code must retain the above copyright
5067 // notice, this list of conditions and the following disclaimer.
5068 // * Redistributions in binary form must reproduce the above
5069 // copyright notice, this list of conditions and the following disclaimer
5070 // in the documentation and/or other materials provided with the
5071 // distribution.
5072 // * Neither the name of Google Inc. nor the names of its
5073 // contributors may be used to endorse or promote products derived from
5074 // this software without specific prior written permission.
5075 //
5076 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5077 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5078 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5079 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5080 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5081 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5082 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5083 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5084 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5085 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5086 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5087
5088
5089 // Google Test - The Google C++ Testing and Mocking Framework
5090 //
5091 // This file implements a universal value printer that can print a
5092 // value of any type T:
5093 //
5094 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
5095 //
5096 // A user can teach this function how to print a class type T by
5097 // defining either operator<<() or PrintTo() in the namespace that
5098 // defines T. More specifically, the FIRST defined function in the
5099 // following list will be used (assuming T is defined in namespace
5100 // foo):
5101 //
5102 // 1. foo::PrintTo(const T&, ostream*)
5103 // 2. operator<<(ostream&, const T&) defined in either foo or the
5104 // global namespace.
5105 //
5106 // However if T is an STL-style container then it is printed element-wise
5107 // unless foo::PrintTo(const T&, ostream*) is defined. Note that
5108 // operator<<() is ignored for container types.
5109 //
5110 // If none of the above is defined, it will print the debug string of
5111 // the value if it is a protocol buffer, or print the raw bytes in the
5112 // value otherwise.
5113 //
5114 // To aid debugging: when T is a reference type, the address of the
5115 // value is also printed; when T is a (const) char pointer, both the
5116 // pointer value and the NUL-terminated string it points to are
5117 // printed.
5118 //
5119 // We also provide some convenient wrappers:
5120 //
5121 // // Prints a value to a string. For a (const or not) char
5122 // // pointer, the NUL-terminated string (but not the pointer) is
5123 // // printed.
5124 // std::string ::testing::PrintToString(const T& value);
5125 //
5126 // // Prints a value tersely: for a reference type, the referenced
5127 // // value (but not the address) is printed; for a (const or not) char
5128 // // pointer, the NUL-terminated string (but not the pointer) is
5129 // // printed.
5130 // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
5131 //
5132 // // Prints value using the type inferred by the compiler. The difference
5133 // // from UniversalTersePrint() is that this function prints both the
5134 // // pointer and the NUL-terminated string for a (const or not) char pointer.
5135 // void ::testing::internal::UniversalPrint(const T& value, ostream*);
5136 //
5137 // // Prints the fields of a tuple tersely to a string vector, one
5138 // // element for each field. Tuple support must be enabled in
5139 // // gtest-port.h.
5140 // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
5141 // const Tuple& value);
5142 //
5143 // Known limitation:
5144 //
5145 // The print primitives print the elements of an STL-style container
5146 // using the compiler-inferred type of *iter where iter is a
5147 // const_iterator of the container. When const_iterator is an input
5148 // iterator but not a forward iterator, this inferred type may not
5149 // match value_type, and the print output may be incorrect. In
5150 // practice, this is rarely a problem as for most containers
5151 // const_iterator is a forward iterator. We'll fix this if there's an
5152 // actual need for it. Note that this fix cannot rely on value_type
5153 // being defined as many user-defined container types don't have
5154 // value_type.
5155
5156 // GOOGLETEST_CM0001 DO NOT DELETE
5157
5158 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
5159 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
5160
5161 #include <functional>
5162 #include <memory>
5163 #include <ostream> // NOLINT
5164 #include <sstream>
5165 #include <string>
5166 #include <tuple>
5167 #include <type_traits>
5168 #include <utility>
5169 #include <vector>
5170
5171
5172 #if GTEST_HAS_RTTI
5173 #include <typeindex>
5174 #include <typeinfo>
5175 #endif // GTEST_HAS_RTTI
5176
5177 namespace testing {
5178
5179 // Definitions in the internal* namespaces are subject to change without notice.
5180 // DO NOT USE THEM IN USER CODE!
5181 namespace internal {
5182
5183 template <typename T>
5184 void UniversalPrint(const T& value, ::std::ostream* os);
5185
5186 // Used to print an STL-style container when the user doesn't define
5187 // a PrintTo() for it.
5188 struct ContainerPrinter {
5189 template <typename T,
5190 typename = typename std::enable_if<
5191 (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
5192 !IsRecursiveContainer<T>::value>::type>
5193 static void PrintValue(const T& container, std::ostream* os) {
5194 const size_t kMaxCount = 32; // The maximum number of elements to print.
5195 *os << '{';
5196 size_t count = 0;
5197 for (auto&& elem : container) {
5198 if (count > 0) {
5199 *os << ',';
5200 if (count == kMaxCount) { // Enough has been printed.
5201 *os << " ...";
5202 break;
5203 }
5204 }
5205 *os << ' ';
5206 // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
5207 // handle `elem` being a native array.
5208 internal::UniversalPrint(elem, os);
5209 ++count;
5210 }
5211
5212 if (count > 0) {
5213 *os << ' ';
5214 }
5215 *os << '}';
5216 }
5217 };
5218
5219 // Used to print a pointer that is neither a char pointer nor a member
5220 // pointer, when the user doesn't define PrintTo() for it. (A member
5221 // variable pointer or member function pointer doesn't really point to
5222 // a location in the address space. Their representation is
5223 // implementation-defined. Therefore they will be printed as raw
5224 // bytes.)
5225 struct FunctionPointerPrinter {
5226 template <typename T, typename = typename std::enable_if<
5227 std::is_function<T>::value>::type>
5228 static void PrintValue(T* p, ::std::ostream* os) {
5229 if (p == nullptr) {
5230 *os << "NULL";
5231 } else {
5232 // T is a function type, so '*os << p' doesn't do what we want
5233 // (it just prints p as bool). We want to print p as a const
5234 // void*.
5235 *os << reinterpret_cast<const void*>(p);
5236 }
5237 }
5238 };
5239
5240 struct PointerPrinter {
5241 template <typename T>
5242 static void PrintValue(T* p, ::std::ostream* os) {
5243 if (p == nullptr) {
5244 *os << "NULL";
5245 } else {
5246 // T is not a function type. We just call << to print p,
5247 // relying on ADL to pick up user-defined << for their pointer
5248 // types, if any.
5249 *os << p;
5250 }
5251 }
5252 };
5253
5254 namespace internal_stream_operator_without_lexical_name_lookup {
5255
5256 // The presence of an operator<< here will terminate lexical scope lookup
5257 // straight away (even though it cannot be a match because of its argument
5258 // types). Thus, the two operator<< calls in StreamPrinter will find only ADL
5259 // candidates.
5260 struct LookupBlocker {};
5261 void operator<<(LookupBlocker, LookupBlocker);
5262
5263 struct StreamPrinter {
5264 template <typename T,
5265 // Don't accept member pointers here. We'd print them via implicit
5266 // conversion to bool, which isn't useful.
5267 typename = typename std::enable_if<
5268 !std::is_member_pointer<T>::value>::type,
5269 // Only accept types for which we can find a streaming operator via
5270 // ADL (possibly involving implicit conversions).
5271 typename = decltype(std::declval<std::ostream&>()
5272 << std::declval<const T&>())>
5273 static void PrintValue(const T& value, ::std::ostream* os) {
5274 // Call streaming operator found by ADL, possibly with implicit conversions
5275 // of the arguments.
5276 *os << value;
5277 }
5278 };
5279
5280 } // namespace internal_stream_operator_without_lexical_name_lookup
5281
5282 struct ProtobufPrinter {
5283 // We print a protobuf using its ShortDebugString() when the string
5284 // doesn't exceed this many characters; otherwise we print it using
5285 // DebugString() for better readability.
5286 static const size_t kProtobufOneLinerMaxLength = 50;
5287
5288 template <typename T,
5289 typename = typename std::enable_if<
5290 internal::HasDebugStringAndShortDebugString<T>::value>::type>
5291 static void PrintValue(const T& value, ::std::ostream* os) {
5292 std::string pretty_str = value.ShortDebugString();
5293 if (pretty_str.length() > kProtobufOneLinerMaxLength) {
5294 pretty_str = "\n" + value.DebugString();
5295 }
5296 *os << ("<" + pretty_str + ">");
5297 }
5298 };
5299
5300 struct ConvertibleToIntegerPrinter {
5301 // Since T has no << operator or PrintTo() but can be implicitly
5302 // converted to BiggestInt, we print it as a BiggestInt.
5303 //
5304 // Most likely T is an enum type (either named or unnamed), in which
5305 // case printing it as an integer is the desired behavior. In case
5306 // T is not an enum, printing it as an integer is the best we can do
5307 // given that it has no user-defined printer.
5308 static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
5309 *os << value;
5310 }
5311 };
5312
5313 struct ConvertibleToStringViewPrinter {
5314 #if GTEST_INTERNAL_HAS_STRING_VIEW
5315 static void PrintValue(internal::StringView value, ::std::ostream* os) {
5316 internal::UniversalPrint(value, os);
5317 }
5318 #endif
5319 };
5320
5321
5322 // Prints the given number of bytes in the given object to the given
5323 // ostream.
5324 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
5325 size_t count,
5326 ::std::ostream* os);
5327 struct RawBytesPrinter {
5328 // SFINAE on `sizeof` to make sure we have a complete type.
5329 template <typename T, size_t = sizeof(T)>
5330 static void PrintValue(const T& value, ::std::ostream* os) {
5331 PrintBytesInObjectTo(
5332 static_cast<const unsigned char*>(
5333 // Load bearing cast to void* to support iOS
5334 reinterpret_cast<const void*>(std::addressof(value))),
5335 sizeof(value), os);
5336 }
5337 };
5338
5339 struct FallbackPrinter {
5340 template <typename T>
5341 static void PrintValue(const T&, ::std::ostream* os) {
5342 *os << "(incomplete type)";
5343 }
5344 };
5345
5346 // Try every printer in order and return the first one that works.
5347 template <typename T, typename E, typename Printer, typename... Printers>
5348 struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
5349
5350 template <typename T, typename Printer, typename... Printers>
5351 struct FindFirstPrinter<
5352 T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
5353 Printer, Printers...> {
5354 using type = Printer;
5355 };
5356
5357 // Select the best printer in the following order:
5358 // - Print containers (they have begin/end/etc).
5359 // - Print function pointers.
5360 // - Print object pointers.
5361 // - Use the stream operator, if available.
5362 // - Print protocol buffers.
5363 // - Print types convertible to BiggestInt.
5364 // - Print types convertible to StringView, if available.
5365 // - Fallback to printing the raw bytes of the object.
5366 template <typename T>
5367 void PrintWithFallback(const T& value, ::std::ostream* os) {
5368 using Printer = typename FindFirstPrinter<
5369 T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
5370 internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
5371 ProtobufPrinter, ConvertibleToIntegerPrinter,
5372 ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
5373 Printer::PrintValue(value, os);
5374 }
5375
5376 // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
5377 // value of type ToPrint that is an operand of a comparison assertion
5378 // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
5379 // the comparison, and is used to help determine the best way to
5380 // format the value. In particular, when the value is a C string
5381 // (char pointer) and the other operand is an STL string object, we
5382 // want to format the C string as a string, since we know it is
5383 // compared by value with the string object. If the value is a char
5384 // pointer but the other operand is not an STL string object, we don't
5385 // know whether the pointer is supposed to point to a NUL-terminated
5386 // string, and thus want to print it as a pointer to be safe.
5387 //
5388 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
5389
5390 // The default case.
5391 template <typename ToPrint, typename OtherOperand>
5392 class FormatForComparison {
5393 public:
5394 static ::std::string Format(const ToPrint& value) {
5395 return ::testing::PrintToString(value);
5396 }
5397 };
5398
5399 // Array.
5400 template <typename ToPrint, size_t N, typename OtherOperand>
5401 class FormatForComparison<ToPrint[N], OtherOperand> {
5402 public:
5403 static ::std::string Format(const ToPrint* value) {
5404 return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
5405 }
5406 };
5407
5408 // By default, print C string as pointers to be safe, as we don't know
5409 // whether they actually point to a NUL-terminated string.
5410
5411 #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
5412 template <typename OtherOperand> \
5413 class FormatForComparison<CharType*, OtherOperand> { \
5414 public: \
5415 static ::std::string Format(CharType* value) { \
5416 return ::testing::PrintToString(static_cast<const void*>(value)); \
5417 } \
5418 }
5419
5420 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
5421 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
5422 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
5423 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
5424 #ifdef __cpp_char8_t
5425 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
5426 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
5427 #endif
5428 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
5429 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
5430 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
5431 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
5432
5433 #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
5434
5435 // If a C string is compared with an STL string object, we know it's meant
5436 // to point to a NUL-terminated string, and thus can print it as a string.
5437
5438 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
5439 template <> \
5440 class FormatForComparison<CharType*, OtherStringType> { \
5441 public: \
5442 static ::std::string Format(CharType* value) { \
5443 return ::testing::PrintToString(value); \
5444 } \
5445 }
5446
5447 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
5448 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
5449 #ifdef __cpp_char8_t
5450 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
5451 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
5452 #endif
5453 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
5454 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
5455 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
5456 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
5457
5458 #if GTEST_HAS_STD_WSTRING
5459 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
5460 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
5461 #endif
5462
5463 #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
5464
5465 // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
5466 // operand to be used in a failure message. The type (but not value)
5467 // of the other operand may affect the format. This allows us to
5468 // print a char* as a raw pointer when it is compared against another
5469 // char* or void*, and print it as a C string when it is compared
5470 // against an std::string object, for example.
5471 //
5472 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
5473 template <typename T1, typename T2>
5474 std::string FormatForComparisonFailureMessage(
5475 const T1& value, const T2& /* other_operand */) {
5476 return FormatForComparison<T1, T2>::Format(value);
5477 }
5478
5479 // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
5480 // value to the given ostream. The caller must ensure that
5481 // 'ostream_ptr' is not NULL, or the behavior is undefined.
5482 //
5483 // We define UniversalPrinter as a class template (as opposed to a
5484 // function template), as we need to partially specialize it for
5485 // reference types, which cannot be done with function templates.
5486 template <typename T>
5487 class UniversalPrinter;
5488
5489 // Prints the given value using the << operator if it has one;
5490 // otherwise prints the bytes in it. This is what
5491 // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
5492 // or overloaded for type T.
5493 //
5494 // A user can override this behavior for a class type Foo by defining
5495 // an overload of PrintTo() in the namespace where Foo is defined. We
5496 // give the user this option as sometimes defining a << operator for
5497 // Foo is not desirable (e.g. the coding style may prevent doing it,
5498 // or there is already a << operator but it doesn't do what the user
5499 // wants).
5500 template <typename T>
5501 void PrintTo(const T& value, ::std::ostream* os) {
5502 internal::PrintWithFallback(value, os);
5503 }
5504
5505 // The following list of PrintTo() overloads tells
5506 // UniversalPrinter<T>::Print() how to print standard types (built-in
5507 // types, strings, plain arrays, and pointers).
5508
5509 // Overloads for various char types.
5510 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
5511 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
5512 inline void PrintTo(char c, ::std::ostream* os) {
5513 // When printing a plain char, we always treat it as unsigned. This
5514 // way, the output won't be affected by whether the compiler thinks
5515 // char is signed or not.
5516 PrintTo(static_cast<unsigned char>(c), os);
5517 }
5518
5519 // Overloads for other simple built-in types.
5520 inline void PrintTo(bool x, ::std::ostream* os) {
5521 *os << (x ? "true" : "false");
5522 }
5523
5524 // Overload for wchar_t type.
5525 // Prints a wchar_t as a symbol if it is printable or as its internal
5526 // code otherwise and also as its decimal code (except for L'\0').
5527 // The L'\0' char is printed as "L'\\0'". The decimal code is printed
5528 // as signed integer when wchar_t is implemented by the compiler
5529 // as a signed type and is printed as an unsigned integer when wchar_t
5530 // is implemented as an unsigned type.
5531 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
5532
5533 GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
5534 inline void PrintTo(char16_t c, ::std::ostream* os) {
5535 PrintTo(ImplicitCast_<char32_t>(c), os);
5536 }
5537 #ifdef __cpp_char8_t
5538 inline void PrintTo(char8_t c, ::std::ostream* os) {
5539 PrintTo(ImplicitCast_<char32_t>(c), os);
5540 }
5541 #endif
5542
5543 // Overloads for C strings.
5544 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
5545 inline void PrintTo(char* s, ::std::ostream* os) {
5546 PrintTo(ImplicitCast_<const char*>(s), os);
5547 }
5548
5549 // signed/unsigned char is often used for representing binary data, so
5550 // we print pointers to it as void* to be safe.
5551 inline void PrintTo(const signed char* s, ::std::ostream* os) {
5552 PrintTo(ImplicitCast_<const void*>(s), os);
5553 }
5554 inline void PrintTo(signed char* s, ::std::ostream* os) {
5555 PrintTo(ImplicitCast_<const void*>(s), os);
5556 }
5557 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
5558 PrintTo(ImplicitCast_<const void*>(s), os);
5559 }
5560 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
5561 PrintTo(ImplicitCast_<const void*>(s), os);
5562 }
5563 #ifdef __cpp_char8_t
5564 // Overloads for u8 strings.
5565 void PrintTo(const char8_t* s, ::std::ostream* os);
5566 inline void PrintTo(char8_t* s, ::std::ostream* os) {
5567 PrintTo(ImplicitCast_<const char8_t*>(s), os);
5568 }
5569 #endif
5570 // Overloads for u16 strings.
5571 void PrintTo(const char16_t* s, ::std::ostream* os);
5572 inline void PrintTo(char16_t* s, ::std::ostream* os) {
5573 PrintTo(ImplicitCast_<const char16_t*>(s), os);
5574 }
5575 // Overloads for u32 strings.
5576 void PrintTo(const char32_t* s, ::std::ostream* os);
5577 inline void PrintTo(char32_t* s, ::std::ostream* os) {
5578 PrintTo(ImplicitCast_<const char32_t*>(s), os);
5579 }
5580
5581 // MSVC can be configured to define wchar_t as a typedef of unsigned
5582 // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
5583 // type. When wchar_t is a typedef, defining an overload for const
5584 // wchar_t* would cause unsigned short* be printed as a wide string,
5585 // possibly causing invalid memory accesses.
5586 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
5587 // Overloads for wide C strings
5588 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
5589 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
5590 PrintTo(ImplicitCast_<const wchar_t*>(s), os);
5591 }
5592 #endif
5593
5594 // Overload for C arrays. Multi-dimensional arrays are printed
5595 // properly.
5596
5597 // Prints the given number of elements in an array, without printing
5598 // the curly braces.
5599 template <typename T>
5600 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
5601 UniversalPrint(a[0], os);
5602 for (size_t i = 1; i != count; i++) {
5603 *os << ", ";
5604 UniversalPrint(a[i], os);
5605 }
5606 }
5607
5608 // Overloads for ::std::string.
5609 GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
5610 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
5611 PrintStringTo(s, os);
5612 }
5613
5614 // Overloads for ::std::u8string
5615 #ifdef __cpp_char8_t
5616 GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
5617 inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
5618 PrintU8StringTo(s, os);
5619 }
5620 #endif
5621
5622 // Overloads for ::std::u16string
5623 GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
5624 inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
5625 PrintU16StringTo(s, os);
5626 }
5627
5628 // Overloads for ::std::u32string
5629 GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
5630 inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
5631 PrintU32StringTo(s, os);
5632 }
5633
5634 // Overloads for ::std::wstring.
5635 #if GTEST_HAS_STD_WSTRING
5636 GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
5637 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
5638 PrintWideStringTo(s, os);
5639 }
5640 #endif // GTEST_HAS_STD_WSTRING
5641
5642 #if GTEST_INTERNAL_HAS_STRING_VIEW
5643 // Overload for internal::StringView.
5644 inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
5645 PrintTo(::std::string(sp), os);
5646 }
5647 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
5648
5649 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
5650
5651 template <typename T>
5652 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
5653 UniversalPrinter<T&>::Print(ref.get(), os);
5654 }
5655
5656 inline const void* VoidifyPointer(const void* p) { return p; }
5657 inline const void* VoidifyPointer(volatile const void* p) {
5658 return const_cast<const void*>(p);
5659 }
5660
5661 template <typename T, typename Ptr>
5662 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
5663 if (ptr == nullptr) {
5664 *os << "(nullptr)";
5665 } else {
5666 // We can't print the value. Just print the pointer..
5667 *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
5668 }
5669 }
5670 template <typename T, typename Ptr,
5671 typename = typename std::enable_if<!std::is_void<T>::value &&
5672 !std::is_array<T>::value>::type>
5673 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
5674 if (ptr == nullptr) {
5675 *os << "(nullptr)";
5676 } else {
5677 *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
5678 UniversalPrinter<T>::Print(*ptr, os);
5679 *os << ")";
5680 }
5681 }
5682
5683 template <typename T, typename D>
5684 void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
5685 (PrintSmartPointer<T>)(ptr, os, 0);
5686 }
5687
5688 template <typename T>
5689 void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
5690 (PrintSmartPointer<T>)(ptr, os, 0);
5691 }
5692
5693 // Helper function for printing a tuple. T must be instantiated with
5694 // a tuple type.
5695 template <typename T>
5696 void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
5697 ::std::ostream*) {}
5698
5699 template <typename T, size_t I>
5700 void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
5701 ::std::ostream* os) {
5702 PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
5703 GTEST_INTENTIONAL_CONST_COND_PUSH_()
5704 if (I > 1) {
5705 GTEST_INTENTIONAL_CONST_COND_POP_()
5706 *os << ", ";
5707 }
5708 UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
5709 std::get<I - 1>(t), os);
5710 }
5711
5712 template <typename... Types>
5713 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
5714 *os << "(";
5715 PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
5716 *os << ")";
5717 }
5718
5719 // Overload for std::pair.
5720 template <typename T1, typename T2>
5721 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
5722 *os << '(';
5723 // We cannot use UniversalPrint(value.first, os) here, as T1 may be
5724 // a reference type. The same for printing value.second.
5725 UniversalPrinter<T1>::Print(value.first, os);
5726 *os << ", ";
5727 UniversalPrinter<T2>::Print(value.second, os);
5728 *os << ')';
5729 }
5730
5731 #if GTEST_HAS_RTTI
5732 inline void PrintTo(const ::std::type_info& value, ::std::ostream* os) {
5733 internal::PrintTo<::std::type_info>(value, os);
5734 *os << " (\"" << value.name() << "\")";
5735 }
5736
5737 inline void PrintTo(const ::std::type_index& value, ::std::ostream* os) {
5738 internal::PrintTo<::std::type_index>(value, os);
5739 *os << " (\"" << value.name() << "\")";
5740 }
5741 #endif // GTEST_HAS_RTTI
5742
5743 // Implements printing a non-reference type T by letting the compiler
5744 // pick the right overload of PrintTo() for T.
5745 template <typename T>
5746 class UniversalPrinter {
5747 public:
5748 // MSVC warns about adding const to a function type, so we want to
5749 // disable the warning.
5750 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5751
5752 // Note: we deliberately don't call this PrintTo(), as that name
5753 // conflicts with ::testing::internal::PrintTo in the body of the
5754 // function.
5755 static void Print(const T& value, ::std::ostream* os) {
5756 // By default, ::testing::internal::PrintTo() is used for printing
5757 // the value.
5758 //
5759 // Thanks to Koenig look-up, if T is a class and has its own
5760 // PrintTo() function defined in its namespace, that function will
5761 // be visible here. Since it is more specific than the generic ones
5762 // in ::testing::internal, it will be picked by the compiler in the
5763 // following statement - exactly what we want.
5764 PrintTo(value, os);
5765 }
5766
5767 GTEST_DISABLE_MSC_WARNINGS_POP_()
5768 };
5769
5770 // Remove any const-qualifiers before passing a type to UniversalPrinter.
5771 template <typename T>
5772 class UniversalPrinter<const T> : public UniversalPrinter<T> {};
5773
5774 #if GTEST_INTERNAL_HAS_ANY
5775
5776 // Printer for std::any / absl::any
5777
5778 template <>
5779 class UniversalPrinter<Any> {
5780 public:
5781 static void Print(const Any& value, ::std::ostream* os) {
5782 if (value.has_value()) {
5783 *os << "value of type " << GetTypeName(value);
5784 } else {
5785 *os << "no value";
5786 }
5787 }
5788
5789 private:
5790 static std::string GetTypeName(const Any& value) {
5791 #if GTEST_HAS_RTTI
5792 return internal::GetTypeName(value.type());
5793 #else
5794 static_cast<void>(value); // possibly unused
5795 return "<unknown_type>";
5796 #endif // GTEST_HAS_RTTI
5797 }
5798 };
5799
5800 #endif // GTEST_INTERNAL_HAS_ANY
5801
5802 #if GTEST_INTERNAL_HAS_OPTIONAL
5803
5804 // Printer for std::optional / absl::optional
5805
5806 template <typename T>
5807 class UniversalPrinter<Optional<T>> {
5808 public:
5809 static void Print(const Optional<T>& value, ::std::ostream* os) {
5810 *os << '(';
5811 if (!value) {
5812 *os << "nullopt";
5813 } else {
5814 UniversalPrint(*value, os);
5815 }
5816 *os << ')';
5817 }
5818 };
5819
5820 #endif // GTEST_INTERNAL_HAS_OPTIONAL
5821
5822 #if GTEST_INTERNAL_HAS_VARIANT
5823
5824 // Printer for std::variant / absl::variant
5825
5826 template <typename... T>
5827 class UniversalPrinter<Variant<T...>> {
5828 public:
5829 static void Print(const Variant<T...>& value, ::std::ostream* os) {
5830 *os << '(';
5831 #if GTEST_HAS_ABSL
5832 absl::visit(Visitor{os, value.index()}, value);
5833 #else
5834 std::visit(Visitor{os, value.index()}, value);
5835 #endif // GTEST_HAS_ABSL
5836 *os << ')';
5837 }
5838
5839 private:
5840 struct Visitor {
5841 template <typename U>
5842 void operator()(const U& u) const {
5843 *os << "'" << GetTypeName<U>() << "(index = " << index
5844 << ")' with value ";
5845 UniversalPrint(u, os);
5846 }
5847 ::std::ostream* os;
5848 std::size_t index;
5849 };
5850 };
5851
5852 #endif // GTEST_INTERNAL_HAS_VARIANT
5853
5854 // UniversalPrintArray(begin, len, os) prints an array of 'len'
5855 // elements, starting at address 'begin'.
5856 template <typename T>
5857 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
5858 if (len == 0) {
5859 *os << "{}";
5860 } else {
5861 *os << "{ ";
5862 const size_t kThreshold = 18;
5863 const size_t kChunkSize = 8;
5864 // If the array has more than kThreshold elements, we'll have to
5865 // omit some details by printing only the first and the last
5866 // kChunkSize elements.
5867 if (len <= kThreshold) {
5868 PrintRawArrayTo(begin, len, os);
5869 } else {
5870 PrintRawArrayTo(begin, kChunkSize, os);
5871 *os << ", ..., ";
5872 PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
5873 }
5874 *os << " }";
5875 }
5876 }
5877 // This overload prints a (const) char array compactly.
5878 GTEST_API_ void UniversalPrintArray(
5879 const char* begin, size_t len, ::std::ostream* os);
5880
5881 #ifdef __cpp_char8_t
5882 // This overload prints a (const) char8_t array compactly.
5883 GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
5884 ::std::ostream* os);
5885 #endif
5886
5887 // This overload prints a (const) char16_t array compactly.
5888 GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
5889 ::std::ostream* os);
5890
5891 // This overload prints a (const) char32_t array compactly.
5892 GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
5893 ::std::ostream* os);
5894
5895 // This overload prints a (const) wchar_t array compactly.
5896 GTEST_API_ void UniversalPrintArray(
5897 const wchar_t* begin, size_t len, ::std::ostream* os);
5898
5899 // Implements printing an array type T[N].
5900 template <typename T, size_t N>
5901 class UniversalPrinter<T[N]> {
5902 public:
5903 // Prints the given array, omitting some elements when there are too
5904 // many.
5905 static void Print(const T (&a)[N], ::std::ostream* os) {
5906 UniversalPrintArray(a, N, os);
5907 }
5908 };
5909
5910 // Implements printing a reference type T&.
5911 template <typename T>
5912 class UniversalPrinter<T&> {
5913 public:
5914 // MSVC warns about adding const to a function type, so we want to
5915 // disable the warning.
5916 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5917
5918 static void Print(const T& value, ::std::ostream* os) {
5919 // Prints the address of the value. We use reinterpret_cast here
5920 // as static_cast doesn't compile when T is a function type.
5921 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
5922
5923 // Then prints the value itself.
5924 UniversalPrint(value, os);
5925 }
5926
5927 GTEST_DISABLE_MSC_WARNINGS_POP_()
5928 };
5929
5930 // Prints a value tersely: for a reference type, the referenced value
5931 // (but not the address) is printed; for a (const) char pointer, the
5932 // NUL-terminated string (but not the pointer) is printed.
5933
5934 template <typename T>
5935 class UniversalTersePrinter {
5936 public:
5937 static void Print(const T& value, ::std::ostream* os) {
5938 UniversalPrint(value, os);
5939 }
5940 };
5941 template <typename T>
5942 class UniversalTersePrinter<T&> {
5943 public:
5944 static void Print(const T& value, ::std::ostream* os) {
5945 UniversalPrint(value, os);
5946 }
5947 };
5948 template <typename T, size_t N>
5949 class UniversalTersePrinter<T[N]> {
5950 public:
5951 static void Print(const T (&value)[N], ::std::ostream* os) {
5952 UniversalPrinter<T[N]>::Print(value, os);
5953 }
5954 };
5955 template <>
5956 class UniversalTersePrinter<const char*> {
5957 public:
5958 static void Print(const char* str, ::std::ostream* os) {
5959 if (str == nullptr) {
5960 *os << "NULL";
5961 } else {
5962 UniversalPrint(std::string(str), os);
5963 }
5964 }
5965 };
5966 template <>
5967 class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
5968 };
5969
5970 #ifdef __cpp_char8_t
5971 template <>
5972 class UniversalTersePrinter<const char8_t*> {
5973 public:
5974 static void Print(const char8_t* str, ::std::ostream* os) {
5975 if (str == nullptr) {
5976 *os << "NULL";
5977 } else {
5978 UniversalPrint(::std::u8string(str), os);
5979 }
5980 }
5981 };
5982 template <>
5983 class UniversalTersePrinter<char8_t*>
5984 : public UniversalTersePrinter<const char8_t*> {};
5985 #endif
5986
5987 template <>
5988 class UniversalTersePrinter<const char16_t*> {
5989 public:
5990 static void Print(const char16_t* str, ::std::ostream* os) {
5991 if (str == nullptr) {
5992 *os << "NULL";
5993 } else {
5994 UniversalPrint(::std::u16string(str), os);
5995 }
5996 }
5997 };
5998 template <>
5999 class UniversalTersePrinter<char16_t*>
6000 : public UniversalTersePrinter<const char16_t*> {};
6001
6002 template <>
6003 class UniversalTersePrinter<const char32_t*> {
6004 public:
6005 static void Print(const char32_t* str, ::std::ostream* os) {
6006 if (str == nullptr) {
6007 *os << "NULL";
6008 } else {
6009 UniversalPrint(::std::u32string(str), os);
6010 }
6011 }
6012 };
6013 template <>
6014 class UniversalTersePrinter<char32_t*>
6015 : public UniversalTersePrinter<const char32_t*> {};
6016
6017 #if GTEST_HAS_STD_WSTRING
6018 template <>
6019 class UniversalTersePrinter<const wchar_t*> {
6020 public:
6021 static void Print(const wchar_t* str, ::std::ostream* os) {
6022 if (str == nullptr) {
6023 *os << "NULL";
6024 } else {
6025 UniversalPrint(::std::wstring(str), os);
6026 }
6027 }
6028 };
6029 #endif
6030
6031 template <>
6032 class UniversalTersePrinter<wchar_t*> {
6033 public:
6034 static void Print(wchar_t* str, ::std::ostream* os) {
6035 UniversalTersePrinter<const wchar_t*>::Print(str, os);
6036 }
6037 };
6038
6039 template <typename T>
6040 void UniversalTersePrint(const T& value, ::std::ostream* os) {
6041 UniversalTersePrinter<T>::Print(value, os);
6042 }
6043
6044 // Prints a value using the type inferred by the compiler. The
6045 // difference between this and UniversalTersePrint() is that for a
6046 // (const) char pointer, this prints both the pointer and the
6047 // NUL-terminated string.
6048 template <typename T>
6049 void UniversalPrint(const T& value, ::std::ostream* os) {
6050 // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
6051 // UniversalPrinter with T directly.
6052 typedef T T1;
6053 UniversalPrinter<T1>::Print(value, os);
6054 }
6055
6056 typedef ::std::vector< ::std::string> Strings;
6057
6058 // Tersely prints the first N fields of a tuple to a string vector,
6059 // one element for each field.
6060 template <typename Tuple>
6061 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
6062 Strings*) {}
6063 template <typename Tuple, size_t I>
6064 void TersePrintPrefixToStrings(const Tuple& t,
6065 std::integral_constant<size_t, I>,
6066 Strings* strings) {
6067 TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
6068 strings);
6069 ::std::stringstream ss;
6070 UniversalTersePrint(std::get<I - 1>(t), &ss);
6071 strings->push_back(ss.str());
6072 }
6073
6074 // Prints the fields of a tuple tersely to a string vector, one
6075 // element for each field. See the comment before
6076 // UniversalTersePrint() for how we define "tersely".
6077 template <typename Tuple>
6078 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
6079 Strings result;
6080 TersePrintPrefixToStrings(
6081 value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
6082 &result);
6083 return result;
6084 }
6085
6086 } // namespace internal
6087
6088 template <typename T>
6089 ::std::string PrintToString(const T& value) {
6090 ::std::stringstream ss;
6091 internal::UniversalTersePrinter<T>::Print(value, &ss);
6092 return ss.str();
6093 }
6094
6095 } // namespace testing
6096
6097 // Include any custom printer added by the local installation.
6098 // We must include this header at the end to make sure it can use the
6099 // declarations from this file.
6100 // Copyright 2015, Google Inc.
6101 // All rights reserved.
6102 //
6103 // Redistribution and use in source and binary forms, with or without
6104 // modification, are permitted provided that the following conditions are
6105 // met:
6106 //
6107 // * Redistributions of source code must retain the above copyright
6108 // notice, this list of conditions and the following disclaimer.
6109 // * Redistributions in binary form must reproduce the above
6110 // copyright notice, this list of conditions and the following disclaimer
6111 // in the documentation and/or other materials provided with the
6112 // distribution.
6113 // * Neither the name of Google Inc. nor the names of its
6114 // contributors may be used to endorse or promote products derived from
6115 // this software without specific prior written permission.
6116 //
6117 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6118 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6119 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6120 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6121 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6122 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6123 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6124 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6125 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6126 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6127 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6128 //
6129 // This file provides an injection point for custom printers in a local
6130 // installation of gTest.
6131 // It will be included from gtest-printers.h and the overrides in this file
6132 // will be visible to everyone.
6133 //
6134 // Injection point for custom user configurations. See README for details
6135 //
6136 // ** Custom implementation starts here **
6137
6138 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6139 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6140
6141 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6142
6143 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
6144
6145 // MSVC warning C5046 is new as of VS2017 version 15.8.
6146 #if defined(_MSC_VER) && _MSC_VER >= 1915
6147 #define GTEST_MAYBE_5046_ 5046
6148 #else
6149 #define GTEST_MAYBE_5046_
6150 #endif
6151
6152 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
6153 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
6154 clients of class B */
6155 /* Symbol involving type with internal linkage not defined */)
6156
6157 namespace testing {
6158
6159 // To implement a matcher Foo for type T, define:
6160 // 1. a class FooMatcherMatcher that implements the matcher interface:
6161 // using is_gtest_matcher = void;
6162 // bool MatchAndExplain(const T&, std::ostream*);
6163 // (MatchResultListener* can also be used instead of std::ostream*)
6164 // void DescribeTo(std::ostream*);
6165 // void DescribeNegationTo(std::ostream*);
6166 //
6167 // 2. a factory function that creates a Matcher<T> object from a
6168 // FooMatcherMatcher.
6169
6170 class MatchResultListener {
6171 public:
6172 // Creates a listener object with the given underlying ostream. The
6173 // listener does not own the ostream, and does not dereference it
6174 // in the constructor or destructor.
6175 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
6176 virtual ~MatchResultListener() = 0; // Makes this class abstract.
6177
6178 // Streams x to the underlying ostream; does nothing if the ostream
6179 // is NULL.
6180 template <typename T>
6181 MatchResultListener& operator<<(const T& x) {
6182 if (stream_ != nullptr) *stream_ << x;
6183 return *this;
6184 }
6185
6186 // Returns the underlying ostream.
6187 ::std::ostream* stream() { return stream_; }
6188
6189 // Returns true if and only if the listener is interested in an explanation
6190 // of the match result. A matcher's MatchAndExplain() method can use
6191 // this information to avoid generating the explanation when no one
6192 // intends to hear it.
6193 bool IsInterested() const { return stream_ != nullptr; }
6194
6195 private:
6196 ::std::ostream* const stream_;
6197
6198 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
6199 };
6200
6201 inline MatchResultListener::~MatchResultListener() {
6202 }
6203
6204 // An instance of a subclass of this knows how to describe itself as a
6205 // matcher.
6206 class MatcherDescriberInterface {
6207 public:
6208 virtual ~MatcherDescriberInterface() {}
6209
6210 // Describes this matcher to an ostream. The function should print
6211 // a verb phrase that describes the property a value matching this
6212 // matcher should have. The subject of the verb phrase is the value
6213 // being matched. For example, the DescribeTo() method of the Gt(7)
6214 // matcher prints "is greater than 7".
6215 virtual void DescribeTo(::std::ostream* os) const = 0;
6216
6217 // Describes the negation of this matcher to an ostream. For
6218 // example, if the description of this matcher is "is greater than
6219 // 7", the negated description could be "is not greater than 7".
6220 // You are not required to override this when implementing
6221 // MatcherInterface, but it is highly advised so that your matcher
6222 // can produce good error messages.
6223 virtual void DescribeNegationTo(::std::ostream* os) const {
6224 *os << "not (";
6225 DescribeTo(os);
6226 *os << ")";
6227 }
6228 };
6229
6230 // The implementation of a matcher.
6231 template <typename T>
6232 class MatcherInterface : public MatcherDescriberInterface {
6233 public:
6234 // Returns true if and only if the matcher matches x; also explains the
6235 // match result to 'listener' if necessary (see the next paragraph), in
6236 // the form of a non-restrictive relative clause ("which ...",
6237 // "whose ...", etc) that describes x. For example, the
6238 // MatchAndExplain() method of the Pointee(...) matcher should
6239 // generate an explanation like "which points to ...".
6240 //
6241 // Implementations of MatchAndExplain() should add an explanation of
6242 // the match result *if and only if* they can provide additional
6243 // information that's not already present (or not obvious) in the
6244 // print-out of x and the matcher's description. Whether the match
6245 // succeeds is not a factor in deciding whether an explanation is
6246 // needed, as sometimes the caller needs to print a failure message
6247 // when the match succeeds (e.g. when the matcher is used inside
6248 // Not()).
6249 //
6250 // For example, a "has at least 10 elements" matcher should explain
6251 // what the actual element count is, regardless of the match result,
6252 // as it is useful information to the reader; on the other hand, an
6253 // "is empty" matcher probably only needs to explain what the actual
6254 // size is when the match fails, as it's redundant to say that the
6255 // size is 0 when the value is already known to be empty.
6256 //
6257 // You should override this method when defining a new matcher.
6258 //
6259 // It's the responsibility of the caller (Google Test) to guarantee
6260 // that 'listener' is not NULL. This helps to simplify a matcher's
6261 // implementation when it doesn't care about the performance, as it
6262 // can talk to 'listener' without checking its validity first.
6263 // However, in order to implement dummy listeners efficiently,
6264 // listener->stream() may be NULL.
6265 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
6266
6267 // Inherits these methods from MatcherDescriberInterface:
6268 // virtual void DescribeTo(::std::ostream* os) const = 0;
6269 // virtual void DescribeNegationTo(::std::ostream* os) const;
6270 };
6271
6272 namespace internal {
6273
6274 struct AnyEq {
6275 template <typename A, typename B>
6276 bool operator()(const A& a, const B& b) const { return a == b; }
6277 };
6278 struct AnyNe {
6279 template <typename A, typename B>
6280 bool operator()(const A& a, const B& b) const { return a != b; }
6281 };
6282 struct AnyLt {
6283 template <typename A, typename B>
6284 bool operator()(const A& a, const B& b) const { return a < b; }
6285 };
6286 struct AnyGt {
6287 template <typename A, typename B>
6288 bool operator()(const A& a, const B& b) const { return a > b; }
6289 };
6290 struct AnyLe {
6291 template <typename A, typename B>
6292 bool operator()(const A& a, const B& b) const { return a <= b; }
6293 };
6294 struct AnyGe {
6295 template <typename A, typename B>
6296 bool operator()(const A& a, const B& b) const { return a >= b; }
6297 };
6298
6299 // A match result listener that ignores the explanation.
6300 class DummyMatchResultListener : public MatchResultListener {
6301 public:
6302 DummyMatchResultListener() : MatchResultListener(nullptr) {}
6303
6304 private:
6305 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
6306 };
6307
6308 // A match result listener that forwards the explanation to a given
6309 // ostream. The difference between this and MatchResultListener is
6310 // that the former is concrete.
6311 class StreamMatchResultListener : public MatchResultListener {
6312 public:
6313 explicit StreamMatchResultListener(::std::ostream* os)
6314 : MatchResultListener(os) {}
6315
6316 private:
6317 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
6318 };
6319
6320 struct SharedPayloadBase {
6321 std::atomic<int> ref{1};
6322 void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
6323 bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
6324 };
6325
6326 template <typename T>
6327 struct SharedPayload : SharedPayloadBase {
6328 explicit SharedPayload(const T& v) : value(v) {}
6329 explicit SharedPayload(T&& v) : value(std::move(v)) {}
6330
6331 static void Destroy(SharedPayloadBase* shared) {
6332 delete static_cast<SharedPayload*>(shared);
6333 }
6334
6335 T value;
6336 };
6337
6338 template <typename T>
6339 using is_trivially_copy_constructible =
6340 #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
6341 std::has_trivial_copy_constructor<T>;
6342 #else
6343 std::is_trivially_copy_constructible<T>;
6344 #endif
6345
6346 // An internal class for implementing Matcher<T>, which will derive
6347 // from it. We put functionalities common to all Matcher<T>
6348 // specializations here to avoid code duplication.
6349 template <typename T>
6350 class MatcherBase : private MatcherDescriberInterface {
6351 public:
6352 // Returns true if and only if the matcher matches x; also explains the
6353 // match result to 'listener'.
6354 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
6355 GTEST_CHECK_(vtable_ != nullptr);
6356 return vtable_->match_and_explain(*this, x, listener);
6357 }
6358
6359 // Returns true if and only if this matcher matches x.
6360 bool Matches(const T& x) const {
6361 DummyMatchResultListener dummy;
6362 return MatchAndExplain(x, &dummy);
6363 }
6364
6365 // Describes this matcher to an ostream.
6366 void DescribeTo(::std::ostream* os) const final {
6367 GTEST_CHECK_(vtable_ != nullptr);
6368 vtable_->describe(*this, os, false);
6369 }
6370
6371 // Describes the negation of this matcher to an ostream.
6372 void DescribeNegationTo(::std::ostream* os) const final {
6373 GTEST_CHECK_(vtable_ != nullptr);
6374 vtable_->describe(*this, os, true);
6375 }
6376
6377 // Explains why x matches, or doesn't match, the matcher.
6378 void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
6379 StreamMatchResultListener listener(os);
6380 MatchAndExplain(x, &listener);
6381 }
6382
6383 // Returns the describer for this matcher object; retains ownership
6384 // of the describer, which is only guaranteed to be alive when
6385 // this matcher object is alive.
6386 const MatcherDescriberInterface* GetDescriber() const {
6387 if (vtable_ == nullptr) return nullptr;
6388 return vtable_->get_describer(*this);
6389 }
6390
6391 protected:
6392 MatcherBase() : vtable_(nullptr) {}
6393
6394 // Constructs a matcher from its implementation.
6395 template <typename U>
6396 explicit MatcherBase(const MatcherInterface<U>* impl) {
6397 Init(impl);
6398 }
6399
6400 template <typename M, typename = typename std::remove_reference<
6401 M>::type::is_gtest_matcher>
6402 MatcherBase(M&& m) { // NOLINT
6403 Init(std::forward<M>(m));
6404 }
6405
6406 MatcherBase(const MatcherBase& other)
6407 : vtable_(other.vtable_), buffer_(other.buffer_) {
6408 if (IsShared()) buffer_.shared->Ref();
6409 }
6410
6411 MatcherBase& operator=(const MatcherBase& other) {
6412 if (this == &other) return *this;
6413 Destroy();
6414 vtable_ = other.vtable_;
6415 buffer_ = other.buffer_;
6416 if (IsShared()) buffer_.shared->Ref();
6417 return *this;
6418 }
6419
6420 MatcherBase(MatcherBase&& other)
6421 : vtable_(other.vtable_), buffer_(other.buffer_) {
6422 other.vtable_ = nullptr;
6423 }
6424
6425 MatcherBase& operator=(MatcherBase&& other) {
6426 if (this == &other) return *this;
6427 Destroy();
6428 vtable_ = other.vtable_;
6429 buffer_ = other.buffer_;
6430 other.vtable_ = nullptr;
6431 return *this;
6432 }
6433
6434 ~MatcherBase() override { Destroy(); }
6435
6436 private:
6437 struct VTable {
6438 bool (*match_and_explain)(const MatcherBase&, const T&,
6439 MatchResultListener*);
6440 void (*describe)(const MatcherBase&, std::ostream*, bool negation);
6441 // Returns the captured object if it implements the interface, otherwise
6442 // returns the MatcherBase itself.
6443 const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
6444 // Called on shared instances when the reference count reaches 0.
6445 void (*shared_destroy)(SharedPayloadBase*);
6446 };
6447
6448 bool IsShared() const {
6449 return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
6450 }
6451
6452 // If the implementation uses a listener, call that.
6453 template <typename P>
6454 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6455 MatchResultListener* listener)
6456 -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
6457 return P::Get(m).MatchAndExplain(value, listener->stream());
6458 }
6459
6460 template <typename P>
6461 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6462 MatchResultListener* listener)
6463 -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
6464 return P::Get(m).MatchAndExplain(value, listener);
6465 }
6466
6467 template <typename P>
6468 static void DescribeImpl(const MatcherBase& m, std::ostream* os,
6469 bool negation) {
6470 if (negation) {
6471 P::Get(m).DescribeNegationTo(os);
6472 } else {
6473 P::Get(m).DescribeTo(os);
6474 }
6475 }
6476
6477 template <typename P>
6478 static const MatcherDescriberInterface* GetDescriberImpl(
6479 const MatcherBase& m) {
6480 // If the impl is a MatcherDescriberInterface, then return it.
6481 // Otherwise use MatcherBase itself.
6482 // This allows us to implement the GetDescriber() function without support
6483 // from the impl, but some users really want to get their impl back when
6484 // they call GetDescriber().
6485 // We use std::get on a tuple as a workaround of not having `if constexpr`.
6486 return std::get<(
6487 std::is_convertible<decltype(&P::Get(m)),
6488 const MatcherDescriberInterface*>::value
6489 ? 1
6490 : 0)>(std::make_tuple(&m, &P::Get(m)));
6491 }
6492
6493 template <typename P>
6494 const VTable* GetVTable() {
6495 static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
6496 &DescribeImpl<P>, &GetDescriberImpl<P>,
6497 P::shared_destroy};
6498 return &kVTable;
6499 }
6500
6501 union Buffer {
6502 // Add some types to give Buffer some common alignment/size use cases.
6503 void* ptr;
6504 double d;
6505 int64_t i;
6506 // And add one for the out-of-line cases.
6507 SharedPayloadBase* shared;
6508 };
6509
6510 void Destroy() {
6511 if (IsShared() && buffer_.shared->Unref()) {
6512 vtable_->shared_destroy(buffer_.shared);
6513 }
6514 }
6515
6516 template <typename M>
6517 static constexpr bool IsInlined() {
6518 return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
6519 is_trivially_copy_constructible<M>::value &&
6520 std::is_trivially_destructible<M>::value;
6521 }
6522
6523 template <typename M, bool = MatcherBase::IsInlined<M>()>
6524 struct ValuePolicy {
6525 static const M& Get(const MatcherBase& m) {
6526 // When inlined along with Init, need to be explicit to avoid violating
6527 // strict aliasing rules.
6528 const M *ptr = static_cast<const M*>(
6529 static_cast<const void*>(&m.buffer_));
6530 return *ptr;
6531 }
6532 static void Init(MatcherBase& m, M impl) {
6533 ::new (static_cast<void*>(&m.buffer_)) M(impl);
6534 }
6535 static constexpr auto shared_destroy = nullptr;
6536 };
6537
6538 template <typename M>
6539 struct ValuePolicy<M, false> {
6540 using Shared = SharedPayload<M>;
6541 static const M& Get(const MatcherBase& m) {
6542 return static_cast<Shared*>(m.buffer_.shared)->value;
6543 }
6544 template <typename Arg>
6545 static void Init(MatcherBase& m, Arg&& arg) {
6546 m.buffer_.shared = new Shared(std::forward<Arg>(arg));
6547 }
6548 static constexpr auto shared_destroy = &Shared::Destroy;
6549 };
6550
6551 template <typename U, bool B>
6552 struct ValuePolicy<const MatcherInterface<U>*, B> {
6553 using M = const MatcherInterface<U>;
6554 using Shared = SharedPayload<std::unique_ptr<M>>;
6555 static const M& Get(const MatcherBase& m) {
6556 return *static_cast<Shared*>(m.buffer_.shared)->value;
6557 }
6558 static void Init(MatcherBase& m, M* impl) {
6559 m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
6560 }
6561
6562 static constexpr auto shared_destroy = &Shared::Destroy;
6563 };
6564
6565 template <typename M>
6566 void Init(M&& m) {
6567 using MM = typename std::decay<M>::type;
6568 using Policy = ValuePolicy<MM>;
6569 vtable_ = GetVTable<Policy>();
6570 Policy::Init(*this, std::forward<M>(m));
6571 }
6572
6573 const VTable* vtable_;
6574 Buffer buffer_;
6575 };
6576
6577 } // namespace internal
6578
6579 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
6580 // object that can check whether a value of type T matches. The
6581 // implementation of Matcher<T> is just a std::shared_ptr to const
6582 // MatcherInterface<T>. Don't inherit from Matcher!
6583 template <typename T>
6584 class Matcher : public internal::MatcherBase<T> {
6585 public:
6586 // Constructs a null matcher. Needed for storing Matcher objects in STL
6587 // containers. A default-constructed matcher is not yet initialized. You
6588 // cannot use it until a valid value has been assigned to it.
6589 explicit Matcher() {} // NOLINT
6590
6591 // Constructs a matcher from its implementation.
6592 explicit Matcher(const MatcherInterface<const T&>* impl)
6593 : internal::MatcherBase<T>(impl) {}
6594
6595 template <typename U>
6596 explicit Matcher(
6597 const MatcherInterface<U>* impl,
6598 typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
6599 nullptr)
6600 : internal::MatcherBase<T>(impl) {}
6601
6602 template <typename M, typename = typename std::remove_reference<
6603 M>::type::is_gtest_matcher>
6604 Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
6605
6606 // Implicit constructor here allows people to write
6607 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
6608 Matcher(T value); // NOLINT
6609 };
6610
6611 // The following two specializations allow the user to write str
6612 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
6613 // matcher is expected.
6614 template <>
6615 class GTEST_API_ Matcher<const std::string&>
6616 : public internal::MatcherBase<const std::string&> {
6617 public:
6618 Matcher() {}
6619
6620 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6621 : internal::MatcherBase<const std::string&>(impl) {}
6622
6623 template <typename M, typename = typename std::remove_reference<
6624 M>::type::is_gtest_matcher>
6625 Matcher(M&& m) // NOLINT
6626 : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
6627
6628 // Allows the user to write str instead of Eq(str) sometimes, where
6629 // str is a std::string object.
6630 Matcher(const std::string& s); // NOLINT
6631
6632 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6633 Matcher(const char* s); // NOLINT
6634 };
6635
6636 template <>
6637 class GTEST_API_ Matcher<std::string>
6638 : public internal::MatcherBase<std::string> {
6639 public:
6640 Matcher() {}
6641
6642 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6643 : internal::MatcherBase<std::string>(impl) {}
6644 explicit Matcher(const MatcherInterface<std::string>* impl)
6645 : internal::MatcherBase<std::string>(impl) {}
6646
6647 template <typename M, typename = typename std::remove_reference<
6648 M>::type::is_gtest_matcher>
6649 Matcher(M&& m) // NOLINT
6650 : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
6651
6652 // Allows the user to write str instead of Eq(str) sometimes, where
6653 // str is a string object.
6654 Matcher(const std::string& s); // NOLINT
6655
6656 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6657 Matcher(const char* s); // NOLINT
6658 };
6659
6660 #if GTEST_INTERNAL_HAS_STRING_VIEW
6661 // The following two specializations allow the user to write str
6662 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
6663 // matcher is expected.
6664 template <>
6665 class GTEST_API_ Matcher<const internal::StringView&>
6666 : public internal::MatcherBase<const internal::StringView&> {
6667 public:
6668 Matcher() {}
6669
6670 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6671 : internal::MatcherBase<const internal::StringView&>(impl) {}
6672
6673 template <typename M, typename = typename std::remove_reference<
6674 M>::type::is_gtest_matcher>
6675 Matcher(M&& m) // NOLINT
6676 : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
6677 }
6678
6679 // Allows the user to write str instead of Eq(str) sometimes, where
6680 // str is a std::string object.
6681 Matcher(const std::string& s); // NOLINT
6682
6683 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6684 Matcher(const char* s); // NOLINT
6685
6686 // Allows the user to pass absl::string_views or std::string_views directly.
6687 Matcher(internal::StringView s); // NOLINT
6688 };
6689
6690 template <>
6691 class GTEST_API_ Matcher<internal::StringView>
6692 : public internal::MatcherBase<internal::StringView> {
6693 public:
6694 Matcher() {}
6695
6696 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6697 : internal::MatcherBase<internal::StringView>(impl) {}
6698 explicit Matcher(const MatcherInterface<internal::StringView>* impl)
6699 : internal::MatcherBase<internal::StringView>(impl) {}
6700
6701 template <typename M, typename = typename std::remove_reference<
6702 M>::type::is_gtest_matcher>
6703 Matcher(M&& m) // NOLINT
6704 : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
6705
6706 // Allows the user to write str instead of Eq(str) sometimes, where
6707 // str is a std::string object.
6708 Matcher(const std::string& s); // NOLINT
6709
6710 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6711 Matcher(const char* s); // NOLINT
6712
6713 // Allows the user to pass absl::string_views or std::string_views directly.
6714 Matcher(internal::StringView s); // NOLINT
6715 };
6716 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6717
6718 // Prints a matcher in a human-readable format.
6719 template <typename T>
6720 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
6721 matcher.DescribeTo(&os);
6722 return os;
6723 }
6724
6725 // The PolymorphicMatcher class template makes it easy to implement a
6726 // polymorphic matcher (i.e. a matcher that can match values of more
6727 // than one type, e.g. Eq(n) and NotNull()).
6728 //
6729 // To define a polymorphic matcher, a user should provide an Impl
6730 // class that has a DescribeTo() method and a DescribeNegationTo()
6731 // method, and define a member function (or member function template)
6732 //
6733 // bool MatchAndExplain(const Value& value,
6734 // MatchResultListener* listener) const;
6735 //
6736 // See the definition of NotNull() for a complete example.
6737 template <class Impl>
6738 class PolymorphicMatcher {
6739 public:
6740 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
6741
6742 // Returns a mutable reference to the underlying matcher
6743 // implementation object.
6744 Impl& mutable_impl() { return impl_; }
6745
6746 // Returns an immutable reference to the underlying matcher
6747 // implementation object.
6748 const Impl& impl() const { return impl_; }
6749
6750 template <typename T>
6751 operator Matcher<T>() const {
6752 return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
6753 }
6754
6755 private:
6756 template <typename T>
6757 class MonomorphicImpl : public MatcherInterface<T> {
6758 public:
6759 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
6760
6761 void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
6762
6763 void DescribeNegationTo(::std::ostream* os) const override {
6764 impl_.DescribeNegationTo(os);
6765 }
6766
6767 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
6768 return impl_.MatchAndExplain(x, listener);
6769 }
6770
6771 private:
6772 const Impl impl_;
6773 };
6774
6775 Impl impl_;
6776 };
6777
6778 // Creates a matcher from its implementation.
6779 // DEPRECATED: Especially in the generic code, prefer:
6780 // Matcher<T>(new MyMatcherImpl<const T&>(...));
6781 //
6782 // MakeMatcher may create a Matcher that accepts its argument by value, which
6783 // leads to unnecessary copies & lack of support for non-copyable types.
6784 template <typename T>
6785 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
6786 return Matcher<T>(impl);
6787 }
6788
6789 // Creates a polymorphic matcher from its implementation. This is
6790 // easier to use than the PolymorphicMatcher<Impl> constructor as it
6791 // doesn't require you to explicitly write the template argument, e.g.
6792 //
6793 // MakePolymorphicMatcher(foo);
6794 // vs
6795 // PolymorphicMatcher<TypeOfFoo>(foo);
6796 template <class Impl>
6797 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
6798 return PolymorphicMatcher<Impl>(impl);
6799 }
6800
6801 namespace internal {
6802 // Implements a matcher that compares a given value with a
6803 // pre-supplied value using one of the ==, <=, <, etc, operators. The
6804 // two values being compared don't have to have the same type.
6805 //
6806 // The matcher defined here is polymorphic (for example, Eq(5) can be
6807 // used to match an int, a short, a double, etc). Therefore we use
6808 // a template type conversion operator in the implementation.
6809 //
6810 // The following template definition assumes that the Rhs parameter is
6811 // a "bare" type (i.e. neither 'const T' nor 'T&').
6812 template <typename D, typename Rhs, typename Op>
6813 class ComparisonBase {
6814 public:
6815 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
6816
6817 using is_gtest_matcher = void;
6818
6819 template <typename Lhs>
6820 bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
6821 return Op()(lhs, Unwrap(rhs_));
6822 }
6823 void DescribeTo(std::ostream* os) const {
6824 *os << D::Desc() << " ";
6825 UniversalPrint(Unwrap(rhs_), os);
6826 }
6827 void DescribeNegationTo(std::ostream* os) const {
6828 *os << D::NegatedDesc() << " ";
6829 UniversalPrint(Unwrap(rhs_), os);
6830 }
6831
6832 private:
6833 template <typename T>
6834 static const T& Unwrap(const T& v) {
6835 return v;
6836 }
6837 template <typename T>
6838 static const T& Unwrap(std::reference_wrapper<T> v) {
6839 return v;
6840 }
6841
6842 Rhs rhs_;
6843 };
6844
6845 template <typename Rhs>
6846 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
6847 public:
6848 explicit EqMatcher(const Rhs& rhs)
6849 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
6850 static const char* Desc() { return "is equal to"; }
6851 static const char* NegatedDesc() { return "isn't equal to"; }
6852 };
6853 template <typename Rhs>
6854 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
6855 public:
6856 explicit NeMatcher(const Rhs& rhs)
6857 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
6858 static const char* Desc() { return "isn't equal to"; }
6859 static const char* NegatedDesc() { return "is equal to"; }
6860 };
6861 template <typename Rhs>
6862 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
6863 public:
6864 explicit LtMatcher(const Rhs& rhs)
6865 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
6866 static const char* Desc() { return "is <"; }
6867 static const char* NegatedDesc() { return "isn't <"; }
6868 };
6869 template <typename Rhs>
6870 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
6871 public:
6872 explicit GtMatcher(const Rhs& rhs)
6873 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
6874 static const char* Desc() { return "is >"; }
6875 static const char* NegatedDesc() { return "isn't >"; }
6876 };
6877 template <typename Rhs>
6878 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
6879 public:
6880 explicit LeMatcher(const Rhs& rhs)
6881 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
6882 static const char* Desc() { return "is <="; }
6883 static const char* NegatedDesc() { return "isn't <="; }
6884 };
6885 template <typename Rhs>
6886 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
6887 public:
6888 explicit GeMatcher(const Rhs& rhs)
6889 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
6890 static const char* Desc() { return "is >="; }
6891 static const char* NegatedDesc() { return "isn't >="; }
6892 };
6893
6894 template <typename T, typename = typename std::enable_if<
6895 std::is_constructible<std::string, T>::value>::type>
6896 using StringLike = T;
6897
6898 // Implements polymorphic matchers MatchesRegex(regex) and
6899 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
6900 // T can be converted to a string.
6901 class MatchesRegexMatcher {
6902 public:
6903 MatchesRegexMatcher(const RE* regex, bool full_match)
6904 : regex_(regex), full_match_(full_match) {}
6905
6906 #if GTEST_INTERNAL_HAS_STRING_VIEW
6907 bool MatchAndExplain(const internal::StringView& s,
6908 MatchResultListener* listener) const {
6909 return MatchAndExplain(std::string(s), listener);
6910 }
6911 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6912
6913 // Accepts pointer types, particularly:
6914 // const char*
6915 // char*
6916 // const wchar_t*
6917 // wchar_t*
6918 template <typename CharType>
6919 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
6920 return s != nullptr && MatchAndExplain(std::string(s), listener);
6921 }
6922
6923 // Matches anything that can convert to std::string.
6924 //
6925 // This is a template, not just a plain function with const std::string&,
6926 // because absl::string_view has some interfering non-explicit constructors.
6927 template <class MatcheeStringType>
6928 bool MatchAndExplain(const MatcheeStringType& s,
6929 MatchResultListener* /* listener */) const {
6930 const std::string& s2(s);
6931 return full_match_ ? RE::FullMatch(s2, *regex_)
6932 : RE::PartialMatch(s2, *regex_);
6933 }
6934
6935 void DescribeTo(::std::ostream* os) const {
6936 *os << (full_match_ ? "matches" : "contains") << " regular expression ";
6937 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6938 }
6939
6940 void DescribeNegationTo(::std::ostream* os) const {
6941 *os << "doesn't " << (full_match_ ? "match" : "contain")
6942 << " regular expression ";
6943 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6944 }
6945
6946 private:
6947 const std::shared_ptr<const RE> regex_;
6948 const bool full_match_;
6949 };
6950 } // namespace internal
6951
6952 // Matches a string that fully matches regular expression 'regex'.
6953 // The matcher takes ownership of 'regex'.
6954 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6955 const internal::RE* regex) {
6956 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
6957 }
6958 template <typename T = std::string>
6959 PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6960 const internal::StringLike<T>& regex) {
6961 return MatchesRegex(new internal::RE(std::string(regex)));
6962 }
6963
6964 // Matches a string that contains regular expression 'regex'.
6965 // The matcher takes ownership of 'regex'.
6966 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6967 const internal::RE* regex) {
6968 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
6969 }
6970 template <typename T = std::string>
6971 PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6972 const internal::StringLike<T>& regex) {
6973 return ContainsRegex(new internal::RE(std::string(regex)));
6974 }
6975
6976 // Creates a polymorphic matcher that matches anything equal to x.
6977 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
6978 // wouldn't compile.
6979 template <typename T>
6980 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
6981
6982 // Constructs a Matcher<T> from a 'value' of type T. The constructed
6983 // matcher matches any value that's equal to 'value'.
6984 template <typename T>
6985 Matcher<T>::Matcher(T value) { *this = Eq(value); }
6986
6987 // Creates a monomorphic matcher that matches anything with type Lhs
6988 // and equal to rhs. A user may need to use this instead of Eq(...)
6989 // in order to resolve an overloading ambiguity.
6990 //
6991 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
6992 // or Matcher<T>(x), but more readable than the latter.
6993 //
6994 // We could define similar monomorphic matchers for other comparison
6995 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
6996 // it yet as those are used much less than Eq() in practice. A user
6997 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
6998 // for example.
6999 template <typename Lhs, typename Rhs>
7000 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
7001
7002 // Creates a polymorphic matcher that matches anything >= x.
7003 template <typename Rhs>
7004 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
7005 return internal::GeMatcher<Rhs>(x);
7006 }
7007
7008 // Creates a polymorphic matcher that matches anything > x.
7009 template <typename Rhs>
7010 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
7011 return internal::GtMatcher<Rhs>(x);
7012 }
7013
7014 // Creates a polymorphic matcher that matches anything <= x.
7015 template <typename Rhs>
7016 inline internal::LeMatcher<Rhs> Le(Rhs x) {
7017 return internal::LeMatcher<Rhs>(x);
7018 }
7019
7020 // Creates a polymorphic matcher that matches anything < x.
7021 template <typename Rhs>
7022 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
7023 return internal::LtMatcher<Rhs>(x);
7024 }
7025
7026 // Creates a polymorphic matcher that matches anything != x.
7027 template <typename Rhs>
7028 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
7029 return internal::NeMatcher<Rhs>(x);
7030 }
7031 } // namespace testing
7032
7033 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
7034
7035 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
7036
7037 #include <stdio.h>
7038 #include <memory>
7039
7040 namespace testing {
7041 namespace internal {
7042
7043 GTEST_DECLARE_string_(internal_run_death_test);
7044
7045 // Names of the flags (needed for parsing Google Test flags).
7046 const char kDeathTestStyleFlag[] = "death_test_style";
7047 const char kDeathTestUseFork[] = "death_test_use_fork";
7048 const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
7049
7050 #if GTEST_HAS_DEATH_TEST
7051
7052 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7053 /* class A needs to have dll-interface to be used by clients of class B */)
7054
7055 // DeathTest is a class that hides much of the complexity of the
7056 // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
7057 // returns a concrete class that depends on the prevailing death test
7058 // style, as defined by the --gtest_death_test_style and/or
7059 // --gtest_internal_run_death_test flags.
7060
7061 // In describing the results of death tests, these terms are used with
7062 // the corresponding definitions:
7063 //
7064 // exit status: The integer exit information in the format specified
7065 // by wait(2)
7066 // exit code: The integer code passed to exit(3), _exit(2), or
7067 // returned from main()
7068 class GTEST_API_ DeathTest {
7069 public:
7070 // Create returns false if there was an error determining the
7071 // appropriate action to take for the current death test; for example,
7072 // if the gtest_death_test_style flag is set to an invalid value.
7073 // The LastMessage method will return a more detailed message in that
7074 // case. Otherwise, the DeathTest pointer pointed to by the "test"
7075 // argument is set. If the death test should be skipped, the pointer
7076 // is set to NULL; otherwise, it is set to the address of a new concrete
7077 // DeathTest object that controls the execution of the current test.
7078 static bool Create(const char* statement, Matcher<const std::string&> matcher,
7079 const char* file, int line, DeathTest** test);
7080 DeathTest();
7081 virtual ~DeathTest() { }
7082
7083 // A helper class that aborts a death test when it's deleted.
7084 class ReturnSentinel {
7085 public:
7086 explicit ReturnSentinel(DeathTest* test) : test_(test) { }
7087 ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
7088 private:
7089 DeathTest* const test_;
7090 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
7091 } GTEST_ATTRIBUTE_UNUSED_;
7092
7093 // An enumeration of possible roles that may be taken when a death
7094 // test is encountered. EXECUTE means that the death test logic should
7095 // be executed immediately. OVERSEE means that the program should prepare
7096 // the appropriate environment for a child process to execute the death
7097 // test, then wait for it to complete.
7098 enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
7099
7100 // An enumeration of the three reasons that a test might be aborted.
7101 enum AbortReason {
7102 TEST_ENCOUNTERED_RETURN_STATEMENT,
7103 TEST_THREW_EXCEPTION,
7104 TEST_DID_NOT_DIE
7105 };
7106
7107 // Assumes one of the above roles.
7108 virtual TestRole AssumeRole() = 0;
7109
7110 // Waits for the death test to finish and returns its status.
7111 virtual int Wait() = 0;
7112
7113 // Returns true if the death test passed; that is, the test process
7114 // exited during the test, its exit status matches a user-supplied
7115 // predicate, and its stderr output matches a user-supplied regular
7116 // expression.
7117 // The user-supplied predicate may be a macro expression rather
7118 // than a function pointer or functor, or else Wait and Passed could
7119 // be combined.
7120 virtual bool Passed(bool exit_status_ok) = 0;
7121
7122 // Signals that the death test did not die as expected.
7123 virtual void Abort(AbortReason reason) = 0;
7124
7125 // Returns a human-readable outcome message regarding the outcome of
7126 // the last death test.
7127 static const char* LastMessage();
7128
7129 static void set_last_death_test_message(const std::string& message);
7130
7131 private:
7132 // A string containing a description of the outcome of the last death test.
7133 static std::string last_death_test_message_;
7134
7135 GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
7136 };
7137
7138 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
7139
7140 // Factory interface for death tests. May be mocked out for testing.
7141 class DeathTestFactory {
7142 public:
7143 virtual ~DeathTestFactory() { }
7144 virtual bool Create(const char* statement,
7145 Matcher<const std::string&> matcher, const char* file,
7146 int line, DeathTest** test) = 0;
7147 };
7148
7149 // A concrete DeathTestFactory implementation for normal use.
7150 class DefaultDeathTestFactory : public DeathTestFactory {
7151 public:
7152 bool Create(const char* statement, Matcher<const std::string&> matcher,
7153 const char* file, int line, DeathTest** test) override;
7154 };
7155
7156 // Returns true if exit_status describes a process that was terminated
7157 // by a signal, or exited normally with a nonzero exit code.
7158 GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
7159
7160 // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
7161 // and interpreted as a regex (rather than an Eq matcher) for legacy
7162 // compatibility.
7163 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7164 ::testing::internal::RE regex) {
7165 return ContainsRegex(regex.pattern());
7166 }
7167 inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
7168 return ContainsRegex(regex);
7169 }
7170 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7171 const ::std::string& regex) {
7172 return ContainsRegex(regex);
7173 }
7174
7175 // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
7176 // used directly.
7177 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7178 Matcher<const ::std::string&> matcher) {
7179 return matcher;
7180 }
7181
7182 // Traps C++ exceptions escaping statement and reports them as test
7183 // failures. Note that trapping SEH exceptions is not implemented here.
7184 # if GTEST_HAS_EXCEPTIONS
7185 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7186 try { \
7187 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7188 } catch (const ::std::exception& gtest_exception) { \
7189 fprintf(\
7190 stderr, \
7191 "\n%s: Caught std::exception-derived exception escaping the " \
7192 "death test statement. Exception message: %s\n", \
7193 ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
7194 gtest_exception.what()); \
7195 fflush(stderr); \
7196 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7197 } catch (...) { \
7198 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7199 }
7200
7201 # else
7202 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7203 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
7204
7205 # endif
7206
7207 // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
7208 // ASSERT_EXIT*, and EXPECT_EXIT*.
7209 #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
7210 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7211 if (::testing::internal::AlwaysTrue()) { \
7212 ::testing::internal::DeathTest* gtest_dt; \
7213 if (!::testing::internal::DeathTest::Create( \
7214 #statement, \
7215 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
7216 __FILE__, __LINE__, &gtest_dt)) { \
7217 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7218 } \
7219 if (gtest_dt != nullptr) { \
7220 std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
7221 switch (gtest_dt->AssumeRole()) { \
7222 case ::testing::internal::DeathTest::OVERSEE_TEST: \
7223 if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
7224 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7225 } \
7226 break; \
7227 case ::testing::internal::DeathTest::EXECUTE_TEST: { \
7228 ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
7229 gtest_dt); \
7230 GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
7231 gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
7232 break; \
7233 } \
7234 default: \
7235 break; \
7236 } \
7237 } \
7238 } else \
7239 GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
7240 : fail(::testing::internal::DeathTest::LastMessage())
7241 // The symbol "fail" here expands to something into which a message
7242 // can be streamed.
7243
7244 // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
7245 // NDEBUG mode. In this case we need the statements to be executed and the macro
7246 // must accept a streamed message even though the message is never printed.
7247 // The regex object is not evaluated, but it is used to prevent "unused"
7248 // warnings and to avoid an expression that doesn't compile in debug mode.
7249 #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
7250 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7251 if (::testing::internal::AlwaysTrue()) { \
7252 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7253 } else if (!::testing::internal::AlwaysTrue()) { \
7254 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
7255 } else \
7256 ::testing::Message()
7257
7258 // A class representing the parsed contents of the
7259 // --gtest_internal_run_death_test flag, as it existed when
7260 // RUN_ALL_TESTS was called.
7261 class InternalRunDeathTestFlag {
7262 public:
7263 InternalRunDeathTestFlag(const std::string& a_file,
7264 int a_line,
7265 int an_index,
7266 int a_write_fd)
7267 : file_(a_file), line_(a_line), index_(an_index),
7268 write_fd_(a_write_fd) {}
7269
7270 ~InternalRunDeathTestFlag() {
7271 if (write_fd_ >= 0)
7272 posix::Close(write_fd_);
7273 }
7274
7275 const std::string& file() const { return file_; }
7276 int line() const { return line_; }
7277 int index() const { return index_; }
7278 int write_fd() const { return write_fd_; }
7279
7280 private:
7281 std::string file_;
7282 int line_;
7283 int index_;
7284 int write_fd_;
7285
7286 GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
7287 };
7288
7289 // Returns a newly created InternalRunDeathTestFlag object with fields
7290 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7291 // the flag is specified; otherwise returns NULL.
7292 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
7293
7294 #endif // GTEST_HAS_DEATH_TEST
7295
7296 } // namespace internal
7297 } // namespace testing
7298
7299 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
7300
7301 namespace testing {
7302
7303 // This flag controls the style of death tests. Valid values are "threadsafe",
7304 // meaning that the death test child process will re-execute the test binary
7305 // from the start, running only a single death test, or "fast",
7306 // meaning that the child process will execute the test logic immediately
7307 // after forking.
7308 GTEST_DECLARE_string_(death_test_style);
7309
7310 #if GTEST_HAS_DEATH_TEST
7311
7312 namespace internal {
7313
7314 // Returns a Boolean value indicating whether the caller is currently
7315 // executing in the context of the death test child process. Tools such as
7316 // Valgrind heap checkers may need this to modify their behavior in death
7317 // tests. IMPORTANT: This is an internal utility. Using it may break the
7318 // implementation of death tests. User code MUST NOT use it.
7319 GTEST_API_ bool InDeathTestChild();
7320
7321 } // namespace internal
7322
7323 // The following macros are useful for writing death tests.
7324
7325 // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
7326 // executed:
7327 //
7328 // 1. It generates a warning if there is more than one active
7329 // thread. This is because it's safe to fork() or clone() only
7330 // when there is a single thread.
7331 //
7332 // 2. The parent process clone()s a sub-process and runs the death
7333 // test in it; the sub-process exits with code 0 at the end of the
7334 // death test, if it hasn't exited already.
7335 //
7336 // 3. The parent process waits for the sub-process to terminate.
7337 //
7338 // 4. The parent process checks the exit code and error message of
7339 // the sub-process.
7340 //
7341 // Examples:
7342 //
7343 // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
7344 // for (int i = 0; i < 5; i++) {
7345 // EXPECT_DEATH(server.ProcessRequest(i),
7346 // "Invalid request .* in ProcessRequest()")
7347 // << "Failed to die on request " << i;
7348 // }
7349 //
7350 // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
7351 //
7352 // bool KilledBySIGHUP(int exit_code) {
7353 // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
7354 // }
7355 //
7356 // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
7357 //
7358 // On the regular expressions used in death tests:
7359 //
7360 // GOOGLETEST_CM0005 DO NOT DELETE
7361 // On POSIX-compliant systems (*nix), we use the <regex.h> library,
7362 // which uses the POSIX extended regex syntax.
7363 //
7364 // On other platforms (e.g. Windows or Mac), we only support a simple regex
7365 // syntax implemented as part of Google Test. This limited
7366 // implementation should be enough most of the time when writing
7367 // death tests; though it lacks many features you can find in PCRE
7368 // or POSIX extended regex syntax. For example, we don't support
7369 // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
7370 // repetition count ("x{5,7}"), among others.
7371 //
7372 // Below is the syntax that we do support. We chose it to be a
7373 // subset of both PCRE and POSIX extended regex, so it's easy to
7374 // learn wherever you come from. In the following: 'A' denotes a
7375 // literal character, period (.), or a single \\ escape sequence;
7376 // 'x' and 'y' denote regular expressions; 'm' and 'n' are for
7377 // natural numbers.
7378 //
7379 // c matches any literal character c
7380 // \\d matches any decimal digit
7381 // \\D matches any character that's not a decimal digit
7382 // \\f matches \f
7383 // \\n matches \n
7384 // \\r matches \r
7385 // \\s matches any ASCII whitespace, including \n
7386 // \\S matches any character that's not a whitespace
7387 // \\t matches \t
7388 // \\v matches \v
7389 // \\w matches any letter, _, or decimal digit
7390 // \\W matches any character that \\w doesn't match
7391 // \\c matches any literal character c, which must be a punctuation
7392 // . matches any single character except \n
7393 // A? matches 0 or 1 occurrences of A
7394 // A* matches 0 or many occurrences of A
7395 // A+ matches 1 or many occurrences of A
7396 // ^ matches the beginning of a string (not that of each line)
7397 // $ matches the end of a string (not that of each line)
7398 // xy matches x followed by y
7399 //
7400 // If you accidentally use PCRE or POSIX extended regex features
7401 // not implemented by us, you will get a run-time failure. In that
7402 // case, please try to rewrite your regular expression within the
7403 // above syntax.
7404 //
7405 // This implementation is *not* meant to be as highly tuned or robust
7406 // as a compiled regex library, but should perform well enough for a
7407 // death test, which already incurs significant overhead by launching
7408 // a child process.
7409 //
7410 // Known caveats:
7411 //
7412 // A "threadsafe" style death test obtains the path to the test
7413 // program from argv[0] and re-executes it in the sub-process. For
7414 // simplicity, the current implementation doesn't search the PATH
7415 // when launching the sub-process. This means that the user must
7416 // invoke the test program via a path that contains at least one
7417 // path separator (e.g. path/to/foo_test and
7418 // /absolute/path/to/bar_test are fine, but foo_test is not). This
7419 // is rarely a problem as people usually don't put the test binary
7420 // directory in PATH.
7421 //
7422
7423 // Asserts that a given statement causes the program to exit, with an
7424 // integer exit status that satisfies predicate, and emitting error output
7425 // that matches regex.
7426 # define ASSERT_EXIT(statement, predicate, regex) \
7427 GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
7428
7429 // Like ASSERT_EXIT, but continues on to successive tests in the
7430 // test suite, if any:
7431 # define EXPECT_EXIT(statement, predicate, regex) \
7432 GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
7433
7434 // Asserts that a given statement causes the program to exit, either by
7435 // explicitly exiting with a nonzero exit code or being killed by a
7436 // signal, and emitting error output that matches regex.
7437 # define ASSERT_DEATH(statement, regex) \
7438 ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
7439
7440 // Like ASSERT_DEATH, but continues on to successive tests in the
7441 // test suite, if any:
7442 # define EXPECT_DEATH(statement, regex) \
7443 EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
7444
7445 // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
7446
7447 // Tests that an exit code describes a normal exit with a given exit code.
7448 class GTEST_API_ ExitedWithCode {
7449 public:
7450 explicit ExitedWithCode(int exit_code);
7451 ExitedWithCode(const ExitedWithCode&) = default;
7452 void operator=(const ExitedWithCode& other) = delete;
7453 bool operator()(int exit_status) const;
7454 private:
7455 const int exit_code_;
7456 };
7457
7458 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7459 // Tests that an exit code describes an exit due to termination by a
7460 // given signal.
7461 // GOOGLETEST_CM0006 DO NOT DELETE
7462 class GTEST_API_ KilledBySignal {
7463 public:
7464 explicit KilledBySignal(int signum);
7465 bool operator()(int exit_status) const;
7466 private:
7467 const int signum_;
7468 };
7469 # endif // !GTEST_OS_WINDOWS
7470
7471 // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
7472 // The death testing framework causes this to have interesting semantics,
7473 // since the sideeffects of the call are only visible in opt mode, and not
7474 // in debug mode.
7475 //
7476 // In practice, this can be used to test functions that utilize the
7477 // LOG(DFATAL) macro using the following style:
7478 //
7479 // int DieInDebugOr12(int* sideeffect) {
7480 // if (sideeffect) {
7481 // *sideeffect = 12;
7482 // }
7483 // LOG(DFATAL) << "death";
7484 // return 12;
7485 // }
7486 //
7487 // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
7488 // int sideeffect = 0;
7489 // // Only asserts in dbg.
7490 // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
7491 //
7492 // #ifdef NDEBUG
7493 // // opt-mode has sideeffect visible.
7494 // EXPECT_EQ(12, sideeffect);
7495 // #else
7496 // // dbg-mode no visible sideeffect.
7497 // EXPECT_EQ(0, sideeffect);
7498 // #endif
7499 // }
7500 //
7501 // This will assert that DieInDebugReturn12InOpt() crashes in debug
7502 // mode, usually due to a DCHECK or LOG(DFATAL), but returns the
7503 // appropriate fallback value (12 in this case) in opt mode. If you
7504 // need to test that a function has appropriate side-effects in opt
7505 // mode, include assertions against the side-effects. A general
7506 // pattern for this is:
7507 //
7508 // EXPECT_DEBUG_DEATH({
7509 // // Side-effects here will have an effect after this statement in
7510 // // opt mode, but none in debug mode.
7511 // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
7512 // }, "death");
7513 //
7514 # ifdef NDEBUG
7515
7516 # define EXPECT_DEBUG_DEATH(statement, regex) \
7517 GTEST_EXECUTE_STATEMENT_(statement, regex)
7518
7519 # define ASSERT_DEBUG_DEATH(statement, regex) \
7520 GTEST_EXECUTE_STATEMENT_(statement, regex)
7521
7522 # else
7523
7524 # define EXPECT_DEBUG_DEATH(statement, regex) \
7525 EXPECT_DEATH(statement, regex)
7526
7527 # define ASSERT_DEBUG_DEATH(statement, regex) \
7528 ASSERT_DEATH(statement, regex)
7529
7530 # endif // NDEBUG for EXPECT_DEBUG_DEATH
7531 #endif // GTEST_HAS_DEATH_TEST
7532
7533 // This macro is used for implementing macros such as
7534 // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
7535 // death tests are not supported. Those macros must compile on such systems
7536 // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
7537 // on systems that support death tests. This allows one to write such a macro on
7538 // a system that does not support death tests and be sure that it will compile
7539 // on a death-test supporting system. It is exposed publicly so that systems
7540 // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
7541 // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
7542 // ASSERT_DEATH_IF_SUPPORTED.
7543 //
7544 // Parameters:
7545 // statement - A statement that a macro such as EXPECT_DEATH would test
7546 // for program termination. This macro has to make sure this
7547 // statement is compiled but not executed, to ensure that
7548 // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
7549 // parameter if and only if EXPECT_DEATH compiles with it.
7550 // regex - A regex that a macro such as EXPECT_DEATH would use to test
7551 // the output of statement. This parameter has to be
7552 // compiled but not evaluated by this macro, to ensure that
7553 // this macro only accepts expressions that a macro such as
7554 // EXPECT_DEATH would accept.
7555 // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
7556 // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
7557 // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
7558 // compile inside functions where ASSERT_DEATH doesn't
7559 // compile.
7560 //
7561 // The branch that has an always false condition is used to ensure that
7562 // statement and regex are compiled (and thus syntactically correct) but
7563 // never executed. The unreachable code macro protects the terminator
7564 // statement from generating an 'unreachable code' warning in case
7565 // statement unconditionally returns or throws. The Message constructor at
7566 // the end allows the syntax of streaming additional messages into the
7567 // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
7568 # define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
7569 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7570 if (::testing::internal::AlwaysTrue()) { \
7571 GTEST_LOG_(WARNING) \
7572 << "Death tests are not supported on this platform.\n" \
7573 << "Statement '" #statement "' cannot be verified."; \
7574 } else if (::testing::internal::AlwaysFalse()) { \
7575 ::testing::internal::RE::PartialMatch(".*", (regex)); \
7576 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7577 terminator; \
7578 } else \
7579 ::testing::Message()
7580
7581 // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
7582 // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
7583 // death tests are supported; otherwise they just issue a warning. This is
7584 // useful when you are combining death test assertions with normal test
7585 // assertions in one test.
7586 #if GTEST_HAS_DEATH_TEST
7587 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7588 EXPECT_DEATH(statement, regex)
7589 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7590 ASSERT_DEATH(statement, regex)
7591 #else
7592 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7593 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
7594 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7595 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
7596 #endif
7597
7598 } // namespace testing
7599
7600 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
7601 // Copyright 2008, Google Inc.
7602 // All rights reserved.
7603 //
7604 // Redistribution and use in source and binary forms, with or without
7605 // modification, are permitted provided that the following conditions are
7606 // met:
7607 //
7608 // * Redistributions of source code must retain the above copyright
7609 // notice, this list of conditions and the following disclaimer.
7610 // * Redistributions in binary form must reproduce the above
7611 // copyright notice, this list of conditions and the following disclaimer
7612 // in the documentation and/or other materials provided with the
7613 // distribution.
7614 // * Neither the name of Google Inc. nor the names of its
7615 // contributors may be used to endorse or promote products derived from
7616 // this software without specific prior written permission.
7617 //
7618 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7619 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7620 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7621 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7622 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7623 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7624 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7625 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7626 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7627 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7628 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7629 //
7630 // Macros and functions for implementing parameterized tests
7631 // in Google C++ Testing and Mocking Framework (Google Test)
7632 //
7633 // GOOGLETEST_CM0001 DO NOT DELETE
7634 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7635 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7636
7637 // Value-parameterized tests allow you to test your code with different
7638 // parameters without writing multiple copies of the same test.
7639 //
7640 // Here is how you use value-parameterized tests:
7641
7642 #if 0
7643
7644 // To write value-parameterized tests, first you should define a fixture
7645 // class. It is usually derived from testing::TestWithParam<T> (see below for
7646 // another inheritance scheme that's sometimes useful in more complicated
7647 // class hierarchies), where the type of your parameter values.
7648 // TestWithParam<T> is itself derived from testing::Test. T can be any
7649 // copyable type. If it's a raw pointer, you are responsible for managing the
7650 // lifespan of the pointed values.
7651
7652 class FooTest : public ::testing::TestWithParam<const char*> {
7653 // You can implement all the usual class fixture members here.
7654 };
7655
7656 // Then, use the TEST_P macro to define as many parameterized tests
7657 // for this fixture as you want. The _P suffix is for "parameterized"
7658 // or "pattern", whichever you prefer to think.
7659
7660 TEST_P(FooTest, DoesBlah) {
7661 // Inside a test, access the test parameter with the GetParam() method
7662 // of the TestWithParam<T> class:
7663 EXPECT_TRUE(foo.Blah(GetParam()));
7664 ...
7665 }
7666
7667 TEST_P(FooTest, HasBlahBlah) {
7668 ...
7669 }
7670
7671 // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
7672 // case with any set of parameters you want. Google Test defines a number
7673 // of functions for generating test parameters. They return what we call
7674 // (surprise!) parameter generators. Here is a summary of them, which
7675 // are all in the testing namespace:
7676 //
7677 //
7678 // Range(begin, end [, step]) - Yields values {begin, begin+step,
7679 // begin+step+step, ...}. The values do not
7680 // include end. step defaults to 1.
7681 // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
7682 // ValuesIn(container) - Yields values from a C-style array, an STL
7683 // ValuesIn(begin,end) container, or an iterator range [begin, end).
7684 // Bool() - Yields sequence {false, true}.
7685 // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
7686 // for the math savvy) of the values generated
7687 // by the N generators.
7688 //
7689 // For more details, see comments at the definitions of these functions below
7690 // in this file.
7691 //
7692 // The following statement will instantiate tests from the FooTest test suite
7693 // each with parameter values "meeny", "miny", and "moe".
7694
7695 INSTANTIATE_TEST_SUITE_P(InstantiationName,
7696 FooTest,
7697 Values("meeny", "miny", "moe"));
7698
7699 // To distinguish different instances of the pattern, (yes, you
7700 // can instantiate it more than once) the first argument to the
7701 // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
7702 // actual test suite name. Remember to pick unique prefixes for different
7703 // instantiations. The tests from the instantiation above will have
7704 // these names:
7705 //
7706 // * InstantiationName/FooTest.DoesBlah/0 for "meeny"
7707 // * InstantiationName/FooTest.DoesBlah/1 for "miny"
7708 // * InstantiationName/FooTest.DoesBlah/2 for "moe"
7709 // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
7710 // * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
7711 // * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
7712 //
7713 // You can use these names in --gtest_filter.
7714 //
7715 // This statement will instantiate all tests from FooTest again, each
7716 // with parameter values "cat" and "dog":
7717
7718 const char* pets[] = {"cat", "dog"};
7719 INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
7720
7721 // The tests from the instantiation above will have these names:
7722 //
7723 // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
7724 // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
7725 // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
7726 // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
7727 //
7728 // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
7729 // in the given test suite, whether their definitions come before or
7730 // AFTER the INSTANTIATE_TEST_SUITE_P statement.
7731 //
7732 // Please also note that generator expressions (including parameters to the
7733 // generators) are evaluated in InitGoogleTest(), after main() has started.
7734 // This allows the user on one hand, to adjust generator parameters in order
7735 // to dynamically determine a set of tests to run and on the other hand,
7736 // give the user a chance to inspect the generated tests with Google Test
7737 // reflection API before RUN_ALL_TESTS() is executed.
7738 //
7739 // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
7740 // for more examples.
7741 //
7742 // In the future, we plan to publish the API for defining new parameter
7743 // generators. But for now this interface remains part of the internal
7744 // implementation and is subject to change.
7745 //
7746 //
7747 // A parameterized test fixture must be derived from testing::Test and from
7748 // testing::WithParamInterface<T>, where T is the type of the parameter
7749 // values. Inheriting from TestWithParam<T> satisfies that requirement because
7750 // TestWithParam<T> inherits from both Test and WithParamInterface. In more
7751 // complicated hierarchies, however, it is occasionally useful to inherit
7752 // separately from Test and WithParamInterface. For example:
7753
7754 class BaseTest : public ::testing::Test {
7755 // You can inherit all the usual members for a non-parameterized test
7756 // fixture here.
7757 };
7758
7759 class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
7760 // The usual test fixture members go here too.
7761 };
7762
7763 TEST_F(BaseTest, HasFoo) {
7764 // This is an ordinary non-parameterized test.
7765 }
7766
7767 TEST_P(DerivedTest, DoesBlah) {
7768 // GetParam works just the same here as if you inherit from TestWithParam.
7769 EXPECT_TRUE(foo.Blah(GetParam()));
7770 }
7771
7772 #endif // 0
7773
7774 #include <iterator>
7775 #include <utility>
7776
7777 // Copyright 2008 Google Inc.
7778 // All Rights Reserved.
7779 //
7780 // Redistribution and use in source and binary forms, with or without
7781 // modification, are permitted provided that the following conditions are
7782 // met:
7783 //
7784 // * Redistributions of source code must retain the above copyright
7785 // notice, this list of conditions and the following disclaimer.
7786 // * Redistributions in binary form must reproduce the above
7787 // copyright notice, this list of conditions and the following disclaimer
7788 // in the documentation and/or other materials provided with the
7789 // distribution.
7790 // * Neither the name of Google Inc. nor the names of its
7791 // contributors may be used to endorse or promote products derived from
7792 // this software without specific prior written permission.
7793 //
7794 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7795 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7796 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7797 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7798 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7799 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7800 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7801 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7802 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7803 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7804 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7805
7806
7807 // Type and function utilities for implementing parameterized tests.
7808
7809 // GOOGLETEST_CM0001 DO NOT DELETE
7810
7811 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7812 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7813
7814 #include <ctype.h>
7815
7816 #include <cassert>
7817 #include <iterator>
7818 #include <memory>
7819 #include <set>
7820 #include <tuple>
7821 #include <type_traits>
7822 #include <utility>
7823 #include <vector>
7824
7825 // Copyright 2008, Google Inc.
7826 // All rights reserved.
7827 //
7828 // Redistribution and use in source and binary forms, with or without
7829 // modification, are permitted provided that the following conditions are
7830 // met:
7831 //
7832 // * Redistributions of source code must retain the above copyright
7833 // notice, this list of conditions and the following disclaimer.
7834 // * Redistributions in binary form must reproduce the above
7835 // copyright notice, this list of conditions and the following disclaimer
7836 // in the documentation and/or other materials provided with the
7837 // distribution.
7838 // * Neither the name of Google Inc. nor the names of its
7839 // contributors may be used to endorse or promote products derived from
7840 // this software without specific prior written permission.
7841 //
7842 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7843 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7844 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7845 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7846 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7847 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7848 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7849 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7850 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7851 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7852 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7853 //
7854 // GOOGLETEST_CM0001 DO NOT DELETE
7855
7856 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7857 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7858
7859 #include <iosfwd>
7860 #include <vector>
7861
7862 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7863 /* class A needs to have dll-interface to be used by clients of class B */)
7864
7865 namespace testing {
7866
7867 // A copyable object representing the result of a test part (i.e. an
7868 // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
7869 //
7870 // Don't inherit from TestPartResult as its destructor is not virtual.
7871 class GTEST_API_ TestPartResult {
7872 public:
7873 // The possible outcomes of a test part (i.e. an assertion or an
7874 // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
7875 enum Type {
7876 kSuccess, // Succeeded.
7877 kNonFatalFailure, // Failed but the test can continue.
7878 kFatalFailure, // Failed and the test should be terminated.
7879 kSkip // Skipped.
7880 };
7881
7882 // C'tor. TestPartResult does NOT have a default constructor.
7883 // Always use this constructor (with parameters) to create a
7884 // TestPartResult object.
7885 TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
7886 const char* a_message)
7887 : type_(a_type),
7888 file_name_(a_file_name == nullptr ? "" : a_file_name),
7889 line_number_(a_line_number),
7890 summary_(ExtractSummary(a_message)),
7891 message_(a_message) {}
7892
7893 // Gets the outcome of the test part.
7894 Type type() const { return type_; }
7895
7896 // Gets the name of the source file where the test part took place, or
7897 // NULL if it's unknown.
7898 const char* file_name() const {
7899 return file_name_.empty() ? nullptr : file_name_.c_str();
7900 }
7901
7902 // Gets the line in the source file where the test part took place,
7903 // or -1 if it's unknown.
7904 int line_number() const { return line_number_; }
7905
7906 // Gets the summary of the failure message.
7907 const char* summary() const { return summary_.c_str(); }
7908
7909 // Gets the message associated with the test part.
7910 const char* message() const { return message_.c_str(); }
7911
7912 // Returns true if and only if the test part was skipped.
7913 bool skipped() const { return type_ == kSkip; }
7914
7915 // Returns true if and only if the test part passed.
7916 bool passed() const { return type_ == kSuccess; }
7917
7918 // Returns true if and only if the test part non-fatally failed.
7919 bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
7920
7921 // Returns true if and only if the test part fatally failed.
7922 bool fatally_failed() const { return type_ == kFatalFailure; }
7923
7924 // Returns true if and only if the test part failed.
7925 bool failed() const { return fatally_failed() || nonfatally_failed(); }
7926
7927 private:
7928 Type type_;
7929
7930 // Gets the summary of the failure message by omitting the stack
7931 // trace in it.
7932 static std::string ExtractSummary(const char* message);
7933
7934 // The name of the source file where the test part took place, or
7935 // "" if the source file is unknown.
7936 std::string file_name_;
7937 // The line in the source file where the test part took place, or -1
7938 // if the line number is unknown.
7939 int line_number_;
7940 std::string summary_; // The test failure summary.
7941 std::string message_; // The test failure message.
7942 };
7943
7944 // Prints a TestPartResult object.
7945 std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
7946
7947 // An array of TestPartResult objects.
7948 //
7949 // Don't inherit from TestPartResultArray as its destructor is not
7950 // virtual.
7951 class GTEST_API_ TestPartResultArray {
7952 public:
7953 TestPartResultArray() {}
7954
7955 // Appends the given TestPartResult to the array.
7956 void Append(const TestPartResult& result);
7957
7958 // Returns the TestPartResult at the given index (0-based).
7959 const TestPartResult& GetTestPartResult(int index) const;
7960
7961 // Returns the number of TestPartResult objects in the array.
7962 int size() const;
7963
7964 private:
7965 std::vector<TestPartResult> array_;
7966
7967 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
7968 };
7969
7970 // This interface knows how to report a test part result.
7971 class GTEST_API_ TestPartResultReporterInterface {
7972 public:
7973 virtual ~TestPartResultReporterInterface() {}
7974
7975 virtual void ReportTestPartResult(const TestPartResult& result) = 0;
7976 };
7977
7978 namespace internal {
7979
7980 // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
7981 // statement generates new fatal failures. To do so it registers itself as the
7982 // current test part result reporter. Besides checking if fatal failures were
7983 // reported, it only delegates the reporting to the former result reporter.
7984 // The original result reporter is restored in the destructor.
7985 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
7986 class GTEST_API_ HasNewFatalFailureHelper
7987 : public TestPartResultReporterInterface {
7988 public:
7989 HasNewFatalFailureHelper();
7990 ~HasNewFatalFailureHelper() override;
7991 void ReportTestPartResult(const TestPartResult& result) override;
7992 bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
7993 private:
7994 bool has_new_fatal_failure_;
7995 TestPartResultReporterInterface* original_reporter_;
7996
7997 GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
7998 };
7999
8000 } // namespace internal
8001
8002 } // namespace testing
8003
8004 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
8005
8006 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
8007
8008 namespace testing {
8009 // Input to a parameterized test name generator, describing a test parameter.
8010 // Consists of the parameter value and the integer parameter index.
8011 template <class ParamType>
8012 struct TestParamInfo {
8013 TestParamInfo(const ParamType& a_param, size_t an_index) :
8014 param(a_param),
8015 index(an_index) {}
8016 ParamType param;
8017 size_t index;
8018 };
8019
8020 // A builtin parameterized test name generator which returns the result of
8021 // testing::PrintToString.
8022 struct PrintToStringParamName {
8023 template <class ParamType>
8024 std::string operator()(const TestParamInfo<ParamType>& info) const {
8025 return PrintToString(info.param);
8026 }
8027 };
8028
8029 namespace internal {
8030
8031 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8032 // Utility Functions
8033
8034 // Outputs a message explaining invalid registration of different
8035 // fixture class for the same test suite. This may happen when
8036 // TEST_P macro is used to define two tests with the same name
8037 // but in different namespaces.
8038 GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
8039 CodeLocation code_location);
8040
8041 template <typename> class ParamGeneratorInterface;
8042 template <typename> class ParamGenerator;
8043
8044 // Interface for iterating over elements provided by an implementation
8045 // of ParamGeneratorInterface<T>.
8046 template <typename T>
8047 class ParamIteratorInterface {
8048 public:
8049 virtual ~ParamIteratorInterface() {}
8050 // A pointer to the base generator instance.
8051 // Used only for the purposes of iterator comparison
8052 // to make sure that two iterators belong to the same generator.
8053 virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
8054 // Advances iterator to point to the next element
8055 // provided by the generator. The caller is responsible
8056 // for not calling Advance() on an iterator equal to
8057 // BaseGenerator()->End().
8058 virtual void Advance() = 0;
8059 // Clones the iterator object. Used for implementing copy semantics
8060 // of ParamIterator<T>.
8061 virtual ParamIteratorInterface* Clone() const = 0;
8062 // Dereferences the current iterator and provides (read-only) access
8063 // to the pointed value. It is the caller's responsibility not to call
8064 // Current() on an iterator equal to BaseGenerator()->End().
8065 // Used for implementing ParamGenerator<T>::operator*().
8066 virtual const T* Current() const = 0;
8067 // Determines whether the given iterator and other point to the same
8068 // element in the sequence generated by the generator.
8069 // Used for implementing ParamGenerator<T>::operator==().
8070 virtual bool Equals(const ParamIteratorInterface& other) const = 0;
8071 };
8072
8073 // Class iterating over elements provided by an implementation of
8074 // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
8075 // and implements the const forward iterator concept.
8076 template <typename T>
8077 class ParamIterator {
8078 public:
8079 typedef T value_type;
8080 typedef const T& reference;
8081 typedef ptrdiff_t difference_type;
8082
8083 // ParamIterator assumes ownership of the impl_ pointer.
8084 ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
8085 ParamIterator& operator=(const ParamIterator& other) {
8086 if (this != &other)
8087 impl_.reset(other.impl_->Clone());
8088 return *this;
8089 }
8090
8091 const T& operator*() const { return *impl_->Current(); }
8092 const T* operator->() const { return impl_->Current(); }
8093 // Prefix version of operator++.
8094 ParamIterator& operator++() {
8095 impl_->Advance();
8096 return *this;
8097 }
8098 // Postfix version of operator++.
8099 ParamIterator operator++(int /*unused*/) {
8100 ParamIteratorInterface<T>* clone = impl_->Clone();
8101 impl_->Advance();
8102 return ParamIterator(clone);
8103 }
8104 bool operator==(const ParamIterator& other) const {
8105 return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
8106 }
8107 bool operator!=(const ParamIterator& other) const {
8108 return !(*this == other);
8109 }
8110
8111 private:
8112 friend class ParamGenerator<T>;
8113 explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
8114 std::unique_ptr<ParamIteratorInterface<T> > impl_;
8115 };
8116
8117 // ParamGeneratorInterface<T> is the binary interface to access generators
8118 // defined in other translation units.
8119 template <typename T>
8120 class ParamGeneratorInterface {
8121 public:
8122 typedef T ParamType;
8123
8124 virtual ~ParamGeneratorInterface() {}
8125
8126 // Generator interface definition
8127 virtual ParamIteratorInterface<T>* Begin() const = 0;
8128 virtual ParamIteratorInterface<T>* End() const = 0;
8129 };
8130
8131 // Wraps ParamGeneratorInterface<T> and provides general generator syntax
8132 // compatible with the STL Container concept.
8133 // This class implements copy initialization semantics and the contained
8134 // ParamGeneratorInterface<T> instance is shared among all copies
8135 // of the original object. This is possible because that instance is immutable.
8136 template<typename T>
8137 class ParamGenerator {
8138 public:
8139 typedef ParamIterator<T> iterator;
8140
8141 explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
8142 ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
8143
8144 ParamGenerator& operator=(const ParamGenerator& other) {
8145 impl_ = other.impl_;
8146 return *this;
8147 }
8148
8149 iterator begin() const { return iterator(impl_->Begin()); }
8150 iterator end() const { return iterator(impl_->End()); }
8151
8152 private:
8153 std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
8154 };
8155
8156 // Generates values from a range of two comparable values. Can be used to
8157 // generate sequences of user-defined types that implement operator+() and
8158 // operator<().
8159 // This class is used in the Range() function.
8160 template <typename T, typename IncrementT>
8161 class RangeGenerator : public ParamGeneratorInterface<T> {
8162 public:
8163 RangeGenerator(T begin, T end, IncrementT step)
8164 : begin_(begin), end_(end),
8165 step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
8166 ~RangeGenerator() override {}
8167
8168 ParamIteratorInterface<T>* Begin() const override {
8169 return new Iterator(this, begin_, 0, step_);
8170 }
8171 ParamIteratorInterface<T>* End() const override {
8172 return new Iterator(this, end_, end_index_, step_);
8173 }
8174
8175 private:
8176 class Iterator : public ParamIteratorInterface<T> {
8177 public:
8178 Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
8179 IncrementT step)
8180 : base_(base), value_(value), index_(index), step_(step) {}
8181 ~Iterator() override {}
8182
8183 const ParamGeneratorInterface<T>* BaseGenerator() const override {
8184 return base_;
8185 }
8186 void Advance() override {
8187 value_ = static_cast<T>(value_ + step_);
8188 index_++;
8189 }
8190 ParamIteratorInterface<T>* Clone() const override {
8191 return new Iterator(*this);
8192 }
8193 const T* Current() const override { return &value_; }
8194 bool Equals(const ParamIteratorInterface<T>& other) const override {
8195 // Having the same base generator guarantees that the other
8196 // iterator is of the same type and we can downcast.
8197 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8198 << "The program attempted to compare iterators "
8199 << "from different generators." << std::endl;
8200 const int other_index =
8201 CheckedDowncastToActualType<const Iterator>(&other)->index_;
8202 return index_ == other_index;
8203 }
8204
8205 private:
8206 Iterator(const Iterator& other)
8207 : ParamIteratorInterface<T>(),
8208 base_(other.base_), value_(other.value_), index_(other.index_),
8209 step_(other.step_) {}
8210
8211 // No implementation - assignment is unsupported.
8212 void operator=(const Iterator& other);
8213
8214 const ParamGeneratorInterface<T>* const base_;
8215 T value_;
8216 int index_;
8217 const IncrementT step_;
8218 }; // class RangeGenerator::Iterator
8219
8220 static int CalculateEndIndex(const T& begin,
8221 const T& end,
8222 const IncrementT& step) {
8223 int end_index = 0;
8224 for (T i = begin; i < end; i = static_cast<T>(i + step))
8225 end_index++;
8226 return end_index;
8227 }
8228
8229 // No implementation - assignment is unsupported.
8230 void operator=(const RangeGenerator& other);
8231
8232 const T begin_;
8233 const T end_;
8234 const IncrementT step_;
8235 // The index for the end() iterator. All the elements in the generated
8236 // sequence are indexed (0-based) to aid iterator comparison.
8237 const int end_index_;
8238 }; // class RangeGenerator
8239
8240
8241 // Generates values from a pair of STL-style iterators. Used in the
8242 // ValuesIn() function. The elements are copied from the source range
8243 // since the source can be located on the stack, and the generator
8244 // is likely to persist beyond that stack frame.
8245 template <typename T>
8246 class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
8247 public:
8248 template <typename ForwardIterator>
8249 ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
8250 : container_(begin, end) {}
8251 ~ValuesInIteratorRangeGenerator() override {}
8252
8253 ParamIteratorInterface<T>* Begin() const override {
8254 return new Iterator(this, container_.begin());
8255 }
8256 ParamIteratorInterface<T>* End() const override {
8257 return new Iterator(this, container_.end());
8258 }
8259
8260 private:
8261 typedef typename ::std::vector<T> ContainerType;
8262
8263 class Iterator : public ParamIteratorInterface<T> {
8264 public:
8265 Iterator(const ParamGeneratorInterface<T>* base,
8266 typename ContainerType::const_iterator iterator)
8267 : base_(base), iterator_(iterator) {}
8268 ~Iterator() override {}
8269
8270 const ParamGeneratorInterface<T>* BaseGenerator() const override {
8271 return base_;
8272 }
8273 void Advance() override {
8274 ++iterator_;
8275 value_.reset();
8276 }
8277 ParamIteratorInterface<T>* Clone() const override {
8278 return new Iterator(*this);
8279 }
8280 // We need to use cached value referenced by iterator_ because *iterator_
8281 // can return a temporary object (and of type other then T), so just
8282 // having "return &*iterator_;" doesn't work.
8283 // value_ is updated here and not in Advance() because Advance()
8284 // can advance iterator_ beyond the end of the range, and we cannot
8285 // detect that fact. The client code, on the other hand, is
8286 // responsible for not calling Current() on an out-of-range iterator.
8287 const T* Current() const override {
8288 if (value_.get() == nullptr) value_.reset(new T(*iterator_));
8289 return value_.get();
8290 }
8291 bool Equals(const ParamIteratorInterface<T>& other) const override {
8292 // Having the same base generator guarantees that the other
8293 // iterator is of the same type and we can downcast.
8294 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8295 << "The program attempted to compare iterators "
8296 << "from different generators." << std::endl;
8297 return iterator_ ==
8298 CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
8299 }
8300
8301 private:
8302 Iterator(const Iterator& other)
8303 // The explicit constructor call suppresses a false warning
8304 // emitted by gcc when supplied with the -Wextra option.
8305 : ParamIteratorInterface<T>(),
8306 base_(other.base_),
8307 iterator_(other.iterator_) {}
8308
8309 const ParamGeneratorInterface<T>* const base_;
8310 typename ContainerType::const_iterator iterator_;
8311 // A cached value of *iterator_. We keep it here to allow access by
8312 // pointer in the wrapping iterator's operator->().
8313 // value_ needs to be mutable to be accessed in Current().
8314 // Use of std::unique_ptr helps manage cached value's lifetime,
8315 // which is bound by the lifespan of the iterator itself.
8316 mutable std::unique_ptr<const T> value_;
8317 }; // class ValuesInIteratorRangeGenerator::Iterator
8318
8319 // No implementation - assignment is unsupported.
8320 void operator=(const ValuesInIteratorRangeGenerator& other);
8321
8322 const ContainerType container_;
8323 }; // class ValuesInIteratorRangeGenerator
8324
8325 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8326 //
8327 // Default parameterized test name generator, returns a string containing the
8328 // integer test parameter index.
8329 template <class ParamType>
8330 std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
8331 Message name_stream;
8332 name_stream << info.index;
8333 return name_stream.GetString();
8334 }
8335
8336 template <typename T = int>
8337 void TestNotEmpty() {
8338 static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
8339 }
8340 template <typename T = int>
8341 void TestNotEmpty(const T&) {}
8342
8343 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8344 //
8345 // Stores a parameter value and later creates tests parameterized with that
8346 // value.
8347 template <class TestClass>
8348 class ParameterizedTestFactory : public TestFactoryBase {
8349 public:
8350 typedef typename TestClass::ParamType ParamType;
8351 explicit ParameterizedTestFactory(ParamType parameter) :
8352 parameter_(parameter) {}
8353 Test* CreateTest() override {
8354 TestClass::SetParam(&parameter_);
8355 return new TestClass();
8356 }
8357
8358 private:
8359 const ParamType parameter_;
8360
8361 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
8362 };
8363
8364 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8365 //
8366 // TestMetaFactoryBase is a base class for meta-factories that create
8367 // test factories for passing into MakeAndRegisterTestInfo function.
8368 template <class ParamType>
8369 class TestMetaFactoryBase {
8370 public:
8371 virtual ~TestMetaFactoryBase() {}
8372
8373 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
8374 };
8375
8376 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8377 //
8378 // TestMetaFactory creates test factories for passing into
8379 // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
8380 // ownership of test factory pointer, same factory object cannot be passed
8381 // into that method twice. But ParameterizedTestSuiteInfo is going to call
8382 // it for each Test/Parameter value combination. Thus it needs meta factory
8383 // creator class.
8384 template <class TestSuite>
8385 class TestMetaFactory
8386 : public TestMetaFactoryBase<typename TestSuite::ParamType> {
8387 public:
8388 using ParamType = typename TestSuite::ParamType;
8389
8390 TestMetaFactory() {}
8391
8392 TestFactoryBase* CreateTestFactory(ParamType parameter) override {
8393 return new ParameterizedTestFactory<TestSuite>(parameter);
8394 }
8395
8396 private:
8397 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
8398 };
8399
8400 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8401 //
8402 // ParameterizedTestSuiteInfoBase is a generic interface
8403 // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
8404 // accumulates test information provided by TEST_P macro invocations
8405 // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
8406 // and uses that information to register all resulting test instances
8407 // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
8408 // a collection of pointers to the ParameterizedTestSuiteInfo objects
8409 // and calls RegisterTests() on each of them when asked.
8410 class ParameterizedTestSuiteInfoBase {
8411 public:
8412 virtual ~ParameterizedTestSuiteInfoBase() {}
8413
8414 // Base part of test suite name for display purposes.
8415 virtual const std::string& GetTestSuiteName() const = 0;
8416 // Test suite id to verify identity.
8417 virtual TypeId GetTestSuiteTypeId() const = 0;
8418 // UnitTest class invokes this method to register tests in this
8419 // test suite right before running them in RUN_ALL_TESTS macro.
8420 // This method should not be called more than once on any single
8421 // instance of a ParameterizedTestSuiteInfoBase derived class.
8422 virtual void RegisterTests() = 0;
8423
8424 protected:
8425 ParameterizedTestSuiteInfoBase() {}
8426
8427 private:
8428 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
8429 };
8430
8431 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8432 //
8433 // Report a the name of a test_suit as safe to ignore
8434 // as the side effect of construction of this type.
8435 struct MarkAsIgnored {
8436 explicit MarkAsIgnored(const char* test_suite);
8437 };
8438
8439 GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
8440 CodeLocation location, bool has_test_p);
8441
8442 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8443 //
8444 // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
8445 // macro invocations for a particular test suite and generators
8446 // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
8447 // test suite. It registers tests with all values generated by all
8448 // generators when asked.
8449 template <class TestSuite>
8450 class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
8451 public:
8452 // ParamType and GeneratorCreationFunc are private types but are required
8453 // for declarations of public methods AddTestPattern() and
8454 // AddTestSuiteInstantiation().
8455 using ParamType = typename TestSuite::ParamType;
8456 // A function that returns an instance of appropriate generator type.
8457 typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
8458 using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
8459
8460 explicit ParameterizedTestSuiteInfo(const char* name,
8461 CodeLocation code_location)
8462 : test_suite_name_(name), code_location_(code_location) {}
8463
8464 // Test suite base name for display purposes.
8465 const std::string& GetTestSuiteName() const override {
8466 return test_suite_name_;
8467 }
8468 // Test suite id to verify identity.
8469 TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
8470 // TEST_P macro uses AddTestPattern() to record information
8471 // about a single test in a LocalTestInfo structure.
8472 // test_suite_name is the base name of the test suite (without invocation
8473 // prefix). test_base_name is the name of an individual test without
8474 // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
8475 // test suite base name and DoBar is test base name.
8476 void AddTestPattern(const char* test_suite_name, const char* test_base_name,
8477 TestMetaFactoryBase<ParamType>* meta_factory,
8478 CodeLocation code_location) {
8479 tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
8480 test_suite_name, test_base_name, meta_factory, code_location)));
8481 }
8482 // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
8483 // about a generator.
8484 int AddTestSuiteInstantiation(const std::string& instantiation_name,
8485 GeneratorCreationFunc* func,
8486 ParamNameGeneratorFunc* name_func,
8487 const char* file, int line) {
8488 instantiations_.push_back(
8489 InstantiationInfo(instantiation_name, func, name_func, file, line));
8490 return 0; // Return value used only to run this method in namespace scope.
8491 }
8492 // UnitTest class invokes this method to register tests in this test suite
8493 // right before running tests in RUN_ALL_TESTS macro.
8494 // This method should not be called more than once on any single
8495 // instance of a ParameterizedTestSuiteInfoBase derived class.
8496 // UnitTest has a guard to prevent from calling this method more than once.
8497 void RegisterTests() override {
8498 bool generated_instantiations = false;
8499
8500 for (typename TestInfoContainer::iterator test_it = tests_.begin();
8501 test_it != tests_.end(); ++test_it) {
8502 std::shared_ptr<TestInfo> test_info = *test_it;
8503 for (typename InstantiationContainer::iterator gen_it =
8504 instantiations_.begin(); gen_it != instantiations_.end();
8505 ++gen_it) {
8506 const std::string& instantiation_name = gen_it->name;
8507 ParamGenerator<ParamType> generator((*gen_it->generator)());
8508 ParamNameGeneratorFunc* name_func = gen_it->name_func;
8509 const char* file = gen_it->file;
8510 int line = gen_it->line;
8511
8512 std::string test_suite_name;
8513 if ( !instantiation_name.empty() )
8514 test_suite_name = instantiation_name + "/";
8515 test_suite_name += test_info->test_suite_base_name;
8516
8517 size_t i = 0;
8518 std::set<std::string> test_param_names;
8519 for (typename ParamGenerator<ParamType>::iterator param_it =
8520 generator.begin();
8521 param_it != generator.end(); ++param_it, ++i) {
8522 generated_instantiations = true;
8523
8524 Message test_name_stream;
8525
8526 std::string param_name = name_func(
8527 TestParamInfo<ParamType>(*param_it, i));
8528
8529 GTEST_CHECK_(IsValidParamName(param_name))
8530 << "Parameterized test name '" << param_name
8531 << "' is invalid, in " << file
8532 << " line " << line << std::endl;
8533
8534 GTEST_CHECK_(test_param_names.count(param_name) == 0)
8535 << "Duplicate parameterized test name '" << param_name
8536 << "', in " << file << " line " << line << std::endl;
8537
8538 test_param_names.insert(param_name);
8539
8540 if (!test_info->test_base_name.empty()) {
8541 test_name_stream << test_info->test_base_name << "/";
8542 }
8543 test_name_stream << param_name;
8544 MakeAndRegisterTestInfo(
8545 test_suite_name.c_str(), test_name_stream.GetString().c_str(),
8546 nullptr, // No type parameter.
8547 PrintToString(*param_it).c_str(), test_info->code_location,
8548 GetTestSuiteTypeId(),
8549 SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
8550 SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
8551 test_info->test_meta_factory->CreateTestFactory(*param_it));
8552 } // for param_it
8553 } // for gen_it
8554 } // for test_it
8555
8556 if (!generated_instantiations) {
8557 // There are no generaotrs, or they all generate nothing ...
8558 InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
8559 !tests_.empty());
8560 }
8561 } // RegisterTests
8562
8563 private:
8564 // LocalTestInfo structure keeps information about a single test registered
8565 // with TEST_P macro.
8566 struct TestInfo {
8567 TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
8568 TestMetaFactoryBase<ParamType>* a_test_meta_factory,
8569 CodeLocation a_code_location)
8570 : test_suite_base_name(a_test_suite_base_name),
8571 test_base_name(a_test_base_name),
8572 test_meta_factory(a_test_meta_factory),
8573 code_location(a_code_location) {}
8574
8575 const std::string test_suite_base_name;
8576 const std::string test_base_name;
8577 const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
8578 const CodeLocation code_location;
8579 };
8580 using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
8581 // Records data received from INSTANTIATE_TEST_SUITE_P macros:
8582 // <Instantiation name, Sequence generator creation function,
8583 // Name generator function, Source file, Source line>
8584 struct InstantiationInfo {
8585 InstantiationInfo(const std::string &name_in,
8586 GeneratorCreationFunc* generator_in,
8587 ParamNameGeneratorFunc* name_func_in,
8588 const char* file_in,
8589 int line_in)
8590 : name(name_in),
8591 generator(generator_in),
8592 name_func(name_func_in),
8593 file(file_in),
8594 line(line_in) {}
8595
8596 std::string name;
8597 GeneratorCreationFunc* generator;
8598 ParamNameGeneratorFunc* name_func;
8599 const char* file;
8600 int line;
8601 };
8602 typedef ::std::vector<InstantiationInfo> InstantiationContainer;
8603
8604 static bool IsValidParamName(const std::string& name) {
8605 // Check for empty string
8606 if (name.empty())
8607 return false;
8608
8609 // Check for invalid characters
8610 for (std::string::size_type index = 0; index < name.size(); ++index) {
8611 if (!isalnum(name[index]) && name[index] != '_')
8612 return false;
8613 }
8614
8615 return true;
8616 }
8617
8618 const std::string test_suite_name_;
8619 CodeLocation code_location_;
8620 TestInfoContainer tests_;
8621 InstantiationContainer instantiations_;
8622
8623 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
8624 }; // class ParameterizedTestSuiteInfo
8625
8626 // Legacy API is deprecated but still available
8627 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8628 template <class TestCase>
8629 using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
8630 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8631
8632 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8633 //
8634 // ParameterizedTestSuiteRegistry contains a map of
8635 // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
8636 // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
8637 // ParameterizedTestSuiteInfo descriptors.
8638 class ParameterizedTestSuiteRegistry {
8639 public:
8640 ParameterizedTestSuiteRegistry() {}
8641 ~ParameterizedTestSuiteRegistry() {
8642 for (auto& test_suite_info : test_suite_infos_) {
8643 delete test_suite_info;
8644 }
8645 }
8646
8647 // Looks up or creates and returns a structure containing information about
8648 // tests and instantiations of a particular test suite.
8649 template <class TestSuite>
8650 ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
8651 const char* test_suite_name, CodeLocation code_location) {
8652 ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
8653 for (auto& test_suite_info : test_suite_infos_) {
8654 if (test_suite_info->GetTestSuiteName() == test_suite_name) {
8655 if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
8656 // Complain about incorrect usage of Google Test facilities
8657 // and terminate the program since we cannot guaranty correct
8658 // test suite setup and tear-down in this case.
8659 ReportInvalidTestSuiteType(test_suite_name, code_location);
8660 posix::Abort();
8661 } else {
8662 // At this point we are sure that the object we found is of the same
8663 // type we are looking for, so we downcast it to that type
8664 // without further checks.
8665 typed_test_info = CheckedDowncastToActualType<
8666 ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
8667 }
8668 break;
8669 }
8670 }
8671 if (typed_test_info == nullptr) {
8672 typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
8673 test_suite_name, code_location);
8674 test_suite_infos_.push_back(typed_test_info);
8675 }
8676 return typed_test_info;
8677 }
8678 void RegisterTests() {
8679 for (auto& test_suite_info : test_suite_infos_) {
8680 test_suite_info->RegisterTests();
8681 }
8682 }
8683 // Legacy API is deprecated but still available
8684 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8685 template <class TestCase>
8686 ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
8687 const char* test_case_name, CodeLocation code_location) {
8688 return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
8689 }
8690
8691 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8692
8693 private:
8694 using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
8695
8696 TestSuiteInfoContainer test_suite_infos_;
8697
8698 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
8699 };
8700
8701 // Keep track of what type-parameterized test suite are defined and
8702 // where as well as which are intatiated. This allows susequently
8703 // identifying suits that are defined but never used.
8704 class TypeParameterizedTestSuiteRegistry {
8705 public:
8706 // Add a suite definition
8707 void RegisterTestSuite(const char* test_suite_name,
8708 CodeLocation code_location);
8709
8710 // Add an instantiation of a suit.
8711 void RegisterInstantiation(const char* test_suite_name);
8712
8713 // For each suit repored as defined but not reported as instantiation,
8714 // emit a test that reports that fact (configurably, as an error).
8715 void CheckForInstantiations();
8716
8717 private:
8718 struct TypeParameterizedTestSuiteInfo {
8719 explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
8720 : code_location(c), instantiated(false) {}
8721
8722 CodeLocation code_location;
8723 bool instantiated;
8724 };
8725
8726 std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
8727 };
8728
8729 } // namespace internal
8730
8731 // Forward declarations of ValuesIn(), which is implemented in
8732 // include/gtest/gtest-param-test.h.
8733 template <class Container>
8734 internal::ParamGenerator<typename Container::value_type> ValuesIn(
8735 const Container& container);
8736
8737 namespace internal {
8738 // Used in the Values() function to provide polymorphic capabilities.
8739
8740 #ifdef _MSC_VER
8741 #pragma warning(push)
8742 #pragma warning(disable : 4100)
8743 #endif
8744
8745 template <typename... Ts>
8746 class ValueArray {
8747 public:
8748 explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
8749
8750 template <typename T>
8751 operator ParamGenerator<T>() const { // NOLINT
8752 return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
8753 }
8754
8755 private:
8756 template <typename T, size_t... I>
8757 std::vector<T> MakeVector(IndexSequence<I...>) const {
8758 return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
8759 }
8760
8761 FlatTuple<Ts...> v_;
8762 };
8763
8764 #ifdef _MSC_VER
8765 #pragma warning(pop)
8766 #endif
8767
8768 template <typename... T>
8769 class CartesianProductGenerator
8770 : public ParamGeneratorInterface<::std::tuple<T...>> {
8771 public:
8772 typedef ::std::tuple<T...> ParamType;
8773
8774 CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
8775 : generators_(g) {}
8776 ~CartesianProductGenerator() override {}
8777
8778 ParamIteratorInterface<ParamType>* Begin() const override {
8779 return new Iterator(this, generators_, false);
8780 }
8781 ParamIteratorInterface<ParamType>* End() const override {
8782 return new Iterator(this, generators_, true);
8783 }
8784
8785 private:
8786 template <class I>
8787 class IteratorImpl;
8788 template <size_t... I>
8789 class IteratorImpl<IndexSequence<I...>>
8790 : public ParamIteratorInterface<ParamType> {
8791 public:
8792 IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
8793 const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
8794 : base_(base),
8795 begin_(std::get<I>(generators).begin()...),
8796 end_(std::get<I>(generators).end()...),
8797 current_(is_end ? end_ : begin_) {
8798 ComputeCurrentValue();
8799 }
8800 ~IteratorImpl() override {}
8801
8802 const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
8803 return base_;
8804 }
8805 // Advance should not be called on beyond-of-range iterators
8806 // so no component iterators must be beyond end of range, either.
8807 void Advance() override {
8808 assert(!AtEnd());
8809 // Advance the last iterator.
8810 ++std::get<sizeof...(T) - 1>(current_);
8811 // if that reaches end, propagate that up.
8812 AdvanceIfEnd<sizeof...(T) - 1>();
8813 ComputeCurrentValue();
8814 }
8815 ParamIteratorInterface<ParamType>* Clone() const override {
8816 return new IteratorImpl(*this);
8817 }
8818
8819 const ParamType* Current() const override { return current_value_.get(); }
8820
8821 bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
8822 // Having the same base generator guarantees that the other
8823 // iterator is of the same type and we can downcast.
8824 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8825 << "The program attempted to compare iterators "
8826 << "from different generators." << std::endl;
8827 const IteratorImpl* typed_other =
8828 CheckedDowncastToActualType<const IteratorImpl>(&other);
8829
8830 // We must report iterators equal if they both point beyond their
8831 // respective ranges. That can happen in a variety of fashions,
8832 // so we have to consult AtEnd().
8833 if (AtEnd() && typed_other->AtEnd()) return true;
8834
8835 bool same = true;
8836 bool dummy[] = {
8837 (same = same && std::get<I>(current_) ==
8838 std::get<I>(typed_other->current_))...};
8839 (void)dummy;
8840 return same;
8841 }
8842
8843 private:
8844 template <size_t ThisI>
8845 void AdvanceIfEnd() {
8846 if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
8847
8848 bool last = ThisI == 0;
8849 if (last) {
8850 // We are done. Nothing else to propagate.
8851 return;
8852 }
8853
8854 constexpr size_t NextI = ThisI - (ThisI != 0);
8855 std::get<ThisI>(current_) = std::get<ThisI>(begin_);
8856 ++std::get<NextI>(current_);
8857 AdvanceIfEnd<NextI>();
8858 }
8859
8860 void ComputeCurrentValue() {
8861 if (!AtEnd())
8862 current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
8863 }
8864 bool AtEnd() const {
8865 bool at_end = false;
8866 bool dummy[] = {
8867 (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
8868 (void)dummy;
8869 return at_end;
8870 }
8871
8872 const ParamGeneratorInterface<ParamType>* const base_;
8873 std::tuple<typename ParamGenerator<T>::iterator...> begin_;
8874 std::tuple<typename ParamGenerator<T>::iterator...> end_;
8875 std::tuple<typename ParamGenerator<T>::iterator...> current_;
8876 std::shared_ptr<ParamType> current_value_;
8877 };
8878
8879 using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
8880
8881 std::tuple<ParamGenerator<T>...> generators_;
8882 };
8883
8884 template <class... Gen>
8885 class CartesianProductHolder {
8886 public:
8887 CartesianProductHolder(const Gen&... g) : generators_(g...) {}
8888 template <typename... T>
8889 operator ParamGenerator<::std::tuple<T...>>() const {
8890 return ParamGenerator<::std::tuple<T...>>(
8891 new CartesianProductGenerator<T...>(generators_));
8892 }
8893
8894 private:
8895 std::tuple<Gen...> generators_;
8896 };
8897
8898 } // namespace internal
8899 } // namespace testing
8900
8901 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
8902
8903 namespace testing {
8904
8905 // Functions producing parameter generators.
8906 //
8907 // Google Test uses these generators to produce parameters for value-
8908 // parameterized tests. When a parameterized test suite is instantiated
8909 // with a particular generator, Google Test creates and runs tests
8910 // for each element in the sequence produced by the generator.
8911 //
8912 // In the following sample, tests from test suite FooTest are instantiated
8913 // each three times with parameter values 3, 5, and 8:
8914 //
8915 // class FooTest : public TestWithParam<int> { ... };
8916 //
8917 // TEST_P(FooTest, TestThis) {
8918 // }
8919 // TEST_P(FooTest, TestThat) {
8920 // }
8921 // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
8922 //
8923
8924 // Range() returns generators providing sequences of values in a range.
8925 //
8926 // Synopsis:
8927 // Range(start, end)
8928 // - returns a generator producing a sequence of values {start, start+1,
8929 // start+2, ..., }.
8930 // Range(start, end, step)
8931 // - returns a generator producing a sequence of values {start, start+step,
8932 // start+step+step, ..., }.
8933 // Notes:
8934 // * The generated sequences never include end. For example, Range(1, 5)
8935 // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
8936 // returns a generator producing {1, 3, 5, 7}.
8937 // * start and end must have the same type. That type may be any integral or
8938 // floating-point type or a user defined type satisfying these conditions:
8939 // * It must be assignable (have operator=() defined).
8940 // * It must have operator+() (operator+(int-compatible type) for
8941 // two-operand version).
8942 // * It must have operator<() defined.
8943 // Elements in the resulting sequences will also have that type.
8944 // * Condition start < end must be satisfied in order for resulting sequences
8945 // to contain any elements.
8946 //
8947 template <typename T, typename IncrementT>
8948 internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
8949 return internal::ParamGenerator<T>(
8950 new internal::RangeGenerator<T, IncrementT>(start, end, step));
8951 }
8952
8953 template <typename T>
8954 internal::ParamGenerator<T> Range(T start, T end) {
8955 return Range(start, end, 1);
8956 }
8957
8958 // ValuesIn() function allows generation of tests with parameters coming from
8959 // a container.
8960 //
8961 // Synopsis:
8962 // ValuesIn(const T (&array)[N])
8963 // - returns a generator producing sequences with elements from
8964 // a C-style array.
8965 // ValuesIn(const Container& container)
8966 // - returns a generator producing sequences with elements from
8967 // an STL-style container.
8968 // ValuesIn(Iterator begin, Iterator end)
8969 // - returns a generator producing sequences with elements from
8970 // a range [begin, end) defined by a pair of STL-style iterators. These
8971 // iterators can also be plain C pointers.
8972 //
8973 // Please note that ValuesIn copies the values from the containers
8974 // passed in and keeps them to generate tests in RUN_ALL_TESTS().
8975 //
8976 // Examples:
8977 //
8978 // This instantiates tests from test suite StringTest
8979 // each with C-string values of "foo", "bar", and "baz":
8980 //
8981 // const char* strings[] = {"foo", "bar", "baz"};
8982 // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
8983 //
8984 // This instantiates tests from test suite StlStringTest
8985 // each with STL strings with values "a" and "b":
8986 //
8987 // ::std::vector< ::std::string> GetParameterStrings() {
8988 // ::std::vector< ::std::string> v;
8989 // v.push_back("a");
8990 // v.push_back("b");
8991 // return v;
8992 // }
8993 //
8994 // INSTANTIATE_TEST_SUITE_P(CharSequence,
8995 // StlStringTest,
8996 // ValuesIn(GetParameterStrings()));
8997 //
8998 //
8999 // This will also instantiate tests from CharTest
9000 // each with parameter values 'a' and 'b':
9001 //
9002 // ::std::list<char> GetParameterChars() {
9003 // ::std::list<char> list;
9004 // list.push_back('a');
9005 // list.push_back('b');
9006 // return list;
9007 // }
9008 // ::std::list<char> l = GetParameterChars();
9009 // INSTANTIATE_TEST_SUITE_P(CharSequence2,
9010 // CharTest,
9011 // ValuesIn(l.begin(), l.end()));
9012 //
9013 template <typename ForwardIterator>
9014 internal::ParamGenerator<
9015 typename std::iterator_traits<ForwardIterator>::value_type>
9016 ValuesIn(ForwardIterator begin, ForwardIterator end) {
9017 typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
9018 return internal::ParamGenerator<ParamType>(
9019 new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
9020 }
9021
9022 template <typename T, size_t N>
9023 internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
9024 return ValuesIn(array, array + N);
9025 }
9026
9027 template <class Container>
9028 internal::ParamGenerator<typename Container::value_type> ValuesIn(
9029 const Container& container) {
9030 return ValuesIn(container.begin(), container.end());
9031 }
9032
9033 // Values() allows generating tests from explicitly specified list of
9034 // parameters.
9035 //
9036 // Synopsis:
9037 // Values(T v1, T v2, ..., T vN)
9038 // - returns a generator producing sequences with elements v1, v2, ..., vN.
9039 //
9040 // For example, this instantiates tests from test suite BarTest each
9041 // with values "one", "two", and "three":
9042 //
9043 // INSTANTIATE_TEST_SUITE_P(NumSequence,
9044 // BarTest,
9045 // Values("one", "two", "three"));
9046 //
9047 // This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
9048 // The exact type of values will depend on the type of parameter in BazTest.
9049 //
9050 // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
9051 //
9052 //
9053 template <typename... T>
9054 internal::ValueArray<T...> Values(T... v) {
9055 return internal::ValueArray<T...>(std::move(v)...);
9056 }
9057
9058 // Bool() allows generating tests with parameters in a set of (false, true).
9059 //
9060 // Synopsis:
9061 // Bool()
9062 // - returns a generator producing sequences with elements {false, true}.
9063 //
9064 // It is useful when testing code that depends on Boolean flags. Combinations
9065 // of multiple flags can be tested when several Bool()'s are combined using
9066 // Combine() function.
9067 //
9068 // In the following example all tests in the test suite FlagDependentTest
9069 // will be instantiated twice with parameters false and true.
9070 //
9071 // class FlagDependentTest : public testing::TestWithParam<bool> {
9072 // virtual void SetUp() {
9073 // external_flag = GetParam();
9074 // }
9075 // }
9076 // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
9077 //
9078 inline internal::ParamGenerator<bool> Bool() {
9079 return Values(false, true);
9080 }
9081
9082 // Combine() allows the user to combine two or more sequences to produce
9083 // values of a Cartesian product of those sequences' elements.
9084 //
9085 // Synopsis:
9086 // Combine(gen1, gen2, ..., genN)
9087 // - returns a generator producing sequences with elements coming from
9088 // the Cartesian product of elements from the sequences generated by
9089 // gen1, gen2, ..., genN. The sequence elements will have a type of
9090 // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
9091 // of elements from sequences produces by gen1, gen2, ..., genN.
9092 //
9093 // Example:
9094 //
9095 // This will instantiate tests in test suite AnimalTest each one with
9096 // the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
9097 // tuple("dog", BLACK), and tuple("dog", WHITE):
9098 //
9099 // enum Color { BLACK, GRAY, WHITE };
9100 // class AnimalTest
9101 // : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
9102 //
9103 // TEST_P(AnimalTest, AnimalLooksNice) {...}
9104 //
9105 // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
9106 // Combine(Values("cat", "dog"),
9107 // Values(BLACK, WHITE)));
9108 //
9109 // This will instantiate tests in FlagDependentTest with all variations of two
9110 // Boolean flags:
9111 //
9112 // class FlagDependentTest
9113 // : public testing::TestWithParam<std::tuple<bool, bool> > {
9114 // virtual void SetUp() {
9115 // // Assigns external_flag_1 and external_flag_2 values from the tuple.
9116 // std::tie(external_flag_1, external_flag_2) = GetParam();
9117 // }
9118 // };
9119 //
9120 // TEST_P(FlagDependentTest, TestFeature1) {
9121 // // Test your code using external_flag_1 and external_flag_2 here.
9122 // }
9123 // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
9124 // Combine(Bool(), Bool()));
9125 //
9126 template <typename... Generator>
9127 internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
9128 return internal::CartesianProductHolder<Generator...>(g...);
9129 }
9130
9131 #define TEST_P(test_suite_name, test_name) \
9132 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
9133 : public test_suite_name { \
9134 public: \
9135 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
9136 void TestBody() override; \
9137 \
9138 private: \
9139 static int AddToRegistry() { \
9140 ::testing::UnitTest::GetInstance() \
9141 ->parameterized_test_registry() \
9142 .GetTestSuitePatternHolder<test_suite_name>( \
9143 GTEST_STRINGIFY_(test_suite_name), \
9144 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9145 ->AddTestPattern( \
9146 GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
9147 new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
9148 test_suite_name, test_name)>(), \
9149 ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
9150 return 0; \
9151 } \
9152 static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
9153 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
9154 test_name)); \
9155 }; \
9156 int GTEST_TEST_CLASS_NAME_(test_suite_name, \
9157 test_name)::gtest_registering_dummy_ = \
9158 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
9159 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
9160
9161 // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
9162 // generator and an optional function or functor that generates custom test name
9163 // suffixes based on the test parameters. Such a function or functor should
9164 // accept one argument of type testing::TestParamInfo<class ParamType>, and
9165 // return std::string.
9166 //
9167 // testing::PrintToStringParamName is a builtin test suffix generator that
9168 // returns the value of testing::PrintToString(GetParam()).
9169 //
9170 // Note: test names must be non-empty, unique, and may only contain ASCII
9171 // alphanumeric characters or underscore. Because PrintToString adds quotes
9172 // to std::string and C strings, it won't work for these types.
9173
9174 #define GTEST_EXPAND_(arg) arg
9175 #define GTEST_GET_FIRST_(first, ...) first
9176 #define GTEST_GET_SECOND_(first, second, ...) second
9177
9178 #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
9179 static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
9180 gtest_##prefix##test_suite_name##_EvalGenerator_() { \
9181 return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
9182 } \
9183 static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
9184 const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
9185 if (::testing::internal::AlwaysFalse()) { \
9186 ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
9187 __VA_ARGS__, \
9188 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9189 DUMMY_PARAM_))); \
9190 auto t = std::make_tuple(__VA_ARGS__); \
9191 static_assert(std::tuple_size<decltype(t)>::value <= 2, \
9192 "Too Many Args!"); \
9193 } \
9194 return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
9195 __VA_ARGS__, \
9196 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9197 DUMMY_PARAM_))))(info); \
9198 } \
9199 static int gtest_##prefix##test_suite_name##_dummy_ \
9200 GTEST_ATTRIBUTE_UNUSED_ = \
9201 ::testing::UnitTest::GetInstance() \
9202 ->parameterized_test_registry() \
9203 .GetTestSuitePatternHolder<test_suite_name>( \
9204 GTEST_STRINGIFY_(test_suite_name), \
9205 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9206 ->AddTestSuiteInstantiation( \
9207 GTEST_STRINGIFY_(prefix), \
9208 &gtest_##prefix##test_suite_name##_EvalGenerator_, \
9209 &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
9210 __FILE__, __LINE__)
9211
9212
9213 // Allow Marking a Parameterized test class as not needing to be instantiated.
9214 #define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
9215 namespace gtest_do_not_use_outside_namespace_scope {} \
9216 static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
9217 GTEST_STRINGIFY_(T))
9218
9219 // Legacy API is deprecated but still available
9220 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9221 #define INSTANTIATE_TEST_CASE_P \
9222 static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
9223 ""); \
9224 INSTANTIATE_TEST_SUITE_P
9225 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9226
9227 } // namespace testing
9228
9229 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
9230 // Copyright 2006, Google Inc.
9231 // All rights reserved.
9232 //
9233 // Redistribution and use in source and binary forms, with or without
9234 // modification, are permitted provided that the following conditions are
9235 // met:
9236 //
9237 // * Redistributions of source code must retain the above copyright
9238 // notice, this list of conditions and the following disclaimer.
9239 // * Redistributions in binary form must reproduce the above
9240 // copyright notice, this list of conditions and the following disclaimer
9241 // in the documentation and/or other materials provided with the
9242 // distribution.
9243 // * Neither the name of Google Inc. nor the names of its
9244 // contributors may be used to endorse or promote products derived from
9245 // this software without specific prior written permission.
9246 //
9247 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9248 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9249 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9250 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9251 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9252 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9253 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9254 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9255 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9256 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9257 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9258
9259 //
9260 // Google C++ Testing and Mocking Framework definitions useful in production code.
9261 // GOOGLETEST_CM0003 DO NOT DELETE
9262
9263 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9264 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9265
9266 // When you need to test the private or protected members of a class,
9267 // use the FRIEND_TEST macro to declare your tests as friends of the
9268 // class. For example:
9269 //
9270 // class MyClass {
9271 // private:
9272 // void PrivateMethod();
9273 // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
9274 // };
9275 //
9276 // class MyClassTest : public testing::Test {
9277 // // ...
9278 // };
9279 //
9280 // TEST_F(MyClassTest, PrivateMethodWorks) {
9281 // // Can call MyClass::PrivateMethod() here.
9282 // }
9283 //
9284 // Note: The test class must be in the same namespace as the class being tested.
9285 // For example, putting MyClassTest in an anonymous namespace will not work.
9286
9287 #define FRIEND_TEST(test_case_name, test_name)\
9288 friend class test_case_name##_##test_name##_Test
9289
9290 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9291 // Copyright 2008 Google Inc.
9292 // All Rights Reserved.
9293 //
9294 // Redistribution and use in source and binary forms, with or without
9295 // modification, are permitted provided that the following conditions are
9296 // met:
9297 //
9298 // * Redistributions of source code must retain the above copyright
9299 // notice, this list of conditions and the following disclaimer.
9300 // * Redistributions in binary form must reproduce the above
9301 // copyright notice, this list of conditions and the following disclaimer
9302 // in the documentation and/or other materials provided with the
9303 // distribution.
9304 // * Neither the name of Google Inc. nor the names of its
9305 // contributors may be used to endorse or promote products derived from
9306 // this software without specific prior written permission.
9307 //
9308 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9309 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9310 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9311 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9312 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9313 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9314 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9315 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9316 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9317 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9318 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9319
9320 // GOOGLETEST_CM0001 DO NOT DELETE
9321
9322 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9323 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9324
9325 // This header implements typed tests and type-parameterized tests.
9326
9327 // Typed (aka type-driven) tests repeat the same test for types in a
9328 // list. You must know which types you want to test with when writing
9329 // typed tests. Here's how you do it:
9330
9331 #if 0
9332
9333 // First, define a fixture class template. It should be parameterized
9334 // by a type. Remember to derive it from testing::Test.
9335 template <typename T>
9336 class FooTest : public testing::Test {
9337 public:
9338 ...
9339 typedef std::list<T> List;
9340 static T shared_;
9341 T value_;
9342 };
9343
9344 // Next, associate a list of types with the test suite, which will be
9345 // repeated for each type in the list. The typedef is necessary for
9346 // the macro to parse correctly.
9347 typedef testing::Types<char, int, unsigned int> MyTypes;
9348 TYPED_TEST_SUITE(FooTest, MyTypes);
9349
9350 // If the type list contains only one type, you can write that type
9351 // directly without Types<...>:
9352 // TYPED_TEST_SUITE(FooTest, int);
9353
9354 // Then, use TYPED_TEST() instead of TEST_F() to define as many typed
9355 // tests for this test suite as you want.
9356 TYPED_TEST(FooTest, DoesBlah) {
9357 // Inside a test, refer to the special name TypeParam to get the type
9358 // parameter. Since we are inside a derived class template, C++ requires
9359 // us to visit the members of FooTest via 'this'.
9360 TypeParam n = this->value_;
9361
9362 // To visit static members of the fixture, add the TestFixture::
9363 // prefix.
9364 n += TestFixture::shared_;
9365
9366 // To refer to typedefs in the fixture, add the "typename
9367 // TestFixture::" prefix.
9368 typename TestFixture::List values;
9369 values.push_back(n);
9370 ...
9371 }
9372
9373 TYPED_TEST(FooTest, HasPropertyA) { ... }
9374
9375 // TYPED_TEST_SUITE takes an optional third argument which allows to specify a
9376 // class that generates custom test name suffixes based on the type. This should
9377 // be a class which has a static template function GetName(int index) returning
9378 // a string for each type. The provided integer index equals the index of the
9379 // type in the provided type list. In many cases the index can be ignored.
9380 //
9381 // For example:
9382 // class MyTypeNames {
9383 // public:
9384 // template <typename T>
9385 // static std::string GetName(int) {
9386 // if (std::is_same<T, char>()) return "char";
9387 // if (std::is_same<T, int>()) return "int";
9388 // if (std::is_same<T, unsigned int>()) return "unsignedInt";
9389 // }
9390 // };
9391 // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
9392
9393 #endif // 0
9394
9395 // Type-parameterized tests are abstract test patterns parameterized
9396 // by a type. Compared with typed tests, type-parameterized tests
9397 // allow you to define the test pattern without knowing what the type
9398 // parameters are. The defined pattern can be instantiated with
9399 // different types any number of times, in any number of translation
9400 // units.
9401 //
9402 // If you are designing an interface or concept, you can define a
9403 // suite of type-parameterized tests to verify properties that any
9404 // valid implementation of the interface/concept should have. Then,
9405 // each implementation can easily instantiate the test suite to verify
9406 // that it conforms to the requirements, without having to write
9407 // similar tests repeatedly. Here's an example:
9408
9409 #if 0
9410
9411 // First, define a fixture class template. It should be parameterized
9412 // by a type. Remember to derive it from testing::Test.
9413 template <typename T>
9414 class FooTest : public testing::Test {
9415 ...
9416 };
9417
9418 // Next, declare that you will define a type-parameterized test suite
9419 // (the _P suffix is for "parameterized" or "pattern", whichever you
9420 // prefer):
9421 TYPED_TEST_SUITE_P(FooTest);
9422
9423 // Then, use TYPED_TEST_P() to define as many type-parameterized tests
9424 // for this type-parameterized test suite as you want.
9425 TYPED_TEST_P(FooTest, DoesBlah) {
9426 // Inside a test, refer to TypeParam to get the type parameter.
9427 TypeParam n = 0;
9428 ...
9429 }
9430
9431 TYPED_TEST_P(FooTest, HasPropertyA) { ... }
9432
9433 // Now the tricky part: you need to register all test patterns before
9434 // you can instantiate them. The first argument of the macro is the
9435 // test suite name; the rest are the names of the tests in this test
9436 // case.
9437 REGISTER_TYPED_TEST_SUITE_P(FooTest,
9438 DoesBlah, HasPropertyA);
9439
9440 // Finally, you are free to instantiate the pattern with the types you
9441 // want. If you put the above code in a header file, you can #include
9442 // it in multiple C++ source files and instantiate it multiple times.
9443 //
9444 // To distinguish different instances of the pattern, the first
9445 // argument to the INSTANTIATE_* macro is a prefix that will be added
9446 // to the actual test suite name. Remember to pick unique prefixes for
9447 // different instances.
9448 typedef testing::Types<char, int, unsigned int> MyTypes;
9449 INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
9450
9451 // If the type list contains only one type, you can write that type
9452 // directly without Types<...>:
9453 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
9454 //
9455 // Similar to the optional argument of TYPED_TEST_SUITE above,
9456 // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
9457 // generate custom names.
9458 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
9459
9460 #endif // 0
9461
9462
9463 // Implements typed tests.
9464
9465 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9466 //
9467 // Expands to the name of the typedef for the type parameters of the
9468 // given test suite.
9469 #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
9470
9471 // Expands to the name of the typedef for the NameGenerator, responsible for
9472 // creating the suffixes of the name.
9473 #define GTEST_NAME_GENERATOR_(TestSuiteName) \
9474 gtest_type_params_##TestSuiteName##_NameGenerator
9475
9476 #define TYPED_TEST_SUITE(CaseName, Types, ...) \
9477 typedef ::testing::internal::GenerateTypeList<Types>::type \
9478 GTEST_TYPE_PARAMS_(CaseName); \
9479 typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
9480 GTEST_NAME_GENERATOR_(CaseName)
9481
9482 #define TYPED_TEST(CaseName, TestName) \
9483 static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
9484 "test-name must not be empty"); \
9485 template <typename gtest_TypeParam_> \
9486 class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
9487 : public CaseName<gtest_TypeParam_> { \
9488 private: \
9489 typedef CaseName<gtest_TypeParam_> TestFixture; \
9490 typedef gtest_TypeParam_ TypeParam; \
9491 void TestBody() override; \
9492 }; \
9493 static bool gtest_##CaseName##_##TestName##_registered_ \
9494 GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
9495 CaseName, \
9496 ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
9497 TestName)>, \
9498 GTEST_TYPE_PARAMS_( \
9499 CaseName)>::Register("", \
9500 ::testing::internal::CodeLocation( \
9501 __FILE__, __LINE__), \
9502 GTEST_STRINGIFY_(CaseName), \
9503 GTEST_STRINGIFY_(TestName), 0, \
9504 ::testing::internal::GenerateNames< \
9505 GTEST_NAME_GENERATOR_(CaseName), \
9506 GTEST_TYPE_PARAMS_(CaseName)>()); \
9507 template <typename gtest_TypeParam_> \
9508 void GTEST_TEST_CLASS_NAME_(CaseName, \
9509 TestName)<gtest_TypeParam_>::TestBody()
9510
9511 // Legacy API is deprecated but still available
9512 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9513 #define TYPED_TEST_CASE \
9514 static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
9515 TYPED_TEST_SUITE
9516 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9517
9518 // Implements type-parameterized tests.
9519
9520 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9521 //
9522 // Expands to the namespace name that the type-parameterized tests for
9523 // the given type-parameterized test suite are defined in. The exact
9524 // name of the namespace is subject to change without notice.
9525 #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
9526
9527 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9528 //
9529 // Expands to the name of the variable used to remember the names of
9530 // the defined tests in the given test suite.
9531 #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
9532 gtest_typed_test_suite_p_state_##TestSuiteName##_
9533
9534 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
9535 //
9536 // Expands to the name of the variable used to remember the names of
9537 // the registered tests in the given test suite.
9538 #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
9539 gtest_registered_test_names_##TestSuiteName##_
9540
9541 // The variables defined in the type-parameterized test macros are
9542 // static as typically these macros are used in a .h file that can be
9543 // #included in multiple translation units linked together.
9544 #define TYPED_TEST_SUITE_P(SuiteName) \
9545 static ::testing::internal::TypedTestSuitePState \
9546 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
9547
9548 // Legacy API is deprecated but still available
9549 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9550 #define TYPED_TEST_CASE_P \
9551 static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
9552 TYPED_TEST_SUITE_P
9553 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9554
9555 #define TYPED_TEST_P(SuiteName, TestName) \
9556 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9557 template <typename gtest_TypeParam_> \
9558 class TestName : public SuiteName<gtest_TypeParam_> { \
9559 private: \
9560 typedef SuiteName<gtest_TypeParam_> TestFixture; \
9561 typedef gtest_TypeParam_ TypeParam; \
9562 void TestBody() override; \
9563 }; \
9564 static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
9565 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
9566 __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
9567 GTEST_STRINGIFY_(TestName)); \
9568 } \
9569 template <typename gtest_TypeParam_> \
9570 void GTEST_SUITE_NAMESPACE_( \
9571 SuiteName)::TestName<gtest_TypeParam_>::TestBody()
9572
9573 // Note: this won't work correctly if the trailing arguments are macros.
9574 #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
9575 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9576 typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
9577 } \
9578 static const char* const GTEST_REGISTERED_TEST_NAMES_( \
9579 SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
9580 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
9581 GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
9582
9583 // Legacy API is deprecated but still available
9584 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9585 #define REGISTER_TYPED_TEST_CASE_P \
9586 static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
9587 ""); \
9588 REGISTER_TYPED_TEST_SUITE_P
9589 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9590
9591 #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
9592 static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
9593 "test-suit-prefix must not be empty"); \
9594 static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
9595 ::testing::internal::TypeParameterizedTestSuite< \
9596 SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
9597 ::testing::internal::GenerateTypeList<Types>::type>:: \
9598 Register(GTEST_STRINGIFY_(Prefix), \
9599 ::testing::internal::CodeLocation(__FILE__, __LINE__), \
9600 &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
9601 GTEST_STRINGIFY_(SuiteName), \
9602 GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
9603 ::testing::internal::GenerateNames< \
9604 ::testing::internal::NameGeneratorSelector< \
9605 __VA_ARGS__>::type, \
9606 ::testing::internal::GenerateTypeList<Types>::type>())
9607
9608 // Legacy API is deprecated but still available
9609 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9610 #define INSTANTIATE_TYPED_TEST_CASE_P \
9611 static_assert( \
9612 ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
9613 INSTANTIATE_TYPED_TEST_SUITE_P
9614 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9615
9616 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9617
9618 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
9619 /* class A needs to have dll-interface to be used by clients of class B */)
9620
9621 namespace testing {
9622
9623 // Silence C4100 (unreferenced formal parameter) and 4805
9624 // unsafe mix of type 'const int' and type 'const bool'
9625 #ifdef _MSC_VER
9626 # pragma warning(push)
9627 # pragma warning(disable:4805)
9628 # pragma warning(disable:4100)
9629 #endif
9630
9631
9632 // Declares the flags.
9633
9634 // This flag temporary enables the disabled tests.
9635 GTEST_DECLARE_bool_(also_run_disabled_tests);
9636
9637 // This flag brings the debugger on an assertion failure.
9638 GTEST_DECLARE_bool_(break_on_failure);
9639
9640 // This flag controls whether Google Test catches all test-thrown exceptions
9641 // and logs them as failures.
9642 GTEST_DECLARE_bool_(catch_exceptions);
9643
9644 // This flag enables using colors in terminal output. Available values are
9645 // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
9646 // to let Google Test decide.
9647 GTEST_DECLARE_string_(color);
9648
9649 // This flag controls whether the test runner should continue execution past
9650 // first failure.
9651 GTEST_DECLARE_bool_(fail_fast);
9652
9653 // This flag sets up the filter to select by name using a glob pattern
9654 // the tests to run. If the filter is not given all tests are executed.
9655 GTEST_DECLARE_string_(filter);
9656
9657 // This flag controls whether Google Test installs a signal handler that dumps
9658 // debugging information when fatal signals are raised.
9659 GTEST_DECLARE_bool_(install_failure_signal_handler);
9660
9661 // This flag causes the Google Test to list tests. None of the tests listed
9662 // are actually run if the flag is provided.
9663 GTEST_DECLARE_bool_(list_tests);
9664
9665 // This flag controls whether Google Test emits a detailed XML report to a file
9666 // in addition to its normal textual output.
9667 GTEST_DECLARE_string_(output);
9668
9669 // This flags control whether Google Test prints only test failures.
9670 GTEST_DECLARE_bool_(brief);
9671
9672 // This flags control whether Google Test prints the elapsed time for each
9673 // test.
9674 GTEST_DECLARE_bool_(print_time);
9675
9676 // This flags control whether Google Test prints UTF8 characters as text.
9677 GTEST_DECLARE_bool_(print_utf8);
9678
9679 // This flag specifies the random number seed.
9680 GTEST_DECLARE_int32_(random_seed);
9681
9682 // This flag sets how many times the tests are repeated. The default value
9683 // is 1. If the value is -1 the tests are repeating forever.
9684 GTEST_DECLARE_int32_(repeat);
9685
9686 // This flag controls whether Google Test includes Google Test internal
9687 // stack frames in failure stack traces.
9688 GTEST_DECLARE_bool_(show_internal_stack_frames);
9689
9690 // When this flag is specified, tests' order is randomized on every iteration.
9691 GTEST_DECLARE_bool_(shuffle);
9692
9693 // This flag specifies the maximum number of stack frames to be
9694 // printed in a failure message.
9695 GTEST_DECLARE_int32_(stack_trace_depth);
9696
9697 // When this flag is specified, a failed assertion will throw an
9698 // exception if exceptions are enabled, or exit the program with a
9699 // non-zero code otherwise. For use with an external test framework.
9700 GTEST_DECLARE_bool_(throw_on_failure);
9701
9702 // When this flag is set with a "host:port" string, on supported
9703 // platforms test results are streamed to the specified port on
9704 // the specified host machine.
9705 GTEST_DECLARE_string_(stream_result_to);
9706
9707 #if GTEST_USE_OWN_FLAGFILE_FLAG_
9708 GTEST_DECLARE_string_(flagfile);
9709 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
9710
9711 // The upper limit for valid stack trace depths.
9712 const int kMaxStackTraceDepth = 100;
9713
9714 namespace internal {
9715
9716 class AssertHelper;
9717 class DefaultGlobalTestPartResultReporter;
9718 class ExecDeathTest;
9719 class NoExecDeathTest;
9720 class FinalSuccessChecker;
9721 class GTestFlagSaver;
9722 class StreamingListenerTest;
9723 class TestResultAccessor;
9724 class TestEventListenersAccessor;
9725 class TestEventRepeater;
9726 class UnitTestRecordPropertyTestHelper;
9727 class WindowsDeathTest;
9728 class FuchsiaDeathTest;
9729 class UnitTestImpl* GetUnitTestImpl();
9730 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
9731 const std::string& message);
9732 std::set<std::string>* GetIgnoredParameterizedTestSuites();
9733
9734 } // namespace internal
9735
9736 // The friend relationship of some of these classes is cyclic.
9737 // If we don't forward declare them the compiler might confuse the classes
9738 // in friendship clauses with same named classes on the scope.
9739 class Test;
9740 class TestSuite;
9741
9742 // Old API is still available but deprecated
9743 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9744 using TestCase = TestSuite;
9745 #endif
9746 class TestInfo;
9747 class UnitTest;
9748
9749 // A class for indicating whether an assertion was successful. When
9750 // the assertion wasn't successful, the AssertionResult object
9751 // remembers a non-empty message that describes how it failed.
9752 //
9753 // To create an instance of this class, use one of the factory functions
9754 // (AssertionSuccess() and AssertionFailure()).
9755 //
9756 // This class is useful for two purposes:
9757 // 1. Defining predicate functions to be used with Boolean test assertions
9758 // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
9759 // 2. Defining predicate-format functions to be
9760 // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
9761 //
9762 // For example, if you define IsEven predicate:
9763 //
9764 // testing::AssertionResult IsEven(int n) {
9765 // if ((n % 2) == 0)
9766 // return testing::AssertionSuccess();
9767 // else
9768 // return testing::AssertionFailure() << n << " is odd";
9769 // }
9770 //
9771 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
9772 // will print the message
9773 //
9774 // Value of: IsEven(Fib(5))
9775 // Actual: false (5 is odd)
9776 // Expected: true
9777 //
9778 // instead of a more opaque
9779 //
9780 // Value of: IsEven(Fib(5))
9781 // Actual: false
9782 // Expected: true
9783 //
9784 // in case IsEven is a simple Boolean predicate.
9785 //
9786 // If you expect your predicate to be reused and want to support informative
9787 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
9788 // about half as often as positive ones in our tests), supply messages for
9789 // both success and failure cases:
9790 //
9791 // testing::AssertionResult IsEven(int n) {
9792 // if ((n % 2) == 0)
9793 // return testing::AssertionSuccess() << n << " is even";
9794 // else
9795 // return testing::AssertionFailure() << n << " is odd";
9796 // }
9797 //
9798 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
9799 //
9800 // Value of: IsEven(Fib(6))
9801 // Actual: true (8 is even)
9802 // Expected: false
9803 //
9804 // NB: Predicates that support negative Boolean assertions have reduced
9805 // performance in positive ones so be careful not to use them in tests
9806 // that have lots (tens of thousands) of positive Boolean assertions.
9807 //
9808 // To use this class with EXPECT_PRED_FORMAT assertions such as:
9809 //
9810 // // Verifies that Foo() returns an even number.
9811 // EXPECT_PRED_FORMAT1(IsEven, Foo());
9812 //
9813 // you need to define:
9814 //
9815 // testing::AssertionResult IsEven(const char* expr, int n) {
9816 // if ((n % 2) == 0)
9817 // return testing::AssertionSuccess();
9818 // else
9819 // return testing::AssertionFailure()
9820 // << "Expected: " << expr << " is even\n Actual: it's " << n;
9821 // }
9822 //
9823 // If Foo() returns 5, you will see the following message:
9824 //
9825 // Expected: Foo() is even
9826 // Actual: it's 5
9827 //
9828 class GTEST_API_ AssertionResult {
9829 public:
9830 // Copy constructor.
9831 // Used in EXPECT_TRUE/FALSE(assertion_result).
9832 AssertionResult(const AssertionResult& other);
9833
9834 // C4800 is a level 3 warning in Visual Studio 2015 and earlier.
9835 // This warning is not emitted in Visual Studio 2017.
9836 // This warning is off by default starting in Visual Studio 2019 but can be
9837 // enabled with command-line options.
9838 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9839 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
9840 #endif
9841
9842 // Used in the EXPECT_TRUE/FALSE(bool_expression).
9843 //
9844 // T must be contextually convertible to bool.
9845 //
9846 // The second parameter prevents this overload from being considered if
9847 // the argument is implicitly convertible to AssertionResult. In that case
9848 // we want AssertionResult's copy constructor to be used.
9849 template <typename T>
9850 explicit AssertionResult(
9851 const T& success,
9852 typename std::enable_if<
9853 !std::is_convertible<T, AssertionResult>::value>::type*
9854 /*enabler*/
9855 = nullptr)
9856 : success_(success) {}
9857
9858 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9859 GTEST_DISABLE_MSC_WARNINGS_POP_()
9860 #endif
9861
9862 // Assignment operator.
9863 AssertionResult& operator=(AssertionResult other) {
9864 swap(other);
9865 return *this;
9866 }
9867
9868 // Returns true if and only if the assertion succeeded.
9869 operator bool() const { return success_; } // NOLINT
9870
9871 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
9872 AssertionResult operator!() const;
9873
9874 // Returns the text streamed into this AssertionResult. Test assertions
9875 // use it when they fail (i.e., the predicate's outcome doesn't match the
9876 // assertion's expectation). When nothing has been streamed into the
9877 // object, returns an empty string.
9878 const char* message() const {
9879 return message_.get() != nullptr ? message_->c_str() : "";
9880 }
9881 // Deprecated; please use message() instead.
9882 const char* failure_message() const { return message(); }
9883
9884 // Streams a custom failure message into this object.
9885 template <typename T> AssertionResult& operator<<(const T& value) {
9886 AppendMessage(Message() << value);
9887 return *this;
9888 }
9889
9890 // Allows streaming basic output manipulators such as endl or flush into
9891 // this object.
9892 AssertionResult& operator<<(
9893 ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
9894 AppendMessage(Message() << basic_manipulator);
9895 return *this;
9896 }
9897
9898 private:
9899 // Appends the contents of message to message_.
9900 void AppendMessage(const Message& a_message) {
9901 if (message_.get() == nullptr) message_.reset(new ::std::string);
9902 message_->append(a_message.GetString().c_str());
9903 }
9904
9905 // Swap the contents of this AssertionResult with other.
9906 void swap(AssertionResult& other);
9907
9908 // Stores result of the assertion predicate.
9909 bool success_;
9910 // Stores the message describing the condition in case the expectation
9911 // construct is not satisfied with the predicate's outcome.
9912 // Referenced via a pointer to avoid taking too much stack frame space
9913 // with test assertions.
9914 std::unique_ptr< ::std::string> message_;
9915 };
9916
9917 // Makes a successful assertion result.
9918 GTEST_API_ AssertionResult AssertionSuccess();
9919
9920 // Makes a failed assertion result.
9921 GTEST_API_ AssertionResult AssertionFailure();
9922
9923 // Makes a failed assertion result with the given failure message.
9924 // Deprecated; use AssertionFailure() << msg.
9925 GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
9926
9927 } // namespace testing
9928
9929 // Includes the auto-generated header that implements a family of generic
9930 // predicate assertion macros. This include comes late because it relies on
9931 // APIs declared above.
9932 // Copyright 2006, Google Inc.
9933 // All rights reserved.
9934 //
9935 // Redistribution and use in source and binary forms, with or without
9936 // modification, are permitted provided that the following conditions are
9937 // met:
9938 //
9939 // * Redistributions of source code must retain the above copyright
9940 // notice, this list of conditions and the following disclaimer.
9941 // * Redistributions in binary form must reproduce the above
9942 // copyright notice, this list of conditions and the following disclaimer
9943 // in the documentation and/or other materials provided with the
9944 // distribution.
9945 // * Neither the name of Google Inc. nor the names of its
9946 // contributors may be used to endorse or promote products derived from
9947 // this software without specific prior written permission.
9948 //
9949 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9950 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9951 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9952 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9953 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9954 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9955 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9956 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9957 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9958 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9959 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9960
9961 // This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
9962 // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
9963 //
9964 // Implements a family of generic predicate assertion macros.
9965 // GOOGLETEST_CM0001 DO NOT DELETE
9966
9967 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9968 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9969
9970
9971 namespace testing {
9972
9973 // This header implements a family of generic predicate assertion
9974 // macros:
9975 //
9976 // ASSERT_PRED_FORMAT1(pred_format, v1)
9977 // ASSERT_PRED_FORMAT2(pred_format, v1, v2)
9978 // ...
9979 //
9980 // where pred_format is a function or functor that takes n (in the
9981 // case of ASSERT_PRED_FORMATn) values and their source expression
9982 // text, and returns a testing::AssertionResult. See the definition
9983 // of ASSERT_EQ in gtest.h for an example.
9984 //
9985 // If you don't care about formatting, you can use the more
9986 // restrictive version:
9987 //
9988 // ASSERT_PRED1(pred, v1)
9989 // ASSERT_PRED2(pred, v1, v2)
9990 // ...
9991 //
9992 // where pred is an n-ary function or functor that returns bool,
9993 // and the values v1, v2, ..., must support the << operator for
9994 // streaming to std::ostream.
9995 //
9996 // We also define the EXPECT_* variations.
9997 //
9998 // For now we only support predicates whose arity is at most 5.
9999 // Please email googletestframework@googlegroups.com if you need
10000 // support for higher arities.
10001
10002 // GTEST_ASSERT_ is the basic statement to which all of the assertions
10003 // in this file reduce. Don't use this in your code.
10004
10005 #define GTEST_ASSERT_(expression, on_failure) \
10006 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
10007 if (const ::testing::AssertionResult gtest_ar = (expression)) \
10008 ; \
10009 else \
10010 on_failure(gtest_ar.failure_message())
10011
10012
10013 // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
10014 // this in your code.
10015 template <typename Pred,
10016 typename T1>
10017 AssertionResult AssertPred1Helper(const char* pred_text,
10018 const char* e1,
10019 Pred pred,
10020 const T1& v1) {
10021 if (pred(v1)) return AssertionSuccess();
10022
10023 return AssertionFailure()
10024 << pred_text << "(" << e1 << ") evaluates to false, where"
10025 << "\n"
10026 << e1 << " evaluates to " << ::testing::PrintToString(v1);
10027 }
10028
10029 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
10030 // Don't use this in your code.
10031 #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
10032 GTEST_ASSERT_(pred_format(#v1, v1), \
10033 on_failure)
10034
10035 // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
10036 // this in your code.
10037 #define GTEST_PRED1_(pred, v1, on_failure)\
10038 GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
10039 #v1, \
10040 pred, \
10041 v1), on_failure)
10042
10043 // Unary predicate assertion macros.
10044 #define EXPECT_PRED_FORMAT1(pred_format, v1) \
10045 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
10046 #define EXPECT_PRED1(pred, v1) \
10047 GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
10048 #define ASSERT_PRED_FORMAT1(pred_format, v1) \
10049 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
10050 #define ASSERT_PRED1(pred, v1) \
10051 GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
10052
10053
10054
10055 // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
10056 // this in your code.
10057 template <typename Pred,
10058 typename T1,
10059 typename T2>
10060 AssertionResult AssertPred2Helper(const char* pred_text,
10061 const char* e1,
10062 const char* e2,
10063 Pred pred,
10064 const T1& v1,
10065 const T2& v2) {
10066 if (pred(v1, v2)) return AssertionSuccess();
10067
10068 return AssertionFailure()
10069 << pred_text << "(" << e1 << ", " << e2
10070 << ") evaluates to false, where"
10071 << "\n"
10072 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10073 << e2 << " evaluates to " << ::testing::PrintToString(v2);
10074 }
10075
10076 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
10077 // Don't use this in your code.
10078 #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
10079 GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
10080 on_failure)
10081
10082 // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
10083 // this in your code.
10084 #define GTEST_PRED2_(pred, v1, v2, on_failure)\
10085 GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
10086 #v1, \
10087 #v2, \
10088 pred, \
10089 v1, \
10090 v2), on_failure)
10091
10092 // Binary predicate assertion macros.
10093 #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
10094 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
10095 #define EXPECT_PRED2(pred, v1, v2) \
10096 GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
10097 #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
10098 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
10099 #define ASSERT_PRED2(pred, v1, v2) \
10100 GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
10101
10102
10103
10104 // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
10105 // this in your code.
10106 template <typename Pred,
10107 typename T1,
10108 typename T2,
10109 typename T3>
10110 AssertionResult AssertPred3Helper(const char* pred_text,
10111 const char* e1,
10112 const char* e2,
10113 const char* e3,
10114 Pred pred,
10115 const T1& v1,
10116 const T2& v2,
10117 const T3& v3) {
10118 if (pred(v1, v2, v3)) return AssertionSuccess();
10119
10120 return AssertionFailure()
10121 << pred_text << "(" << e1 << ", " << e2 << ", " << e3
10122 << ") evaluates to false, where"
10123 << "\n"
10124 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10125 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10126 << e3 << " evaluates to " << ::testing::PrintToString(v3);
10127 }
10128
10129 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
10130 // Don't use this in your code.
10131 #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
10132 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
10133 on_failure)
10134
10135 // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
10136 // this in your code.
10137 #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
10138 GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
10139 #v1, \
10140 #v2, \
10141 #v3, \
10142 pred, \
10143 v1, \
10144 v2, \
10145 v3), on_failure)
10146
10147 // Ternary predicate assertion macros.
10148 #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10149 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10150 #define EXPECT_PRED3(pred, v1, v2, v3) \
10151 GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10152 #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10153 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
10154 #define ASSERT_PRED3(pred, v1, v2, v3) \
10155 GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
10156
10157
10158
10159 // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
10160 // this in your code.
10161 template <typename Pred,
10162 typename T1,
10163 typename T2,
10164 typename T3,
10165 typename T4>
10166 AssertionResult AssertPred4Helper(const char* pred_text,
10167 const char* e1,
10168 const char* e2,
10169 const char* e3,
10170 const char* e4,
10171 Pred pred,
10172 const T1& v1,
10173 const T2& v2,
10174 const T3& v3,
10175 const T4& v4) {
10176 if (pred(v1, v2, v3, v4)) return AssertionSuccess();
10177
10178 return AssertionFailure()
10179 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10180 << ") evaluates to false, where"
10181 << "\n"
10182 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10183 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10184 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10185 << e4 << " evaluates to " << ::testing::PrintToString(v4);
10186 }
10187
10188 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
10189 // Don't use this in your code.
10190 #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
10191 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
10192 on_failure)
10193
10194 // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
10195 // this in your code.
10196 #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
10197 GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
10198 #v1, \
10199 #v2, \
10200 #v3, \
10201 #v4, \
10202 pred, \
10203 v1, \
10204 v2, \
10205 v3, \
10206 v4), on_failure)
10207
10208 // 4-ary predicate assertion macros.
10209 #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10210 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10211 #define EXPECT_PRED4(pred, v1, v2, v3, v4) \
10212 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10213 #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10214 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10215 #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
10216 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10217
10218
10219
10220 // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
10221 // this in your code.
10222 template <typename Pred,
10223 typename T1,
10224 typename T2,
10225 typename T3,
10226 typename T4,
10227 typename T5>
10228 AssertionResult AssertPred5Helper(const char* pred_text,
10229 const char* e1,
10230 const char* e2,
10231 const char* e3,
10232 const char* e4,
10233 const char* e5,
10234 Pred pred,
10235 const T1& v1,
10236 const T2& v2,
10237 const T3& v3,
10238 const T4& v4,
10239 const T5& v5) {
10240 if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
10241
10242 return AssertionFailure()
10243 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10244 << ", " << e5 << ") evaluates to false, where"
10245 << "\n"
10246 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10247 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10248 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10249 << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
10250 << e5 << " evaluates to " << ::testing::PrintToString(v5);
10251 }
10252
10253 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
10254 // Don't use this in your code.
10255 #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
10256 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
10257 on_failure)
10258
10259 // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
10260 // this in your code.
10261 #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
10262 GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
10263 #v1, \
10264 #v2, \
10265 #v3, \
10266 #v4, \
10267 #v5, \
10268 pred, \
10269 v1, \
10270 v2, \
10271 v3, \
10272 v4, \
10273 v5), on_failure)
10274
10275 // 5-ary predicate assertion macros.
10276 #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10277 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10278 #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
10279 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10280 #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10281 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10282 #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
10283 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10284
10285
10286
10287 } // namespace testing
10288
10289 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
10290
10291 namespace testing {
10292
10293 // The abstract class that all tests inherit from.
10294 //
10295 // In Google Test, a unit test program contains one or many TestSuites, and
10296 // each TestSuite contains one or many Tests.
10297 //
10298 // When you define a test using the TEST macro, you don't need to
10299 // explicitly derive from Test - the TEST macro automatically does
10300 // this for you.
10301 //
10302 // The only time you derive from Test is when defining a test fixture
10303 // to be used in a TEST_F. For example:
10304 //
10305 // class FooTest : public testing::Test {
10306 // protected:
10307 // void SetUp() override { ... }
10308 // void TearDown() override { ... }
10309 // ...
10310 // };
10311 //
10312 // TEST_F(FooTest, Bar) { ... }
10313 // TEST_F(FooTest, Baz) { ... }
10314 //
10315 // Test is not copyable.
10316 class GTEST_API_ Test {
10317 public:
10318 friend class TestInfo;
10319
10320 // The d'tor is virtual as we intend to inherit from Test.
10321 virtual ~Test();
10322
10323 // Sets up the stuff shared by all tests in this test suite.
10324 //
10325 // Google Test will call Foo::SetUpTestSuite() before running the first
10326 // test in test suite Foo. Hence a sub-class can define its own
10327 // SetUpTestSuite() method to shadow the one defined in the super
10328 // class.
10329 static void SetUpTestSuite() {}
10330
10331 // Tears down the stuff shared by all tests in this test suite.
10332 //
10333 // Google Test will call Foo::TearDownTestSuite() after running the last
10334 // test in test suite Foo. Hence a sub-class can define its own
10335 // TearDownTestSuite() method to shadow the one defined in the super
10336 // class.
10337 static void TearDownTestSuite() {}
10338
10339 // Legacy API is deprecated but still available. Use SetUpTestSuite and
10340 // TearDownTestSuite instead.
10341 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10342 static void TearDownTestCase() {}
10343 static void SetUpTestCase() {}
10344 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10345
10346 // Returns true if and only if the current test has a fatal failure.
10347 static bool HasFatalFailure();
10348
10349 // Returns true if and only if the current test has a non-fatal failure.
10350 static bool HasNonfatalFailure();
10351
10352 // Returns true if and only if the current test was skipped.
10353 static bool IsSkipped();
10354
10355 // Returns true if and only if the current test has a (either fatal or
10356 // non-fatal) failure.
10357 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
10358
10359 // Logs a property for the current test, test suite, or for the entire
10360 // invocation of the test program when used outside of the context of a
10361 // test suite. Only the last value for a given key is remembered. These
10362 // are public static so they can be called from utility functions that are
10363 // not members of the test fixture. Calls to RecordProperty made during
10364 // lifespan of the test (from the moment its constructor starts to the
10365 // moment its destructor finishes) will be output in XML as attributes of
10366 // the <testcase> element. Properties recorded from fixture's
10367 // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
10368 // corresponding <testsuite> element. Calls to RecordProperty made in the
10369 // global context (before or after invocation of RUN_ALL_TESTS and from
10370 // SetUp/TearDown method of Environment objects registered with Google
10371 // Test) will be output as attributes of the <testsuites> element.
10372 static void RecordProperty(const std::string& key, const std::string& value);
10373 static void RecordProperty(const std::string& key, int value);
10374
10375 protected:
10376 // Creates a Test object.
10377 Test();
10378
10379 // Sets up the test fixture.
10380 virtual void SetUp();
10381
10382 // Tears down the test fixture.
10383 virtual void TearDown();
10384
10385 private:
10386 // Returns true if and only if the current test has the same fixture class
10387 // as the first test in the current test suite.
10388 static bool HasSameFixtureClass();
10389
10390 // Runs the test after the test fixture has been set up.
10391 //
10392 // A sub-class must implement this to define the test logic.
10393 //
10394 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
10395 // Instead, use the TEST or TEST_F macro.
10396 virtual void TestBody() = 0;
10397
10398 // Sets up, executes, and tears down the test.
10399 void Run();
10400
10401 // Deletes self. We deliberately pick an unusual name for this
10402 // internal method to avoid clashing with names used in user TESTs.
10403 void DeleteSelf_() { delete this; }
10404
10405 const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
10406
10407 // Often a user misspells SetUp() as Setup() and spends a long time
10408 // wondering why it is never called by Google Test. The declaration of
10409 // the following method is solely for catching such an error at
10410 // compile time:
10411 //
10412 // - The return type is deliberately chosen to be not void, so it
10413 // will be a conflict if void Setup() is declared in the user's
10414 // test fixture.
10415 //
10416 // - This method is private, so it will be another compiler error
10417 // if the method is called from the user's test fixture.
10418 //
10419 // DO NOT OVERRIDE THIS FUNCTION.
10420 //
10421 // If you see an error about overriding the following function or
10422 // about it being private, you have mis-spelled SetUp() as Setup().
10423 struct Setup_should_be_spelled_SetUp {};
10424 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10425
10426 // We disallow copying Tests.
10427 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
10428 };
10429
10430 typedef internal::TimeInMillis TimeInMillis;
10431
10432 // A copyable object representing a user specified test property which can be
10433 // output as a key/value string pair.
10434 //
10435 // Don't inherit from TestProperty as its destructor is not virtual.
10436 class TestProperty {
10437 public:
10438 // C'tor. TestProperty does NOT have a default constructor.
10439 // Always use this constructor (with parameters) to create a
10440 // TestProperty object.
10441 TestProperty(const std::string& a_key, const std::string& a_value) :
10442 key_(a_key), value_(a_value) {
10443 }
10444
10445 // Gets the user supplied key.
10446 const char* key() const {
10447 return key_.c_str();
10448 }
10449
10450 // Gets the user supplied value.
10451 const char* value() const {
10452 return value_.c_str();
10453 }
10454
10455 // Sets a new value, overriding the one supplied in the constructor.
10456 void SetValue(const std::string& new_value) {
10457 value_ = new_value;
10458 }
10459
10460 private:
10461 // The key supplied by the user.
10462 std::string key_;
10463 // The value supplied by the user.
10464 std::string value_;
10465 };
10466
10467 // The result of a single Test. This includes a list of
10468 // TestPartResults, a list of TestProperties, a count of how many
10469 // death tests there are in the Test, and how much time it took to run
10470 // the Test.
10471 //
10472 // TestResult is not copyable.
10473 class GTEST_API_ TestResult {
10474 public:
10475 // Creates an empty TestResult.
10476 TestResult();
10477
10478 // D'tor. Do not inherit from TestResult.
10479 ~TestResult();
10480
10481 // Gets the number of all test parts. This is the sum of the number
10482 // of successful test parts and the number of failed test parts.
10483 int total_part_count() const;
10484
10485 // Returns the number of the test properties.
10486 int test_property_count() const;
10487
10488 // Returns true if and only if the test passed (i.e. no test part failed).
10489 bool Passed() const { return !Skipped() && !Failed(); }
10490
10491 // Returns true if and only if the test was skipped.
10492 bool Skipped() const;
10493
10494 // Returns true if and only if the test failed.
10495 bool Failed() const;
10496
10497 // Returns true if and only if the test fatally failed.
10498 bool HasFatalFailure() const;
10499
10500 // Returns true if and only if the test has a non-fatal failure.
10501 bool HasNonfatalFailure() const;
10502
10503 // Returns the elapsed time, in milliseconds.
10504 TimeInMillis elapsed_time() const { return elapsed_time_; }
10505
10506 // Gets the time of the test case start, in ms from the start of the
10507 // UNIX epoch.
10508 TimeInMillis start_timestamp() const { return start_timestamp_; }
10509
10510 // Returns the i-th test part result among all the results. i can range from 0
10511 // to total_part_count() - 1. If i is not in that range, aborts the program.
10512 const TestPartResult& GetTestPartResult(int i) const;
10513
10514 // Returns the i-th test property. i can range from 0 to
10515 // test_property_count() - 1. If i is not in that range, aborts the
10516 // program.
10517 const TestProperty& GetTestProperty(int i) const;
10518
10519 private:
10520 friend class TestInfo;
10521 friend class TestSuite;
10522 friend class UnitTest;
10523 friend class internal::DefaultGlobalTestPartResultReporter;
10524 friend class internal::ExecDeathTest;
10525 friend class internal::TestResultAccessor;
10526 friend class internal::UnitTestImpl;
10527 friend class internal::WindowsDeathTest;
10528 friend class internal::FuchsiaDeathTest;
10529
10530 // Gets the vector of TestPartResults.
10531 const std::vector<TestPartResult>& test_part_results() const {
10532 return test_part_results_;
10533 }
10534
10535 // Gets the vector of TestProperties.
10536 const std::vector<TestProperty>& test_properties() const {
10537 return test_properties_;
10538 }
10539
10540 // Sets the start time.
10541 void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
10542
10543 // Sets the elapsed time.
10544 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
10545
10546 // Adds a test property to the list. The property is validated and may add
10547 // a non-fatal failure if invalid (e.g., if it conflicts with reserved
10548 // key names). If a property is already recorded for the same key, the
10549 // value will be updated, rather than storing multiple values for the same
10550 // key. xml_element specifies the element for which the property is being
10551 // recorded and is used for validation.
10552 void RecordProperty(const std::string& xml_element,
10553 const TestProperty& test_property);
10554
10555 // Adds a failure if the key is a reserved attribute of Google Test
10556 // testsuite tags. Returns true if the property is valid.
10557 // FIXME: Validate attribute names are legal and human readable.
10558 static bool ValidateTestProperty(const std::string& xml_element,
10559 const TestProperty& test_property);
10560
10561 // Adds a test part result to the list.
10562 void AddTestPartResult(const TestPartResult& test_part_result);
10563
10564 // Returns the death test count.
10565 int death_test_count() const { return death_test_count_; }
10566
10567 // Increments the death test count, returning the new count.
10568 int increment_death_test_count() { return ++death_test_count_; }
10569
10570 // Clears the test part results.
10571 void ClearTestPartResults();
10572
10573 // Clears the object.
10574 void Clear();
10575
10576 // Protects mutable state of the property vector and of owned
10577 // properties, whose values may be updated.
10578 internal::Mutex test_properties_mutex_;
10579
10580 // The vector of TestPartResults
10581 std::vector<TestPartResult> test_part_results_;
10582 // The vector of TestProperties
10583 std::vector<TestProperty> test_properties_;
10584 // Running count of death tests.
10585 int death_test_count_;
10586 // The start time, in milliseconds since UNIX Epoch.
10587 TimeInMillis start_timestamp_;
10588 // The elapsed time, in milliseconds.
10589 TimeInMillis elapsed_time_;
10590
10591 // We disallow copying TestResult.
10592 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
10593 }; // class TestResult
10594
10595 // A TestInfo object stores the following information about a test:
10596 //
10597 // Test suite name
10598 // Test name
10599 // Whether the test should be run
10600 // A function pointer that creates the test object when invoked
10601 // Test result
10602 //
10603 // The constructor of TestInfo registers itself with the UnitTest
10604 // singleton such that the RUN_ALL_TESTS() macro knows which tests to
10605 // run.
10606 class GTEST_API_ TestInfo {
10607 public:
10608 // Destructs a TestInfo object. This function is not virtual, so
10609 // don't inherit from TestInfo.
10610 ~TestInfo();
10611
10612 // Returns the test suite name.
10613 const char* test_suite_name() const { return test_suite_name_.c_str(); }
10614
10615 // Legacy API is deprecated but still available
10616 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10617 const char* test_case_name() const { return test_suite_name(); }
10618 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10619
10620 // Returns the test name.
10621 const char* name() const { return name_.c_str(); }
10622
10623 // Returns the name of the parameter type, or NULL if this is not a typed
10624 // or a type-parameterized test.
10625 const char* type_param() const {
10626 if (type_param_.get() != nullptr) return type_param_->c_str();
10627 return nullptr;
10628 }
10629
10630 // Returns the text representation of the value parameter, or NULL if this
10631 // is not a value-parameterized test.
10632 const char* value_param() const {
10633 if (value_param_.get() != nullptr) return value_param_->c_str();
10634 return nullptr;
10635 }
10636
10637 // Returns the file name where this test is defined.
10638 const char* file() const { return location_.file.c_str(); }
10639
10640 // Returns the line where this test is defined.
10641 int line() const { return location_.line; }
10642
10643 // Return true if this test should not be run because it's in another shard.
10644 bool is_in_another_shard() const { return is_in_another_shard_; }
10645
10646 // Returns true if this test should run, that is if the test is not
10647 // disabled (or it is disabled but the also_run_disabled_tests flag has
10648 // been specified) and its full name matches the user-specified filter.
10649 //
10650 // Google Test allows the user to filter the tests by their full names.
10651 // The full name of a test Bar in test suite Foo is defined as
10652 // "Foo.Bar". Only the tests that match the filter will run.
10653 //
10654 // A filter is a colon-separated list of glob (not regex) patterns,
10655 // optionally followed by a '-' and a colon-separated list of
10656 // negative patterns (tests to exclude). A test is run if it
10657 // matches one of the positive patterns and does not match any of
10658 // the negative patterns.
10659 //
10660 // For example, *A*:Foo.* is a filter that matches any string that
10661 // contains the character 'A' or starts with "Foo.".
10662 bool should_run() const { return should_run_; }
10663
10664 // Returns true if and only if this test will appear in the XML report.
10665 bool is_reportable() const {
10666 // The XML report includes tests matching the filter, excluding those
10667 // run in other shards.
10668 return matches_filter_ && !is_in_another_shard_;
10669 }
10670
10671 // Returns the result of the test.
10672 const TestResult* result() const { return &result_; }
10673
10674 private:
10675 #if GTEST_HAS_DEATH_TEST
10676 friend class internal::DefaultDeathTestFactory;
10677 #endif // GTEST_HAS_DEATH_TEST
10678 friend class Test;
10679 friend class TestSuite;
10680 friend class internal::UnitTestImpl;
10681 friend class internal::StreamingListenerTest;
10682 friend TestInfo* internal::MakeAndRegisterTestInfo(
10683 const char* test_suite_name, const char* name, const char* type_param,
10684 const char* value_param, internal::CodeLocation code_location,
10685 internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
10686 internal::TearDownTestSuiteFunc tear_down_tc,
10687 internal::TestFactoryBase* factory);
10688
10689 // Constructs a TestInfo object. The newly constructed instance assumes
10690 // ownership of the factory object.
10691 TestInfo(const std::string& test_suite_name, const std::string& name,
10692 const char* a_type_param, // NULL if not a type-parameterized test
10693 const char* a_value_param, // NULL if not a value-parameterized test
10694 internal::CodeLocation a_code_location,
10695 internal::TypeId fixture_class_id,
10696 internal::TestFactoryBase* factory);
10697
10698 // Increments the number of death tests encountered in this test so
10699 // far.
10700 int increment_death_test_count() {
10701 return result_.increment_death_test_count();
10702 }
10703
10704 // Creates the test object, runs it, records its result, and then
10705 // deletes it.
10706 void Run();
10707
10708 // Skip and records the test result for this object.
10709 void Skip();
10710
10711 static void ClearTestResult(TestInfo* test_info) {
10712 test_info->result_.Clear();
10713 }
10714
10715 // These fields are immutable properties of the test.
10716 const std::string test_suite_name_; // test suite name
10717 const std::string name_; // Test name
10718 // Name of the parameter type, or NULL if this is not a typed or a
10719 // type-parameterized test.
10720 const std::unique_ptr<const ::std::string> type_param_;
10721 // Text representation of the value parameter, or NULL if this is not a
10722 // value-parameterized test.
10723 const std::unique_ptr<const ::std::string> value_param_;
10724 internal::CodeLocation location_;
10725 const internal::TypeId fixture_class_id_; // ID of the test fixture class
10726 bool should_run_; // True if and only if this test should run
10727 bool is_disabled_; // True if and only if this test is disabled
10728 bool matches_filter_; // True if this test matches the
10729 // user-specified filter.
10730 bool is_in_another_shard_; // Will be run in another shard.
10731 internal::TestFactoryBase* const factory_; // The factory that creates
10732 // the test object
10733
10734 // This field is mutable and needs to be reset before running the
10735 // test for the second time.
10736 TestResult result_;
10737
10738 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
10739 };
10740
10741 // A test suite, which consists of a vector of TestInfos.
10742 //
10743 // TestSuite is not copyable.
10744 class GTEST_API_ TestSuite {
10745 public:
10746 // Creates a TestSuite with the given name.
10747 //
10748 // TestSuite does NOT have a default constructor. Always use this
10749 // constructor to create a TestSuite object.
10750 //
10751 // Arguments:
10752 //
10753 // name: name of the test suite
10754 // a_type_param: the name of the test's type parameter, or NULL if
10755 // this is not a type-parameterized test.
10756 // set_up_tc: pointer to the function that sets up the test suite
10757 // tear_down_tc: pointer to the function that tears down the test suite
10758 TestSuite(const char* name, const char* a_type_param,
10759 internal::SetUpTestSuiteFunc set_up_tc,
10760 internal::TearDownTestSuiteFunc tear_down_tc);
10761
10762 // Destructor of TestSuite.
10763 virtual ~TestSuite();
10764
10765 // Gets the name of the TestSuite.
10766 const char* name() const { return name_.c_str(); }
10767
10768 // Returns the name of the parameter type, or NULL if this is not a
10769 // type-parameterized test suite.
10770 const char* type_param() const {
10771 if (type_param_.get() != nullptr) return type_param_->c_str();
10772 return nullptr;
10773 }
10774
10775 // Returns true if any test in this test suite should run.
10776 bool should_run() const { return should_run_; }
10777
10778 // Gets the number of successful tests in this test suite.
10779 int successful_test_count() const;
10780
10781 // Gets the number of skipped tests in this test suite.
10782 int skipped_test_count() const;
10783
10784 // Gets the number of failed tests in this test suite.
10785 int failed_test_count() const;
10786
10787 // Gets the number of disabled tests that will be reported in the XML report.
10788 int reportable_disabled_test_count() const;
10789
10790 // Gets the number of disabled tests in this test suite.
10791 int disabled_test_count() const;
10792
10793 // Gets the number of tests to be printed in the XML report.
10794 int reportable_test_count() const;
10795
10796 // Get the number of tests in this test suite that should run.
10797 int test_to_run_count() const;
10798
10799 // Gets the number of all tests in this test suite.
10800 int total_test_count() const;
10801
10802 // Returns true if and only if the test suite passed.
10803 bool Passed() const { return !Failed(); }
10804
10805 // Returns true if and only if the test suite failed.
10806 bool Failed() const {
10807 return failed_test_count() > 0 || ad_hoc_test_result().Failed();
10808 }
10809
10810 // Returns the elapsed time, in milliseconds.
10811 TimeInMillis elapsed_time() const { return elapsed_time_; }
10812
10813 // Gets the time of the test suite start, in ms from the start of the
10814 // UNIX epoch.
10815 TimeInMillis start_timestamp() const { return start_timestamp_; }
10816
10817 // Returns the i-th test among all the tests. i can range from 0 to
10818 // total_test_count() - 1. If i is not in that range, returns NULL.
10819 const TestInfo* GetTestInfo(int i) const;
10820
10821 // Returns the TestResult that holds test properties recorded during
10822 // execution of SetUpTestSuite and TearDownTestSuite.
10823 const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
10824
10825 private:
10826 friend class Test;
10827 friend class internal::UnitTestImpl;
10828
10829 // Gets the (mutable) vector of TestInfos in this TestSuite.
10830 std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
10831
10832 // Gets the (immutable) vector of TestInfos in this TestSuite.
10833 const std::vector<TestInfo*>& test_info_list() const {
10834 return test_info_list_;
10835 }
10836
10837 // Returns the i-th test among all the tests. i can range from 0 to
10838 // total_test_count() - 1. If i is not in that range, returns NULL.
10839 TestInfo* GetMutableTestInfo(int i);
10840
10841 // Sets the should_run member.
10842 void set_should_run(bool should) { should_run_ = should; }
10843
10844 // Adds a TestInfo to this test suite. Will delete the TestInfo upon
10845 // destruction of the TestSuite object.
10846 void AddTestInfo(TestInfo * test_info);
10847
10848 // Clears the results of all tests in this test suite.
10849 void ClearResult();
10850
10851 // Clears the results of all tests in the given test suite.
10852 static void ClearTestSuiteResult(TestSuite* test_suite) {
10853 test_suite->ClearResult();
10854 }
10855
10856 // Runs every test in this TestSuite.
10857 void Run();
10858
10859 // Skips the execution of tests under this TestSuite
10860 void Skip();
10861
10862 // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
10863 // for catching exceptions thrown from SetUpTestSuite().
10864 void RunSetUpTestSuite() {
10865 if (set_up_tc_ != nullptr) {
10866 (*set_up_tc_)();
10867 }
10868 }
10869
10870 // Runs TearDownTestSuite() for this TestSuite. This wrapper is
10871 // needed for catching exceptions thrown from TearDownTestSuite().
10872 void RunTearDownTestSuite() {
10873 if (tear_down_tc_ != nullptr) {
10874 (*tear_down_tc_)();
10875 }
10876 }
10877
10878 // Returns true if and only if test passed.
10879 static bool TestPassed(const TestInfo* test_info) {
10880 return test_info->should_run() && test_info->result()->Passed();
10881 }
10882
10883 // Returns true if and only if test skipped.
10884 static bool TestSkipped(const TestInfo* test_info) {
10885 return test_info->should_run() && test_info->result()->Skipped();
10886 }
10887
10888 // Returns true if and only if test failed.
10889 static bool TestFailed(const TestInfo* test_info) {
10890 return test_info->should_run() && test_info->result()->Failed();
10891 }
10892
10893 // Returns true if and only if the test is disabled and will be reported in
10894 // the XML report.
10895 static bool TestReportableDisabled(const TestInfo* test_info) {
10896 return test_info->is_reportable() && test_info->is_disabled_;
10897 }
10898
10899 // Returns true if and only if test is disabled.
10900 static bool TestDisabled(const TestInfo* test_info) {
10901 return test_info->is_disabled_;
10902 }
10903
10904 // Returns true if and only if this test will appear in the XML report.
10905 static bool TestReportable(const TestInfo* test_info) {
10906 return test_info->is_reportable();
10907 }
10908
10909 // Returns true if the given test should run.
10910 static bool ShouldRunTest(const TestInfo* test_info) {
10911 return test_info->should_run();
10912 }
10913
10914 // Shuffles the tests in this test suite.
10915 void ShuffleTests(internal::Random* random);
10916
10917 // Restores the test order to before the first shuffle.
10918 void UnshuffleTests();
10919
10920 // Name of the test suite.
10921 std::string name_;
10922 // Name of the parameter type, or NULL if this is not a typed or a
10923 // type-parameterized test.
10924 const std::unique_ptr<const ::std::string> type_param_;
10925 // The vector of TestInfos in their original order. It owns the
10926 // elements in the vector.
10927 std::vector<TestInfo*> test_info_list_;
10928 // Provides a level of indirection for the test list to allow easy
10929 // shuffling and restoring the test order. The i-th element in this
10930 // vector is the index of the i-th test in the shuffled test list.
10931 std::vector<int> test_indices_;
10932 // Pointer to the function that sets up the test suite.
10933 internal::SetUpTestSuiteFunc set_up_tc_;
10934 // Pointer to the function that tears down the test suite.
10935 internal::TearDownTestSuiteFunc tear_down_tc_;
10936 // True if and only if any test in this test suite should run.
10937 bool should_run_;
10938 // The start time, in milliseconds since UNIX Epoch.
10939 TimeInMillis start_timestamp_;
10940 // Elapsed time, in milliseconds.
10941 TimeInMillis elapsed_time_;
10942 // Holds test properties recorded during execution of SetUpTestSuite and
10943 // TearDownTestSuite.
10944 TestResult ad_hoc_test_result_;
10945
10946 // We disallow copying TestSuites.
10947 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
10948 };
10949
10950 // An Environment object is capable of setting up and tearing down an
10951 // environment. You should subclass this to define your own
10952 // environment(s).
10953 //
10954 // An Environment object does the set-up and tear-down in virtual
10955 // methods SetUp() and TearDown() instead of the constructor and the
10956 // destructor, as:
10957 //
10958 // 1. You cannot safely throw from a destructor. This is a problem
10959 // as in some cases Google Test is used where exceptions are enabled, and
10960 // we may want to implement ASSERT_* using exceptions where they are
10961 // available.
10962 // 2. You cannot use ASSERT_* directly in a constructor or
10963 // destructor.
10964 class Environment {
10965 public:
10966 // The d'tor is virtual as we need to subclass Environment.
10967 virtual ~Environment() {}
10968
10969 // Override this to define how to set up the environment.
10970 virtual void SetUp() {}
10971
10972 // Override this to define how to tear down the environment.
10973 virtual void TearDown() {}
10974 private:
10975 // If you see an error about overriding the following function or
10976 // about it being private, you have mis-spelled SetUp() as Setup().
10977 struct Setup_should_be_spelled_SetUp {};
10978 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10979 };
10980
10981 #if GTEST_HAS_EXCEPTIONS
10982
10983 // Exception which can be thrown from TestEventListener::OnTestPartResult.
10984 class GTEST_API_ AssertionException
10985 : public internal::GoogleTestFailureException {
10986 public:
10987 explicit AssertionException(const TestPartResult& result)
10988 : GoogleTestFailureException(result) {}
10989 };
10990
10991 #endif // GTEST_HAS_EXCEPTIONS
10992
10993 // The interface for tracing execution of tests. The methods are organized in
10994 // the order the corresponding events are fired.
10995 class TestEventListener {
10996 public:
10997 virtual ~TestEventListener() {}
10998
10999 // Fired before any test activity starts.
11000 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
11001
11002 // Fired before each iteration of tests starts. There may be more than
11003 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
11004 // index, starting from 0.
11005 virtual void OnTestIterationStart(const UnitTest& unit_test,
11006 int iteration) = 0;
11007
11008 // Fired before environment set-up for each iteration of tests starts.
11009 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
11010
11011 // Fired after environment set-up for each iteration of tests ends.
11012 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
11013
11014 // Fired before the test suite starts.
11015 virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
11016
11017 // Legacy API is deprecated but still available
11018 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11019 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
11020 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11021
11022 // Fired before the test starts.
11023 virtual void OnTestStart(const TestInfo& test_info) = 0;
11024
11025 // Fired after a failed assertion or a SUCCEED() invocation.
11026 // If you want to throw an exception from this function to skip to the next
11027 // TEST, it must be AssertionException defined above, or inherited from it.
11028 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
11029
11030 // Fired after the test ends.
11031 virtual void OnTestEnd(const TestInfo& test_info) = 0;
11032
11033 // Fired after the test suite ends.
11034 virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
11035
11036 // Legacy API is deprecated but still available
11037 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11038 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
11039 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11040
11041 // Fired before environment tear-down for each iteration of tests starts.
11042 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
11043
11044 // Fired after environment tear-down for each iteration of tests ends.
11045 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
11046
11047 // Fired after each iteration of tests finishes.
11048 virtual void OnTestIterationEnd(const UnitTest& unit_test,
11049 int iteration) = 0;
11050
11051 // Fired after all test activities have ended.
11052 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
11053 };
11054
11055 // The convenience class for users who need to override just one or two
11056 // methods and are not concerned that a possible change to a signature of
11057 // the methods they override will not be caught during the build. For
11058 // comments about each method please see the definition of TestEventListener
11059 // above.
11060 class EmptyTestEventListener : public TestEventListener {
11061 public:
11062 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
11063 void OnTestIterationStart(const UnitTest& /*unit_test*/,
11064 int /*iteration*/) override {}
11065 void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
11066 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
11067 void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
11068 // Legacy API is deprecated but still available
11069 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11070 void OnTestCaseStart(const TestCase& /*test_case*/) override {}
11071 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11072
11073 void OnTestStart(const TestInfo& /*test_info*/) override {}
11074 void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
11075 void OnTestEnd(const TestInfo& /*test_info*/) override {}
11076 void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
11077 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11078 void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
11079 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11080
11081 void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
11082 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
11083 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
11084 int /*iteration*/) override {}
11085 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
11086 };
11087
11088 // TestEventListeners lets users add listeners to track events in Google Test.
11089 class GTEST_API_ TestEventListeners {
11090 public:
11091 TestEventListeners();
11092 ~TestEventListeners();
11093
11094 // Appends an event listener to the end of the list. Google Test assumes
11095 // the ownership of the listener (i.e. it will delete the listener when
11096 // the test program finishes).
11097 void Append(TestEventListener* listener);
11098
11099 // Removes the given event listener from the list and returns it. It then
11100 // becomes the caller's responsibility to delete the listener. Returns
11101 // NULL if the listener is not found in the list.
11102 TestEventListener* Release(TestEventListener* listener);
11103
11104 // Returns the standard listener responsible for the default console
11105 // output. Can be removed from the listeners list to shut down default
11106 // console output. Note that removing this object from the listener list
11107 // with Release transfers its ownership to the caller and makes this
11108 // function return NULL the next time.
11109 TestEventListener* default_result_printer() const {
11110 return default_result_printer_;
11111 }
11112
11113 // Returns the standard listener responsible for the default XML output
11114 // controlled by the --gtest_output=xml flag. Can be removed from the
11115 // listeners list by users who want to shut down the default XML output
11116 // controlled by this flag and substitute it with custom one. Note that
11117 // removing this object from the listener list with Release transfers its
11118 // ownership to the caller and makes this function return NULL the next
11119 // time.
11120 TestEventListener* default_xml_generator() const {
11121 return default_xml_generator_;
11122 }
11123
11124 private:
11125 friend class TestSuite;
11126 friend class TestInfo;
11127 friend class internal::DefaultGlobalTestPartResultReporter;
11128 friend class internal::NoExecDeathTest;
11129 friend class internal::TestEventListenersAccessor;
11130 friend class internal::UnitTestImpl;
11131
11132 // Returns repeater that broadcasts the TestEventListener events to all
11133 // subscribers.
11134 TestEventListener* repeater();
11135
11136 // Sets the default_result_printer attribute to the provided listener.
11137 // The listener is also added to the listener list and previous
11138 // default_result_printer is removed from it and deleted. The listener can
11139 // also be NULL in which case it will not be added to the list. Does
11140 // nothing if the previous and the current listener objects are the same.
11141 void SetDefaultResultPrinter(TestEventListener* listener);
11142
11143 // Sets the default_xml_generator attribute to the provided listener. The
11144 // listener is also added to the listener list and previous
11145 // default_xml_generator is removed from it and deleted. The listener can
11146 // also be NULL in which case it will not be added to the list. Does
11147 // nothing if the previous and the current listener objects are the same.
11148 void SetDefaultXmlGenerator(TestEventListener* listener);
11149
11150 // Controls whether events will be forwarded by the repeater to the
11151 // listeners in the list.
11152 bool EventForwardingEnabled() const;
11153 void SuppressEventForwarding();
11154
11155 // The actual list of listeners.
11156 internal::TestEventRepeater* repeater_;
11157 // Listener responsible for the standard result output.
11158 TestEventListener* default_result_printer_;
11159 // Listener responsible for the creation of the XML output file.
11160 TestEventListener* default_xml_generator_;
11161
11162 // We disallow copying TestEventListeners.
11163 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
11164 };
11165
11166 // A UnitTest consists of a vector of TestSuites.
11167 //
11168 // This is a singleton class. The only instance of UnitTest is
11169 // created when UnitTest::GetInstance() is first called. This
11170 // instance is never deleted.
11171 //
11172 // UnitTest is not copyable.
11173 //
11174 // This class is thread-safe as long as the methods are called
11175 // according to their specification.
11176 class GTEST_API_ UnitTest {
11177 public:
11178 // Gets the singleton UnitTest object. The first time this method
11179 // is called, a UnitTest object is constructed and returned.
11180 // Consecutive calls will return the same object.
11181 static UnitTest* GetInstance();
11182
11183 // Runs all tests in this UnitTest object and prints the result.
11184 // Returns 0 if successful, or 1 otherwise.
11185 //
11186 // This method can only be called from the main thread.
11187 //
11188 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11189 int Run() GTEST_MUST_USE_RESULT_;
11190
11191 // Returns the working directory when the first TEST() or TEST_F()
11192 // was executed. The UnitTest object owns the string.
11193 const char* original_working_dir() const;
11194
11195 // Returns the TestSuite object for the test that's currently running,
11196 // or NULL if no test is running.
11197 const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
11198
11199 // Legacy API is still available but deprecated
11200 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11201 const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
11202 #endif
11203
11204 // Returns the TestInfo object for the test that's currently running,
11205 // or NULL if no test is running.
11206 const TestInfo* current_test_info() const
11207 GTEST_LOCK_EXCLUDED_(mutex_);
11208
11209 // Returns the random seed used at the start of the current test run.
11210 int random_seed() const;
11211
11212 // Returns the ParameterizedTestSuiteRegistry object used to keep track of
11213 // value-parameterized tests and instantiate and register them.
11214 //
11215 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11216 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
11217 GTEST_LOCK_EXCLUDED_(mutex_);
11218
11219 // Gets the number of successful test suites.
11220 int successful_test_suite_count() const;
11221
11222 // Gets the number of failed test suites.
11223 int failed_test_suite_count() const;
11224
11225 // Gets the number of all test suites.
11226 int total_test_suite_count() const;
11227
11228 // Gets the number of all test suites that contain at least one test
11229 // that should run.
11230 int test_suite_to_run_count() const;
11231
11232 // Legacy API is deprecated but still available
11233 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11234 int successful_test_case_count() const;
11235 int failed_test_case_count() const;
11236 int total_test_case_count() const;
11237 int test_case_to_run_count() const;
11238 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11239
11240 // Gets the number of successful tests.
11241 int successful_test_count() const;
11242
11243 // Gets the number of skipped tests.
11244 int skipped_test_count() const;
11245
11246 // Gets the number of failed tests.
11247 int failed_test_count() const;
11248
11249 // Gets the number of disabled tests that will be reported in the XML report.
11250 int reportable_disabled_test_count() const;
11251
11252 // Gets the number of disabled tests.
11253 int disabled_test_count() const;
11254
11255 // Gets the number of tests to be printed in the XML report.
11256 int reportable_test_count() const;
11257
11258 // Gets the number of all tests.
11259 int total_test_count() const;
11260
11261 // Gets the number of tests that should run.
11262 int test_to_run_count() const;
11263
11264 // Gets the time of the test program start, in ms from the start of the
11265 // UNIX epoch.
11266 TimeInMillis start_timestamp() const;
11267
11268 // Gets the elapsed time, in milliseconds.
11269 TimeInMillis elapsed_time() const;
11270
11271 // Returns true if and only if the unit test passed (i.e. all test suites
11272 // passed).
11273 bool Passed() const;
11274
11275 // Returns true if and only if the unit test failed (i.e. some test suite
11276 // failed or something outside of all tests failed).
11277 bool Failed() const;
11278
11279 // Gets the i-th test suite among all the test suites. i can range from 0 to
11280 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11281 const TestSuite* GetTestSuite(int i) const;
11282
11283 // Legacy API is deprecated but still available
11284 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11285 const TestCase* GetTestCase(int i) const;
11286 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11287
11288 // Returns the TestResult containing information on test failures and
11289 // properties logged outside of individual test suites.
11290 const TestResult& ad_hoc_test_result() const;
11291
11292 // Returns the list of event listeners that can be used to track events
11293 // inside Google Test.
11294 TestEventListeners& listeners();
11295
11296 private:
11297 // Registers and returns a global test environment. When a test
11298 // program is run, all global test environments will be set-up in
11299 // the order they were registered. After all tests in the program
11300 // have finished, all global test environments will be torn-down in
11301 // the *reverse* order they were registered.
11302 //
11303 // The UnitTest object takes ownership of the given environment.
11304 //
11305 // This method can only be called from the main thread.
11306 Environment* AddEnvironment(Environment* env);
11307
11308 // Adds a TestPartResult to the current TestResult object. All
11309 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
11310 // eventually call this to report their results. The user code
11311 // should use the assertion macros instead of calling this directly.
11312 void AddTestPartResult(TestPartResult::Type result_type,
11313 const char* file_name,
11314 int line_number,
11315 const std::string& message,
11316 const std::string& os_stack_trace)
11317 GTEST_LOCK_EXCLUDED_(mutex_);
11318
11319 // Adds a TestProperty to the current TestResult object when invoked from
11320 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
11321 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
11322 // when invoked elsewhere. If the result already contains a property with
11323 // the same key, the value will be updated.
11324 void RecordProperty(const std::string& key, const std::string& value);
11325
11326 // Gets the i-th test suite among all the test suites. i can range from 0 to
11327 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11328 TestSuite* GetMutableTestSuite(int i);
11329
11330 // Accessors for the implementation object.
11331 internal::UnitTestImpl* impl() { return impl_; }
11332 const internal::UnitTestImpl* impl() const { return impl_; }
11333
11334 // These classes and functions are friends as they need to access private
11335 // members of UnitTest.
11336 friend class ScopedTrace;
11337 friend class Test;
11338 friend class internal::AssertHelper;
11339 friend class internal::StreamingListenerTest;
11340 friend class internal::UnitTestRecordPropertyTestHelper;
11341 friend Environment* AddGlobalTestEnvironment(Environment* env);
11342 friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
11343 friend internal::UnitTestImpl* internal::GetUnitTestImpl();
11344 friend void internal::ReportFailureInUnknownLocation(
11345 TestPartResult::Type result_type,
11346 const std::string& message);
11347
11348 // Creates an empty UnitTest.
11349 UnitTest();
11350
11351 // D'tor
11352 virtual ~UnitTest();
11353
11354 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
11355 // Google Test trace stack.
11356 void PushGTestTrace(const internal::TraceInfo& trace)
11357 GTEST_LOCK_EXCLUDED_(mutex_);
11358
11359 // Pops a trace from the per-thread Google Test trace stack.
11360 void PopGTestTrace()
11361 GTEST_LOCK_EXCLUDED_(mutex_);
11362
11363 // Protects mutable state in *impl_. This is mutable as some const
11364 // methods need to lock it too.
11365 mutable internal::Mutex mutex_;
11366
11367 // Opaque implementation object. This field is never changed once
11368 // the object is constructed. We don't mark it as const here, as
11369 // doing so will cause a warning in the constructor of UnitTest.
11370 // Mutable state in *impl_ is protected by mutex_.
11371 internal::UnitTestImpl* impl_;
11372
11373 // We disallow copying UnitTest.
11374 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
11375 };
11376
11377 // A convenient wrapper for adding an environment for the test
11378 // program.
11379 //
11380 // You should call this before RUN_ALL_TESTS() is called, probably in
11381 // main(). If you use gtest_main, you need to call this before main()
11382 // starts for it to take effect. For example, you can define a global
11383 // variable like this:
11384 //
11385 // testing::Environment* const foo_env =
11386 // testing::AddGlobalTestEnvironment(new FooEnvironment);
11387 //
11388 // However, we strongly recommend you to write your own main() and
11389 // call AddGlobalTestEnvironment() there, as relying on initialization
11390 // of global variables makes the code harder to read and may cause
11391 // problems when you register multiple environments from different
11392 // translation units and the environments have dependencies among them
11393 // (remember that the compiler doesn't guarantee the order in which
11394 // global variables from different translation units are initialized).
11395 inline Environment* AddGlobalTestEnvironment(Environment* env) {
11396 return UnitTest::GetInstance()->AddEnvironment(env);
11397 }
11398
11399 // Initializes Google Test. This must be called before calling
11400 // RUN_ALL_TESTS(). In particular, it parses a command line for the
11401 // flags that Google Test recognizes. Whenever a Google Test flag is
11402 // seen, it is removed from argv, and *argc is decremented.
11403 //
11404 // No value is returned. Instead, the Google Test flag variables are
11405 // updated.
11406 //
11407 // Calling the function for the second time has no user-visible effect.
11408 GTEST_API_ void InitGoogleTest(int* argc, char** argv);
11409
11410 // This overloaded version can be used in Windows programs compiled in
11411 // UNICODE mode.
11412 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
11413
11414 // This overloaded version can be used on Arduino/embedded platforms where
11415 // there is no argc/argv.
11416 GTEST_API_ void InitGoogleTest();
11417
11418 namespace internal {
11419
11420 // Separate the error generating code from the code path to reduce the stack
11421 // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
11422 // when calling EXPECT_* in a tight loop.
11423 template <typename T1, typename T2>
11424 AssertionResult CmpHelperEQFailure(const char* lhs_expression,
11425 const char* rhs_expression,
11426 const T1& lhs, const T2& rhs) {
11427 return EqFailure(lhs_expression,
11428 rhs_expression,
11429 FormatForComparisonFailureMessage(lhs, rhs),
11430 FormatForComparisonFailureMessage(rhs, lhs),
11431 false);
11432 }
11433
11434 // This block of code defines operator==/!=
11435 // to block lexical scope lookup.
11436 // It prevents using invalid operator==/!= defined at namespace scope.
11437 struct faketype {};
11438 inline bool operator==(faketype, faketype) { return true; }
11439 inline bool operator!=(faketype, faketype) { return false; }
11440
11441 // The helper function for {ASSERT|EXPECT}_EQ.
11442 template <typename T1, typename T2>
11443 AssertionResult CmpHelperEQ(const char* lhs_expression,
11444 const char* rhs_expression,
11445 const T1& lhs,
11446 const T2& rhs) {
11447 if (lhs == rhs) {
11448 return AssertionSuccess();
11449 }
11450
11451 return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
11452 }
11453
11454 class EqHelper {
11455 public:
11456 // This templatized version is for the general case.
11457 template <
11458 typename T1, typename T2,
11459 // Disable this overload for cases where one argument is a pointer
11460 // and the other is the null pointer constant.
11461 typename std::enable_if<!std::is_integral<T1>::value ||
11462 !std::is_pointer<T2>::value>::type* = nullptr>
11463 static AssertionResult Compare(const char* lhs_expression,
11464 const char* rhs_expression, const T1& lhs,
11465 const T2& rhs) {
11466 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11467 }
11468
11469 // With this overloaded version, we allow anonymous enums to be used
11470 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
11471 // enums can be implicitly cast to BiggestInt.
11472 //
11473 // Even though its body looks the same as the above version, we
11474 // cannot merge the two, as it will make anonymous enums unhappy.
11475 static AssertionResult Compare(const char* lhs_expression,
11476 const char* rhs_expression,
11477 BiggestInt lhs,
11478 BiggestInt rhs) {
11479 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11480 }
11481
11482 template <typename T>
11483 static AssertionResult Compare(
11484 const char* lhs_expression, const char* rhs_expression,
11485 // Handle cases where '0' is used as a null pointer literal.
11486 std::nullptr_t /* lhs */, T* rhs) {
11487 // We already know that 'lhs' is a null pointer.
11488 return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
11489 rhs);
11490 }
11491 };
11492
11493 // Separate the error generating code from the code path to reduce the stack
11494 // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
11495 // when calling EXPECT_OP in a tight loop.
11496 template <typename T1, typename T2>
11497 AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
11498 const T1& val1, const T2& val2,
11499 const char* op) {
11500 return AssertionFailure()
11501 << "Expected: (" << expr1 << ") " << op << " (" << expr2
11502 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
11503 << " vs " << FormatForComparisonFailureMessage(val2, val1);
11504 }
11505
11506 // A macro for implementing the helper functions needed to implement
11507 // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
11508 // of similar code.
11509 //
11510 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11511
11512 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
11513 template <typename T1, typename T2>\
11514 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
11515 const T1& val1, const T2& val2) {\
11516 if (val1 op val2) {\
11517 return AssertionSuccess();\
11518 } else {\
11519 return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
11520 }\
11521 }
11522
11523 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11524
11525 // Implements the helper function for {ASSERT|EXPECT}_NE
11526 GTEST_IMPL_CMP_HELPER_(NE, !=)
11527 // Implements the helper function for {ASSERT|EXPECT}_LE
11528 GTEST_IMPL_CMP_HELPER_(LE, <=)
11529 // Implements the helper function for {ASSERT|EXPECT}_LT
11530 GTEST_IMPL_CMP_HELPER_(LT, <)
11531 // Implements the helper function for {ASSERT|EXPECT}_GE
11532 GTEST_IMPL_CMP_HELPER_(GE, >=)
11533 // Implements the helper function for {ASSERT|EXPECT}_GT
11534 GTEST_IMPL_CMP_HELPER_(GT, >)
11535
11536 #undef GTEST_IMPL_CMP_HELPER_
11537
11538 // The helper function for {ASSERT|EXPECT}_STREQ.
11539 //
11540 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11541 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11542 const char* s2_expression,
11543 const char* s1,
11544 const char* s2);
11545
11546 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
11547 //
11548 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11549 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
11550 const char* s2_expression,
11551 const char* s1,
11552 const char* s2);
11553
11554 // The helper function for {ASSERT|EXPECT}_STRNE.
11555 //
11556 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11557 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11558 const char* s2_expression,
11559 const char* s1,
11560 const char* s2);
11561
11562 // The helper function for {ASSERT|EXPECT}_STRCASENE.
11563 //
11564 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11565 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
11566 const char* s2_expression,
11567 const char* s1,
11568 const char* s2);
11569
11570
11571 // Helper function for *_STREQ on wide strings.
11572 //
11573 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11574 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11575 const char* s2_expression,
11576 const wchar_t* s1,
11577 const wchar_t* s2);
11578
11579 // Helper function for *_STRNE on wide strings.
11580 //
11581 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11582 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11583 const char* s2_expression,
11584 const wchar_t* s1,
11585 const wchar_t* s2);
11586
11587 } // namespace internal
11588
11589 // IsSubstring() and IsNotSubstring() are intended to be used as the
11590 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
11591 // themselves. They check whether needle is a substring of haystack
11592 // (NULL is considered a substring of itself only), and return an
11593 // appropriate error message when they fail.
11594 //
11595 // The {needle,haystack}_expr arguments are the stringified
11596 // expressions that generated the two real arguments.
11597 GTEST_API_ AssertionResult IsSubstring(
11598 const char* needle_expr, const char* haystack_expr,
11599 const char* needle, const char* haystack);
11600 GTEST_API_ AssertionResult IsSubstring(
11601 const char* needle_expr, const char* haystack_expr,
11602 const wchar_t* needle, const wchar_t* haystack);
11603 GTEST_API_ AssertionResult IsNotSubstring(
11604 const char* needle_expr, const char* haystack_expr,
11605 const char* needle, const char* haystack);
11606 GTEST_API_ AssertionResult IsNotSubstring(
11607 const char* needle_expr, const char* haystack_expr,
11608 const wchar_t* needle, const wchar_t* haystack);
11609 GTEST_API_ AssertionResult IsSubstring(
11610 const char* needle_expr, const char* haystack_expr,
11611 const ::std::string& needle, const ::std::string& haystack);
11612 GTEST_API_ AssertionResult IsNotSubstring(
11613 const char* needle_expr, const char* haystack_expr,
11614 const ::std::string& needle, const ::std::string& haystack);
11615
11616 #if GTEST_HAS_STD_WSTRING
11617 GTEST_API_ AssertionResult IsSubstring(
11618 const char* needle_expr, const char* haystack_expr,
11619 const ::std::wstring& needle, const ::std::wstring& haystack);
11620 GTEST_API_ AssertionResult IsNotSubstring(
11621 const char* needle_expr, const char* haystack_expr,
11622 const ::std::wstring& needle, const ::std::wstring& haystack);
11623 #endif // GTEST_HAS_STD_WSTRING
11624
11625 namespace internal {
11626
11627 // Helper template function for comparing floating-points.
11628 //
11629 // Template parameter:
11630 //
11631 // RawType: the raw floating-point type (either float or double)
11632 //
11633 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11634 template <typename RawType>
11635 AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
11636 const char* rhs_expression,
11637 RawType lhs_value,
11638 RawType rhs_value) {
11639 const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
11640
11641 if (lhs.AlmostEquals(rhs)) {
11642 return AssertionSuccess();
11643 }
11644
11645 ::std::stringstream lhs_ss;
11646 lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11647 << lhs_value;
11648
11649 ::std::stringstream rhs_ss;
11650 rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11651 << rhs_value;
11652
11653 return EqFailure(lhs_expression,
11654 rhs_expression,
11655 StringStreamToString(&lhs_ss),
11656 StringStreamToString(&rhs_ss),
11657 false);
11658 }
11659
11660 // Helper function for implementing ASSERT_NEAR.
11661 //
11662 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11663 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
11664 const char* expr2,
11665 const char* abs_error_expr,
11666 double val1,
11667 double val2,
11668 double abs_error);
11669
11670 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
11671 // A class that enables one to stream messages to assertion macros
11672 class GTEST_API_ AssertHelper {
11673 public:
11674 // Constructor.
11675 AssertHelper(TestPartResult::Type type,
11676 const char* file,
11677 int line,
11678 const char* message);
11679 ~AssertHelper();
11680
11681 // Message assignment is a semantic trick to enable assertion
11682 // streaming; see the GTEST_MESSAGE_ macro below.
11683 void operator=(const Message& message) const;
11684
11685 private:
11686 // We put our data in a struct so that the size of the AssertHelper class can
11687 // be as small as possible. This is important because gcc is incapable of
11688 // re-using stack space even for temporary variables, so every EXPECT_EQ
11689 // reserves stack space for another AssertHelper.
11690 struct AssertHelperData {
11691 AssertHelperData(TestPartResult::Type t,
11692 const char* srcfile,
11693 int line_num,
11694 const char* msg)
11695 : type(t), file(srcfile), line(line_num), message(msg) { }
11696
11697 TestPartResult::Type const type;
11698 const char* const file;
11699 int const line;
11700 std::string const message;
11701
11702 private:
11703 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
11704 };
11705
11706 AssertHelperData* const data_;
11707
11708 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
11709 };
11710
11711 } // namespace internal
11712
11713 // The pure interface class that all value-parameterized tests inherit from.
11714 // A value-parameterized class must inherit from both ::testing::Test and
11715 // ::testing::WithParamInterface. In most cases that just means inheriting
11716 // from ::testing::TestWithParam, but more complicated test hierarchies
11717 // may need to inherit from Test and WithParamInterface at different levels.
11718 //
11719 // This interface has support for accessing the test parameter value via
11720 // the GetParam() method.
11721 //
11722 // Use it with one of the parameter generator defining functions, like Range(),
11723 // Values(), ValuesIn(), Bool(), and Combine().
11724 //
11725 // class FooTest : public ::testing::TestWithParam<int> {
11726 // protected:
11727 // FooTest() {
11728 // // Can use GetParam() here.
11729 // }
11730 // ~FooTest() override {
11731 // // Can use GetParam() here.
11732 // }
11733 // void SetUp() override {
11734 // // Can use GetParam() here.
11735 // }
11736 // void TearDown override {
11737 // // Can use GetParam() here.
11738 // }
11739 // };
11740 // TEST_P(FooTest, DoesBar) {
11741 // // Can use GetParam() method here.
11742 // Foo foo;
11743 // ASSERT_TRUE(foo.DoesBar(GetParam()));
11744 // }
11745 // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
11746
11747 template <typename T>
11748 class WithParamInterface {
11749 public:
11750 typedef T ParamType;
11751 virtual ~WithParamInterface() {}
11752
11753 // The current parameter value. Is also available in the test fixture's
11754 // constructor.
11755 static const ParamType& GetParam() {
11756 GTEST_CHECK_(parameter_ != nullptr)
11757 << "GetParam() can only be called inside a value-parameterized test "
11758 << "-- did you intend to write TEST_P instead of TEST_F?";
11759 return *parameter_;
11760 }
11761
11762 private:
11763 // Sets parameter value. The caller is responsible for making sure the value
11764 // remains alive and unchanged throughout the current test.
11765 static void SetParam(const ParamType* parameter) {
11766 parameter_ = parameter;
11767 }
11768
11769 // Static value used for accessing parameter during a test lifetime.
11770 static const ParamType* parameter_;
11771
11772 // TestClass must be a subclass of WithParamInterface<T> and Test.
11773 template <class TestClass> friend class internal::ParameterizedTestFactory;
11774 };
11775
11776 template <typename T>
11777 const T* WithParamInterface<T>::parameter_ = nullptr;
11778
11779 // Most value-parameterized classes can ignore the existence of
11780 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
11781
11782 template <typename T>
11783 class TestWithParam : public Test, public WithParamInterface<T> {
11784 };
11785
11786 // Macros for indicating success/failure in test code.
11787
11788 // Skips test in runtime.
11789 // Skipping test aborts current function.
11790 // Skipped tests are neither successful nor failed.
11791 #define GTEST_SKIP() GTEST_SKIP_("")
11792
11793 // ADD_FAILURE unconditionally adds a failure to the current test.
11794 // SUCCEED generates a success - it doesn't automatically make the
11795 // current test successful, as a test is only successful when it has
11796 // no failure.
11797 //
11798 // EXPECT_* verifies that a certain condition is satisfied. If not,
11799 // it behaves like ADD_FAILURE. In particular:
11800 //
11801 // EXPECT_TRUE verifies that a Boolean condition is true.
11802 // EXPECT_FALSE verifies that a Boolean condition is false.
11803 //
11804 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
11805 // that they will also abort the current function on failure. People
11806 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
11807 // writing data-driven tests often find themselves using ADD_FAILURE
11808 // and EXPECT_* more.
11809
11810 // Generates a nonfatal failure with a generic message.
11811 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
11812
11813 // Generates a nonfatal failure at the given source file location with
11814 // a generic message.
11815 #define ADD_FAILURE_AT(file, line) \
11816 GTEST_MESSAGE_AT_(file, line, "Failed", \
11817 ::testing::TestPartResult::kNonFatalFailure)
11818
11819 // Generates a fatal failure with a generic message.
11820 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
11821
11822 // Like GTEST_FAIL(), but at the given source file location.
11823 #define GTEST_FAIL_AT(file, line) \
11824 GTEST_MESSAGE_AT_(file, line, "Failed", \
11825 ::testing::TestPartResult::kFatalFailure)
11826
11827 // Define this macro to 1 to omit the definition of FAIL(), which is a
11828 // generic name and clashes with some other libraries.
11829 #if !GTEST_DONT_DEFINE_FAIL
11830 # define FAIL() GTEST_FAIL()
11831 #endif
11832
11833 // Generates a success with a generic message.
11834 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
11835
11836 // Define this macro to 1 to omit the definition of SUCCEED(), which
11837 // is a generic name and clashes with some other libraries.
11838 #if !GTEST_DONT_DEFINE_SUCCEED
11839 # define SUCCEED() GTEST_SUCCEED()
11840 #endif
11841
11842 // Macros for testing exceptions.
11843 //
11844 // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
11845 // Tests that the statement throws the expected exception.
11846 // * {ASSERT|EXPECT}_NO_THROW(statement):
11847 // Tests that the statement doesn't throw any exception.
11848 // * {ASSERT|EXPECT}_ANY_THROW(statement):
11849 // Tests that the statement throws an exception.
11850
11851 #define EXPECT_THROW(statement, expected_exception) \
11852 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
11853 #define EXPECT_NO_THROW(statement) \
11854 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11855 #define EXPECT_ANY_THROW(statement) \
11856 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11857 #define ASSERT_THROW(statement, expected_exception) \
11858 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
11859 #define ASSERT_NO_THROW(statement) \
11860 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
11861 #define ASSERT_ANY_THROW(statement) \
11862 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
11863
11864 // Boolean assertions. Condition can be either a Boolean expression or an
11865 // AssertionResult. For more information on how to use AssertionResult with
11866 // these macros see comments on that class.
11867 #define GTEST_EXPECT_TRUE(condition) \
11868 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11869 GTEST_NONFATAL_FAILURE_)
11870 #define GTEST_EXPECT_FALSE(condition) \
11871 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11872 GTEST_NONFATAL_FAILURE_)
11873 #define GTEST_ASSERT_TRUE(condition) \
11874 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11875 GTEST_FATAL_FAILURE_)
11876 #define GTEST_ASSERT_FALSE(condition) \
11877 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11878 GTEST_FATAL_FAILURE_)
11879
11880 // Define these macros to 1 to omit the definition of the corresponding
11881 // EXPECT or ASSERT, which clashes with some users' own code.
11882
11883 #if !GTEST_DONT_DEFINE_EXPECT_TRUE
11884 #define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
11885 #endif
11886
11887 #if !GTEST_DONT_DEFINE_EXPECT_FALSE
11888 #define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
11889 #endif
11890
11891 #if !GTEST_DONT_DEFINE_ASSERT_TRUE
11892 #define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
11893 #endif
11894
11895 #if !GTEST_DONT_DEFINE_ASSERT_FALSE
11896 #define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
11897 #endif
11898
11899 // Macros for testing equalities and inequalities.
11900 //
11901 // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
11902 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
11903 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
11904 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
11905 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
11906 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
11907 //
11908 // When they are not, Google Test prints both the tested expressions and
11909 // their actual values. The values must be compatible built-in types,
11910 // or you will get a compiler error. By "compatible" we mean that the
11911 // values can be compared by the respective operator.
11912 //
11913 // Note:
11914 //
11915 // 1. It is possible to make a user-defined type work with
11916 // {ASSERT|EXPECT}_??(), but that requires overloading the
11917 // comparison operators and is thus discouraged by the Google C++
11918 // Usage Guide. Therefore, you are advised to use the
11919 // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
11920 // equal.
11921 //
11922 // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
11923 // pointers (in particular, C strings). Therefore, if you use it
11924 // with two C strings, you are testing how their locations in memory
11925 // are related, not how their content is related. To compare two C
11926 // strings by content, use {ASSERT|EXPECT}_STR*().
11927 //
11928 // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
11929 // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
11930 // what the actual value is when it fails, and similarly for the
11931 // other comparisons.
11932 //
11933 // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
11934 // evaluate their arguments, which is undefined.
11935 //
11936 // 5. These macros evaluate their arguments exactly once.
11937 //
11938 // Examples:
11939 //
11940 // EXPECT_NE(Foo(), 5);
11941 // EXPECT_EQ(a_pointer, NULL);
11942 // ASSERT_LT(i, array_size);
11943 // ASSERT_GT(records.size(), 0) << "There is no record left.";
11944
11945 #define EXPECT_EQ(val1, val2) \
11946 EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11947 #define EXPECT_NE(val1, val2) \
11948 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11949 #define EXPECT_LE(val1, val2) \
11950 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11951 #define EXPECT_LT(val1, val2) \
11952 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11953 #define EXPECT_GE(val1, val2) \
11954 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11955 #define EXPECT_GT(val1, val2) \
11956 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11957
11958 #define GTEST_ASSERT_EQ(val1, val2) \
11959 ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11960 #define GTEST_ASSERT_NE(val1, val2) \
11961 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11962 #define GTEST_ASSERT_LE(val1, val2) \
11963 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11964 #define GTEST_ASSERT_LT(val1, val2) \
11965 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11966 #define GTEST_ASSERT_GE(val1, val2) \
11967 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11968 #define GTEST_ASSERT_GT(val1, val2) \
11969 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11970
11971 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
11972 // ASSERT_XY(), which clashes with some users' own code.
11973
11974 #if !GTEST_DONT_DEFINE_ASSERT_EQ
11975 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
11976 #endif
11977
11978 #if !GTEST_DONT_DEFINE_ASSERT_NE
11979 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
11980 #endif
11981
11982 #if !GTEST_DONT_DEFINE_ASSERT_LE
11983 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
11984 #endif
11985
11986 #if !GTEST_DONT_DEFINE_ASSERT_LT
11987 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
11988 #endif
11989
11990 #if !GTEST_DONT_DEFINE_ASSERT_GE
11991 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
11992 #endif
11993
11994 #if !GTEST_DONT_DEFINE_ASSERT_GT
11995 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
11996 #endif
11997
11998 // C-string Comparisons. All tests treat NULL and any non-NULL string
11999 // as different. Two NULLs are equal.
12000 //
12001 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
12002 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
12003 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
12004 // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
12005 //
12006 // For wide or narrow string objects, you can use the
12007 // {ASSERT|EXPECT}_??() macros.
12008 //
12009 // Don't depend on the order in which the arguments are evaluated,
12010 // which is undefined.
12011 //
12012 // These macros evaluate their arguments exactly once.
12013
12014 #define EXPECT_STREQ(s1, s2) \
12015 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12016 #define EXPECT_STRNE(s1, s2) \
12017 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12018 #define EXPECT_STRCASEEQ(s1, s2) \
12019 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12020 #define EXPECT_STRCASENE(s1, s2)\
12021 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12022
12023 #define ASSERT_STREQ(s1, s2) \
12024 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12025 #define ASSERT_STRNE(s1, s2) \
12026 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12027 #define ASSERT_STRCASEEQ(s1, s2) \
12028 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12029 #define ASSERT_STRCASENE(s1, s2)\
12030 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12031
12032 // Macros for comparing floating-point numbers.
12033 //
12034 // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
12035 // Tests that two float values are almost equal.
12036 // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
12037 // Tests that two double values are almost equal.
12038 // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
12039 // Tests that v1 and v2 are within the given distance to each other.
12040 //
12041 // Google Test uses ULP-based comparison to automatically pick a default
12042 // error bound that is appropriate for the operands. See the
12043 // FloatingPoint template class in gtest-internal.h if you are
12044 // interested in the implementation details.
12045
12046 #define EXPECT_FLOAT_EQ(val1, val2)\
12047 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12048 val1, val2)
12049
12050 #define EXPECT_DOUBLE_EQ(val1, val2)\
12051 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12052 val1, val2)
12053
12054 #define ASSERT_FLOAT_EQ(val1, val2)\
12055 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12056 val1, val2)
12057
12058 #define ASSERT_DOUBLE_EQ(val1, val2)\
12059 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12060 val1, val2)
12061
12062 #define EXPECT_NEAR(val1, val2, abs_error)\
12063 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12064 val1, val2, abs_error)
12065
12066 #define ASSERT_NEAR(val1, val2, abs_error)\
12067 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12068 val1, val2, abs_error)
12069
12070 // These predicate format functions work on floating-point values, and
12071 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
12072 //
12073 // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
12074
12075 // Asserts that val1 is less than, or almost equal to, val2. Fails
12076 // otherwise. In particular, it fails if either val1 or val2 is NaN.
12077 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
12078 float val1, float val2);
12079 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
12080 double val1, double val2);
12081
12082
12083 #if GTEST_OS_WINDOWS
12084
12085 // Macros that test for HRESULT failure and success, these are only useful
12086 // on Windows, and rely on Windows SDK macros and APIs to compile.
12087 //
12088 // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
12089 //
12090 // When expr unexpectedly fails or succeeds, Google Test prints the
12091 // expected result and the actual result with both a human-readable
12092 // string representation of the error, if available, as well as the
12093 // hex result code.
12094 # define EXPECT_HRESULT_SUCCEEDED(expr) \
12095 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12096
12097 # define ASSERT_HRESULT_SUCCEEDED(expr) \
12098 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12099
12100 # define EXPECT_HRESULT_FAILED(expr) \
12101 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12102
12103 # define ASSERT_HRESULT_FAILED(expr) \
12104 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12105
12106 #endif // GTEST_OS_WINDOWS
12107
12108 // Macros that execute statement and check that it doesn't generate new fatal
12109 // failures in the current thread.
12110 //
12111 // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
12112 //
12113 // Examples:
12114 //
12115 // EXPECT_NO_FATAL_FAILURE(Process());
12116 // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
12117 //
12118 #define ASSERT_NO_FATAL_FAILURE(statement) \
12119 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
12120 #define EXPECT_NO_FATAL_FAILURE(statement) \
12121 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
12122
12123 // Causes a trace (including the given source file path and line number,
12124 // and the given message) to be included in every test failure message generated
12125 // by code in the scope of the lifetime of an instance of this class. The effect
12126 // is undone with the destruction of the instance.
12127 //
12128 // The message argument can be anything streamable to std::ostream.
12129 //
12130 // Example:
12131 // testing::ScopedTrace trace("file.cc", 123, "message");
12132 //
12133 class GTEST_API_ ScopedTrace {
12134 public:
12135 // The c'tor pushes the given source file location and message onto
12136 // a trace stack maintained by Google Test.
12137
12138 // Template version. Uses Message() to convert the values into strings.
12139 // Slow, but flexible.
12140 template <typename T>
12141 ScopedTrace(const char* file, int line, const T& message) {
12142 PushTrace(file, line, (Message() << message).GetString());
12143 }
12144
12145 // Optimize for some known types.
12146 ScopedTrace(const char* file, int line, const char* message) {
12147 PushTrace(file, line, message ? message : "(null)");
12148 }
12149
12150 ScopedTrace(const char* file, int line, const std::string& message) {
12151 PushTrace(file, line, message);
12152 }
12153
12154 // The d'tor pops the info pushed by the c'tor.
12155 //
12156 // Note that the d'tor is not virtual in order to be efficient.
12157 // Don't inherit from ScopedTrace!
12158 ~ScopedTrace();
12159
12160 private:
12161 void PushTrace(const char* file, int line, std::string message);
12162
12163 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
12164 } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
12165 // c'tor and d'tor. Therefore it doesn't
12166 // need to be used otherwise.
12167
12168 // Causes a trace (including the source file path, the current line
12169 // number, and the given message) to be included in every test failure
12170 // message generated by code in the current scope. The effect is
12171 // undone when the control leaves the current scope.
12172 //
12173 // The message argument can be anything streamable to std::ostream.
12174 //
12175 // In the implementation, we include the current line number as part
12176 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
12177 // to appear in the same block - as long as they are on different
12178 // lines.
12179 //
12180 // Assuming that each thread maintains its own stack of traces.
12181 // Therefore, a SCOPED_TRACE() would (correctly) only affect the
12182 // assertions in its own thread.
12183 #define SCOPED_TRACE(message) \
12184 ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
12185 __FILE__, __LINE__, (message))
12186
12187 // Compile-time assertion for type equality.
12188 // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
12189 // are the same type. The value it returns is not interesting.
12190 //
12191 // Instead of making StaticAssertTypeEq a class template, we make it a
12192 // function template that invokes a helper class template. This
12193 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
12194 // defining objects of that type.
12195 //
12196 // CAVEAT:
12197 //
12198 // When used inside a method of a class template,
12199 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
12200 // instantiated. For example, given:
12201 //
12202 // template <typename T> class Foo {
12203 // public:
12204 // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
12205 // };
12206 //
12207 // the code:
12208 //
12209 // void Test1() { Foo<bool> foo; }
12210 //
12211 // will NOT generate a compiler error, as Foo<bool>::Bar() is never
12212 // actually instantiated. Instead, you need:
12213 //
12214 // void Test2() { Foo<bool> foo; foo.Bar(); }
12215 //
12216 // to cause a compiler error.
12217 template <typename T1, typename T2>
12218 constexpr bool StaticAssertTypeEq() noexcept {
12219 static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
12220 return true;
12221 }
12222
12223 // Defines a test.
12224 //
12225 // The first parameter is the name of the test suite, and the second
12226 // parameter is the name of the test within the test suite.
12227 //
12228 // The convention is to end the test suite name with "Test". For
12229 // example, a test suite for the Foo class can be named FooTest.
12230 //
12231 // Test code should appear between braces after an invocation of
12232 // this macro. Example:
12233 //
12234 // TEST(FooTest, InitializesCorrectly) {
12235 // Foo foo;
12236 // EXPECT_TRUE(foo.StatusIsOK());
12237 // }
12238
12239 // Note that we call GetTestTypeId() instead of GetTypeId<
12240 // ::testing::Test>() here to get the type ID of testing::Test. This
12241 // is to work around a suspected linker bug when using Google Test as
12242 // a framework on Mac OS X. The bug causes GetTypeId<
12243 // ::testing::Test>() to return different values depending on whether
12244 // the call is from the Google Test framework itself or from user test
12245 // code. GetTestTypeId() is guaranteed to always return the same
12246 // value, as it always calls GetTypeId<>() from the Google Test
12247 // framework.
12248 #define GTEST_TEST(test_suite_name, test_name) \
12249 GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
12250 ::testing::internal::GetTestTypeId())
12251
12252 // Define this macro to 1 to omit the definition of TEST(), which
12253 // is a generic name and clashes with some other libraries.
12254 #if !GTEST_DONT_DEFINE_TEST
12255 #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
12256 #endif
12257
12258 // Defines a test that uses a test fixture.
12259 //
12260 // The first parameter is the name of the test fixture class, which
12261 // also doubles as the test suite name. The second parameter is the
12262 // name of the test within the test suite.
12263 //
12264 // A test fixture class must be declared earlier. The user should put
12265 // the test code between braces after using this macro. Example:
12266 //
12267 // class FooTest : public testing::Test {
12268 // protected:
12269 // void SetUp() override { b_.AddElement(3); }
12270 //
12271 // Foo a_;
12272 // Foo b_;
12273 // };
12274 //
12275 // TEST_F(FooTest, InitializesCorrectly) {
12276 // EXPECT_TRUE(a_.StatusIsOK());
12277 // }
12278 //
12279 // TEST_F(FooTest, ReturnsElementCountCorrectly) {
12280 // EXPECT_EQ(a_.size(), 0);
12281 // EXPECT_EQ(b_.size(), 1);
12282 // }
12283 //
12284 // GOOGLETEST_CM0011 DO NOT DELETE
12285 #if !GTEST_DONT_DEFINE_TEST
12286 #define TEST_F(test_fixture, test_name)\
12287 GTEST_TEST_(test_fixture, test_name, test_fixture, \
12288 ::testing::internal::GetTypeId<test_fixture>())
12289 #endif // !GTEST_DONT_DEFINE_TEST
12290
12291 // Returns a path to temporary directory.
12292 // Tries to determine an appropriate directory for the platform.
12293 GTEST_API_ std::string TempDir();
12294
12295 #ifdef _MSC_VER
12296 # pragma warning(pop)
12297 #endif
12298
12299 // Dynamically registers a test with the framework.
12300 //
12301 // This is an advanced API only to be used when the `TEST` macros are
12302 // insufficient. The macros should be preferred when possible, as they avoid
12303 // most of the complexity of calling this function.
12304 //
12305 // The `factory` argument is a factory callable (move-constructible) object or
12306 // function pointer that creates a new instance of the Test object. It
12307 // handles ownership to the caller. The signature of the callable is
12308 // `Fixture*()`, where `Fixture` is the test fixture class for the test. All
12309 // tests registered with the same `test_suite_name` must return the same
12310 // fixture type. This is checked at runtime.
12311 //
12312 // The framework will infer the fixture class from the factory and will call
12313 // the `SetUpTestSuite` and `TearDownTestSuite` for it.
12314 //
12315 // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
12316 // undefined.
12317 //
12318 // Use case example:
12319 //
12320 // class MyFixture : public ::testing::Test {
12321 // public:
12322 // // All of these optional, just like in regular macro usage.
12323 // static void SetUpTestSuite() { ... }
12324 // static void TearDownTestSuite() { ... }
12325 // void SetUp() override { ... }
12326 // void TearDown() override { ... }
12327 // };
12328 //
12329 // class MyTest : public MyFixture {
12330 // public:
12331 // explicit MyTest(int data) : data_(data) {}
12332 // void TestBody() override { ... }
12333 //
12334 // private:
12335 // int data_;
12336 // };
12337 //
12338 // void RegisterMyTests(const std::vector<int>& values) {
12339 // for (int v : values) {
12340 // ::testing::RegisterTest(
12341 // "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
12342 // std::to_string(v).c_str(),
12343 // __FILE__, __LINE__,
12344 // // Important to use the fixture type as the return type here.
12345 // [=]() -> MyFixture* { return new MyTest(v); });
12346 // }
12347 // }
12348 // ...
12349 // int main(int argc, char** argv) {
12350 // std::vector<int> values_to_test = LoadValuesFromConfig();
12351 // RegisterMyTests(values_to_test);
12352 // ...
12353 // return RUN_ALL_TESTS();
12354 // }
12355 //
12356 template <int&... ExplicitParameterBarrier, typename Factory>
12357 TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
12358 const char* type_param, const char* value_param,
12359 const char* file, int line, Factory factory) {
12360 using TestT = typename std::remove_pointer<decltype(factory())>::type;
12361
12362 class FactoryImpl : public internal::TestFactoryBase {
12363 public:
12364 explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
12365 Test* CreateTest() override { return factory_(); }
12366
12367 private:
12368 Factory factory_;
12369 };
12370
12371 return internal::MakeAndRegisterTestInfo(
12372 test_suite_name, test_name, type_param, value_param,
12373 internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
12374 internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
12375 internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
12376 new FactoryImpl{std::move(factory)});
12377 }
12378
12379 } // namespace testing
12380
12381 // Use this function in main() to run all tests. It returns 0 if all
12382 // tests are successful, or 1 otherwise.
12383 //
12384 // RUN_ALL_TESTS() should be invoked after the command line has been
12385 // parsed by InitGoogleTest().
12386 //
12387 // This function was formerly a macro; thus, it is in the global
12388 // namespace and has an all-caps name.
12389 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
12390
12391 inline int RUN_ALL_TESTS() {
12392 return ::testing::UnitTest::GetInstance()->Run();
12393 }
12394
12395 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
12396
12397 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_
+0
-413
source/misc/embedded_libs/fmt-8.1.1/test/gtest-extra-test.cc less more
0 // Formatting library for C++ - tests of custom Google Test assertions
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "gtest-extra.h"
8
9 #include <gtest/gtest-spi.h>
10
11 #include <cstring>
12 #include <memory>
13 #include <stdexcept>
14
15 #include "fmt/os.h"
16 #include "util.h"
17
18 // Tests that assertion macros evaluate their arguments exactly once.
19 namespace {
20 class single_evaluation_test : public ::testing::Test {
21 protected:
22 single_evaluation_test() {
23 p_ = s_;
24 a_ = 0;
25 b_ = 0;
26 }
27
28 static const char* const s_;
29 static const char* p_;
30
31 static int a_;
32 static int b_;
33 };
34 } // namespace
35
36 const char* const single_evaluation_test::s_ = "01234";
37 const char* single_evaluation_test::p_;
38 int single_evaluation_test::a_;
39 int single_evaluation_test::b_;
40
41 void do_nothing() {}
42
43 FMT_NORETURN void throw_exception() { throw std::runtime_error("test"); }
44
45 FMT_NORETURN void throw_system_error() {
46 throw fmt::system_error(EDOM, "test");
47 }
48
49 // Tests that when EXPECT_THROW_MSG fails, it evaluates its message argument
50 // exactly once.
51 TEST_F(single_evaluation_test, failed_expect_throw_msg) {
52 EXPECT_NONFATAL_FAILURE(
53 EXPECT_THROW_MSG(throw_exception(), std::exception, p_++), "01234");
54 EXPECT_EQ(s_ + 1, p_);
55 }
56
57 // Tests that when EXPECT_SYSTEM_ERROR fails, it evaluates its message argument
58 // exactly once.
59 TEST_F(single_evaluation_test, failed_expect_system_error) {
60 EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++),
61 "01234");
62 EXPECT_EQ(s_ + 1, p_);
63 }
64
65 // Tests that assertion arguments are evaluated exactly once.
66 TEST_F(single_evaluation_test, exception_tests) {
67 // successful EXPECT_THROW_MSG
68 EXPECT_THROW_MSG(
69 { // NOLINT
70 a_++;
71 throw_exception();
72 },
73 std::exception, (b_++, "test"));
74 EXPECT_EQ(1, a_);
75 EXPECT_EQ(1, b_);
76
77 // failed EXPECT_THROW_MSG, throws different type
78 EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
79 { // NOLINT
80 a_++;
81 throw_exception();
82 },
83 std::logic_error, (b_++, "test")),
84 "throws a different type");
85 EXPECT_EQ(2, a_);
86 EXPECT_EQ(2, b_);
87
88 // failed EXPECT_THROW_MSG, throws an exception with different message
89 EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
90 { // NOLINT
91 a_++;
92 throw_exception();
93 },
94 std::exception, (b_++, "other")),
95 "throws an exception with a different message");
96 EXPECT_EQ(3, a_);
97 EXPECT_EQ(3, b_);
98
99 // failed EXPECT_THROW_MSG, throws nothing
100 EXPECT_NONFATAL_FAILURE(
101 EXPECT_THROW_MSG(a_++, std::exception, (b_++, "test")), "throws nothing");
102 EXPECT_EQ(4, a_);
103 EXPECT_EQ(4, b_);
104 }
105
106 TEST_F(single_evaluation_test, system_error_tests) {
107 // successful EXPECT_SYSTEM_ERROR
108 EXPECT_SYSTEM_ERROR(
109 { // NOLINT
110 a_++;
111 throw_system_error();
112 },
113 EDOM, (b_++, "test"));
114 EXPECT_EQ(1, a_);
115 EXPECT_EQ(1, b_);
116
117 // failed EXPECT_SYSTEM_ERROR, throws different type
118 EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
119 { // NOLINT
120 a_++;
121 throw_exception();
122 },
123 EDOM, (b_++, "test")),
124 "throws a different type");
125 EXPECT_EQ(2, a_);
126 EXPECT_EQ(2, b_);
127
128 // failed EXPECT_SYSTEM_ERROR, throws an exception with different message
129 EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
130 { // NOLINT
131 a_++;
132 throw_system_error();
133 },
134 EDOM, (b_++, "other")),
135 "throws an exception with a different message");
136 EXPECT_EQ(3, a_);
137 EXPECT_EQ(3, b_);
138
139 // failed EXPECT_SYSTEM_ERROR, throws nothing
140 EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")),
141 "throws nothing");
142 EXPECT_EQ(4, a_);
143 EXPECT_EQ(4, b_);
144 }
145
146 #if FMT_USE_FCNTL
147 // Tests that when EXPECT_WRITE fails, it evaluates its message argument
148 // exactly once.
149 TEST_F(single_evaluation_test, failed_expect_write) {
150 EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), p_++),
151 "01234");
152 EXPECT_EQ(s_ + 1, p_);
153 }
154
155 // Tests that assertion arguments are evaluated exactly once.
156 TEST_F(single_evaluation_test, write_tests) {
157 // successful EXPECT_WRITE
158 EXPECT_WRITE(
159 stdout,
160 { // NOLINT
161 a_++;
162 std::printf("test");
163 },
164 (b_++, "test"));
165 EXPECT_EQ(1, a_);
166 EXPECT_EQ(1, b_);
167
168 // failed EXPECT_WRITE
169 EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(
170 stdout,
171 { // NOLINT
172 a_++;
173 std::printf("test");
174 },
175 (b_++, "other")),
176 "Actual: test");
177 EXPECT_EQ(2, a_);
178 EXPECT_EQ(2, b_);
179 }
180
181 // Tests EXPECT_WRITE.
182 TEST(gtest_extra_test, expect_write) {
183 EXPECT_WRITE(stdout, do_nothing(), "");
184 EXPECT_WRITE(stdout, std::printf("test"), "test");
185 EXPECT_WRITE(stderr, std::fprintf(stderr, "test"), "test");
186 EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("that"), "this"),
187 "Expected: this\n"
188 " Actual: that");
189 }
190
191 TEST(gtest_extra_test, expect_write_streaming) {
192 EXPECT_WRITE(stdout, std::printf("test"), "test") << "unexpected failure";
193 EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), "other")
194 << "expected failure",
195 "expected failure");
196 }
197 #endif // FMT_USE_FCNTL
198
199 // Tests that the compiler will not complain about unreachable code in the
200 // EXPECT_THROW_MSG macro.
201 TEST(gtest_extra_test, expect_throw_no_unreachable_code_warning) {
202 int n = 0;
203 using std::runtime_error;
204 EXPECT_THROW_MSG(throw runtime_error(""), runtime_error, "");
205 EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(n++, runtime_error, ""), "");
206 EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(throw 1, runtime_error, ""), "");
207 EXPECT_NONFATAL_FAILURE(
208 EXPECT_THROW_MSG(throw runtime_error("a"), runtime_error, "b"), "");
209 }
210
211 // Tests that the compiler will not complain about unreachable code in the
212 // EXPECT_SYSTEM_ERROR macro.
213 TEST(gtest_extra_test, expect_system_error_no_unreachable_code_warning) {
214 int n = 0;
215 EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "test"), EDOM, "test");
216 EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(n++, EDOM, ""), "");
217 EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw 1, EDOM, ""), "");
218 EXPECT_NONFATAL_FAILURE(
219 EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "aaa"), EDOM, "bbb"),
220 "");
221 }
222
223 TEST(gtest_extra_test, expect_throw_behaves_like_single_statement) {
224 if (::testing::internal::AlwaysFalse())
225 EXPECT_THROW_MSG(do_nothing(), std::exception, "");
226
227 if (::testing::internal::AlwaysTrue())
228 EXPECT_THROW_MSG(throw_exception(), std::exception, "test");
229 else
230 do_nothing();
231 }
232
233 TEST(gtest_extra_test, expect_system_error_behaves_like_single_statement) {
234 if (::testing::internal::AlwaysFalse())
235 EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, "");
236
237 if (::testing::internal::AlwaysTrue())
238 EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test");
239 else
240 do_nothing();
241 }
242
243 TEST(gtest_extra_test, expect_write_behaves_like_single_statement) {
244 if (::testing::internal::AlwaysFalse())
245 EXPECT_WRITE(stdout, std::printf("x"), "x");
246
247 if (::testing::internal::AlwaysTrue())
248 EXPECT_WRITE(stdout, std::printf("x"), "x");
249 else
250 do_nothing();
251 }
252
253 // Tests EXPECT_THROW_MSG.
254 TEST(gtest_extra_test, expect_throw_msg) {
255 EXPECT_THROW_MSG(throw_exception(), std::exception, "test");
256 EXPECT_NONFATAL_FAILURE(
257 EXPECT_THROW_MSG(throw_exception(), std::logic_error, "test"),
258 "Expected: throw_exception() throws an exception of "
259 "type std::logic_error.\n Actual: it throws a different type.");
260 EXPECT_NONFATAL_FAILURE(
261 EXPECT_THROW_MSG(do_nothing(), std::exception, "test"),
262 "Expected: do_nothing() throws an exception of type std::exception.\n"
263 " Actual: it throws nothing.");
264 EXPECT_NONFATAL_FAILURE(
265 EXPECT_THROW_MSG(throw_exception(), std::exception, "other"),
266 "throw_exception() throws an exception with a different message.\n"
267 "Expected: other\n"
268 " Actual: test");
269 }
270
271 // Tests EXPECT_SYSTEM_ERROR.
272 TEST(gtest_extra_test, expect_system_error) {
273 EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test");
274 EXPECT_NONFATAL_FAILURE(
275 EXPECT_SYSTEM_ERROR(throw_exception(), EDOM, "test"),
276 "Expected: throw_exception() throws an exception of "
277 "type std::system_error.\n Actual: it throws a different type.");
278 EXPECT_NONFATAL_FAILURE(
279 EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, "test"),
280 "Expected: do_nothing() throws an exception of type std::system_error.\n"
281 " Actual: it throws nothing.");
282 EXPECT_NONFATAL_FAILURE(
283 EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other"),
284 fmt::format(
285 "throw_system_error() throws an exception with a different message.\n"
286 "Expected: {}\n"
287 " Actual: {}",
288 system_error_message(EDOM, "other"),
289 system_error_message(EDOM, "test")));
290 }
291
292 TEST(gtest_extra_test, expect_throw_msg_streaming) {
293 EXPECT_THROW_MSG(throw_exception(), std::exception, "test")
294 << "unexpected failure";
295 EXPECT_NONFATAL_FAILURE(
296 EXPECT_THROW_MSG(throw_exception(), std::exception, "other")
297 << "expected failure",
298 "expected failure");
299 }
300
301 TEST(gtest_extra_test, expect_system_error_streaming) {
302 EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test")
303 << "unexpected failure";
304 EXPECT_NONFATAL_FAILURE(
305 EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other")
306 << "expected failure",
307 "expected failure");
308 }
309
310 #if FMT_USE_FCNTL
311
312 using fmt::buffered_file;
313 using fmt::file;
314
315 TEST(output_redirect_test, scoped_redirect) {
316 file read_end, write_end;
317 file::pipe(read_end, write_end);
318 {
319 buffered_file file(write_end.fdopen("w"));
320 std::fprintf(file.get(), "[[[");
321 {
322 output_redirect redir(file.get());
323 std::fprintf(file.get(), "censored");
324 }
325 std::fprintf(file.get(), "]]]");
326 }
327 EXPECT_READ(read_end, "[[[]]]");
328 }
329
330 // Test that output_redirect handles errors in flush correctly.
331 TEST(output_redirect_test, flush_error_in_ctor) {
332 file read_end, write_end;
333 file::pipe(read_end, write_end);
334 int write_fd = write_end.descriptor();
335 file write_copy = write_end.dup(write_fd);
336 buffered_file f = write_end.fdopen("w");
337 // Put a character in a file buffer.
338 EXPECT_EQ('x', fputc('x', f.get()));
339 FMT_POSIX(close(write_fd));
340 std::unique_ptr<output_redirect> redir{nullptr};
341 EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new output_redirect(f.get())), EBADF,
342 "cannot flush stream");
343 redir.reset(nullptr);
344 write_copy.dup2(write_fd); // "undo" close or dtor will fail
345 }
346
347 TEST(output_redirect_test, dup_error_in_ctor) {
348 buffered_file f = open_buffered_file();
349 int fd = (f.fileno)();
350 file copy = file::dup(fd);
351 FMT_POSIX(close(fd));
352 std::unique_ptr<output_redirect> redir{nullptr};
353 EXPECT_SYSTEM_ERROR_NOASSERT(
354 redir.reset(new output_redirect(f.get())), EBADF,
355 fmt::format("cannot duplicate file descriptor {}", fd));
356 copy.dup2(fd); // "undo" close or dtor will fail
357 }
358
359 TEST(output_redirect_test, restore_and_read) {
360 file read_end, write_end;
361 file::pipe(read_end, write_end);
362 buffered_file file(write_end.fdopen("w"));
363 std::fprintf(file.get(), "[[[");
364 output_redirect redir(file.get());
365 std::fprintf(file.get(), "censored");
366 EXPECT_EQ("censored", redir.restore_and_read());
367 EXPECT_EQ("", redir.restore_and_read());
368 std::fprintf(file.get(), "]]]");
369 file = buffered_file();
370 EXPECT_READ(read_end, "[[[]]]");
371 }
372
373 // Test that OutputRedirect handles errors in flush correctly.
374 TEST(output_redirect_test, flush_error_in_restore_and_read) {
375 file read_end, write_end;
376 file::pipe(read_end, write_end);
377 int write_fd = write_end.descriptor();
378 file write_copy = write_end.dup(write_fd);
379 buffered_file f = write_end.fdopen("w");
380 output_redirect redir(f.get());
381 // Put a character in a file buffer.
382 EXPECT_EQ('x', fputc('x', f.get()));
383 FMT_POSIX(close(write_fd));
384 EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(), EBADF,
385 "cannot flush stream");
386 write_copy.dup2(write_fd); // "undo" close or dtor will fail
387 }
388
389 TEST(output_redirect_test, error_in_dtor) {
390 file read_end, write_end;
391 file::pipe(read_end, write_end);
392 int write_fd = write_end.descriptor();
393 file write_copy = write_end.dup(write_fd);
394 buffered_file f = write_end.fdopen("w");
395 std::unique_ptr<output_redirect> redir(new output_redirect(f.get()));
396 // Put a character in a file buffer.
397 EXPECT_EQ('x', fputc('x', f.get()));
398 EXPECT_WRITE(
399 stderr,
400 {
401 // The close function must be called inside EXPECT_WRITE,
402 // otherwise the system may recycle closed file descriptor when
403 // redirecting the output in EXPECT_STDERR and the second close
404 // will break output redirection.
405 FMT_POSIX(close(write_fd));
406 SUPPRESS_ASSERT(redir.reset(nullptr));
407 },
408 system_error_message(EBADF, "cannot flush stream"));
409 write_copy.dup2(write_fd); // "undo" close or dtor of buffered_file will fail
410 }
411
412 #endif // FMT_USE_FCNTL
+0
-80
source/misc/embedded_libs/fmt-8.1.1/test/gtest-extra.cc less more
0 // Formatting library for C++ - custom Google Test assertions
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "gtest-extra.h"
8
9 #if FMT_USE_FCNTL
10
11 using fmt::file;
12
13 output_redirect::output_redirect(FILE* f) : file_(f) {
14 flush();
15 int fd = FMT_POSIX(fileno(f));
16 // Create a file object referring to the original file.
17 original_ = file::dup(fd);
18 // Create a pipe.
19 file write_end;
20 file::pipe(read_end_, write_end);
21 // Connect the passed FILE object to the write end of the pipe.
22 write_end.dup2(fd);
23 }
24
25 output_redirect::~output_redirect() FMT_NOEXCEPT {
26 try {
27 restore();
28 } catch (const std::exception& e) {
29 std::fputs(e.what(), stderr);
30 }
31 }
32
33 void output_redirect::flush() {
34 int result = 0;
35 do {
36 result = fflush(file_);
37 } while (result == EOF && errno == EINTR);
38 if (result != 0) throw fmt::system_error(errno, "cannot flush stream");
39 }
40
41 void output_redirect::restore() {
42 if (original_.descriptor() == -1) return; // Already restored.
43 flush();
44 // Restore the original file.
45 original_.dup2(FMT_POSIX(fileno(file_)));
46 original_.close();
47 }
48
49 std::string output_redirect::restore_and_read() {
50 // Restore output.
51 restore();
52
53 // Read everything from the pipe.
54 std::string content;
55 if (read_end_.descriptor() == -1) return content; // Already read.
56 enum { BUFFER_SIZE = 4096 };
57 char buffer[BUFFER_SIZE];
58 size_t count = 0;
59 do {
60 count = read_end_.read(buffer, BUFFER_SIZE);
61 content.append(buffer, count);
62 } while (count != 0);
63 read_end_.close();
64 return content;
65 }
66
67 std::string read(file& f, size_t count) {
68 std::string buffer(count, '\0');
69 size_t n = 0, offset = 0;
70 do {
71 n = f.read(&buffer[offset], count - offset);
72 // We can't read more than size_t bytes since count has type size_t.
73 offset += n;
74 } while (offset < count && n != 0);
75 buffer.resize(offset);
76 return buffer;
77 }
78
79 #endif // FMT_USE_FCNTL
+0
-170
source/misc/embedded_libs/fmt-8.1.1/test/gtest-extra.h less more
0 // Formatting library for C++ - custom Google Test assertions
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_GTEST_EXTRA_H_
8 #define FMT_GTEST_EXTRA_H_
9
10 #include <stdlib.h> // _invalid_parameter_handler
11
12 #include <string>
13
14 #ifdef FMT_MODULE_TEST
15 import fmt;
16 #else
17 # include "fmt/os.h"
18 #endif // FMG_MODULE_TEST
19
20 #include "gmock/gmock.h"
21
22 #define FMT_TEST_THROW_(statement, expected_exception, expected_message, fail) \
23 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
24 if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
25 std::string gtest_expected_message = expected_message; \
26 bool gtest_caught_expected = false; \
27 try { \
28 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
29 } catch (expected_exception const& e) { \
30 if (gtest_expected_message != e.what()) { \
31 gtest_ar << #statement \
32 " throws an exception with a different message.\n" \
33 << "Expected: " << gtest_expected_message << "\n" \
34 << " Actual: " << e.what(); \
35 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
36 } \
37 gtest_caught_expected = true; \
38 } catch (...) { \
39 gtest_ar << "Expected: " #statement \
40 " throws an exception of type " #expected_exception \
41 ".\n Actual: it throws a different type."; \
42 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
43 } \
44 if (!gtest_caught_expected) { \
45 gtest_ar << "Expected: " #statement \
46 " throws an exception of type " #expected_exception \
47 ".\n Actual: it throws nothing."; \
48 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
49 } \
50 } else \
51 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
52 : fail(gtest_ar.failure_message())
53
54 // Tests that the statement throws the expected exception and the exception's
55 // what() method returns expected message.
56 #define EXPECT_THROW_MSG(statement, expected_exception, expected_message) \
57 FMT_TEST_THROW_(statement, expected_exception, expected_message, \
58 GTEST_NONFATAL_FAILURE_)
59
60 inline std::string system_error_message(int error_code,
61 const std::string& message) {
62 auto ec = std::error_code(error_code, std::generic_category());
63 return std::system_error(ec, message).what();
64 }
65
66 #define EXPECT_SYSTEM_ERROR(statement, error_code, message) \
67 EXPECT_THROW_MSG(statement, std::system_error, \
68 system_error_message(error_code, message))
69
70 #if FMT_USE_FCNTL
71
72 // Captures file output by redirecting it to a pipe.
73 // The output it can handle is limited by the pipe capacity.
74 class output_redirect {
75 private:
76 FILE* file_;
77 fmt::file original_; // Original file passed to redirector.
78 fmt::file read_end_; // Read end of the pipe where the output is redirected.
79
80 void flush();
81 void restore();
82
83 public:
84 explicit output_redirect(FILE* file);
85 ~output_redirect() FMT_NOEXCEPT;
86
87 output_redirect(const output_redirect&) = delete;
88 void operator=(const output_redirect&) = delete;
89
90 // Restores the original file, reads output from the pipe into a string
91 // and returns it.
92 std::string restore_and_read();
93 };
94
95 # define FMT_TEST_WRITE_(statement, expected_output, file, fail) \
96 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
97 if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
98 std::string gtest_expected_output = expected_output; \
99 output_redirect gtest_redir(file); \
100 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
101 std::string gtest_output = gtest_redir.restore_and_read(); \
102 if (gtest_output != gtest_expected_output) { \
103 gtest_ar << #statement " produces different output.\n" \
104 << "Expected: " << gtest_expected_output << "\n" \
105 << " Actual: " << gtest_output; \
106 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
107 } \
108 } else \
109 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
110 : fail(gtest_ar.failure_message())
111
112 // Tests that the statement writes the expected output to file.
113 # define EXPECT_WRITE(file, statement, expected_output) \
114 FMT_TEST_WRITE_(statement, expected_output, file, GTEST_NONFATAL_FAILURE_)
115
116 # ifdef _MSC_VER
117
118 // Suppresses Windows assertions on invalid file descriptors, making
119 // POSIX functions return proper error codes instead of crashing on Windows.
120 class suppress_assert {
121 private:
122 _invalid_parameter_handler original_handler_;
123 int original_report_mode_;
124
125 static void handle_invalid_parameter(const wchar_t*, const wchar_t*,
126 const wchar_t*, unsigned, uintptr_t) {}
127
128 public:
129 suppress_assert()
130 : original_handler_(
131 _set_invalid_parameter_handler(handle_invalid_parameter)),
132 original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {}
133 ~suppress_assert() {
134 _set_invalid_parameter_handler(original_handler_);
135 _CrtSetReportMode(_CRT_ASSERT, original_report_mode_);
136 (void)original_report_mode_;
137 }
138 };
139
140 # define SUPPRESS_ASSERT(statement) \
141 { \
142 suppress_assert sa; \
143 statement; \
144 }
145 # else
146 # define SUPPRESS_ASSERT(statement) statement
147 # endif // _MSC_VER
148
149 # define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \
150 EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message)
151
152 // Attempts to read count characters from a file.
153 std::string read(fmt::file& f, size_t count);
154
155 # define EXPECT_READ(file, expected_content) \
156 EXPECT_EQ(expected_content, \
157 read(file, fmt::string_view(expected_content).size()))
158
159 #else
160 # define EXPECT_WRITE(file, statement, expected_output) \
161 do { \
162 (void)(file); \
163 (void)(statement); \
164 (void)(expected_output); \
165 SUCCEED(); \
166 } while (false)
167 #endif // FMT_USE_FCNTL
168
169 #endif // FMT_GTEST_EXTRA_H_
+0
-11
source/misc/embedded_libs/fmt-8.1.1/test/header-only-test.cc less more
0 // Header-only configuration test
1
2 #include "fmt/core.h"
3 #include "fmt/ostream.h"
4 #include "gtest/gtest.h"
5
6 #ifndef FMT_HEADER_ONLY
7 # error "Not in the header-only mode."
8 #endif
9
10 TEST(header_only_test, format) { EXPECT_EQ(fmt::format("foo"), "foo"); }
+0
-64
source/misc/embedded_libs/fmt-8.1.1/test/mock-allocator.h less more
0 // Formatting library for C++ - mock allocator
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_MOCK_ALLOCATOR_H_
8 #define FMT_MOCK_ALLOCATOR_H_
9
10 #include <assert.h> // assert
11 #include <stddef.h> // size_t
12
13 #include <memory> // std::allocator_traits
14
15 #include "gmock/gmock.h"
16
17 template <typename T> class mock_allocator {
18 public:
19 mock_allocator() {}
20 mock_allocator(const mock_allocator&) {}
21 using value_type = T;
22 MOCK_METHOD1_T(allocate, T*(size_t n));
23 MOCK_METHOD2_T(deallocate, void(T* p, size_t n));
24 };
25
26 template <typename Allocator> class allocator_ref {
27 private:
28 Allocator* alloc_;
29
30 void move(allocator_ref& other) {
31 alloc_ = other.alloc_;
32 other.alloc_ = nullptr;
33 }
34
35 public:
36 using value_type = typename Allocator::value_type;
37
38 explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {}
39
40 allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {}
41 allocator_ref(allocator_ref&& other) { move(other); }
42
43 allocator_ref& operator=(allocator_ref&& other) {
44 assert(this != &other);
45 move(other);
46 return *this;
47 }
48
49 allocator_ref& operator=(const allocator_ref& other) {
50 alloc_ = other.alloc_;
51 return *this;
52 }
53
54 public:
55 Allocator* get() const { return alloc_; }
56
57 value_type* allocate(size_t n) {
58 return std::allocator_traits<Allocator>::allocate(*alloc_, n);
59 }
60 void deallocate(value_type* p, size_t n) { alloc_->deallocate(p, n); }
61 };
62
63 #endif // FMT_MOCK_ALLOCATOR_H_
+0
-580
source/misc/embedded_libs/fmt-8.1.1/test/module-test.cc less more
0 // Formatting library for C++ - module tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6 //
7 // Copyright (c) 2021 - present, Daniela Engert
8 // All Rights Reserved
9 // {fmt} module.
10
11 #ifdef _MSC_FULL_VER
12 // hide some implementation bugs in msvc
13 // that are not essential to users of the module.
14 # define FMT_HIDE_MODULE_BUGS
15 #endif
16
17 #define FMT_MODULE_TEST
18
19 #include <bit>
20 #include <chrono>
21 #include <exception>
22 #include <iterator>
23 #include <locale>
24 #include <memory>
25 #include <ostream>
26 #include <string>
27 #include <string_view>
28 #include <system_error>
29
30 #if (__has_include(<fcntl.h>) || defined(__APPLE__) || \
31 defined(__linux__)) && \
32 (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
33 # include <fcntl.h>
34 # define FMT_USE_FCNTL 1
35 #else
36 # define FMT_USE_FCNTL 0
37 #endif
38 #define FMT_NOEXCEPT noexcept
39 #if defined(_WIN32) && !defined(__MINGW32__)
40 # define FMT_POSIX(call) _##call
41 #else
42 # define FMT_POSIX(call) call
43 #endif
44 #define FMT_OS_H_ // don't pull in os.h directly or indirectly
45
46 import fmt;
47
48 // check for macros leaking from BMI
49 static bool macro_leaked =
50 #if defined(FMT_CORE_H_) || defined(FMT_FORMAT_H_)
51 true;
52 #else
53 false;
54 #endif
55
56 // Include sources to pick up functions and classes from the module rather than
57 // from the non-modular library which is baked into the 'test-main' library.
58 // This averts linker problems:
59 // - strong ownership model: missing linker symbols
60 // - weak ownership model: duplicate linker symbols
61 #include "gtest-extra.cc"
62 #include "util.cc"
63
64 // an implicitly exported namespace must be visible [module.interface]/2.2
65 TEST(module_test, namespace) {
66 using namespace fmt;
67 using namespace fmt::literals;
68 ASSERT_TRUE(true);
69 }
70
71 namespace detail {
72 bool oops_detail_namespace_is_visible;
73 }
74
75 namespace fmt {
76 bool namespace_detail_invisible() {
77 #if defined(FMT_HIDE_MODULE_BUGS) && defined(_MSC_FULL_VER) && \
78 ((_MSC_VER == 1929 && _MSC_FULL_VER <= 192930136) || \
79 (_MSC_VER == 1930 && _MSC_FULL_VER <= 193030704))
80 // bug in msvc up to 16.11.5 / 17.0-pre5:
81
82 // the namespace is visible even when it is neither
83 // implicitly nor explicitly exported
84 return true;
85 #else
86 using namespace detail;
87 // this fails to compile if fmt::detail is visible
88 return !oops_detail_namespace_is_visible;
89 #endif
90 }
91 } // namespace fmt
92
93 // the non-exported namespace 'detail' must be invisible [module.interface]/2
94 TEST(module_test, detail_namespace) {
95 EXPECT_TRUE(fmt::namespace_detail_invisible());
96 }
97
98 // macros must not be imported from a *named* module [cpp.import]/5.1
99 TEST(module_test, macros) {
100 #if defined(FMT_HIDE_MODULE_BUGS) && defined(_MSC_FULL_VER) && \
101 _MSC_FULL_VER <= 192930130
102 // bug in msvc up to 16.11-pre2:
103 // include-guard macros leak from BMI
104 // and even worse: they cannot be #undef-ined
105 macro_leaked = false;
106 #endif
107 EXPECT_FALSE(macro_leaked);
108 }
109
110 // The following is less about functional testing (that's done elsewhere)
111 // but rather visibility of all client-facing overloads, reachability of
112 // non-exported entities, name lookup and overload resolution within
113 // template instantitions.
114 // Excercise all exported entities of the API at least once.
115 // Instantiate as many code paths as possible.
116
117 TEST(module_test, to_string) {
118 EXPECT_EQ("42", fmt::to_string(42));
119 EXPECT_EQ("42", fmt::to_string(42.0));
120
121 EXPECT_EQ(L"42", fmt::to_wstring(42));
122 EXPECT_EQ(L"42", fmt::to_wstring(42.0));
123 }
124
125 TEST(module_test, format) {
126 EXPECT_EQ("42", fmt::format("{:}", 42));
127 EXPECT_EQ("-42", fmt::format("{0}", -42.0));
128
129 EXPECT_EQ(L"42", fmt::format(L"{:}", 42));
130 EXPECT_EQ(L"-42", fmt::format(L"{0}", -42.0));
131 }
132
133 TEST(module_test, format_to) {
134 std::string s;
135 fmt::format_to(std::back_inserter(s), "{}", 42);
136 EXPECT_EQ("42", s);
137
138 char buffer[4] = {0};
139 fmt::format_to(buffer, "{}", 42);
140 EXPECT_EQ("42", std::string_view(buffer));
141
142 fmt::memory_buffer mb;
143 fmt::format_to(mb, "{}", 42);
144 EXPECT_EQ("42", std::string_view(buffer));
145
146 std::wstring w;
147 fmt::format_to(std::back_inserter(w), L"{}", 42);
148 EXPECT_EQ(L"42", w);
149
150 wchar_t wbuffer[4] = {0};
151 fmt::format_to(wbuffer, L"{}", 42);
152 EXPECT_EQ(L"42", std::wstring_view(wbuffer));
153
154 fmt::wmemory_buffer wb;
155 fmt::format_to(wb, L"{}", 42);
156 EXPECT_EQ(L"42", std::wstring_view(wbuffer));
157 }
158
159 TEST(module_test, formatted_size) {
160 EXPECT_EQ(2u, fmt::formatted_size("{}", 42));
161 EXPECT_EQ(2u, fmt::formatted_size(L"{}", 42));
162 }
163
164 TEST(module_test, format_to_n) {
165 std::string s;
166 auto result = fmt::format_to_n(std::back_inserter(s), 1, "{}", 42);
167 EXPECT_EQ(2u, result.size);
168 char buffer[4] = {0};
169 fmt::format_to_n(buffer, 3, "{}", 12345);
170
171 std::wstring w;
172 auto wresult = fmt::format_to_n(std::back_inserter(w), 1, L"{}", 42);
173 EXPECT_EQ(2u, wresult.size);
174 wchar_t wbuffer[4] = {0};
175 fmt::format_to_n(wbuffer, 3, L"{}", 12345);
176 }
177
178 TEST(module_test, format_args) {
179 auto no_args = fmt::format_args();
180 EXPECT_FALSE(no_args.get(1));
181
182 fmt::basic_format_args args = fmt::make_format_args(42);
183 EXPECT_TRUE(args.max_size() > 0);
184 auto arg0 = args.get(0);
185 EXPECT_TRUE(arg0);
186 decltype(arg0) arg_none;
187 EXPECT_FALSE(arg_none);
188 EXPECT_TRUE(arg0.type() != arg_none.type());
189 }
190
191 TEST(module_test, wformat_args) {
192 auto no_args = fmt::wformat_args();
193 EXPECT_FALSE(no_args.get(1));
194 fmt::basic_format_args args = fmt::make_wformat_args(42);
195 EXPECT_TRUE(args.get(0));
196 }
197
198 TEST(module_test, checked_format_args) {
199 fmt::basic_format_args args = fmt::make_args_checked<int>("{}", 42);
200 EXPECT_TRUE(args.get(0));
201 fmt::basic_format_args wargs = fmt::make_args_checked<int>(L"{}", 42);
202 EXPECT_TRUE(wargs.get(0));
203 }
204
205 TEST(module_test, dynamic_format_args) {
206 fmt::dynamic_format_arg_store<fmt::format_context> dyn_store;
207 dyn_store.push_back(fmt::arg("a42", 42));
208 fmt::basic_format_args args = dyn_store;
209 EXPECT_FALSE(args.get(3));
210 EXPECT_TRUE(args.get(fmt::string_view("a42")));
211
212 fmt::dynamic_format_arg_store<fmt::wformat_context> wdyn_store;
213 wdyn_store.push_back(fmt::arg(L"a42", 42));
214 fmt::basic_format_args wargs = wdyn_store;
215 EXPECT_FALSE(wargs.get(3));
216 EXPECT_TRUE(wargs.get(fmt::wstring_view(L"a42")));
217 }
218
219 TEST(module_test, vformat) {
220 EXPECT_EQ("42", fmt::vformat("{}", fmt::make_format_args(42)));
221 EXPECT_EQ(L"42", fmt::vformat(fmt::to_string_view(L"{}"),
222 fmt::make_wformat_args(42)));
223 }
224
225 TEST(module_test, vformat_to) {
226 auto store = fmt::make_format_args(42);
227 std::string s;
228 fmt::vformat_to(std::back_inserter(s), "{}", store);
229 EXPECT_EQ("42", s);
230
231 char buffer[4] = {0};
232 fmt::vformat_to(buffer, "{:}", store);
233 EXPECT_EQ("42", std::string_view(buffer));
234
235 auto wstore = fmt::make_wformat_args(42);
236 std::wstring w;
237 fmt::vformat_to(std::back_inserter(w), L"{}", wstore);
238 EXPECT_EQ(L"42", w);
239
240 wchar_t wbuffer[4] = {0};
241 fmt::vformat_to(wbuffer, L"{:}", wstore);
242 EXPECT_EQ(L"42", std::wstring_view(wbuffer));
243 }
244
245 TEST(module_test, vformat_to_n) {
246 auto store = fmt::make_format_args(12345);
247 std::string s;
248 auto result = fmt::vformat_to_n(std::back_inserter(s), 1, "{}", store);
249 char buffer[4] = {0};
250 fmt::vformat_to_n(buffer, 3, "{:}", store);
251
252 auto wstore = fmt::make_wformat_args(12345);
253 std::wstring w;
254 auto wresult = fmt::vformat_to_n(std::back_inserter(w), 1,
255 fmt::to_string_view(L"{}"), wstore);
256 wchar_t wbuffer[4] = {0};
257 fmt::vformat_to_n(wbuffer, 3, fmt::to_string_view(L"{:}"), wstore);
258 }
259
260 std::string as_string(std::wstring_view text) {
261 return {reinterpret_cast<const char*>(text.data()),
262 text.size() * sizeof(text[0])};
263 }
264
265 TEST(module_test, print) {
266 EXPECT_WRITE(stdout, fmt::print("{}µ", 42), "42µ");
267 EXPECT_WRITE(stderr, fmt::print(stderr, "{}µ", 4.2), "4.2µ");
268 if (false) {
269 EXPECT_WRITE(stdout, fmt::print(L"{}µ", 42), as_string(L"42µ"));
270 EXPECT_WRITE(stderr, fmt::print(stderr, L"{}µ", 4.2), as_string(L"4.2µ"));
271 }
272 }
273
274 TEST(module_test, vprint) {
275 EXPECT_WRITE(stdout, fmt::vprint("{:}µ", fmt::make_format_args(42)), "42µ");
276 EXPECT_WRITE(stderr, fmt::vprint(stderr, "{}", fmt::make_format_args(4.2)),
277 "4.2");
278 if (false) {
279 EXPECT_WRITE(stdout, fmt::vprint(L"{:}µ", fmt::make_wformat_args(42)),
280 as_string(L"42µ"));
281 EXPECT_WRITE(stderr, fmt::vprint(stderr, L"{}", fmt::make_wformat_args(42)),
282 as_string(L"42"));
283 }
284 }
285
286 TEST(module_test, named_args) {
287 EXPECT_EQ("42", fmt::format("{answer}", fmt::arg("answer", 42)));
288 EXPECT_EQ(L"42", fmt::format(L"{answer}", fmt::arg(L"answer", 42)));
289 }
290
291 TEST(module_test, literals) {
292 using namespace fmt::literals;
293 EXPECT_EQ("42", fmt::format("{answer}", "answer"_a = 42));
294 EXPECT_EQ("42", "{}"_format(42));
295 EXPECT_EQ(L"42", fmt::format(L"{answer}", L"answer"_a = 42));
296 EXPECT_EQ(L"42", L"{}"_format(42));
297 }
298
299 TEST(module_test, locale) {
300 auto store = fmt::make_format_args(4.2);
301 const auto classic = std::locale::classic();
302 EXPECT_EQ("4.2", fmt::format(classic, "{:L}", 4.2));
303 EXPECT_EQ("4.2", fmt::vformat(classic, "{:L}", store));
304 std::string s;
305 fmt::vformat_to(std::back_inserter(s), classic, "{:L}", store);
306 EXPECT_EQ("4.2", s);
307 EXPECT_EQ("4.2", fmt::format("{:L}", 4.2));
308
309 auto wstore = fmt::make_wformat_args(4.2);
310 EXPECT_EQ(L"4.2", fmt::format(classic, L"{:L}", 4.2));
311 EXPECT_EQ(L"4.2", fmt::vformat(classic, L"{:L}", wstore));
312 std::wstring w;
313 fmt::vformat_to(std::back_inserter(w), classic, L"{:L}", wstore);
314 EXPECT_EQ(L"4.2", w);
315 EXPECT_EQ(L"4.2", fmt::format(L"{:L}", 4.2));
316 }
317
318 TEST(module_test, string_view) {
319 fmt::string_view nsv("fmt");
320 EXPECT_EQ("fmt", nsv);
321 EXPECT_TRUE(fmt::string_view("fmt") == nsv);
322
323 fmt::wstring_view wsv(L"fmt");
324 EXPECT_EQ(L"fmt", wsv);
325 EXPECT_TRUE(fmt::wstring_view(L"fmt") == wsv);
326 }
327
328 TEST(module_test, memory_buffer) {
329 fmt::basic_memory_buffer<char, fmt::inline_buffer_size> buffer;
330 fmt::format_to(buffer, "{}", "42");
331 EXPECT_EQ("42", to_string(buffer));
332 fmt::memory_buffer nbuffer(std::move(buffer));
333 EXPECT_EQ("42", to_string(nbuffer));
334 buffer = std::move(nbuffer);
335 EXPECT_EQ("42", to_string(buffer));
336 nbuffer.clear();
337 EXPECT_EQ(0u, to_string(nbuffer).size());
338
339 fmt::wmemory_buffer wbuffer;
340 EXPECT_EQ(0u, to_string(wbuffer).size());
341 }
342
343 TEST(module_test, is_char) {
344 EXPECT_TRUE(fmt::is_char<char>());
345 EXPECT_TRUE(fmt::is_char<wchar_t>());
346 EXPECT_TRUE(fmt::is_char<char8_t>());
347 EXPECT_TRUE(fmt::is_char<char16_t>());
348 EXPECT_TRUE(fmt::is_char<char32_t>());
349 EXPECT_FALSE(fmt::is_char<signed char>());
350 }
351
352 TEST(module_test, ptr) {
353 uintptr_t answer = 42;
354 auto p = std::bit_cast<int*>(answer);
355 EXPECT_EQ("0x2a", fmt::to_string(fmt::ptr(p)));
356 std::unique_ptr<int> up(p);
357 EXPECT_EQ("0x2a", fmt::to_string(fmt::ptr(up)));
358 up.release();
359 auto sp = std::make_shared<int>(0);
360 p = sp.get();
361 EXPECT_EQ(fmt::to_string(fmt::ptr(p)), fmt::to_string(fmt::ptr(sp)));
362 }
363
364 TEST(module_test, errors) {
365 auto store = fmt::make_format_args(42);
366 EXPECT_THROW(throw fmt::format_error("oops"), std::exception);
367 EXPECT_THROW(throw fmt::vsystem_error(0, "{}", store), std::system_error);
368 EXPECT_THROW(throw fmt::system_error(0, "{}", 42), std::system_error);
369
370 fmt::memory_buffer buffer;
371 fmt::format_system_error(buffer, 0, "oops");
372 auto oops = to_string(buffer);
373 EXPECT_TRUE(oops.size() > 0);
374 EXPECT_WRITE(stderr, fmt::report_system_error(0, "oops"), oops + '\n');
375
376 #ifdef _WIN32
377 EXPECT_THROW(throw fmt::vwindows_error(0, "{}", store), std::system_error);
378 EXPECT_THROW(throw fmt::windows_error(0, "{}", 42), std::system_error);
379 output_redirect redirect(stderr);
380 fmt::report_windows_error(0, "oops");
381 EXPECT_TRUE(redirect.restore_and_read().size() > 0);
382 #endif
383 }
384
385 TEST(module_test, error_code) {
386 EXPECT_EQ("generic:42",
387 fmt::format("{0}", std::error_code(42, std::generic_category())));
388 EXPECT_EQ("system:42",
389 fmt::format("{0}", std::error_code(42, fmt::system_category())));
390 EXPECT_EQ(L"generic:42",
391 fmt::format(L"{0}", std::error_code(42, std::generic_category())));
392 }
393
394 TEST(module_test, format_int) {
395 fmt::format_int sanswer(42);
396 EXPECT_EQ("42", fmt::string_view(sanswer.data(), sanswer.size()));
397 fmt::format_int uanswer(42u);
398 EXPECT_EQ("42", fmt::string_view(uanswer.data(), uanswer.size()));
399 }
400
401 struct test_formatter : fmt::formatter<char> {
402 bool check() { return true; }
403 };
404
405 struct test_dynamic_formatter : fmt::dynamic_formatter<> {
406 bool check() { return true; }
407 };
408
409 TEST(module_test, formatter) {
410 EXPECT_TRUE(test_formatter{}.check());
411 EXPECT_TRUE(test_dynamic_formatter{}.check());
412 }
413
414 TEST(module_test, join) {
415 int arr[3] = {1, 2, 3};
416 std::vector<double> vec{1.0, 2.0, 3.0};
417 std::initializer_list<int> il{1, 2, 3};
418 auto sep = fmt::to_string_view(", ");
419 EXPECT_EQ("1, 2, 3", to_string(fmt::join(arr + 0, arr + 3, sep)));
420 EXPECT_EQ("1, 2, 3", to_string(fmt::join(arr, sep)));
421 EXPECT_EQ("1, 2, 3", to_string(fmt::join(vec.begin(), vec.end(), sep)));
422 EXPECT_EQ("1, 2, 3", to_string(fmt::join(vec, sep)));
423 EXPECT_EQ("1, 2, 3", to_string(fmt::join(il, sep)));
424
425 auto wsep = fmt::to_string_view(L", ");
426 EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(arr + 0, arr + 3, wsep)));
427 EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(arr, wsep)));
428 EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(il, wsep)));
429 }
430
431 TEST(module_test, time) {
432 auto time_now = std::time(nullptr);
433 EXPECT_TRUE(fmt::localtime(time_now).tm_year > 120);
434 EXPECT_TRUE(fmt::gmtime(time_now).tm_year > 120);
435 auto chrono_now = std::chrono::system_clock::now();
436 EXPECT_TRUE(fmt::localtime(chrono_now).tm_year > 120);
437 EXPECT_TRUE(fmt::gmtime(chrono_now).tm_year > 120);
438 }
439
440 TEST(module_test, time_point) {
441 auto now = std::chrono::system_clock::now();
442 std::string_view past("2021-05-20 10:30:15");
443 EXPECT_TRUE(past < fmt::format("{:%Y-%m-%d %H:%M:%S}", now));
444 std::wstring_view wpast(L"2021-05-20 10:30:15");
445 EXPECT_TRUE(wpast < fmt::format(L"{:%Y-%m-%d %H:%M:%S}", now));
446 }
447
448 TEST(module_test, time_duration) {
449 using us = std::chrono::duration<double, std::micro>;
450 EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds{42}));
451 EXPECT_EQ("4.2µs", fmt::format("{:3.1}", us{4.234}));
452 EXPECT_EQ("4.2µs", fmt::format(std::locale::classic(), "{:L}", us{4.2}));
453
454 EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds{42}));
455 EXPECT_EQ(L"4.2µs", fmt::format(L"{:3.1}", us{4.234}));
456 EXPECT_EQ(L"4.2µs", fmt::format(std::locale::classic(), L"{:L}", us{4.2}));
457 }
458
459 TEST(module_test, weekday) {
460 EXPECT_EQ("Mon", fmt::format(std::locale::classic(), "{}", fmt::weekday(1)));
461 }
462
463 TEST(module_test, to_string_view) {
464 using fmt::to_string_view;
465 fmt::string_view nsv{to_string_view("42")};
466 EXPECT_EQ("42", nsv);
467 fmt::wstring_view wsv{to_string_view(L"42")};
468 EXPECT_EQ(L"42", wsv);
469 }
470
471 TEST(module_test, printf) {
472 EXPECT_WRITE(stdout, fmt::printf("%f", 42.123456), "42.123456");
473 EXPECT_WRITE(stdout, fmt::printf("%d", 42), "42");
474 if (false) {
475 EXPECT_WRITE(stdout, fmt::printf(L"%f", 42.123456),
476 as_string(L"42.123456"));
477 EXPECT_WRITE(stdout, fmt::printf(L"%d", 42), as_string(L"42"));
478 }
479 }
480
481 TEST(module_test, fprintf) {
482 EXPECT_WRITE(stderr, fmt::fprintf(stderr, "%d", 42), "42");
483 std::ostringstream os;
484 fmt::fprintf(os, "%s", "bla");
485 EXPECT_EQ("bla", os.str());
486
487 EXPECT_WRITE(stderr, fmt::fprintf(stderr, L"%d", 42), as_string(L"42"));
488 std::wostringstream ws;
489 fmt::fprintf(ws, L"%s", L"bla");
490 EXPECT_EQ(L"bla", ws.str());
491 }
492
493 TEST(module_test, sprintf) {
494 EXPECT_EQ("42", fmt::sprintf("%d", 42));
495 EXPECT_EQ(L"42", fmt::sprintf(L"%d", 42));
496 }
497
498 TEST(module_test, vprintf) {
499 EXPECT_WRITE(stdout, fmt::vprintf("%d", fmt::make_printf_args(42)), "42");
500 if (false) {
501 EXPECT_WRITE(stdout, fmt::vprintf(L"%d", fmt::make_wprintf_args(42)),
502 as_string(L"42"));
503 }
504 }
505
506 TEST(module_test, vfprintf) {
507 auto args = fmt::make_printf_args(42);
508 EXPECT_WRITE(stderr, fmt::vfprintf(stderr, "%d", args), "42");
509 std::ostringstream os;
510 fmt::vfprintf(os, "%d", args);
511 EXPECT_EQ("42", os.str());
512 auto wargs = fmt::make_wprintf_args(42);
513 if (false) {
514 EXPECT_WRITE(stderr, fmt::vfprintf(stderr, L"%d", wargs), as_string(L"42"));
515 }
516 std::wostringstream ws;
517 fmt::vfprintf(ws, L"%d", wargs);
518 EXPECT_EQ(L"42", ws.str());
519 }
520
521 TEST(module_test, vsprintf) {
522 EXPECT_EQ("42", fmt::vsprintf("%d", fmt::make_printf_args(42)));
523 EXPECT_EQ(L"42", fmt::vsprintf(L"%d", fmt::make_wprintf_args(42)));
524 }
525
526 TEST(module_test, color) {
527 auto fg_check = fg(fmt::rgb(255, 200, 30));
528 auto bg_check = bg(fmt::color::dark_slate_gray) | fmt::emphasis::italic;
529 auto emphasis_check = fmt::emphasis::underline | fmt::emphasis::bold;
530 EXPECT_EQ("\x1B[30m42\x1B[0m",
531 fmt::format(fg(fmt::terminal_color::black), "{}", 42));
532 EXPECT_EQ(L"\x1B[30m42\x1B[0m",
533 fmt::format(fg(fmt::terminal_color::black), L"{}", 42));
534 }
535
536 TEST(module_test, cstring_view) {
537 auto s = "fmt";
538 EXPECT_EQ(s, fmt::cstring_view(s).c_str());
539 auto w = L"fmt";
540 EXPECT_EQ(w, fmt::wcstring_view(w).c_str());
541 }
542
543 TEST(module_test, buffered_file) {
544 EXPECT_TRUE(fmt::buffered_file{}.get() == nullptr);
545 }
546
547 TEST(module_test, output_file) {
548 fmt::ostream out = fmt::output_file("module-test", fmt::buffer_size = 1);
549 out.close();
550 }
551
552 struct custom_context {
553 using char_type = char;
554 using parse_context_type = fmt::format_parse_context;
555 };
556
557 TEST(module_test, custom_context) {
558 fmt::basic_format_arg<custom_context> custom_arg;
559 EXPECT_TRUE(!custom_arg);
560 }
561
562 struct disabled_formatter {};
563
564 TEST(module_test, has_formatter) {
565 EXPECT_FALSE(
566 (fmt::has_formatter<disabled_formatter, fmt::format_context>::value));
567 }
568
569 TEST(module_test, is_formattable) {
570 EXPECT_FALSE(fmt::is_formattable<disabled_formatter>::value);
571 }
572
573 TEST(module_test, compile_format_string) {
574 using namespace fmt::literals;
575 EXPECT_EQ("42", fmt::format("{0:x}"_cf, 0x42));
576 EXPECT_EQ(L"42", fmt::format(L"{:}"_cf, 42));
577 EXPECT_EQ("4.2", fmt::format("{arg:3.1f}"_cf, "arg"_a = 4.2));
578 EXPECT_EQ(L" 42", fmt::format(L"{arg:>3}"_cf, L"arg"_a = L"42"));
579 }
+0
-18
source/misc/embedded_libs/fmt-8.1.1/test/noexception-test.cc less more
0 // Formatting library for C++ - Noexception tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/args.h"
8 #include "fmt/chrono.h"
9 #include "fmt/color.h"
10 #include "fmt/compile.h"
11 #include "fmt/core.h"
12 #include "fmt/format.h"
13 #include "fmt/os.h"
14 #include "fmt/ostream.h"
15 #include "fmt/printf.h"
16 #include "fmt/ranges.h"
17 #include "fmt/xchar.h"
+0
-551
source/misc/embedded_libs/fmt-8.1.1/test/os-test.cc less more
0 // Formatting library for C++ - tests of the OS-specific functionality
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/os.h"
8
9 #include <cstdlib> // std::exit
10 #include <cstring>
11 #include <memory>
12
13 #include "gtest-extra.h"
14 #include "util.h"
15
16 #ifdef fileno
17 # undef fileno
18 #endif
19
20 using fmt::buffered_file;
21 using testing::HasSubstr;
22 using wstring_view = fmt::basic_string_view<wchar_t>;
23
24 #ifdef _WIN32
25
26 # include <windows.h>
27
28 TEST(util_test, utf16_to_utf8) {
29 auto s = std::string("ёжик");
30 fmt::detail::utf16_to_utf8 u(L"\x0451\x0436\x0438\x043A");
31 EXPECT_EQ(s, u.str());
32 EXPECT_EQ(s.size(), u.size());
33 }
34
35 TEST(util_test, utf16_to_utf8_empty_string) {
36 std::string s = "";
37 fmt::detail::utf16_to_utf8 u(L"");
38 EXPECT_EQ(s, u.str());
39 EXPECT_EQ(s.size(), u.size());
40 }
41
42 template <typename Converter, typename Char>
43 void check_utf_conversion_error(const char* message,
44 fmt::basic_string_view<Char> str =
45 fmt::basic_string_view<Char>(nullptr, 1)) {
46 fmt::memory_buffer out;
47 fmt::detail::format_windows_error(out, ERROR_INVALID_PARAMETER, message);
48 auto error = std::system_error(std::error_code());
49 try {
50 (Converter)(str);
51 } catch (const std::system_error& e) {
52 error = e;
53 }
54 EXPECT_EQ(ERROR_INVALID_PARAMETER, error.code().value());
55 EXPECT_THAT(error.what(), HasSubstr(fmt::to_string(out)));
56 }
57
58 TEST(util_test, utf16_to_utf8_error) {
59 check_utf_conversion_error<fmt::detail::utf16_to_utf8, wchar_t>(
60 "cannot convert string from UTF-16 to UTF-8");
61 }
62
63 TEST(util_test, utf16_to_utf8_convert) {
64 fmt::detail::utf16_to_utf8 u;
65 EXPECT_EQ(ERROR_INVALID_PARAMETER, u.convert(wstring_view(nullptr, 1)));
66 EXPECT_EQ(ERROR_INVALID_PARAMETER,
67 u.convert(wstring_view(L"foo", INT_MAX + 1u)));
68 }
69
70 TEST(os_test, format_std_error_code) {
71 EXPECT_EQ("generic:42",
72 fmt::format(FMT_STRING("{0}"),
73 std::error_code(42, std::generic_category())));
74 EXPECT_EQ("system:42",
75 fmt::format(FMT_STRING("{0}"),
76 std::error_code(42, fmt::system_category())));
77 EXPECT_EQ("system:-42",
78 fmt::format(FMT_STRING("{0}"),
79 std::error_code(-42, fmt::system_category())));
80 }
81
82 TEST(os_test, format_windows_error) {
83 LPWSTR message = nullptr;
84 auto result = FormatMessageW(
85 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
86 FORMAT_MESSAGE_IGNORE_INSERTS,
87 nullptr, ERROR_FILE_EXISTS, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
88 reinterpret_cast<LPWSTR>(&message), 0, nullptr);
89 fmt::detail::utf16_to_utf8 utf8_message(wstring_view(message, result - 2));
90 LocalFree(message);
91 fmt::memory_buffer actual_message;
92 fmt::detail::format_windows_error(actual_message, ERROR_FILE_EXISTS, "test");
93 EXPECT_EQ(fmt::format("test: {}", utf8_message.str()),
94 fmt::to_string(actual_message));
95 actual_message.resize(0);
96 }
97
98 TEST(os_test, format_long_windows_error) {
99 LPWSTR message = nullptr;
100 // this error code is not available on all Windows platforms and
101 // Windows SDKs, so do not fail the test if the error string cannot
102 // be retrieved.
103 int provisioning_not_allowed = 0x80284013L; // TBS_E_PROVISIONING_NOT_ALLOWED
104 auto result = FormatMessageW(
105 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
106 FORMAT_MESSAGE_IGNORE_INSERTS,
107 nullptr, static_cast<DWORD>(provisioning_not_allowed),
108 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
109 reinterpret_cast<LPWSTR>(&message), 0, nullptr);
110 if (result == 0) {
111 LocalFree(message);
112 return;
113 }
114 fmt::detail::utf16_to_utf8 utf8_message(wstring_view(message, result - 2));
115 LocalFree(message);
116 fmt::memory_buffer actual_message;
117 fmt::detail::format_windows_error(actual_message, provisioning_not_allowed,
118 "test");
119 EXPECT_EQ(fmt::format("test: {}", utf8_message.str()),
120 fmt::to_string(actual_message));
121 }
122
123 TEST(os_test, windows_error) {
124 auto error = std::system_error(std::error_code());
125 try {
126 throw fmt::windows_error(ERROR_FILE_EXISTS, "test {}", "error");
127 } catch (const std::system_error& e) {
128 error = e;
129 }
130 fmt::memory_buffer message;
131 fmt::detail::format_windows_error(message, ERROR_FILE_EXISTS, "test error");
132 EXPECT_THAT(error.what(), HasSubstr(to_string(message)));
133 EXPECT_EQ(ERROR_FILE_EXISTS, error.code().value());
134 }
135
136 TEST(os_test, report_windows_error) {
137 fmt::memory_buffer out;
138 fmt::detail::format_windows_error(out, ERROR_FILE_EXISTS, "test error");
139 out.push_back('\n');
140 EXPECT_WRITE(stderr,
141 fmt::report_windows_error(ERROR_FILE_EXISTS, "test error"),
142 fmt::to_string(out));
143 }
144
145 #endif // _WIN32
146
147 #if FMT_USE_FCNTL
148
149 using fmt::file;
150
151 bool isclosed(int fd) {
152 char buffer;
153 auto result = std::streamsize();
154 SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1)));
155 return result == -1 && errno == EBADF;
156 }
157
158 // Opens a file for reading.
159 file open_file() {
160 file read_end, write_end;
161 file::pipe(read_end, write_end);
162 write_end.write(file_content, std::strlen(file_content));
163 write_end.close();
164 return read_end;
165 }
166
167 // Attempts to write a string to a file.
168 void write(file& f, fmt::string_view s) {
169 size_t num_chars_left = s.size();
170 const char* ptr = s.data();
171 do {
172 size_t count = f.write(ptr, num_chars_left);
173 ptr += count;
174 // We can't write more than size_t bytes since num_chars_left
175 // has type size_t.
176 num_chars_left -= count;
177 } while (num_chars_left != 0);
178 }
179
180 TEST(buffered_file_test, default_ctor) {
181 auto f = buffered_file();
182 EXPECT_TRUE(f.get() == nullptr);
183 }
184
185 TEST(buffered_file_test, move_ctor) {
186 buffered_file bf = open_buffered_file();
187 FILE* fp = bf.get();
188 EXPECT_TRUE(fp != nullptr);
189 buffered_file bf2(std::move(bf));
190 EXPECT_EQ(fp, bf2.get());
191 EXPECT_TRUE(bf.get() == nullptr);
192 }
193
194 TEST(buffered_file_test, move_assignment) {
195 buffered_file bf = open_buffered_file();
196 FILE* fp = bf.get();
197 EXPECT_TRUE(fp != nullptr);
198 buffered_file bf2;
199 bf2 = std::move(bf);
200 EXPECT_EQ(fp, bf2.get());
201 EXPECT_TRUE(bf.get() == nullptr);
202 }
203
204 TEST(buffered_file_test, move_assignment_closes_file) {
205 buffered_file bf = open_buffered_file();
206 buffered_file bf2 = open_buffered_file();
207 int old_fd = bf2.fileno();
208 bf2 = std::move(bf);
209 EXPECT_TRUE(isclosed(old_fd));
210 }
211
212 TEST(buffered_file_test, move_from_temporary_in_ctor) {
213 FILE* fp = nullptr;
214 buffered_file f = open_buffered_file(&fp);
215 EXPECT_EQ(fp, f.get());
216 }
217
218 TEST(buffered_file_test, move_from_temporary_in_assignment) {
219 FILE* fp = nullptr;
220 auto f = buffered_file();
221 f = open_buffered_file(&fp);
222 EXPECT_EQ(fp, f.get());
223 }
224
225 TEST(buffered_file_test, move_from_temporary_in_assignment_closes_file) {
226 buffered_file f = open_buffered_file();
227 int old_fd = f.fileno();
228 f = open_buffered_file();
229 EXPECT_TRUE(isclosed(old_fd));
230 }
231
232 TEST(buffered_file_test, close_file_in_dtor) {
233 int fd = 0;
234 {
235 buffered_file f = open_buffered_file();
236 fd = f.fileno();
237 }
238 EXPECT_TRUE(isclosed(fd));
239 }
240
241 TEST(buffered_file_test, close_error_in_dtor) {
242 auto f =
243 std::unique_ptr<buffered_file>(new buffered_file(open_buffered_file()));
244 EXPECT_WRITE(
245 stderr,
246 {
247 // The close function must be called inside EXPECT_WRITE,
248 // otherwise the system may recycle closed file descriptor when
249 // redirecting the output in EXPECT_STDERR and the second close
250 // will break output redirection.
251 FMT_POSIX(close(f->fileno()));
252 SUPPRESS_ASSERT(f.reset(nullptr));
253 },
254 system_error_message(EBADF, "cannot close file") + "\n");
255 }
256
257 TEST(buffered_file_test, close) {
258 buffered_file f = open_buffered_file();
259 int fd = f.fileno();
260 f.close();
261 EXPECT_TRUE(f.get() == nullptr);
262 EXPECT_TRUE(isclosed(fd));
263 }
264
265 TEST(buffered_file_test, close_error) {
266 buffered_file f = open_buffered_file();
267 FMT_POSIX(close(f.fileno()));
268 EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
269 EXPECT_TRUE(f.get() == nullptr);
270 }
271
272 TEST(buffered_file_test, fileno) {
273 auto f = open_buffered_file();
274 EXPECT_TRUE(f.fileno() != -1);
275 file copy = file::dup(f.fileno());
276 EXPECT_READ(copy, file_content);
277 }
278
279 TEST(ostream_test, move) {
280 fmt::ostream out = fmt::output_file("test-file");
281 fmt::ostream moved(std::move(out));
282 moved.print("hello");
283 }
284
285 TEST(ostream_test, move_while_holding_data) {
286 {
287 fmt::ostream out = fmt::output_file("test-file");
288 out.print("Hello, ");
289 fmt::ostream moved(std::move(out));
290 moved.print("world!\n");
291 }
292 {
293 file in("test-file", file::RDONLY);
294 EXPECT_READ(in, "Hello, world!\n");
295 }
296 }
297
298 TEST(ostream_test, print) {
299 fmt::ostream out = fmt::output_file("test-file");
300 out.print("The answer is {}.\n",
301 fmt::join(std::initializer_list<int>{42}, ", "));
302 out.close();
303 file in("test-file", file::RDONLY);
304 EXPECT_READ(in, "The answer is 42.\n");
305 }
306
307 TEST(ostream_test, buffer_boundary) {
308 auto str = std::string(4096, 'x');
309 fmt::ostream out = fmt::output_file("test-file");
310 out.print("{}", str);
311 out.print("{}", str);
312 out.close();
313 file in("test-file", file::RDONLY);
314 EXPECT_READ(in, str + str);
315 }
316
317 TEST(ostream_test, buffer_size) {
318 fmt::ostream out = fmt::output_file("test-file", fmt::buffer_size = 1);
319 out.print("{}", "foo");
320 out.close();
321 file in("test-file", file::RDONLY);
322 EXPECT_READ(in, "foo");
323 }
324
325 TEST(ostream_test, truncate) {
326 {
327 fmt::ostream out = fmt::output_file("test-file");
328 out.print("0123456789");
329 }
330 {
331 fmt::ostream out = fmt::output_file("test-file");
332 out.print("foo");
333 }
334 file in("test-file", file::RDONLY);
335 EXPECT_EQ("foo", read(in, 4));
336 }
337
338 TEST(ostream_test, flush) {
339 auto out = fmt::output_file("test-file");
340 out.print("x");
341 out.flush();
342 auto in = fmt::file("test-file", file::RDONLY);
343 EXPECT_READ(in, "x");
344 }
345
346 TEST(file_test, default_ctor) {
347 file f;
348 EXPECT_EQ(-1, f.descriptor());
349 }
350
351 TEST(file_test, open_buffered_file_in_ctor) {
352 FILE* fp = safe_fopen("test-file", "w");
353 std::fputs(file_content, fp);
354 std::fclose(fp);
355 file f("test-file", file::RDONLY);
356 // Check if the file is open by reading one character from it.
357 char buffer;
358 bool isopen = FMT_POSIX(read(f.descriptor(), &buffer, 1)) == 1;
359 ASSERT_TRUE(isopen);
360 }
361
362 TEST(file_test, open_buffered_file_error) {
363 EXPECT_SYSTEM_ERROR(file("nonexistent", file::RDONLY), ENOENT,
364 "cannot open file nonexistent");
365 }
366
367 TEST(file_test, move_ctor) {
368 file f = open_file();
369 int fd = f.descriptor();
370 EXPECT_NE(-1, fd);
371 file f2(std::move(f));
372 EXPECT_EQ(fd, f2.descriptor());
373 EXPECT_EQ(-1, f.descriptor());
374 }
375
376 TEST(file_test, move_assignment) {
377 file f = open_file();
378 int fd = f.descriptor();
379 EXPECT_NE(-1, fd);
380 file f2;
381 f2 = std::move(f);
382 EXPECT_EQ(fd, f2.descriptor());
383 EXPECT_EQ(-1, f.descriptor());
384 }
385
386 TEST(file_test, move_assignment_closes_file) {
387 file f = open_file();
388 file f2 = open_file();
389 int old_fd = f2.descriptor();
390 f2 = std::move(f);
391 EXPECT_TRUE(isclosed(old_fd));
392 }
393
394 file open_buffered_file(int& fd) {
395 file f = open_file();
396 fd = f.descriptor();
397 return f;
398 }
399
400 TEST(file_test, move_from_temporary_in_ctor) {
401 int fd = 0xdead;
402 file f(open_buffered_file(fd));
403 EXPECT_EQ(fd, f.descriptor());
404 }
405
406 TEST(file_test, move_from_temporary_in_assignment) {
407 int fd = 0xdead;
408 file f;
409 f = open_buffered_file(fd);
410 EXPECT_EQ(fd, f.descriptor());
411 }
412
413 TEST(file_test, move_from_temporary_in_assignment_closes_file) {
414 int fd = 0xdead;
415 file f = open_file();
416 int old_fd = f.descriptor();
417 f = open_buffered_file(fd);
418 EXPECT_TRUE(isclosed(old_fd));
419 }
420
421 TEST(file_test, close_file_in_dtor) {
422 int fd = 0;
423 {
424 file f = open_file();
425 fd = f.descriptor();
426 }
427 EXPECT_TRUE(isclosed(fd));
428 }
429
430 TEST(file_test, close_error_in_dtor) {
431 std::unique_ptr<file> f(new file(open_file()));
432 EXPECT_WRITE(
433 stderr,
434 {
435 // The close function must be called inside EXPECT_WRITE,
436 // otherwise the system may recycle closed file descriptor when
437 // redirecting the output in EXPECT_STDERR and the second close
438 // will break output redirection.
439 FMT_POSIX(close(f->descriptor()));
440 SUPPRESS_ASSERT(f.reset(nullptr));
441 },
442 system_error_message(EBADF, "cannot close file") + "\n");
443 }
444
445 TEST(file_test, close) {
446 file f = open_file();
447 int fd = f.descriptor();
448 f.close();
449 EXPECT_EQ(-1, f.descriptor());
450 EXPECT_TRUE(isclosed(fd));
451 }
452
453 TEST(file_test, close_error) {
454 file f = open_file();
455 FMT_POSIX(close(f.descriptor()));
456 EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
457 EXPECT_EQ(-1, f.descriptor());
458 }
459
460 TEST(file_test, read) {
461 file f = open_file();
462 EXPECT_READ(f, file_content);
463 }
464
465 TEST(file_test, read_error) {
466 file f("test-file", file::WRONLY);
467 char buf;
468 // We intentionally read from a file opened in the write-only mode to
469 // cause error.
470 EXPECT_SYSTEM_ERROR(f.read(&buf, 1), EBADF, "cannot read from file");
471 }
472
473 TEST(file_test, write) {
474 file read_end, write_end;
475 file::pipe(read_end, write_end);
476 write(write_end, "test");
477 write_end.close();
478 EXPECT_READ(read_end, "test");
479 }
480
481 TEST(file_test, write_error) {
482 file f("test-file", file::RDONLY);
483 // We intentionally write to a file opened in the read-only mode to
484 // cause error.
485 EXPECT_SYSTEM_ERROR(f.write(" ", 1), EBADF, "cannot write to file");
486 }
487
488 TEST(file_test, dup) {
489 file f = open_file();
490 file copy = file::dup(f.descriptor());
491 EXPECT_NE(f.descriptor(), copy.descriptor());
492 EXPECT_EQ(file_content, read(copy, std::strlen(file_content)));
493 }
494
495 # ifndef __COVERITY__
496 TEST(file_test, dup_error) {
497 int value = -1;
498 EXPECT_SYSTEM_ERROR_NOASSERT(file::dup(value), EBADF,
499 "cannot duplicate file descriptor -1");
500 }
501 # endif
502
503 TEST(file_test, dup2) {
504 file f = open_file();
505 file copy = open_file();
506 f.dup2(copy.descriptor());
507 EXPECT_NE(f.descriptor(), copy.descriptor());
508 EXPECT_READ(copy, file_content);
509 }
510
511 TEST(file_test, dup2_error) {
512 file f = open_file();
513 EXPECT_SYSTEM_ERROR_NOASSERT(
514 f.dup2(-1), EBADF,
515 fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor()));
516 }
517
518 TEST(file_test, dup2_noexcept) {
519 file f = open_file();
520 file copy = open_file();
521 std::error_code ec;
522 f.dup2(copy.descriptor(), ec);
523 EXPECT_EQ(ec.value(), 0);
524 EXPECT_NE(f.descriptor(), copy.descriptor());
525 EXPECT_READ(copy, file_content);
526 }
527
528 TEST(file_test, dup2_noexcept_error) {
529 file f = open_file();
530 std::error_code ec;
531 SUPPRESS_ASSERT(f.dup2(-1, ec));
532 EXPECT_EQ(EBADF, ec.value());
533 }
534
535 TEST(file_test, pipe) {
536 file read_end, write_end;
537 file::pipe(read_end, write_end);
538 EXPECT_NE(-1, read_end.descriptor());
539 EXPECT_NE(-1, write_end.descriptor());
540 write(write_end, "test");
541 EXPECT_READ(read_end, "test");
542 }
543
544 TEST(file_test, fdopen) {
545 file read_end, write_end;
546 file::pipe(read_end, write_end);
547 int read_fd = read_end.descriptor();
548 EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get())));
549 }
550 #endif // FMT_USE_FCNTL
+0
-301
source/misc/embedded_libs/fmt-8.1.1/test/ostream-test.cc less more
0 // Formatting library for C++ - std::ostream support tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/format.h"
8
9 using fmt::runtime;
10
11 struct test {};
12
13 // Test that there is no issues with specializations when fmt/ostream.h is
14 // included after fmt/format.h.
15 namespace fmt {
16 template <> struct formatter<test> : formatter<int> {
17 auto format(const test&, format_context& ctx) -> decltype(ctx.out()) {
18 return formatter<int>::format(42, ctx);
19 }
20 };
21 } // namespace fmt
22
23 #include <sstream>
24
25 #include "fmt/compile.h"
26 #include "fmt/ostream.h"
27 #include "fmt/ranges.h"
28 #include "gmock/gmock.h"
29 #include "gtest-extra.h"
30 #include "util.h"
31
32 std::ostream& operator<<(std::ostream& os, const date& d) {
33 os << d.year() << '-' << d.month() << '-' << d.day();
34 return os;
35 }
36
37 std::wostream& operator<<(std::wostream& os, const date& d) {
38 os << d.year() << L'-' << d.month() << L'-' << d.day();
39 return os;
40 }
41
42 // Make sure that overloaded comma operators do no harm to is_streamable.
43 struct type_with_comma_op {};
44 template <typename T> void operator,(type_with_comma_op, const T&);
45 template <typename T> type_with_comma_op operator<<(T&, const date&);
46
47 enum streamable_enum {};
48
49 std::ostream& operator<<(std::ostream& os, streamable_enum) {
50 return os << "streamable_enum";
51 }
52
53 enum unstreamable_enum {};
54
55 TEST(ostream_test, enum) {
56 EXPECT_EQ("streamable_enum", fmt::format("{}", streamable_enum()));
57 EXPECT_EQ("0", fmt::format("{}", unstreamable_enum()));
58 }
59
60 TEST(ostream_test, format) {
61 EXPECT_EQ("a string", fmt::format("{0}", test_string("a string")));
62 EXPECT_EQ("The date is 2012-12-9",
63 fmt::format("The date is {0}", date(2012, 12, 9)));
64 }
65
66 TEST(ostream_test, format_specs) {
67 using fmt::format_error;
68 EXPECT_EQ("def ", fmt::format("{0:<5}", test_string("def")));
69 EXPECT_EQ(" def", fmt::format("{0:>5}", test_string("def")));
70 EXPECT_EQ(" def ", fmt::format("{0:^5}", test_string("def")));
71 EXPECT_EQ("def**", fmt::format("{0:*<5}", test_string("def")));
72 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), test_string()),
73 format_error, "format specifier requires numeric argument");
74 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), test_string()),
75 format_error, "format specifier requires numeric argument");
76 EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), test_string()),
77 format_error, "format specifier requires numeric argument");
78 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#}"), test_string()),
79 format_error, "format specifier requires numeric argument");
80 EXPECT_THROW_MSG((void)fmt::format(runtime("{0:05}"), test_string()),
81 format_error, "format specifier requires numeric argument");
82 EXPECT_EQ("test ", fmt::format("{0:13}", test_string("test")));
83 EXPECT_EQ("test ", fmt::format("{0:{1}}", test_string("test"), 13));
84 EXPECT_EQ("te", fmt::format("{0:.2}", test_string("test")));
85 EXPECT_EQ("te", fmt::format("{0:.{1}}", test_string("test"), 2));
86 }
87
88 struct empty_test {};
89 std::ostream& operator<<(std::ostream& os, empty_test) { return os << ""; }
90
91 TEST(ostream_test, empty_custom_output) {
92 EXPECT_EQ("", fmt::format("{}", empty_test()));
93 }
94
95 TEST(ostream_test, print) {
96 std::ostringstream os;
97 fmt::print(os, "Don't {}!", "panic");
98 EXPECT_EQ("Don't panic!", os.str());
99 }
100
101 TEST(ostream_test, write_to_ostream) {
102 std::ostringstream os;
103 fmt::memory_buffer buffer;
104 const char* foo = "foo";
105 buffer.append(foo, foo + std::strlen(foo));
106 fmt::detail::write_buffer(os, buffer);
107 EXPECT_EQ("foo", os.str());
108 }
109
110 TEST(ostream_test, write_to_ostream_max_size) {
111 auto max_size = fmt::detail::max_value<size_t>();
112 auto max_streamsize = fmt::detail::max_value<std::streamsize>();
113 if (max_size <= fmt::detail::to_unsigned(max_streamsize)) return;
114
115 struct test_buffer final : fmt::detail::buffer<char> {
116 explicit test_buffer(size_t size)
117 : fmt::detail::buffer<char>(nullptr, size, size) {}
118 void grow(size_t) override {}
119 } buffer(max_size);
120
121 struct mock_streambuf : std::streambuf {
122 MOCK_METHOD2(xsputn, std::streamsize(const void* s, std::streamsize n));
123 std::streamsize xsputn(const char* s, std::streamsize n) override {
124 const void* v = s;
125 return xsputn(v, n);
126 }
127 } streambuf;
128
129 struct test_ostream : std::ostream {
130 explicit test_ostream(mock_streambuf& output_buffer)
131 : std::ostream(&output_buffer) {}
132 } os(streambuf);
133
134 testing::InSequence sequence;
135 const char* data = nullptr;
136 using ustreamsize = std::make_unsigned<std::streamsize>::type;
137 ustreamsize size = max_size;
138 do {
139 auto n = std::min(size, fmt::detail::to_unsigned(max_streamsize));
140 EXPECT_CALL(streambuf, xsputn(data, static_cast<std::streamsize>(n)))
141 .WillOnce(testing::Return(max_streamsize));
142 data += n;
143 size -= n;
144 } while (size != 0);
145 fmt::detail::write_buffer(os, buffer);
146 }
147
148 TEST(ostream_test, join) {
149 int v[3] = {1, 2, 3};
150 EXPECT_EQ("1, 2, 3", fmt::format("{}", fmt::join(v, v + 3, ", ")));
151 }
152
153 TEST(ostream_test, join_fallback_formatter) {
154 auto strs = std::vector<test_string>{test_string("foo"), test_string("bar")};
155 EXPECT_EQ("foo, bar", fmt::format("{}", fmt::join(strs, ", ")));
156 }
157
158 #if FMT_USE_CONSTEXPR
159 TEST(ostream_test, constexpr_string) {
160 EXPECT_EQ("42", format(FMT_STRING("{}"), std::string("42")));
161 EXPECT_EQ("a string", format(FMT_STRING("{0}"), test_string("a string")));
162 }
163 #endif
164
165 namespace fmt_test {
166 struct abc {};
167
168 template <typename Output> Output& operator<<(Output& out, abc) {
169 return out << "abc";
170 }
171 } // namespace fmt_test
172
173 template <typename T> struct test_template {};
174
175 template <typename T>
176 std::ostream& operator<<(std::ostream& os, test_template<T>) {
177 return os << 1;
178 }
179
180 namespace fmt {
181 template <typename T> struct formatter<test_template<T>> : formatter<int> {
182 auto format(test_template<T>, format_context& ctx) -> decltype(ctx.out()) {
183 return formatter<int>::format(2, ctx);
184 }
185 };
186 } // namespace fmt
187
188 TEST(ostream_test, template) {
189 EXPECT_EQ("2", fmt::format("{}", test_template<int>()));
190 }
191
192 TEST(ostream_test, format_to_n) {
193 char buffer[4];
194 buffer[3] = 'x';
195 auto result = fmt::format_to_n(buffer, 3, "{}", fmt_test::abc());
196 EXPECT_EQ(3u, result.size);
197 EXPECT_EQ(buffer + 3, result.out);
198 EXPECT_EQ("abcx", fmt::string_view(buffer, 4));
199 result = fmt::format_to_n(buffer, 3, "x{}y", fmt_test::abc());
200 EXPECT_EQ(5u, result.size);
201 EXPECT_EQ(buffer + 3, result.out);
202 EXPECT_EQ("xabx", fmt::string_view(buffer, 4));
203 }
204
205 template <typename T> struct convertible {
206 T value;
207 explicit convertible(const T& val) : value(val) {}
208 operator T() const { return value; }
209 };
210
211 TEST(ostream_test, disable_builtin_ostream_operators) {
212 EXPECT_EQ("42", fmt::format("{:d}", convertible<unsigned short>(42)));
213 EXPECT_EQ("foo", fmt::format("{}", convertible<const char*>("foo")));
214 }
215
216 struct explicitly_convertible_to_string_like {
217 template <typename String,
218 typename = typename std::enable_if<std::is_constructible<
219 String, const char*, size_t>::value>::type>
220 explicit operator String() const {
221 return String("foo", 3u);
222 }
223 };
224
225 std::ostream& operator<<(std::ostream& os,
226 explicitly_convertible_to_string_like) {
227 return os << "bar";
228 }
229
230 TEST(ostream_test, format_explicitly_convertible_to_string_like) {
231 EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like()));
232 }
233
234 #ifdef FMT_USE_STRING_VIEW
235 struct explicitly_convertible_to_std_string_view {
236 explicit operator fmt::detail::std_string_view<char>() const {
237 return {"foo", 3u};
238 }
239 };
240
241 std::ostream& operator<<(std::ostream& os,
242 explicitly_convertible_to_std_string_view) {
243 return os << "bar";
244 }
245
246 TEST(ostream_test, format_explicitly_convertible_to_std_string_view) {
247 EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like()));
248 }
249 #endif // FMT_USE_STRING_VIEW
250
251 struct streamable_and_convertible_to_bool {
252 operator bool() const { return true; }
253 };
254
255 std::ostream& operator<<(std::ostream& os, streamable_and_convertible_to_bool) {
256 return os << "foo";
257 }
258
259 TEST(ostream_test, format_convertible_to_bool) {
260 // operator<< is intentionally not used because of potential ODR violations.
261 EXPECT_EQ(fmt::format("{}", streamable_and_convertible_to_bool()), "true");
262 }
263
264 struct copyfmt_test {};
265
266 std::ostream& operator<<(std::ostream& os, copyfmt_test) {
267 std::ios ios(nullptr);
268 ios.copyfmt(os);
269 return os << "foo";
270 }
271
272 TEST(ostream_test, copyfmt) {
273 EXPECT_EQ("foo", fmt::format("{}", copyfmt_test()));
274 }
275
276 TEST(ostream_test, to_string) {
277 EXPECT_EQ("abc", fmt::to_string(fmt_test::abc()));
278 }
279
280 TEST(ostream_test, range) {
281 auto strs = std::vector<test_string>{test_string("foo"), test_string("bar")};
282 EXPECT_EQ("[foo, bar]", fmt::format("{}", strs));
283 }
284
285 struct abstract {
286 virtual ~abstract() = default;
287 virtual void f() = 0;
288 friend std::ostream& operator<<(std::ostream& os, const abstract&) {
289 return os;
290 }
291 };
292
293 void format_abstract_compiles(const abstract& a) {
294 fmt::format(FMT_COMPILE("{}"), a);
295 }
296
297 TEST(ostream_test, is_formattable) {
298 EXPECT_TRUE(fmt::is_formattable<std::string>());
299 EXPECT_TRUE(fmt::is_formattable<fmt::detail::std_string_view<char>>());
300 }
+0
-540
source/misc/embedded_libs/fmt-8.1.1/test/posix-mock-test.cc less more
0 // Tests of the C++ interface to POSIX functions that require mocks
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 // Disable bogus MSVC warnings.
8 #ifndef _CRT_SECURE_NO_WARNINGS
9 # define _CRT_SECURE_NO_WARNINGS
10 #endif
11
12 #include "posix-mock.h"
13
14 #include <errno.h>
15 #include <fcntl.h>
16
17 #include <climits>
18 #include <memory>
19
20 #include "../src/os.cc"
21
22 #ifdef _WIN32
23 # include <io.h>
24 # undef max
25 #endif
26
27 #include "gmock/gmock.h"
28 #include "gtest-extra.h"
29 #include "util.h"
30
31 using fmt::buffered_file;
32
33 using testing::_;
34 using testing::Return;
35 using testing::StrEq;
36
37 template <typename Mock> struct scoped_mock : testing::StrictMock<Mock> {
38 scoped_mock() { Mock::instance = this; }
39 ~scoped_mock() { Mock::instance = nullptr; }
40 };
41
42 namespace {
43 int open_count;
44 int close_count;
45 int dup_count;
46 int dup2_count;
47 int fdopen_count;
48 int read_count;
49 int write_count;
50 int pipe_count;
51 int fopen_count;
52 int fclose_count;
53 int fileno_count;
54 size_t read_nbyte;
55 size_t write_nbyte;
56 bool sysconf_error;
57
58 enum { none, max_size, error } fstat_sim;
59 } // namespace
60
61 #define EMULATE_EINTR(func, error_result) \
62 if (func##_count != 0) { \
63 if (func##_count++ != 3) { \
64 errno = EINTR; \
65 return error_result; \
66 } \
67 }
68
69 #ifndef _MSC_VER
70 int test::open(const char* path, int oflag, int mode) {
71 EMULATE_EINTR(open, -1);
72 return ::open(path, oflag, mode);
73 }
74 #else
75 errno_t test::sopen_s(int* pfh, const char* filename, int oflag, int shflag,
76 int pmode) {
77 EMULATE_EINTR(open, EINTR);
78 return _sopen_s(pfh, filename, oflag, shflag, pmode);
79 }
80 #endif
81
82 #ifndef _WIN32
83
84 long test::sysconf(int name) {
85 long result = ::sysconf(name);
86 if (!sysconf_error) return result;
87 // Simulate an error.
88 errno = EINVAL;
89 return -1;
90 }
91
92 static off_t max_file_size() { return std::numeric_limits<off_t>::max(); }
93
94 int test::fstat(int fd, struct stat* buf) {
95 int result = ::fstat(fd, buf);
96 if (fstat_sim == max_size) buf->st_size = max_file_size();
97 return result;
98 }
99
100 #else
101
102 static LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); }
103
104 DWORD test::GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) {
105 if (fstat_sim == error) {
106 SetLastError(ERROR_ACCESS_DENIED);
107 return INVALID_FILE_SIZE;
108 }
109 if (fstat_sim == max_size) {
110 DWORD max = std::numeric_limits<DWORD>::max();
111 *lpFileSizeHigh = max >> 1;
112 return max;
113 }
114 return ::GetFileSize(hFile, lpFileSizeHigh);
115 }
116
117 #endif
118
119 int test::close(int fildes) {
120 // Close the file first because close shouldn't be retried.
121 int result = ::FMT_POSIX(close(fildes));
122 EMULATE_EINTR(close, -1);
123 return result;
124 }
125
126 int test::dup(int fildes) {
127 EMULATE_EINTR(dup, -1);
128 return ::FMT_POSIX(dup(fildes));
129 }
130
131 int test::dup2(int fildes, int fildes2) {
132 EMULATE_EINTR(dup2, -1);
133 return ::FMT_POSIX(dup2(fildes, fildes2));
134 }
135
136 FILE* test::fdopen(int fildes, const char* mode) {
137 EMULATE_EINTR(fdopen, nullptr);
138 return ::FMT_POSIX(fdopen(fildes, mode));
139 }
140
141 test::ssize_t test::read(int fildes, void* buf, test::size_t nbyte) {
142 read_nbyte = nbyte;
143 EMULATE_EINTR(read, -1);
144 return ::FMT_POSIX(read(fildes, buf, nbyte));
145 }
146
147 test::ssize_t test::write(int fildes, const void* buf, test::size_t nbyte) {
148 write_nbyte = nbyte;
149 EMULATE_EINTR(write, -1);
150 return ::FMT_POSIX(write(fildes, buf, nbyte));
151 }
152
153 #ifndef _WIN32
154 int test::pipe(int fildes[2]) {
155 EMULATE_EINTR(pipe, -1);
156 return ::pipe(fildes);
157 }
158 #else
159 int test::pipe(int* pfds, unsigned psize, int textmode) {
160 EMULATE_EINTR(pipe, -1);
161 return _pipe(pfds, psize, textmode);
162 }
163 #endif
164
165 FILE* test::fopen(const char* filename, const char* mode) {
166 EMULATE_EINTR(fopen, nullptr);
167 return ::fopen(filename, mode);
168 }
169
170 int test::fclose(FILE* stream) {
171 EMULATE_EINTR(fclose, EOF);
172 return ::fclose(stream);
173 }
174
175 int(test::fileno)(FILE* stream) {
176 EMULATE_EINTR(fileno, -1);
177 #ifdef fileno
178 return FMT_POSIX(fileno(stream));
179 #else
180 return ::FMT_POSIX(fileno(stream));
181 #endif
182 }
183
184 #ifndef _WIN32
185 # define EXPECT_RETRY(statement, func, message) \
186 func##_count = 1; \
187 statement; \
188 EXPECT_EQ(4, func##_count); \
189 func##_count = 0;
190 # define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual)
191 #else
192 # define EXPECT_RETRY(statement, func, message) \
193 func##_count = 1; \
194 EXPECT_SYSTEM_ERROR(statement, EINTR, message); \
195 func##_count = 0;
196 # define EXPECT_EQ_POSIX(expected, actual)
197 #endif
198
199 #if FMT_USE_FCNTL
200 void write_file(fmt::cstring_view filename, fmt::string_view content) {
201 fmt::buffered_file f(filename, "w");
202 f.print("{}", content);
203 }
204
205 using fmt::file;
206
207 TEST(os_test, getpagesize) {
208 # ifdef _WIN32
209 SYSTEM_INFO si = {};
210 GetSystemInfo(&si);
211 EXPECT_EQ(si.dwPageSize, fmt::getpagesize());
212 # else
213 EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize());
214 sysconf_error = true;
215 EXPECT_SYSTEM_ERROR(fmt::getpagesize(), EINVAL,
216 "cannot get memory page size");
217 sysconf_error = false;
218 # endif
219 }
220
221 TEST(file_test, open_retry) {
222 write_file("temp", "there must be something here");
223 std::unique_ptr<file> f{nullptr};
224 EXPECT_RETRY(f.reset(new file("temp", file::RDONLY)), open,
225 "cannot open file temp");
226 # ifndef _WIN32
227 char c = 0;
228 f->read(&c, 1);
229 # endif
230 }
231
232 TEST(file_test, close_no_retry_in_dtor) {
233 file read_end, write_end;
234 file::pipe(read_end, write_end);
235 std::unique_ptr<file> f(new file(std::move(read_end)));
236 int saved_close_count = 0;
237 EXPECT_WRITE(
238 stderr,
239 {
240 close_count = 1;
241 f.reset(nullptr);
242 saved_close_count = close_count;
243 close_count = 0;
244 },
245 system_error_message(EINTR, "cannot close file") + "\n");
246 EXPECT_EQ(2, saved_close_count);
247 }
248
249 TEST(file_test, close_no_retry) {
250 file read_end, write_end;
251 file::pipe(read_end, write_end);
252 close_count = 1;
253 EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file");
254 EXPECT_EQ(2, close_count);
255 close_count = 0;
256 }
257
258 TEST(file_test, size) {
259 std::string content = "top secret, destroy before reading";
260 write_file("temp", content);
261 file f("temp", file::RDONLY);
262 EXPECT_GE(f.size(), 0);
263 EXPECT_EQ(content.size(), static_cast<unsigned long long>(f.size()));
264 # ifdef _WIN32
265 auto error_code = std::error_code();
266 fstat_sim = error;
267 try {
268 f.size();
269 } catch (const std::system_error& e) {
270 error_code = e.code();
271 }
272 fstat_sim = none;
273 EXPECT_EQ(error_code,
274 std::error_code(ERROR_ACCESS_DENIED, fmt::system_category()));
275 # else
276 f.close();
277 EXPECT_SYSTEM_ERROR(f.size(), EBADF, "cannot get file attributes");
278 # endif
279 }
280
281 TEST(file_test, max_size) {
282 write_file("temp", "");
283 file f("temp", file::RDONLY);
284 fstat_sim = max_size;
285 EXPECT_GE(f.size(), 0);
286 EXPECT_EQ(max_file_size(), f.size());
287 fstat_sim = none;
288 }
289
290 TEST(file_test, read_retry) {
291 file read_end, write_end;
292 file::pipe(read_end, write_end);
293 enum { SIZE = 4 };
294 write_end.write("test", SIZE);
295 write_end.close();
296 char buffer[SIZE];
297 size_t count = 0;
298 EXPECT_RETRY(count = read_end.read(buffer, SIZE), read,
299 "cannot read from file");
300 EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count);
301 }
302
303 TEST(file_test, write_retry) {
304 file read_end, write_end;
305 file::pipe(read_end, write_end);
306 enum { SIZE = 4 };
307 size_t count = 0;
308 EXPECT_RETRY(count = write_end.write("test", SIZE), write,
309 "cannot write to file");
310 write_end.close();
311 # ifndef _WIN32
312 EXPECT_EQ(static_cast<std::streamsize>(SIZE), count);
313 char buffer[SIZE + 1];
314 read_end.read(buffer, SIZE);
315 buffer[SIZE] = '\0';
316 EXPECT_STREQ("test", buffer);
317 # endif
318 }
319
320 # ifdef _WIN32
321 TEST(file_test, convert_read_count) {
322 file read_end, write_end;
323 file::pipe(read_end, write_end);
324 char c;
325 size_t size = UINT_MAX;
326 if (sizeof(unsigned) != sizeof(size_t)) ++size;
327 read_count = 1;
328 read_nbyte = 0;
329 EXPECT_THROW(read_end.read(&c, size), std::system_error);
330 read_count = 0;
331 EXPECT_EQ(UINT_MAX, read_nbyte);
332 }
333
334 TEST(file_test, convert_write_count) {
335 file read_end, write_end;
336 file::pipe(read_end, write_end);
337 char c;
338 size_t size = UINT_MAX;
339 if (sizeof(unsigned) != sizeof(size_t)) ++size;
340 write_count = 1;
341 write_nbyte = 0;
342 EXPECT_THROW(write_end.write(&c, size), std::system_error);
343 write_count = 0;
344 EXPECT_EQ(UINT_MAX, write_nbyte);
345 }
346 # endif
347
348 TEST(file_test, dup_no_retry) {
349 int stdout_fd = FMT_POSIX(fileno(stdout));
350 dup_count = 1;
351 EXPECT_SYSTEM_ERROR(
352 file::dup(stdout_fd), EINTR,
353 fmt::format("cannot duplicate file descriptor {}", stdout_fd));
354 dup_count = 0;
355 }
356
357 TEST(file_test, dup2_retry) {
358 int stdout_fd = FMT_POSIX(fileno(stdout));
359 file f1 = file::dup(stdout_fd), f2 = file::dup(stdout_fd);
360 EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2,
361 fmt::format("cannot duplicate file descriptor {} to {}",
362 f1.descriptor(), f2.descriptor()));
363 }
364
365 TEST(file_test, dup2_no_except_retry) {
366 int stdout_fd = FMT_POSIX(fileno(stdout));
367 file f1 = file::dup(stdout_fd), f2 = file::dup(stdout_fd);
368 std::error_code ec;
369 dup2_count = 1;
370 f1.dup2(f2.descriptor(), ec);
371 # ifndef _WIN32
372 EXPECT_EQ(4, dup2_count);
373 # else
374 EXPECT_EQ(EINTR, ec.value());
375 # endif
376 dup2_count = 0;
377 }
378
379 TEST(file_test, pipe_no_retry) {
380 file read_end, write_end;
381 pipe_count = 1;
382 EXPECT_SYSTEM_ERROR(file::pipe(read_end, write_end), EINTR,
383 "cannot create pipe");
384 pipe_count = 0;
385 }
386
387 TEST(file_test, fdopen_no_retry) {
388 file read_end, write_end;
389 file::pipe(read_end, write_end);
390 fdopen_count = 1;
391 EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR,
392 "cannot associate stream with file descriptor");
393 fdopen_count = 0;
394 }
395
396 TEST(buffered_file_test, open_retry) {
397 write_file("temp", "there must be something here");
398 std::unique_ptr<buffered_file> f{nullptr};
399 EXPECT_RETRY(f.reset(new buffered_file("temp", "r")), fopen,
400 "cannot open file temp");
401 # ifndef _WIN32
402 char c = 0;
403 if (fread(&c, 1, 1, f->get()) < 1)
404 throw fmt::system_error(errno, "fread failed");
405 # endif
406 }
407
408 TEST(buffered_file_test, close_no_retry_in_dtor) {
409 file read_end, write_end;
410 file::pipe(read_end, write_end);
411 std::unique_ptr<buffered_file> f(new buffered_file(read_end.fdopen("r")));
412 int saved_fclose_count = 0;
413 EXPECT_WRITE(
414 stderr,
415 {
416 fclose_count = 1;
417 f.reset(nullptr);
418 saved_fclose_count = fclose_count;
419 fclose_count = 0;
420 },
421 system_error_message(EINTR, "cannot close file") + "\n");
422 EXPECT_EQ(2, saved_fclose_count);
423 }
424
425 TEST(buffered_file_test, close_no_retry) {
426 file read_end, write_end;
427 file::pipe(read_end, write_end);
428 buffered_file f = read_end.fdopen("r");
429 fclose_count = 1;
430 EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file");
431 EXPECT_EQ(2, fclose_count);
432 fclose_count = 0;
433 }
434
435 TEST(buffered_file_test, fileno_no_retry) {
436 file read_end, write_end;
437 file::pipe(read_end, write_end);
438 buffered_file f = read_end.fdopen("r");
439 fileno_count = 1;
440 EXPECT_SYSTEM_ERROR((f.fileno)(), EINTR, "cannot get file descriptor");
441 EXPECT_EQ(2, fileno_count);
442 fileno_count = 0;
443 }
444 #endif // FMT_USE_FCNTL
445
446 struct test_mock {
447 static test_mock* instance;
448 } * test_mock::instance;
449
450 TEST(scoped_mock, scope) {
451 {
452 scoped_mock<test_mock> mock;
453 EXPECT_EQ(&mock, test_mock::instance);
454 test_mock& copy = mock;
455 static_cast<void>(copy);
456 }
457 EXPECT_EQ(nullptr, test_mock::instance);
458 }
459
460 #ifdef FMT_LOCALE
461
462 using locale_type = fmt::locale::type;
463
464 struct locale_mock {
465 static locale_mock* instance;
466 MOCK_METHOD3(newlocale, locale_type(int category_mask, const char* locale,
467 locale_type base));
468 MOCK_METHOD1(freelocale, void(locale_type locale));
469 } * locale_mock::instance;
470
471 # ifdef _MSC_VER
472 # pragma warning(push)
473 # pragma warning(disable : 4273)
474 # ifdef __clang__
475 # pragma clang diagnostic push
476 # pragma clang diagnostic ignored "-Winconsistent-dllimport"
477 # endif
478
479 _locale_t _create_locale(int category, const char* locale) {
480 return locale_mock::instance->newlocale(category, locale, 0);
481 }
482
483 void _free_locale(_locale_t locale) {
484 locale_mock::instance->freelocale(locale);
485 }
486 # ifdef __clang__
487 # pragma clang diagnostic pop
488 # endif
489 # pragma warning(pop)
490 # endif
491
492 # if defined(__THROW) && \
493 ((FMT_GCC_VERSION > 0 && FMT_GCC_VERSION <= 408) || defined(__e2k__))
494 # define FMT_LOCALE_THROW __THROW
495 # else
496 # define FMT_LOCALE_THROW
497 # endif
498
499 # if defined(__APPLE__) || \
500 (defined(__FreeBSD__) && __FreeBSD_version < 1200002)
501 typedef int FreeLocaleResult;
502 # else
503 typedef void FreeLocaleResult;
504 # endif
505
506 FreeLocaleResult freelocale(locale_type locale) FMT_LOCALE_THROW {
507 locale_mock::instance->freelocale(locale);
508 return FreeLocaleResult();
509 }
510
511 # undef FMT_LOCALE_THROW
512
513 # ifndef _WIN32
514 locale_t test::newlocale(int category_mask, const char* locale, locale_t base) {
515 return locale_mock::instance->newlocale(category_mask, locale, base);
516 }
517
518 TEST(locale_test, locale_mock) {
519 scoped_mock<locale_mock> mock;
520 auto locale = reinterpret_cast<locale_type>(11);
521 EXPECT_CALL(mock, newlocale(222, StrEq("foo"), locale));
522 FMT_SYSTEM(newlocale(222, "foo", locale));
523 }
524 # endif
525
526 TEST(locale_test, locale) {
527 # ifndef LC_NUMERIC_MASK
528 enum { LC_NUMERIC_MASK = LC_NUMERIC };
529 # endif
530 scoped_mock<locale_mock> mock;
531 auto impl = reinterpret_cast<locale_type>(42);
532 EXPECT_CALL(mock, newlocale(LC_NUMERIC_MASK, StrEq("C"), nullptr))
533 .WillOnce(Return(impl));
534 EXPECT_CALL(mock, freelocale(impl));
535 fmt::locale loc;
536 EXPECT_EQ(impl, loc.get());
537 }
538
539 #endif // FMT_LOCALE
+0
-77
source/misc/embedded_libs/fmt-8.1.1/test/posix-mock.h less more
0 // Formatting library for C++ - mocks of POSIX functions
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_POSIX_TEST_H
8 #define FMT_POSIX_TEST_H
9
10 #include <errno.h>
11 #include <locale.h>
12 #include <stdio.h>
13 #ifdef __APPLE__
14 # include <xlocale.h>
15 #endif
16
17 #ifdef _WIN32
18 # include <windows.h>
19 #else
20 # include <sys/param.h> // for FreeBSD version
21 # include <sys/types.h> // for ssize_t
22 #endif
23
24 #ifndef _MSC_VER
25 struct stat;
26 #endif
27
28 namespace test {
29
30 #ifndef _MSC_VER
31 // Size type for read and write.
32 typedef size_t size_t;
33 typedef ssize_t ssize_t;
34 int open(const char* path, int oflag, int mode);
35 int fstat(int fd, struct stat* buf);
36 #else
37 typedef unsigned size_t;
38 typedef int ssize_t;
39 errno_t sopen_s(int* pfh, const char* filename, int oflag, int shflag,
40 int pmode);
41 #endif
42
43 #ifndef _WIN32
44 long sysconf(int name);
45 #else
46 DWORD GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh);
47 #endif
48
49 int close(int fildes);
50
51 int dup(int fildes);
52 int dup2(int fildes, int fildes2);
53
54 FILE* fdopen(int fildes, const char* mode);
55
56 ssize_t read(int fildes, void* buf, size_t nbyte);
57 ssize_t write(int fildes, const void* buf, size_t nbyte);
58
59 #ifndef _WIN32
60 int pipe(int fildes[2]);
61 #else
62 int pipe(int* pfds, unsigned psize, int textmode);
63 #endif
64
65 FILE* fopen(const char* filename, const char* mode);
66 int fclose(FILE* stream);
67 int(fileno)(FILE* stream);
68
69 #if defined(FMT_LOCALE) && !defined(_WIN32)
70 locale_t newlocale(int category_mask, const char* locale, locale_t base);
71 #endif
72 } // namespace test
73
74 #define FMT_SYSTEM(call) test::call
75
76 #endif // FMT_POSIX_TEST_H
+0
-588
source/misc/embedded_libs/fmt-8.1.1/test/printf-test.cc less more
0 // Formatting library for C++ - printf tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/printf.h"
8
9 #include <cctype>
10 #include <climits>
11 #include <cstring>
12
13 #include "fmt/ostream.h"
14 #include "fmt/xchar.h"
15 #include "gtest-extra.h"
16 #include "util.h"
17
18 using fmt::format;
19 using fmt::format_error;
20 using fmt::detail::max_value;
21
22 const unsigned big_num = INT_MAX + 1u;
23
24 // Makes format string argument positional.
25 static std::string make_positional(fmt::string_view format) {
26 std::string s(format.data(), format.size());
27 s.replace(s.find('%'), 1, "%1$");
28 return s;
29 }
30
31 static std::wstring make_positional(fmt::basic_string_view<wchar_t> format) {
32 std::wstring s(format.data(), format.size());
33 s.replace(s.find(L'%'), 1, L"%1$");
34 return s;
35 }
36
37 // A wrapper around fmt::sprintf to workaround bogus warnings about invalid
38 // format strings in MSVC.
39 template <typename... Args>
40 std::string test_sprintf(fmt::string_view format, const Args&... args) {
41 return fmt::sprintf(format, args...);
42 }
43 template <typename... Args>
44 std::wstring test_sprintf(fmt::basic_string_view<wchar_t> format,
45 const Args&... args) {
46 return fmt::sprintf(format, args...);
47 }
48
49 #define EXPECT_PRINTF(expected_output, format, arg) \
50 EXPECT_EQ(expected_output, test_sprintf(format, arg)) \
51 << "format: " << format; \
52 EXPECT_EQ(expected_output, fmt::sprintf(make_positional(format), arg))
53
54 TEST(printf_test, no_args) {
55 EXPECT_EQ("test", test_sprintf("test"));
56 EXPECT_EQ(L"test", fmt::sprintf(L"test"));
57 }
58
59 TEST(printf_test, escape) {
60 EXPECT_EQ("%", test_sprintf("%%"));
61 EXPECT_EQ("before %", test_sprintf("before %%"));
62 EXPECT_EQ("% after", test_sprintf("%% after"));
63 EXPECT_EQ("before % after", test_sprintf("before %% after"));
64 EXPECT_EQ("%s", test_sprintf("%%s"));
65 EXPECT_EQ(L"%", fmt::sprintf(L"%%"));
66 EXPECT_EQ(L"before %", fmt::sprintf(L"before %%"));
67 EXPECT_EQ(L"% after", fmt::sprintf(L"%% after"));
68 EXPECT_EQ(L"before % after", fmt::sprintf(L"before %% after"));
69 EXPECT_EQ(L"%s", fmt::sprintf(L"%%s"));
70 }
71
72 TEST(printf_test, positional_args) {
73 EXPECT_EQ("42", test_sprintf("%1$d", 42));
74 EXPECT_EQ("before 42", test_sprintf("before %1$d", 42));
75 EXPECT_EQ("42 after", test_sprintf("%1$d after", 42));
76 EXPECT_EQ("before 42 after", test_sprintf("before %1$d after", 42));
77 EXPECT_EQ("answer = 42", test_sprintf("%1$s = %2$d", "answer", 42));
78 EXPECT_EQ("42 is the answer", test_sprintf("%2$d is the %1$s", "answer", 42));
79 EXPECT_EQ("abracadabra", test_sprintf("%1$s%2$s%1$s", "abra", "cad"));
80 }
81
82 TEST(printf_test, automatic_arg_indexing) {
83 EXPECT_EQ("abc", test_sprintf("%c%c%c", 'a', 'b', 'c'));
84 }
85
86 TEST(printf_test, number_is_too_big_in_arg_index) {
87 EXPECT_THROW_MSG(test_sprintf(format("%{}$", big_num)), format_error,
88 "argument not found");
89 EXPECT_THROW_MSG(test_sprintf(format("%{}$d", big_num)), format_error,
90 "argument not found");
91 }
92
93 TEST(printf_test, switch_arg_indexing) {
94 EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2), format_error,
95 "cannot switch from manual to automatic argument indexing");
96 EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", big_num), 1, 2),
97 format_error, "number is too big");
98 EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2), format_error,
99 "cannot switch from manual to automatic argument indexing");
100
101 EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2), format_error,
102 "cannot switch from automatic to manual argument indexing");
103 EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", big_num), 1, 2), format_error,
104 "cannot switch from automatic to manual argument indexing");
105 EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2), format_error,
106 "cannot switch from automatic to manual argument indexing");
107
108 // Indexing errors override width errors.
109 EXPECT_THROW_MSG(test_sprintf(format("%d%1${}d", big_num), 1, 2),
110 format_error, "number is too big");
111 EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", big_num), 1, 2),
112 format_error, "number is too big");
113 }
114
115 TEST(printf_test, invalid_arg_index) {
116 EXPECT_THROW_MSG(test_sprintf("%0$d", 42), format_error,
117 "argument not found");
118 EXPECT_THROW_MSG(test_sprintf("%2$d", 42), format_error,
119 "argument not found");
120 EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42), format_error,
121 "argument not found");
122
123 EXPECT_THROW_MSG(test_sprintf("%2$", 42), format_error, "argument not found");
124 EXPECT_THROW_MSG(test_sprintf(format("%{}$d", big_num), 42), format_error,
125 "argument not found");
126 }
127
128 TEST(printf_test, default_align_right) {
129 EXPECT_PRINTF(" 42", "%5d", 42);
130 EXPECT_PRINTF(" abc", "%5s", "abc");
131 }
132
133 TEST(printf_test, zero_flag) {
134 EXPECT_PRINTF("00042", "%05d", 42);
135 EXPECT_PRINTF("-0042", "%05d", -42);
136
137 EXPECT_PRINTF("00042", "%05d", 42);
138 EXPECT_PRINTF("-0042", "%05d", -42);
139 EXPECT_PRINTF("-004.2", "%06g", -4.2);
140
141 EXPECT_PRINTF("+00042", "%00+6d", 42);
142
143 EXPECT_PRINTF(" 42", "%05.d", 42);
144 EXPECT_PRINTF(" 0042", "%05.4d", 42);
145
146 // '0' flag is ignored for non-numeric types.
147 EXPECT_PRINTF(" x", "%05c", 'x');
148 }
149
150 TEST(printf_test, plus_flag) {
151 EXPECT_PRINTF("+42", "%+d", 42);
152 EXPECT_PRINTF("-42", "%+d", -42);
153 EXPECT_PRINTF("+0042", "%+05d", 42);
154 EXPECT_PRINTF("+0042", "%0++5d", 42);
155
156 // '+' flag is ignored for non-numeric types.
157 EXPECT_PRINTF("x", "%+c", 'x');
158
159 // '+' flag wins over space flag
160 EXPECT_PRINTF("+42", "%+ d", 42);
161 EXPECT_PRINTF("-42", "%+ d", -42);
162 EXPECT_PRINTF("+42", "% +d", 42);
163 EXPECT_PRINTF("-42", "% +d", -42);
164 EXPECT_PRINTF("+0042", "% +05d", 42);
165 EXPECT_PRINTF("+0042", "%0+ 5d", 42);
166
167 // '+' flag and space flag are both ignored for non-numeric types.
168 EXPECT_PRINTF("x", "%+ c", 'x');
169 EXPECT_PRINTF("x", "% +c", 'x');
170 }
171
172 TEST(printf_test, minus_flag) {
173 EXPECT_PRINTF("abc ", "%-5s", "abc");
174 EXPECT_PRINTF("abc ", "%0--5s", "abc");
175
176 EXPECT_PRINTF("7 ", "%-5d", 7);
177 EXPECT_PRINTF("97 ", "%-5hhi", 'a');
178 EXPECT_PRINTF("a ", "%-5c", 'a');
179
180 // '0' flag is ignored if '-' flag is given
181 EXPECT_PRINTF("7 ", "%-05d", 7);
182 EXPECT_PRINTF("7 ", "%0-5d", 7);
183 EXPECT_PRINTF("a ", "%-05c", 'a');
184 EXPECT_PRINTF("a ", "%0-5c", 'a');
185 EXPECT_PRINTF("97 ", "%-05hhi", 'a');
186 EXPECT_PRINTF("97 ", "%0-5hhi", 'a');
187
188 // '-' and space flag don't interfere
189 EXPECT_PRINTF(" 42", "%- d", 42);
190 }
191
192 TEST(printf_test, space_flag) {
193 EXPECT_PRINTF(" 42", "% d", 42);
194 EXPECT_PRINTF("-42", "% d", -42);
195 EXPECT_PRINTF(" 0042", "% 05d", 42);
196 EXPECT_PRINTF(" 0042", "%0 5d", 42);
197
198 // ' ' flag is ignored for non-numeric types.
199 EXPECT_PRINTF("x", "% c", 'x');
200 }
201
202 TEST(printf_test, hash_flag) {
203 EXPECT_PRINTF("042", "%#o", 042);
204 EXPECT_PRINTF(fmt::format("0{:o}", static_cast<unsigned>(-042)), "%#o", -042);
205 EXPECT_PRINTF("0", "%#o", 0);
206
207 EXPECT_PRINTF("0x42", "%#x", 0x42);
208 EXPECT_PRINTF("0X42", "%#X", 0x42);
209 EXPECT_PRINTF(fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x",
210 -0x42);
211 EXPECT_PRINTF("0", "%#x", 0);
212
213 EXPECT_PRINTF("0x0042", "%#06x", 0x42);
214 EXPECT_PRINTF("0x0042", "%0##6x", 0x42);
215
216 EXPECT_PRINTF("-42.000000", "%#f", -42.0);
217 EXPECT_PRINTF("-42.000000", "%#F", -42.0);
218
219 char buffer[256];
220 safe_sprintf(buffer, "%#e", -42.0);
221 EXPECT_PRINTF(buffer, "%#e", -42.0);
222 safe_sprintf(buffer, "%#E", -42.0);
223 EXPECT_PRINTF(buffer, "%#E", -42.0);
224
225 EXPECT_PRINTF("-42.0000", "%#g", -42.0);
226 EXPECT_PRINTF("-42.0000", "%#G", -42.0);
227
228 safe_sprintf(buffer, "%#a", 16.0);
229 EXPECT_PRINTF(buffer, "%#a", 16.0);
230 safe_sprintf(buffer, "%#A", 16.0);
231 EXPECT_PRINTF(buffer, "%#A", 16.0);
232
233 // '#' flag is ignored for non-numeric types.
234 EXPECT_PRINTF("x", "%#c", 'x');
235 }
236
237 TEST(printf_test, width) {
238 EXPECT_PRINTF(" abc", "%5s", "abc");
239
240 // Width cannot be specified twice.
241 EXPECT_THROW_MSG(test_sprintf("%5-5d", 42), format_error,
242 "invalid type specifier");
243
244 EXPECT_THROW_MSG(test_sprintf(format("%{}d", big_num), 42), format_error,
245 "number is too big");
246 EXPECT_THROW_MSG(test_sprintf(format("%1${}d", big_num), 42), format_error,
247 "number is too big");
248 }
249
250 TEST(printf_test, dynamic_width) {
251 EXPECT_EQ(" 42", test_sprintf("%*d", 5, 42));
252 EXPECT_EQ("42 ", test_sprintf("%*d", -5, 42));
253 EXPECT_THROW_MSG(test_sprintf("%*d", 5.0, 42), format_error,
254 "width is not integer");
255 EXPECT_THROW_MSG(test_sprintf("%*d"), format_error, "argument not found");
256 EXPECT_THROW_MSG(test_sprintf("%*d", big_num, 42), format_error,
257 "number is too big");
258 }
259
260 TEST(printf_test, int_precision) {
261 EXPECT_PRINTF("00042", "%.5d", 42);
262 EXPECT_PRINTF("-00042", "%.5d", -42);
263 EXPECT_PRINTF("00042", "%.5x", 0x42);
264 EXPECT_PRINTF("0x00042", "%#.5x", 0x42);
265 EXPECT_PRINTF("00042", "%.5o", 042);
266 EXPECT_PRINTF("00042", "%#.5o", 042);
267
268 EXPECT_PRINTF(" 00042", "%7.5d", 42);
269 EXPECT_PRINTF(" 00042", "%7.5x", 0x42);
270 EXPECT_PRINTF(" 0x00042", "%#10.5x", 0x42);
271 EXPECT_PRINTF(" 00042", "%7.5o", 042);
272 EXPECT_PRINTF(" 00042", "%#10.5o", 042);
273
274 EXPECT_PRINTF("00042 ", "%-7.5d", 42);
275 EXPECT_PRINTF("00042 ", "%-7.5x", 0x42);
276 EXPECT_PRINTF("0x00042 ", "%-#10.5x", 0x42);
277 EXPECT_PRINTF("00042 ", "%-7.5o", 042);
278 EXPECT_PRINTF("00042 ", "%-#10.5o", 042);
279 }
280
281 TEST(printf_test, float_precision) {
282 char buffer[256];
283 safe_sprintf(buffer, "%.3e", 1234.5678);
284 EXPECT_PRINTF(buffer, "%.3e", 1234.5678);
285 EXPECT_PRINTF("1234.568", "%.3f", 1234.5678);
286 EXPECT_PRINTF("1.23e+03", "%.3g", 1234.5678);
287 safe_sprintf(buffer, "%.3a", 1234.5678);
288 EXPECT_PRINTF(buffer, "%.3a", 1234.5678);
289 }
290
291 TEST(printf_test, string_precision) {
292 char test[] = {'H', 'e', 'l', 'l', 'o'};
293 EXPECT_EQ(fmt::sprintf("%.4s", test), "Hell");
294 }
295
296 TEST(printf_test, ignore_precision_for_non_numeric_arg) {
297 EXPECT_PRINTF("abc", "%.5s", "abc");
298 }
299
300 TEST(printf_test, dynamic_precision) {
301 EXPECT_EQ("00042", test_sprintf("%.*d", 5, 42));
302 EXPECT_EQ("42", test_sprintf("%.*d", -5, 42));
303 EXPECT_THROW_MSG(test_sprintf("%.*d", 5.0, 42), format_error,
304 "precision is not integer");
305 EXPECT_THROW_MSG(test_sprintf("%.*d"), format_error, "argument not found");
306 EXPECT_THROW_MSG(test_sprintf("%.*d", big_num, 42), format_error,
307 "number is too big");
308 if (sizeof(long long) != sizeof(int)) {
309 long long prec = static_cast<long long>(INT_MIN) - 1;
310 EXPECT_THROW_MSG(test_sprintf("%.*d", prec, 42), format_error,
311 "number is too big");
312 }
313 }
314
315 template <typename T> struct make_signed { typedef T type; };
316
317 #define SPECIALIZE_MAKE_SIGNED(T, S) \
318 template <> struct make_signed<T> { typedef S type; }
319
320 SPECIALIZE_MAKE_SIGNED(char, signed char);
321 SPECIALIZE_MAKE_SIGNED(unsigned char, signed char);
322 SPECIALIZE_MAKE_SIGNED(unsigned short, short);
323 SPECIALIZE_MAKE_SIGNED(unsigned, int);
324 SPECIALIZE_MAKE_SIGNED(unsigned long, long);
325 SPECIALIZE_MAKE_SIGNED(unsigned long long, long long);
326
327 // Test length format specifier ``length_spec``.
328 template <typename T, typename U>
329 void test_length(const char* length_spec, U value) {
330 long long signed_value = 0;
331 unsigned long long unsigned_value = 0;
332 // Apply integer promotion to the argument.
333 unsigned long long max = max_value<U>();
334 using fmt::detail::const_check;
335 if (const_check(max <= static_cast<unsigned>(max_value<int>()))) {
336 signed_value = static_cast<int>(value);
337 unsigned_value = static_cast<unsigned long long>(value);
338 } else if (const_check(max <= max_value<unsigned>())) {
339 signed_value = static_cast<unsigned>(value);
340 unsigned_value = static_cast<unsigned long long>(value);
341 }
342 if (sizeof(U) <= sizeof(int) && sizeof(int) < sizeof(T)) {
343 signed_value = static_cast<long long>(value);
344 unsigned_value = static_cast<unsigned long long>(
345 static_cast<typename std::make_unsigned<unsigned>::type>(value));
346 } else {
347 signed_value = static_cast<typename make_signed<T>::type>(value);
348 unsigned_value = static_cast<typename std::make_unsigned<T>::type>(value);
349 }
350 std::ostringstream os;
351 os << signed_value;
352 EXPECT_PRINTF(os.str(), fmt::format("%{}d", length_spec), value);
353 EXPECT_PRINTF(os.str(), fmt::format("%{}i", length_spec), value);
354 os.str("");
355 os << unsigned_value;
356 EXPECT_PRINTF(os.str(), fmt::format("%{}u", length_spec), value);
357 os.str("");
358 os << std::oct << unsigned_value;
359 EXPECT_PRINTF(os.str(), fmt::format("%{}o", length_spec), value);
360 os.str("");
361 os << std::hex << unsigned_value;
362 EXPECT_PRINTF(os.str(), fmt::format("%{}x", length_spec), value);
363 os.str("");
364 os << std::hex << std::uppercase << unsigned_value;
365 EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value);
366 }
367
368 template <typename T> void test_length(const char* length_spec) {
369 T min = std::numeric_limits<T>::min(), max = max_value<T>();
370 test_length<T>(length_spec, 42);
371 test_length<T>(length_spec, -42);
372 test_length<T>(length_spec, min);
373 test_length<T>(length_spec, max);
374 long long long_long_min = std::numeric_limits<long long>::min();
375 if (static_cast<long long>(min) > long_long_min)
376 test_length<T>(length_spec, static_cast<long long>(min) - 1);
377 unsigned long long long_long_max = max_value<long long>();
378 if (static_cast<unsigned long long>(max) < long_long_max)
379 test_length<T>(length_spec, static_cast<long long>(max) + 1);
380 test_length<T>(length_spec, std::numeric_limits<short>::min());
381 test_length<T>(length_spec, max_value<unsigned short>());
382 test_length<T>(length_spec, std::numeric_limits<int>::min());
383 test_length<T>(length_spec, max_value<int>());
384 test_length<T>(length_spec, std::numeric_limits<unsigned>::min());
385 test_length<T>(length_spec, max_value<unsigned>());
386 test_length<T>(length_spec, std::numeric_limits<long long>::min());
387 test_length<T>(length_spec, max_value<long long>());
388 test_length<T>(length_spec, std::numeric_limits<unsigned long long>::min());
389 test_length<T>(length_spec, max_value<unsigned long long>());
390 }
391
392 TEST(printf_test, length) {
393 test_length<char>("hh");
394 test_length<signed char>("hh");
395 test_length<unsigned char>("hh");
396 test_length<short>("h");
397 test_length<unsigned short>("h");
398 test_length<long>("l");
399 test_length<unsigned long>("l");
400 test_length<long long>("ll");
401 test_length<unsigned long long>("ll");
402 test_length<intmax_t>("j");
403 test_length<size_t>("z");
404 test_length<std::ptrdiff_t>("t");
405 long double max = max_value<long double>();
406 EXPECT_PRINTF(fmt::format("{:.6}", max), "%g", max);
407 EXPECT_PRINTF(fmt::format("{:.6}", max), "%Lg", max);
408 }
409
410 TEST(printf_test, bool) {
411 EXPECT_PRINTF("1", "%d", true);
412 EXPECT_PRINTF("true", "%s", true);
413 }
414
415 TEST(printf_test, int) {
416 EXPECT_PRINTF("-42", "%d", -42);
417 EXPECT_PRINTF("-42", "%i", -42);
418 unsigned u = 0 - 42u;
419 EXPECT_PRINTF(fmt::format("{}", u), "%u", -42);
420 EXPECT_PRINTF(fmt::format("{:o}", u), "%o", -42);
421 EXPECT_PRINTF(fmt::format("{:x}", u), "%x", -42);
422 EXPECT_PRINTF(fmt::format("{:X}", u), "%X", -42);
423 }
424
425 TEST(printf_test, long_long) {
426 // fmt::printf allows passing long long arguments to %d without length
427 // specifiers.
428 long long max = max_value<long long>();
429 EXPECT_PRINTF(fmt::format("{}", max), "%d", max);
430 }
431
432 TEST(printf_test, float) {
433 EXPECT_PRINTF("392.650000", "%f", 392.65);
434 EXPECT_PRINTF("392.65", "%.2f", 392.65);
435 EXPECT_PRINTF("392.6", "%.1f", 392.65);
436 EXPECT_PRINTF("393", "%.f", 392.65);
437 EXPECT_PRINTF("392.650000", "%F", 392.65);
438 char buffer[256];
439 safe_sprintf(buffer, "%e", 392.65);
440 EXPECT_PRINTF(buffer, "%e", 392.65);
441 safe_sprintf(buffer, "%E", 392.65);
442 EXPECT_PRINTF(buffer, "%E", 392.65);
443 EXPECT_PRINTF("392.65", "%g", 392.65);
444 EXPECT_PRINTF("392.65", "%G", 392.65);
445 EXPECT_PRINTF("392", "%g", 392.0);
446 EXPECT_PRINTF("392", "%G", 392.0);
447 EXPECT_PRINTF("4.56e-07", "%g", 0.000000456);
448 safe_sprintf(buffer, "%a", -392.65);
449 EXPECT_EQ(buffer, format("{:a}", -392.65));
450 safe_sprintf(buffer, "%A", -392.65);
451 EXPECT_EQ(buffer, format("{:A}", -392.65));
452 }
453
454 TEST(printf_test, inf) {
455 double inf = std::numeric_limits<double>::infinity();
456 for (const char* type = "fega"; *type; ++type) {
457 EXPECT_PRINTF("inf", fmt::format("%{}", *type), inf);
458 char upper = static_cast<char>(std::toupper(*type));
459 EXPECT_PRINTF("INF", fmt::format("%{}", upper), inf);
460 }
461 }
462
463 TEST(printf_test, char) {
464 EXPECT_PRINTF("x", "%c", 'x');
465 int max = max_value<int>();
466 EXPECT_PRINTF(fmt::format("{}", static_cast<char>(max)), "%c", max);
467 // EXPECT_PRINTF("x", "%lc", L'x');
468 EXPECT_PRINTF(L"x", L"%c", L'x');
469 EXPECT_PRINTF(fmt::format(L"{}", static_cast<wchar_t>(max)), L"%c", max);
470 }
471
472 TEST(printf_test, string) {
473 EXPECT_PRINTF("abc", "%s", "abc");
474 const char* null_str = nullptr;
475 EXPECT_PRINTF("(null)", "%s", null_str);
476 EXPECT_PRINTF(" (null)", "%10s", null_str);
477 EXPECT_PRINTF(L"abc", L"%s", L"abc");
478 const wchar_t* null_wstr = nullptr;
479 EXPECT_PRINTF(L"(null)", L"%s", null_wstr);
480 EXPECT_PRINTF(L" (null)", L"%10s", null_wstr);
481 }
482
483 TEST(printf_test, pointer) {
484 int n;
485 void* p = &n;
486 EXPECT_PRINTF(fmt::format("{}", p), "%p", p);
487 p = nullptr;
488 EXPECT_PRINTF("(nil)", "%p", p);
489 EXPECT_PRINTF(" (nil)", "%10p", p);
490 const char* s = "test";
491 EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s);
492 const char* null_str = nullptr;
493 EXPECT_PRINTF("(nil)", "%p", null_str);
494
495 p = &n;
496 EXPECT_PRINTF(fmt::format(L"{}", p), L"%p", p);
497 p = nullptr;
498 EXPECT_PRINTF(L"(nil)", L"%p", p);
499 EXPECT_PRINTF(L" (nil)", L"%10p", p);
500 const wchar_t* w = L"test";
501 EXPECT_PRINTF(fmt::format(L"{:p}", w), L"%p", w);
502 const wchar_t* null_wstr = nullptr;
503 EXPECT_PRINTF(L"(nil)", L"%p", null_wstr);
504 }
505
506 enum test_enum { answer = 42 };
507
508 TEST(printf_test, enum) {
509 EXPECT_PRINTF("42", "%d", answer);
510 volatile test_enum volatile_enum = answer;
511 EXPECT_PRINTF("42", "%d", volatile_enum);
512 }
513
514 #if FMT_USE_FCNTL
515 TEST(printf_test, examples) {
516 const char* weekday = "Thursday";
517 const char* month = "August";
518 int day = 21;
519 EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day),
520 "Thursday, 21 August");
521 }
522
523 TEST(printf_test, printf_error) {
524 fmt::file read_end, write_end;
525 fmt::file::pipe(read_end, write_end);
526 int result = fmt::fprintf(read_end.fdopen("r").get(), "test");
527 EXPECT_LT(result, 0);
528 }
529 #endif
530
531 TEST(printf_test, wide_string) {
532 EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc"));
533 }
534
535 TEST(printf_test, printf_custom) {
536 EXPECT_EQ("abc", test_sprintf("%s", test_string("abc")));
537 }
538
539 TEST(printf_test, vprintf) {
540 fmt::format_arg_store<fmt::printf_context, int> as{42};
541 fmt::basic_format_args<fmt::printf_context> args(as);
542 EXPECT_EQ(fmt::vsprintf("%d", args), "42");
543 EXPECT_WRITE(stdout, fmt::vprintf("%d", args), "42");
544 EXPECT_WRITE(stdout, fmt::vfprintf(stdout, "%d", args), "42");
545 }
546
547 template <typename... Args>
548 void check_format_string_regression(fmt::string_view s, const Args&... args) {
549 fmt::sprintf(s, args...);
550 }
551
552 TEST(printf_test, check_format_string_regression) {
553 check_format_string_regression("%c%s", 'x', "");
554 }
555
556 TEST(printf_test, fixed_large_exponent) {
557 EXPECT_EQ("1000000000000000000000", fmt::sprintf("%.*f", -13, 1e21));
558 }
559
560 TEST(printf_test, vsprintf_make_args_example) {
561 fmt::format_arg_store<fmt::printf_context, int, const char*> as{42,
562 "something"};
563 fmt::basic_format_args<fmt::printf_context> args(as);
564 EXPECT_EQ("[42] something happened", fmt::vsprintf("[%d] %s happened", args));
565 auto as2 = fmt::make_printf_args(42, "something");
566 fmt::basic_format_args<fmt::printf_context> args2(as2);
567 EXPECT_EQ("[42] something happened",
568 fmt::vsprintf("[%d] %s happened", args2));
569 EXPECT_EQ("[42] something happened",
570 fmt::vsprintf("[%d] %s happened",
571 {fmt::make_printf_args(42, "something")}));
572 }
573
574 TEST(printf_test, vsprintf_make_wargs_example) {
575 fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t*> as{
576 42, L"something"};
577 fmt::basic_format_args<fmt::wprintf_context> args(as);
578 EXPECT_EQ(L"[42] something happened",
579 fmt::vsprintf(L"[%d] %s happened", args));
580 auto as2 = fmt::make_wprintf_args(42, L"something");
581 fmt::basic_format_args<fmt::wprintf_context> args2(as2);
582 EXPECT_EQ(L"[42] something happened",
583 fmt::vsprintf(L"[%d] %s happened", args2));
584 EXPECT_EQ(L"[42] something happened",
585 fmt::vsprintf(L"[%d] %s happened",
586 {fmt::make_wprintf_args(42, L"something")}));
587 }
+0
-17
source/misc/embedded_libs/fmt-8.1.1/test/ranges-odr-test.cc less more
0 // Formatting library for C++ - the core API
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include <vector>
8
9 #include "fmt/ranges.h"
10 #include "gtest/gtest.h"
11
12 // call fmt::format from another translation unit to test ODR
13 TEST(ranges_odr_test, format_vector) {
14 auto v = std::vector<int>{1, 2, 3, 5, 7, 11};
15 EXPECT_EQ(fmt::format("{}", v), "[1, 2, 3, 5, 7, 11]");
16 }
+0
-363
source/misc/embedded_libs/fmt-8.1.1/test/ranges-test.cc less more
0 // Formatting library for C++ - the core API
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6 //
7 // Copyright (c) 2018 - present, Remotion (Igor Schulz)
8 // All Rights Reserved
9 // {fmt} support for ranges, containers and types tuple interface.
10
11 #include "fmt/ranges.h"
12
13 #include <map>
14 #include <string>
15 #include <vector>
16
17 #include "gtest/gtest.h"
18
19 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 601
20 # define FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
21 #endif
22
23 #if !FMT_MSC_VER || FMT_MSC_VER > 1910
24 # define FMT_RANGES_TEST_ENABLE_JOIN
25 # define FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
26 #endif
27
28 #ifdef FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
29 TEST(ranges_test, format_array) {
30 int arr[] = {1, 2, 3, 5, 7, 11};
31 EXPECT_EQ(fmt::format("{}", arr), "[1, 2, 3, 5, 7, 11]");
32 }
33
34 TEST(ranges_test, format_2d_array) {
35 int arr[][2] = {{1, 2}, {3, 5}, {7, 11}};
36 EXPECT_EQ(fmt::format("{}", arr), "[[1, 2], [3, 5], [7, 11]]");
37 }
38
39 TEST(ranges_test, format_array_of_literals) {
40 const char* arr[] = {"1234", "abcd"};
41 EXPECT_EQ(fmt::format("{}", arr), "[\"1234\", \"abcd\"]");
42 }
43 #endif // FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
44
45 TEST(ranges_test, format_vector) {
46 auto v = std::vector<int>{1, 2, 3, 5, 7, 11};
47 EXPECT_EQ(fmt::format("{}", v), "[1, 2, 3, 5, 7, 11]");
48 }
49
50 TEST(ranges_test, format_vector2) {
51 auto v = std::vector<std::vector<int>>{{1, 2}, {3, 5}, {7, 11}};
52 EXPECT_EQ(fmt::format("{}", v), "[[1, 2], [3, 5], [7, 11]]");
53 }
54
55 TEST(ranges_test, format_map) {
56 auto m = std::map<std::string, int>{{"one", 1}, {"two", 2}};
57 EXPECT_EQ(fmt::format("{}", m), "{\"one\": 1, \"two\": 2}");
58 }
59
60 TEST(ranges_test, format_set) {
61 EXPECT_EQ(fmt::format("{}", std::set<std::string>{"one", "two"}),
62 "{\"one\", \"two\"}");
63 }
64
65 TEST(ranges_test, format_pair) {
66 auto p = std::pair<int, float>(42, 1.5f);
67 EXPECT_EQ(fmt::format("{}", p), "(42, 1.5)");
68 }
69
70 TEST(ranges_test, format_tuple) {
71 auto t =
72 std::tuple<int, float, std::string, char>(42, 1.5f, "this is tuple", 'i');
73 EXPECT_EQ(fmt::format("{}", t), "(42, 1.5, \"this is tuple\", 'i')");
74 EXPECT_EQ(fmt::format("{}", std::tuple<>()), "()");
75 }
76
77 #ifdef FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
78 struct tuple_like {
79 int i;
80 std::string str;
81
82 template <size_t N> fmt::enable_if_t<N == 0, int> get() const noexcept {
83 return i;
84 }
85 template <size_t N>
86 fmt::enable_if_t<N == 1, fmt::string_view> get() const noexcept {
87 return str;
88 }
89 };
90
91 template <size_t N>
92 auto get(const tuple_like& t) noexcept -> decltype(t.get<N>()) {
93 return t.get<N>();
94 }
95
96 namespace std {
97 template <>
98 struct tuple_size<tuple_like> : std::integral_constant<size_t, 2> {};
99
100 template <size_t N> struct tuple_element<N, tuple_like> {
101 using type = decltype(std::declval<tuple_like>().get<N>());
102 };
103 } // namespace std
104
105 TEST(ranges_test, format_struct) {
106 auto t = tuple_like{42, "foo"};
107 EXPECT_EQ(fmt::format("{}", t), "(42, \"foo\")");
108 }
109 #endif // FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
110
111 TEST(ranges_test, format_to) {
112 char buf[10];
113 auto end = fmt::format_to(buf, "{}", std::vector<int>{1, 2, 3});
114 *end = '\0';
115 EXPECT_STREQ(buf, "[1, 2, 3]");
116 }
117
118 struct path_like {
119 const path_like* begin() const;
120 const path_like* end() const;
121
122 operator std::string() const;
123 };
124
125 TEST(ranges_test, path_like) {
126 EXPECT_FALSE((fmt::is_range<path_like, char>::value));
127 }
128
129 #ifdef FMT_USE_STRING_VIEW
130 struct string_like {
131 const char* begin();
132 const char* end();
133 explicit operator fmt::string_view() const { return "foo"; }
134 explicit operator std::string_view() const { return "foo"; }
135 };
136
137 TEST(ranges_test, format_string_like) {
138 EXPECT_EQ(fmt::format("{}", string_like()), "foo");
139 }
140 #endif // FMT_USE_STRING_VIEW
141
142 // A range that provides non-const only begin()/end() to test fmt::join handles
143 // that.
144 //
145 // Some ranges (e.g. those produced by range-v3's views::filter()) can cache
146 // information during iteration so they only provide non-const begin()/end().
147 template <typename T> class non_const_only_range {
148 private:
149 std::vector<T> vec;
150
151 public:
152 using const_iterator = typename ::std::vector<T>::const_iterator;
153
154 template <typename... Args>
155 explicit non_const_only_range(Args&&... args)
156 : vec(std::forward<Args>(args)...) {}
157
158 const_iterator begin() { return vec.begin(); }
159 const_iterator end() { return vec.end(); }
160 };
161
162 template <typename T> class noncopyable_range {
163 private:
164 std::vector<T> vec;
165
166 public:
167 using const_iterator = typename ::std::vector<T>::const_iterator;
168
169 template <typename... Args>
170 explicit noncopyable_range(Args&&... args)
171 : vec(std::forward<Args>(args)...) {}
172
173 noncopyable_range(noncopyable_range const&) = delete;
174 noncopyable_range(noncopyable_range&) = delete;
175
176 const_iterator begin() const { return vec.begin(); }
177 const_iterator end() const { return vec.end(); }
178 };
179
180 TEST(ranges_test, range) {
181 noncopyable_range<int> w(3u, 0);
182 EXPECT_EQ(fmt::format("{}", w), "[0, 0, 0]");
183 EXPECT_EQ(fmt::format("{}", noncopyable_range<int>(3u, 0)), "[0, 0, 0]");
184
185 non_const_only_range<int> x(3u, 0);
186 EXPECT_EQ(fmt::format("{}", x), "[0, 0, 0]");
187 EXPECT_EQ(fmt::format("{}", non_const_only_range<int>(3u, 0)), "[0, 0, 0]");
188
189 auto y = std::vector<int>(3u, 0);
190 EXPECT_EQ(fmt::format("{}", y), "[0, 0, 0]");
191 EXPECT_EQ(fmt::format("{}", std::vector<int>(3u, 0)), "[0, 0, 0]");
192
193 const auto z = std::vector<int>(3u, 0);
194 EXPECT_EQ(fmt::format("{}", z), "[0, 0, 0]");
195 }
196
197 enum test_enum { foo };
198
199 TEST(ranges_test, enum_range) {
200 auto v = std::vector<test_enum>{test_enum::foo};
201 EXPECT_EQ(fmt::format("{}", v), "[0]");
202 }
203
204 #if !FMT_MSC_VER
205 struct unformattable {};
206
207 TEST(ranges_test, unformattable_range) {
208 EXPECT_FALSE((fmt::has_formatter<std::vector<unformattable>,
209 fmt::format_context>::value));
210 }
211 #endif
212
213 #ifdef FMT_RANGES_TEST_ENABLE_JOIN
214 TEST(ranges_test, join_tuple) {
215 // Value tuple args.
216 auto t1 = std::tuple<char, int, float>('a', 1, 2.0f);
217 EXPECT_EQ(fmt::format("({})", fmt::join(t1, ", ")), "(a, 1, 2)");
218
219 // Testing lvalue tuple args.
220 int x = 4;
221 auto t2 = std::tuple<char, int&>('b', x);
222 EXPECT_EQ(fmt::format("{}", fmt::join(t2, " + ")), "b + 4");
223
224 // Empty tuple.
225 auto t3 = std::tuple<>();
226 EXPECT_EQ(fmt::format("{}", fmt::join(t3, "|")), "");
227
228 // Single element tuple.
229 auto t4 = std::tuple<float>(4.0f);
230 EXPECT_EQ(fmt::format("{}", fmt::join(t4, "/")), "4");
231
232 # if FMT_TUPLE_JOIN_SPECIFIERS
233 // Specs applied to each element.
234 auto t5 = std::tuple<int, int, long>(-3, 100, 1);
235 EXPECT_EQ(fmt::format("{:+03}", fmt::join(t5, ", ")), "-03, +100, +01");
236
237 auto t6 = std::tuple<float, double, long double>(3, 3.14, 3.1415);
238 EXPECT_EQ(fmt::format("{:5.5f}", fmt::join(t6, ", ")),
239 "3.00000, 3.14000, 3.14150");
240
241 // Testing lvalue tuple args.
242 int y = -1;
243 auto t7 = std::tuple<int, int&, const int&>(3, y, y);
244 EXPECT_EQ(fmt::format("{:03}", fmt::join(t7, ", ")), "003, -01, -01");
245 # endif
246 }
247
248 TEST(ranges_test, join_initializer_list) {
249 EXPECT_EQ(fmt::format("{}", fmt::join({1, 2, 3}, ", ")), "1, 2, 3");
250 EXPECT_EQ(fmt::format("{}", fmt::join({"fmt", "rocks", "!"}, " ")),
251 "fmt rocks !");
252 }
253
254 struct zstring_sentinel {};
255
256 bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; }
257 bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; }
258
259 struct zstring {
260 const char* p;
261 const char* begin() const { return p; }
262 zstring_sentinel end() const { return {}; }
263 };
264
265 # ifdef __cpp_lib_ranges
266 struct cpp20_only_range {
267 struct iterator {
268 int val = 0;
269
270 using value_type = int;
271 using difference_type = std::ptrdiff_t;
272 using iterator_concept = std::input_iterator_tag;
273
274 iterator() = default;
275 iterator(int i) : val(i) {}
276 int operator*() const { return val; }
277 iterator& operator++() {
278 ++val;
279 return *this;
280 }
281 void operator++(int) { ++*this; }
282 bool operator==(const iterator& rhs) const { return val == rhs.val; }
283 };
284
285 int lo;
286 int hi;
287
288 iterator begin() const { return iterator(lo); }
289 iterator end() const { return iterator(hi); }
290 };
291
292 static_assert(std::input_iterator<cpp20_only_range::iterator>);
293 # endif
294
295 TEST(ranges_test, join_sentinel) {
296 auto hello = zstring{"hello"};
297 EXPECT_EQ(fmt::format("{}", hello), "['h', 'e', 'l', 'l', 'o']");
298 EXPECT_EQ(fmt::format("{}", fmt::join(hello, "_")), "h_e_l_l_o");
299 }
300
301 TEST(ranges_test, join_range) {
302 noncopyable_range<int> w(3u, 0);
303 EXPECT_EQ(fmt::format("{}", fmt::join(w, ",")), "0,0,0");
304 EXPECT_EQ(fmt::format("{}", fmt::join(noncopyable_range<int>(3u, 0), ",")),
305 "0,0,0");
306
307 non_const_only_range<int> x(3u, 0);
308 EXPECT_EQ(fmt::format("{}", fmt::join(x, ",")), "0,0,0");
309 EXPECT_EQ(fmt::format("{}", fmt::join(non_const_only_range<int>(3u, 0), ",")),
310 "0,0,0");
311
312 auto y = std::vector<int>(3u, 0);
313 EXPECT_EQ(fmt::format("{}", fmt::join(y, ",")), "0,0,0");
314 EXPECT_EQ(fmt::format("{}", fmt::join(std::vector<int>(3u, 0), ",")),
315 "0,0,0");
316
317 const auto z = std::vector<int>(3u, 0);
318 EXPECT_EQ(fmt::format("{}", fmt::join(z, ",")), "0,0,0");
319
320 # ifdef __cpp_lib_ranges
321 EXPECT_EQ(fmt::format("{}", cpp20_only_range{.lo = 0, .hi = 5}),
322 "[0, 1, 2, 3, 4]");
323 EXPECT_EQ(
324 fmt::format("{}", fmt::join(cpp20_only_range{.lo = 0, .hi = 5}, ",")),
325 "0,1,2,3,4");
326 # endif
327 }
328 #endif // FMT_RANGES_TEST_ENABLE_JOIN
329
330 TEST(ranges_test, is_printable) {
331 using fmt::detail::is_printable;
332 EXPECT_TRUE(is_printable(0x0323));
333 EXPECT_FALSE(is_printable(0x0378));
334 EXPECT_FALSE(is_printable(0x110000));
335 }
336
337 TEST(ranges_test, escape_string) {
338 using vec = std::vector<std::string>;
339 EXPECT_EQ(fmt::format("{}", vec{"\n\r\t\"\\"}), "[\"\\n\\r\\t\\\"\\\\\"]");
340 EXPECT_EQ(fmt::format("{}", vec{"\x07"}), "[\"\\x07\"]");
341 EXPECT_EQ(fmt::format("{}", vec{"\x7f"}), "[\"\\x7f\"]");
342 EXPECT_EQ(fmt::format("{}", vec{"n\xcc\x83"}), "[\"n\xcc\x83\"]");
343
344 if (fmt::detail::is_utf8()) {
345 EXPECT_EQ(fmt::format("{}", vec{"\xcd\xb8"}), "[\"\\u0378\"]");
346 // Unassigned Unicode code points.
347 EXPECT_EQ(fmt::format("{}", vec{"\xf0\xaa\x9b\x9e"}), "[\"\\U0002a6de\"]");
348 EXPECT_EQ(fmt::format("{}", vec{"\xf4\x8f\xbf\xc0"}),
349 "[\"\\xf4\\x8f\\xbf\\xc0\"]");
350 }
351 }
352
353 #ifdef FMT_USE_STRING_VIEW
354 struct convertible_to_string_view {
355 operator std::string_view() const { return "foo"; }
356 };
357
358 TEST(ranges_test, escape_convertible_to_string_view) {
359 EXPECT_EQ(fmt::format("{}", std::vector<convertible_to_string_view>(1)),
360 "[\"foo\"]");
361 }
362 #endif // FMT_USE_STRING_VIEW
+0
-116
source/misc/embedded_libs/fmt-8.1.1/test/scan-test.cc less more
0 // Formatting library for C++ - scanning API test
1 //
2 // Copyright (c) 2019 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "scan.h"
8
9 #include <time.h>
10
11 #include <climits>
12
13 #include "gmock/gmock.h"
14 #include "gtest-extra.h"
15
16 TEST(scan_test, read_text) {
17 auto s = fmt::string_view("foo");
18 auto end = fmt::scan(s, "foo");
19 EXPECT_EQ(end, s.end());
20 EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input");
21 }
22
23 TEST(scan_test, read_int) {
24 auto n = int();
25 fmt::scan("42", "{}", n);
26 EXPECT_EQ(n, 42);
27 fmt::scan("-42", "{}", n);
28 EXPECT_EQ(n, -42);
29 }
30
31 TEST(scan_test, read_longlong) {
32 long long n = 0;
33 fmt::scan("42", "{}", n);
34 EXPECT_EQ(n, 42);
35 fmt::scan("-42", "{}", n);
36 EXPECT_EQ(n, -42);
37 }
38
39 TEST(scan_test, read_uint) {
40 auto n = unsigned();
41 fmt::scan("42", "{}", n);
42 EXPECT_EQ(n, 42);
43 EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error,
44 "invalid input");
45 }
46
47 TEST(scan_test, read_ulonglong) {
48 unsigned long long n = 0;
49 fmt::scan("42", "{}", n);
50 EXPECT_EQ(n, 42);
51 EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error,
52 "invalid input");
53 }
54
55 TEST(scan_test, read_string) {
56 auto s = std::string();
57 fmt::scan("foo", "{}", s);
58 EXPECT_EQ(s, "foo");
59 }
60
61 TEST(scan_test, read_string_view) {
62 auto s = fmt::string_view();
63 fmt::scan("foo", "{}", s);
64 EXPECT_EQ(s, "foo");
65 }
66
67 #ifndef _WIN32
68 namespace fmt {
69 template <> struct scanner<tm> {
70 std::string format;
71
72 scan_parse_context::iterator parse(scan_parse_context& ctx) {
73 auto it = ctx.begin();
74 if (it != ctx.end() && *it == ':') ++it;
75 auto end = it;
76 while (end != ctx.end() && *end != '}') ++end;
77 format.reserve(detail::to_unsigned(end - it + 1));
78 format.append(it, end);
79 format.push_back('\0');
80 return end;
81 }
82
83 template <class ScanContext>
84 typename ScanContext::iterator scan(tm& t, ScanContext& ctx) {
85 auto result = strptime(ctx.begin(), format.c_str(), &t);
86 if (!result) throw format_error("failed to parse time");
87 return result;
88 }
89 };
90 } // namespace fmt
91
92 TEST(scan_test, read_custom) {
93 auto input = "Date: 1985-10-25";
94 auto t = tm();
95 fmt::scan(input, "Date: {0:%Y-%m-%d}", t);
96 EXPECT_EQ(t.tm_year, 85);
97 EXPECT_EQ(t.tm_mon, 9);
98 EXPECT_EQ(t.tm_mday, 25);
99 }
100 #endif
101
102 TEST(scan_test, invalid_format) {
103 EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error,
104 "argument index out of range");
105 EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error,
106 "invalid format string");
107 }
108
109 TEST(scan_test, example) {
110 auto key = std::string();
111 auto value = int();
112 fmt::scan("answer = 42", "{} = {}", key, value);
113 EXPECT_EQ(key, "answer");
114 EXPECT_EQ(value, 42);
115 }
+0
-241
source/misc/embedded_libs/fmt-8.1.1/test/scan.h less more
0 // Formatting library for C++ - scanning API proof of concept
1 //
2 // Copyright (c) 2019 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include <array>
8 #include <cassert>
9 #include <climits>
10
11 #include "fmt/format.h"
12
13 FMT_BEGIN_NAMESPACE
14 template <typename T, typename Char = char> struct scanner {
15 // A deleted default constructor indicates a disabled scanner.
16 scanner() = delete;
17 };
18
19 class scan_parse_context {
20 private:
21 string_view format_;
22
23 public:
24 using iterator = string_view::iterator;
25
26 explicit FMT_CONSTEXPR scan_parse_context(string_view format)
27 : format_(format) {}
28
29 FMT_CONSTEXPR iterator begin() const { return format_.begin(); }
30 FMT_CONSTEXPR iterator end() const { return format_.end(); }
31
32 void advance_to(iterator it) {
33 format_.remove_prefix(detail::to_unsigned(it - begin()));
34 }
35 };
36
37 struct scan_context {
38 private:
39 string_view input_;
40
41 public:
42 using iterator = const char*;
43
44 explicit scan_context(string_view input) : input_(input) {}
45
46 iterator begin() const { return input_.data(); }
47 iterator end() const { return begin() + input_.size(); }
48
49 void advance_to(iterator it) {
50 input_.remove_prefix(detail::to_unsigned(it - begin()));
51 }
52 };
53
54 namespace detail {
55 enum class scan_type {
56 none_type,
57 int_type,
58 uint_type,
59 long_long_type,
60 ulong_long_type,
61 string_type,
62 string_view_type,
63 custom_type
64 };
65
66 struct custom_scan_arg {
67 void* value;
68 void (*scan)(void* arg, scan_parse_context& parse_ctx, scan_context& ctx);
69 };
70
71 class scan_arg {
72 public:
73 scan_type type;
74 union {
75 int* int_value;
76 unsigned* uint_value;
77 long long* long_long_value;
78 unsigned long long* ulong_long_value;
79 std::string* string;
80 fmt::string_view* string_view;
81 custom_scan_arg custom;
82 // TODO: more types
83 };
84
85 scan_arg() : type(scan_type::none_type) {}
86 scan_arg(int& value) : type(scan_type::int_type), int_value(&value) {}
87 scan_arg(unsigned& value) : type(scan_type::uint_type), uint_value(&value) {}
88 scan_arg(long long& value)
89 : type(scan_type::long_long_type), long_long_value(&value) {}
90 scan_arg(unsigned long long& value)
91 : type(scan_type::ulong_long_type), ulong_long_value(&value) {}
92 scan_arg(std::string& value) : type(scan_type::string_type), string(&value) {}
93 scan_arg(fmt::string_view& value)
94 : type(scan_type::string_view_type), string_view(&value) {}
95 template <typename T> scan_arg(T& value) : type(scan_type::custom_type) {
96 custom.value = &value;
97 custom.scan = scan_custom_arg<T>;
98 }
99
100 private:
101 template <typename T>
102 static void scan_custom_arg(void* arg, scan_parse_context& parse_ctx,
103 scan_context& ctx) {
104 scanner<T> s;
105 parse_ctx.advance_to(s.parse(parse_ctx));
106 ctx.advance_to(s.scan(*static_cast<T*>(arg), ctx));
107 }
108 };
109 } // namespace detail
110
111 struct scan_args {
112 int size;
113 const detail::scan_arg* data;
114
115 template <size_t N>
116 scan_args(const std::array<detail::scan_arg, N>& store)
117 : size(N), data(store.data()) {
118 static_assert(N < INT_MAX, "too many arguments");
119 }
120 };
121
122 namespace detail {
123
124 struct scan_handler : error_handler {
125 private:
126 scan_parse_context parse_ctx_;
127 scan_context scan_ctx_;
128 scan_args args_;
129 int next_arg_id_;
130 scan_arg arg_;
131
132 template <typename T = unsigned> T read_uint() {
133 T value = 0;
134 auto it = scan_ctx_.begin(), end = scan_ctx_.end();
135 while (it != end) {
136 char c = *it++;
137 if (c < '0' || c > '9') on_error("invalid input");
138 // TODO: check overflow
139 value = value * 10 + static_cast<unsigned>(c - '0');
140 }
141 scan_ctx_.advance_to(it);
142 return value;
143 }
144
145 template <typename T = int> T read_int() {
146 auto it = scan_ctx_.begin(), end = scan_ctx_.end();
147 bool negative = it != end && *it == '-';
148 if (negative) ++it;
149 scan_ctx_.advance_to(it);
150 const auto value = read_uint<typename std::make_unsigned<T>::type>();
151 if (negative) return -static_cast<T>(value);
152 return static_cast<T>(value);
153 }
154
155 public:
156 scan_handler(string_view format, string_view input, scan_args args)
157 : parse_ctx_(format), scan_ctx_(input), args_(args), next_arg_id_(0) {}
158
159 const char* pos() const { return scan_ctx_.begin(); }
160
161 void on_text(const char* begin, const char* end) {
162 auto size = to_unsigned(end - begin);
163 auto it = scan_ctx_.begin();
164 if (it + size > scan_ctx_.end() ||
165 !std::equal(begin, end, make_checked(it, size))) {
166 on_error("invalid input");
167 }
168 scan_ctx_.advance_to(it + size);
169 }
170
171 FMT_CONSTEXPR int on_arg_id() { return on_arg_id(next_arg_id_++); }
172 FMT_CONSTEXPR int on_arg_id(int id) {
173 if (id >= args_.size) on_error("argument index out of range");
174 arg_ = args_.data[id];
175 return id;
176 }
177 FMT_CONSTEXPR int on_arg_id(string_view id) {
178 if (id.data()) on_error("invalid format");
179 return 0;
180 }
181
182 void on_replacement_field(int, const char*) {
183 auto it = scan_ctx_.begin(), end = scan_ctx_.end();
184 switch (arg_.type) {
185 case scan_type::int_type:
186 *arg_.int_value = read_int();
187 break;
188 case scan_type::uint_type:
189 *arg_.uint_value = read_uint();
190 break;
191 case scan_type::long_long_type:
192 *arg_.long_long_value = read_int<long long>();
193 break;
194 case scan_type::ulong_long_type:
195 *arg_.ulong_long_value = read_uint<unsigned long long>();
196 break;
197 case scan_type::string_type:
198 while (it != end && *it != ' ') arg_.string->push_back(*it++);
199 scan_ctx_.advance_to(it);
200 break;
201 case scan_type::string_view_type: {
202 auto s = it;
203 while (it != end && *it != ' ') ++it;
204 *arg_.string_view = fmt::string_view(s, to_unsigned(it - s));
205 scan_ctx_.advance_to(it);
206 break;
207 }
208 case scan_type::none_type:
209 case scan_type::custom_type:
210 assert(false);
211 }
212 }
213
214 const char* on_format_specs(int, const char* begin, const char*) {
215 if (arg_.type != scan_type::custom_type) return begin;
216 parse_ctx_.advance_to(begin);
217 arg_.custom.scan(arg_.custom.value, parse_ctx_, scan_ctx_);
218 return parse_ctx_.begin();
219 }
220 };
221 } // namespace detail
222
223 template <typename... Args>
224 std::array<detail::scan_arg, sizeof...(Args)> make_scan_args(Args&... args) {
225 return {{args...}};
226 }
227
228 string_view::iterator vscan(string_view input, string_view format_str,
229 scan_args args) {
230 detail::scan_handler h(format_str, input, args);
231 detail::parse_format_string<false>(format_str, h);
232 return input.begin() + (h.pos() - &*input.begin());
233 }
234
235 template <typename... Args>
236 string_view::iterator scan(string_view input, string_view format_str,
237 Args&... args) {
238 return vscan(input, format_str, make_scan_args(args...));
239 }
240 FMT_END_NAMESPACE
+0
-30
source/misc/embedded_libs/fmt-8.1.1/test/static-export-test/CMakeLists.txt less more
0 cmake_minimum_required(VERSION 3.1...3.18)
1
2 project(fmt-link CXX)
3
4 set(BUILD_SHARED_LIBS OFF)
5 set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE)
6 set(CMAKE_CXX_VISIBILITY_PRESET "hidden")
7
8 # Broken LTO on GCC 4
9 if (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5)
10 set(BROKEN_LTO ON)
11 endif ()
12
13 if (NOT BROKEN_LTO AND CMAKE_VERSION VERSION_GREATER "3.8")
14 # CMake 3.9+
15 include(CheckIPOSupported)
16 check_ipo_supported(RESULT HAVE_IPO)
17 if (HAVE_IPO)
18 set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
19 endif ()
20 endif ()
21
22 add_subdirectory(../.. fmt)
23 set_property(TARGET fmt PROPERTY POSITION_INDEPENDENT_CODE ON)
24
25 add_library(library-test SHARED library.cc)
26 target_link_libraries(library-test PRIVATE fmt::fmt)
27
28 add_executable(exe-test main.cc)
29 target_link_libraries(exe-test PRIVATE library-test)
+0
-5
source/misc/embedded_libs/fmt-8.1.1/test/static-export-test/library.cc less more
0 #include <fmt/compile.h>
1
2 __attribute__((visibility("default"))) std::string foo() {
3 return fmt::format(FMT_COMPILE("foo bar {}"), 4242);
4 }
+0
-6
source/misc/embedded_libs/fmt-8.1.1/test/static-export-test/main.cc less more
0 #include <iostream>
1 #include <string>
2
3 extern std::string foo();
4
5 int main() { std::cout << foo() << std::endl; }
+0
-39
source/misc/embedded_libs/fmt-8.1.1/test/test-assert.h less more
0 // Formatting library for C++ - test version of FMT_ASSERT
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #ifndef FMT_TEST_ASSERT_H_
8 #define FMT_TEST_ASSERT_H_
9
10 #include <stdexcept>
11
12 void throw_assertion_failure(const char* message);
13 #define FMT_ASSERT(condition, message) \
14 if (!(condition)) throw_assertion_failure(message);
15
16 #include "gtest/gtest.h"
17
18 class assertion_failure : public std::logic_error {
19 public:
20 explicit assertion_failure(const char* message) : std::logic_error(message) {}
21
22 private:
23 virtual void avoid_weak_vtable();
24 };
25
26 void assertion_failure::avoid_weak_vtable() {}
27
28 // We use a separate function (rather than throw directly from FMT_ASSERT) to
29 // avoid GCC's -Wterminate warning when FMT_ASSERT is used in a destructor.
30 inline void throw_assertion_failure(const char* message) {
31 throw assertion_failure(message);
32 }
33
34 // Expects an assertion failure.
35 #define EXPECT_ASSERT(stmt, message) \
36 FMT_TEST_THROW_(stmt, assertion_failure, message, GTEST_NONFATAL_FAILURE_)
37
38 #endif // FMT_TEST_ASSERT_H_
+0
-44
source/misc/embedded_libs/fmt-8.1.1/test/test-main.cc less more
0 // Formatting library for C++ - test main function.
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include <cstdlib>
8
9 #include "gtest/gtest.h"
10
11 #ifdef _WIN32
12 # include <windows.h>
13 #endif
14
15 #ifdef _MSC_VER
16 # include <crtdbg.h>
17 #else
18 # define _CrtSetReportFile(a, b)
19 # define _CrtSetReportMode(a, b)
20 #endif
21
22 int main(int argc, char** argv) {
23 #ifdef _WIN32
24 // Don't display any error dialogs. This also suppresses message boxes
25 // on assertion failures in MinGW where _set_error_mode/CrtSetReportMode
26 // doesn't help.
27 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
28 SEM_NOOPENFILEERRORBOX);
29 #endif
30 // Disable message boxes on assertion failures.
31 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
32 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
33 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
34 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
35 try {
36 testing::InitGoogleTest(&argc, argv);
37 testing::FLAGS_gtest_death_test_style = "threadsafe";
38 return RUN_ALL_TESTS();
39 } catch (...) {
40 // Catch all exceptions to make Coverity happy.
41 }
42 return EXIT_FAILURE;
43 }
+0
-48
source/misc/embedded_libs/fmt-8.1.1/test/unicode-test.cc less more
0 // Formatting library for C++ - Unicode tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include <iomanip>
8 #include <locale>
9 #include <vector>
10
11 #include "fmt/chrono.h"
12 #include "gmock/gmock.h"
13 #include "util.h" // get_locale
14
15 using testing::Contains;
16
17 TEST(unicode_test, is_utf8) { EXPECT_TRUE(fmt::detail::is_utf8()); }
18
19 TEST(unicode_test, legacy_locale) {
20 auto loc = get_locale("ru_RU.CP1251", "Russian_Russia.1251");
21 if (loc == std::locale::classic()) return;
22
23 auto s = std::string();
24 try {
25 s = fmt::format(loc, "День недели: {:L}", fmt::weekday(1));
26 } catch (const fmt::format_error& e) {
27 // Formatting can fail due to an unsupported encoding.
28 fmt::print("Format error: {}\n", e.what());
29 return;
30 }
31
32 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 500
33 auto&& os = std::ostringstream();
34 os.imbue(loc);
35 auto tm = std::tm();
36 tm.tm_wday = 1;
37 os << std::put_time(&tm, "%a");
38 auto wd = os.str();
39 if (wd == "??") {
40 EXPECT_EQ(s, "День недели: ??");
41 fmt::print("std::locale gives ?? as a weekday.\n");
42 return;
43 }
44 #endif
45 EXPECT_THAT((std::vector<std::string>{"День недели: пн", "День недели: Пн"}),
46 Contains(s));
47 }
+0
-46
source/misc/embedded_libs/fmt-8.1.1/test/util.cc less more
0 // Formatting library for C++ - test utilities
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "util.h"
8
9 #include <cstring>
10
11 const char* const file_content = "Don't panic!";
12
13 fmt::buffered_file open_buffered_file(FILE** fp) {
14 #if FMT_USE_FCNTL
15 fmt::file read_end, write_end;
16 fmt::file::pipe(read_end, write_end);
17 write_end.write(file_content, std::strlen(file_content));
18 write_end.close();
19 fmt::buffered_file f = read_end.fdopen("r");
20 if (fp) *fp = f.get();
21 #else
22 fmt::buffered_file f("test-file", "w");
23 fputs(file_content, f.get());
24 if (fp) *fp = f.get();
25 #endif
26 return f;
27 }
28
29 std::locale do_get_locale(const char* name) {
30 try {
31 return std::locale(name);
32 } catch (const std::runtime_error&) {
33 }
34 return std::locale::classic();
35 }
36
37 std::locale get_locale(const char* name, const char* alt_name) {
38 auto loc = do_get_locale(name);
39 if (loc == std::locale::classic() && alt_name) {
40 loc = do_get_locale(alt_name);
41 }
42 if (loc == std::locale::classic())
43 fmt::print(stderr, "{} locale is missing.\n", name);
44 return loc;
45 }
+0
-85
source/misc/embedded_libs/fmt-8.1.1/test/util.h less more
0 // Formatting library for C++ - test utilities
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include <cstdarg>
8 #include <cstdio>
9 #include <locale>
10 #include <string>
11
12 #ifdef FMT_MODULE_TEST
13 import fmt;
14 #else
15 # include "fmt/os.h"
16 #endif // FMT_MODULE_TEST
17
18 #ifdef _MSC_VER
19 # define FMT_VSNPRINTF vsprintf_s
20 #else
21 # define FMT_VSNPRINTF vsnprintf
22 #endif
23
24 template <size_t SIZE>
25 void safe_sprintf(char (&buffer)[SIZE], const char* format, ...) {
26 std::va_list args;
27 va_start(args, format);
28 FMT_VSNPRINTF(buffer, SIZE, format, args);
29 va_end(args);
30 }
31
32 extern const char* const file_content;
33
34 // Opens a buffered file for reading.
35 fmt::buffered_file open_buffered_file(FILE** fp = nullptr);
36
37 inline FILE* safe_fopen(const char* filename, const char* mode) {
38 #if defined(_WIN32) && !defined(__MINGW32__)
39 // Fix MSVC warning about "unsafe" fopen.
40 FILE* f = nullptr;
41 errno = fopen_s(&f, filename, mode);
42 return f;
43 #else
44 return std::fopen(filename, mode);
45 #endif
46 }
47
48 template <typename Char> class basic_test_string {
49 private:
50 std::basic_string<Char> value_;
51
52 static const Char empty[];
53
54 public:
55 explicit basic_test_string(const Char* value = empty) : value_(value) {}
56
57 const std::basic_string<Char>& value() const { return value_; }
58 };
59
60 template <typename Char> const Char basic_test_string<Char>::empty[] = {0};
61
62 typedef basic_test_string<char> test_string;
63 typedef basic_test_string<wchar_t> test_wstring;
64
65 template <typename Char>
66 std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os,
67 const basic_test_string<Char>& s) {
68 os << s.value();
69 return os;
70 }
71
72 class date {
73 int year_, month_, day_;
74
75 public:
76 date(int year, int month, int day) : year_(year), month_(month), day_(day) {}
77
78 int year() const { return year_; }
79 int month() const { return month_; }
80 int day() const { return day_; }
81 };
82
83 // Returns a locale with the given name if available or classic locale othewise.
84 std::locale get_locale(const char* name, const char* alt_name = nullptr);
+0
-502
source/misc/embedded_libs/fmt-8.1.1/test/xchar-test.cc less more
0 // Formatting library for C++ - formatting library tests
1 //
2 // Copyright (c) 2012 - present, Victor Zverovich
3 // All rights reserved.
4 //
5 // For the license information refer to format.h.
6
7 #include "fmt/xchar.h"
8
9 #include <complex>
10 #include <cwchar>
11 #include <vector>
12
13 #include "fmt/chrono.h"
14 #include "fmt/color.h"
15 #include "fmt/ostream.h"
16 #include "fmt/ranges.h"
17 #include "gtest-extra.h" // Contains
18 #include "util.h" // get_locale
19
20 using fmt::detail::max_value;
21 using testing::Contains;
22
23 namespace test_ns {
24 template <typename Char> class test_string {
25 private:
26 std::basic_string<Char> s_;
27
28 public:
29 test_string(const Char* s) : s_(s) {}
30 const Char* data() const { return s_.data(); }
31 size_t length() const { return s_.size(); }
32 operator const Char*() const { return s_.c_str(); }
33 };
34
35 template <typename Char>
36 fmt::basic_string_view<Char> to_string_view(const test_string<Char>& s) {
37 return {s.data(), s.length()};
38 }
39
40 struct non_string {};
41 } // namespace test_ns
42
43 template <typename T> class is_string_test : public testing::Test {};
44
45 using string_char_types = testing::Types<char, wchar_t, char16_t, char32_t>;
46 TYPED_TEST_SUITE(is_string_test, string_char_types);
47
48 template <typename Char>
49 struct derived_from_string_view : fmt::basic_string_view<Char> {};
50
51 TYPED_TEST(is_string_test, is_string) {
52 EXPECT_TRUE(fmt::detail::is_string<TypeParam*>::value);
53 EXPECT_TRUE(fmt::detail::is_string<const TypeParam*>::value);
54 EXPECT_TRUE(fmt::detail::is_string<TypeParam[2]>::value);
55 EXPECT_TRUE(fmt::detail::is_string<const TypeParam[2]>::value);
56 EXPECT_TRUE(fmt::detail::is_string<std::basic_string<TypeParam>>::value);
57 EXPECT_TRUE(fmt::detail::is_string<fmt::basic_string_view<TypeParam>>::value);
58 EXPECT_TRUE(
59 fmt::detail::is_string<derived_from_string_view<TypeParam>>::value);
60 using fmt_string_view = fmt::detail::std_string_view<TypeParam>;
61 EXPECT_TRUE(std::is_empty<fmt_string_view>::value !=
62 fmt::detail::is_string<fmt_string_view>::value);
63 EXPECT_TRUE(fmt::detail::is_string<test_ns::test_string<TypeParam>>::value);
64 EXPECT_FALSE(fmt::detail::is_string<test_ns::non_string>::value);
65 }
66
67 // std::is_constructible is broken in MSVC until version 2015.
68 #if !FMT_MSC_VER || FMT_MSC_VER >= 1900
69 struct explicitly_convertible_to_wstring_view {
70 explicit operator fmt::wstring_view() const { return L"foo"; }
71 };
72
73 TEST(xchar_test, format_explicitly_convertible_to_wstring_view) {
74 EXPECT_EQ(L"foo",
75 fmt::format(L"{}", explicitly_convertible_to_wstring_view()));
76 }
77 #endif
78
79 TEST(xchar_test, format) {
80 EXPECT_EQ(L"42", fmt::format(L"{}", 42));
81 EXPECT_EQ(L"4.2", fmt::format(L"{}", 4.2));
82 EXPECT_EQ(L"abc", fmt::format(L"{}", L"abc"));
83 EXPECT_EQ(L"z", fmt::format(L"{}", L'z'));
84 EXPECT_THROW(fmt::format(L"{:*\x343E}", 42), fmt::format_error);
85 EXPECT_EQ(L"true", fmt::format(L"{}", true));
86 EXPECT_EQ(L"a", fmt::format(L"{0}", 'a'));
87 EXPECT_EQ(L"a", fmt::format(L"{0}", L'a'));
88 EXPECT_EQ(L"Cyrillic letter \x42e",
89 fmt::format(L"Cyrillic letter {}", L'\x42e'));
90 EXPECT_EQ(L"abc1", fmt::format(L"{}c{}", L"ab", 1));
91 }
92
93 TEST(xchar_test, is_formattable) {
94 static_assert(!fmt::is_formattable<const wchar_t*>::value, "");
95 }
96
97 TEST(xchar_test, compile_time_string) {
98 #if defined(FMT_USE_STRING_VIEW) && __cplusplus >= 201703L
99 EXPECT_EQ(L"42", fmt::format(FMT_STRING(std::wstring_view(L"{}")), 42));
100 #endif
101 }
102
103 #if __cplusplus > 201103L
104 struct custom_char {
105 int value;
106 custom_char() = default;
107
108 template <typename T>
109 constexpr custom_char(T val) : value(static_cast<int>(val)) {}
110
111 operator int() const { return value; }
112 };
113
114 int to_ascii(custom_char c) { return c; }
115
116 FMT_BEGIN_NAMESPACE
117 template <> struct is_char<custom_char> : std::true_type {};
118 FMT_END_NAMESPACE
119
120 TEST(xchar_test, format_custom_char) {
121 const custom_char format[] = {'{', '}', 0};
122 auto result = fmt::format(format, custom_char('x'));
123 EXPECT_EQ(result.size(), 1);
124 EXPECT_EQ(result[0], custom_char('x'));
125 }
126 #endif
127
128 // Convert a char8_t string to std::string. Otherwise GTest will insist on
129 // inserting `char8_t` NTBS into a `char` stream which is disabled by P1423.
130 template <typename S> std::string from_u8str(const S& str) {
131 return std::string(str.begin(), str.end());
132 }
133
134 TEST(xchar_test, format_utf8_precision) {
135 using str_type = std::basic_string<fmt::detail::char8_type>;
136 auto format =
137 str_type(reinterpret_cast<const fmt::detail::char8_type*>(u8"{:.4}"));
138 auto str = str_type(reinterpret_cast<const fmt::detail::char8_type*>(
139 u8"caf\u00e9s")); // cafés
140 auto result = fmt::format(format, str);
141 EXPECT_EQ(fmt::detail::compute_width(result), 4);
142 EXPECT_EQ(result.size(), 5);
143 EXPECT_EQ(from_u8str(result), from_u8str(str.substr(0, 5)));
144 }
145
146 TEST(xchar_test, format_to) {
147 auto buf = std::vector<wchar_t>();
148 fmt::format_to(std::back_inserter(buf), L"{}{}", 42, L'\0');
149 EXPECT_STREQ(buf.data(), L"42");
150 }
151
152 TEST(xchar_test, vformat_to) {
153 using wcontext = fmt::wformat_context;
154 fmt::basic_format_arg<wcontext> warg = fmt::detail::make_arg<wcontext>(42);
155 auto wargs = fmt::basic_format_args<wcontext>(&warg, 1);
156 auto w = std::wstring();
157 fmt::vformat_to(std::back_inserter(w), L"{}", wargs);
158 EXPECT_EQ(L"42", w);
159 w.clear();
160 fmt::vformat_to(std::back_inserter(w), FMT_STRING(L"{}"), wargs);
161 EXPECT_EQ(L"42", w);
162 }
163
164 TEST(format_test, wide_format_to_n) {
165 wchar_t buffer[4];
166 buffer[3] = L'x';
167 auto result = fmt::format_to_n(buffer, 3, L"{}", 12345);
168 EXPECT_EQ(5u, result.size);
169 EXPECT_EQ(buffer + 3, result.out);
170 EXPECT_EQ(L"123x", fmt::wstring_view(buffer, 4));
171 buffer[0] = L'x';
172 buffer[1] = L'x';
173 buffer[2] = L'x';
174 result = fmt::format_to_n(buffer, 3, L"{}", L'A');
175 EXPECT_EQ(1u, result.size);
176 EXPECT_EQ(buffer + 1, result.out);
177 EXPECT_EQ(L"Axxx", fmt::wstring_view(buffer, 4));
178 result = fmt::format_to_n(buffer, 3, L"{}{} ", L'B', L'C');
179 EXPECT_EQ(3u, result.size);
180 EXPECT_EQ(buffer + 3, result.out);
181 EXPECT_EQ(L"BC x", fmt::wstring_view(buffer, 4));
182 }
183
184 #if FMT_USE_USER_DEFINED_LITERALS
185 TEST(xchar_test, format_udl) {
186 using namespace fmt::literals;
187 EXPECT_EQ(L"{}c{}"_format(L"ab", 1), fmt::format(L"{}c{}", L"ab", 1));
188 }
189
190 TEST(xchar_test, named_arg_udl) {
191 using namespace fmt::literals;
192 auto udl_a =
193 fmt::format(L"{first}{second}{first}{third}", L"first"_a = L"abra",
194 L"second"_a = L"cad", L"third"_a = 99);
195 EXPECT_EQ(
196 fmt::format(L"{first}{second}{first}{third}", fmt::arg(L"first", L"abra"),
197 fmt::arg(L"second", L"cad"), fmt::arg(L"third", 99)),
198 udl_a);
199 }
200 #endif // FMT_USE_USER_DEFINED_LITERALS
201
202 TEST(xchar_test, print) {
203 // Check that the wide print overload compiles.
204 if (fmt::detail::const_check(false)) fmt::print(L"test");
205 }
206
207 TEST(xchar_test, join) {
208 int v[3] = {1, 2, 3};
209 EXPECT_EQ(fmt::format(L"({})", fmt::join(v, v + 3, L", ")), L"(1, 2, 3)");
210 auto t = std::tuple<wchar_t, int, float>('a', 1, 2.0f);
211 EXPECT_EQ(fmt::format(L"({})", fmt::join(t, L", ")), L"(a, 1, 2)");
212 }
213
214 enum streamable_enum {};
215
216 std::wostream& operator<<(std::wostream& os, streamable_enum) {
217 return os << L"streamable_enum";
218 }
219
220 enum unstreamable_enum {};
221
222 TEST(xchar_test, enum) {
223 EXPECT_EQ(L"streamable_enum", fmt::format(L"{}", streamable_enum()));
224 EXPECT_EQ(L"0", fmt::format(L"{}", unstreamable_enum()));
225 }
226
227 TEST(xchar_test, sign_not_truncated) {
228 wchar_t format_str[] = {
229 L'{', L':',
230 '+' | static_cast<wchar_t>(1 << fmt::detail::num_bits<char>()), L'}', 0};
231 EXPECT_THROW(fmt::format(format_str, 42), fmt::format_error);
232 }
233
234 namespace fake_qt {
235 class QString {
236 public:
237 QString(const wchar_t* s) : s_(s) {}
238 const wchar_t* utf16() const FMT_NOEXCEPT { return s_.data(); }
239 int size() const FMT_NOEXCEPT { return static_cast<int>(s_.size()); }
240
241 private:
242 std::wstring s_;
243 };
244
245 fmt::basic_string_view<wchar_t> to_string_view(const QString& s) FMT_NOEXCEPT {
246 return {s.utf16(), static_cast<size_t>(s.size())};
247 }
248 } // namespace fake_qt
249
250 TEST(format_test, format_foreign_strings) {
251 using fake_qt::QString;
252 EXPECT_EQ(fmt::format(QString(L"{}"), 42), L"42");
253 EXPECT_EQ(fmt::format(QString(L"{}"), QString(L"42")), L"42");
254 }
255
256 TEST(xchar_test, chrono) {
257 auto tm = std::tm();
258 tm.tm_year = 116;
259 tm.tm_mon = 3;
260 tm.tm_mday = 25;
261 tm.tm_hour = 11;
262 tm.tm_min = 22;
263 tm.tm_sec = 33;
264 EXPECT_EQ(fmt::format("The date is {:%Y-%m-%d %H:%M:%S}.", tm),
265 "The date is 2016-04-25 11:22:33.");
266 EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds(42)));
267 EXPECT_EQ(fmt::format(L"{:%F}", tm), L"2016-04-25");
268 EXPECT_EQ(fmt::format(L"{:%T}", tm), L"11:22:33");
269 }
270
271 std::wstring system_wcsftime(const std::wstring& format, const std::tm* timeptr,
272 std::locale* locptr = nullptr) {
273 auto loc = locptr ? *locptr : std::locale::classic();
274 auto& facet = std::use_facet<std::time_put<wchar_t>>(loc);
275 std::wostringstream os;
276 os.imbue(loc);
277 facet.put(os, os, L' ', timeptr, format.c_str(),
278 format.c_str() + format.size());
279 #ifdef _WIN32
280 // Workaround a bug in older versions of Universal CRT.
281 auto str = os.str();
282 if (str == L"-0000") str = L"+0000";
283 return str;
284 #else
285 return os.str();
286 #endif
287 }
288
289 TEST(chrono_test, time_point) {
290 auto t1 = std::chrono::system_clock::now();
291
292 std::vector<std::wstring> spec_list = {
293 L"%%", L"%n", L"%t", L"%Y", L"%EY", L"%y", L"%Oy", L"%Ey", L"%C",
294 L"%EC", L"%G", L"%g", L"%b", L"%h", L"%B", L"%m", L"%Om", L"%U",
295 L"%OU", L"%W", L"%OW", L"%V", L"%OV", L"%j", L"%d", L"%Od", L"%e",
296 L"%Oe", L"%a", L"%A", L"%w", L"%Ow", L"%u", L"%Ou", L"%H", L"%OH",
297 L"%I", L"%OI", L"%M", L"%OM", L"%S", L"%OS", L"%x", L"%Ex", L"%X",
298 L"%EX", L"%D", L"%F", L"%R", L"%T", L"%p", L"%z", L"%Z"};
299 spec_list.push_back(L"%Y-%m-%d %H:%M:%S");
300 #ifndef _WIN32
301 // Disabled on Windows, because these formats is not consistent among
302 // platforms.
303 spec_list.insert(spec_list.end(), {L"%c", L"%Ec", L"%r"});
304 #endif
305
306 for (const auto& spec : spec_list) {
307 auto t = std::chrono::system_clock::to_time_t(t1);
308 auto tm = *std::localtime(&t);
309
310 auto sys_output = system_wcsftime(spec, &tm);
311
312 auto fmt_spec = fmt::format(L"{{:{}}}", spec);
313 EXPECT_EQ(sys_output, fmt::format(fmt_spec, t1));
314 EXPECT_EQ(sys_output, fmt::format(fmt_spec, tm));
315 }
316 }
317
318 TEST(xchar_test, color) {
319 EXPECT_EQ(fmt::format(fg(fmt::rgb(255, 20, 30)), L"rgb(255,20,30) wide"),
320 L"\x1b[38;2;255;020;030mrgb(255,20,30) wide\x1b[0m");
321 }
322
323 TEST(xchar_test, ostream) {
324 std::wostringstream wos;
325 fmt::print(wos, L"Don't {}!", L"panic");
326 EXPECT_EQ(L"Don't panic!", wos.str());
327 }
328
329 TEST(xchar_test, to_wstring) { EXPECT_EQ(L"42", fmt::to_wstring(42)); }
330
331 #ifndef FMT_STATIC_THOUSANDS_SEPARATOR
332 template <typename Char> struct numpunct : std::numpunct<Char> {
333 protected:
334 Char do_decimal_point() const override { return '?'; }
335 std::string do_grouping() const override { return "\03"; }
336 Char do_thousands_sep() const override { return '~'; }
337 };
338
339 template <typename Char> struct no_grouping : std::numpunct<Char> {
340 protected:
341 Char do_decimal_point() const override { return '.'; }
342 std::string do_grouping() const override { return ""; }
343 Char do_thousands_sep() const override { return ','; }
344 };
345
346 template <typename Char> struct special_grouping : std::numpunct<Char> {
347 protected:
348 Char do_decimal_point() const override { return '.'; }
349 std::string do_grouping() const override { return "\03\02"; }
350 Char do_thousands_sep() const override { return ','; }
351 };
352
353 template <typename Char> struct small_grouping : std::numpunct<Char> {
354 protected:
355 Char do_decimal_point() const override { return '.'; }
356 std::string do_grouping() const override { return "\01"; }
357 Char do_thousands_sep() const override { return ','; }
358 };
359
360 TEST(locale_test, localized_double) {
361 auto loc = std::locale(std::locale(), new numpunct<char>());
362 EXPECT_EQ("1?23", fmt::format(loc, "{:L}", 1.23));
363 EXPECT_EQ("1?230000", fmt::format(loc, "{:Lf}", 1.23));
364 EXPECT_EQ("1~234?5", fmt::format(loc, "{:L}", 1234.5));
365 EXPECT_EQ("12~000", fmt::format(loc, "{:L}", 12000.0));
366 }
367
368 TEST(locale_test, format) {
369 auto loc = std::locale(std::locale(), new numpunct<char>());
370 EXPECT_EQ("1234567", fmt::format(std::locale(), "{:L}", 1234567));
371 EXPECT_EQ("1~234~567", fmt::format(loc, "{:L}", 1234567));
372 EXPECT_EQ("-1~234~567", fmt::format(loc, "{:L}", -1234567));
373 EXPECT_EQ("-256", fmt::format(loc, "{:L}", -256));
374 fmt::format_arg_store<fmt::format_context, int> as{1234567};
375 EXPECT_EQ("1~234~567", fmt::vformat(loc, "{:L}", fmt::format_args(as)));
376 auto s = std::string();
377 fmt::format_to(std::back_inserter(s), loc, "{:L}", 1234567);
378 EXPECT_EQ("1~234~567", s);
379
380 auto no_grouping_loc = std::locale(std::locale(), new no_grouping<char>());
381 EXPECT_EQ("1234567", fmt::format(no_grouping_loc, "{:L}", 1234567));
382
383 auto special_grouping_loc =
384 std::locale(std::locale(), new special_grouping<char>());
385 EXPECT_EQ("1,23,45,678", fmt::format(special_grouping_loc, "{:L}", 12345678));
386 EXPECT_EQ("12,345", fmt::format(special_grouping_loc, "{:L}", 12345));
387
388 auto small_grouping_loc =
389 std::locale(std::locale(), new small_grouping<char>());
390 EXPECT_EQ("4,2,9,4,9,6,7,2,9,5",
391 fmt::format(small_grouping_loc, "{:L}", max_value<uint32_t>()));
392 }
393
394 TEST(locale_test, format_detault_align) {
395 auto loc = std::locale({}, new special_grouping<char>());
396 EXPECT_EQ(" 12,345", fmt::format(loc, "{:8L}", 12345));
397 }
398
399 TEST(locale_test, format_plus) {
400 auto loc = std::locale({}, new special_grouping<char>());
401 EXPECT_EQ("+100", fmt::format(loc, "{:+L}", 100));
402 }
403
404 TEST(locale_test, wformat) {
405 auto loc = std::locale(std::locale(), new numpunct<wchar_t>());
406 EXPECT_EQ(L"1234567", fmt::format(std::locale(), L"{:L}", 1234567));
407 EXPECT_EQ(L"1~234~567", fmt::format(loc, L"{:L}", 1234567));
408 using wcontext = fmt::buffer_context<wchar_t>;
409 fmt::format_arg_store<wcontext, int> as{1234567};
410 EXPECT_EQ(L"1~234~567",
411 fmt::vformat(loc, L"{:L}", fmt::basic_format_args<wcontext>(as)));
412 EXPECT_EQ(L"1234567", fmt::format(std::locale("C"), L"{:L}", 1234567));
413
414 auto no_grouping_loc = std::locale(std::locale(), new no_grouping<wchar_t>());
415 EXPECT_EQ(L"1234567", fmt::format(no_grouping_loc, L"{:L}", 1234567));
416
417 auto special_grouping_loc =
418 std::locale(std::locale(), new special_grouping<wchar_t>());
419 EXPECT_EQ(L"1,23,45,678",
420 fmt::format(special_grouping_loc, L"{:L}", 12345678));
421
422 auto small_grouping_loc =
423 std::locale(std::locale(), new small_grouping<wchar_t>());
424 EXPECT_EQ(L"4,2,9,4,9,6,7,2,9,5",
425 fmt::format(small_grouping_loc, L"{:L}", max_value<uint32_t>()));
426 }
427
428 TEST(locale_test, double_formatter) {
429 auto loc = std::locale(std::locale(), new special_grouping<char>());
430 auto f = fmt::formatter<int>();
431 auto parse_ctx = fmt::format_parse_context("L");
432 f.parse(parse_ctx);
433 char buf[10] = {};
434 fmt::basic_format_context<char*, char> format_ctx(
435 buf, {}, fmt::detail::locale_ref(loc));
436 *f.format(12345, format_ctx) = 0;
437 EXPECT_STREQ("12,345", buf);
438 }
439
440 FMT_BEGIN_NAMESPACE
441 template <class charT> struct formatter<std::complex<double>, charT> {
442 private:
443 detail::dynamic_format_specs<char> specs_;
444
445 public:
446 FMT_CONSTEXPR typename basic_format_parse_context<charT>::iterator parse(
447 basic_format_parse_context<charT>& ctx) {
448 using handler_type =
449 detail::dynamic_specs_handler<basic_format_parse_context<charT>>;
450 detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
451 detail::type::string_type);
452 auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
453 detail::parse_float_type_spec(specs_, ctx.error_handler());
454 return it;
455 }
456
457 template <class FormatContext>
458 typename FormatContext::iterator format(const std::complex<double>& c,
459 FormatContext& ctx) {
460 detail::handle_dynamic_spec<detail::precision_checker>(
461 specs_.precision, specs_.precision_ref, ctx);
462 auto specs = std::string();
463 if (specs_.precision > 0) specs = fmt::format(".{}", specs_.precision);
464 if (specs_.type == presentation_type::fixed_lower) specs += 'f';
465 auto real = fmt::format(ctx.locale().template get<std::locale>(),
466 fmt::runtime("{:" + specs + "}"), c.real());
467 auto imag = fmt::format(ctx.locale().template get<std::locale>(),
468 fmt::runtime("{:" + specs + "}"), c.imag());
469 auto fill_align_width = std::string();
470 if (specs_.width > 0) fill_align_width = fmt::format(">{}", specs_.width);
471 return format_to(ctx.out(), runtime("{:" + fill_align_width + "}"),
472 c.real() != 0 ? fmt::format("({}+{}i)", real, imag)
473 : fmt::format("{}i", imag));
474 }
475 };
476 FMT_END_NAMESPACE
477
478 TEST(locale_test, complex) {
479 std::string s = fmt::format("{}", std::complex<double>(1, 2));
480 EXPECT_EQ(s, "(1+2i)");
481 EXPECT_EQ(fmt::format("{:.2f}", std::complex<double>(1, 2)), "(1.00+2.00i)");
482 EXPECT_EQ(fmt::format("{:8}", std::complex<double>(1, 2)), " (1+2i)");
483 }
484
485 TEST(locale_test, chrono_weekday) {
486 auto loc = get_locale("ru_RU.UTF-8", "Russian_Russia.1251");
487 auto loc_old = std::locale::global(loc);
488 auto mon = fmt::weekday(1);
489 EXPECT_EQ(fmt::format(L"{}", mon), L"Mon");
490 if (loc != std::locale::classic()) {
491 // {L"\x43F\x43D", L"\x41F\x43D", L"\x43F\x43D\x434", L"\x41F\x43D\x434"}
492 // {L"пн", L"Пн", L"пнд", L"Пнд"}
493 EXPECT_THAT(
494 (std::vector<std::wstring>{L"\x43F\x43D", L"\x41F\x43D",
495 L"\x43F\x43D\x434", L"\x41F\x43D\x434"}),
496 Contains(fmt::format(loc, L"{:L}", mon)));
497 }
498 std::locale::global(loc_old);
499 }
500
501 #endif // FMT_STATIC_THOUSANDS_SEPARATOR