cppformat-1.1.0/000077500000000000000000000000001247635332500135165ustar00rootroot00000000000000cppformat-1.1.0/.gitignore000066400000000000000000000002671247635332500155130ustar00rootroot00000000000000/bin /_CPack_Packages /doc/doxyxml /doc/html /Testing /install_manifest.txt *~ *.a *.zip cmake_install.cmake CPack*Config.cmake CTestTestfile.cmake CMakeCache.txt CMakeFiles Makefile cppformat-1.1.0/.gitmodules000066400000000000000000000003441247635332500156740ustar00rootroot00000000000000[submodule "breathe"] path = breathe url = https://github.com/michaeljones/breathe.git [submodule "doc/sphinx-bootstrap-theme"] path = doc/sphinx-bootstrap-theme url = https://github.com/cppformat/sphinx-bootstrap-theme.git cppformat-1.1.0/CMakeLists.txt000066400000000000000000000126711247635332500162650ustar00rootroot00000000000000message(STATUS "CMake version: ${CMAKE_VERSION}") cmake_minimum_required(VERSION 2.6) # Set the default CMAKE_BUILD_TYPE to Release. # This should be done before the project command since the latter can set # CMAKE_BUILD_TYPE itself (it does so for nmake). if (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.") endif () option(FMT_EXTRA_TESTS "Enable extra tests." OFF) project(FORMAT) message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) include(CheckCXXCompilerFlag) check_cxx_compiler_flag(-std=c++11 HAVE_STD_CPP11_FLAG) if (HAVE_STD_CPP11_FLAG) set(CPP11_FLAG -std=c++11) else () check_cxx_compiler_flag(-std=c++0x HAVE_STD_CPP0X_FLAG) if (HAVE_STD_CPP0X_FLAG) set(CPP11_FLAG -std=c++0x) endif () endif () set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/support/cmake") if (CMAKE_GENERATOR MATCHES "Visual Studio") # If Microsoft SDK is installed create script run-msbuild.bat that # calls SetEnv.cmd to to set up build environment and runs msbuild. # It is useful when building Visual Studio projects with the SDK # toolchain rather than Visual Studio. include(FindSetEnv) if (WINSDK_SETENV) set(MSBUILD_SETUP "call \"${WINSDK_SETENV}\"") endif () # Set FrameworkPathOverride to get rid of MSB3644 warnings. set(netfxpath "C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0") file(WRITE run-msbuild.bat " ${MSBUILD_SETUP} ${CMAKE_MAKE_PROGRAM} -p:FrameworkPathOverride=\"${netfxpath}\" %*") endif () set(FMT_SOURCES format.cc format.h) include(CheckSymbolExists) if (WIN32) check_symbol_exists(open io.h HAVE_OPEN) else () check_symbol_exists(open fcntl.h HAVE_OPEN) endif () if (HAVE_OPEN) add_definitions(-DFMT_USE_FILE_DESCRIPTORS=1) set(FMT_SOURCES ${FMT_SOURCES} posix.cc posix.h) endif () if (CPP11_FLAG) set(CMAKE_REQUIRED_FLAGS ${CPP11_FLAG}) endif () if (BIICODE) include(support/cmake/biicode.cmake) return() endif () add_library(format ${FMT_SOURCES}) if (CMAKE_COMPILER_IS_GNUCXX) set_target_properties(format PROPERTIES COMPILE_FLAGS "-Wall -Wextra -Wshadow -pedantic") endif () if (CPP11_FLAG AND FMT_EXTRA_TESTS) set_target_properties(format PROPERTIES COMPILE_FLAGS ${CPP11_FLAG}) # Test compilation with default flags. file(GLOB src RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} test/*.cc test/*.h) add_library(testformat STATIC ${FMT_SOURCE_FILES} ${src}) endif () add_subdirectory(doc) include_directories(. gmock) # We compile Google Test ourselves instead of using pre-compiled libraries. # See the Google Test FAQ "Why is it not recommended to install a # pre-compiled copy of Google Test (for example, into /usr/local)?" # at http://code.google.com/p/googletest/wiki/FAQ for more details. add_library(gmock STATIC gmock/gmock-gtest-all.cc) find_package(Threads) target_link_libraries(gmock ${CMAKE_THREAD_LIBS_INIT}) # Check if variadic templates are working and not affected by GCC bug 39653: # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=39653 check_cxx_source_compiles(" template struct S { typedef typename S::type type; }; int main() {}" FMT_VARIADIC_TEMPLATES) # Check if initializer lists are supported. check_cxx_source_compiles(" #include int main() {}" FMT_INITIALIZER_LIST) if (NOT FMT_VARIADIC_TEMPLATES OR NOT FMT_INITIALIZER_LIST) add_definitions(-DGTEST_LANG_CXX11=0) endif () # This is disabled at the moment because format is compiled without -std=c++11 # by default. #check_cxx_source_compiles(" # void f() noexcept {} # int main(){ f(); }" FMT_BASIC_NOEXCEPT_SUPPORT) #if (FMT_BASIC_NOEXCEPT_SUPPORT) # add_definitions(-DFMT_USE_NOEXCEPT=1) #endif () #check_cxx_source_compiles(" # struct C{ # C()=delete; # C(const C&)=delete; # C& operator=(const C&)=delete; # }; # int main(){}" FMT_DELETED_FUNCTIONS) #if (FMT_DELETED_FUNCTIONS) # add_definitions(-DFMT_USE_DELETED_FUNCTIONS=1) #endif () #check_cxx_source_compiles(" # static_assert(true, \"\"); # int main(){}" FMT_STATIC_ASSERT) #if (FMT_STATIC_ASSERT) # add_definitions(-DFMT_USE_STATIC_ASSERT=1) #endif () # GTest doesn't detect with clang. if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") target_compile_definitions(gmock PUBLIC GTEST_USE_OWN_TR1_TUPLE=1) endif () enable_testing() add_subdirectory(test) if (EXISTS .gitignore) # Get the list of ignored files from .gitignore. file (STRINGS ".gitignore" lines) LIST(REMOVE_ITEM lines /doc/html) foreach (line ${lines}) string(REPLACE "." "[.]" line "${line}") string(REPLACE "*" ".*" line "${line}") set(ignored_files ${ignored_files} "${line}$" "${line}/") endforeach () set(ignored_files ${ignored_files} /.git /breathe /format-benchmark sphinx/) set(CPACK_SOURCE_GENERATOR ZIP) set(CPACK_SOURCE_IGNORE_FILES ${ignored_files}) set(CPACK_PACKAGE_VERSION_MAJOR 1) set(CPACK_PACKAGE_VERSION_MINOR 1) set(CPACK_PACKAGE_VERSION_PATCH 0) set(CPPFORMAT_VERSION ${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}) set(CPACK_SOURCE_PACKAGE_FILE_NAME cppformat-${CPPFORMAT_VERSION}) set(CPACK_RESOURCE_FILE_README ${FORMAT_SOURCE_DIR}/README.rst) include(CPack) endif () # Install our targets install(TARGETS format DESTINATION lib) install(FILES format.h DESTINATION include) cppformat-1.1.0/ChangeLog.rst000066400000000000000000000261641247635332500161100ustar00rootroot000000000000001.1.0 - 2015-03-06 ------------------ * Added ``BasicArrayWriter``, a class template that provides operations for formatting and writing data into a fixed-size array (`#105 `_ and `#122 `_): .. code:: c++ char buffer[100]; fmt::ArrayWriter w(buffer); w.write("The answer is {}", 42); * Added `0 A.D. `_ and `PenUltima Online (POL) `_ to the list of notable projects using C++ Format. * C++ Format now uses MSVC intrinsics for better formatting performance (`#115 `_, `#116 `_, `#118 `_ and `#121 `_). Previously these optimizations where only used on GCC and Clang. Thanks to `@CarterLi `_ and `@objectx `_. * CMake install target (`#119 `_). Thanks to `@TrentHouliston `_. You can now install C++ Format with ``make install`` command. * Improved `Biicode `_ support (`#98 `_ and `#104 `_). Thanks to `@MariadeAnton `_ and `@franramirez688 `_. * Improved support for bulding with `Android NDK `_ (`#107 `_). Thanks to `@newnon `_. The `android-ndk-example `_ repository provides and example of using C++ Format with Android NDK: .. image:: https://raw.githubusercontent.com/cppformat/android-ndk-example/ master/screenshot.png * Improved documentation of ``SystemError`` and ``WindowsError`` (`#54 `_). * Various code improvements (`#110 `_, `#111 `_ `#112 `_). Thanks to `@CarterLi `_. * Improved compile-time errors when formatting wide into narrow strings (`#117 `_). * Fixed ``BasicWriter::write`` without formatting arguments when C++11 support is disabled (`#109 `_). * Fixed header-only build on OS X with GCC 4.9 (`#124 `_). * Fixed packaging issues (`#94 `_). * Fixed warnings in GCC, MSVC and Xcode/Clang (`#95 `_, `#96 `_ and `#114 `_). * Added `changelog `_ (`#103 `_). 1.0.0 - 2015-02-05 ------------------ * Add support for a header-only configuration when ``FMT_HEADER_ONLY`` is defined before including ``format.h``: .. code:: c++ #define FMT_HEADER_ONLY #include "format.h" * Compute string length in the constructor of ``BasicStringRef`` instead of the ``size`` method (`#79 `_). This eliminates size computation for string literals on reasonable optimizing compilers. * Fix formatting of types with overloaded ``operator <<`` for ``std::wostream`` (`#86 `_): .. code:: c++ fmt::format(L"The date is {0}", Date(2012, 12, 9)); * Fix linkage of tests on Arch Linux (`#89 `_). * Allow precision specifier for non-float arguments (`#90 `_): .. code:: c++ fmt::print("{:.3}\n", "Carpet"); // prints "Car" * Fix build on Android NDK (`#93 `_) * Improvements to documentation build procedure. * Remove ``FMT_SHARED`` CMake variable in favor of standard `BUILD_SHARED_LIBS `_. * Fix error handling in ``fmt::fprintf``. * Fix a number of warnings. 0.12.0 - 2014-10-25 ------------------- * [Breaking] Improved separation between formatting and buffer management. ``Writer`` is now a base class that cannot be instantiated directly. The new ``MemoryWriter`` class implements the default buffer management with small allocations done on stack. So ``fmt::Writer`` should be replaced with ``fmt::MemoryWriter`` in variable declarations. Old code: .. code:: c++ fmt::Writer w; New code: .. code:: c++ fmt::MemoryWriter w; If you pass ``fmt::Writer`` by reference, you can continue to do so: .. code:: c++ void f(fmt::Writer &w); This doesn't affect the formatting API. * Support for custom memory allocators (`#69 `_) * Formatting functions now accept `signed char` and `unsigned char` strings as arguments (`#73 `_): .. code:: c++ auto s = format("GLSL version: {}", glGetString(GL_VERSION)); * Reduced code bloat. According to the new `benchmark results `_, cppformat is close to ``printf`` and by the order of magnitude better than Boost Format in terms of compiled code size. * Improved appearance of the documentation on mobile by using the `Sphinx Bootstrap theme `_: .. |old| image:: https://cloud.githubusercontent.com/assets/576385/4792130/ cd256436-5de3-11e4-9a62-c077d0c2b003.png .. |new| image:: https://cloud.githubusercontent.com/assets/576385/4792131/ cd29896c-5de3-11e4-8f59-cac952942bf0.png +-------+-------+ | Old | New | +-------+-------+ | |old| | |new| | +-------+-------+ 0.11.0 - 2014-08-21 ------------------- * Safe printf implementation with a POSIX extension for positional arguments: .. code:: c++ fmt::printf("Elapsed time: %.2f seconds", 1.23); fmt::printf("%1$s, %3$d %2$s", weekday, month, day); * Arguments of ``char`` type can now be formatted as integers (Issue `#55 `_): .. code:: c++ fmt::format("0x{0:02X}", 'a'); * Deprecated parts of the API removed. * The library is now built and tested on MinGW with Appveyor in addition to existing test platforms Linux/GCC, OS X/Clang, Windows/MSVC. 0.10.0 - 2014-07-01 ------------------- **Improved API** * All formatting methods are now implemented as variadic functions instead of using ``operator<<`` for feeding arbitrary arguments into a temporary formatter object. This works both with C++11 where variadic templates are used and with older standards where variadic functions are emulated by providing lightweight wrapper functions defined with the ``FMT_VARIADIC`` macro. You can use this macro for defining your own portable variadic functions: .. code:: c++ void report_error(const char *format, const fmt::ArgList &args) { fmt::print("Error: {}"); fmt::print(format, args); } FMT_VARIADIC(void, report_error, const char *) report_error("file not found: {}", path); Apart from a more natural syntax, this also improves performance as there is no need to construct temporary formatter objects and control arguments' lifetimes. Because the wrapper functions are very ligthweight, this doesn't cause code bloat even in pre-C++11 mode. * Simplified common case of formatting an ``std::string``. Now it requires a single function call: .. code:: c++ std::string s = format("The answer is {}.", 42); Previously it required 2 function calls: .. code:: c++ std::string s = str(Format("The answer is {}.") << 42); Instead of unsafe ``c_str`` function, ``fmt::Writer`` should be used directly to bypass creation of ``std::string``: .. code:: c++ fmt::Writer w; w.write("The answer is {}.", 42); w.c_str(); // returns a C string This doesn't do dynamic memory allocation for small strings and is less error prone as the lifetime of the string is the same as for ``std::string::c_str`` which is well understood (hopefully). * Improved consistency in naming functions that are a part of the public API. Now all public functions are lowercase following the standard library conventions. Previously it was a combination of lowercase and CapitalizedWords. Issue `#50 `_. * Old functions are marked as deprecated and will be removed in the next release. **Other Changes** * Experimental support for printf format specifications (work in progress): .. code:: c++ fmt::printf("The answer is %d.", 42); std::string s = fmt::sprintf("Look, a %s!", "string"); * Support for hexadecimal floating point format specifiers ``a`` and ``A``: .. code:: c++ print("{:a}", -42.0); // Prints -0x1.5p+5 print("{:A}", -42.0); // Prints -0X1.5P+5 * CMake option ``FMT_SHARED`` that specifies whether to build format as a shared library (off by default). 0.9.0 - 2014-05-13 ------------------ * More efficient implementation of variadic formatting functions. * ``Writer::Format`` now has a variadic overload: .. code:: c++ Writer out; out.Format("Look, I'm {}!", "variadic"); * For efficiency and consistency with other overloads, variadic overload of the ``Format`` function now returns ``Writer`` instead of ``std::string``. Use the ``str`` function to convert it to ``std::string``: .. code:: c++ std::string s = str(Format("Look, I'm {}!", "variadic")); * Replaced formatter actions with output sinks: ``NoAction`` -> ``NullSink``, ``Write`` -> ``FileSink``, ``ColorWriter`` -> ``ANSITerminalSink``. This improves naming consistency and shouldn't affect client code unless these classes are used directly which should be rarely needed. * Added ``ThrowSystemError`` function that formats a message and throws ``SystemError`` containing the formatted message and system-specific error description. For example, the following code .. code:: c++ FILE *f = fopen(filename, "r"); if (!f) ThrowSystemError(errno, "Failed to open file '{}'") << filename; will throw ``SystemError`` exception with description "Failed to open file '': No such file or directory" if file doesn't exist. * Support for AppVeyor continuous integration platform. * ``Format`` now throws ``SystemError`` in case of I/O errors. * Improve test infrastructure. Print functions are now tested by redirecting the output to a pipe. 0.8.0 - 2014-04-14 ------------------ * Initial release cppformat-1.1.0/README.rst000066400000000000000000000413621247635332500152130ustar00rootroot00000000000000C++ Format ========== .. image:: https://travis-ci.org/cppformat/cppformat.png?branch=master :target: https://travis-ci.org/cppformat/cppformat .. image:: https://ci.appveyor.com/api/projects/status/qk0bhyhqp1ekpat8 :target: https://ci.appveyor.com/project/vitaut/cppformat .. image:: https://readthedocs.org/projects/cppformat/badge/?version=stable :target: http://cppformat.readthedocs.org/en/stable/ :alt: Documentation Status .. image:: https://webapi.biicode.com/v1/badges/vitaut/vitaut/cppformat/master :target: https://www.biicode.com/vitaut/cppformat C++ Format is an open-source formatting library for C++. It can be used as a safe alternative to printf or as a fast alternative to IOStreams. Features -------- * Two APIs: faster concatenation-based write API and slower (but still very fast) replacement-based format API with positional arguments for localization. * Write API similar to the one used by IOStreams but stateless allowing faster implementation. * Format API with `format string syntax `_ similar to the one used by `str.format `_ in Python. * Safe `printf implementation `_ including the POSIX extension for positional arguments. * Support for user-defined types. * High speed: performance of the format API is close to that of glibc's `printf `_ and better than performance of IOStreams. See `Speed tests`_ and `Fast integer to string conversion in C++ `_. * Small code size both in terms of source code (format consists of a single header file and a single source file) and compiled code. See `Compile time and code bloat`_. * Reliability: the library has an extensive set of `unit tests `_. * Safety: the library is fully type safe, errors in format strings are reported using exceptions, automatic memory management prevents buffer overflow errors. * Ease of use: small self-contained code base, no external dependencies, permissive BSD `license`_. * `Portability `_ with consistent output across platforms and support for older compilers. * Clean warning-free codebase even on high warning levels (-Wall -Wextra -pedantic). * Support for wide strings. * Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro. See the `documentation `_ for more details. Examples -------- This prints ``Hello, world!`` to stdout: .. code:: c++ fmt::print("Hello, {}!", "world"); // uses Python-like format string syntax fmt::printf("Hello, %s!", "world"); // uses printf format string syntax Arguments can be accessed by position and arguments' indices can be repeated: .. code:: c++ std::string s = fmt::format("{0}{1}{0}", "abra", "cad"); // s == "abracadabra" C++ Format can be used as a safe portable replacement for ``itoa``: .. code:: c++ fmt::MemoryWriter w; w << 42; // replaces itoa(42, buffer, 10) w << fmt::hex(42); // replaces itoa(42, buffer, 16) // access the string using w.str() or w.c_str() An object of any user-defined type for which there is an overloaded :code:`std::ostream` insertion operator (``operator<<``) can be formatted: .. code:: c++ class Date { int year_, month_, day_; public: Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} friend std::ostream &operator<<(std::ostream &os, const Date &d) { return os << d.year_ << '-' << d.month_ << '-' << d.day_; } }; std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); // s == "The date is 2012-12-9" You can use the `FMT_VARIADIC `_ macro to create your own functions similar to `format `_ and `print `_ which take arbitrary arguments: .. code:: c++ // Prints formatted error message. void report_error(const char *format, fmt::ArgList args) { fmt::print("Error: "); fmt::print(format, args); } FMT_VARIADIC(void, report_error, const char *) report_error("file not found: {}", path); Note that you only need to define one function that takes ``fmt::ArgList`` argument. ``FMT_VARIADIC`` automatically defines necessary wrappers that accept variable number of arguments. Projects using this library --------------------------- * `0 A.D. `_: A free, open-source, cross-platform real-time strategy game * `AMPL/MP `_: An open-source library for mathematical programming * `HarpyWar/pvpgn `_: Player vs Player Gaming Network with tweaks * `KBEngine `_: An open-source MMOG server engine * `Lifeline `_: A 2D game * `PenUltima Online (POL) `_: An MMO server, compatible with most Ultima Online clients * `readpe `_: Read Portable Executable * `Saddy `_: Small crossplatform 2D graphic engine * `Salesforce Analytics Cloud `_: Business intelligence software * `spdlog `_: Super fast C++ logging library `More... `_ If you are aware of other projects using this library, please let me know by `email `_ or by submitting an `issue `_. Motivation ---------- So why yet another formatting library? There are plenty of methods for doing this task, from standard ones like the printf family of function and IOStreams to Boost Format library and FastFormat. The reason for creating a new library is that every existing solution that I found either had serious issues or didn't provide all the features I needed. Printf ~~~~~~ The good thing about printf is that it is very fast and readily available being a part of the C standard library. The main drawback is that it doesn't support user-defined types. Printf also has safety issues although they are mostly solved with `_attribute__ ((format (printf, ...)) `_ in GCC. There is a POSIX extension that adds positional arguments required for `i18n `_ to printf but it is not a part of C99 and may not be available on some platforms. IOStreams ~~~~~~~~~ The main issue with IOStreams is best illustrated with an example: .. code:: c++ std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; which is a lot of typing compared to printf: .. code:: c++ printf("%.2f\n", 1.23456); Matthew Wilson, the author of FastFormat, referred to this situation with IOStreams as "chevron hell". IOStreams doesn't support positional arguments by design. The good part is that IOStreams supports user-defined types and is safe although error reporting is awkward. Boost Format library ~~~~~~~~~~~~~~~~~~~~ This is a very powerful library which supports both printf-like format strings and positional arguments. The main its drawback is performance. According to various benchmarks it is much slower than other methods considered here. Boost Format also has excessive build times and severe code bloat issues (see `Benchmarks`_). FastFormat ~~~~~~~~~~ This is an interesting library which is fast, safe and has positional arguments. However it has significant limitations, citing its author: Three features that have no hope of being accommodated within the current design are: * Leading zeros (or any other non-space padding) * Octal/hexadecimal encoding * Runtime width/alignment specification It is also quite big and has a heavy dependency, STLSoft, which might be too restrictive for using it in some projects. Loki SafeFormat ~~~~~~~~~~~~~~~ SafeFormat is a formatting library which uses printf-like format strings and is type safe. It doesn't support user-defined types or positional arguments. It makes unconventional use of ``operator()`` for passing format arguments. Tinyformat ~~~~~~~~~~ This library supports printf-like format strings and is very small and fast. Unfortunately it doesn't support positional arguments and wrapping it in C++98 is somewhat difficult. Also its performance and code compactness are limited by IOStreams. Boost Spirit.Karma ~~~~~~~~~~~~~~~~~~ This is not really a formatting library but I decided to include it here for completeness. As IOStreams it suffers from the problem of mixing verbatim text with arguments. The library is pretty fast, but slower on integer formatting than ``fmt::Writer`` on Karma's own benchmark, see `Fast integer to string conversion in C++ `_. What Users Say -------------- Thanks for creating this library. It’s been a hole in C++ for a long time. I’ve used both boost::format and loki::SPrintf, and neither felt like the right answer. This does. -- Kurt Haas Benchmarks ---------- Speed tests ~~~~~~~~~~~ The following speed tests results were generated by building ``tinyformat_test.cpp`` on Ubuntu GNU/Linux 14.04.1 with ``g++-4.8.2 -O3 -DSPEED_TEST -DHAVE_FORMAT``, and taking the best of three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"`` or equivalent is filled 2000000 times with output sent to ``/dev/null``; for further details see the `source `_. ================= ============= =========== Library Method Run Time, s ================= ============= =========== EGLIBC 2.19 printf 1.30 libstdc++ 4.8.2 std::ostream 1.85 C++ Format 1.0 fmt::print 1.42 tinyformat 2.0.1 tfm::printf 2.25 Boost Format 1.54 boost::format 9.94 ================= ============= =========== As you can see boost::format is much slower than the alternative methods; this is confirmed by `other tests `_. Tinyformat is quite good coming close to IOStreams. Unfortunately tinyformat cannot be faster than the IOStreams because it uses them internally. Performance of cppformat is close to that of printf, being `faster than printf on integer formatting `_, but slower on floating-point formatting which dominates this benchmark. Compile time and code bloat ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The script `bloat-test.py `_ from `format-benchmark `_ tests compile time and code bloat for nontrivial projects. It generates 100 translation units and uses ``printf()`` or its alternative five times in each to simulate a medium sized project. The resulting executable size and compile time (g++-4.8.1, Ubuntu GNU/Linux 13.10, best of three) is shown in the following tables. **Optimized build (-O3)** ============ =============== ==================== ================== Method Compile Time, s Executable size, KiB Stripped size, KiB ============ =============== ==================== ================== printf 2.6 41 30 IOStreams 19.4 92 70 C++ Format 46.8 46 34 tinyformat 64.6 418 386 Boost Format 222.8 990 923 ============ =============== ==================== ================== As you can see, C++ Format has 80% less overhead in terms of resulting code size compared to IOStreams and comes pretty close to ``printf``. Boost Format has by far the largest overheads. **Non-optimized build** ============ =============== ==================== ================== Method Compile Time, s Executable size, KiB Stripped size, KiB ============ =============== ==================== ================== printf 2.1 41 30 IOStreams 19.7 86 62 C++ Format 47.9 108 86 tinyformat 27.7 234 190 Boost Format 122.6 884 763 ============ =============== ==================== ================== ``libc``, ``libstdc++`` and ``libformat`` are all linked as shared libraries to compare formatting function overhead only. Boost Format and tinyformat are header-only libraries so they don't provide any linkage options. Running the tests ~~~~~~~~~~~~~~~~~ Please refer to `Building the library`__ for the instructions on how to build the library and run the unit tests. __ http://cppformat.readthedocs.org/en/latest/usage.html#building-the-library Benchmarks reside in a separate repository, `format-benchmarks `_, so to run the benchmarks you first need to clone this repository and generate Makefiles with CMake:: $ git clone --recursive https://github.com/cppformat/format-benchmark.git $ cd format-benchmark $ cmake . Then you can run the speed test:: $ make speed-test or the bloat test:: $ make bloat-test License ------- Copyright (c) 2012 - 2015, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Documentation License --------------------- The `Format String Syntax `_ section in the documentation is based on the one from Python `string module documentation `_ adapted for the current library. For this reason the documentation is distributed under the Python Software Foundation license available in `doc/LICENSE.python `_. Acknowledgments --------------- The benchmark section of this readme file and the performance tests are taken from the excellent `tinyformat `_ library written by Chris Foster. Boost Format library is acknowledged transitively since it had some influence on tinyformat. Some ideas used in the implementation are borrowed from `Loki `_ SafeFormat and `Diagnostic API `_ in `Clang `_. Format string syntax and the documentation are based on Python's `str.format `_. Thanks `Doug Turnbull `_ for his valuable comments and contribution to the design of the type-safe API and `Gregory Czajkowski `_ for implementing binary formatting. Thanks `Ruslan Baratov `_ for comprehensive `comparison of integer formatting algorithms `_ and useful comments regarding performance, `Boris Kaul `_ for `C++ counting digits benchmark `_. cppformat-1.1.0/doc/000077500000000000000000000000001247635332500142635ustar00rootroot00000000000000cppformat-1.1.0/doc/CMakeLists.txt000066400000000000000000000006611247635332500170260ustar00rootroot00000000000000if (NOT EXISTS ${FORMAT_SOURCE_DIR}/breathe/breathe) message(STATUS "Target 'doc' disabled (requires breathe module)") return () endif () foreach (program doxygen sphinx-build) find_program(${program} ${program}) if (NOT ${program}) message(STATUS "Target 'doc' disabled (requires ${program})") return () endif () endforeach () add_custom_target(doc COMMAND ${doxygen} COMMAND ${sphinx-build} -b html . html) cppformat-1.1.0/doc/Doxyfile000066400000000000000000000011171247635332500157710ustar00rootroot00000000000000PROJECT_NAME = C++ Format GENERATE_LATEX = NO GENERATE_MAN = NO GENERATE_RTF = NO CASE_SENSE_NAMES = NO INPUT = ../format.h QUIET = YES JAVADOC_AUTOBRIEF = YES AUTOLINK_SUPPORT = NO GENERATE_HTML = NO GENERATE_XML = YES XML_OUTPUT = doxyxml ALIASES = "rst=\verbatim embed:rst" ALIASES += "endrst=\endverbatim" PREDEFINED = _WIN32=1 \ FMT_NO_DEPRECATED=1 \ FMT_USE_VARIADIC_TEMPLATES=1 \ FMT_USE_RVALUE_REFERENCES=1 EXCLUDE_SYMBOLS = fmt::internal::* BasicArg FormatParser StringValue \ write_str cppformat-1.1.0/doc/_static/000077500000000000000000000000001247635332500157115ustar00rootroot00000000000000cppformat-1.1.0/doc/_static/breathe.css000066400000000000000000000005701247635332500200370ustar00rootroot00000000000000 /* -- breathe specific styles ----------------------------------------------- */ /* So enum value descriptions are displayed inline to the item */ .breatheenumvalues li tt + p { display: inline; } /* So parameter descriptions are displayed inline to the item */ .breatheparameterlist li tt + p { display: inline; } .container .breathe-sectiondef { width: inherit; } cppformat-1.1.0/doc/_static/cppformat.css000066400000000000000000000001461247635332500204170ustar00rootroot00000000000000.class dd, .define dd, .function dd { margin-left: 30px; } .public-func dd { margin-left: 0px; } cppformat-1.1.0/doc/_templates/000077500000000000000000000000001247635332500164205ustar00rootroot00000000000000cppformat-1.1.0/doc/conf.py000066400000000000000000000213311247635332500155620ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # format documentation build configuration file, created by # sphinx-quickstart on Tue Dec 18 06:46:16 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os, re, subprocess # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' sys.path.append("../breathe") if os.environ.get('READTHEDOCS', None) == 'True': subprocess.call('doxygen') # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.ifconfig', 'breathe'] breathe_projects = { "format": "doxyxml" } breathe_default_project = "format" breathe_domain_by_extension = {"h" : "cpp"} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'C++ Format' copyright = u'2012-2014, Victor Zverovich' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. # Get version from CMakeLists.txt. version = {} with open('../CMakeLists.txt') as f: for line in f: m = re.match(r'set\(CPACK_PACKAGE_VERSION_([A-Z]+) ([0-9]+)\)', line.strip()) if m: kind, value = m.groups() version[kind] = value version = '{}.{}.{}'.format(version['MAJOR'], version['MINOR'], version['PATCH']) # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['sphinx-bootstrap-theme/*'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' highlight_language = 'c++' primary_domain = 'cpp' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'bootstrap' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { # HTML navbar class (Default: "navbar") to attach to
. # For black navbar, do "navbar navbar-inverse" #'navbar_class': "navbar navbar-inverse", # Fix navigation bar to top of page? # Values: "true" (default) or "false" 'navbar_fixed_top': "true", # Location of link to source. # Options are "nav" (default), "footer". 'source_link_position': "footer", # Render the next and previous page links in navbar. (Default: true) 'navbar_sidebarrel': False } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['sphinx-bootstrap-theme'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'formatdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'format.tex', u'C++ Format Documentation', u'Victor Zverovich', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'format', u'format Documentation', [u'Victor Zverovich'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'format', u'format Documentation', u'Victor Zverovich', 'format', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' cppformat-1.1.0/doc/index.rst000066400000000000000000000001401247635332500161170ustar00rootroot00000000000000########## C++ Format ########## .. toctree:: :maxdepth: 2 usage reference syntax cppformat-1.1.0/doc/reference.rst000066400000000000000000000054761247635332500167670ustar00rootroot00000000000000.. cpp:namespace:: fmt .. _string-formatting-api: ************* API Reference ************* All functions and classes provided by the C++ Format library reside in namespace ``fmt`` and macros have prefix ``FMT_``. For brevity the namespace is usually omitted in examples. Formatting functions ==================== The following functions use :ref:`format string syntax ` similar to the one used by Python's `str.format `_ function. They take *format_str* and *args* as arguments. *format_str* is a format string that contains literal text and replacement fields surrounded by braces ``{}``. The fields are replaced with formatted arguments in the resulting string. *args* is an argument list representing arbitrary arguments. .. _format: .. doxygenfunction:: format(StringRef, ArgList) .. _print: .. doxygenfunction:: print(StringRef, ArgList) .. doxygenfunction:: print(std::FILE*, StringRef, ArgList) .. doxygenfunction:: print(std::ostream&, StringRef, ArgList) Printf formatting functions =========================== The following functions use `printf format string syntax `_ with a POSIX extension for positional arguments. .. doxygenfunction:: printf(StringRef, ArgList) .. doxygenfunction:: fprintf(std::FILE*, StringRef, ArgList) .. doxygenfunction:: sprintf(StringRef, ArgList) Write API ========= .. doxygenclass:: fmt::BasicWriter :members: .. doxygenclass:: fmt::BasicMemoryWriter :members: .. doxygenclass:: fmt::BasicArrayWriter :members: .. doxygenfunction:: bin .. doxygenfunction:: oct .. doxygenfunction:: hex .. doxygenfunction:: hexu .. doxygenfunction:: pad(int, unsigned int, Char) Utilities ========= .. doxygendefine:: FMT_VARIADIC .. doxygenclass:: fmt::ArgList :members: .. doxygenclass:: fmt::BasicStringRef :members: System Errors ============= .. doxygenclass:: fmt::SystemError :members: .. doxygenclass:: fmt::WindowsError :members: .. _formatstrings: Custom allocators ================= The C++ Format library supports custom dynamic memory allocators. A custom allocator class can be specified as a template argument to :class:`fmt::BasicMemoryWriter`:: typedef fmt::BasicMemoryWriter CustomMemoryWriter; It is also possible to write a formatting function that uses a custom allocator:: typedef std::basic_string, CustomAllocator> CustomString; CustomString format(CustomAllocator alloc, fmt::StringRef format_str, fmt::ArgList args) { CustomMemoryWriter writer(alloc); writer.write(format_str, args); return CustomString(writer.data(), writer.size(), alloc); } FMT_VARIADIC(CustomString, format, CustomAllocator, fmt::StringRef) cppformat-1.1.0/doc/sphinx-bootstrap-theme/000077500000000000000000000000001247635332500207075ustar00rootroot00000000000000cppformat-1.1.0/doc/syntax.rst000066400000000000000000000453241247635332500163530ustar00rootroot00000000000000.. _syntax: ******************** Format String Syntax ******************** Formatting functions such as :ref:`fmt::format() ` and :ref:`fmt::print() ` use the same format string syntax described in this section. Format strings contain "replacement fields" surrounded by curly braces ``{}``. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: ``{{`` and ``}}``. The grammar for a replacement field is as follows: .. productionlist:: sf replacement_field: "{" [`arg_index`] [":" `format_spec`] "}" arg_index: `integer` In less formal terms, the replacement field can start with an *arg_index* that specifies the argument whose value is to be formatted and inserted into the output instead of the replacement field. The *arg_index* is optionally followed by a *format_spec*, which is preceded by a colon ``':'``. These specify a non-default format for the replacement value. See also the :ref:`formatspec` section. If the numerical arg_indexes in a format string are 0, 1, 2, ... in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be automatically inserted in that order. Some simple format string examples:: "First, thou shalt count to {0}" // References the first argument "Bring me a {}" // Implicitly references the first argument "From {} to {}" // Same as "From {0} to {1}" The *format_spec* field contains a specification of how the value should be presented, including such details as field width, alignment, padding, decimal precision and so on. Each value type can define its own "formatting mini-language" or interpretation of the *format_spec*. Most built-in types support a common formatting mini-language, which is described in the next section. A *format_spec* field can also include nested replacement fields within it. These nested replacement fields can contain only an argument index; format specifications are not allowed. Formatting is performed as if the replacement fields within the format_spec are substituted before the *format_spec* string is interpreted. This allows the formatting of a value to be dynamically specified. See the :ref:`formatexamples` section for some examples. .. _formatspec: Format Specification Mini-Language ================================== "Format specifications" are used within replacement fields contained within a format string to define how individual values are presented (see :ref:`syntax`). Each formattable type may define how the format specification is to be interpreted. Most built-in types implement the following options for format specifications, although some of the formatting options are only supported by the numeric types. The general form of a *standard format specifier* is: .. productionlist:: sf format_spec: [[`fill`]`align`][`sign`]["#"]["0"][`width`]["." `precision`][`type`] fill: align: "<" | ">" | "=" | "^" sign: "+" | "-" | " " width: `integer` precision: `integer` | "{" `arg_index` "}" type: `int_type` | "c" | "e" | "E" | "f" | "F" | "g" | "G" | "p" | "s" int_type: "b" | "B" | "d" | "o" | "x" | "X" The *fill* character can be any character other than '{' or '}'. The presence of a fill character is signaled by the character following it, which must be one of the alignment options. If the second character of *format_spec* is not a valid alignment option, then it is assumed that both the fill character and the alignment option are absent. The meaning of the various alignment options is as follows: +---------+----------------------------------------------------------+ | Option | Meaning | +=========+==========================================================+ | ``'<'`` | Forces the field to be left-aligned within the available | | | space (this is the default for most objects). | +---------+----------------------------------------------------------+ | ``'>'`` | Forces the field to be right-aligned within the | | | available space (this is the default for numbers). | +---------+----------------------------------------------------------+ | ``'='`` | Forces the padding to be placed after the sign (if any) | | | but before the digits. This is used for printing fields | | | in the form '+000000120'. This alignment option is only | | | valid for numeric types. | +---------+----------------------------------------------------------+ | ``'^'`` | Forces the field to be centered within the available | | | space. | +---------+----------------------------------------------------------+ Note that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case. The *sign* option is only valid for number types, and can be one of the following: +---------+----------------------------------------------------------+ | Option | Meaning | +=========+==========================================================+ | ``'+'`` | indicates that a sign should be used for both | | | positive as well as negative numbers. | +---------+----------------------------------------------------------+ | ``'-'`` | indicates that a sign should be used only for negative | | | numbers (this is the default behavior). | +---------+----------------------------------------------------------+ | space | indicates that a leading space should be used on | | | positive numbers, and a minus sign on negative numbers. | +---------+----------------------------------------------------------+ The ``'#'`` option causes the "alternate form" to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer and floating-point types. For integers, when binary, octal, or hexadecimal output is used, this option adds the prefix respective ``"0b"`` (``"0B"``), ``"0"``, or ``"0x"`` (``"0X"``) to the output value. Whether the prefix is lower-case or upper-case is determined by the case of the type specifier, for example, the prefix ``"0x"`` is used for the type ``'x'`` and ``"0X"`` is used for ``'X'``. For floating-point numbers the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for ``'g'`` and ``'G'`` conversions, trailing zeros are not removed from the result. .. ifconfig:: False The ``','`` option signals the use of a comma for a thousands separator. For a locale aware separator, use the ``'n'`` integer presentation type instead. *width* is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content. Preceding the *width* field by a zero (``'0'``) character enables sign-aware zero-padding for numeric types. This is equivalent to a *fill* character of ``'0'`` with an *alignment* type of ``'='``. The *precision* is a decimal number indicating how many digits should be displayed after the decimal point for a floating-point value formatted with ``'f'`` and ``'F'``, or before and after the decimal point for a floating-point value formatted with ``'g'`` or ``'G'``. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The *precision* is not allowed for integer values or pointers. Finally, the *type* determines how the data should be presented. The available string presentation types are: +---------+----------------------------------------------------------+ | Type | Meaning | +=========+==========================================================+ | ``'s'`` | String format. This is the default type for strings and | | | may be omitted. | +---------+----------------------------------------------------------+ | none | The same as ``'s'``. | +---------+----------------------------------------------------------+ The available character presentation types are: +---------+----------------------------------------------------------+ | Type | Meaning | +=========+==========================================================+ | ``'c'`` | Character format. This is the default type for | | | characters and may be omitted. | +---------+----------------------------------------------------------+ | none | The same as ``'c'``. | +---------+----------------------------------------------------------+ The available integer presentation types are: +---------+----------------------------------------------------------+ | Type | Meaning | +=========+==========================================================+ | ``'b'`` | Binary format. Outputs the number in base 2. Using the | | | ``'#'`` option with this type adds the prefix ``"0b"`` | | | to the output value. | +---------+----------------------------------------------------------+ | ``'B'`` | Binary format. Outputs the number in base 2. Using the | | | ``'#'`` option with this type adds the prefix ``"0B"`` | | | to the output value. | +---------+----------------------------------------------------------+ | ``'d'`` | Decimal integer. Outputs the number in base 10. | +---------+----------------------------------------------------------+ | ``'o'`` | Octal format. Outputs the number in base 8. | +---------+----------------------------------------------------------+ | ``'x'`` | Hex format. Outputs the number in base 16, using | | | lower-case letters for the digits above 9. Using the | | | ``'#'`` option with this type adds the prefix ``"0x"`` | | | to the output value. | +---------+----------------------------------------------------------+ | ``'X'`` | Hex format. Outputs the number in base 16, using | | | upper-case letters for the digits above 9. Using the | | | ``'#'`` option with this type adds the prefix ``"0X"`` | | | to the output value. | +---------+----------------------------------------------------------+ | none | The same as ``'d'``. | +---------+----------------------------------------------------------+ The available presentation types for floating-point values are: +---------+----------------------------------------------------------+ | Type | Meaning | +=========+==========================================================+ | ``'a'`` | Hexadecimal floating point format. Prints the number in | | | base 16 with prefix ``"0x"`` and lower-case letters for | | | digits above 9. Uses 'p' to indicate the exponent. | +---------+----------------------------------------------------------+ | ``'A'`` | Same as ``'a'`` except it uses upper-case letters for | | | the prefix, digits above 9 and to indicate the exponent. | +---------+----------------------------------------------------------+ | ``'e'`` | Exponent notation. Prints the number in scientific | | | notation using the letter 'e' to indicate the exponent. | +---------+----------------------------------------------------------+ | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an | | | upper-case 'E' as the separator character. | +---------+----------------------------------------------------------+ | ``'f'`` | Fixed point. Displays the number as a fixed-point | | | number. | +---------+----------------------------------------------------------+ | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to | | | ``NAN`` and ``inf`` to ``INF``. | +---------+----------------------------------------------------------+ | ``'g'`` | General format. For a given precision ``p >= 1``, | | | this rounds the number to ``p`` significant digits and | | | then formats the result in either fixed-point format | | | or in scientific notation, depending on its magnitude. | | | | | | A precision of ``0`` is treated as equivalent to a | | | precision of ``1``. | +---------+----------------------------------------------------------+ | ``'G'`` | General format. Same as ``'g'`` except switches to | | | ``'E'`` if the number gets too large. The | | | representations of infinity and NaN are uppercased, too. | +---------+----------------------------------------------------------+ | none | The same as ``'g'``. | +---------+----------------------------------------------------------+ .. ifconfig:: False +---------+----------------------------------------------------------+ | | The precise rules are as follows: suppose that the | | | result formatted with presentation type ``'e'`` and | | | precision ``p-1`` would have exponent ``exp``. Then | | | if ``-4 <= exp < p``, the number is formatted | | | with presentation type ``'f'`` and precision | | | ``p-1-exp``. Otherwise, the number is formatted | | | with presentation type ``'e'`` and precision ``p-1``. | | | In both cases insignificant trailing zeros are removed | | | from the significand, and the decimal point is also | | | removed if there are no remaining digits following it. | | | | | | Positive and negative infinity, positive and negative | | | zero, and nans, are formatted as ``inf``, ``-inf``, | | | ``0``, ``-0`` and ``nan`` respectively, regardless of | | | the precision. | | | | +---------+----------------------------------------------------------+ The available presentation types for pointers are: +---------+----------------------------------------------------------+ | Type | Meaning | +=========+==========================================================+ | ``'p'`` | Pointer format. This is the default type for | | | pointers and may be omitted. | +---------+----------------------------------------------------------+ | none | The same as ``'p'``. | +---------+----------------------------------------------------------+ .. _formatexamples: Format examples =============== This section contains examples of the format syntax and comparison with the printf formatting. In most of the cases the syntax is similar to the printf formatting, with the addition of the ``{}`` and with ``:`` used instead of ``%``. For example, ``"%03.2f"`` can be translated to ``"{:03.2f}"``. The new format syntax also supports new and different options, shown in the following examples. Accessing arguments by position:: format("{0}, {1}, {2}", 'a', 'b', 'c'); // Result: "a, b, c" format("{}, {}, {}", 'a', 'b', 'c'); // Result: "a, b, c" format("{2}, {1}, {0}", 'a', 'b', 'c'); // Result: "c, b, a" format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated // Result: "abracadabra" Aligning the text and specifying a width:: format("{:<30}", "left aligned"); // Result: "left aligned " format("{:>30}", "right aligned"); // Result: " right aligned" format("{:^30}", "centered"); // Result: " centered " format("{:*^30}", "centered"); // use '*' as a fill char // Result: "***********centered***********" Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:: format("{:+f}; {:+f}", 3.14, -3.14); // show it always // Result: "+3.140000; -3.140000" format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers // Result: " 3.140000; -3.140000" format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}' // Result: "3.140000; -3.140000" Replacing ``%x`` and ``%o`` and converting the value to different bases:: format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); // Result: "int: 42; hex: 2a; oct: 52; bin: 101010" // with 0x or 0 or 0b as prefix: format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42); // Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010" .. ifconfig:: False Using the comma as a thousands separator:: format("{:,}", 1234567890); '1,234,567,890' Expressing a percentage:: >>> points = 19 >>> total = 22 Format("Correct answers: {:.2%}") << points/total) 'Correct answers: 86.36%' Using type-specific formatting:: >>> import datetime >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58) Format("{:%Y-%m-%d %H:%M:%S}") << d) '2010-07-04 12:15:58' Nesting arguments and more complex examples:: >>> for align, text in zip('<^>', ['left', 'center', 'right']): ... '{0:{fill}{align}16}") << text, fill=align, align=align) ... 'left<<<<<<<<<<<<' '^^^^^center^^^^^' '>>>>>>>>>>>right' >>> >>> octets = [192, 168, 0, 1] Format("{:02X}{:02X}{:02X}{:02X}") << *octets) 'C0A80001' >>> int(_, 16) 3232235521 >>> >>> width = 5 >>> for num in range(5,12): ... for base in 'dXob': ... print('{0:{width}{base}}") << num, base=base, width=width), end=' ') ... print() ... 5 5 5 101 6 6 6 110 7 7 7 111 8 8 10 1000 9 9 11 1001 10 A 12 1010 11 B 13 1011 cppformat-1.1.0/doc/usage.rst000066400000000000000000000043571247635332500161320ustar00rootroot00000000000000***** Usage ***** To use the C++ Format library, add :file:`format.h` and :file:`format.cc` from a `release archive `_ or the `Git repository `_ to your project. Alternatively, you can :ref:`build the library with CMake `. If you are using Visual C++ with precompiled headers, you might need to add the line :: #include "stdafx.h" before other includes in :file:`format.cc`. .. _building: Building the library ==================== The included `CMake build script`__ can be used to build the C++ Format library on a wide range of platforms. CMake is freely available for download from http://www.cmake.org/download/. __ https://github.com/cppformat/cppformat/blob/master/CMakeLists.txt CMake works by generating native makefiles or project files that can be used in the compiler environment of your choice. The typical workflow starts with:: mkdir build # Create a directory to hold the build output. cd build cmake # Generate native build scripts. where :file:`{}` is a path to the ``cppformat`` repository. If you are on a \*nix system, you should now see a Makefile in the current directory. Now you can build C++ Format by running :command:`make`. Once the library has been built you can invoke :command:`make test` to run the tests. If you use Windows and have Vistual Studio installed, a :file:`FORMAT.sln` file and several :file:`.vcproj` files will be created. You can then build them using Visual Studio or msbuild. On Mac OS X with Xcode installed, an :file:`.xcodeproj` file will be generated. To build a `shared library`__ set the ``BUILD_SHARED_LIBS`` CMake variable to ``TRUE``:: cmake -DBUILD_SHARED_LIBS=TRUE ... __ http://en.wikipedia.org/wiki/Library_%28computing%29#Shared_libraries Android NDK =========== C++ Format provides `Android.mk file`__ that can be used to build the library with `Android NDK `_. For an example of using C++ Format with Android NDK, see the `android-ndk-example `_ repository. __ https://github.com/cppformat/cppformat/blob/master/Android.mk cppformat-1.1.0/format.cc000066400000000000000000001043301247635332500153160ustar00rootroot00000000000000/* Formatting library for C++ Copyright (c) 2012 - 2015, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "format.h" #include #include #include #include #include #include #ifdef _WIN32 # ifdef __MINGW32__ # include # endif # include #endif using fmt::internal::Arg; // Check if exceptions are disabled. #if __GNUC__ && !__EXCEPTIONS # define FMT_EXCEPTIONS 0 #endif #if _MSC_VER && !_HAS_EXCEPTIONS # define FMT_EXCEPTIONS 0 #endif #ifndef FMT_EXCEPTIONS # define FMT_EXCEPTIONS 1 #endif #if FMT_EXCEPTIONS # define FMT_TRY try # define FMT_CATCH(x) catch (x) #else # define FMT_TRY if (true) # define FMT_CATCH(x) if (false) #endif #ifndef FMT_THROW # if FMT_EXCEPTIONS # define FMT_THROW(x) throw x # define FMT_RETURN_AFTER_THROW(x) # else # define FMT_THROW(x) assert(false) # define FMT_RETURN_AFTER_THROW(x) return x # endif #endif #ifdef FMT_HEADER_ONLY # define FMT_FUNC inline #else # define FMT_FUNC #endif #if _MSC_VER # pragma warning(push) # pragma warning(disable: 4127) // conditional expression is constant # pragma warning(disable: 4702) // unreachable code #endif namespace { #ifndef _MSC_VER # define FMT_SNPRINTF snprintf #else // _MSC_VER inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) { va_list args; va_start(args, format); int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); va_end(args); return result; } # define FMT_SNPRINTF fmt_snprintf #endif // _MSC_VER // Checks if a value fits in int - used to avoid warnings about comparing // signed and unsigned integers. template struct IntChecker { template static bool fits_in_int(T value) { unsigned max = INT_MAX; return value <= max; } }; template <> struct IntChecker { template static bool fits_in_int(T value) { return value >= INT_MIN && value <= INT_MAX; } }; const char RESET_COLOR[] = "\x1b[0m"; typedef void (*FormatFunc)(fmt::Writer &, int, fmt::StringRef); // Portable thread-safe version of strerror. // Sets buffer to point to a string describing the error code. // This can be either a pointer to a string stored in buffer, // or a pointer to some static immutable string. // Returns one of the following values: // 0 - success // ERANGE - buffer is not large enough to store the error message // other - failure // Buffer should be at least of size 1. int safe_strerror( int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT { assert(buffer != 0 && buffer_size != 0); int result = 0; #if ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE) || __ANDROID__ // XSI-compliant version of strerror_r. result = strerror_r(error_code, buffer, buffer_size); if (result != 0) result = errno; #elif _GNU_SOURCE // GNU-specific version of strerror_r. char *message = strerror_r(error_code, buffer, buffer_size); // If the buffer is full then the message is probably truncated. if (message == buffer && strlen(buffer) == buffer_size - 1) result = ERANGE; buffer = message; #elif __MINGW32__ errno = 0; (void)buffer_size; buffer = strerror(error_code); result = errno; #elif _WIN32 result = strerror_s(buffer, buffer_size, error_code); // If the buffer is full then the message is probably truncated. if (result == 0 && std::strlen(buffer) == buffer_size - 1) result = ERANGE; #else result = strerror_r(error_code, buffer, buffer_size); if (result == -1) result = errno; // glibc versions before 2.13 return result in errno. #endif return result; } void format_error_code(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT { // Report error code making sure that the output fits into // INLINE_BUFFER_SIZE to avoid dynamic memory allocation and potential // bad_alloc. out.clear(); static const char SEP[] = ": "; static const char ERR[] = "error "; fmt::internal::IntTraits::MainType ec_value = error_code; // Subtract 2 to account for terminating null characters in SEP and ERR. std::size_t error_code_size = sizeof(SEP) + sizeof(ERR) + fmt::internal::count_digits(ec_value) - 2; if (message.size() <= fmt::internal::INLINE_BUFFER_SIZE - error_code_size) out << message << SEP; out << ERR << error_code; assert(out.size() <= fmt::internal::INLINE_BUFFER_SIZE); } void report_error(FormatFunc func, int error_code, fmt::StringRef message) FMT_NOEXCEPT { fmt::MemoryWriter full_message; func(full_message, error_code, message); // Use Writer::data instead of Writer::c_str to avoid potential memory // allocation. std::fwrite(full_message.data(), full_message.size(), 1, stderr); std::fputc('\n', stderr); } // IsZeroInt::visit(arg) returns true iff arg is a zero integer. class IsZeroInt : public fmt::internal::ArgVisitor { public: template bool visit_any_int(T value) { return value == 0; } }; // Parses an unsigned integer advancing s to the end of the parsed input. // This function assumes that the first character of s is a digit. template int parse_nonnegative_int(const Char *&s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; do { unsigned new_value = value * 10 + (*s++ - '0'); // Check if value wrapped around. if (new_value < value) { value = UINT_MAX; break; } value = new_value; } while ('0' <= *s && *s <= '9'); if (value > INT_MAX) FMT_THROW(fmt::FormatError("number is too big")); return value; } inline void require_numeric_argument(const Arg &arg, char spec) { if (arg.type > Arg::LAST_NUMERIC_TYPE) { std::string message = fmt::format("format specifier '{}' requires numeric argument", spec); FMT_THROW(fmt::FormatError(message)); } } template void check_sign(const Char *&s, const Arg &arg) { char sign = static_cast(*s); require_numeric_argument(arg, sign); if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { FMT_THROW(fmt::FormatError(fmt::format( "format specifier '{}' requires signed argument", sign))); } ++s; } // Checks if an argument is a valid printf width specifier and sets // left alignment if it is negative. class WidthHandler : public fmt::internal::ArgVisitor { private: fmt::FormatSpec &spec_; FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler); public: explicit WidthHandler(fmt::FormatSpec &spec) : spec_(spec) {} unsigned visit_unhandled_arg() { FMT_THROW(fmt::FormatError("width is not integer")); FMT_RETURN_AFTER_THROW(0); } template unsigned visit_any_int(T value) { typedef typename fmt::internal::IntTraits::MainType UnsignedType; UnsignedType width = value; if (fmt::internal::is_negative(value)) { spec_.align_ = fmt::ALIGN_LEFT; width = 0 - width; } if (width > INT_MAX) FMT_THROW(fmt::FormatError("number is too big")); return static_cast(width); } }; class PrecisionHandler : public fmt::internal::ArgVisitor { public: unsigned visit_unhandled_arg() { FMT_THROW(fmt::FormatError("precision is not integer")); FMT_RETURN_AFTER_THROW(0); } template int visit_any_int(T value) { if (!IntChecker::is_signed>::fits_in_int(value)) FMT_THROW(fmt::FormatError("number is too big")); return static_cast(value); } }; // Converts an integer argument to an integral type T for printf. template class ArgConverter : public fmt::internal::ArgVisitor, void> { private: fmt::internal::Arg &arg_; wchar_t type_; FMT_DISALLOW_COPY_AND_ASSIGN(ArgConverter); public: ArgConverter(fmt::internal::Arg &arg, wchar_t type) : arg_(arg), type_(type) {} template void visit_any_int(U value) { bool is_signed = type_ == 'd' || type_ == 'i'; using fmt::internal::Arg; if (sizeof(T) <= sizeof(int)) { // Extra casts are used to silence warnings. if (is_signed) { arg_.type = Arg::INT; arg_.int_value = static_cast(static_cast(value)); } else { arg_.type = Arg::UINT; arg_.uint_value = static_cast( static_cast::Type>(value)); } } else { if (is_signed) { arg_.type = Arg::LONG_LONG; arg_.long_long_value = static_cast::Type>(value); } else { arg_.type = Arg::ULONG_LONG; arg_.ulong_long_value = static_cast::Type>(value); } } } }; // Converts an integer argument to char for printf. class CharConverter : public fmt::internal::ArgVisitor { private: fmt::internal::Arg &arg_; FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter); public: explicit CharConverter(fmt::internal::Arg &arg) : arg_(arg) {} template void visit_any_int(T value) { arg_.type = Arg::CHAR; arg_.int_value = static_cast(value); } }; // This function template is used to prevent compile errors when handling // incompatible string arguments, e.g. handling a wide string in a narrow // string formatter. template Arg::StringValue ignore_incompatible_str(Arg::StringValue); template <> inline Arg::StringValue ignore_incompatible_str( Arg::StringValue) { return Arg::StringValue(); } template <> inline Arg::StringValue ignore_incompatible_str( Arg::StringValue s) { return s; } } // namespace FMT_FUNC void fmt::SystemError::init( int err_code, StringRef format_str, ArgList args) { error_code_ = err_code; MemoryWriter w; internal::format_system_error(w, err_code, format(format_str, args)); std::runtime_error &base = *this; base = std::runtime_error(w.str()); } template int fmt::internal::CharTraits::format_float( char *buffer, std::size_t size, const char *format, unsigned width, int precision, T value) { if (width == 0) { return precision < 0 ? FMT_SNPRINTF(buffer, size, format, value) : FMT_SNPRINTF(buffer, size, format, precision, value); } return precision < 0 ? FMT_SNPRINTF(buffer, size, format, width, value) : FMT_SNPRINTF(buffer, size, format, width, precision, value); } template int fmt::internal::CharTraits::format_float( wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, T value) { if (width == 0) { return precision < 0 ? swprintf(buffer, size, format, value) : swprintf(buffer, size, format, precision, value); } return precision < 0 ? swprintf(buffer, size, format, width, value) : swprintf(buffer, size, format, width, precision, value); } template const char fmt::internal::BasicData::DIGITS[] = "0001020304050607080910111213141516171819" "2021222324252627282930313233343536373839" "4041424344454647484950515253545556575859" "6061626364656667686970717273747576777879" "8081828384858687888990919293949596979899"; #define FMT_POWERS_OF_10(factor) \ factor * 10, \ factor * 100, \ factor * 1000, \ factor * 10000, \ factor * 100000, \ factor * 1000000, \ factor * 10000000, \ factor * 100000000, \ factor * 1000000000 template const uint32_t fmt::internal::BasicData::POWERS_OF_10_32[] = { 0, FMT_POWERS_OF_10(1) }; template const uint64_t fmt::internal::BasicData::POWERS_OF_10_64[] = { 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(fmt::ULongLong(1000000000)), // Multiply several constants instead of using a single long long constant // to avoid warnings about C++98 not supporting long long. fmt::ULongLong(1000000000) * fmt::ULongLong(1000000000) * 10 }; FMT_FUNC void fmt::internal::report_unknown_type(char code, const char *type) { if (std::isprint(static_cast(code))) { FMT_THROW(fmt::FormatError( fmt::format("unknown format code '{}' for {}", code, type))); } FMT_THROW(fmt::FormatError( fmt::format("unknown format code '\\x{:02x}' for {}", static_cast(code), type))); } #ifdef _WIN32 FMT_FUNC fmt::internal::UTF8ToUTF16::UTF8ToUTF16(fmt::StringRef s) { int length = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, s.c_str(), -1, 0, 0); static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16"; if (length == 0) FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); buffer_.resize(length); length = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, s.c_str(), -1, &buffer_[0], length); if (length == 0) FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); } FMT_FUNC fmt::internal::UTF16ToUTF8::UTF16ToUTF8(fmt::WStringRef s) { if (int error_code = convert(s)) { FMT_THROW(WindowsError(error_code, "cannot convert string from UTF-16 to UTF-8")); } } FMT_FUNC int fmt::internal::UTF16ToUTF8::convert(fmt::WStringRef s) { int length = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, 0, 0, 0, 0); if (length == 0) return GetLastError(); buffer_.resize(length); length = WideCharToMultiByte( CP_UTF8, 0, s.c_str(), -1, &buffer_[0], length, 0, 0); if (length == 0) return GetLastError(); return 0; } FMT_FUNC void fmt::WindowsError::init( int err_code, StringRef format_str, ArgList args) { error_code_ = err_code; MemoryWriter w; internal::format_windows_error(w, err_code, format(format_str, args)); std::runtime_error &base = *this; base = std::runtime_error(w.str()); } #endif FMT_FUNC void fmt::internal::format_system_error( fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT { FMT_TRY { MemoryBuffer buffer; buffer.resize(INLINE_BUFFER_SIZE); for (;;) { char *system_message = &buffer[0]; int result = safe_strerror(error_code, system_message, buffer.size()); if (result == 0) { out << message << ": " << system_message; return; } if (result != ERANGE) break; // Can't get error message, report error code instead. buffer.resize(buffer.size() * 2); } } FMT_CATCH(...) {} format_error_code(out, error_code, message); } #ifdef _WIN32 FMT_FUNC void fmt::internal::format_windows_error( fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT { class String { private: LPWSTR str_; public: String() : str_() {} ~String() { LocalFree(str_); } LPWSTR *ptr() { return &str_; } LPCWSTR c_str() const { return str_; } }; FMT_TRY { String system_message; if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast(system_message.ptr()), 0, 0)) { UTF16ToUTF8 utf8_message; if (utf8_message.convert(system_message.c_str()) == ERROR_SUCCESS) { out << message << ": " << utf8_message; return; } } } FMT_CATCH(...) {} format_error_code(out, error_code, message); } #endif // An argument formatter. template class fmt::internal::ArgFormatter : public fmt::internal::ArgVisitor, void> { private: fmt::BasicFormatter &formatter_; fmt::BasicWriter &writer_; fmt::FormatSpec &spec_; const Char *format_; FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatter); public: ArgFormatter( fmt::BasicFormatter &f,fmt::FormatSpec &s, const Char *fmt) : formatter_(f), writer_(f.writer()), spec_(s), format_(fmt) {} template void visit_any_int(T value) { writer_.write_int(value, spec_); } template void visit_any_double(T value) { writer_.write_double(value, spec_); } void visit_char(int value) { if (spec_.type_ && spec_.type_ != 'c') { spec_.flags_ |= CHAR_FLAG; writer_.write_int(value, spec_); return; } if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0) FMT_THROW(FormatError("invalid format specifier for char")); typedef typename fmt::BasicWriter::CharPtr CharPtr; Char fill = static_cast(spec_.fill()); if (spec_.precision_ == 0) { std::fill_n(writer_.grow_buffer(spec_.width_), spec_.width_, fill); return; } CharPtr out = CharPtr(); if (spec_.width_ > 1) { out = writer_.grow_buffer(spec_.width_); if (spec_.align_ == fmt::ALIGN_RIGHT) { std::fill_n(out, spec_.width_ - 1, fill); out += spec_.width_ - 1; } else if (spec_.align_ == fmt::ALIGN_CENTER) { out = writer_.fill_padding(out, spec_.width_, 1, fill); } else { std::fill_n(out + 1, spec_.width_ - 1, fill); } } else { out = writer_.grow_buffer(1); } *out = static_cast(value); } void visit_string(Arg::StringValue value) { writer_.write_str(value, spec_); } void visit_wstring(Arg::StringValue value) { writer_.write_str(ignore_incompatible_str(value), spec_); } void visit_pointer(const void *value) { if (spec_.type_ && spec_.type_ != 'p') fmt::internal::report_unknown_type(spec_.type_, "pointer"); spec_.flags_ = fmt::HASH_FLAG; spec_.type_ = 'x'; writer_.write_int(reinterpret_cast(value), spec_); } void visit_custom(Arg::CustomValue c) { c.format(&formatter_, c.value, &format_); } }; template void fmt::internal::FixedBuffer::grow(std::size_t) { FMT_THROW(std::runtime_error("buffer overflow")); } template template void fmt::BasicWriter::write_str( const Arg::StringValue &s, const FormatSpec &spec) { // Check if StrChar is convertible to Char. internal::CharTraits::convert(StrChar()); if (spec.type_ && spec.type_ != 's') internal::report_unknown_type(spec.type_, "string"); const StrChar *str_value = s.value; std::size_t str_size = s.size; if (str_size == 0) { if (!str_value) FMT_THROW(FormatError("string pointer is null")); if (*str_value) str_size = std::char_traits::length(str_value); } std::size_t precision = spec.precision_; if (spec.precision_ >= 0 && precision < str_size) str_size = spec.precision_; write_str(str_value, str_size, spec); } template inline Arg fmt::BasicFormatter::parse_arg_index(const Char *&s) { const char *error = 0; Arg arg = *s < '0' || *s > '9' ? next_arg(error) : get_arg(parse_nonnegative_int(s), error); if (error) { FMT_THROW(FormatError( *s != '}' && *s != ':' ? "invalid format string" : error)); } return arg; } FMT_FUNC Arg fmt::internal::FormatterBase::do_get_arg( unsigned arg_index, const char *&error) { Arg arg = args_[arg_index]; if (arg.type == Arg::NONE) error = "argument index out of range"; return arg; } inline Arg fmt::internal::FormatterBase::next_arg(const char *&error) { if (next_arg_index_ >= 0) return do_get_arg(next_arg_index_++, error); error = "cannot switch from manual to automatic argument indexing"; return Arg(); } inline Arg fmt::internal::FormatterBase::get_arg( unsigned arg_index, const char *&error) { if (next_arg_index_ <= 0) { next_arg_index_ = -1; return do_get_arg(arg_index, error); } error = "cannot switch from automatic to manual argument indexing"; return Arg(); } template void fmt::internal::PrintfFormatter::parse_flags( FormatSpec &spec, const Char *&s) { for (;;) { switch (*s++) { case '-': spec.align_ = ALIGN_LEFT; break; case '+': spec.flags_ |= SIGN_FLAG | PLUS_FLAG; break; case '0': spec.fill_ = '0'; break; case ' ': spec.flags_ |= SIGN_FLAG; break; case '#': spec.flags_ |= HASH_FLAG; break; default: --s; return; } } } template Arg fmt::internal::PrintfFormatter::get_arg( const Char *s, unsigned arg_index) { const char *error = 0; Arg arg = arg_index == UINT_MAX ? next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); if (error) FMT_THROW(FormatError(!*s ? "invalid format string" : error)); return arg; } template unsigned fmt::internal::PrintfFormatter::parse_header( const Char *&s, FormatSpec &spec) { unsigned arg_index = UINT_MAX; Char c = *s; if (c >= '0' && c <= '9') { // Parse an argument index (if followed by '$') or a width possibly // preceded with '0' flag(s). unsigned value = parse_nonnegative_int(s); if (*s == '$') { // value is an argument index ++s; arg_index = value; } else { if (c == '0') spec.fill_ = '0'; if (value != 0) { // Nonzero value means that we parsed width and don't need to // parse it or flags again, so return now. spec.width_ = value; return arg_index; } } } parse_flags(spec, s); // Parse width. if (*s >= '0' && *s <= '9') { spec.width_ = parse_nonnegative_int(s); } else if (*s == '*') { ++s; spec.width_ = WidthHandler(spec).visit(get_arg(s)); } return arg_index; } template void fmt::internal::PrintfFormatter::format( BasicWriter &writer, BasicStringRef format_str, const ArgList &args) { const Char *start = format_str.c_str(); set_args(args); const Char *s = start; while (*s) { Char c = *s++; if (c != '%') continue; if (*s == c) { write(writer, start, s); start = ++s; continue; } write(writer, start, s - 1); FormatSpec spec; spec.align_ = ALIGN_RIGHT; // Parse argument index, flags and width. unsigned arg_index = parse_header(s, spec); // Parse precision. if (*s == '.') { ++s; if ('0' <= *s && *s <= '9') { spec.precision_ = parse_nonnegative_int(s); } else if (*s == '*') { ++s; spec.precision_ = PrecisionHandler().visit(get_arg(s)); } } Arg arg = get_arg(s, arg_index); if (spec.flag(HASH_FLAG) && IsZeroInt().visit(arg)) spec.flags_ &= ~HASH_FLAG; if (spec.fill_ == '0') { if (arg.type <= Arg::LAST_NUMERIC_TYPE) spec.align_ = ALIGN_NUMERIC; else spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. } // Parse length and convert the argument to the required type. switch (*s++) { case 'h': if (*s == 'h') ArgConverter(arg, *++s).visit(arg); else ArgConverter(arg, *s).visit(arg); break; case 'l': if (*s == 'l') ArgConverter(arg, *++s).visit(arg); else ArgConverter(arg, *s).visit(arg); break; case 'j': ArgConverter(arg, *s).visit(arg); break; case 'z': ArgConverter(arg, *s).visit(arg); break; case 't': ArgConverter(arg, *s).visit(arg); break; case 'L': // printf produces garbage when 'L' is omitted for long double, no // need to do the same. break; default: --s; ArgConverter(arg, *s).visit(arg); } // Parse type. if (!*s) FMT_THROW(FormatError("invalid format string")); spec.type_ = static_cast(*s++); if (arg.type <= Arg::LAST_INTEGER_TYPE) { // Normalize type. switch (spec.type_) { case 'i': case 'u': spec.type_ = 'd'; break; case 'c': // TODO: handle wchar_t CharConverter(arg).visit(arg); break; } } start = s; // Format argument. switch (arg.type) { case Arg::INT: writer.write_int(arg.int_value, spec); break; case Arg::UINT: writer.write_int(arg.uint_value, spec); break; case Arg::LONG_LONG: writer.write_int(arg.long_long_value, spec); break; case Arg::ULONG_LONG: writer.write_int(arg.ulong_long_value, spec); break; case Arg::CHAR: { if (spec.type_ && spec.type_ != 'c') writer.write_int(arg.int_value, spec); typedef typename BasicWriter::CharPtr CharPtr; CharPtr out = CharPtr(); if (spec.width_ > 1) { Char fill = ' '; out = writer.grow_buffer(spec.width_); if (spec.align_ != ALIGN_LEFT) { std::fill_n(out, spec.width_ - 1, fill); out += spec.width_ - 1; } else { std::fill_n(out + 1, spec.width_ - 1, fill); } } else { out = writer.grow_buffer(1); } *out = static_cast(arg.int_value); break; } case Arg::DOUBLE: writer.write_double(arg.double_value, spec); break; case Arg::LONG_DOUBLE: writer.write_double(arg.long_double_value, spec); break; case Arg::CSTRING: arg.string.size = 0; writer.write_str(arg.string, spec); break; case Arg::STRING: writer.write_str(arg.string, spec); break; case Arg::WSTRING: writer.write_str(ignore_incompatible_str(arg.wstring), spec); break; case Arg::POINTER: if (spec.type_ && spec.type_ != 'p') internal::report_unknown_type(spec.type_, "pointer"); spec.flags_= HASH_FLAG; spec.type_ = 'x'; writer.write_int(reinterpret_cast(arg.pointer), spec); break; case Arg::CUSTOM: { if (spec.type_) internal::report_unknown_type(spec.type_, "object"); const void *str_format = "s"; arg.custom.format(&writer, arg.custom.value, &str_format); break; } default: assert(false); break; } } write(writer, start, s); } template const Char *fmt::BasicFormatter::format( const Char *&format_str, const Arg &arg) { const Char *s = format_str; FormatSpec spec; if (*s == ':') { if (arg.type == Arg::CUSTOM) { arg.custom.format(this, arg.custom.value, &s); return s; } ++s; // Parse fill and alignment. if (Char c = *s) { const Char *p = s + 1; spec.align_ = ALIGN_DEFAULT; do { switch (*p) { case '<': spec.align_ = ALIGN_LEFT; break; case '>': spec.align_ = ALIGN_RIGHT; break; case '=': spec.align_ = ALIGN_NUMERIC; break; case '^': spec.align_ = ALIGN_CENTER; break; } if (spec.align_ != ALIGN_DEFAULT) { if (p != s) { if (c == '}') break; if (c == '{') FMT_THROW(FormatError("invalid fill character '{'")); s += 2; spec.fill_ = c; } else ++s; if (spec.align_ == ALIGN_NUMERIC) require_numeric_argument(arg, '='); break; } } while (--p >= s); } // Parse sign. switch (*s) { case '+': check_sign(s, arg); spec.flags_ |= SIGN_FLAG | PLUS_FLAG; break; case '-': check_sign(s, arg); spec.flags_ |= MINUS_FLAG; break; case ' ': check_sign(s, arg); spec.flags_ |= SIGN_FLAG; break; } if (*s == '#') { require_numeric_argument(arg, '#'); spec.flags_ |= HASH_FLAG; ++s; } // Parse width and zero flag. if ('0' <= *s && *s <= '9') { if (*s == '0') { require_numeric_argument(arg, '0'); spec.align_ = ALIGN_NUMERIC; spec.fill_ = '0'; } // Zero may be parsed again as a part of the width, but it is simpler // and more efficient than checking if the next char is a digit. spec.width_ = parse_nonnegative_int(s); } // Parse precision. if (*s == '.') { ++s; spec.precision_ = 0; if ('0' <= *s && *s <= '9') { spec.precision_ = parse_nonnegative_int(s); } else if (*s == '{') { ++s; const Arg &precision_arg = parse_arg_index(s); if (*s++ != '}') FMT_THROW(FormatError("invalid format string")); ULongLong value = 0; switch (precision_arg.type) { case Arg::INT: if (precision_arg.int_value < 0) FMT_THROW(FormatError("negative precision")); value = precision_arg.int_value; break; case Arg::UINT: value = precision_arg.uint_value; break; case Arg::LONG_LONG: if (precision_arg.long_long_value < 0) FMT_THROW(FormatError("negative precision")); value = precision_arg.long_long_value; break; case Arg::ULONG_LONG: value = precision_arg.ulong_long_value; break; default: FMT_THROW(FormatError("precision is not integer")); } if (value > INT_MAX) FMT_THROW(FormatError("number is too big")); spec.precision_ = static_cast(value); } else { FMT_THROW(FormatError("missing precision specifier")); } if (arg.type < Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) { FMT_THROW(FormatError( fmt::format("precision not allowed in {} format specifier", arg.type == Arg::POINTER ? "pointer" : "integer"))); } } // Parse type. if (*s != '}' && *s) spec.type_ = static_cast(*s++); } if (*s++ != '}') FMT_THROW(FormatError("missing '}' in format string")); start_ = s; // Format argument. internal::ArgFormatter(*this, spec, s - 1).visit(arg); return s; } template void fmt::BasicFormatter::format( BasicStringRef format_str, const ArgList &args) { const Char *s = start_ = format_str.c_str(); set_args(args); while (*s) { Char c = *s++; if (c != '{' && c != '}') continue; if (*s == c) { write(writer_, start_, s); start_ = ++s; continue; } if (c == '}') FMT_THROW(FormatError("unmatched '}' in format string")); write(writer_, start_, s - 1); Arg arg = parse_arg_index(s); s = format(s, arg); } write(writer_, start_, s); } FMT_FUNC void fmt::report_system_error( int error_code, fmt::StringRef message) FMT_NOEXCEPT { report_error(internal::format_system_error, error_code, message); } #ifdef _WIN32 FMT_FUNC void fmt::report_windows_error( int error_code, fmt::StringRef message) FMT_NOEXCEPT { report_error(internal::format_windows_error, error_code, message); } #endif FMT_FUNC void fmt::print(std::FILE *f, StringRef format_str, ArgList args) { MemoryWriter w; w.write(format_str, args); std::fwrite(w.data(), 1, w.size(), f); } FMT_FUNC void fmt::print(StringRef format_str, ArgList args) { print(stdout, format_str, args); } FMT_FUNC void fmt::print(std::ostream &os, StringRef format_str, ArgList args) { MemoryWriter w; w.write(format_str, args); os.write(w.data(), w.size()); } FMT_FUNC void fmt::print_colored(Color c, StringRef format, ArgList args) { char escape[] = "\x1b[30m"; escape[3] = '0' + static_cast(c); std::fputs(escape, stdout); print(format, args); std::fputs(RESET_COLOR, stdout); } FMT_FUNC int fmt::fprintf(std::FILE *f, StringRef format, ArgList args) { MemoryWriter w; printf(w, format, args); std::size_t size = w.size(); return std::fwrite(w.data(), 1, size, f) < size ? -1 : static_cast(size); } #ifndef FMT_HEADER_ONLY // Explicit instantiations for char. template void fmt::internal::FixedBuffer::grow(std::size_t); template const char *fmt::BasicFormatter::format( const char *&format_str, const fmt::internal::Arg &arg); template void fmt::BasicFormatter::format( BasicStringRef format, const ArgList &args); template void fmt::internal::PrintfFormatter::format( BasicWriter &writer, BasicStringRef format, const ArgList &args); template int fmt::internal::CharTraits::format_float( char *buffer, std::size_t size, const char *format, unsigned width, int precision, double value); template int fmt::internal::CharTraits::format_float( char *buffer, std::size_t size, const char *format, unsigned width, int precision, long double value); // Explicit instantiations for wchar_t. template void fmt::internal::FixedBuffer::grow(std::size_t); template const wchar_t *fmt::BasicFormatter::format( const wchar_t *&format_str, const fmt::internal::Arg &arg); template void fmt::BasicFormatter::format( BasicStringRef format, const ArgList &args); template void fmt::internal::PrintfFormatter::format( BasicWriter &writer, BasicStringRef format, const ArgList &args); template int fmt::internal::CharTraits::format_float( wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, double value); template int fmt::internal::CharTraits::format_float( wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, long double value); #endif // FMT_HEADER_ONLY #if _MSC_VER # pragma warning(pop) #endif cppformat-1.1.0/format.h000066400000000000000000002341141247635332500151640ustar00rootroot00000000000000/* Formatting library for C++ Copyright (c) 2012 - 2015, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FMT_FORMAT_H_ #define FMT_FORMAT_H_ #include #include #include #include // for std::ptrdiff_t #include #include #include #include #include #include #if _SECURE_SCL # include #endif #ifdef _MSC_VER # include // _BitScanReverse, _BitScanReverse64 namespace fmt { namespace internal { # pragma intrinsic(_BitScanReverse) inline uint32_t clz(uint32_t x) { unsigned long r = 0; _BitScanReverse(&r, x); return 31 - r; } # define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) # ifdef _WIN64 # pragma intrinsic(_BitScanReverse64) # endif inline uint32_t clzll(uint64_t x) { unsigned long r = 0; # ifdef _WIN64 _BitScanReverse64(&r, x); # else // Scan the high 32 bits. if (_BitScanReverse(&r, static_cast(x >> 32))) return 63 - (r + 32); // Scan the low 32 bits. _BitScanReverse(&r, static_cast(x)); # endif return 63 - r; } # define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) } } #endif #ifdef __GNUC__ # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) # define FMT_GCC_EXTENSION __extension__ # if FMT_GCC_VERSION >= 406 # pragma GCC diagnostic push // Disable the warning about "long long" which is sometimes reported even // when using __extension__. # pragma GCC diagnostic ignored "-Wlong-long" // Disable the warning about declaration shadowing because it affects too // many valid cases. # pragma GCC diagnostic ignored "-Wshadow" # endif # if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ # define FMT_HAS_GXX_CXX11 1 # endif #else # define FMT_GCC_EXTENSION #endif #ifdef __clang__ # pragma clang diagnostic ignored "-Wdocumentation" #endif #ifdef __GNUC_LIBSTD__ # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) #endif #ifdef __has_feature # define FMT_HAS_FEATURE(x) __has_feature(x) #else # define FMT_HAS_FEATURE(x) 0 #endif #ifdef __has_builtin # define FMT_HAS_BUILTIN(x) __has_builtin(x) #else # define FMT_HAS_BUILTIN(x) 0 #endif #ifdef __has_cpp_attribute # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) #else # define FMT_HAS_CPP_ATTRIBUTE(x) 0 #endif #ifndef FMT_USE_VARIADIC_TEMPLATES // Variadic templates are available in GCC since version 4.4 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++ // since version 2013. # define FMT_USE_VARIADIC_TEMPLATES \ (FMT_HAS_FEATURE(cxx_variadic_templates) || \ (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800) #endif #ifndef FMT_USE_RVALUE_REFERENCES // Don't use rvalue references when compiling with clang and an old libstdc++ // as the latter doesn't provide std::move. # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 # define FMT_USE_RVALUE_REFERENCES 0 # else # define FMT_USE_RVALUE_REFERENCES \ (FMT_HAS_FEATURE(cxx_rvalue_references) || \ (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600) # endif #endif #if FMT_USE_RVALUE_REFERENCES # include // for std::move #endif // Define FMT_USE_NOEXCEPT to make C++ Format use noexcept (C++11 feature). #if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) # define FMT_NOEXCEPT noexcept #else # define FMT_NOEXCEPT throw() #endif // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \ (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&) = delete; \ TypeName& operator=(const TypeName&) = delete #else # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ TypeName& operator=(const TypeName&) #endif namespace fmt { // Fix the warning about long long on older versions of GCC // that don't support the diagnostic pragma. FMT_GCC_EXTENSION typedef long long LongLong; FMT_GCC_EXTENSION typedef unsigned long long ULongLong; #if FMT_USE_RVALUE_REFERENCES using std::move; #endif template class BasicWriter; typedef BasicWriter Writer; typedef BasicWriter WWriter; template class BasicFormatter; template void format(BasicFormatter &f, const Char *&format_str, const T &value); /** \rst A string reference. It can be constructed from a C string or ``std::string``. You can use one of the following typedefs for common character types: +------------+-------------------------+ | Type | Definition | +============+=========================+ | StringRef | BasicStringRef | +------------+-------------------------+ | WStringRef | BasicStringRef | +------------+-------------------------+ This class is most useful as a parameter type to allow passing different types of strings to a function, for example:: template std::string format(StringRef format_str, const Args & ... args); format("{}", 42); format(std::string("{}"), 42); \endrst */ template class BasicStringRef { private: const Char *data_; std::size_t size_; public: /** Constructs a string reference object from a C string and a size. */ BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {} /** Constructs a string reference object from a C string computing the size with ``std::char_traits::length``. */ BasicStringRef(const Char *s) : data_(s), size_(std::char_traits::length(s)) {} /** Constructs a string reference from an `std::string` object. */ BasicStringRef(const std::basic_string &s) : data_(s.c_str()), size_(s.size()) {} /** Converts a string reference to an `std::string` object. */ operator std::basic_string() const { return std::basic_string(data_, size()); } /** Returns the pointer to a C string. */ const Char *c_str() const { return data_; } /** Returns the string size. */ std::size_t size() const { return size_; } friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) { return lhs.data_ == rhs.data_; } friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) { return lhs.data_ != rhs.data_; } }; typedef BasicStringRef StringRef; typedef BasicStringRef WStringRef; /** A formatting error such as invalid format string. */ class FormatError : public std::runtime_error { public: explicit FormatError(StringRef message) : std::runtime_error(message.c_str()) {} }; namespace internal { // The number of characters to store in the MemoryBuffer object itself // to avoid dynamic memory allocation. enum { INLINE_BUFFER_SIZE = 500 }; #if _SECURE_SCL // Use checked iterator to avoid warnings on MSVC. template inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) { return stdext::checked_array_iterator(ptr, size); } #else template inline T *make_ptr(T *ptr, std::size_t) { return ptr; } #endif // A buffer for POD types. It supports a subset of std::vector's operations. template class Buffer { private: FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); protected: T *ptr_; std::size_t size_; std::size_t capacity_; Buffer(T *ptr = 0, std::size_t capacity = 0) : ptr_(ptr), size_(0), capacity_(capacity) {} virtual void grow(std::size_t size) = 0; public: virtual ~Buffer() {} // Returns the size of this buffer. std::size_t size() const { return size_; } // Returns the capacity of this buffer. std::size_t capacity() const { return capacity_; } // Resizes the buffer. If T is a POD type new elements are not initialized. void resize(std::size_t new_size) { if (new_size > capacity_) grow(new_size); size_ = new_size; } // Reserves space to store at least capacity elements. void reserve(std::size_t capacity) { if (capacity > capacity_) grow(capacity); } void clear() FMT_NOEXCEPT { size_ = 0; } void push_back(const T &value) { if (size_ == capacity_) grow(size_ + 1); ptr_[size_++] = value; } // Appends data to the end of the buffer. void append(const T *begin, const T *end); T &operator[](std::size_t index) { return ptr_[index]; } const T &operator[](std::size_t index) const { return ptr_[index]; } }; template void Buffer::append(const T *begin, const T *end) { std::ptrdiff_t num_elements = end - begin; if (size_ + num_elements > capacity_) grow(size_ + num_elements); std::copy(begin, end, make_ptr(ptr_, capacity_) + size_); size_ += num_elements; } // A memory buffer for POD types with the first SIZE elements stored in // the object itself. template > class MemoryBuffer : private Allocator, public Buffer { private: T data_[SIZE]; // Free memory allocated by the buffer. void free() { if (this->ptr_ != data_) this->deallocate(this->ptr_, this->capacity_); } protected: void grow(std::size_t size); public: explicit MemoryBuffer(const Allocator &alloc = Allocator()) : Allocator(alloc), Buffer(data_, SIZE) {} ~MemoryBuffer() { free(); } #if FMT_USE_RVALUE_REFERENCES private: // Move data from other to this buffer. void move(MemoryBuffer &other) { Allocator &this_alloc = *this, &other_alloc = other; this_alloc = std::move(other_alloc); this->size_ = other.size_; this->capacity_ = other.capacity_; if (other.ptr_ == other.data_) { this->ptr_ = data_; std::copy(other.data_, other.data_ + this->size_, make_ptr(data_, this->capacity_)); } else { this->ptr_ = other.ptr_; // Set pointer to the inline array so that delete is not called // when freeing. other.ptr_ = other.data_; } } public: MemoryBuffer(MemoryBuffer &&other) { move(other); } MemoryBuffer &operator=(MemoryBuffer &&other) { assert(this != &other); free(); move(other); return *this; } #endif // Returns a copy of the allocator associated with this buffer. Allocator get_allocator() const { return *this; } }; template void MemoryBuffer::grow(std::size_t size) { std::size_t new_capacity = (std::max)(size, this->capacity_ + this->capacity_ / 2); T *new_ptr = this->allocate(new_capacity); // The following code doesn't throw, so the raw pointer above doesn't leak. std::copy(this->ptr_, this->ptr_ + this->size_, make_ptr(new_ptr, new_capacity)); std::size_t old_capacity = this->capacity_; T *old_ptr = this->ptr_; this->capacity_ = new_capacity; this->ptr_ = new_ptr; // deallocate may throw (at least in principle), but it doesn't matter since // the buffer already uses the new storage and will deallocate it in case // of exception. if (old_ptr != data_) this->deallocate(old_ptr, old_capacity); } // A fixed-size buffer. template class FixedBuffer : public fmt::internal::Buffer { public: FixedBuffer(Char *array, std::size_t size) : fmt::internal::Buffer(array, size) {} protected: void grow(std::size_t size); }; #ifndef _MSC_VER // Portable version of signbit. inline int getsign(double x) { // When compiled in C++11 mode signbit is no longer a macro but a function // defined in namespace std and the macro is undefined. # ifdef signbit return signbit(x); # else return std::signbit(x); # endif } // Portable version of isinf. # ifdef isinf inline int isinfinity(double x) { return isinf(x); } inline int isinfinity(long double x) { return isinf(x); } # else inline int isinfinity(double x) { return std::isinf(x); } inline int isinfinity(long double x) { return std::isinf(x); } # endif #else inline int getsign(double value) { if (value < 0) return 1; if (value == value) return 0; int dec = 0, sign = 0; char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. _ecvt_s(buffer, sizeof(buffer), value, 0, &dec, &sign); return sign; } inline int isinfinity(double x) { return !_finite(x); } inline int isinfinity(long double x) { return !_finite(static_cast(x)); } #endif template class BasicCharTraits { public: #if _SECURE_SCL typedef stdext::checked_array_iterator CharPtr; #else typedef Char *CharPtr; #endif }; template class CharTraits; template <> class CharTraits : public BasicCharTraits { private: // Conversion from wchar_t to char is not allowed. static char convert(wchar_t); public: static char convert(char value) { return value; } // Formats a floating-point number. template static int format_float(char *buffer, std::size_t size, const char *format, unsigned width, int precision, T value); }; template <> class CharTraits : public BasicCharTraits { public: static wchar_t convert(char value) { return value; } static wchar_t convert(wchar_t value) { return value; } template static int format_float(wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, T value); }; // Checks if a number is negative - used to avoid warnings. template struct SignChecker { template static bool is_negative(T value) { return value < 0; } }; template <> struct SignChecker { template static bool is_negative(T) { return false; } }; // Returns true if value is negative, false otherwise. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. template inline bool is_negative(T value) { return SignChecker::is_signed>::is_negative(value); } // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. template struct TypeSelector { typedef uint32_t Type; }; template <> struct TypeSelector { typedef uint64_t Type; }; template struct IntTraits { // Smallest of uint32_t and uint64_t that is large enough to represent // all values of T. typedef typename TypeSelector::digits <= 32>::Type MainType; }; // MakeUnsigned::Type gives an unsigned type corresponding to integer type T. template struct MakeUnsigned { typedef T Type; }; #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ template <> \ struct MakeUnsigned { typedef U Type; } FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char); FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char); FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short); FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned); FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); void report_unknown_type(char code, const char *type); // Static data is placed in this class template to allow header-only // configuration. template struct BasicData { static const uint32_t POWERS_OF_10_32[]; static const uint64_t POWERS_OF_10_64[]; static const char DIGITS[]; }; typedef BasicData<> Data; #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) # define FMT_BUILTIN_CLZ(n) __builtin_clz(n) #endif #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) #endif #ifdef FMT_BUILTIN_CLZLL // Returns the number of decimal digits in n. Leading zeros are not counted // except for n == 0 in which case count_digits returns 1. inline unsigned count_digits(uint64_t n) { // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. unsigned t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; return t - (n < Data::POWERS_OF_10_64[t]) + 1; } #else // Fallback version of count_digits used when __builtin_clz is not available. inline unsigned count_digits(uint64_t n) { unsigned count = 1; for (;;) { // Integer division is slow so do it for a group of four digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. if (n < 10) return count; if (n < 100) return count + 1; if (n < 1000) return count + 2; if (n < 10000) return count + 3; n /= 10000u; count += 4; } } #endif #ifdef FMT_BUILTIN_CLZ // Optional version of count_digits for better performance on 32-bit platforms. inline unsigned count_digits(uint32_t n) { uint32_t t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; return t - (n < Data::POWERS_OF_10_32[t]) + 1; } #endif // Formats a decimal unsigned integer value writing into buffer. template inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { --num_digits; while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. unsigned index = (value % 100) * 2; value /= 100; buffer[num_digits] = Data::DIGITS[index + 1]; buffer[num_digits - 1] = Data::DIGITS[index]; num_digits -= 2; } if (value < 10) { *buffer = static_cast('0' + value); return; } unsigned index = static_cast(value * 2); buffer[1] = Data::DIGITS[index + 1]; buffer[0] = Data::DIGITS[index]; } #ifdef _WIN32 // A converter from UTF-8 to UTF-16. // It is only provided for Windows since other systems support UTF-8 natively. class UTF8ToUTF16 { private: MemoryBuffer buffer_; public: explicit UTF8ToUTF16(StringRef s); operator WStringRef() const { return WStringRef(&buffer_[0], size()); } size_t size() const { return buffer_.size() - 1; } const wchar_t *c_str() const { return &buffer_[0]; } std::wstring str() const { return std::wstring(&buffer_[0], size()); } }; // A converter from UTF-16 to UTF-8. // It is only provided for Windows since other systems support UTF-8 natively. class UTF16ToUTF8 { private: MemoryBuffer buffer_; public: UTF16ToUTF8() {} explicit UTF16ToUTF8(WStringRef s); operator StringRef() const { return StringRef(&buffer_[0], size()); } size_t size() const { return buffer_.size() - 1; } const char *c_str() const { return &buffer_[0]; } std::string str() const { return std::string(&buffer_[0], size()); } // Performs conversion returning a system error code instead of // throwing exception on conversion error. This method may still throw // in case of memory allocation error. int convert(WStringRef s); }; #endif void format_system_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; #ifdef _WIN32 void format_windows_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; #endif // Computes max(Arg, 1) at compile time. It is used to avoid errors about // allocating an array of 0 size. template struct NonZero { enum { VALUE = Arg }; }; template <> struct NonZero<0> { enum { VALUE = 1 }; }; // The value of a formatting argument. It is a POD type to allow storage in // internal::MemoryBuffer. struct Value { template struct StringValue { const Char *value; std::size_t size; }; typedef void (*FormatFunc)( void *formatter, const void *arg, void *format_str_ptr); struct CustomValue { const void *value; FormatFunc format; }; union { int int_value; unsigned uint_value; LongLong long_long_value; ULongLong ulong_long_value; double double_value; long double long_double_value; const void *pointer; StringValue string; StringValue sstring; StringValue ustring; StringValue wstring; CustomValue custom; }; }; struct Arg : Value { enum Type { NONE, // Integer types should go first, INT, UINT, LONG_LONG, ULONG_LONG, CHAR, LAST_INTEGER_TYPE = CHAR, // followed by floating-point types. DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE, CSTRING, STRING, WSTRING, POINTER, CUSTOM }; Type type; }; template struct None {}; // A helper class template to enable or disable overloads taking wide // characters and strings in MakeValue. template struct WCharHelper { typedef None Supported; typedef T Unsupported; }; template struct WCharHelper { typedef T Supported; typedef None Unsupported; }; // Makes a Value object from any type. template class MakeValue : public Value { private: // The following two methods are private to disallow formatting of // arbitrary pointers. If you want to output a pointer cast it to // "void *" or "const void *". In particular, this forbids formatting // of "[const] volatile char *" which is printed as bool by iostreams. // Do not implement! template MakeValue(const T *value); template MakeValue(T *value); // The following methods are private to disallow formatting of wide // characters and strings into narrow strings as in // fmt::format("{}", L"test"); // To fix this, use a wide format string: fmt::format(L"{}", L"test"). MakeValue(typename WCharHelper::Unsupported); MakeValue(typename WCharHelper::Unsupported); MakeValue(typename WCharHelper::Unsupported); MakeValue(typename WCharHelper::Unsupported); MakeValue(typename WCharHelper::Unsupported); void set_string(StringRef str) { string.value = str.c_str(); string.size = str.size(); } void set_string(WStringRef str) { wstring.value = str.c_str(); wstring.size = str.size(); } // Formats an argument of a custom type, such as a user-defined class. template static void format_custom_arg( void *formatter, const void *arg, void *format_str_ptr) { format(*static_cast*>(formatter), *static_cast(format_str_ptr), *static_cast(arg)); } public: MakeValue() {} #define FMT_MAKE_VALUE(Type, field, TYPE) \ MakeValue(Type value) { field = value; } \ static uint64_t type(Type) { return Arg::TYPE; } FMT_MAKE_VALUE(bool, int_value, INT) FMT_MAKE_VALUE(short, int_value, INT) FMT_MAKE_VALUE(unsigned short, uint_value, UINT) FMT_MAKE_VALUE(int, int_value, INT) FMT_MAKE_VALUE(unsigned, uint_value, UINT) MakeValue(long value) { // To minimize the number of types we need to deal with, long is // translated either to int or to long long depending on its size. if (sizeof(long) == sizeof(int)) int_value = static_cast(value); else long_long_value = value; } static uint64_t type(long) { return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG; } MakeValue(unsigned long value) { if (sizeof(unsigned long) == sizeof(unsigned)) uint_value = static_cast(value); else ulong_long_value = value; } static uint64_t type(unsigned long) { return sizeof(unsigned long) == sizeof(unsigned) ? Arg::UINT : Arg::ULONG_LONG; } FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG) FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG) FMT_MAKE_VALUE(float, double_value, DOUBLE) FMT_MAKE_VALUE(double, double_value, DOUBLE) FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE) FMT_MAKE_VALUE(signed char, int_value, CHAR) FMT_MAKE_VALUE(unsigned char, int_value, CHAR) FMT_MAKE_VALUE(char, int_value, CHAR) MakeValue(typename WCharHelper::Supported value) { int_value = value; } static uint64_t type(wchar_t) { return Arg::CHAR; } #define FMT_MAKE_STR_VALUE(Type, TYPE) \ MakeValue(Type value) { set_string(value); } \ static uint64_t type(Type) { return Arg::TYPE; } FMT_MAKE_VALUE(char *, string.value, CSTRING) FMT_MAKE_VALUE(const char *, string.value, CSTRING) FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING) FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING) FMT_MAKE_STR_VALUE(const std::string &, STRING) FMT_MAKE_STR_VALUE(StringRef, STRING) #define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ MakeValue(typename WCharHelper::Supported value) { \ set_string(value); \ } \ static uint64_t type(Type) { return Arg::TYPE; } FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING) FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING) FMT_MAKE_VALUE(void *, pointer, POINTER) FMT_MAKE_VALUE(const void *, pointer, POINTER) template MakeValue(const T &value) { custom.value = &value; custom.format = &format_custom_arg; } template static uint64_t type(const T &) { return Arg::CUSTOM; } }; #define FMT_DISPATCH(call) static_cast(this)->call // An argument visitor. // To use ArgVisitor define a subclass that implements some or all of the // visit methods with the same signatures as the methods in ArgVisitor, // for example, visit_int(int). // Specify the subclass name as the Impl template parameter. Then calling // ArgVisitor::visit for some argument will dispatch to a visit method // specific to the argument type. For example, if the argument type is // double then visit_double(double) method of a subclass will be called. // If the subclass doesn't contain a method with this signature, then // a corresponding method of ArgVisitor will be called. // // Example: // class MyArgVisitor : public ArgVisitor { // public: // void visit_int(int value) { print("{}", value); } // void visit_double(double value) { print("{}", value ); } // }; // // ArgVisitor uses the curiously recurring template pattern: // http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern template class ArgVisitor { public: Result visit_unhandled_arg() { return Result(); } Result visit_int(int value) { return FMT_DISPATCH(visit_any_int(value)); } Result visit_long_long(LongLong value) { return FMT_DISPATCH(visit_any_int(value)); } Result visit_uint(unsigned value) { return FMT_DISPATCH(visit_any_int(value)); } Result visit_ulong_long(ULongLong value) { return FMT_DISPATCH(visit_any_int(value)); } Result visit_char(int value) { return FMT_DISPATCH(visit_any_int(value)); } template Result visit_any_int(T) { return FMT_DISPATCH(visit_unhandled_arg()); } Result visit_double(double value) { return FMT_DISPATCH(visit_any_double(value)); } Result visit_long_double(long double value) { return FMT_DISPATCH(visit_any_double(value)); } template Result visit_any_double(T) { return FMT_DISPATCH(visit_unhandled_arg()); } Result visit_string(Arg::StringValue) { return FMT_DISPATCH(visit_unhandled_arg()); } Result visit_wstring(Arg::StringValue) { return FMT_DISPATCH(visit_unhandled_arg()); } Result visit_pointer(const void *) { return FMT_DISPATCH(visit_unhandled_arg()); } Result visit_custom(Arg::CustomValue) { return FMT_DISPATCH(visit_unhandled_arg()); } Result visit(const Arg &arg) { switch (arg.type) { default: assert(false); return Result(); case Arg::INT: return FMT_DISPATCH(visit_int(arg.int_value)); case Arg::UINT: return FMT_DISPATCH(visit_uint(arg.uint_value)); case Arg::LONG_LONG: return FMT_DISPATCH(visit_long_long(arg.long_long_value)); case Arg::ULONG_LONG: return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value)); case Arg::DOUBLE: return FMT_DISPATCH(visit_double(arg.double_value)); case Arg::LONG_DOUBLE: return FMT_DISPATCH(visit_long_double(arg.long_double_value)); case Arg::CHAR: return FMT_DISPATCH(visit_char(arg.int_value)); case Arg::CSTRING: { Value::StringValue str = arg.string; str.size = 0; return FMT_DISPATCH(visit_string(str)); } case Arg::STRING: return FMT_DISPATCH(visit_string(arg.string)); case Arg::WSTRING: return FMT_DISPATCH(visit_wstring(arg.wstring)); case Arg::POINTER: return FMT_DISPATCH(visit_pointer(arg.pointer)); case Arg::CUSTOM: return FMT_DISPATCH(visit_custom(arg.custom)); } } }; class RuntimeError : public std::runtime_error { protected: RuntimeError() : std::runtime_error("") {} }; template class ArgFormatter; } // namespace internal /** An argument list. */ class ArgList { private: uint64_t types_; const internal::Value *values_; public: // Maximum number of arguments that can be passed in ArgList. enum { MAX_ARGS = 16 }; ArgList() : types_(0) {} ArgList(ULongLong types, const internal::Value *values) : types_(types), values_(values) {} /** Returns the argument at specified index. */ internal::Arg operator[](unsigned index) const { using internal::Arg; Arg arg; if (index >= MAX_ARGS) { arg.type = Arg::NONE; return arg; } unsigned shift = index * 4; uint64_t mask = 0xf; Arg::Type type = static_cast((types_ & (mask << shift)) >> shift); arg.type = type; if (type != Arg::NONE) { internal::Value &value = arg; value = values_[index]; } return arg; } }; struct FormatSpec; namespace internal { class FormatterBase { private: ArgList args_; int next_arg_index_; // Returns the argument with specified index. Arg do_get_arg(unsigned arg_index, const char *&error); protected: void set_args(const ArgList &args) { args_ = args; next_arg_index_ = 0; } // Returns the next argument. Arg next_arg(const char *&error); // Checks if manual indexing is used and returns the argument with // specified index. Arg get_arg(unsigned arg_index, const char *&error); template void write(BasicWriter &w, const Char *start, const Char *end) { if (start != end) w << BasicStringRef(start, end - start); } }; // A printf formatter. template class PrintfFormatter : private FormatterBase { private: void parse_flags(FormatSpec &spec, const Char *&s); // Returns the argument with specified index or, if arg_index is equal // to the maximum unsigned value, the next argument. Arg get_arg(const Char *s, unsigned arg_index = (std::numeric_limits::max)()); // Parses argument index, flags and width and returns the argument index. unsigned parse_header(const Char *&s, FormatSpec &spec); public: void format(BasicWriter &writer, BasicStringRef format_str, const ArgList &args); }; } // namespace internal // A formatter. template class BasicFormatter : private internal::FormatterBase { private: BasicWriter &writer_; const Char *start_; FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter); // Parses argument index and returns corresponding argument. internal::Arg parse_arg_index(const Char *&s); public: explicit BasicFormatter(BasicWriter &w) : writer_(w) {} BasicWriter &writer() { return writer_; } void format(BasicStringRef format_str, const ArgList &args); const Char *format(const Char *&format_str, const internal::Arg &arg); }; enum Alignment { ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC }; // Flags. enum { SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. }; // An empty format specifier. struct EmptySpec {}; // A type specifier. template struct TypeSpec : EmptySpec { Alignment align() const { return ALIGN_DEFAULT; } unsigned width() const { return 0; } int precision() const { return -1; } bool flag(unsigned) const { return false; } char type() const { return TYPE; } char fill() const { return ' '; } }; // A width specifier. struct WidthSpec { unsigned width_; // Fill is always wchar_t and cast to char if necessary to avoid having // two specialization of WidthSpec and its subclasses. wchar_t fill_; WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} unsigned width() const { return width_; } wchar_t fill() const { return fill_; } }; // An alignment specifier. struct AlignSpec : WidthSpec { Alignment align_; AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) : WidthSpec(width, fill), align_(align) {} Alignment align() const { return align_; } int precision() const { return -1; } }; // An alignment and type specifier. template struct AlignTypeSpec : AlignSpec { AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} bool flag(unsigned) const { return false; } char type() const { return TYPE; } }; // A full format specifier. struct FormatSpec : AlignSpec { unsigned flags_; int precision_; char type_; FormatSpec( unsigned width = 0, char type = 0, wchar_t fill = ' ') : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} bool flag(unsigned f) const { return (flags_ & f) != 0; } int precision() const { return precision_; } char type() const { return type_; } }; // An integer format specifier. template , typename Char = char> class IntFormatSpec : public SpecT { private: T value_; public: IntFormatSpec(T val, const SpecT &spec = SpecT()) : SpecT(spec), value_(val) {} T value() const { return value_; } }; // A string format specifier. template class StrFormatSpec : public AlignSpec { private: const T *str_; public: StrFormatSpec(const T *str, unsigned width, wchar_t fill) : AlignSpec(width, fill), str_(str) {} const T *str() const { return str_; } }; /** Returns an integer format specifier to format the value in base 2. */ IntFormatSpec > bin(int value); /** Returns an integer format specifier to format the value in base 8. */ IntFormatSpec > oct(int value); /** Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9. */ IntFormatSpec > hex(int value); /** Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9. */ IntFormatSpec > hexu(int value); /** \rst Returns an integer format specifier to pad the formatted argument with the fill character to the specified width using the default (right) numeric alignment. **Example**:: MemoryWriter out; out << pad(hex(0xcafe), 8, '0'); // out.str() == "0000cafe" \endrst */ template IntFormatSpec, Char> pad( int value, unsigned width, Char fill = ' '); #define FMT_DEFINE_INT_FORMATTERS(TYPE) \ inline IntFormatSpec > bin(TYPE value) { \ return IntFormatSpec >(value, TypeSpec<'b'>()); \ } \ \ inline IntFormatSpec > oct(TYPE value) { \ return IntFormatSpec >(value, TypeSpec<'o'>()); \ } \ \ inline IntFormatSpec > hex(TYPE value) { \ return IntFormatSpec >(value, TypeSpec<'x'>()); \ } \ \ inline IntFormatSpec > hexu(TYPE value) { \ return IntFormatSpec >(value, TypeSpec<'X'>()); \ } \ \ template \ inline IntFormatSpec > pad( \ IntFormatSpec > f, unsigned width) { \ return IntFormatSpec >( \ f.value(), AlignTypeSpec(width, ' ')); \ } \ \ /* For compatibility with older compilers we provide two overloads for pad, */ \ /* one that takes a fill character and one that doesn't. In the future this */ \ /* can be replaced with one overload making the template argument Char */ \ /* default to char (C++11). */ \ template \ inline IntFormatSpec, Char> pad( \ IntFormatSpec, Char> f, \ unsigned width, Char fill) { \ return IntFormatSpec, Char>( \ f.value(), AlignTypeSpec(width, fill)); \ } \ \ inline IntFormatSpec > pad( \ TYPE value, unsigned width) { \ return IntFormatSpec >( \ value, AlignTypeSpec<0>(width, ' ')); \ } \ \ template \ inline IntFormatSpec, Char> pad( \ TYPE value, unsigned width, Char fill) { \ return IntFormatSpec, Char>( \ value, AlignTypeSpec<0>(width, fill)); \ } FMT_DEFINE_INT_FORMATTERS(int) FMT_DEFINE_INT_FORMATTERS(long) FMT_DEFINE_INT_FORMATTERS(unsigned) FMT_DEFINE_INT_FORMATTERS(unsigned long) FMT_DEFINE_INT_FORMATTERS(LongLong) FMT_DEFINE_INT_FORMATTERS(ULongLong) /** \rst Returns a string formatter that pads the formatted argument with the fill character to the specified width using the default (left) string alignment. **Example**:: std::string s = str(MemoryWriter() << pad("abc", 8)); // s == "abc " \endrst */ template inline StrFormatSpec pad( const Char *str, unsigned width, Char fill = ' ') { return StrFormatSpec(str, width, fill); } inline StrFormatSpec pad( const wchar_t *str, unsigned width, char fill = ' ') { return StrFormatSpec(str, width, fill); } // Generates a comma-separated list with results of applying f to // numbers 0..n-1. # define FMT_GEN(n, f) FMT_GEN##n(f) # define FMT_GEN1(f) f(0) # define FMT_GEN2(f) FMT_GEN1(f), f(1) # define FMT_GEN3(f) FMT_GEN2(f), f(2) # define FMT_GEN4(f) FMT_GEN3(f), f(3) # define FMT_GEN5(f) FMT_GEN4(f), f(4) # define FMT_GEN6(f) FMT_GEN5(f), f(5) # define FMT_GEN7(f) FMT_GEN6(f), f(6) # define FMT_GEN8(f) FMT_GEN7(f), f(7) # define FMT_GEN9(f) FMT_GEN8(f), f(8) # define FMT_GEN10(f) FMT_GEN9(f), f(9) # define FMT_GEN11(f) FMT_GEN10(f), f(10) # define FMT_GEN12(f) FMT_GEN11(f), f(11) # define FMT_GEN13(f) FMT_GEN12(f), f(12) # define FMT_GEN14(f) FMT_GEN13(f), f(13) # define FMT_GEN15(f) FMT_GEN14(f), f(14) namespace internal { inline uint64_t make_type() { return 0; } template inline uint64_t make_type(const T &arg) { return MakeValue::type(arg); } #if FMT_USE_VARIADIC_TEMPLATES template inline uint64_t make_type(const Arg &first, const Args & ... tail) { return make_type(first) | (make_type(tail...) << 4); } #else struct ArgType { uint64_t type; ArgType() : type(0) {} template ArgType(const T &arg) : type(make_type(arg)) {} }; # define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) { return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) | (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | (t12.type << 48) | (t13.type << 52) | (t14.type << 56); } #endif } // namespace internal # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n # define FMT_MAKE_ARG_TYPE(n) T##n # define FMT_MAKE_ARG(n) const T##n &v##n # define FMT_MAKE_REF_char(n) fmt::internal::MakeValue(v##n) # define FMT_MAKE_REF_wchar_t(n) fmt::internal::MakeValue(v##n) #if FMT_USE_VARIADIC_TEMPLATES // Defines a variadic function returning void. # define FMT_VARIADIC_VOID(func, arg_type) \ template \ void func(arg_type arg1, const Args & ... args) { \ const fmt::internal::Value values[ \ fmt::internal::NonZero::VALUE] = { \ fmt::internal::MakeValue(args)... \ }; \ func(arg1, ArgList(fmt::internal::make_type(args...), values)); \ } // Defines a variadic constructor. # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ template \ ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \ using fmt::internal::MakeValue; \ const fmt::internal::Value values[ \ fmt::internal::NonZero::VALUE] = { \ MakeValue(args)... \ }; \ func(arg0, arg1, ArgList(fmt::internal::make_type(args...), values)); \ } #else # define FMT_MAKE_REF(n) fmt::internal::MakeValue(v##n) # define FMT_MAKE_REF2(n) v##n // Defines a wrapper for a function taking one argument of type arg_type // and n additional arguments of arbitrary types. # define FMT_WRAP1(func, arg_type, n) \ template \ inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg1, fmt::ArgList( \ fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \ } // Emulates a variadic function returning void on a pre-C++11 compiler. # define FMT_VARIADIC_VOID(func, arg_type) \ inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \ FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \ FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \ FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \ FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ template \ ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg0, arg1, fmt::ArgList( \ fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \ } // Emulates a variadic constructor on a pre-C++11 compiler. # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) #endif // Generates a comma-separated list with results of applying f to pairs // (argument, index). #define FMT_FOR_EACH1(f, x0) f(x0, 0) #define FMT_FOR_EACH2(f, x0, x1) \ FMT_FOR_EACH1(f, x0), f(x1, 1) #define FMT_FOR_EACH3(f, x0, x1, x2) \ FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2) #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \ FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \ FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \ FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \ FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \ FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \ FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \ FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) /** An error returned by an operating system or a language runtime, for example a file opening error. */ class SystemError : public internal::RuntimeError { private: void init(int err_code, StringRef format_str, ArgList args); protected: int error_code_; typedef char Char; // For FMT_VARIADIC_CTOR. SystemError() {} public: /** \rst Constructs a :class:`fmt::SystemError` object with the description of the form .. parsed-literal:: **: ** where ** is the formatted message and ** is the system message corresponding to the error code. *error_code* is a system error code as given by ``errno``. If *error_code* is not a valid error code such as -1, the system message may look like "Unknown error -1" and is platform-dependent. **Example**:: // This throws a SystemError with the description // cannot open file 'madeup': No such file or directory // or similar (system message may vary). const char *filename = "madeup"; std::FILE *file = std::fopen(filename, "r"); if (!file) throw fmt::SystemError(errno, "cannot open file '{}'", filename); \endrst */ SystemError(int error_code, StringRef message) { init(error_code, message, ArgList()); } FMT_VARIADIC_CTOR(SystemError, init, int, StringRef) int error_code() const { return error_code_; } }; /** \rst This template provides operations for formatting and writing data into a character stream. The output is stored in a buffer provided by a subclass such as :class:`fmt::BasicMemoryWriter`. You can use one of the following typedefs for common character types: +---------+----------------------+ | Type | Definition | +=========+======================+ | Writer | BasicWriter | +---------+----------------------+ | WWriter | BasicWriter | +---------+----------------------+ \endrst */ template class BasicWriter { private: // Output buffer. internal::Buffer &buffer_; FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter); typedef typename internal::CharTraits::CharPtr CharPtr; #if _SECURE_SCL // Returns pointer value. static Char *get(CharPtr p) { return p.base(); } #else static Char *get(Char *p) { return p; } #endif // Fills the padding around the content and returns the pointer to the // content area. static CharPtr fill_padding(CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill); // Grows the buffer by n characters and returns a pointer to the newly // allocated area. CharPtr grow_buffer(std::size_t n) { std::size_t size = buffer_.size(); buffer_.resize(size + n); return internal::make_ptr(&buffer_[size], n); } // Prepare a buffer for integer formatting. CharPtr prepare_int_buffer(unsigned num_digits, const EmptySpec &, const char *prefix, unsigned prefix_size) { unsigned size = prefix_size + num_digits; CharPtr p = grow_buffer(size); std::copy(prefix, prefix + prefix_size, p); return p + size - 1; } template CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); // Formats an integer. template void write_int(T value, Spec spec); // Formats a floating-point number (double or long double). template void write_double(T value, const FormatSpec &spec); // Writes a formatted string. template CharPtr write_str( const StrChar *s, std::size_t size, const AlignSpec &spec); template void write_str( const internal::Arg::StringValue &str, const FormatSpec &spec); // This following methods are private to disallow writing wide characters // and strings to a char stream. If you want to print a wide string as a // pointer as std::ostream does, cast it to const void*. // Do not implement! void operator<<(typename internal::WCharHelper::Unsupported); void operator<<( typename internal::WCharHelper::Unsupported); // Appends floating-point length specifier to the format string. // The second argument is only used for overload resolution. void append_float_length(Char *&format_ptr, long double) { *format_ptr++ = 'L'; } template void append_float_length(Char *&, T) {} friend class internal::ArgFormatter; friend class internal::PrintfFormatter; protected: /** Constructs a ``BasicWriter`` object. */ explicit BasicWriter(internal::Buffer &b) : buffer_(b) {} public: /** Destroys a ``BasicWriter`` object. */ virtual ~BasicWriter() {} /** Returns the total number of characters written. */ std::size_t size() const { return buffer_.size(); } /** Returns a pointer to the output buffer content. No terminating null character is appended. */ const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; } /** Returns a pointer to the output buffer content with terminating null character appended. */ const Char *c_str() const { std::size_t size = buffer_.size(); buffer_.reserve(size + 1); buffer_[size] = '\0'; return &buffer_[0]; } /** Returns the content of the output buffer as an `std::string`. */ std::basic_string str() const { return std::basic_string(&buffer_[0], buffer_.size()); } /** \rst Writes formatted data. *args* is an argument list representing arbitrary arguments. **Example**:: MemoryWriter out; out.write("Current point:\n"); out.write("({:+f}, {:+f})", -3.14, 3.14); This will write the following output to the ``out`` object: .. code-block:: none Current point: (-3.140000, +3.140000) The output can be accessed using :func:`data()`, :func:`c_str` or :func:`str` methods. See also :ref:`syntax`. \endrst */ void write(BasicStringRef format, ArgList args) { BasicFormatter(*this).format(format, args); } FMT_VARIADIC_VOID(write, BasicStringRef) BasicWriter &operator<<(int value) { return *this << IntFormatSpec(value); } BasicWriter &operator<<(unsigned value) { return *this << IntFormatSpec(value); } BasicWriter &operator<<(long value) { return *this << IntFormatSpec(value); } BasicWriter &operator<<(unsigned long value) { return *this << IntFormatSpec(value); } BasicWriter &operator<<(LongLong value) { return *this << IntFormatSpec(value); } /** Formats *value* and writes it to the stream. */ BasicWriter &operator<<(ULongLong value) { return *this << IntFormatSpec(value); } BasicWriter &operator<<(double value) { write_double(value, FormatSpec()); return *this; } /** Formats *value* using the general format for floating-point numbers (``'g'``) and writes it to the stream. */ BasicWriter &operator<<(long double value) { write_double(value, FormatSpec()); return *this; } /** Writes a character to the stream. */ BasicWriter &operator<<(char value) { buffer_.push_back(value); return *this; } BasicWriter &operator<<( typename internal::WCharHelper::Supported value) { buffer_.push_back(value); return *this; } /** Writes *value* to the stream. */ BasicWriter &operator<<(fmt::BasicStringRef value) { const Char *str = value.c_str(); buffer_.append(str, str + value.size()); return *this; } template BasicWriter &operator<<(IntFormatSpec spec) { internal::CharTraits::convert(FillChar()); write_int(spec.value(), spec); return *this; } template BasicWriter &operator<<(const StrFormatSpec &spec) { const StrChar *s = spec.str(); // TODO: error if fill is not convertible to Char write_str(s, std::char_traits::length(s), spec); return *this; } void clear() FMT_NOEXCEPT { buffer_.clear(); } }; template template typename BasicWriter::CharPtr BasicWriter::write_str( const StrChar *s, std::size_t size, const AlignSpec &spec) { CharPtr out = CharPtr(); if (spec.width() > size) { out = grow_buffer(spec.width()); Char fill = static_cast(spec.fill()); if (spec.align() == ALIGN_RIGHT) { std::fill_n(out, spec.width() - size, fill); out += spec.width() - size; } else if (spec.align() == ALIGN_CENTER) { out = fill_padding(out, spec.width(), size, fill); } else { std::fill_n(out + size, spec.width() - size, fill); } } else { out = grow_buffer(size); } std::copy(s, s + size, out); return out; } template typename BasicWriter::CharPtr BasicWriter::fill_padding( CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill) { std::size_t padding = total_size - content_size; std::size_t left_padding = padding / 2; Char fill_char = static_cast(fill); std::fill_n(buffer, left_padding, fill_char); buffer += left_padding; CharPtr content = buffer; std::fill_n(buffer + content_size, padding - left_padding, fill_char); return content; } template template typename BasicWriter::CharPtr BasicWriter::prepare_int_buffer( unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size) { unsigned width = spec.width(); Alignment align = spec.align(); Char fill = static_cast(spec.fill()); if (spec.precision() > static_cast(num_digits)) { // Octal prefix '0' is counted as a digit, so ignore it if precision // is specified. if (prefix_size > 0 && prefix[prefix_size - 1] == '0') --prefix_size; unsigned number_size = prefix_size + spec.precision(); AlignSpec subspec(number_size, '0', ALIGN_NUMERIC); if (number_size >= width) return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); buffer_.reserve(width); unsigned fill_size = width - number_size; if (align != ALIGN_LEFT) { CharPtr p = grow_buffer(fill_size); std::fill(p, p + fill_size, fill); } CharPtr result = prepare_int_buffer( num_digits, subspec, prefix, prefix_size); if (align == ALIGN_LEFT) { CharPtr p = grow_buffer(fill_size); std::fill(p, p + fill_size, fill); } return result; } unsigned size = prefix_size + num_digits; if (width <= size) { CharPtr p = grow_buffer(size); std::copy(prefix, prefix + prefix_size, p); return p + size - 1; } CharPtr p = grow_buffer(width); CharPtr end = p + width; if (align == ALIGN_LEFT) { std::copy(prefix, prefix + prefix_size, p); p += size; std::fill(p, end, fill); } else if (align == ALIGN_CENTER) { p = fill_padding(p, width, size, fill); std::copy(prefix, prefix + prefix_size, p); p += size; } else { if (align == ALIGN_NUMERIC) { if (prefix_size != 0) { p = std::copy(prefix, prefix + prefix_size, p); size -= prefix_size; } } else { std::copy(prefix, prefix + prefix_size, end - size); } std::fill(p, end - size, fill); p = end; } return p - 1; } template template void BasicWriter::write_int(T value, Spec spec) { unsigned prefix_size = 0; typedef typename internal::IntTraits::MainType UnsignedType; UnsignedType abs_value = value; char prefix[4] = ""; if (internal::is_negative(value)) { prefix[0] = '-'; ++prefix_size; abs_value = 0 - abs_value; } else if (spec.flag(SIGN_FLAG)) { prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' '; ++prefix_size; } switch (spec.type()) { case 0: case 'd': { unsigned num_digits = internal::count_digits(abs_value); CharPtr p = prepare_int_buffer( num_digits, spec, prefix, prefix_size) + 1 - num_digits; internal::format_decimal(get(p), abs_value, num_digits); break; } case 'x': case 'X': { UnsignedType n = abs_value; if (spec.flag(HASH_FLAG)) { prefix[prefix_size++] = '0'; prefix[prefix_size++] = spec.type(); } unsigned num_digits = 0; do { ++num_digits; } while ((n >>= 4) != 0); Char *p = get(prepare_int_buffer( num_digits, spec, prefix, prefix_size)); n = abs_value; const char *digits = spec.type() == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; do { *p-- = digits[n & 0xf]; } while ((n >>= 4) != 0); break; } case 'b': case 'B': { UnsignedType n = abs_value; if (spec.flag(HASH_FLAG)) { prefix[prefix_size++] = '0'; prefix[prefix_size++] = spec.type(); } unsigned num_digits = 0; do { ++num_digits; } while ((n >>= 1) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = '0' + (n & 1); } while ((n >>= 1) != 0); break; } case 'o': { UnsignedType n = abs_value; if (spec.flag(HASH_FLAG)) prefix[prefix_size++] = '0'; unsigned num_digits = 0; do { ++num_digits; } while ((n >>= 3) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = '0' + (n & 7); } while ((n >>= 3) != 0); break; } default: internal::report_unknown_type( spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); break; } } template template void BasicWriter::write_double( T value, const FormatSpec &spec) { // Check type. char type = spec.type(); bool upper = false; switch (type) { case 0: type = 'g'; break; case 'e': case 'f': case 'g': case 'a': break; case 'F': #ifdef _MSC_VER // MSVC's printf doesn't support 'F'. type = 'f'; #endif // Fall through. case 'E': case 'G': case 'A': upper = true; break; default: internal::report_unknown_type(type, "double"); break; } char sign = 0; // Use getsign instead of value < 0 because the latter is always // false for NaN. if (internal::getsign(static_cast(value))) { sign = '-'; value = -value; } else if (spec.flag(SIGN_FLAG)) { sign = spec.flag(PLUS_FLAG) ? '+' : ' '; } if (value != value) { // Format NaN ourselves because sprintf's output is not consistent // across platforms. std::size_t nan_size = 4; const char *nan = upper ? " NAN" : " nan"; if (!sign) { --nan_size; ++nan; } CharPtr out = write_str(nan, nan_size, spec); if (sign) *out = sign; return; } if (internal::isinfinity(value)) { // Format infinity ourselves because sprintf's output is not consistent // across platforms. std::size_t inf_size = 4; const char *inf = upper ? " INF" : " inf"; if (!sign) { --inf_size; ++inf; } CharPtr out = write_str(inf, inf_size, spec); if (sign) *out = sign; return; } std::size_t offset = buffer_.size(); unsigned width = spec.width(); if (sign) { buffer_.reserve(buffer_.size() + (std::max)(width, 1u)); if (width > 0) --width; ++offset; } // Build format string. enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg Char format[MAX_FORMAT_SIZE]; Char *format_ptr = format; *format_ptr++ = '%'; unsigned width_for_sprintf = width; if (spec.flag(HASH_FLAG)) *format_ptr++ = '#'; if (spec.align() == ALIGN_CENTER) { width_for_sprintf = 0; } else { if (spec.align() == ALIGN_LEFT) *format_ptr++ = '-'; if (width != 0) *format_ptr++ = '*'; } if (spec.precision() >= 0) { *format_ptr++ = '.'; *format_ptr++ = '*'; } append_float_length(format_ptr, value); *format_ptr++ = type; *format_ptr = '\0'; // Format using snprintf. Char fill = static_cast(spec.fill()); for (;;) { std::size_t buffer_size = buffer_.capacity() - offset; #if _MSC_VER // MSVC's vsnprintf_s doesn't work with zero size, so reserve // space for at least one extra character to make the size non-zero. // Note that the buffer's capacity will increase by more than 1. if (buffer_size == 0) { buffer_.reserve(offset + 1); buffer_size = buffer_.capacity() - offset; } #endif Char *start = &buffer_[offset]; int n = internal::CharTraits::format_float( start, buffer_size, format, width_for_sprintf, spec.precision(), value); if (n >= 0 && offset + n < buffer_.capacity()) { if (sign) { if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || *start != ' ') { *(start - 1) = sign; sign = 0; } else { *(start - 1) = fill; } ++n; } if (spec.align() == ALIGN_CENTER && spec.width() > static_cast(n)) { width = spec.width(); CharPtr p = grow_buffer(width); std::copy(p, p + n, p + (width - n) / 2); fill_padding(p, spec.width(), n, fill); return; } if (spec.fill() != ' ' || sign) { while (*start == ' ') *start++ = fill; if (sign) *(start - 1) = sign; } grow_buffer(n); return; } // If n is negative we ask to increase the capacity by at least 1, // but as std::vector, the buffer grows exponentially. buffer_.reserve(n >= 0 ? offset + n + 1 : buffer_.capacity() + 1); } } /** \rst This class template provides operations for formatting and writing data into a character stream. The output is stored in a memory buffer that grows dynamically. You can use one of the following typedefs for common character types and the standard allocator: +---------------+-----------------------------------------------------+ | Type | Definition | +===============+=====================================================+ | MemoryWriter | BasicMemoryWriter> | +---------------+-----------------------------------------------------+ | WMemoryWriter | BasicMemoryWriter> | +---------------+-----------------------------------------------------+ **Example**:: MemoryWriter out; out << "The answer is " << 42 << "\n"; out.write("({:+f}, {:+f})", -3.14, 3.14); This will write the following output to the ``out`` object: .. code-block:: none The answer is 42 (-3.140000, +3.140000) The output can be converted to an ``std::string`` with ``out.str()`` or accessed as a C string with ``out.c_str()``. \endrst */ template > class BasicMemoryWriter : public BasicWriter { private: internal::MemoryBuffer buffer_; public: explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) : BasicWriter(buffer_), buffer_(alloc) {} #if FMT_USE_RVALUE_REFERENCES /** \rst Constructs a :class:`fmt::BasicMemoryWriter` object moving the content of the other object to it. \endrst */ BasicMemoryWriter(BasicMemoryWriter &&other) : BasicWriter(buffer_), buffer_(std::move(other.buffer_)) { } /** \rst Moves the content of the other ``BasicMemoryWriter`` object to this one. \endrst */ BasicMemoryWriter &operator=(BasicMemoryWriter &&other) { buffer_ = std::move(other.buffer_); return *this; } #endif }; typedef BasicMemoryWriter MemoryWriter; typedef BasicMemoryWriter WMemoryWriter; /** \rst This class template provides operations for formatting and writing data into a fixed-size array. For writing into a dynamically growing buffer use :class:`fmt::BasicMemoryWriter`. Any write method will throw ``std::runtime_error`` if the output doesn't fit into the array. You can use one of the following typedefs for common character types: +--------------+---------------------------+ | Type | Definition | +==============+===========================+ | ArrayWriter | BasicArrayWriter | +--------------+---------------------------+ | WArrayWriter | BasicArrayWriter | +--------------+---------------------------+ \endrst */ template class BasicArrayWriter : public BasicWriter { private: internal::FixedBuffer buffer_; public: /** \rst Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the given size. \endrst */ BasicArrayWriter(Char *array, std::size_t size) : BasicWriter(buffer_), buffer_(array, size) {} // FIXME: this is temporary undocumented due to a bug in Sphinx /* \rst Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the size known at compile time. \endrst */ template explicit BasicArrayWriter(Char (&array)[SIZE]) : BasicWriter(buffer_), buffer_(array, SIZE) {} }; typedef BasicArrayWriter ArrayWriter; typedef BasicArrayWriter WArrayWriter; // Formats a value. template void format(BasicFormatter &f, const Char *&format_str, const T &value) { std::basic_ostringstream os; os << value; internal::Arg arg; internal::Value &arg_value = arg; std::basic_string str = os.str(); arg_value = internal::MakeValue(str); arg.type = static_cast( internal::MakeValue::type(str)); format_str = f.format(format_str, arg); } // Reports a system error without throwing an exception. // Can be used to report errors from destructors. void report_system_error(int error_code, StringRef message) FMT_NOEXCEPT; #ifdef _WIN32 /** A Windows error. */ class WindowsError : public SystemError { private: void init(int error_code, StringRef format_str, ArgList args); public: /** \rst Constructs a :class:`fmt::WindowsError` object with the description of the form .. parsed-literal:: **: ** where ** is the formatted message and ** is the system message corresponding to the error code. *error_code* is a Windows error code as given by ``GetLastError``. If *error_code* is not a valid error code such as -1, the system message will look like "error -1". **Example**:: // This throws a WindowsError with the description // cannot open file 'madeup': The system cannot find the file specified. // or similar (system message may vary). const char *filename = "madeup"; LPOFSTRUCT of = LPOFSTRUCT(); HFILE file = OpenFile(filename, &of, OF_READ); if (file == HFILE_ERROR) { throw fmt::WindowsError(GetLastError(), "cannot open file '{}'", filename); } \endrst */ WindowsError(int error_code, StringRef message) { init(error_code, message, ArgList()); } FMT_VARIADIC_CTOR(WindowsError, init, int, StringRef) }; // Reports a Windows error without throwing an exception. // Can be used to report errors from destructors. void report_windows_error(int error_code, StringRef message) FMT_NOEXCEPT; #endif enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; /** Formats a string and prints it to stdout using ANSI escape sequences to specify color (experimental). Example: PrintColored(fmt::RED, "Elapsed time: {0:.2f} seconds") << 1.23; */ void print_colored(Color c, StringRef format, ArgList args); /** \rst Formats arguments and returns the result as a string. **Example**:: std::string message = format("The answer is {}", 42); \endrst */ inline std::string format(StringRef format_str, ArgList args) { MemoryWriter w; w.write(format_str, args); return w.str(); } inline std::wstring format(WStringRef format_str, ArgList args) { WMemoryWriter w; w.write(format_str, args); return w.str(); } /** \rst Prints formatted data to the file *f*. **Example**:: print(stderr, "Don't {}!", "panic"); \endrst */ void print(std::FILE *f, StringRef format_str, ArgList args); /** \rst Prints formatted data to ``stdout``. **Example**:: print("Elapsed time: {0:.2f} seconds", 1.23); \endrst */ void print(StringRef format_str, ArgList args); /** \rst Prints formatted data to the stream *os*. **Example**:: print(cerr, "Don't {}!", "panic"); \endrst */ void print(std::ostream &os, StringRef format_str, ArgList args); template void printf(BasicWriter &w, BasicStringRef format, ArgList args) { internal::PrintfFormatter().format(w, format, args); } /** \rst Formats arguments and returns the result as a string. **Example**:: std::string message = fmt::sprintf("The answer is %d", 42); \endrst */ inline std::string sprintf(StringRef format, ArgList args) { MemoryWriter w; printf(w, format, args); return w.str(); } /** \rst Prints formatted data to the file *f*. **Example**:: fmt::fprintf(stderr, "Don't %s!", "panic"); \endrst */ int fprintf(std::FILE *f, StringRef format, ArgList args); /** \rst Prints formatted data to ``stdout``. **Example**:: fmt::printf("Elapsed time: %.2f seconds", 1.23); \endrst */ inline int printf(StringRef format, ArgList args) { return fprintf(stdout, format, args); } /** Fast integer formatter. */ class FormatInt { private: // Buffer should be large enough to hold all digits (digits10 + 1), // a sign and a null character. enum {BUFFER_SIZE = std::numeric_limits::digits10 + 3}; mutable char buffer_[BUFFER_SIZE]; char *str_; // Formats value in reverse and returns the number of digits. char *format_decimal(ULongLong value) { char *buffer_end = buffer_ + BUFFER_SIZE - 1; while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. unsigned index = (value % 100) * 2; value /= 100; *--buffer_end = internal::Data::DIGITS[index + 1]; *--buffer_end = internal::Data::DIGITS[index]; } if (value < 10) { *--buffer_end = static_cast('0' + value); return buffer_end; } unsigned index = static_cast(value * 2); *--buffer_end = internal::Data::DIGITS[index + 1]; *--buffer_end = internal::Data::DIGITS[index]; return buffer_end; } void FormatSigned(LongLong value) { ULongLong abs_value = static_cast(value); bool negative = value < 0; if (negative) abs_value = 0 - abs_value; str_ = format_decimal(abs_value); if (negative) *--str_ = '-'; } public: explicit FormatInt(int value) { FormatSigned(value); } explicit FormatInt(long value) { FormatSigned(value); } explicit FormatInt(LongLong value) { FormatSigned(value); } explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {} explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} /** Returns the number of characters written to the output buffer. */ std::size_t size() const { return buffer_ - str_ + BUFFER_SIZE - 1; } /** Returns a pointer to the output buffer content. No terminating null character is appended. */ const char *data() const { return str_; } /** Returns a pointer to the output buffer content with terminating null character appended. */ const char *c_str() const { buffer_[BUFFER_SIZE - 1] = '\0'; return str_; } /** Returns the content of the output buffer as an `std::string`. */ std::string str() const { return std::string(str_, size()); } }; // Formats a decimal integer value writing into buffer and returns // a pointer to the end of the formatted string. This function doesn't // write a terminating null character. template inline void format_decimal(char *&buffer, T value) { typename internal::IntTraits::MainType abs_value = value; if (internal::is_negative(value)) { *buffer++ = '-'; abs_value = 0 - abs_value; } if (abs_value < 100) { if (abs_value < 10) { *buffer++ = static_cast('0' + abs_value); return; } unsigned index = static_cast(abs_value * 2); *buffer++ = internal::Data::DIGITS[index]; *buffer++ = internal::Data::DIGITS[index + 1]; return; } unsigned num_digits = internal::count_digits(abs_value); internal::format_decimal(buffer, abs_value, num_digits); buffer += num_digits; } } #if FMT_GCC_VERSION // Use the system_header pragma to suppress warnings about variadic macros // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't // work. It is used at the end because we want to suppress as little warnings // as possible. # pragma GCC system_header #endif // This is used to work around VC++ bugs in handling variadic macros. #define FMT_EXPAND(args) args // Returns the number of arguments. // Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s. #define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N()) #define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__)) #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 #define FMT_CONCAT(a, b) a##b #define FMT_FOR_EACH_(N, f, ...) \ FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) #define FMT_FOR_EACH(f, ...) \ FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) #define FMT_ADD_ARG_NAME(type, index) type arg##index #define FMT_GET_ARG_NAME(type, index) arg##index #if FMT_USE_VARIADIC_TEMPLATES # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ template \ ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ const Args & ... args) { \ using fmt::internal::Value; \ const Value values[fmt::internal::NonZero::VALUE] = { \ fmt::internal::MakeValue(args)... \ }; \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ fmt::internal::make_type(args...), values)); \ } #else // Defines a wrapper for a function taking __VA_ARGS__ arguments // and n additional arguments of arbitrary types. # define FMT_WRAP(Char, ReturnType, func, call, n, ...) \ template \ inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ FMT_GEN(n, FMT_MAKE_ARG)) { \ const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF_##Char)}; \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \ } # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ } \ FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__) #endif // FMT_USE_VARIADIC_TEMPLATES /** \rst Defines a variadic function with the specified return type, function name and argument types passed as variable arguments to this macro. **Example**:: void print_error(const char *file, int line, const char *format, fmt::ArgList args) { fmt::print("{}: {}: ", file, line); fmt::print(format, args); } FMT_VARIADIC(void, print_error, const char *, int, const char *) ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that don't implement variadic templates. You don't have to use this macro if you don't need legacy compiler support and can use variadic templates directly:: template void print_error(const char *file, int line, const char *format, const Args & ... args) { fmt::print("{}: {}: ", file, line); fmt::print(format, args...); } \endrst */ #define FMT_VARIADIC(ReturnType, func, ...) \ FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__) #define FMT_VARIADIC_W(ReturnType, func, ...) \ FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__) namespace fmt { FMT_VARIADIC(std::string, format, StringRef) FMT_VARIADIC_W(std::wstring, format, WStringRef) FMT_VARIADIC(void, print, StringRef) FMT_VARIADIC(void, print, std::FILE *, StringRef) FMT_VARIADIC(void, print, std::ostream &, StringRef) FMT_VARIADIC(void, print_colored, Color, StringRef) FMT_VARIADIC(std::string, sprintf, StringRef) FMT_VARIADIC(int, printf, StringRef) FMT_VARIADIC(int, fprintf, std::FILE *, StringRef) } // Restore warnings. #if FMT_GCC_VERSION >= 406 # pragma GCC diagnostic pop #endif #ifdef __clang__ # pragma clang diagnostic pop #endif #ifdef FMT_HEADER_ONLY # include "format.cc" #endif #endif // FMT_FORMAT_H_ cppformat-1.1.0/posix.cc000066400000000000000000000163451247635332500152000ustar00rootroot00000000000000/* A C++ interface to POSIX functions. Copyright (c) 2014 - 2015, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Disable bogus MSVC warnings. #ifndef _CRT_SECURE_NO_WARNINGS # define _CRT_SECURE_NO_WARNINGS #endif #include "posix.h" #include #include #include #ifndef _WIN32 # include #else # include # include # define O_CREAT _O_CREAT # define O_TRUNC _O_TRUNC #ifndef S_IRUSR # define S_IRUSR _S_IREAD #endif #ifndef S_IWUSR # define S_IWUSR _S_IWRITE #endif # ifdef __MINGW32__ # define _SH_DENYNO 0x40 # endif #endif // _WIN32 namespace { #ifdef _WIN32 // Return type of read and write functions. typedef int RWResult; // On Windows the count argument to read and write is unsigned, so convert // it from size_t preventing integer overflow. inline unsigned convert_rwcount(std::size_t count) { return count <= UINT_MAX ? static_cast(count) : UINT_MAX; } #else // Return type of read and write functions. typedef ssize_t RWResult; inline std::size_t convert_rwcount(std::size_t count) { return count; } #endif } fmt::BufferedFile::~BufferedFile() FMT_NOEXCEPT { if (file_ && FMT_SYSTEM(fclose(file_)) != 0) fmt::report_system_error(errno, "cannot close file"); } fmt::BufferedFile::BufferedFile(fmt::StringRef filename, fmt::StringRef mode) { FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), 0); if (!file_) throw SystemError(errno, "cannot open file {}", filename); } void fmt::BufferedFile::close() { if (!file_) return; int result = FMT_SYSTEM(fclose(file_)); file_ = 0; if (result != 0) throw SystemError(errno, "cannot close file"); } int fmt::BufferedFile::fileno() const { int fd = FMT_POSIX_CALL(fileno(file_)); if (fd == -1) throw SystemError(errno, "cannot get file descriptor"); return fd; } fmt::File::File(fmt::StringRef path, int oflag) { int mode = S_IRUSR | S_IWUSR; #ifdef _WIN32 fd_ = -1; FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode)); #else FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode))); #endif if (fd_ == -1) throw SystemError(errno, "cannot open file {}", path); } fmt::File::~File() FMT_NOEXCEPT { // Don't retry close in case of EINTR! // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0) fmt::report_system_error(errno, "cannot close file"); } void fmt::File::close() { if (fd_ == -1) return; // Don't retry close in case of EINTR! // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html int result = FMT_POSIX_CALL(close(fd_)); fd_ = -1; if (result != 0) throw SystemError(errno, "cannot close file"); } fmt::LongLong fmt::File::size() const { #ifdef _WIN32 LARGE_INTEGER filesize = {}; HANDLE handle = reinterpret_cast(_get_osfhandle(fd_)); if (!FMT_SYSTEM(GetFileSizeEx(handle, &filesize))) throw WindowsError(GetLastError(), "cannot get file size"); FMT_STATIC_ASSERT(sizeof(fmt::LongLong) >= sizeof(filesize.QuadPart), "return type of File::size is not large enough"); return filesize.QuadPart; #else typedef struct stat Stat; Stat file_stat = Stat(); if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1) throw SystemError(errno, "cannot get file attributes"); FMT_STATIC_ASSERT(sizeof(fmt::LongLong) >= sizeof(file_stat.st_size), "return type of File::size is not large enough"); return file_stat.st_size; #endif } std::size_t fmt::File::read(void *buffer, std::size_t count) { RWResult result = 0; FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); if (result < 0) throw SystemError(errno, "cannot read from file"); return result; } std::size_t fmt::File::write(const void *buffer, std::size_t count) { RWResult result = 0; FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count)))); if (result < 0) throw SystemError(errno, "cannot write to file"); return result; } fmt::File fmt::File::dup(int fd) { // Don't retry as dup doesn't return EINTR. // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html int new_fd = FMT_POSIX_CALL(dup(fd)); if (new_fd == -1) throw SystemError(errno, "cannot duplicate file descriptor {}", fd); return File(new_fd); } void fmt::File::dup2(int fd) { int result = 0; FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); if (result == -1) { throw SystemError(errno, "cannot duplicate file descriptor {} to {}", fd_, fd); } } void fmt::File::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT { int result = 0; FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); if (result == -1) ec = ErrorCode(errno); } void fmt::File::pipe(File &read_end, File &write_end) { // Close the descriptors first to make sure that assignments don't throw // and there are no leaks. read_end.close(); write_end.close(); int fds[2] = {}; #ifdef _WIN32 // Make the default pipe capacity same as on Linux 2.6.11+. enum { DEFAULT_CAPACITY = 65536 }; int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); #else // Don't retry as the pipe function doesn't return EINTR. // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html int result = FMT_POSIX_CALL(pipe(fds)); #endif if (result != 0) throw SystemError(errno, "cannot create pipe"); // The following assignments don't throw because read_fd and write_fd // are closed. read_end = File(fds[0]); write_end = File(fds[1]); } fmt::BufferedFile fmt::File::fdopen(const char *mode) { // Don't retry as fdopen doesn't return EINTR. FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode)); if (!f) throw SystemError(errno, "cannot associate stream with file descriptor"); BufferedFile file(f); fd_ = -1; return file; } long fmt::getpagesize() { #ifdef _WIN32 SYSTEM_INFO si; GetSystemInfo(&si); return si.dwPageSize; #else long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); if (size < 0) throw SystemError(errno, "cannot get memory page size"); return size; #endif } cppformat-1.1.0/posix.h000066400000000000000000000221551247635332500150360ustar00rootroot00000000000000/* A C++ interface to POSIX functions. Copyright (c) 2014 - 2015, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FMT_POSIX_H_ #define FMT_POSIX_H_ #include #include // for O_RDONLY #include #include #include "format.h" #ifdef FMT_INCLUDE_POSIX_TEST # include "test/posix-test.h" #endif #ifndef FMT_POSIX # ifdef _WIN32 // Fix warnings about deprecated symbols. # define FMT_POSIX(call) _##call # else # define FMT_POSIX(call) call # endif #endif // Calls to system functions are wrapped in FMT_SYSTEM for testability. #ifdef FMT_SYSTEM # define FMT_POSIX_CALL(call) FMT_SYSTEM(call) #else # define FMT_SYSTEM(call) call # ifdef _WIN32 // Fix warnings about deprecated symbols. # define FMT_POSIX_CALL(call) ::_##call # else # define FMT_POSIX_CALL(call) ::call # endif #endif #if FMT_GCC_VERSION >= 407 # define FMT_UNUSED __attribute__((unused)) #else # define FMT_UNUSED #endif #if FMT_USE_STATIC_ASSERT || FMT_HAS_CPP_ATTRIBUTE(cxx_static_assert) || \ (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600 # define FMT_STATIC_ASSERT(cond, message) static_assert(cond, message) #else # define FMT_CONCAT_(a, b) FMT_CONCAT(a, b) # define FMT_STATIC_ASSERT(cond, message) \ typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED #endif // Retries the expression while it evaluates to error_result and errno // equals to EINTR. #ifndef _WIN32 # define FMT_RETRY_VAL(result, expression, error_result) \ do { \ result = (expression); \ } while (result == error_result && errno == EINTR) #else # define FMT_RETRY_VAL(result, expression, error_result) result = (expression) #endif #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) namespace fmt { // An error code. class ErrorCode { private: int value_; public: explicit ErrorCode(int value = 0) FMT_NOEXCEPT : value_(value) {} int get() const FMT_NOEXCEPT { return value_; } }; // A buffered file. class BufferedFile { private: FILE *file_; friend class File; explicit BufferedFile(FILE *f) : file_(f) {} public: // Constructs a BufferedFile object which doesn't represent any file. BufferedFile() FMT_NOEXCEPT : file_(0) {} // Destroys the object closing the file it represents if any. ~BufferedFile() FMT_NOEXCEPT; #if !FMT_USE_RVALUE_REFERENCES // Emulate a move constructor and a move assignment operator if rvalue // references are not supported. private: // A proxy object to emulate a move constructor. // It is private to make it impossible call operator Proxy directly. struct Proxy { FILE *file; }; public: // A "move constructor" for moving from a temporary. BufferedFile(Proxy p) FMT_NOEXCEPT : file_(p.file) {} // A "move constructor" for for moving from an lvalue. BufferedFile(BufferedFile &f) FMT_NOEXCEPT : file_(f.file_) { f.file_ = 0; } // A "move assignment operator" for moving from a temporary. BufferedFile &operator=(Proxy p) { close(); file_ = p.file; return *this; } // A "move assignment operator" for moving from an lvalue. BufferedFile &operator=(BufferedFile &other) { close(); file_ = other.file_; other.file_ = 0; return *this; } // Returns a proxy object for moving from a temporary: // BufferedFile file = BufferedFile(...); operator Proxy() FMT_NOEXCEPT { Proxy p = {file_}; file_ = 0; return p; } #else private: FMT_DISALLOW_COPY_AND_ASSIGN(BufferedFile); public: BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : file_(other.file_) { other.file_ = 0; } BufferedFile& operator=(BufferedFile &&other) { close(); file_ = other.file_; other.file_ = 0; return *this; } #endif // Opens a file. BufferedFile(fmt::StringRef filename, fmt::StringRef mode); // Closes the file. void close(); // Returns the pointer to a FILE object representing this file. FILE *get() const FMT_NOEXCEPT { return file_; } int fileno() const; void print(fmt::StringRef format_str, const ArgList &args) { fmt::print(file_, format_str, args); } FMT_VARIADIC(void, print, fmt::StringRef) }; // A file. Closed file is represented by a File object with descriptor -1. // Methods that are not declared with FMT_NOEXCEPT may throw // fmt::SystemError in case of failure. Note that some errors such as // closing the file multiple times will cause a crash on Windows rather // than an exception. You can get standard behavior by overriding the // invalid parameter handler with _set_invalid_parameter_handler. class File { private: int fd_; // File descriptor. // Constructs a File object with a given descriptor. explicit File(int fd) : fd_(fd) {} public: // Possible values for the oflag argument to the constructor. enum { RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. }; // Constructs a File object which doesn't represent any file. File() FMT_NOEXCEPT : fd_(-1) {} // Opens a file and constructs a File object representing this file. File(fmt::StringRef path, int oflag); #if !FMT_USE_RVALUE_REFERENCES // Emulate a move constructor and a move assignment operator if rvalue // references are not supported. private: // A proxy object to emulate a move constructor. // It is private to make it impossible call operator Proxy directly. struct Proxy { int fd; }; public: // A "move constructor" for moving from a temporary. File(Proxy p) FMT_NOEXCEPT : fd_(p.fd) {} // A "move constructor" for for moving from an lvalue. File(File &other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } // A "move assignment operator" for moving from a temporary. File &operator=(Proxy p) { close(); fd_ = p.fd; return *this; } // A "move assignment operator" for moving from an lvalue. File &operator=(File &other) { close(); fd_ = other.fd_; other.fd_ = -1; return *this; } // Returns a proxy object for moving from a temporary: // File file = File(...); operator Proxy() FMT_NOEXCEPT { Proxy p = {fd_}; fd_ = -1; return p; } #else private: FMT_DISALLOW_COPY_AND_ASSIGN(File); public: File(File &&other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } File& operator=(File &&other) { close(); fd_ = other.fd_; other.fd_ = -1; return *this; } #endif // Destroys the object closing the file it represents if any. ~File() FMT_NOEXCEPT; // Returns the file descriptor. int descriptor() const FMT_NOEXCEPT { return fd_; } // Closes the file. void close(); // Returns the file size. fmt::LongLong size() const; // Attempts to read count bytes from the file into the specified buffer. std::size_t read(void *buffer, std::size_t count); // Attempts to write count bytes from the specified buffer to the file. std::size_t write(const void *buffer, std::size_t count); // Duplicates a file descriptor with the dup function and returns // the duplicate as a file object. static File dup(int fd); // Makes fd be the copy of this file descriptor, closing fd first if // necessary. void dup2(int fd); // Makes fd be the copy of this file descriptor, closing fd first if // necessary. void dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT; // Creates a pipe setting up read_end and write_end file objects for reading // and writing respectively. static void pipe(File &read_end, File &write_end); // Creates a BufferedFile object associated with this file and detaches // this File object from the file. BufferedFile fdopen(const char *mode); }; // Returns the memory page size. long getpagesize(); } // namespace fmt #if !FMT_USE_RVALUE_REFERENCES namespace std { // For compatibility with C++98. inline fmt::BufferedFile &move(fmt::BufferedFile &f) { return f; } inline fmt::File &move(fmt::File &f) { return f; } } #endif #endif // FMT_POSIX_H_ cppformat-1.1.0/test/000077500000000000000000000000001247635332500144755ustar00rootroot00000000000000cppformat-1.1.0/test/CMakeLists.txt000066400000000000000000000054151247635332500172420ustar00rootroot00000000000000set(TEST_MAIN_SRC test-main.cc gtest-extra.cc gtest-extra.h util.cc) add_library(test-main STATIC ${TEST_MAIN_SRC}) target_link_libraries(test-main format gmock) # Adds a test. # Usage: add_fmt_test(name [CUSTOM_LINK] srcs...) function(add_fmt_test name) cmake_parse_arguments(add_fmt_test CUSTOM_LINK "" "" ${ARGN}) add_executable(${name} ${name}.cc ${add_fmt_test_UNPARSED_ARGUMENTS}) target_link_libraries(${name} test-main) if (NOT add_fmt_test_CUSTOM_LINK) target_link_libraries(${name} format) endif () add_test(NAME ${name} COMMAND ${name}) endfunction() add_fmt_test(gtest-extra-test) add_fmt_test(format-test) add_fmt_test(format-impl-test CUSTOM_LINK) add_fmt_test(printf-test) foreach (target format-test printf-test) if (CMAKE_COMPILER_IS_GNUCXX) set_target_properties(${target} PROPERTIES COMPILE_FLAGS "-Wall -Wextra -pedantic -Wno-long-long -Wno-variadic-macros") endif () if (CPP11_FLAG) set_target_properties(${target} PROPERTIES COMPILE_FLAGS ${CPP11_FLAG}) endif () endforeach () add_fmt_test(util-test mock-allocator.h) if (CPP11_FLAG) set_target_properties(util-test PROPERTIES COMPILE_FLAGS ${CPP11_FLAG}) endif () foreach (src ${FMT_SOURCES}) set(FMT_TEST_SOURCES ${FMT_TEST_SOURCES} ../${src}) endforeach () check_cxx_source_compiles(" #include class C { void operator=(const C&); }; int main() { static_assert(!std::is_copy_assignable::value, \"\"); }" HAVE_TYPE_TRAITS) if (HAVE_TYPE_TRAITS) add_definitions(-DFMT_USE_TYPE_TRAITS=1) endif () add_executable(macro-test macro-test.cc ${FMT_TEST_SOURCES} ${TEST_MAIN_SRC}) set_target_properties(macro-test PROPERTIES COMPILE_DEFINITIONS "FMT_USE_VARIADIC_TEMPLATES=0") target_link_libraries(macro-test gmock) if (HAVE_OPEN) add_executable(posix-test posix-test.cc ${FMT_TEST_SOURCES} ${TEST_MAIN_SRC}) set_target_properties(posix-test PROPERTIES COMPILE_DEFINITIONS "FMT_INCLUDE_POSIX_TEST=1") target_link_libraries(posix-test gmock) add_test(NAME posix-test COMMAND posix-test) endif () add_executable(header-only-test header-only-test.cc header-only-test2.cc test-main.cc) set_target_properties(header-only-test PROPERTIES COMPILE_DEFINITIONS "FMT_HEADER_ONLY=1") target_link_libraries(header-only-test gmock) # Test that the library can be compiled with exceptions disabled. check_cxx_compiler_flag(-fno-exceptions HAVE_FNO_EXCEPTIONS_FLAG) if (HAVE_FNO_EXCEPTIONS_FLAG) add_library(noexception-test STATIC ../format.cc) set_target_properties(noexception-test PROPERTIES COMPILE_FLAGS -fno-exceptions) endif () add_test(compile-test ${CMAKE_CTEST_COMMAND} --build-and-test "${CMAKE_CURRENT_SOURCE_DIR}/compile-test" "${CMAKE_CURRENT_BINARY_DIR}/compile-test" --build-generator ${CMAKE_GENERATOR} --build-makeprogram ${CMAKE_MAKE_PROGRAM}) cppformat-1.1.0/test/compile-test/000077500000000000000000000000001247635332500171025ustar00rootroot00000000000000cppformat-1.1.0/test/compile-test/CMakeLists.txt000066400000000000000000000027271247635332500216520ustar00rootroot00000000000000# Test if compile errors are produced where necessary. cmake_minimum_required(VERSION 2.8) include(CheckCXXSourceCompiles) set(CMAKE_REQUIRED_INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/../..) function (expect_compile_error code) check_cxx_source_compiles(" #include \"format.cc\" #include \"posix.h\" int main() { ${code} } " compiles) set (does_compile ${compiles}) # Unset the CMake cache variable compiles. Otherwise the compile test will # just use cached information next time it runs. unset(compiles CACHE) if (does_compile) message(FATAL_ERROR "No compile error for: ${code}") endif () endfunction () # MakeArg doesn't accept [const] volatile char *. expect_compile_error("volatile char s[] = \"test\"; (fmt::internal::MakeArg)(s);") expect_compile_error("const volatile char s[] = \"test\"; (fmt::internal::MakeArg)(s);") # MakeArg doesn't accept wchar_t. expect_compile_error("fmt::internal::MakeValue(L'a');") expect_compile_error("fmt::internal::MakeValue(L\"test\");") # Writing a wide character to a character stream Writer is forbidden. expect_compile_error("fmt::MemoryWriter() << L'a';") expect_compile_error("fmt::MemoryWriter() << fmt::pad(\"abc\", 5, L' ');") expect_compile_error("fmt::MemoryWriter() << fmt::pad(42, 5, L' ');") # Formatting a wide character with a narrow format string is forbidden. expect_compile_error("fmt::format(\"{}\", L'a';") expect_compile_error("FMT_STATIC_ASSERT(0 > 1, \"oops\");") cppformat-1.1.0/test/format-impl-test.cc000066400000000000000000000075041247635332500202160ustar00rootroot00000000000000/* Formatting library implementation tests. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Include format.cc instead of format.h to test implementation-specific stuff. #include "format.cc" #include #include "gtest-extra.h" #include "util.h" #undef max TEST(FormatTest, ArgConverter) { using fmt::internal::Arg; Arg arg = Arg(); arg.type = Arg::LONG_LONG; arg.long_long_value = std::numeric_limits::max(); ArgConverter(arg, 'd').visit(arg); EXPECT_EQ(Arg::LONG_LONG, arg.type); } TEST(FormatTest, FormatNegativeNaN) { double nan = std::numeric_limits::quiet_NaN(); if (fmt::internal::getsign(-nan)) EXPECT_EQ("-nan", fmt::format("{}", -nan)); else fmt::print("Warning: compiler doesn't handle negative NaN correctly"); } TEST(FormatTest, StrError) { char *message = 0; char buffer[BUFFER_SIZE]; #ifndef NDEBUG EXPECT_DEBUG_DEATH(safe_strerror(EDOM, message = 0, 0), "Assertion"); EXPECT_DEBUG_DEATH(safe_strerror(EDOM, message = buffer, 0), "Assertion"); #endif buffer[0] = 'x'; #ifdef _GNU_SOURCE // Use invalid error code to make sure that safe_strerror returns an error // message in the buffer rather than a pointer to a static string. int error_code = -1; #else int error_code = EDOM; #endif int result = safe_strerror(error_code, message = buffer, BUFFER_SIZE); EXPECT_EQ(0, result); std::size_t message_size = std::strlen(message); EXPECT_GE(BUFFER_SIZE - 1u, message_size); EXPECT_EQ(get_system_error(error_code), message); // safe_strerror never uses buffer on MinGW. #ifndef __MINGW32__ result = safe_strerror(error_code, message = buffer, message_size); EXPECT_EQ(ERANGE, result); result = safe_strerror(error_code, message = buffer, 1); EXPECT_EQ(buffer, message); // Message should point to buffer. EXPECT_EQ(ERANGE, result); EXPECT_STREQ("", message); #endif } TEST(FormatTest, FormatErrorCode) { std::string msg = "error 42", sep = ": "; { fmt::MemoryWriter w; w << "garbage"; format_error_code(w, 42, "test"); EXPECT_EQ("test: " + msg, w.str()); } { fmt::MemoryWriter w; std::string prefix( fmt::internal::INLINE_BUFFER_SIZE - msg.size() - sep.size() + 1, 'x'); format_error_code(w, 42, prefix); EXPECT_EQ(msg, w.str()); } { fmt::MemoryWriter w; std::string prefix( fmt::internal::INLINE_BUFFER_SIZE - msg.size() - sep.size(), 'x'); format_error_code(w, 42, prefix); EXPECT_EQ(prefix + sep + msg, w.str()); std::size_t size = fmt::internal::INLINE_BUFFER_SIZE; EXPECT_EQ(size, w.size()); } } cppformat-1.1.0/test/format-test.cc000066400000000000000000001506741247635332500172660ustar00rootroot00000000000000/* Formatting library tests. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #if FMT_USE_TYPE_TRAITS # include #endif #include "gmock/gmock.h" #include "format.h" #include "util.h" #include "mock-allocator.h" #include "gtest-extra.h" #if defined(_WIN32) && !defined(__MINGW32__) // Fix MSVC warning about "unsafe" fopen. FILE *safe_fopen(const char *filename, const char *mode) { FILE *f = 0; errno = fopen_s(&f, filename, mode); return f; } #define fopen safe_fopen #endif #undef min #undef max using std::size_t; using fmt::BasicWriter; using fmt::format; using fmt::FormatError; using fmt::StringRef; using fmt::MemoryWriter; using fmt::WMemoryWriter; using fmt::pad; namespace { // Checks if writing value to BasicWriter produces the same result // as writing it to std::basic_ostringstream. template ::testing::AssertionResult check_write(const T &value, const char *type) { std::basic_ostringstream os; os << value; std::basic_string expected = os.str(); std::basic_string actual = (fmt::BasicMemoryWriter() << value).str(); if (expected == actual) return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "Value of: (Writer<" << type << ">() << value).str()\n" << " Actual: " << actual << "\n" << "Expected: " << expected << "\n"; } struct AnyWriteChecker { template ::testing::AssertionResult operator()(const char *, const T &value) const { ::testing::AssertionResult result = check_write(value, "char"); return result ? check_write(value, "wchar_t") : result; } }; template struct WriteChecker { template ::testing::AssertionResult operator()(const char *, const T &value) const { return check_write(value, "char"); } }; // Checks if writing value to BasicWriter produces the same result // as writing it to std::ostringstream both for char and wchar_t. #define CHECK_WRITE(value) EXPECT_PRED_FORMAT1(AnyWriteChecker(), value) #define CHECK_WRITE_CHAR(value) \ EXPECT_PRED_FORMAT1(WriteChecker(), value) #define CHECK_WRITE_WCHAR(value) \ EXPECT_PRED_FORMAT1(WriteChecker(), value) } // namespace class TestString { private: std::string value_; public: explicit TestString(const char *value = "") : value_(value) {} friend std::ostream &operator<<(std::ostream &os, const TestString &s) { os << s.value_; return os; } }; #if FMT_USE_TYPE_TRAITS TEST(WriterTest, NotCopyConstructible) { EXPECT_FALSE(std::is_copy_constructible >::value); } TEST(WriterTest, NotCopyAssignable) { EXPECT_FALSE(std::is_copy_assignable >::value); } #endif TEST(WriterTest, Ctor) { MemoryWriter w; EXPECT_EQ(0u, w.size()); EXPECT_STREQ("", w.c_str()); EXPECT_EQ("", w.str()); } #if FMT_USE_RVALUE_REFERENCES void check_move_writer(const std::string &str, MemoryWriter &w) { MemoryWriter w2(std::move(w)); // Move shouldn't destroy the inline content of the first writer. EXPECT_EQ(str, w.str()); EXPECT_EQ(str, w2.str()); } TEST(WriterTest, MoveCtor) { MemoryWriter w; w << "test"; check_move_writer("test", w); // This fills the inline buffer, but doesn't cause dynamic allocation. std::string s; for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE; ++i) s += '*'; w.clear(); w << s; check_move_writer(s, w); const char *inline_buffer_ptr = w.data(); // Adding one more character causes the content to move from the inline to // a dynamically allocated buffer. w << '*'; MemoryWriter w2(std::move(w)); // Move should rip the guts of the first writer. EXPECT_EQ(inline_buffer_ptr, w.data()); EXPECT_EQ(s + '*', w2.str()); } void CheckMoveAssignWriter(const std::string &str, MemoryWriter &w) { MemoryWriter w2; w2 = std::move(w); // Move shouldn't destroy the inline content of the first writer. EXPECT_EQ(str, w.str()); EXPECT_EQ(str, w2.str()); } TEST(WriterTest, MoveAssignment) { MemoryWriter w; w << "test"; CheckMoveAssignWriter("test", w); // This fills the inline buffer, but doesn't cause dynamic allocation. std::string s; for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE; ++i) s += '*'; w.clear(); w << s; CheckMoveAssignWriter(s, w); const char *inline_buffer_ptr = w.data(); // Adding one more character causes the content to move from the inline to // a dynamically allocated buffer. w << '*'; MemoryWriter w2; w2 = std::move(w); // Move should rip the guts of the first writer. EXPECT_EQ(inline_buffer_ptr, w.data()); EXPECT_EQ(s + '*', w2.str()); } #endif // FMT_USE_RVALUE_REFERENCES TEST(WriterTest, Allocator) { typedef testing::StrictMock< MockAllocator > MockAllocator; typedef AllocatorRef TestAllocator; MockAllocator alloc; fmt::BasicMemoryWriter w((TestAllocator(&alloc))); std::size_t size = static_cast(1.5 * fmt::internal::INLINE_BUFFER_SIZE); std::vector mem(size); EXPECT_CALL(alloc, allocate(size)).WillOnce(testing::Return(&mem[0])); for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE + 1; ++i) w << '*'; EXPECT_CALL(alloc, deallocate(&mem[0], size)); } TEST(WriterTest, Data) { MemoryWriter w; w << 42; EXPECT_EQ("42", std::string(w.data(), w.size())); } TEST(WriterTest, WriteWithoutArgs) { MemoryWriter w; w.write("test"); EXPECT_EQ("test", std::string(w.data(), w.size())); } TEST(WriterTest, WriteInt) { CHECK_WRITE(42); CHECK_WRITE(-42); CHECK_WRITE(static_cast(12)); CHECK_WRITE(34u); CHECK_WRITE(std::numeric_limits::min()); CHECK_WRITE(std::numeric_limits::max()); CHECK_WRITE(std::numeric_limits::max()); } TEST(WriterTest, WriteLong) { CHECK_WRITE(56l); CHECK_WRITE(78ul); CHECK_WRITE(std::numeric_limits::min()); CHECK_WRITE(std::numeric_limits::max()); CHECK_WRITE(std::numeric_limits::max()); } TEST(WriterTest, WriteLongLong) { CHECK_WRITE(56ll); CHECK_WRITE(78ull); CHECK_WRITE(std::numeric_limits::min()); CHECK_WRITE(std::numeric_limits::max()); CHECK_WRITE(std::numeric_limits::max()); } TEST(WriterTest, WriteDouble) { CHECK_WRITE(4.2); CHECK_WRITE(-4.2); CHECK_WRITE(std::numeric_limits::min()); CHECK_WRITE(std::numeric_limits::max()); } TEST(WriterTest, WriteLongDouble) { CHECK_WRITE(4.2l); CHECK_WRITE(-4.2l); CHECK_WRITE(std::numeric_limits::min()); CHECK_WRITE(std::numeric_limits::max()); } TEST(WriterTest, WriteDoubleAtBufferBoundary) { MemoryWriter writer; for (int i = 0; i < 100; ++i) writer << 1.23456789; } TEST(WriterTest, WriteDoubleWithFilledBuffer) { MemoryWriter writer; // Fill the buffer. for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE; ++i) writer << ' '; writer << 1.2; EXPECT_STREQ("1.2", writer.c_str() + fmt::internal::INLINE_BUFFER_SIZE); } TEST(WriterTest, WriteChar) { CHECK_WRITE('a'); } TEST(WriterTest, WriteWideChar) { CHECK_WRITE_WCHAR(L'a'); } TEST(WriterTest, WriteString) { CHECK_WRITE_CHAR("abc"); // The following line shouldn't compile: //MemoryWriter() << L"abc"; } TEST(WriterTest, WriteWideString) { CHECK_WRITE_WCHAR(L"abc"); // The following line shouldn't compile: //fmt::WMemoryWriter() << "abc"; } TEST(WriterTest, bin) { using fmt::bin; EXPECT_EQ("1100101011111110", (MemoryWriter() << bin(0xcafe)).str()); EXPECT_EQ("1011101010111110", (MemoryWriter() << bin(0xbabeu)).str()); EXPECT_EQ("1101111010101101", (MemoryWriter() << bin(0xdeadl)).str()); EXPECT_EQ("1011111011101111", (MemoryWriter() << bin(0xbeeful)).str()); EXPECT_EQ("11001010111111101011101010111110", (MemoryWriter() << bin(0xcafebabell)).str()); EXPECT_EQ("11011110101011011011111011101111", (MemoryWriter() << bin(0xdeadbeefull)).str()); } TEST(WriterTest, oct) { using fmt::oct; EXPECT_EQ("12", (MemoryWriter() << oct(static_cast(012))).str()); EXPECT_EQ("12", (MemoryWriter() << oct(012)).str()); EXPECT_EQ("34", (MemoryWriter() << oct(034u)).str()); EXPECT_EQ("56", (MemoryWriter() << oct(056l)).str()); EXPECT_EQ("70", (MemoryWriter() << oct(070ul)).str()); EXPECT_EQ("1234", (MemoryWriter() << oct(01234ll)).str()); EXPECT_EQ("5670", (MemoryWriter() << oct(05670ull)).str()); } TEST(WriterTest, hex) { using fmt::hex; fmt::IntFormatSpec > (*phex)(int value) = hex; phex(42); // This shouldn't compile: //fmt::IntFormatSpec > (*phex2)(short value) = hex; EXPECT_EQ("cafe", (MemoryWriter() << hex(0xcafe)).str()); EXPECT_EQ("babe", (MemoryWriter() << hex(0xbabeu)).str()); EXPECT_EQ("dead", (MemoryWriter() << hex(0xdeadl)).str()); EXPECT_EQ("beef", (MemoryWriter() << hex(0xbeeful)).str()); EXPECT_EQ("cafebabe", (MemoryWriter() << hex(0xcafebabell)).str()); EXPECT_EQ("deadbeef", (MemoryWriter() << hex(0xdeadbeefull)).str()); } TEST(WriterTest, hexu) { using fmt::hexu; EXPECT_EQ("CAFE", (MemoryWriter() << hexu(0xcafe)).str()); EXPECT_EQ("BABE", (MemoryWriter() << hexu(0xbabeu)).str()); EXPECT_EQ("DEAD", (MemoryWriter() << hexu(0xdeadl)).str()); EXPECT_EQ("BEEF", (MemoryWriter() << hexu(0xbeeful)).str()); EXPECT_EQ("CAFEBABE", (MemoryWriter() << hexu(0xcafebabell)).str()); EXPECT_EQ("DEADBEEF", (MemoryWriter() << hexu(0xdeadbeefull)).str()); } class Date { int year_, month_, day_; public: Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} int year() const { return year_; } int month() const { return month_; } int day() const { return day_; } friend std::ostream &operator<<(std::ostream &os, const Date &d) { os << d.year_ << '-' << d.month_ << '-' << d.day_; return os; } friend std::wostream &operator<<(std::wostream &os, const Date &d) { os << d.year_ << L'-' << d.month_ << L'-' << d.day_; return os; } template friend BasicWriter &operator<<(BasicWriter &f, const Date &d) { return f << d.year_ << '-' << d.month_ << '-' << d.day_; } }; class ISO8601DateFormatter { const Date *date_; public: ISO8601DateFormatter(const Date &d) : date_(&d) {} template friend BasicWriter &operator<<( BasicWriter &w, const ISO8601DateFormatter &d) { return w << pad(d.date_->year(), 4, '0') << '-' << pad(d.date_->month(), 2, '0') << '-' << pad(d.date_->day(), 2, '0'); } }; ISO8601DateFormatter iso8601(const Date &d) { return ISO8601DateFormatter(d); } TEST(WriterTest, pad) { using fmt::hex; EXPECT_EQ(" cafe", (MemoryWriter() << pad(hex(0xcafe), 8)).str()); EXPECT_EQ(" babe", (MemoryWriter() << pad(hex(0xbabeu), 8)).str()); EXPECT_EQ(" dead", (MemoryWriter() << pad(hex(0xdeadl), 8)).str()); EXPECT_EQ(" beef", (MemoryWriter() << pad(hex(0xbeeful), 8)).str()); EXPECT_EQ(" dead", (MemoryWriter() << pad(hex(0xdeadll), 8)).str()); EXPECT_EQ(" beef", (MemoryWriter() << pad(hex(0xbeefull), 8)).str()); EXPECT_EQ(" 11", (MemoryWriter() << pad(11, 7)).str()); EXPECT_EQ(" 22", (MemoryWriter() << pad(22u, 7)).str()); EXPECT_EQ(" 33", (MemoryWriter() << pad(33l, 7)).str()); EXPECT_EQ(" 44", (MemoryWriter() << pad(44ul, 7)).str()); EXPECT_EQ(" 33", (MemoryWriter() << pad(33ll, 7)).str()); EXPECT_EQ(" 44", (MemoryWriter() << pad(44ull, 7)).str()); MemoryWriter w; w.clear(); w << pad(42, 5, '0'); EXPECT_EQ("00042", w.str()); w.clear(); w << Date(2012, 12, 9); EXPECT_EQ("2012-12-9", w.str()); w.clear(); w << iso8601(Date(2012, 1, 9)); EXPECT_EQ("2012-01-09", w.str()); } TEST(WriterTest, PadString) { EXPECT_EQ("test ", (MemoryWriter() << pad("test", 8)).str()); EXPECT_EQ("test******", (MemoryWriter() << pad("test", 10, '*')).str()); } TEST(WriterTest, PadWString) { EXPECT_EQ(L"test ", (WMemoryWriter() << pad(L"test", 8)).str()); EXPECT_EQ(L"test******", (WMemoryWriter() << pad(L"test", 10, '*')).str()); EXPECT_EQ(L"test******", (WMemoryWriter() << pad(L"test", 10, L'*')).str()); } TEST(WriterTest, NoConflictWithIOManip) { using namespace std; using namespace fmt; EXPECT_EQ("cafe", (MemoryWriter() << hex(0xcafe)).str()); EXPECT_EQ("12", (MemoryWriter() << oct(012)).str()); } TEST(WriterTest, Format) { MemoryWriter w; w.write("part{0}", 1); EXPECT_EQ(strlen("part1"), w.size()); EXPECT_STREQ("part1", w.c_str()); EXPECT_STREQ("part1", w.data()); EXPECT_EQ("part1", w.str()); w.write("part{0}", 2); EXPECT_EQ(strlen("part1part2"), w.size()); EXPECT_STREQ("part1part2", w.c_str()); EXPECT_STREQ("part1part2", w.data()); EXPECT_EQ("part1part2", w.str()); } TEST(WriterTest, WWriter) { EXPECT_EQ(L"cafe", (fmt::WMemoryWriter() << fmt::hex(0xcafe)).str()); } TEST(ArrayWriterTest, Ctor) { char array[10] = "garbage"; fmt::ArrayWriter w(array, sizeof(array)); EXPECT_EQ(0u, w.size()); EXPECT_STREQ("", w.c_str()); } TEST(ArrayWriterTest, CompileTimeSizeCtor) { char array[10] = "garbage"; fmt::ArrayWriter w(array); EXPECT_EQ(0u, w.size()); EXPECT_STREQ("", w.c_str()); w.write("{:10}", 1); } TEST(ArrayWriterTest, Write) { char array[10]; fmt::ArrayWriter w(array, sizeof(array)); w.write("{}", 42); EXPECT_EQ("42", w.str()); } TEST(ArrayWriterTest, BufferOverflow) { char array[10]; fmt::ArrayWriter w(array, sizeof(array)); w.write("{:10}", 1); EXPECT_THROW_MSG(w.write("{}", 1), std::runtime_error, "buffer overflow"); } TEST(ArrayWriterTest, WChar) { wchar_t array[10]; fmt::WArrayWriter w(array); w.write(L"{}", 42); EXPECT_EQ(L"42", w.str()); } TEST(FormatterTest, Escape) { EXPECT_EQ("{", format("{{")); EXPECT_EQ("before {", format("before {{")); EXPECT_EQ("{ after", format("{{ after")); EXPECT_EQ("before { after", format("before {{ after")); EXPECT_EQ("}", format("}}")); EXPECT_EQ("before }", format("before }}")); EXPECT_EQ("} after", format("}} after")); EXPECT_EQ("before } after", format("before }} after")); EXPECT_EQ("{}", format("{{}}")); EXPECT_EQ("{42}", format("{{{0}}}", 42)); } TEST(FormatterTest, UnmatchedBraces) { EXPECT_THROW_MSG(format("{"), FormatError, "invalid format string"); EXPECT_THROW_MSG(format("}"), FormatError, "unmatched '}' in format string"); EXPECT_THROW_MSG(format("{0{}"), FormatError, "invalid format string"); } TEST(FormatterTest, NoArgs) { EXPECT_EQ("test", format("test")); } TEST(FormatterTest, ArgsInDifferentPositions) { EXPECT_EQ("42", format("{0}", 42)); EXPECT_EQ("before 42", format("before {0}", 42)); EXPECT_EQ("42 after", format("{0} after", 42)); EXPECT_EQ("before 42 after", format("before {0} after", 42)); EXPECT_EQ("answer = 42", format("{0} = {1}", "answer", 42)); EXPECT_EQ("42 is the answer", format("{1} is the {0}", "answer", 42)); EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad")); } TEST(FormatterTest, ArgErrors) { EXPECT_THROW_MSG(format("{"), FormatError, "invalid format string"); EXPECT_THROW_MSG(format("{x}"), FormatError, "invalid format string"); EXPECT_THROW_MSG(format("{0"), FormatError, "invalid format string"); EXPECT_THROW_MSG(format("{0}"), FormatError, "argument index out of range"); char format_str[BUFFER_SIZE]; safe_sprintf(format_str, "{%u", INT_MAX); EXPECT_THROW_MSG(format(format_str), FormatError, "invalid format string"); safe_sprintf(format_str, "{%u}", INT_MAX); EXPECT_THROW_MSG(format(format_str), FormatError, "argument index out of range"); safe_sprintf(format_str, "{%u", INT_MAX + 1u); EXPECT_THROW_MSG(format(format_str), FormatError, "number is too big"); safe_sprintf(format_str, "{%u}", INT_MAX + 1u); EXPECT_THROW_MSG(format(format_str), FormatError, "number is too big"); } TEST(FormatterTest, AutoArgIndex) { EXPECT_EQ("abc", format("{}{}{}", 'a', 'b', 'c')); EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'), FormatError, "cannot switch from manual to automatic argument indexing"); EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'), FormatError, "cannot switch from automatic to manual argument indexing"); EXPECT_EQ("1.2", format("{:.{}}", 1.2345, 2)); EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2), FormatError, "cannot switch from manual to automatic argument indexing"); EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2), FormatError, "cannot switch from automatic to manual argument indexing"); EXPECT_THROW_MSG(format("{}"), FormatError, "argument index out of range"); } TEST(FormatterTest, EmptySpecs) { EXPECT_EQ("42", format("{0:}", 42)); } TEST(FormatterTest, LeftAlign) { EXPECT_EQ("42 ", format("{0:<4}", 42)); EXPECT_EQ("42 ", format("{0:<4o}", 042)); EXPECT_EQ("42 ", format("{0:<4x}", 0x42)); EXPECT_EQ("-42 ", format("{0:<5}", -42)); EXPECT_EQ("42 ", format("{0:<5}", 42u)); EXPECT_EQ("-42 ", format("{0:<5}", -42l)); EXPECT_EQ("42 ", format("{0:<5}", 42ul)); EXPECT_EQ("-42 ", format("{0:<5}", -42ll)); EXPECT_EQ("42 ", format("{0:<5}", 42ull)); EXPECT_EQ("-42 ", format("{0:<5}", -42.0)); EXPECT_EQ("-42 ", format("{0:<5}", -42.0l)); EXPECT_EQ("c ", format("{0:<5}", 'c')); EXPECT_EQ("abc ", format("{0:<5}", "abc")); EXPECT_EQ("0xface ", format("{0:<8}", reinterpret_cast(0xface))); EXPECT_EQ("def ", format("{0:<5}", TestString("def"))); } TEST(FormatterTest, RightAlign) { EXPECT_EQ(" 42", format("{0:>4}", 42)); EXPECT_EQ(" 42", format("{0:>4o}", 042)); EXPECT_EQ(" 42", format("{0:>4x}", 0x42)); EXPECT_EQ(" -42", format("{0:>5}", -42)); EXPECT_EQ(" 42", format("{0:>5}", 42u)); EXPECT_EQ(" -42", format("{0:>5}", -42l)); EXPECT_EQ(" 42", format("{0:>5}", 42ul)); EXPECT_EQ(" -42", format("{0:>5}", -42ll)); EXPECT_EQ(" 42", format("{0:>5}", 42ull)); EXPECT_EQ(" -42", format("{0:>5}", -42.0)); EXPECT_EQ(" -42", format("{0:>5}", -42.0l)); EXPECT_EQ(" c", format("{0:>5}", 'c')); EXPECT_EQ(" abc", format("{0:>5}", "abc")); EXPECT_EQ(" 0xface", format("{0:>8}", reinterpret_cast(0xface))); EXPECT_EQ(" def", format("{0:>5}", TestString("def"))); } TEST(FormatterTest, NumericAlign) { EXPECT_EQ(" 42", format("{0:=4}", 42)); EXPECT_EQ("+ 42", format("{0:=+4}", 42)); EXPECT_EQ(" 42", format("{0:=4o}", 042)); EXPECT_EQ("+ 42", format("{0:=+4o}", 042)); EXPECT_EQ(" 42", format("{0:=4x}", 0x42)); EXPECT_EQ("+ 42", format("{0:=+4x}", 0x42)); EXPECT_EQ("- 42", format("{0:=5}", -42)); EXPECT_EQ(" 42", format("{0:=5}", 42u)); EXPECT_EQ("- 42", format("{0:=5}", -42l)); EXPECT_EQ(" 42", format("{0:=5}", 42ul)); EXPECT_EQ("- 42", format("{0:=5}", -42ll)); EXPECT_EQ(" 42", format("{0:=5}", 42ull)); EXPECT_EQ("- 42", format("{0:=5}", -42.0)); EXPECT_EQ("- 42", format("{0:=5}", -42.0l)); EXPECT_THROW_MSG(format("{0:=5", 'c'), FormatError, "missing '}' in format string"); EXPECT_THROW_MSG(format("{0:=5}", 'c'), FormatError, "invalid format specifier for char"); EXPECT_THROW_MSG(format("{0:=5}", "abc"), FormatError, "format specifier '=' requires numeric argument"); EXPECT_THROW_MSG(format("{0:=8}", reinterpret_cast(0xface)), FormatError, "format specifier '=' requires numeric argument"); EXPECT_THROW_MSG(format("{0:=5}", TestString("def")), FormatError, "format specifier '=' requires numeric argument"); } TEST(FormatterTest, CenterAlign) { EXPECT_EQ(" 42 ", format("{0:^5}", 42)); EXPECT_EQ(" 42 ", format("{0:^5o}", 042)); EXPECT_EQ(" 42 ", format("{0:^5x}", 0x42)); EXPECT_EQ(" -42 ", format("{0:^5}", -42)); EXPECT_EQ(" 42 ", format("{0:^5}", 42u)); EXPECT_EQ(" -42 ", format("{0:^5}", -42l)); EXPECT_EQ(" 42 ", format("{0:^5}", 42ul)); EXPECT_EQ(" -42 ", format("{0:^5}", -42ll)); EXPECT_EQ(" 42 ", format("{0:^5}", 42ull)); EXPECT_EQ(" -42 ", format("{0:^6}", -42.0)); EXPECT_EQ(" -42 ", format("{0:^5}", -42.0l)); EXPECT_EQ(" c ", format("{0:^5}", 'c')); EXPECT_EQ(" abc ", format("{0:^6}", "abc")); EXPECT_EQ(" 0xface ", format("{0:^8}", reinterpret_cast(0xface))); EXPECT_EQ(" def ", format("{0:^5}", TestString("def"))); } TEST(FormatterTest, Fill) { EXPECT_THROW_MSG(format("{0:{<5}", 'c'), FormatError, "invalid fill character '{'"); EXPECT_THROW_MSG(format("{0:{<5}}", 'c'), FormatError, "invalid fill character '{'"); EXPECT_EQ("**42", format("{0:*>4}", 42)); EXPECT_EQ("**-42", format("{0:*>5}", -42)); EXPECT_EQ("***42", format("{0:*>5}", 42u)); EXPECT_EQ("**-42", format("{0:*>5}", -42l)); EXPECT_EQ("***42", format("{0:*>5}", 42ul)); EXPECT_EQ("**-42", format("{0:*>5}", -42ll)); EXPECT_EQ("***42", format("{0:*>5}", 42ull)); EXPECT_EQ("**-42", format("{0:*>5}", -42.0)); EXPECT_EQ("**-42", format("{0:*>5}", -42.0l)); EXPECT_EQ("c****", format("{0:*<5}", 'c')); EXPECT_EQ("abc**", format("{0:*<5}", "abc")); EXPECT_EQ("**0xface", format("{0:*>8}", reinterpret_cast(0xface))); EXPECT_EQ("def**", format("{0:*<5}", TestString("def"))); } TEST(FormatterTest, PlusSign) { EXPECT_EQ("+42", format("{0:+}", 42)); EXPECT_EQ("-42", format("{0:+}", -42)); EXPECT_EQ("+42", format("{0:+}", 42)); EXPECT_THROW_MSG(format("{0:+}", 42u), FormatError, "format specifier '+' requires signed argument"); EXPECT_EQ("+42", format("{0:+}", 42l)); EXPECT_THROW_MSG(format("{0:+}", 42ul), FormatError, "format specifier '+' requires signed argument"); EXPECT_EQ("+42", format("{0:+}", 42ll)); EXPECT_THROW_MSG(format("{0:+}", 42ull), FormatError, "format specifier '+' requires signed argument"); EXPECT_EQ("+42", format("{0:+}", 42.0)); EXPECT_EQ("+42", format("{0:+}", 42.0l)); EXPECT_THROW_MSG(format("{0:+", 'c'), FormatError, "missing '}' in format string"); EXPECT_THROW_MSG(format("{0:+}", 'c'), FormatError, "invalid format specifier for char"); EXPECT_THROW_MSG(format("{0:+}", "abc"), FormatError, "format specifier '+' requires numeric argument"); EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast(0x42)), FormatError, "format specifier '+' requires numeric argument"); EXPECT_THROW_MSG(format("{0:+}", TestString()), FormatError, "format specifier '+' requires numeric argument"); } TEST(FormatterTest, MinusSign) { EXPECT_EQ("42", format("{0:-}", 42)); EXPECT_EQ("-42", format("{0:-}", -42)); EXPECT_EQ("42", format("{0:-}", 42)); EXPECT_THROW_MSG(format("{0:-}", 42u), FormatError, "format specifier '-' requires signed argument"); EXPECT_EQ("42", format("{0:-}", 42l)); EXPECT_THROW_MSG(format("{0:-}", 42ul), FormatError, "format specifier '-' requires signed argument"); EXPECT_EQ("42", format("{0:-}", 42ll)); EXPECT_THROW_MSG(format("{0:-}", 42ull), FormatError, "format specifier '-' requires signed argument"); EXPECT_EQ("42", format("{0:-}", 42.0)); EXPECT_EQ("42", format("{0:-}", 42.0l)); EXPECT_THROW_MSG(format("{0:-", 'c'), FormatError, "missing '}' in format string"); EXPECT_THROW_MSG(format("{0:-}", 'c'), FormatError, "invalid format specifier for char"); EXPECT_THROW_MSG(format("{0:-}", "abc"), FormatError, "format specifier '-' requires numeric argument"); EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast(0x42)), FormatError, "format specifier '-' requires numeric argument"); EXPECT_THROW_MSG(format("{0:-}", TestString()), FormatError, "format specifier '-' requires numeric argument"); } TEST(FormatterTest, SpaceSign) { EXPECT_EQ(" 42", format("{0: }", 42)); EXPECT_EQ("-42", format("{0: }", -42)); EXPECT_EQ(" 42", format("{0: }", 42)); EXPECT_THROW_MSG(format("{0: }", 42u), FormatError, "format specifier ' ' requires signed argument"); EXPECT_EQ(" 42", format("{0: }", 42l)); EXPECT_THROW_MSG(format("{0: }", 42ul), FormatError, "format specifier ' ' requires signed argument"); EXPECT_EQ(" 42", format("{0: }", 42ll)); EXPECT_THROW_MSG(format("{0: }", 42ull), FormatError, "format specifier ' ' requires signed argument"); EXPECT_EQ(" 42", format("{0: }", 42.0)); EXPECT_EQ(" 42", format("{0: }", 42.0l)); EXPECT_THROW_MSG(format("{0: ", 'c'), FormatError, "missing '}' in format string"); EXPECT_THROW_MSG(format("{0: }", 'c'), FormatError, "invalid format specifier for char"); EXPECT_THROW_MSG(format("{0: }", "abc"), FormatError, "format specifier ' ' requires numeric argument"); EXPECT_THROW_MSG(format("{0: }", reinterpret_cast(0x42)), FormatError, "format specifier ' ' requires numeric argument"); EXPECT_THROW_MSG(format("{0: }", TestString()), FormatError, "format specifier ' ' requires numeric argument"); } TEST(FormatterTest, HashFlag) { EXPECT_EQ("42", format("{0:#}", 42)); EXPECT_EQ("-42", format("{0:#}", -42)); EXPECT_EQ("0b101010", format("{0:#b}", 42)); EXPECT_EQ("0B101010", format("{0:#B}", 42)); EXPECT_EQ("-0b101010", format("{0:#b}", -42)); EXPECT_EQ("0x42", format("{0:#x}", 0x42)); EXPECT_EQ("0X42", format("{0:#X}", 0x42)); EXPECT_EQ("-0x42", format("{0:#x}", -0x42)); EXPECT_EQ("042", format("{0:#o}", 042)); EXPECT_EQ("-042", format("{0:#o}", -042)); EXPECT_EQ("42", format("{0:#}", 42u)); EXPECT_EQ("0x42", format("{0:#x}", 0x42u)); EXPECT_EQ("042", format("{0:#o}", 042u)); EXPECT_EQ("-42", format("{0:#}", -42l)); EXPECT_EQ("0x42", format("{0:#x}", 0x42l)); EXPECT_EQ("-0x42", format("{0:#x}", -0x42l)); EXPECT_EQ("042", format("{0:#o}", 042l)); EXPECT_EQ("-042", format("{0:#o}", -042l)); EXPECT_EQ("42", format("{0:#}", 42ul)); EXPECT_EQ("0x42", format("{0:#x}", 0x42ul)); EXPECT_EQ("042", format("{0:#o}", 042ul)); EXPECT_EQ("-42", format("{0:#}", -42ll)); EXPECT_EQ("0x42", format("{0:#x}", 0x42ll)); EXPECT_EQ("-0x42", format("{0:#x}", -0x42ll)); EXPECT_EQ("042", format("{0:#o}", 042ll)); EXPECT_EQ("-042", format("{0:#o}", -042ll)); EXPECT_EQ("42", format("{0:#}", 42ull)); EXPECT_EQ("0x42", format("{0:#x}", 0x42ull)); EXPECT_EQ("042", format("{0:#o}", 042ull)); EXPECT_EQ("-42.0000", format("{0:#}", -42.0)); EXPECT_EQ("-42.0000", format("{0:#}", -42.0l)); EXPECT_THROW_MSG(format("{0:#", 'c'), FormatError, "missing '}' in format string"); EXPECT_THROW_MSG(format("{0:#}", 'c'), FormatError, "invalid format specifier for char"); EXPECT_THROW_MSG(format("{0:#}", "abc"), FormatError, "format specifier '#' requires numeric argument"); EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast(0x42)), FormatError, "format specifier '#' requires numeric argument"); EXPECT_THROW_MSG(format("{0:#}", TestString()), FormatError, "format specifier '#' requires numeric argument"); } TEST(FormatterTest, ZeroFlag) { EXPECT_EQ("42", format("{0:0}", 42)); EXPECT_EQ("-0042", format("{0:05}", -42)); EXPECT_EQ("00042", format("{0:05}", 42u)); EXPECT_EQ("-0042", format("{0:05}", -42l)); EXPECT_EQ("00042", format("{0:05}", 42ul)); EXPECT_EQ("-0042", format("{0:05}", -42ll)); EXPECT_EQ("00042", format("{0:05}", 42ull)); EXPECT_EQ("-0042", format("{0:05}", -42.0)); EXPECT_EQ("-0042", format("{0:05}", -42.0l)); EXPECT_THROW_MSG(format("{0:0", 'c'), FormatError, "missing '}' in format string"); EXPECT_THROW_MSG(format("{0:05}", 'c'), FormatError, "invalid format specifier for char"); EXPECT_THROW_MSG(format("{0:05}", "abc"), FormatError, "format specifier '0' requires numeric argument"); EXPECT_THROW_MSG(format("{0:05}", reinterpret_cast(0x42)), FormatError, "format specifier '0' requires numeric argument"); EXPECT_THROW_MSG(format("{0:05}", TestString()), FormatError, "format specifier '0' requires numeric argument"); } TEST(FormatterTest, Width) { char format_str[BUFFER_SIZE]; safe_sprintf(format_str, "{0:%u", UINT_MAX); increment(format_str + 3); EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); std::size_t size = std::strlen(format_str); format_str[size] = '}'; format_str[size + 1] = 0; EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); safe_sprintf(format_str, "{0:%u", INT_MAX + 1u); EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); safe_sprintf(format_str, "{0:%u}", INT_MAX + 1u); EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); EXPECT_EQ(" -42", format("{0:4}", -42)); EXPECT_EQ(" 42", format("{0:5}", 42u)); EXPECT_EQ(" -42", format("{0:6}", -42l)); EXPECT_EQ(" 42", format("{0:7}", 42ul)); EXPECT_EQ(" -42", format("{0:6}", -42ll)); EXPECT_EQ(" 42", format("{0:7}", 42ull)); EXPECT_EQ(" -1.23", format("{0:8}", -1.23)); EXPECT_EQ(" -1.23", format("{0:9}", -1.23l)); EXPECT_EQ(" 0xcafe", format("{0:10}", reinterpret_cast(0xcafe))); EXPECT_EQ("x ", format("{0:11}", 'x')); EXPECT_EQ("str ", format("{0:12}", "str")); EXPECT_EQ("test ", format("{0:13}", TestString("test"))); } TEST(FormatterTest, Precision) { char format_str[BUFFER_SIZE]; safe_sprintf(format_str, "{0:.%u", UINT_MAX); increment(format_str + 4); EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); std::size_t size = std::strlen(format_str); format_str[size] = '}'; format_str[size + 1] = 0; EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u); EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u); EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); EXPECT_THROW_MSG(format("{0:.", 0), FormatError, "missing precision specifier"); EXPECT_THROW_MSG(format("{0:.}", 0), FormatError, "missing precision specifier"); EXPECT_THROW_MSG(format("{0:.2", 0), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2}", 42), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2f}", 42), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2}", 42u), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2f}", 42u), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2}", 42l), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2f}", 42l), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2}", 42ul), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2f}", 42ul), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2}", 42ll), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2f}", 42ll), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2}", 42ull), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.2f}", 42ull), FormatError, "precision not allowed in integer format specifier"); EXPECT_EQ("1.2", format("{0:.2}", 1.2345)); EXPECT_EQ("1.2", format("{0:.2}", 1.2345l)); EXPECT_THROW_MSG(format("{0:.2}", reinterpret_cast(0xcafe)), FormatError, "precision not allowed in pointer format specifier"); EXPECT_THROW_MSG(format("{0:.2f}", reinterpret_cast(0xcafe)), FormatError, "precision not allowed in pointer format specifier"); EXPECT_EQ(" ", format("{0:3.0}", 'x')); EXPECT_EQ("st", format("{0:.2}", "str")); EXPECT_EQ("te", format("{0:.2}", TestString("test"))); } TEST(FormatterTest, RuntimePrecision) { char format_str[BUFFER_SIZE]; safe_sprintf(format_str, "{0:.{%u", UINT_MAX); increment(format_str + 5); EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); std::size_t size = std::strlen(format_str); format_str[size] = '}'; format_str[size + 1] = 0; EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); format_str[size + 1] = '}'; format_str[size + 2] = 0; EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big"); EXPECT_THROW_MSG(format("{0:.{", 0), FormatError, "invalid format string"); EXPECT_THROW_MSG(format("{0:.{}", 0), FormatError, "cannot switch from manual to automatic argument indexing"); EXPECT_THROW_MSG(format("{0:.{x}}", 0), FormatError, "invalid format string"); EXPECT_THROW_MSG(format("{0:.{1}", 0, 0), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}}", 0), FormatError, "argument index out of range"); EXPECT_THROW_MSG(format("{0:.{0:}}", 0), FormatError, "invalid format string"); EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1), FormatError, "negative precision"); EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)), FormatError, "number is too big"); EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l), FormatError, "negative precision"); if (sizeof(long) > sizeof(int)) { long value = INT_MAX; EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)), FormatError, "number is too big"); } EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)), FormatError, "number is too big"); EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'), FormatError, "precision is not integer"); EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0), FormatError, "precision is not integer"); EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2), FormatError, "precision not allowed in integer format specifier"); EXPECT_EQ("1.2", format("{0:.{1}}", 1.2345, 2)); EXPECT_EQ("1.2", format("{1:.{0}}", 2, 1.2345l)); EXPECT_THROW_MSG(format("{0:.{1}}", reinterpret_cast(0xcafe), 2), FormatError, "precision not allowed in pointer format specifier"); EXPECT_THROW_MSG(format("{0:.{1}f}", reinterpret_cast(0xcafe), 2), FormatError, "precision not allowed in pointer format specifier"); EXPECT_EQ(" ", format("{0:3.{1}}", 'x', 0)); EXPECT_EQ("st", format("{0:.{1}}", "str", 2)); EXPECT_EQ("te", format("{0:.{1}}", TestString("test"), 2)); } template void check_unknown_types( const T &value, const char *types, const char *type_name) { char format_str[BUFFER_SIZE], message[BUFFER_SIZE]; const char *special = ".0123456789}"; for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) { char c = i; if (std::strchr(types, c) || std::strchr(special, c) || !c) continue; safe_sprintf(format_str, "{0:10%c}", c); if (std::isprint(static_cast(c))) safe_sprintf(message, "unknown format code '%c' for %s", c, type_name); else safe_sprintf(message, "unknown format code '\\x%02x' for %s", c, type_name); EXPECT_THROW_MSG(format(format_str, value), FormatError, message) << format_str << " " << message; } } TEST(FormatterTest, FormatBool) { EXPECT_EQ(L"1", format(L"{}", true)); } TEST(FormatterTest, FormatShort) { short s = 42; EXPECT_EQ("42", format("{0:d}", s)); unsigned short us = 42; EXPECT_EQ("42", format("{0:d}", us)); } TEST(FormatterTest, FormatInt) { EXPECT_THROW_MSG(format("{0:v", 42), FormatError, "missing '}' in format string"); check_unknown_types(42, "bBdoxX", "integer"); } TEST(FormatterTest, FormatBin) { EXPECT_EQ("0", format("{0:b}", 0)); EXPECT_EQ("101010", format("{0:b}", 42)); EXPECT_EQ("101010", format("{0:b}", 42u)); EXPECT_EQ("-101010", format("{0:b}", -42)); EXPECT_EQ("11000000111001", format("{0:b}", 12345)); EXPECT_EQ("10010001101000101011001111000", format("{0:b}", 0x12345678)); EXPECT_EQ("10010000101010111100110111101111", format("{0:b}", 0x90ABCDEF)); EXPECT_EQ("11111111111111111111111111111111", format("{0:b}", std::numeric_limits::max())); } TEST(FormatterTest, FormatDec) { EXPECT_EQ("0", format("{0}", 0)); EXPECT_EQ("42", format("{0}", 42)); EXPECT_EQ("42", format("{0:d}", 42)); EXPECT_EQ("42", format("{0}", 42u)); EXPECT_EQ("-42", format("{0}", -42)); EXPECT_EQ("12345", format("{0}", 12345)); EXPECT_EQ("67890", format("{0}", 67890)); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "%d", INT_MIN); EXPECT_EQ(buffer, format("{0}", INT_MIN)); safe_sprintf(buffer, "%d", INT_MAX); EXPECT_EQ(buffer, format("{0}", INT_MAX)); safe_sprintf(buffer, "%u", UINT_MAX); EXPECT_EQ(buffer, format("{0}", UINT_MAX)); safe_sprintf(buffer, "%ld", 0 - static_cast(LONG_MIN)); EXPECT_EQ(buffer, format("{0}", LONG_MIN)); safe_sprintf(buffer, "%ld", LONG_MAX); EXPECT_EQ(buffer, format("{0}", LONG_MAX)); safe_sprintf(buffer, "%lu", ULONG_MAX); EXPECT_EQ(buffer, format("{0}", ULONG_MAX)); } TEST(FormatterTest, FormatHex) { EXPECT_EQ("0", format("{0:x}", 0)); EXPECT_EQ("42", format("{0:x}", 0x42)); EXPECT_EQ("42", format("{0:x}", 0x42u)); EXPECT_EQ("-42", format("{0:x}", -0x42)); EXPECT_EQ("12345678", format("{0:x}", 0x12345678)); EXPECT_EQ("90abcdef", format("{0:x}", 0x90abcdef)); EXPECT_EQ("12345678", format("{0:X}", 0x12345678)); EXPECT_EQ("90ABCDEF", format("{0:X}", 0x90ABCDEF)); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "-%x", 0 - static_cast(INT_MIN)); EXPECT_EQ(buffer, format("{0:x}", INT_MIN)); safe_sprintf(buffer, "%x", INT_MAX); EXPECT_EQ(buffer, format("{0:x}", INT_MAX)); safe_sprintf(buffer, "%x", UINT_MAX); EXPECT_EQ(buffer, format("{0:x}", UINT_MAX)); safe_sprintf(buffer, "-%lx", 0 - static_cast(LONG_MIN)); EXPECT_EQ(buffer, format("{0:x}", LONG_MIN)); safe_sprintf(buffer, "%lx", LONG_MAX); EXPECT_EQ(buffer, format("{0:x}", LONG_MAX)); safe_sprintf(buffer, "%lx", ULONG_MAX); EXPECT_EQ(buffer, format("{0:x}", ULONG_MAX)); } TEST(FormatterTest, FormatOct) { EXPECT_EQ("0", format("{0:o}", 0)); EXPECT_EQ("42", format("{0:o}", 042)); EXPECT_EQ("42", format("{0:o}", 042u)); EXPECT_EQ("-42", format("{0:o}", -042)); EXPECT_EQ("12345670", format("{0:o}", 012345670)); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "-%o", 0 - static_cast(INT_MIN)); EXPECT_EQ(buffer, format("{0:o}", INT_MIN)); safe_sprintf(buffer, "%o", INT_MAX); EXPECT_EQ(buffer, format("{0:o}", INT_MAX)); safe_sprintf(buffer, "%o", UINT_MAX); EXPECT_EQ(buffer, format("{0:o}", UINT_MAX)); safe_sprintf(buffer, "-%lo", 0 - static_cast(LONG_MIN)); EXPECT_EQ(buffer, format("{0:o}", LONG_MIN)); safe_sprintf(buffer, "%lo", LONG_MAX); EXPECT_EQ(buffer, format("{0:o}", LONG_MAX)); safe_sprintf(buffer, "%lo", ULONG_MAX); EXPECT_EQ(buffer, format("{0:o}", ULONG_MAX)); } TEST(FormatterTest, FormatFloat) { EXPECT_EQ("392.500000", format("{0:f}", 392.5f)); } TEST(FormatterTest, FormatDouble) { check_unknown_types(1.2, "eEfFgGaA", "double"); EXPECT_EQ("0", format("{0:}", 0.0)); EXPECT_EQ("0.000000", format("{0:f}", 0.0)); EXPECT_EQ("392.65", format("{0:}", 392.65)); EXPECT_EQ("392.65", format("{0:g}", 392.65)); EXPECT_EQ("392.65", format("{0:G}", 392.65)); EXPECT_EQ("392.650000", format("{0:f}", 392.65)); EXPECT_EQ("392.650000", format("{0:F}", 392.65)); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "%e", 392.65); EXPECT_EQ(buffer, format("{0:e}", 392.65)); safe_sprintf(buffer, "%E", 392.65); EXPECT_EQ(buffer, format("{0:E}", 392.65)); EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.65)); safe_sprintf(buffer, "%a", -42.0); EXPECT_EQ(buffer, format("{:a}", -42.0)); safe_sprintf(buffer, "%A", -42.0); EXPECT_EQ(buffer, format("{:A}", -42.0)); } TEST(FormatterTest, FormatNaN) { double nan = std::numeric_limits::quiet_NaN(); EXPECT_EQ("nan", format("{}", nan)); EXPECT_EQ("+nan", format("{:+}", nan)); EXPECT_EQ(" nan", format("{: }", nan)); EXPECT_EQ("NAN", format("{:F}", nan)); EXPECT_EQ("nan ", format("{:<7}", nan)); EXPECT_EQ(" nan ", format("{:^7}", nan)); EXPECT_EQ(" nan", format("{:>7}", nan)); } TEST(FormatterTest, FormatInfinity) { double inf = std::numeric_limits::infinity(); EXPECT_EQ("inf", format("{}", inf)); EXPECT_EQ("+inf", format("{:+}", inf)); EXPECT_EQ("-inf", format("{}", -inf)); EXPECT_EQ(" inf", format("{: }", inf)); EXPECT_EQ("INF", format("{:F}", inf)); EXPECT_EQ("inf ", format("{:<7}", inf)); EXPECT_EQ(" inf ", format("{:^7}", inf)); EXPECT_EQ(" inf", format("{:>7}", inf)); } TEST(FormatterTest, FormatLongDouble) { EXPECT_EQ("0", format("{0:}", 0.0l)); EXPECT_EQ("0.000000", format("{0:f}", 0.0l)); EXPECT_EQ("392.65", format("{0:}", 392.65l)); EXPECT_EQ("392.65", format("{0:g}", 392.65l)); EXPECT_EQ("392.65", format("{0:G}", 392.65l)); EXPECT_EQ("392.650000", format("{0:f}", 392.65l)); EXPECT_EQ("392.650000", format("{0:F}", 392.65l)); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "%Le", 392.65l); EXPECT_EQ(buffer, format("{0:e}", 392.65l)); safe_sprintf(buffer, "%LE", 392.65l); EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.65l)); } TEST(FormatterTest, FormatChar) { const char types[] = "cbBdoxX"; check_unknown_types('a', types, "char"); EXPECT_EQ("a", format("{0}", 'a')); EXPECT_EQ("z", format("{0:c}", 'z')); EXPECT_EQ(L"a", format(L"{0}", 'a')); int n = 'x'; for (const char *type = types + 1; *type; ++type) { std::string format_str = fmt::format("{{:{}}}", *type); EXPECT_EQ(fmt::format(format_str, n), fmt::format(format_str, 'x')); } EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x')); } TEST(FormatterTest, FormatWChar) { EXPECT_EQ(L"a", format(L"{0}", L'a')); // This shouldn't compile: //format("{}", L'a'); } TEST(FormatterTest, FormatCString) { check_unknown_types("test", "s", "string"); EXPECT_EQ("test", format("{0}", "test")); EXPECT_EQ("test", format("{0:s}", "test")); char nonconst[] = "nonconst"; EXPECT_EQ("nonconst", format("{0}", nonconst)); EXPECT_THROW_MSG(format("{0}", reinterpret_cast(0)), FormatError, "string pointer is null"); } TEST(FormatterTest, FormatSCharString) { signed char str[] = "test"; EXPECT_EQ("test", format("{0:s}", str)); const signed char *const_str = str; EXPECT_EQ("test", format("{0:s}", const_str)); } TEST(FormatterTest, FormatUCharString) { unsigned char str[] = "test"; EXPECT_EQ("test", format("{0:s}", str)); const unsigned char *const_str = str; EXPECT_EQ("test", format("{0:s}", const_str)); } TEST(FormatterTest, FormatPointer) { check_unknown_types(reinterpret_cast(0x1234), "p", "pointer"); EXPECT_EQ("0x0", format("{0}", reinterpret_cast(0))); EXPECT_EQ("0x1234", format("{0}", reinterpret_cast(0x1234))); EXPECT_EQ("0x1234", format("{0:p}", reinterpret_cast(0x1234))); EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'), format("{0}", reinterpret_cast(~uintptr_t()))); } TEST(FormatterTest, FormatString) { EXPECT_EQ("test", format("{0}", std::string("test"))); } TEST(FormatterTest, FormatStringRef) { EXPECT_EQ("test", format("{0}", StringRef("test"))); } TEST(FormatterTest, FormatUsingIOStreams) { EXPECT_EQ("a string", format("{0}", TestString("a string"))); std::string s = format("The date is {0}", Date(2012, 12, 9)); EXPECT_EQ("The date is 2012-12-9", s); Date date(2012, 12, 9); check_unknown_types(date, "s", "string"); EXPECT_EQ(L"The date is 2012-12-9", format(L"The date is {0}", Date(2012, 12, 9))); } class Answer {}; template void format(fmt::BasicFormatter &f, const Char *, Answer) { f.writer() << "42"; } TEST(FormatterTest, CustomFormat) { EXPECT_EQ("42", format("{0}", Answer())); } TEST(FormatterTest, WideFormatString) { EXPECT_EQ(L"42", format(L"{}", 42)); EXPECT_EQ(L"4.2", format(L"{}", 4.2)); EXPECT_EQ(L"abc", format(L"{}", L"abc")); EXPECT_EQ(L"z", format(L"{}", L'z')); } TEST(FormatterTest, FormatStringFromSpeedTest) { EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%", format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42, 3.13, "str", reinterpret_cast(1000), 'X')); } TEST(FormatterTest, FormatExamples) { using fmt::hex; EXPECT_EQ("0000cafe", (MemoryWriter() << pad(hex(0xcafe), 8, '0')).str()); std::string message = format("The answer is {}", 42); EXPECT_EQ("The answer is 42", message); EXPECT_EQ("42", format("{}", 42)); EXPECT_EQ("42", format(std::string("{}"), 42)); MemoryWriter out; out << "The answer is " << 42 << "\n"; out.write("({:+f}, {:+f})", -3.14, 3.14); EXPECT_EQ("The answer is 42\n(-3.140000, +3.140000)", out.str()); { MemoryWriter writer; for (int i = 0; i < 10; i++) writer.write("{}", i); std::string s = writer.str(); // s == 0123456789 EXPECT_EQ("0123456789", s); } const char *filename = "nonexistent"; FILE *ftest = fopen(filename, "r"); int error_code = errno; EXPECT_TRUE(ftest == 0); EXPECT_SYSTEM_ERROR({ FILE *f = fopen(filename, "r"); if (!f) throw fmt::SystemError(errno, "Cannot open file '{}'", filename); }, error_code, "Cannot open file 'nonexistent'"); } TEST(StringRefTest, Ctor) { EXPECT_STREQ("abc", StringRef("abc").c_str()); EXPECT_EQ(3u, StringRef("abc").size()); EXPECT_STREQ("defg", StringRef(std::string("defg")).c_str()); EXPECT_EQ(4u, StringRef(std::string("defg")).size()); } TEST(StringRefTest, ConvertToString) { std::string s = StringRef("abc"); EXPECT_EQ("abc", s); } TEST(FormatterTest, Examples) { EXPECT_EQ("First, thou shalt count to three", format("First, thou shalt count to {0}", "three")); EXPECT_EQ("Bring me a shrubbery", format("Bring me a {}", "shrubbery")); EXPECT_EQ("From 1 to 3", format("From {} to {}", 1, 3)); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "%03.2f", -1.2); EXPECT_EQ(buffer, format("{:03.2f}", -1.2)); EXPECT_EQ("a, b, c", format("{0}, {1}, {2}", 'a', 'b', 'c')); EXPECT_EQ("a, b, c", format("{}, {}, {}", 'a', 'b', 'c')); EXPECT_EQ("c, b, a", format("{2}, {1}, {0}", 'a', 'b', 'c')); EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad")); EXPECT_EQ("left aligned ", format("{:<30}", "left aligned")); EXPECT_EQ(" right aligned", format("{:>30}", "right aligned")); EXPECT_EQ(" centered ", format("{:^30}", "centered")); EXPECT_EQ("***********centered***********", format("{:*^30}", "centered")); EXPECT_EQ("+3.140000; -3.140000", format("{:+f}; {:+f}", 3.14, -3.14)); EXPECT_EQ(" 3.140000; -3.140000", format("{: f}; {: f}", 3.14, -3.14)); EXPECT_EQ("3.140000; -3.140000", format("{:-f}; {:-f}", 3.14, -3.14)); EXPECT_EQ("int: 42; hex: 2a; oct: 52", format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42)); EXPECT_EQ("int: 42; hex: 0x2a; oct: 052", format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42)); EXPECT_EQ("The answer is 42", format("The answer is {}", 42)); EXPECT_THROW_MSG( format("The answer is {:d}", "forty-two"), FormatError, "unknown format code 'd' for string"); EXPECT_EQ(L"Cyrillic letter \x42e", format(L"Cyrillic letter {}", L'\x42e')); EXPECT_WRITE(stdout, fmt::print("{}", std::numeric_limits::infinity()), "inf"); } TEST(FormatIntTest, Data) { fmt::FormatInt format_int(42); EXPECT_EQ("42", std::string(format_int.data(), format_int.size())); } TEST(FormatIntTest, FormatInt) { EXPECT_EQ("42", fmt::FormatInt(42).str()); EXPECT_EQ(2u, fmt::FormatInt(42).size()); EXPECT_EQ("-42", fmt::FormatInt(-42).str()); EXPECT_EQ(3u, fmt::FormatInt(-42).size()); EXPECT_EQ("42", fmt::FormatInt(42ul).str()); EXPECT_EQ("-42", fmt::FormatInt(-42l).str()); EXPECT_EQ("42", fmt::FormatInt(42ull).str()); EXPECT_EQ("-42", fmt::FormatInt(-42ll).str()); std::ostringstream os; os << std::numeric_limits::max(); EXPECT_EQ(os.str(), fmt::FormatInt(std::numeric_limits::max()).str()); } template std::string format_decimal(T value) { char buffer[10]; char *ptr = buffer; fmt::format_decimal(ptr, value); return std::string(buffer, ptr); } TEST(FormatIntTest, FormatDec) { EXPECT_EQ("-42", format_decimal(static_cast(-42))); EXPECT_EQ("-42", format_decimal(static_cast(-42))); std::ostringstream os; os << std::numeric_limits::max(); EXPECT_EQ(os.str(), format_decimal(std::numeric_limits::max())); EXPECT_EQ("1", format_decimal(1)); EXPECT_EQ("-1", format_decimal(-1)); EXPECT_EQ("42", format_decimal(42)); EXPECT_EQ("-42", format_decimal(-42)); EXPECT_EQ("42", format_decimal(42l)); EXPECT_EQ("42", format_decimal(42ul)); EXPECT_EQ("42", format_decimal(42ll)); EXPECT_EQ("42", format_decimal(42ull)); } TEST(FormatTest, Print) { #if FMT_USE_FILE_DESCRIPTORS EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!"); EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"), "Don't panic!"); #endif std::ostringstream os; fmt::print(os, "Don't {}!", "panic"); EXPECT_EQ("Don't panic!", os.str()); } #if FMT_USE_FILE_DESCRIPTORS TEST(FormatTest, PrintColored) { EXPECT_WRITE(stdout, fmt::print_colored(fmt::RED, "Hello, {}!\n", "world"), "\x1b[31mHello, world!\n\x1b[0m"); } #endif TEST(FormatTest, Variadic) { EXPECT_EQ("abc1", format("{}c{}", "ab", 1)); EXPECT_EQ(L"abc1", format(L"{}c{}", L"ab", 1)); } template std::string str(const T &value) { return fmt::format("{}", value); } TEST(StrTest, Convert) { EXPECT_EQ("42", str(42)); std::string s = str(Date(2012, 12, 9)); EXPECT_EQ("2012-12-9", s); } std::string format_message(int id, const char *format, const fmt::ArgList &args) { MemoryWriter w; w.write("[{}] ", id); w.write(format, args); return w.str(); } FMT_VARIADIC(std::string, format_message, int, const char *) TEST(FormatTest, FormatMessageExample) { EXPECT_EQ("[42] something happened", format_message(42, "{} happened", "something")); } #if FMT_USE_VARIADIC_TEMPLATES template void print_error(const char *file, int line, const char *format, const Args & ... args) { fmt::print("{}: {}: ", file, line); fmt::print(format, args...); } #endif TEST(FormatTest, MaxArgs) { EXPECT_EQ("0123456789abcde", fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e')); } cppformat-1.1.0/test/gtest-extra-test.cc000066400000000000000000000604011247635332500202310ustar00rootroot00000000000000/* Tests of custom Google Test assertions. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gtest-extra.h" #include #include #include #include #if defined(_WIN32) && !defined(__MINGW32__) # include // for _CrtSetReportMode #endif // _WIN32 namespace { #if defined(_WIN32) && !defined(__MINGW32__) // Suppresses Windows assertions on invalid file descriptors, making // POSIX functions return proper error codes instead of crashing on Windows. class SuppressAssert { private: _invalid_parameter_handler original_handler_; int original_report_mode_; static void handle_invalid_parameter(const wchar_t *, const wchar_t *, const wchar_t *, unsigned , uintptr_t) {} public: SuppressAssert() : original_handler_(_set_invalid_parameter_handler(handle_invalid_parameter)), original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) { } ~SuppressAssert() { _set_invalid_parameter_handler(original_handler_); _CrtSetReportMode(_CRT_ASSERT, original_report_mode_); } }; # define SUPPRESS_ASSERT(statement) { SuppressAssert sa; statement; } // Fix "secure" warning about using fopen without defining // _CRT_SECURE_NO_WARNINGS. FILE *safe_fopen(const char *filename, const char *mode) { FILE *f = 0; errno = fopen_s(&f, filename, mode); return f; } #define fopen safe_fopen #else # define SUPPRESS_ASSERT(statement) statement using std::fopen; #endif // _WIN32 #define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \ EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message) // Tests that assertion macros evaluate their arguments exactly once. class SingleEvaluationTest : public ::testing::Test { protected: SingleEvaluationTest() { p_ = s_; a_ = 0; b_ = 0; } static const char* const s_; static const char* p_; static int a_; static int b_; }; const char* const SingleEvaluationTest::s_ = "01234"; const char* SingleEvaluationTest::p_; int SingleEvaluationTest::a_; int SingleEvaluationTest::b_; void do_nothing() {} void throw_exception() { throw std::runtime_error("test"); } void throw_system_error() { throw fmt::SystemError(EDOM, "test"); } // Tests that when EXPECT_THROW_MSG fails, it evaluates its message argument // exactly once. TEST_F(SingleEvaluationTest, FailedEXPECT_THROW_MSG) { EXPECT_NONFATAL_FAILURE( EXPECT_THROW_MSG(throw_exception(), std::exception, p_++), "01234"); EXPECT_EQ(s_ + 1, p_); } // Tests that when EXPECT_SYSTEM_ERROR fails, it evaluates its message argument // exactly once. TEST_F(SingleEvaluationTest, FailedEXPECT_SYSTEM_ERROR) { EXPECT_NONFATAL_FAILURE( EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++), "01234"); EXPECT_EQ(s_ + 1, p_); } // Tests that when EXPECT_WRITE fails, it evaluates its message argument // exactly once. TEST_F(SingleEvaluationTest, FailedEXPECT_WRITE) { EXPECT_NONFATAL_FAILURE( EXPECT_WRITE(stdout, std::printf("test"), p_++), "01234"); EXPECT_EQ(s_ + 1, p_); } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ExceptionTests) { // successful EXPECT_THROW_MSG EXPECT_THROW_MSG({ // NOLINT a_++; throw_exception(); }, std::exception, (b_++, "test")); EXPECT_EQ(1, a_); EXPECT_EQ(1, b_); // failed EXPECT_THROW_MSG, throws different type EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT a_++; throw_exception(); }, std::logic_error, (b_++, "test")), "throws a different type"); EXPECT_EQ(2, a_); EXPECT_EQ(2, b_); // failed EXPECT_THROW_MSG, throws an exception with different message EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT a_++; throw_exception(); }, std::exception, (b_++, "other")), "throws an exception with a different message"); EXPECT_EQ(3, a_); EXPECT_EQ(3, b_); // failed EXPECT_THROW_MSG, throws nothing EXPECT_NONFATAL_FAILURE( EXPECT_THROW_MSG(a_++, std::exception, (b_++, "test")), "throws nothing"); EXPECT_EQ(4, a_); EXPECT_EQ(4, b_); } TEST_F(SingleEvaluationTest, SystemErrorTests) { // successful EXPECT_SYSTEM_ERROR EXPECT_SYSTEM_ERROR({ // NOLINT a_++; throw_system_error(); }, EDOM, (b_++, "test")); EXPECT_EQ(1, a_); EXPECT_EQ(1, b_); // failed EXPECT_SYSTEM_ERROR, throws different type EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT a_++; throw_exception(); }, EDOM, (b_++, "test")), "throws a different type"); EXPECT_EQ(2, a_); EXPECT_EQ(2, b_); // failed EXPECT_SYSTEM_ERROR, throws an exception with different message EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT a_++; throw_system_error(); }, EDOM, (b_++, "other")), "throws an exception with a different message"); EXPECT_EQ(3, a_); EXPECT_EQ(3, b_); // failed EXPECT_SYSTEM_ERROR, throws nothing EXPECT_NONFATAL_FAILURE( EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")), "throws nothing"); EXPECT_EQ(4, a_); EXPECT_EQ(4, b_); } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, WriteTests) { // successful EXPECT_WRITE EXPECT_WRITE(stdout, { // NOLINT a_++; std::printf("test"); }, (b_++, "test")); EXPECT_EQ(1, a_); EXPECT_EQ(1, b_); // failed EXPECT_WRITE EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, { // NOLINT a_++; std::printf("test"); }, (b_++, "other")), "Actual: test"); EXPECT_EQ(2, a_); EXPECT_EQ(2, b_); } // Tests that the compiler will not complain about unreachable code in the // EXPECT_THROW_MSG macro. TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { int n = 0; using std::runtime_error; EXPECT_THROW_MSG(throw runtime_error(""), runtime_error, ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(n++, runtime_error, ""), ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(throw 1, runtime_error, ""), ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG( throw runtime_error("a"), runtime_error, "b"), ""); } // Tests that the compiler will not complain about unreachable code in the // EXPECT_SYSTEM_ERROR macro. TEST(ExpectSystemErrorTest, DoesNotGenerateUnreachableCodeWarning) { int n = 0; EXPECT_SYSTEM_ERROR(throw fmt::SystemError(EDOM, "test"), EDOM, "test"); EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(n++, EDOM, ""), ""); EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw 1, EDOM, ""), ""); EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR( throw fmt::SystemError(EDOM, "aaa"), EDOM, "bbb"), ""); } TEST(AssertionSyntaxTest, ExceptionAssertionBehavesLikeSingleStatement) { if (::testing::internal::AlwaysFalse()) EXPECT_THROW_MSG(do_nothing(), std::exception, ""); if (::testing::internal::AlwaysTrue()) EXPECT_THROW_MSG(throw_exception(), std::exception, "test"); else do_nothing(); } TEST(AssertionSyntaxTest, SystemErrorAssertionBehavesLikeSingleStatement) { if (::testing::internal::AlwaysFalse()) EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, ""); if (::testing::internal::AlwaysTrue()) EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test"); else do_nothing(); } TEST(AssertionSyntaxTest, WriteAssertionBehavesLikeSingleStatement) { if (::testing::internal::AlwaysFalse()) EXPECT_WRITE(stdout, std::printf("x"), "x"); if (::testing::internal::AlwaysTrue()) EXPECT_WRITE(stdout, std::printf("x"), "x"); else do_nothing(); } // Tests EXPECT_THROW_MSG. TEST(ExpectTest, EXPECT_THROW_MSG) { EXPECT_THROW_MSG(throw_exception(), std::exception, "test"); EXPECT_NONFATAL_FAILURE( EXPECT_THROW_MSG(throw_exception(), std::logic_error, "test"), "Expected: throw_exception() throws an exception of " "type std::logic_error.\n Actual: it throws a different type."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW_MSG(do_nothing(), std::exception, "test"), "Expected: do_nothing() throws an exception of type std::exception.\n" " Actual: it throws nothing."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW_MSG(throw_exception(), std::exception, "other"), "throw_exception() throws an exception with a different message.\n" "Expected: other\n" " Actual: test"); } // Tests EXPECT_SYSTEM_ERROR. TEST(ExpectTest, EXPECT_SYSTEM_ERROR) { EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test"); EXPECT_NONFATAL_FAILURE( EXPECT_SYSTEM_ERROR(throw_exception(), EDOM, "test"), "Expected: throw_exception() throws an exception of " "type fmt::SystemError.\n Actual: it throws a different type."); EXPECT_NONFATAL_FAILURE( EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, "test"), "Expected: do_nothing() throws an exception of type fmt::SystemError.\n" " Actual: it throws nothing."); EXPECT_NONFATAL_FAILURE( EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other"), fmt::format( "throw_system_error() throws an exception with a different message.\n" "Expected: {}\n" " Actual: {}", format_system_error(EDOM, "other"), format_system_error(EDOM, "test"))); } // Tests EXPECT_WRITE. TEST(ExpectTest, EXPECT_WRITE) { EXPECT_WRITE(stdout, do_nothing(), ""); EXPECT_WRITE(stdout, std::printf("test"), "test"); EXPECT_WRITE(stderr, std::fprintf(stderr, "test"), "test"); EXPECT_NONFATAL_FAILURE( EXPECT_WRITE(stdout, std::printf("that"), "this"), "Expected: this\n" " Actual: that"); } TEST(StreamingAssertionsTest, EXPECT_THROW_MSG) { EXPECT_THROW_MSG(throw_exception(), std::exception, "test") << "unexpected failure"; EXPECT_NONFATAL_FAILURE( EXPECT_THROW_MSG(throw_exception(), std::exception, "other") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, EXPECT_SYSTEM_ERROR) { EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test") << "unexpected failure"; EXPECT_NONFATAL_FAILURE( EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, EXPECT_WRITE) { EXPECT_WRITE(stdout, std::printf("test"), "test") << "unexpected failure"; EXPECT_NONFATAL_FAILURE( EXPECT_WRITE(stdout, std::printf("test"), "other") << "expected failure", "expected failure"); } TEST(UtilTest, FormatSystemError) { fmt::MemoryWriter out; fmt::internal::format_system_error(out, EDOM, "test message"); EXPECT_EQ(out.str(), format_system_error(EDOM, "test message")); } #if FMT_USE_FILE_DESCRIPTORS using fmt::BufferedFile; using fmt::ErrorCode; using fmt::File; // Checks if the file is open by reading one character from it. bool isopen(int fd) { char buffer; return FMT_POSIX(read(fd, &buffer, 1)) == 1; } bool isclosed(int fd) { char buffer; std::streamsize result = 0; SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1))); return result == -1 && errno == EBADF; } // Attempts to read count characters from a file. std::string read(File &f, std::size_t count) { std::string buffer(count, '\0'); std::streamsize n = 0; std::size_t offset = 0; do { n = f.read(&buffer[offset], count - offset); // We can't read more than size_t bytes since count has type size_t. offset += static_cast(n); } while (offset < count && n != 0); buffer.resize(offset); return buffer; } // Attempts to write a string to a file. void write(File &f, fmt::StringRef s) { std::size_t num_chars_left = s.size(); const char *ptr = s.c_str(); do { std::streamsize count = f.write(ptr, num_chars_left); ptr += count; // We can't write more than size_t bytes since num_chars_left // has type size_t. num_chars_left -= static_cast(count); } while (num_chars_left != 0); } #define EXPECT_READ(file, expected_content) \ EXPECT_EQ(expected_content, read(file, std::strlen(expected_content))) TEST(ErrorCodeTest, Ctor) { EXPECT_EQ(0, ErrorCode().get()); EXPECT_EQ(42, ErrorCode(42).get()); } const char FILE_CONTENT[] = "Don't panic!"; // Opens a file for reading. File open_file() { File read_end, write_end; File::pipe(read_end, write_end); write_end.write(FILE_CONTENT, sizeof(FILE_CONTENT) - 1); write_end.close(); return read_end; } // Opens a buffered file for reading. BufferedFile open_buffered_file(FILE **fp = 0) { File read_end, write_end; File::pipe(read_end, write_end); write_end.write(FILE_CONTENT, sizeof(FILE_CONTENT) - 1); write_end.close(); BufferedFile f = read_end.fdopen("r"); if (fp) *fp = f.get(); return f; } TEST(BufferedFileTest, DefaultCtor) { BufferedFile f; EXPECT_TRUE(f.get() == 0); } TEST(BufferedFileTest, MoveCtor) { BufferedFile bf = open_buffered_file(); FILE *fp = bf.get(); EXPECT_TRUE(fp != 0); BufferedFile bf2(std::move(bf)); EXPECT_EQ(fp, bf2.get()); EXPECT_TRUE(bf.get() == 0); } TEST(BufferedFileTest, MoveAssignment) { BufferedFile bf = open_buffered_file(); FILE *fp = bf.get(); EXPECT_TRUE(fp != 0); BufferedFile bf2; bf2 = std::move(bf); EXPECT_EQ(fp, bf2.get()); EXPECT_TRUE(bf.get() == 0); } TEST(BufferedFileTest, MoveAssignmentClosesFile) { BufferedFile bf = open_buffered_file(); BufferedFile bf2 = open_buffered_file(); int old_fd = bf2.fileno(); bf2 = std::move(bf); EXPECT_TRUE(isclosed(old_fd)); } TEST(BufferedFileTest, MoveFromTemporaryInCtor) { FILE *fp = 0; BufferedFile f(open_buffered_file(&fp)); EXPECT_EQ(fp, f.get()); } TEST(BufferedFileTest, MoveFromTemporaryInAssignment) { FILE *fp = 0; BufferedFile f; f = open_buffered_file(&fp); EXPECT_EQ(fp, f.get()); } TEST(BufferedFileTest, MoveFromTemporaryInAssignmentClosesFile) { BufferedFile f = open_buffered_file(); int old_fd = f.fileno(); f = open_buffered_file(); EXPECT_TRUE(isclosed(old_fd)); } TEST(BufferedFileTest, CloseFileInDtor) { int fd = 0; { BufferedFile f = open_buffered_file(); fd = f.fileno(); } EXPECT_TRUE(isclosed(fd)); } TEST(BufferedFileTest, CloseErrorInDtor) { BufferedFile *f = new BufferedFile(open_buffered_file()); EXPECT_WRITE(stderr, { // The close function must be called inside EXPECT_WRITE, otherwise // the system may recycle closed file descriptor when redirecting the // output in EXPECT_STDERR and the second close will break output // redirection. FMT_POSIX(close(f->fileno())); SUPPRESS_ASSERT(delete f); }, format_system_error(EBADF, "cannot close file") + "\n"); } TEST(BufferedFileTest, Close) { BufferedFile f = open_buffered_file(); int fd = f.fileno(); f.close(); EXPECT_TRUE(f.get() == 0); EXPECT_TRUE(isclosed(fd)); } TEST(BufferedFileTest, CloseError) { BufferedFile f = open_buffered_file(); FMT_POSIX(close(f.fileno())); EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file"); EXPECT_TRUE(f.get() == 0); } TEST(BufferedFileTest, Fileno) { BufferedFile f; // fileno on a null FILE pointer either crashes or returns an error. EXPECT_DEATH({ try { f.fileno(); } catch (fmt::SystemError) { std::exit(1); } }, ""); f = open_buffered_file(); EXPECT_TRUE(f.fileno() != -1); File copy = File::dup(f.fileno()); EXPECT_READ(copy, FILE_CONTENT); } TEST(FileTest, DefaultCtor) { File f; EXPECT_EQ(-1, f.descriptor()); } TEST(FileTest, OpenBufferedFileInCtor) { FILE *fp = fopen("test-file", "w"); std::fputs(FILE_CONTENT, fp); std::fclose(fp); File f("test-file", File::RDONLY); ASSERT_TRUE(isopen(f.descriptor())); } TEST(FileTest, OpenBufferedFileError) { EXPECT_SYSTEM_ERROR(File("nonexistent", File::RDONLY), ENOENT, "cannot open file nonexistent"); } TEST(FileTest, MoveCtor) { File f = open_file(); int fd = f.descriptor(); EXPECT_NE(-1, fd); File f2(std::move(f)); EXPECT_EQ(fd, f2.descriptor()); EXPECT_EQ(-1, f.descriptor()); } TEST(FileTest, MoveAssignment) { File f = open_file(); int fd = f.descriptor(); EXPECT_NE(-1, fd); File f2; f2 = std::move(f); EXPECT_EQ(fd, f2.descriptor()); EXPECT_EQ(-1, f.descriptor()); } TEST(FileTest, MoveAssignmentClosesFile) { File f = open_file(); File f2 = open_file(); int old_fd = f2.descriptor(); f2 = std::move(f); EXPECT_TRUE(isclosed(old_fd)); } File OpenBufferedFile(int &fd) { File f = open_file(); fd = f.descriptor(); return std::move(f); } TEST(FileTest, MoveFromTemporaryInCtor) { int fd = 0xdeadbeef; File f(OpenBufferedFile(fd)); EXPECT_EQ(fd, f.descriptor()); } TEST(FileTest, MoveFromTemporaryInAssignment) { int fd = 0xdeadbeef; File f; f = OpenBufferedFile(fd); EXPECT_EQ(fd, f.descriptor()); } TEST(FileTest, MoveFromTemporaryInAssignmentClosesFile) { int fd = 0xdeadbeef; File f = open_file(); int old_fd = f.descriptor(); f = OpenBufferedFile(fd); EXPECT_TRUE(isclosed(old_fd)); } TEST(FileTest, CloseFileInDtor) { int fd = 0; { File f = open_file(); fd = f.descriptor(); } EXPECT_TRUE(isclosed(fd)); } TEST(FileTest, CloseErrorInDtor) { File *f = new File(open_file()); EXPECT_WRITE(stderr, { // The close function must be called inside EXPECT_WRITE, otherwise // the system may recycle closed file descriptor when redirecting the // output in EXPECT_STDERR and the second close will break output // redirection. FMT_POSIX(close(f->descriptor())); SUPPRESS_ASSERT(delete f); }, format_system_error(EBADF, "cannot close file") + "\n"); } TEST(FileTest, Close) { File f = open_file(); int fd = f.descriptor(); f.close(); EXPECT_EQ(-1, f.descriptor()); EXPECT_TRUE(isclosed(fd)); } TEST(FileTest, CloseError) { File f = open_file(); FMT_POSIX(close(f.descriptor())); EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file"); EXPECT_EQ(-1, f.descriptor()); } TEST(FileTest, Read) { File f = open_file(); EXPECT_READ(f, FILE_CONTENT); } TEST(FileTest, ReadError) { File read_end, write_end; File::pipe(read_end, write_end); char buf; // We intentionally read from write_end to cause error. EXPECT_SYSTEM_ERROR(write_end.read(&buf, 1), EBADF, "cannot read from file"); } TEST(FileTest, Write) { File read_end, write_end; File::pipe(read_end, write_end); write(write_end, "test"); write_end.close(); EXPECT_READ(read_end, "test"); } TEST(FileTest, WriteError) { File read_end, write_end; File::pipe(read_end, write_end); // We intentionally write to read_end to cause error. EXPECT_SYSTEM_ERROR(read_end.write(" ", 1), EBADF, "cannot write to file"); } TEST(FileTest, Dup) { File f = open_file(); File copy = File::dup(f.descriptor()); EXPECT_NE(f.descriptor(), copy.descriptor()); EXPECT_EQ(FILE_CONTENT, read(copy, sizeof(FILE_CONTENT) - 1)); } TEST(FileTest, DupError) { EXPECT_SYSTEM_ERROR_NOASSERT(File::dup(-1), EBADF, "cannot duplicate file descriptor -1"); } TEST(FileTest, Dup2) { File f = open_file(); File copy = open_file(); f.dup2(copy.descriptor()); EXPECT_NE(f.descriptor(), copy.descriptor()); EXPECT_READ(copy, FILE_CONTENT); } TEST(FileTest, Dup2Error) { File f = open_file(); EXPECT_SYSTEM_ERROR_NOASSERT(f.dup2(-1), EBADF, fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor())); } TEST(FileTest, Dup2NoExcept) { File f = open_file(); File copy = open_file(); ErrorCode ec; f.dup2(copy.descriptor(), ec); EXPECT_EQ(0, ec.get()); EXPECT_NE(f.descriptor(), copy.descriptor()); EXPECT_READ(copy, FILE_CONTENT); } TEST(FileTest, Dup2NoExceptError) { File f = open_file(); ErrorCode ec; SUPPRESS_ASSERT(f.dup2(-1, ec)); EXPECT_EQ(EBADF, ec.get()); } TEST(FileTest, Pipe) { File read_end, write_end; File::pipe(read_end, write_end); EXPECT_NE(-1, read_end.descriptor()); EXPECT_NE(-1, write_end.descriptor()); write(write_end, "test"); EXPECT_READ(read_end, "test"); } TEST(FileTest, Fdopen) { File read_end, write_end; File::pipe(read_end, write_end); int read_fd = read_end.descriptor(); EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get()))); } TEST(FileTest, FdopenError) { File f; EXPECT_SYSTEM_ERROR_NOASSERT( f.fdopen("r"), EBADF, "cannot associate stream with file descriptor"); } TEST(OutputRedirectTest, ScopedRedirect) { File read_end, write_end; File::pipe(read_end, write_end); { BufferedFile file(write_end.fdopen("w")); std::fprintf(file.get(), "[[["); { OutputRedirect redir(file.get()); std::fprintf(file.get(), "censored"); } std::fprintf(file.get(), "]]]"); } EXPECT_READ(read_end, "[[[]]]"); } // Test that OutputRedirect handles errors in flush correctly. TEST(OutputRedirectTest, FlushErrorInCtor) { File read_end, write_end; File::pipe(read_end, write_end); int write_fd = write_end.descriptor(); File write_copy = write_end.dup(write_fd); BufferedFile f = write_end.fdopen("w"); // Put a character in a file buffer. EXPECT_EQ('x', fputc('x', f.get())); FMT_POSIX(close(write_fd)); OutputRedirect *redir = 0; EXPECT_SYSTEM_ERROR_NOASSERT(redir = new OutputRedirect(f.get()), EBADF, "cannot flush stream"); delete redir; write_copy.dup2(write_fd); // "undo" close or dtor will fail } TEST(OutputRedirectTest, DupErrorInCtor) { BufferedFile f = open_buffered_file(); int fd = f.fileno(); File copy = File::dup(fd); FMT_POSIX(close(fd)); OutputRedirect *redir = 0; EXPECT_SYSTEM_ERROR_NOASSERT(redir = new OutputRedirect(f.get()), EBADF, fmt::format("cannot duplicate file descriptor {}", fd)); copy.dup2(fd); // "undo" close or dtor will fail delete redir; } TEST(OutputRedirectTest, RestoreAndRead) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile file(write_end.fdopen("w")); std::fprintf(file.get(), "[[["); OutputRedirect redir(file.get()); std::fprintf(file.get(), "censored"); EXPECT_EQ("censored", redir.restore_and_read()); EXPECT_EQ("", redir.restore_and_read()); std::fprintf(file.get(), "]]]"); file = BufferedFile(); EXPECT_READ(read_end, "[[[]]]"); } // Test that OutputRedirect handles errors in flush correctly. TEST(OutputRedirectTest, FlushErrorInRestoreAndRead) { File read_end, write_end; File::pipe(read_end, write_end); int write_fd = write_end.descriptor(); File write_copy = write_end.dup(write_fd); BufferedFile f = write_end.fdopen("w"); OutputRedirect redir(f.get()); // Put a character in a file buffer. EXPECT_EQ('x', fputc('x', f.get())); FMT_POSIX(close(write_fd)); EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(), EBADF, "cannot flush stream"); write_copy.dup2(write_fd); // "undo" close or dtor will fail } TEST(OutputRedirectTest, ErrorInDtor) { File read_end, write_end; File::pipe(read_end, write_end); int write_fd = write_end.descriptor(); File write_copy = write_end.dup(write_fd); BufferedFile f = write_end.fdopen("w"); OutputRedirect *redir = new OutputRedirect(f.get()); // Put a character in a file buffer. EXPECT_EQ('x', fputc('x', f.get())); EXPECT_WRITE(stderr, { // The close function must be called inside EXPECT_WRITE, otherwise // the system may recycle closed file descriptor when redirecting the // output in EXPECT_STDERR and the second close will break output // redirection. FMT_POSIX(close(write_fd)); SUPPRESS_ASSERT(delete redir); }, format_system_error(EBADF, "cannot flush stream")); write_copy.dup2(write_fd); // "undo" close or dtor of BufferedFile will fail } #endif // FMT_USE_FILE_DESCRIPTORS } // namespace cppformat-1.1.0/test/gtest-extra.cc000066400000000000000000000060661247635332500172630ustar00rootroot00000000000000/* Custom Google Test assertions. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gtest-extra.h" #if FMT_USE_FILE_DESCRIPTORS using fmt::File; void OutputRedirect::flush() { #if EOF != -1 # error "FMT_RETRY assumes return value of -1 indicating failure" #endif int result = 0; FMT_RETRY(result, fflush(file_)); if (result != 0) throw fmt::SystemError(errno, "cannot flush stream"); } void OutputRedirect::restore() { if (original_.descriptor() == -1) return; // Already restored. flush(); // Restore the original file. original_.dup2(FMT_POSIX(fileno(file_))); original_.close(); } OutputRedirect::OutputRedirect(FILE *file) : file_(file) { flush(); int fd = FMT_POSIX(fileno(file)); // Create a File object referring to the original file. original_ = File::dup(fd); // Create a pipe. File write_end; File::pipe(read_end_, write_end); // Connect the passed FILE object to the write end of the pipe. write_end.dup2(fd); } OutputRedirect::~OutputRedirect() FMT_NOEXCEPT { try { restore(); } catch (const std::exception &e) { std::fputs(e.what(), stderr); } } std::string OutputRedirect::restore_and_read() { // Restore output. restore(); // Read everything from the pipe. std::string content; if (read_end_.descriptor() == -1) return content; // Already read. enum { BUFFER_SIZE = 4096 }; char buffer[BUFFER_SIZE]; std::streamsize count = 0; do { count = read_end_.read(buffer, BUFFER_SIZE); content.append(buffer, static_cast(count)); } while (count != 0); read_end_.close(); return content; } #endif // FMT_USE_FILE_DESCRIPTORS std::string format_system_error(int error_code, fmt::StringRef message) { fmt::MemoryWriter out; fmt::internal::format_system_error(out, error_code, message); return out.str(); } cppformat-1.1.0/test/gtest-extra.h000066400000000000000000000123151247635332500171170ustar00rootroot00000000000000/* Custom Google Test assertions. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FMT_GTEST_EXTRA_H_ #define FMT_GTEST_EXTRA_H_ #include #include #include "format.h" #ifndef FMT_USE_FILE_DESCRIPTORS # define FMT_USE_FILE_DESCRIPTORS 0 #endif #if FMT_USE_FILE_DESCRIPTORS # include "posix.h" #endif #define FMT_TEST_THROW_(statement, expected_exception, expected_message, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \ std::string gtest_expected_message = expected_message; \ bool gtest_caught_expected = false; \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (expected_exception const& e) { \ if (gtest_expected_message != e.what()) { \ gtest_ar \ << #statement " throws an exception with a different message.\n" \ << "Expected: " << gtest_expected_message << "\n" \ << " Actual: " << e.what(); \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ gtest_caught_expected = true; \ } \ catch (...) { \ gtest_ar << \ "Expected: " #statement " throws an exception of type " \ #expected_exception ".\n Actual: it throws a different type."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ if (!gtest_caught_expected) { \ gtest_ar << \ "Expected: " #statement " throws an exception of type " \ #expected_exception ".\n Actual: it throws nothing."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ fail(gtest_ar.failure_message()) // Tests that the statement throws the expected exception and the exception's // what() method returns expected message. #define EXPECT_THROW_MSG(statement, expected_exception, expected_message) \ FMT_TEST_THROW_(statement, expected_exception, \ expected_message, GTEST_NONFATAL_FAILURE_) std::string format_system_error(int error_code, fmt::StringRef message); #define EXPECT_SYSTEM_ERROR(statement, error_code, message) \ EXPECT_THROW_MSG(statement, fmt::SystemError, \ format_system_error(error_code, message)) #if FMT_USE_FILE_DESCRIPTORS // Captures file output by redirecting it to a pipe. // The output it can handle is limited by the pipe capacity. class OutputRedirect { private: FILE *file_; fmt::File original_; // Original file passed to redirector. fmt::File read_end_; // Read end of the pipe where the output is redirected. GTEST_DISALLOW_COPY_AND_ASSIGN_(OutputRedirect); void flush(); void restore(); public: explicit OutputRedirect(FILE *file); ~OutputRedirect() FMT_NOEXCEPT; // Restores the original file, reads output from the pipe into a string // and returns it. std::string restore_and_read(); }; #define FMT_TEST_WRITE_(statement, expected_output, file, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \ std::string gtest_expected_output = expected_output; \ OutputRedirect gtest_redir(file); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ std::string gtest_output = gtest_redir.restore_and_read(); \ if (gtest_output != gtest_expected_output) { \ gtest_ar \ << #statement " produces different output.\n" \ << "Expected: " << gtest_expected_output << "\n" \ << " Actual: " << gtest_output; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ fail(gtest_ar.failure_message()) // Tests that the statement writes the expected output to file. #define EXPECT_WRITE(file, statement, expected_output) \ FMT_TEST_WRITE_(statement, expected_output, file, GTEST_NONFATAL_FAILURE_) #endif // FMT_USE_FILE_DESCRIPTORS #endif // FMT_GTEST_EXTRA_H_ cppformat-1.1.0/test/header-only-test.cc000066400000000000000000000025461247635332500201770ustar00rootroot00000000000000/* Header-only configuration test Copyright (c) 2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "format.h" cppformat-1.1.0/test/header-only-test2.cc000066400000000000000000000026121247635332500202530ustar00rootroot00000000000000/* Additional translation unit for the header-only configuration test Copyright (c) 2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "format.h" cppformat-1.1.0/test/macro-test.cc000066400000000000000000000066071247635332500170730ustar00rootroot00000000000000/* Tests of variadic function emulation macros. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include "format.h" #define IDENTITY(x) x TEST(UtilTest, Gen) { int values[] = {FMT_GEN(10, IDENTITY)}; for (int i = 0; i < 10; ++i) EXPECT_EQ(i, values[i]); } #define MAKE_PAIR(x, y) std::make_pair(x, y) TEST(UtilTest, ForEach) { std::pair values[] = { FMT_FOR_EACH10(MAKE_PAIR, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j') }; for (int i = 0; i < 10; ++i) { EXPECT_EQ('a' + i, values[i].first); EXPECT_EQ(i, values[i].second); } } TEST(UtilTest, NArg) { EXPECT_EQ(1, FMT_NARG(a)); EXPECT_EQ(2, FMT_NARG(a, b)); EXPECT_EQ(3, FMT_NARG(a, b, c)); EXPECT_EQ(4, FMT_NARG(a, b, c, d)); EXPECT_EQ(5, FMT_NARG(a, b, c, d, e)); EXPECT_EQ(6, FMT_NARG(a, b, c, d, e, f)); EXPECT_EQ(7, FMT_NARG(a, b, c, d, e, f, g)); EXPECT_EQ(8, FMT_NARG(a, b, c, d, e, f, g, h)); EXPECT_EQ(9, FMT_NARG(a, b, c, d, e, f, g, h, i)); EXPECT_EQ(10, FMT_NARG(a, b, c, d, e, f, g, h, i, j)); } int result; #define MAKE_TEST(func) \ void func(const char *format, const fmt::ArgList &args) { \ result = 0; \ for (unsigned i = 0; args[i].type; ++i) \ result += args[i].int_value; \ } MAKE_TEST(test_func) typedef char Char; FMT_WRAP1(test_func, const char *, 1) TEST(UtilTest, Wrap1) { result = 0; test_func("", 42); EXPECT_EQ(42, result); } MAKE_TEST(test_variadic_void) FMT_VARIADIC_VOID(test_variadic_void, const char *) TEST(UtilTest, VariadicVoid) { result = 0; test_variadic_void("", 10, 20, 30, 40, 50, 60, 70, 80, 90, 100); EXPECT_EQ(550, result); } template struct S {}; #define GET_TYPE(n) S int test_variadic(FMT_GEN(10, GET_TYPE), const fmt::ArgList &args) { \ int result = 0; \ for (std::size_t i = 0; args[i].type; ++i) \ result += args[i].int_value; \ return result; } FMT_VARIADIC(int, test_variadic, S<0>, S<1>, S<2>, S<3>, S<4>, S<5>, S<6>, S<7>, S<8>, S<9>) #define MAKE_ARG(n) S() TEST(UtilTest, Variadic) { EXPECT_EQ(550, test_variadic(FMT_GEN(10, MAKE_ARG), 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)); } cppformat-1.1.0/test/mock-allocator.h000066400000000000000000000051001247635332500175510ustar00rootroot00000000000000/* Mock allocator. Copyright (c) 2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FMT_MOCK_ALLOCATOR_H_ #define FMT_MOCK_ALLOCATOR_H_ #include "gmock/gmock.h" template class MockAllocator { public: MockAllocator() {} MockAllocator(const MockAllocator &) {} typedef T value_type; MOCK_METHOD1_T(allocate, T* (std::size_t n)); MOCK_METHOD2_T(deallocate, void (T* p, std::size_t n)); }; template class AllocatorRef { private: Allocator *alloc_; public: typedef typename Allocator::value_type value_type; explicit AllocatorRef(Allocator *alloc = 0) : alloc_(alloc) {} AllocatorRef(const AllocatorRef &other) : alloc_(other.alloc_) {} AllocatorRef& operator=(const AllocatorRef &other) { alloc_ = other.alloc_; return *this; } #if FMT_USE_RVALUE_REFERENCES private: void move(AllocatorRef &other) { alloc_ = other.alloc_; other.alloc_ = 0; } public: AllocatorRef(AllocatorRef &&other) { move(other); } AllocatorRef& operator=(AllocatorRef &&other) { assert(this != &other); move(other); return *this; } #endif Allocator *get() const { return alloc_; } value_type* allocate(std::size_t n) { return alloc_->allocate(n); } void deallocate(value_type* p, std::size_t n) { alloc_->deallocate(p, n); } }; #endif // FMT_MOCK_ALLOCATOR_H_ cppformat-1.1.0/test/posix-test.cc000066400000000000000000000266031247635332500171320ustar00rootroot00000000000000/* Test wrappers around POSIX functions. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Disable bogus MSVC warnings. #define _CRT_SECURE_NO_WARNINGS #include "posix-test.h" #include #include #include #ifdef _WIN32 # include # undef max # undef ERROR #endif #include "gtest-extra.h" using fmt::BufferedFile; using fmt::ErrorCode; using fmt::File; namespace { int open_count; int close_count; int dup_count; int dup2_count; int fdopen_count; int read_count; int write_count; int pipe_count; int fopen_count; int fclose_count; int fileno_count; std::size_t read_nbyte; std::size_t write_nbyte; bool sysconf_error; enum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim; } #define EMULATE_EINTR(func, error_result) \ if (func##_count != 0) { \ if (func##_count++ != 3) { \ errno = EINTR; \ return error_result; \ } \ } #ifndef _WIN32 int test::open(const char *path, int oflag, int mode) { EMULATE_EINTR(open, -1); return ::open(path, oflag, mode); } static off_t max_file_size() { return std::numeric_limits::max(); } int test::fstat(int fd, struct stat *buf) { int result = ::fstat(fd, buf); if (fstat_sim == MAX_SIZE) buf->st_size = max_file_size(); return result; } long test::sysconf(int name) { long result = ::sysconf(name); if (!sysconf_error) return result; // Simulate an error. errno = EINVAL; return -1; } #else errno_t test::sopen_s( int* pfh, const char *filename, int oflag, int shflag, int pmode) { EMULATE_EINTR(open, EINTR); return _sopen_s(pfh, filename, oflag, shflag, pmode); } static LONGLONG max_file_size() { return std::numeric_limits::max(); } BOOL test::GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize) { if (fstat_sim == ERROR) { SetLastError(ERROR_ACCESS_DENIED); return FALSE; } BOOL result = ::GetFileSizeEx(hFile, lpFileSize); if (fstat_sim == MAX_SIZE) lpFileSize->QuadPart = max_file_size(); return result; } #endif int test::close(int fildes) { // Close the file first because close shouldn't be retried. int result = ::FMT_POSIX(close(fildes)); EMULATE_EINTR(close, -1); return result; } int test::dup(int fildes) { EMULATE_EINTR(dup, -1); return ::FMT_POSIX(dup(fildes)); } int test::dup2(int fildes, int fildes2) { EMULATE_EINTR(dup2, -1); return ::FMT_POSIX(dup2(fildes, fildes2)); } FILE *test::fdopen(int fildes, const char *mode) { EMULATE_EINTR(fdopen, 0); return ::FMT_POSIX(fdopen(fildes, mode)); } test::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) { read_nbyte = nbyte; EMULATE_EINTR(read, -1); return ::FMT_POSIX(read(fildes, buf, nbyte)); } test::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) { write_nbyte = nbyte; EMULATE_EINTR(write, -1); return ::FMT_POSIX(write(fildes, buf, nbyte)); } #ifndef _WIN32 int test::pipe(int fildes[2]) { EMULATE_EINTR(pipe, -1); return ::pipe(fildes); } #else int test::pipe(int *pfds, unsigned psize, int textmode) { EMULATE_EINTR(pipe, -1); return _pipe(pfds, psize, textmode); } #endif FILE *test::fopen(const char *filename, const char *mode) { EMULATE_EINTR(fopen, 0); return ::fopen(filename, mode); } int test::fclose(FILE *stream) { EMULATE_EINTR(fclose, EOF); return ::fclose(stream); } int test::fileno(FILE *stream) { EMULATE_EINTR(fileno, -1); return ::FMT_POSIX(fileno(stream)); } #ifndef _WIN32 # define EXPECT_RETRY(statement, func, message) \ func##_count = 1; \ statement; \ EXPECT_EQ(4, func##_count); \ func##_count = 0; # define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual) #else # define EXPECT_RETRY(statement, func, message) \ func##_count = 1; \ EXPECT_SYSTEM_ERROR(statement, EINTR, message); \ func##_count = 0; # define EXPECT_EQ_POSIX(expected, actual) #endif void write_file(fmt::StringRef filename, fmt::StringRef content) { fmt::BufferedFile f(filename, "w"); f.print("{}", content); } TEST(UtilTest, StaticAssert) { FMT_STATIC_ASSERT(true, "success"); // Static assertion failure is tested in compile-test because it causes // a compile-time error. } TEST(UtilTest, GetPageSize) { #ifdef _WIN32 SYSTEM_INFO si = {}; GetSystemInfo(&si); EXPECT_EQ(si.dwPageSize, fmt::getpagesize()); #else EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize()); sysconf_error = true; EXPECT_SYSTEM_ERROR( fmt::getpagesize(), EINVAL, "cannot get memory page size"); sysconf_error = false; #endif } TEST(FileTest, OpenRetry) { write_file("test", "there must be something here"); File *f = 0; EXPECT_RETRY(f = new File("test", File::RDONLY), open, "cannot open file test"); #ifndef _WIN32 char c = 0; f->read(&c, 1); #endif delete f; } TEST(FileTest, CloseNoRetryInDtor) { File read_end, write_end; File::pipe(read_end, write_end); File *f = new File(std::move(read_end)); int saved_close_count = 0; EXPECT_WRITE(stderr, { close_count = 1; delete f; saved_close_count = close_count; close_count = 0; }, format_system_error(EINTR, "cannot close file") + "\n"); EXPECT_EQ(2, saved_close_count); } TEST(FileTest, CloseNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); close_count = 1; EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file"); EXPECT_EQ(2, close_count); close_count = 0; } TEST(FileTest, Size) { std::string content = "top secret, destroy before reading"; write_file("test", content); File f("test", File::RDONLY); EXPECT_GE(f.size(), 0); fmt::ULongLong file_size = f.size(); EXPECT_EQ(content.size(), file_size); #ifdef _WIN32 fmt::MemoryWriter message; fmt::internal::format_windows_error( message, ERROR_ACCESS_DENIED, "cannot get file size"); fstat_sim = ERROR; EXPECT_THROW_MSG(f.size(), fmt::WindowsError, message.str()); fstat_sim = NONE; #else f.close(); EXPECT_SYSTEM_ERROR(f.size(), EBADF, "cannot get file attributes"); #endif } TEST(FileTest, MaxSize) { write_file("test", ""); File f("test", File::RDONLY); fstat_sim = MAX_SIZE; EXPECT_GE(f.size(), 0); EXPECT_EQ(max_file_size(), f.size()); fstat_sim = NONE; } TEST(FileTest, ReadRetry) { File read_end, write_end; File::pipe(read_end, write_end); enum { SIZE = 4 }; write_end.write("test", SIZE); write_end.close(); char buffer[SIZE]; std::streamsize count = 0; EXPECT_RETRY(count = read_end.read(buffer, SIZE), read, "cannot read from file"); EXPECT_EQ_POSIX(static_cast(SIZE), count); } TEST(FileTest, WriteRetry) { File read_end, write_end; File::pipe(read_end, write_end); enum { SIZE = 4 }; std::streamsize count = 0; EXPECT_RETRY(count = write_end.write("test", SIZE), write, "cannot write to file"); write_end.close(); #ifndef _WIN32 EXPECT_EQ(static_cast(SIZE), count); char buffer[SIZE + 1]; read_end.read(buffer, SIZE); buffer[SIZE] = '\0'; EXPECT_STREQ("test", buffer); #endif } #ifdef _WIN32 TEST(FileTest, ConvertReadCount) { File read_end, write_end; File::pipe(read_end, write_end); char c; std::size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(std::size_t)) ++size; read_count = 1; read_nbyte = 0; EXPECT_THROW(read_end.read(&c, size), fmt::SystemError); read_count = 0; EXPECT_EQ(UINT_MAX, read_nbyte); } TEST(FileTest, ConvertWriteCount) { File read_end, write_end; File::pipe(read_end, write_end); char c; std::size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(std::size_t)) ++size; write_count = 1; write_nbyte = 0; EXPECT_THROW(write_end.write(&c, size), fmt::SystemError); write_count = 0; EXPECT_EQ(UINT_MAX, write_nbyte); } #endif TEST(FileTest, DupNoRetry) { int stdout_fd = FMT_POSIX(fileno(stdout)); dup_count = 1; EXPECT_SYSTEM_ERROR(File::dup(stdout_fd), EINTR, fmt::format("cannot duplicate file descriptor {}", stdout_fd)); dup_count = 0; } TEST(FileTest, Dup2Retry) { int stdout_fd = FMT_POSIX(fileno(stdout)); File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd); EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2, fmt::format("cannot duplicate file descriptor {} to {}", f1.descriptor(), f2.descriptor())); } TEST(FileTest, Dup2NoExceptRetry) { int stdout_fd = FMT_POSIX(fileno(stdout)); File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd); ErrorCode ec; dup2_count = 1; f1.dup2(f2.descriptor(), ec); #ifndef _WIN32 EXPECT_EQ(4, dup2_count); #else EXPECT_EQ(EINTR, ec.get()); #endif dup2_count = 0; } TEST(FileTest, PipeNoRetry) { File read_end, write_end; pipe_count = 1; EXPECT_SYSTEM_ERROR( File::pipe(read_end, write_end), EINTR, "cannot create pipe"); pipe_count = 0; } TEST(FileTest, FdopenNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); fdopen_count = 1; EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR, "cannot associate stream with file descriptor"); fdopen_count = 0; } TEST(BufferedFileTest, OpenRetry) { write_file("test", "there must be something here"); BufferedFile *f = 0; EXPECT_RETRY(f = new BufferedFile("test", "r"), fopen, "cannot open file test"); #ifndef _WIN32 char c = 0; if (fread(&c, 1, 1, f->get()) < 1) throw fmt::SystemError(errno, "fread failed"); #endif delete f; } TEST(BufferedFileTest, CloseNoRetryInDtor) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile *f = new BufferedFile(read_end.fdopen("r")); int saved_fclose_count = 0; EXPECT_WRITE(stderr, { fclose_count = 1; delete f; saved_fclose_count = fclose_count; fclose_count = 0; }, format_system_error(EINTR, "cannot close file") + "\n"); EXPECT_EQ(2, saved_fclose_count); } TEST(BufferedFileTest, CloseNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile f = read_end.fdopen("r"); fclose_count = 1; EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file"); EXPECT_EQ(2, fclose_count); fclose_count = 0; } TEST(BufferedFileTest, FilenoNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile f = read_end.fdopen("r"); fileno_count = 1; EXPECT_SYSTEM_ERROR(f.fileno(), EINTR, "cannot get file descriptor"); EXPECT_EQ(2, fileno_count); fileno_count = 0; } cppformat-1.1.0/test/posix-test.h000066400000000000000000000046771247635332500170030ustar00rootroot00000000000000/* Test wrappers around POSIX functions. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FMT_POSIX_TEST_H #define FMT_POSIX_TEST_H #include #include #ifndef _WIN32 struct stat; #else # include #endif namespace test { #ifndef _WIN32 // Size type for read and write. typedef size_t size_t; typedef ssize_t ssize_t; int open(const char *path, int oflag, int mode); int fstat(int fd, struct stat *buf); long sysconf(int name); #else typedef unsigned size_t; typedef int ssize_t; errno_t sopen_s( int* pfh, const char *filename, int oflag, int shflag, int pmode); BOOL GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize); #endif int close(int fildes); int dup(int fildes); int dup2(int fildes, int fildes2); FILE *fdopen(int fildes, const char *mode); ssize_t read(int fildes, void *buf, size_t nbyte); ssize_t write(int fildes, const void *buf, size_t nbyte); #ifndef _WIN32 int pipe(int fildes[2]); #else int pipe(int *pfds, unsigned psize, int textmode); #endif FILE *fopen(const char *filename, const char *mode); int fclose(FILE *stream); int fileno(FILE *stream); } // namespace test #define FMT_SYSTEM(call) test::call #endif // FMT_POSIX_TEST_H cppformat-1.1.0/test/printf-test.cc000066400000000000000000000363461247635332500172770ustar00rootroot00000000000000/* printf tests. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include "format.h" #include "gtest-extra.h" #include "util.h" using fmt::format; using fmt::FormatError; const unsigned BIG_NUM = INT_MAX + 1u; // Makes format string argument positional. std::string make_positional(fmt::StringRef format) { std::string s(format); s.replace(s.find('%'), 1, "%1$"); return s; } #define EXPECT_PRINTF(expected_output, format, arg) \ EXPECT_EQ(expected_output, fmt::sprintf(format, arg)) \ << "format: " << format; \ EXPECT_EQ(expected_output, fmt::sprintf(make_positional(format), arg)) TEST(PrintfTest, NoArgs) { EXPECT_EQ("test", fmt::sprintf("test")); } TEST(PrintfTest, Escape) { EXPECT_EQ("%", fmt::sprintf("%%")); EXPECT_EQ("before %", fmt::sprintf("before %%")); EXPECT_EQ("% after", fmt::sprintf("%% after")); EXPECT_EQ("before % after", fmt::sprintf("before %% after")); EXPECT_EQ("%s", fmt::sprintf("%%s")); } TEST(PrintfTest, PositionalArgs) { EXPECT_EQ("42", fmt::sprintf("%1$d", 42)); EXPECT_EQ("before 42", fmt::sprintf("before %1$d", 42)); EXPECT_EQ("42 after", fmt::sprintf("%1$d after",42)); EXPECT_EQ("before 42 after", fmt::sprintf("before %1$d after", 42)); EXPECT_EQ("answer = 42", fmt::sprintf("%1$s = %2$d", "answer", 42)); EXPECT_EQ("42 is the answer", fmt::sprintf("%2$d is the %1$s", "answer", 42)); EXPECT_EQ("abracadabra", fmt::sprintf("%1$s%2$s%1$s", "abra", "cad")); } TEST(PrintfTest, AutomaticArgIndexing) { EXPECT_EQ("abc", fmt::sprintf("%c%c%c", 'a', 'b', 'c')); } TEST(PrintfTest, NumberIsTooBigInArgIndex) { EXPECT_THROW_MSG(fmt::sprintf(format("%{}$", BIG_NUM)), FormatError, "number is too big"); EXPECT_THROW_MSG(fmt::sprintf(format("%{}$d", BIG_NUM)), FormatError, "number is too big"); } TEST(PrintfTest, SwitchArgIndexing) { EXPECT_THROW_MSG(fmt::sprintf("%1$d%", 1, 2), FormatError, "invalid format string"); EXPECT_THROW_MSG(fmt::sprintf(format("%1$d%{}d", BIG_NUM), 1, 2), FormatError, "number is too big"); EXPECT_THROW_MSG(fmt::sprintf("%1$d%d", 1, 2), FormatError, "cannot switch from manual to automatic argument indexing"); EXPECT_THROW_MSG(fmt::sprintf("%d%1$", 1, 2), FormatError, "invalid format string"); EXPECT_THROW_MSG(fmt::sprintf(format("%d%{}$d", BIG_NUM), 1, 2), FormatError, "number is too big"); EXPECT_THROW_MSG(fmt::sprintf("%d%1$d", 1, 2), FormatError, "cannot switch from automatic to manual argument indexing"); // Indexing errors override width errors. EXPECT_THROW_MSG(fmt::sprintf(format("%d%1${}d", BIG_NUM), 1, 2), FormatError, "number is too big"); EXPECT_THROW_MSG(fmt::sprintf(format("%1$d%{}d", BIG_NUM), 1, 2), FormatError, "number is too big"); } TEST(PrintfTest, InvalidArgIndex) { EXPECT_THROW_MSG(fmt::sprintf("%0$d", 42), FormatError, "argument index out of range"); EXPECT_THROW_MSG(fmt::sprintf("%2$d", 42), FormatError, "argument index out of range"); EXPECT_THROW_MSG(fmt::sprintf(format("%{}$d", INT_MAX), 42), FormatError, "argument index out of range"); EXPECT_THROW_MSG(fmt::sprintf("%2$", 42), FormatError, "invalid format string"); EXPECT_THROW_MSG(fmt::sprintf(format("%{}$d", BIG_NUM), 42), FormatError, "number is too big"); } TEST(PrintfTest, DefaultAlignRight) { EXPECT_PRINTF(" 42", "%5d", 42); EXPECT_PRINTF(" abc", "%5s", "abc"); } TEST(PrintfTest, ZeroFlag) { EXPECT_PRINTF("00042", "%05d", 42); EXPECT_PRINTF("-0042", "%05d", -42); EXPECT_PRINTF("00042", "%05d", 42); EXPECT_PRINTF("-0042", "%05d", -42); EXPECT_PRINTF("-004.2", "%06g", -4.2); EXPECT_PRINTF("+00042", "%00+6d", 42); // '0' flag is ignored for non-numeric types. EXPECT_PRINTF(" x", "%05c", 'x'); } TEST(PrintfTest, PlusFlag) { EXPECT_PRINTF("+42", "%+d", 42); EXPECT_PRINTF("-42", "%+d", -42); EXPECT_PRINTF("+0042", "%+05d", 42); EXPECT_PRINTF("+0042", "%0++5d", 42); // '+' flag is ignored for non-numeric types. EXPECT_PRINTF("x", "%+c", 'x'); } TEST(PrintfTest, MinusFlag) { EXPECT_PRINTF("abc ", "%-5s", "abc"); EXPECT_PRINTF("abc ", "%0--5s", "abc"); } TEST(PrintfTest, SpaceFlag) { EXPECT_PRINTF(" 42", "% d", 42); EXPECT_PRINTF("-42", "% d", -42); EXPECT_PRINTF(" 0042", "% 05d", 42); EXPECT_PRINTF(" 0042", "%0 5d", 42); // ' ' flag is ignored for non-numeric types. EXPECT_PRINTF("x", "% c", 'x'); } TEST(PrintfTest, HashFlag) { EXPECT_PRINTF("042", "%#o", 042); EXPECT_PRINTF(fmt::format("0{:o}", static_cast(-042)), "%#o", -042); EXPECT_PRINTF("0", "%#o", 0); EXPECT_PRINTF("0x42", "%#x", 0x42); EXPECT_PRINTF("0X42", "%#X", 0x42); EXPECT_PRINTF( fmt::format("0x{:x}", static_cast(-0x42)), "%#x", -0x42); EXPECT_PRINTF("0", "%#x", 0); EXPECT_PRINTF("0x0042", "%#06x", 0x42); EXPECT_PRINTF("0x0042", "%0##6x", 0x42); EXPECT_PRINTF("-42.000000", "%#f", -42.0); EXPECT_PRINTF("-42.000000", "%#F", -42.0); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "%#e", -42.0); EXPECT_PRINTF(buffer, "%#e", -42.0); safe_sprintf(buffer, "%#E", -42.0); EXPECT_PRINTF(buffer, "%#E", -42.0); EXPECT_PRINTF("-42.0000", "%#g", -42.0); EXPECT_PRINTF("-42.0000", "%#G", -42.0); safe_sprintf(buffer, "%#a", 16.0); EXPECT_PRINTF(buffer, "%#a", 16.0); safe_sprintf(buffer, "%#A", 16.0); EXPECT_PRINTF(buffer, "%#A", 16.0); // '#' flag is ignored for non-numeric types. EXPECT_PRINTF("x", "%#c", 'x'); } TEST(PrintfTest, Width) { EXPECT_PRINTF(" abc", "%5s", "abc"); // Width cannot be specified twice. EXPECT_THROW_MSG(fmt::sprintf("%5-5d", 42), FormatError, "unknown format code '-' for integer"); EXPECT_THROW_MSG(fmt::sprintf(format("%{}d", BIG_NUM), 42), FormatError, "number is too big"); EXPECT_THROW_MSG(fmt::sprintf(format("%1${}d", BIG_NUM), 42), FormatError, "number is too big"); } TEST(PrintfTest, DynamicWidth) { EXPECT_EQ(" 42", fmt::sprintf("%*d", 5, 42)); EXPECT_EQ("42 ", fmt::sprintf("%*d", -5, 42)); EXPECT_THROW_MSG(fmt::sprintf("%*d", 5.0, 42), FormatError, "width is not integer"); EXPECT_THROW_MSG(fmt::sprintf("%*d"), FormatError, "argument index out of range"); EXPECT_THROW_MSG(fmt::sprintf("%*d", BIG_NUM, 42), FormatError, "number is too big"); } TEST(PrintfTest, IntPrecision) { EXPECT_PRINTF("00042", "%.5d", 42); EXPECT_PRINTF("-00042", "%.5d", -42); EXPECT_PRINTF("00042", "%.5x", 0x42); EXPECT_PRINTF("0x00042", "%#.5x", 0x42); EXPECT_PRINTF("00042", "%.5o", 042); EXPECT_PRINTF("00042", "%#.5o", 042); EXPECT_PRINTF(" 00042", "%7.5d", 42); EXPECT_PRINTF(" 00042", "%7.5x", 0x42); EXPECT_PRINTF(" 0x00042", "%#10.5x", 0x42); EXPECT_PRINTF(" 00042", "%7.5o", 042); EXPECT_PRINTF(" 00042", "%#10.5o", 042); EXPECT_PRINTF("00042 ", "%-7.5d", 42); EXPECT_PRINTF("00042 ", "%-7.5x", 0x42); EXPECT_PRINTF("0x00042 ", "%-#10.5x", 0x42); EXPECT_PRINTF("00042 ", "%-7.5o", 042); EXPECT_PRINTF("00042 ", "%-#10.5o", 042); } TEST(PrintfTest, FloatPrecision) { char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "%.3e", 1234.5678); EXPECT_PRINTF(buffer, "%.3e", 1234.5678); EXPECT_PRINTF("1234.568", "%.3f", 1234.5678); safe_sprintf(buffer, "%.3g", 1234.5678); EXPECT_PRINTF(buffer, "%.3g", 1234.5678); safe_sprintf(buffer, "%.3a", 1234.5678); EXPECT_PRINTF(buffer, "%.3a", 1234.5678); } TEST(PrintfTest, IgnorePrecisionForNonNumericArg) { EXPECT_PRINTF("abc", "%.5s", "abc"); } TEST(PrintfTest, DynamicPrecision) { EXPECT_EQ("00042", fmt::sprintf("%.*d", 5, 42)); EXPECT_EQ("42", fmt::sprintf("%.*d", -5, 42)); EXPECT_THROW_MSG(fmt::sprintf("%.*d", 5.0, 42), FormatError, "precision is not integer"); EXPECT_THROW_MSG(fmt::sprintf("%.*d"), FormatError, "argument index out of range"); EXPECT_THROW_MSG(fmt::sprintf("%.*d", BIG_NUM, 42), FormatError, "number is too big"); if (sizeof(fmt::LongLong) != sizeof(int)) { fmt::LongLong prec = static_cast(INT_MIN) - 1; EXPECT_THROW_MSG(fmt::sprintf("%.*d", prec, 42), FormatError, "number is too big"); } } template struct MakeSigned { typedef T Type; }; #define SPECIALIZE_MAKE_SIGNED(T, S) \ template <> \ struct MakeSigned { typedef S Type; } SPECIALIZE_MAKE_SIGNED(char, signed char); SPECIALIZE_MAKE_SIGNED(unsigned char, signed char); SPECIALIZE_MAKE_SIGNED(unsigned short, short); SPECIALIZE_MAKE_SIGNED(unsigned, int); SPECIALIZE_MAKE_SIGNED(unsigned long, long); SPECIALIZE_MAKE_SIGNED(fmt::ULongLong, fmt::LongLong); template void TestLength(const char *length_spec, U value) { fmt::LongLong signed_value = value; fmt::ULongLong unsigned_value = value; // Apply integer promotion to the argument. fmt::ULongLong max = std::numeric_limits::max(); if (max <= static_cast(std::numeric_limits::max())) { signed_value = static_cast(value); unsigned_value = static_cast(value); } else if (max <= std::numeric_limits::max()) { signed_value = static_cast(value); unsigned_value = static_cast(value); } using fmt::internal::MakeUnsigned; if (sizeof(U) <= sizeof(int) && sizeof(int) < sizeof(T)) { signed_value = unsigned_value = static_cast::Type>(value); } else { signed_value = static_cast::Type>(value); unsigned_value = static_cast::Type>(value); } std::ostringstream os; os << signed_value; EXPECT_PRINTF(os.str(), fmt::format("%{}d", length_spec), value); EXPECT_PRINTF(os.str(), fmt::format("%{}i", length_spec), value); os.str(""); os << unsigned_value; EXPECT_PRINTF(os.str(), fmt::format("%{}u", length_spec), value); os.str(""); os << std::oct << unsigned_value; EXPECT_PRINTF(os.str(), fmt::format("%{}o", length_spec), value); os.str(""); os << std::hex << unsigned_value; EXPECT_PRINTF(os.str(), fmt::format("%{}x", length_spec), value); os.str(""); os << std::hex << std::uppercase << unsigned_value; EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value); } template void TestLength(const char *length_spec) { T min = std::numeric_limits::min(), max = std::numeric_limits::max(); TestLength(length_spec, 42); TestLength(length_spec, -42); TestLength(length_spec, min); TestLength(length_spec, max); if (min >= 0 || static_cast(min) > std::numeric_limits::min()) { TestLength(length_spec, fmt::LongLong(min) - 1); } fmt::ULongLong long_long_max = std::numeric_limits::max(); if (max < 0 || static_cast(max) < long_long_max) TestLength(length_spec, fmt::LongLong(max) + 1); TestLength(length_spec, std::numeric_limits::min()); TestLength(length_spec, std::numeric_limits::max()); TestLength(length_spec, std::numeric_limits::min()); TestLength(length_spec, std::numeric_limits::max()); TestLength(length_spec, std::numeric_limits::min()); TestLength(length_spec, std::numeric_limits::max()); TestLength(length_spec, std::numeric_limits::min()); TestLength(length_spec, std::numeric_limits::max()); TestLength(length_spec, std::numeric_limits::min()); TestLength(length_spec, std::numeric_limits::max()); } TEST(PrintfTest, Length) { TestLength("hh"); TestLength("hh"); TestLength("hh"); TestLength("h"); TestLength("h"); TestLength("l"); TestLength("l"); TestLength("ll"); TestLength("ll"); TestLength("j"); TestLength("z"); TestLength("t"); long double max = std::numeric_limits::max(); EXPECT_PRINTF(fmt::format("{}", max), "%g", max); EXPECT_PRINTF(fmt::format("{}", max), "%Lg", max); } TEST(PrintfTest, Int) { EXPECT_PRINTF("-42", "%d", -42); EXPECT_PRINTF("-42", "%i", -42); unsigned u = -42; EXPECT_PRINTF(fmt::format("{}", u), "%u", -42); EXPECT_PRINTF(fmt::format("{:o}", u), "%o", -42); EXPECT_PRINTF(fmt::format("{:x}", u), "%x", -42); EXPECT_PRINTF(fmt::format("{:X}", u), "%X", -42); } TEST(PrintfTest, Float) { EXPECT_PRINTF("392.650000", "%f", 392.65); EXPECT_PRINTF("392.650000", "%F", 392.65); char buffer[BUFFER_SIZE]; safe_sprintf(buffer, "%e", 392.65); EXPECT_PRINTF(buffer, "%e", 392.65); safe_sprintf(buffer, "%E", 392.65); EXPECT_PRINTF(buffer, "%E", 392.65); EXPECT_PRINTF("392.65", "%g", 392.65); EXPECT_PRINTF("392.65", "%G", 392.65); safe_sprintf(buffer, "%a", -392.65); EXPECT_EQ(buffer, format("{:a}", -392.65)); safe_sprintf(buffer, "%A", -392.65); EXPECT_EQ(buffer, format("{:A}", -392.65)); } TEST(PrintfTest, Inf) { double inf = std::numeric_limits::infinity(); for (const char* type = "fega"; *type; ++type) { EXPECT_PRINTF("inf", fmt::format("%{}", *type), inf); char upper = std::toupper(*type); EXPECT_PRINTF("INF", fmt::format("%{}", upper), inf); } } TEST(PrintfTest, Char) { EXPECT_PRINTF("x", "%c", 'x'); int max = std::numeric_limits::max(); EXPECT_PRINTF(fmt::format("{}", static_cast(max)), "%c", max); //EXPECT_PRINTF("x", "%lc", L'x'); // TODO: test wchar_t } TEST(PrintfTest, String) { EXPECT_PRINTF("abc", "%s", "abc"); // TODO: wide string } TEST(PrintfTest, Pointer) { int n; void *p = &n; EXPECT_PRINTF(fmt::format("{}", p), "%p", p); } TEST(PrintfTest, Location) { // TODO: test %n } #if FMT_USE_FILE_DESCRIPTORS TEST(PrintfTest, Examples) { const char *weekday = "Thursday"; const char *month = "August"; int day = 21; EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day), "Thursday, 21 August"); } TEST(PrintfTest, PrintfError) { fmt::File read_end, write_end; fmt::File::pipe(read_end, write_end); int result = fmt::fprintf(read_end.fdopen("r").get(), "test"); EXPECT_LT(result, 0); } #endif cppformat-1.1.0/test/test-main.cc000066400000000000000000000041461247635332500167120ustar00rootroot00000000000000/* Tests of additional gtest macros. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #ifdef _WIN32 # include # include #endif int main(int argc, char **argv) { #ifdef _WIN32 // Don't display any error dialogs. This also suppresses message boxes // on assertion failures in MinGW where _set_error_mode/CrtSetReportMode // doesn't help. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); // Disable message boxes on assertion failures. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); #endif testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } cppformat-1.1.0/test/util-test.cc000066400000000000000000000623311247635332500167430ustar00rootroot00000000000000/* Utility tests. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #if FMT_USE_TYPE_TRAITS # include #endif #include "gmock/gmock.h" #include "gtest-extra.h" #include "mock-allocator.h" #include "util.h" // Check if format.h compiles with windows.h included. #ifdef _WIN32 # include #endif #include "format.h" #undef max using fmt::StringRef; using fmt::internal::Arg; using fmt::internal::Value; using fmt::internal::Buffer; using fmt::internal::MemoryBuffer; using testing::Return; using testing::StrictMock; namespace { struct Test {}; template std::basic_ostream &operator<<(std::basic_ostream &os, Test) { return os << "test"; } template Arg make_arg(const T &value) { Arg arg = Arg(); Value &arg_value = arg; arg_value = fmt::internal::MakeValue(value); arg.type = static_cast( fmt::internal::MakeValue::type(value)); return arg; } } // namespace void CheckForwarding( MockAllocator &alloc, AllocatorRef< MockAllocator > &ref) { int mem; // Check if value_type is properly defined. AllocatorRef< MockAllocator >::value_type *ptr = &mem; // Check forwarding. EXPECT_CALL(alloc, allocate(42)).WillOnce(Return(ptr)); ref.allocate(42); EXPECT_CALL(alloc, deallocate(ptr, 42)); ref.deallocate(ptr, 42); } TEST(AllocatorTest, AllocatorRef) { StrictMock< MockAllocator > alloc; typedef AllocatorRef< MockAllocator > TestAllocatorRef; TestAllocatorRef ref(&alloc); // Check if AllocatorRef forwards to the underlying allocator. CheckForwarding(alloc, ref); TestAllocatorRef ref2(ref); CheckForwarding(alloc, ref2); TestAllocatorRef ref3; EXPECT_EQ(0, ref3.get()); ref3 = ref; CheckForwarding(alloc, ref3); } #if FMT_USE_TYPE_TRAITS TEST(BufferTest, Noncopyable) { EXPECT_FALSE(std::is_copy_constructible >::value); EXPECT_FALSE(std::is_copy_assignable >::value); } TEST(BufferTest, Nonmoveable) { EXPECT_FALSE(std::is_move_constructible >::value); EXPECT_FALSE(std::is_move_assignable >::value); } #endif // A test buffer with a dummy grow method. template struct TestBuffer : Buffer { void grow(std::size_t size) { this->capacity_ = size; } }; template struct MockBuffer : Buffer { MOCK_METHOD1(do_grow, void (std::size_t size)); void grow(std::size_t size) { this->capacity_ = size; do_grow(size); } MockBuffer() {} MockBuffer(T *ptr) : Buffer(ptr) {} MockBuffer(T *ptr, std::size_t capacity) : Buffer(ptr, capacity) {} }; TEST(BufferTest, Ctor) { { MockBuffer buffer; EXPECT_EQ(0, &buffer[0]); EXPECT_EQ(0u, buffer.size()); EXPECT_EQ(0u, buffer.capacity()); } { int dummy; MockBuffer buffer(&dummy); EXPECT_EQ(&dummy, &buffer[0]); EXPECT_EQ(0u, buffer.size()); EXPECT_EQ(0u, buffer.capacity()); } { int dummy; std::size_t capacity = std::numeric_limits::max(); MockBuffer buffer(&dummy, capacity); EXPECT_EQ(&dummy, &buffer[0]); EXPECT_EQ(0u, buffer.size()); EXPECT_EQ(capacity, buffer.capacity()); } } struct DyingBuffer : TestBuffer { MOCK_METHOD0(die, void()); ~DyingBuffer() { die(); } }; TEST(BufferTest, VirtualDtor) { typedef StrictMock StictMockBuffer; StictMockBuffer *mock_buffer = new StictMockBuffer(); EXPECT_CALL(*mock_buffer, die()); Buffer *buffer = mock_buffer; delete buffer; } TEST(BufferTest, Access) { char data[10]; MockBuffer buffer(data, sizeof(data)); buffer[0] = 11; EXPECT_EQ(11, buffer[0]); buffer[3] = 42; EXPECT_EQ(42, *(&buffer[0] + 3)); const Buffer &const_buffer = buffer; EXPECT_EQ(42, const_buffer[3]); } TEST(BufferTest, Resize) { char data[123]; MockBuffer buffer(data, sizeof(data)); buffer[10] = 42; EXPECT_EQ(42, buffer[10]); buffer.resize(20); EXPECT_EQ(20u, buffer.size()); EXPECT_EQ(123u, buffer.capacity()); EXPECT_EQ(42, buffer[10]); buffer.resize(5); EXPECT_EQ(5u, buffer.size()); EXPECT_EQ(123u, buffer.capacity()); EXPECT_EQ(42, buffer[10]); // Check if resize calls grow. EXPECT_CALL(buffer, do_grow(124)); buffer.resize(124); EXPECT_CALL(buffer, do_grow(200)); buffer.resize(200); } TEST(BufferTest, Clear) { TestBuffer buffer; buffer.resize(20); buffer.clear(); EXPECT_EQ(0u, buffer.size()); EXPECT_EQ(20u, buffer.capacity()); } TEST(BufferTest, PushBack) { int data[15]; MockBuffer buffer(data, 10); buffer.push_back(11); EXPECT_EQ(11, buffer[0]); EXPECT_EQ(1u, buffer.size()); buffer.resize(10); EXPECT_CALL(buffer, do_grow(11)); buffer.push_back(22); EXPECT_EQ(22, buffer[10]); EXPECT_EQ(11u, buffer.size()); } TEST(BufferTest, Append) { char data[15]; MockBuffer buffer(data, 10); const char *test = "test"; buffer.append(test, test + 5); EXPECT_STREQ(test, &buffer[0]); EXPECT_EQ(5u, buffer.size()); buffer.resize(10); EXPECT_CALL(buffer, do_grow(12)); buffer.append(test, test + 2); EXPECT_EQ('t', buffer[10]); EXPECT_EQ('e', buffer[11]); EXPECT_EQ(12u, buffer.size()); } TEST(BufferTest, AppendAllocatesEnoughStorage) { char data[19]; MockBuffer buffer(data, 10); const char *test = "abcdefgh"; buffer.resize(10); EXPECT_CALL(buffer, do_grow(19)); buffer.append(test, test + 9); } TEST(MemoryBufferTest, Ctor) { MemoryBuffer buffer; EXPECT_EQ(0u, buffer.size()); EXPECT_EQ(123u, buffer.capacity()); } #if FMT_USE_RVALUE_REFERENCES typedef AllocatorRef< std::allocator > TestAllocator; void check_move_buffer(const char *str, MemoryBuffer &buffer) { std::allocator *alloc = buffer.get_allocator().get(); MemoryBuffer buffer2(std::move(buffer)); // Move shouldn't destroy the inline content of the first buffer. EXPECT_EQ(str, std::string(&buffer[0], buffer.size())); EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size())); EXPECT_EQ(5u, buffer2.capacity()); // Move should transfer allocator. EXPECT_EQ(0, buffer.get_allocator().get()); EXPECT_EQ(alloc, buffer2.get_allocator().get()); } TEST(MemoryBufferTest, MoveCtor) { std::allocator alloc; MemoryBuffer buffer((TestAllocator(&alloc))); const char test[] = "test"; buffer.append(test, test + 4); check_move_buffer("test", buffer); // Adding one more character fills the inline buffer, but doesn't cause // dynamic allocation. buffer.push_back('a'); check_move_buffer("testa", buffer); const char *inline_buffer_ptr = &buffer[0]; // Adding one more character causes the content to move from the inline to // a dynamically allocated buffer. buffer.push_back('b'); MemoryBuffer buffer2(std::move(buffer)); // Move should rip the guts of the first buffer. EXPECT_EQ(inline_buffer_ptr, &buffer[0]); EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size())); EXPECT_GT(buffer2.capacity(), 5u); } void check_move_assign_buffer(const char *str, MemoryBuffer &buffer) { MemoryBuffer buffer2; buffer2 = std::move(buffer); // Move shouldn't destroy the inline content of the first buffer. EXPECT_EQ(str, std::string(&buffer[0], buffer.size())); EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size())); EXPECT_EQ(5u, buffer2.capacity()); } TEST(MemoryBufferTest, MoveAssignment) { MemoryBuffer buffer; const char test[] = "test"; buffer.append(test, test + 4); check_move_assign_buffer("test", buffer); // Adding one more character fills the inline buffer, but doesn't cause // dynamic allocation. buffer.push_back('a'); check_move_assign_buffer("testa", buffer); const char *inline_buffer_ptr = &buffer[0]; // Adding one more character causes the content to move from the inline to // a dynamically allocated buffer. buffer.push_back('b'); MemoryBuffer buffer2; buffer2 = std::move(buffer); // Move should rip the guts of the first buffer. EXPECT_EQ(inline_buffer_ptr, &buffer[0]); EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size())); EXPECT_GT(buffer2.capacity(), 5u); } #endif // FMT_USE_RVALUE_REFERENCES TEST(MemoryBufferTest, Grow) { typedef AllocatorRef< MockAllocator > Allocator; typedef MemoryBuffer Base; MockAllocator alloc; struct TestMemoryBuffer : Base { TestMemoryBuffer(Allocator alloc) : Base(alloc) {} void grow(std::size_t size) { Base::grow(size); } } buffer((Allocator(&alloc))); buffer.resize(7); for (int i = 0; i < 7; ++i) buffer[i] = i * i; EXPECT_EQ(10u, buffer.capacity()); int mem[20]; mem[7] = 0xdead; EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem)); buffer.grow(20); EXPECT_EQ(20u, buffer.capacity()); // Check if size elements have been copied for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[i]); // and no more than that. EXPECT_EQ(0xdead, buffer[7]); EXPECT_CALL(alloc, deallocate(mem, 20)); } TEST(MemoryBufferTest, Allocator) { typedef AllocatorRef< MockAllocator > TestAllocator; MemoryBuffer buffer; EXPECT_EQ(0, buffer.get_allocator().get()); StrictMock< MockAllocator > alloc; char mem; { MemoryBuffer buffer2((TestAllocator(&alloc))); EXPECT_EQ(&alloc, buffer2.get_allocator().get()); std::size_t size = 2 * fmt::internal::INLINE_BUFFER_SIZE; EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem)); buffer2.reserve(size); EXPECT_CALL(alloc, deallocate(&mem, size)); } } TEST(MemoryBufferTest, ExceptionInDeallocate) { typedef AllocatorRef< MockAllocator > TestAllocator; StrictMock< MockAllocator > alloc; MemoryBuffer buffer((TestAllocator(&alloc))); std::size_t size = 2 * fmt::internal::INLINE_BUFFER_SIZE; std::vector mem(size); { EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0])); buffer.resize(size); std::fill(&buffer[0], &buffer[0] + size, 'x'); } std::vector mem2(2 * size); { EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0])); std::exception e; EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e)); EXPECT_THROW(buffer.reserve(2 * size), std::exception); EXPECT_EQ(&mem2[0], &buffer[0]); // Check that the data has been copied. for (std::size_t i = 0; i < size; ++i) EXPECT_EQ('x', buffer[i]); } EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size)); } TEST(UtilTest, Increment) { char s[10] = "123"; increment(s); EXPECT_STREQ("124", s); s[2] = '8'; increment(s); EXPECT_STREQ("129", s); increment(s); EXPECT_STREQ("130", s); s[1] = s[2] = '9'; increment(s); EXPECT_STREQ("200", s); } template struct ArgInfo; #define ARG_INFO(type_code, Type, field) \ template <> \ struct ArgInfo { \ static Type get(const Value &value) { return value.field; } \ }; ARG_INFO(INT, int, int_value); ARG_INFO(UINT, unsigned, uint_value); ARG_INFO(LONG_LONG, fmt::LongLong, long_long_value); ARG_INFO(ULONG_LONG, fmt::ULongLong, ulong_long_value); ARG_INFO(DOUBLE, double, double_value); ARG_INFO(LONG_DOUBLE, long double, long_double_value); ARG_INFO(CHAR, int, int_value); ARG_INFO(CSTRING, const char *, string.value); ARG_INFO(STRING, const char *, string.value); ARG_INFO(WSTRING, const wchar_t *, wstring.value); ARG_INFO(POINTER, const void *, pointer); ARG_INFO(CUSTOM, Arg::CustomValue, custom); #define CHECK_ARG_INFO(Type, field, value) { \ Value arg_value = {}; \ arg_value.field = value; \ EXPECT_EQ(value, ArgInfo::get(arg_value)); \ } TEST(ArgTest, ArgInfo) { CHECK_ARG_INFO(INT, int_value, 42); CHECK_ARG_INFO(UINT, uint_value, 42u); CHECK_ARG_INFO(LONG_LONG, long_long_value, 42); CHECK_ARG_INFO(ULONG_LONG, ulong_long_value, 42u); CHECK_ARG_INFO(DOUBLE, double_value, 4.2); CHECK_ARG_INFO(LONG_DOUBLE, long_double_value, 4.2); CHECK_ARG_INFO(CHAR, int_value, 'x'); const char STR[] = "abc"; CHECK_ARG_INFO(CSTRING, string.value, STR); const wchar_t WSTR[] = L"abc"; CHECK_ARG_INFO(WSTRING, wstring.value, WSTR); int p = 0; CHECK_ARG_INFO(POINTER, pointer, &p); Value value = {}; value.custom.value = &p; EXPECT_EQ(&p, ArgInfo::get(value).value); } #define EXPECT_ARG_(Char, type_code, MakeArgType, ExpectedType, value) { \ MakeArgType input = static_cast(value); \ Arg arg = make_arg(input); \ EXPECT_EQ(Arg::type_code, arg.type); \ ExpectedType expected_value = static_cast(value); \ EXPECT_EQ(expected_value, ArgInfo::get(arg)); \ } #define EXPECT_ARG(type_code, Type, value) \ EXPECT_ARG_(char, type_code, Type, Type, value) #define EXPECT_ARGW(type_code, Type, value) \ EXPECT_ARG_(wchar_t, type_code, Type, Type, value) TEST(ArgTest, MakeArg) { // Test bool. EXPECT_ARG_(char, INT, bool, int, true); EXPECT_ARG_(wchar_t, INT, bool, int, true); // Test char. EXPECT_ARG(CHAR, signed char, 'a'); EXPECT_ARG(CHAR, signed char, SCHAR_MIN); EXPECT_ARG(CHAR, signed char, SCHAR_MAX); EXPECT_ARG(CHAR, unsigned char, 'a'); EXPECT_ARG(CHAR, unsigned char, UCHAR_MAX ); EXPECT_ARG(CHAR, char, 'a'); EXPECT_ARG(CHAR, char, CHAR_MIN); EXPECT_ARG(CHAR, char, CHAR_MAX); // Test wchar_t. EXPECT_ARGW(CHAR, wchar_t, L'a'); EXPECT_ARGW(CHAR, wchar_t, WCHAR_MIN); EXPECT_ARGW(CHAR, wchar_t, WCHAR_MAX); // Test short. EXPECT_ARG(INT, short, 42); EXPECT_ARG(INT, short, SHRT_MIN); EXPECT_ARG(INT, short, SHRT_MAX); EXPECT_ARG(UINT, unsigned short, 42); EXPECT_ARG(UINT, unsigned short, USHRT_MAX); // Test int. EXPECT_ARG(INT, int, 42); EXPECT_ARG(INT, int, INT_MIN); EXPECT_ARG(INT, int, INT_MAX); EXPECT_ARG(UINT, unsigned, 42); EXPECT_ARG(UINT, unsigned, UINT_MAX); // Test long. #if LONG_MAX == INT_MAX # define LONG INT # define ULONG UINT # define long_value int_value # define ulong_value uint_value #else # define LONG LONG_LONG # define ULONG ULONG_LONG # define long_value long_long_value # define ulong_value ulong_long_value #endif EXPECT_ARG(LONG, long, 42); EXPECT_ARG(LONG, long, LONG_MIN); EXPECT_ARG(LONG, long, LONG_MAX); EXPECT_ARG(ULONG, unsigned long, 42); EXPECT_ARG(ULONG, unsigned long, ULONG_MAX); // Test long long. EXPECT_ARG(LONG_LONG, fmt::LongLong, 42); EXPECT_ARG(LONG_LONG, fmt::LongLong, LLONG_MIN); EXPECT_ARG(LONG_LONG, fmt::LongLong, LLONG_MAX); EXPECT_ARG(ULONG_LONG, fmt::ULongLong, 42); EXPECT_ARG(ULONG_LONG, fmt::ULongLong, ULLONG_MAX); // Test float. EXPECT_ARG(DOUBLE, float, 4.2); EXPECT_ARG(DOUBLE, float, FLT_MIN); EXPECT_ARG(DOUBLE, float, FLT_MAX); // Test double. EXPECT_ARG(DOUBLE, double, 4.2); EXPECT_ARG(DOUBLE, double, DBL_MIN); EXPECT_ARG(DOUBLE, double, DBL_MAX); // Test long double. EXPECT_ARG(LONG_DOUBLE, long double, 4.2); EXPECT_ARG(LONG_DOUBLE, long double, LDBL_MIN); EXPECT_ARG(LONG_DOUBLE, long double, LDBL_MAX); // Test string. char STR[] = "test"; EXPECT_ARG(CSTRING, char*, STR); EXPECT_ARG(CSTRING, const char*, STR); EXPECT_ARG(STRING, std::string, STR); EXPECT_ARG(STRING, fmt::StringRef, STR); // Test wide string. wchar_t WSTR[] = L"test"; EXPECT_ARGW(WSTRING, wchar_t*, WSTR); EXPECT_ARGW(WSTRING, const wchar_t*, WSTR); EXPECT_ARGW(WSTRING, std::wstring, WSTR); EXPECT_ARGW(WSTRING, fmt::WStringRef, WSTR); int n = 42; EXPECT_ARG(POINTER, void*, &n); EXPECT_ARG(POINTER, const void*, &n); ::Test t; Arg arg = make_arg(t); EXPECT_EQ(fmt::internal::Arg::CUSTOM, arg.type); EXPECT_EQ(&t, arg.custom.value); fmt::MemoryWriter w; fmt::BasicFormatter formatter(w); const char *s = "}"; arg.custom.format(&formatter, &t, &s); EXPECT_EQ("test", w.str()); } TEST(UtilTest, ArgList) { fmt::ArgList args; EXPECT_EQ(Arg::NONE, args[fmt::ArgList::MAX_ARGS].type); } struct Result { Arg arg; Result() : arg(make_arg(0xdeadbeef)) {} template Result(const T& value) : arg(make_arg(value)) {} Result(const wchar_t *s) : arg(make_arg(s)) {} }; struct TestVisitor : fmt::internal::ArgVisitor { Result visit_int(int value) { return value; } Result visit_uint(unsigned value) { return value; } Result visit_long_long(fmt::LongLong value) { return value; } Result visit_ulong_long(fmt::ULongLong value) { return value; } Result visit_double(double value) { return value; } Result visit_long_double(long double value) { return value; } Result visit_char(int value) { return static_cast(value); } Result visit_string(Arg::StringValue s) { return s.value; } Result visit_wstring(Arg::StringValue s) { return s.value; } Result visit_pointer(const void *p) { return p; } Result visit_custom(Arg::CustomValue c) { return *static_cast(c.value); } }; #define EXPECT_RESULT_(Char, type_code, value) { \ Arg arg = make_arg(value); \ Result result = TestVisitor().visit(arg); \ EXPECT_EQ(Arg::type_code, result.arg.type); \ EXPECT_EQ(value, ArgInfo::get(result.arg)); \ } #define EXPECT_RESULT(type_code, value) \ EXPECT_RESULT_(char, type_code, value) #define EXPECT_RESULTW(type_code, value) \ EXPECT_RESULT_(wchar_t, type_code, value) TEST(ArgVisitorTest, VisitAll) { EXPECT_RESULT(INT, 42); EXPECT_RESULT(UINT, 42u); EXPECT_RESULT(LONG_LONG, 42ll); EXPECT_RESULT(ULONG_LONG, 42ull); EXPECT_RESULT(DOUBLE, 4.2); EXPECT_RESULT(LONG_DOUBLE, 4.2l); EXPECT_RESULT(CHAR, 'x'); const char STR[] = "abc"; EXPECT_RESULT(CSTRING, STR); const wchar_t WSTR[] = L"abc"; EXPECT_RESULTW(WSTRING, WSTR); const void *p = STR; EXPECT_RESULT(POINTER, p); ::Test t; Result result = TestVisitor().visit(make_arg(t)); EXPECT_EQ(Arg::CUSTOM, result.arg.type); EXPECT_EQ(&t, result.arg.custom.value); } struct TestAnyVisitor : fmt::internal::ArgVisitor { template Result visit_any_int(T value) { return value; } template Result visit_any_double(T value) { return value; } }; #undef EXPECT_RESULT #define EXPECT_RESULT(type_code, value) { \ Result result = TestAnyVisitor().visit(make_arg(value)); \ EXPECT_EQ(Arg::type_code, result.arg.type); \ EXPECT_EQ(value, ArgInfo::get(result.arg)); \ } TEST(ArgVisitorTest, VisitAny) { EXPECT_RESULT(INT, 42); EXPECT_RESULT(UINT, 42u); EXPECT_RESULT(LONG_LONG, 42ll); EXPECT_RESULT(ULONG_LONG, 42ull); EXPECT_RESULT(DOUBLE, 4.2); EXPECT_RESULT(LONG_DOUBLE, 4.2l); } struct TestUnhandledVisitor : fmt::internal::ArgVisitor { const char *visit_unhandled_arg() { return "test"; } }; #define EXPECT_UNHANDLED(value) \ EXPECT_STREQ("test", TestUnhandledVisitor().visit(make_arg(value))); TEST(ArgVisitorTest, VisitUnhandledArg) { EXPECT_UNHANDLED(42); EXPECT_UNHANDLED(42u); EXPECT_UNHANDLED(42ll); EXPECT_UNHANDLED(42ull); EXPECT_UNHANDLED(4.2); EXPECT_UNHANDLED(4.2l); EXPECT_UNHANDLED('x'); const char STR[] = "abc"; EXPECT_UNHANDLED(STR); const wchar_t WSTR[] = L"abc"; EXPECT_UNHANDLED(WSTR); const void *p = STR; EXPECT_UNHANDLED(p); EXPECT_UNHANDLED(::Test()); } TEST(ArgVisitorTest, VisitInvalidArg) { Arg arg = Arg(); arg.type = static_cast(Arg::CUSTOM + 1); EXPECT_DEBUG_DEATH(TestVisitor().visit(arg), "Assertion"); } // Tests fmt::internal::count_digits for integer type Int. template void test_count_digits() { for (Int i = 0; i < 10; ++i) EXPECT_EQ(1u, fmt::internal::count_digits(i)); for (Int i = 1, n = 1, end = std::numeric_limits::max() / 10; n <= end; ++i) { n *= 10; EXPECT_EQ(i, fmt::internal::count_digits(n - 1)); EXPECT_EQ(i + 1, fmt::internal::count_digits(n)); } } TEST(UtilTest, StringRef) { // Test that StringRef::size() returns string length, not buffer size. char str[100] = "some string"; EXPECT_EQ(std::strlen(str), StringRef(str).size()); EXPECT_LT(std::strlen(str), sizeof(str)); } TEST(UtilTest, CountDigits) { test_count_digits(); test_count_digits(); } #ifdef _WIN32 TEST(UtilTest, UTF16ToUTF8) { std::string s = "ёжик"; fmt::internal::UTF16ToUTF8 u(L"\x0451\x0436\x0438\x043A"); EXPECT_EQ(s, u.str()); EXPECT_EQ(s.size(), u.size()); } TEST(UtilTest, UTF8ToUTF16) { std::string s = "лошадка"; fmt::internal::UTF8ToUTF16 u(s.c_str()); EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str()); EXPECT_EQ(7, u.size()); } template void check_utf_conversion_error(const char *message) { fmt::MemoryWriter out; fmt::internal::format_windows_error(out, ERROR_INVALID_PARAMETER, message); fmt::SystemError error(0, ""); try { Converter(fmt::BasicStringRef(0, 0)); } catch (const fmt::SystemError &e) { error = e; } EXPECT_EQ(ERROR_INVALID_PARAMETER, error.error_code()); EXPECT_EQ(out.str(), error.what()); } TEST(UtilTest, UTF16ToUTF8Error) { check_utf_conversion_error( "cannot convert string from UTF-16 to UTF-8"); } TEST(UtilTest, UTF8ToUTF16Error) { check_utf_conversion_error( "cannot convert string from UTF-8 to UTF-16"); } TEST(UtilTest, UTF16ToUTF8Convert) { fmt::internal::UTF16ToUTF8 u; EXPECT_EQ(ERROR_INVALID_PARAMETER, u.convert(fmt::WStringRef(0, 0))); } #endif // _WIN32 typedef void (*FormatErrorMessage)( fmt::Writer &out, int error_code, StringRef message); template void check_throw_error(int error_code, FormatErrorMessage format) { fmt::SystemError error(0, ""); try { throw Error(error_code, "test {}", "error"); } catch (const fmt::SystemError &e) { error = e; } fmt::MemoryWriter message; format(message, error_code, "test error"); EXPECT_EQ(message.str(), error.what()); EXPECT_EQ(error_code, error.error_code()); } TEST(UtilTest, FormatSystemError) { fmt::MemoryWriter message; fmt::internal::format_system_error(message, EDOM, "test"); EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), message.str()); message.clear(); fmt::internal::format_system_error( message, EDOM, fmt::StringRef("x", std::numeric_limits::max())); EXPECT_EQ(fmt::format("error {}", EDOM), message.str()); } TEST(UtilTest, SystemError) { fmt::SystemError e(EDOM, "test"); EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), e.what()); EXPECT_EQ(EDOM, e.error_code()); check_throw_error(EDOM, fmt::internal::format_system_error); } TEST(UtilTest, ReportSystemError) { fmt::MemoryWriter out; fmt::internal::format_system_error(out, EDOM, "test error"); out << '\n'; EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"), out.str()); } #ifdef _WIN32 TEST(UtilTest, FormatWindowsError) { LPWSTR message = 0; FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, ERROR_FILE_EXISTS, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast(&message), 0, 0); fmt::internal::UTF16ToUTF8 utf8_message(message); LocalFree(message); fmt::MemoryWriter actual_message; fmt::internal::format_windows_error( actual_message, ERROR_FILE_EXISTS, "test"); EXPECT_EQ(fmt::format("test: {}", utf8_message.str()), actual_message.str()); actual_message.clear(); fmt::internal::format_windows_error( actual_message, ERROR_FILE_EXISTS, fmt::StringRef("x", std::numeric_limits::max())); EXPECT_EQ(fmt::format("error {}", ERROR_FILE_EXISTS), actual_message.str()); } TEST(UtilTest, WindowsError) { check_throw_error( ERROR_FILE_EXISTS, fmt::internal::format_windows_error); } TEST(UtilTest, ReportWindowsError) { fmt::MemoryWriter out; fmt::internal::format_windows_error(out, ERROR_FILE_EXISTS, "test error"); out << '\n'; EXPECT_WRITE(stderr, fmt::report_windows_error(ERROR_FILE_EXISTS, "test error"), out.str()); } #endif // _WIN32 cppformat-1.1.0/test/util.cc000066400000000000000000000035221247635332500157630ustar00rootroot00000000000000/* Test utilities. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "util.h" #include void increment(char *s) { for (int i = static_cast(std::strlen(s)) - 1; i >= 0; --i) { if (s[i] != '9') { ++s[i]; break; } s[i] = '0'; } } std::string get_system_error(int error_code) { #if defined(__MINGW32__) || !defined(_WIN32) return strerror(error_code); #else enum { BUFFER_SIZE = 200 }; char buffer[BUFFER_SIZE]; if (strerror_s(buffer, BUFFER_SIZE, error_code)) throw std::exception("strerror_s failed"); return buffer; #endif } cppformat-1.1.0/test/util.h000066400000000000000000000034651247635332500156330ustar00rootroot00000000000000/* Test utilities. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include enum {BUFFER_SIZE = 256}; #ifdef _MSC_VER # define FMT_VSNPRINTF vsprintf_s #else # define FMT_VSNPRINTF vsnprintf #endif template void safe_sprintf(char (&buffer)[SIZE], const char *format, ...) { std::va_list args; va_start(args, format); FMT_VSNPRINTF(buffer, SIZE, format, args); va_end(args); } // Increment a number in a string. void increment(char *s); std::string get_system_error(int error_code);