Compare commits

..

124 Commits

Author SHA1 Message Date
Gabi Melman
10e809cf64 Merge pull request #864 from DimRochette/v1.x
fix namespace of make_unique
2018-10-10 12:58:46 +03:00
DimRochette
3079551d30 fix namespace of make_unique 2018-10-10 11:23:25 +02:00
gabime
f4c5c5a367 Replaced noexcept with SPDLOG_NOEXCEPT 2018-10-10 01:01:37 +03:00
gabime
2a7b995723 Added noexcept some function in common.h 2018-10-10 00:57:16 +03:00
gabime
d0beac70bd Removed dead code from os.h 2018-10-10 00:29:34 +03:00
gabime
cbf66ac653 Removed dead code from os.h 2018-10-10 00:29:21 +03:00
gabime
98f9cb8c1f Added noexcept to most of details::os functions 2018-10-10 00:26:52 +03:00
Gabi Melman
8bd4c87d2f Merge pull request #856 from ulvgard/cmake_android_log_dependency
Add dependency to Android's log target in CMake
2018-10-08 12:12:29 +03:00
Gabi Melman
c88b568685 Update example.cpp 2018-10-08 01:46:01 +03:00
gabime
c83c9a3193 Version 1.2.0 2018-10-07 22:31:36 +03:00
Gabi Melman
410c46f1ab Update README.md 2018-10-06 15:38:26 +03:00
gabime
1b8bf35acc Micro optimize: don't init log_msg.msg_id on construction. It will be set anyway later 2018-10-06 01:49:34 +03:00
gabime
aa47ac85c9 add constexpr to hex chars 2018-10-05 23:23:09 +03:00
gabime
3eadda9466 code formating 2018-10-05 15:21:05 +03:00
gabime
dea6a7c217 Tests: Fixed some clang-tidy warnings 2018-10-05 15:20:14 +03:00
gabime
887a104dd0 Fixed clang-tidy warning 2018-10-05 15:19:03 +03:00
gabime
1808e3c4c8 Fixed bug in async_bench 2018-10-05 14:52:38 +03:00
gabime
1f4cae4bf7 Changed forward<log_msg> to std::move(log_msg) in thread pool 2018-10-05 14:50:30 +03:00
gabime
3b009f5aa6 Changed forward<worker_ptr> to std::move in async logger 2018-10-05 14:33:53 +03:00
gabime
36112371c0 Reverted const qualifier to log_msg& args, fixed issue #849, and added counter tests 2018-10-05 14:23:37 +03:00
gabime
2fa538779f Fixed static_assert 2018-10-04 02:20:47 +03:00
gabime
b7a6659451 code formatting 2018-10-04 02:10:46 +03:00
gabime
102c31a04c Accecpt iterators by value in logger ctor insted of ref 2018-10-04 02:06:39 +03:00
Tobias Ulvgard
f01da91abf Add dependency to Android's log target in CMake 2018-10-03 10:10:37 +02:00
gabime
10000c383a Better error message if WideCharToMultiByte fails 2018-10-03 00:26:58 +03:00
gabime
8b42b7d269 Fix support for wchar to utf8 under windows (fix issue #851 and #764) 2018-10-02 18:27:49 +03:00
gabime
17702969fa Upgrded to fmt version 5.2.1 2018-10-02 16:14:39 +03:00
Gabi Melman
cc3613e012 Update README.md 2018-10-02 15:24:43 +03:00
Gabi Melman
0258418a99 Merge pull request #853 from blackball/v1.x
return nothing if it's a void function.
2018-10-02 15:22:58 +03:00
Hui
397c2a934f Merge pull request #1 from blackball/blackball-patch-1
Fix return type in README file.
2018-10-02 19:22:02 +08:00
Hui
796986f38c Fix return type in README file.
void function should not return 1.
2018-10-02 19:21:41 +08:00
Gabi Melman
c5011181bb Update log_msg.h 2018-10-01 14:27:43 +03:00
gabime
dace099348 Added fmt_helper tests 2018-09-28 01:30:29 +03:00
gabime
0876e39c4f pad3 small optimization 2018-09-28 01:27:37 +03:00
gabime
0b516733db user buffer.clear() insread of resize(0) 2018-09-27 17:08:21 +03:00
Gabi Melman
e15deead32 Update README.md 2018-09-27 03:59:43 +03:00
gabime
18df6138a7 clang-format 2018-09-27 02:03:12 +03:00
gabime
8c125ed009 Added clang-tidy script 2018-09-27 02:02:13 +03:00
gabime
4720b703f4 Fixed clang-tidy warnings 2018-09-27 01:58:39 +03:00
gabime
cd8e15dcd1 Fixed clang-tidy warnings 2018-09-27 01:39:26 +03:00
gabime
a06d32ae19 Fixed clang-tidy warnings 2018-09-27 01:14:35 +03:00
gabime
7af3f014af Fixed clang-tidy warning 2018-09-27 00:59:28 +03:00
gabime
8e80081f99 Fixed clang-tidy warning 2018-09-27 00:56:19 +03:00
gabime
14c0417f3e Fixed clang-tidy warning 2018-09-27 00:47:09 +03:00
gabime
0879dea444 Fixed clang-tidy warning 2018-09-27 00:39:17 +03:00
gabime
a8c4aef6bd fix typo 2018-09-26 23:50:47 +03:00
gabime
669a66f18a format 2018-09-26 23:48:59 +03:00
gabime
e8dae26176 Moved spdlog::make_unique to spdlog::details::make_unique and prevent T to be array 2018-09-26 23:48:36 +03:00
gabime
e3a66473b2 Small cleanup in set_formatter 2018-09-26 15:53:54 +03:00
gabime
7704e41336 Fixed issue #833 2018-09-26 15:43:23 +03:00
gabime
a74bbe7381 base_sink default ctor 2018-09-26 15:41:57 +03:00
gabime
729ec21629 Added virtual protected functions to base_sink 2018-09-26 15:29:19 +03:00
gabime
b393715bee Added virtual protected functions to base_sink 2018-09-26 15:27:48 +03:00
gabime
5ec4e60424 Replaced SPDLOG_FINAL macro with final 2018-09-26 15:26:34 +03:00
gabime
5cd24f3033 Replaced SPDLOG_FINAL macro with final 2018-09-26 15:26:27 +03:00
gabime
27a03c5cec Replaced SPDLOG_FINAL macro with final 2018-09-26 15:24:22 +03:00
gabime
5d34d21f40 Fixed issue #842 in tests 2018-09-26 14:45:57 +03:00
gabime
ca8accbaa8 Replaced SPDLOG_FINAL macro with final 2018-09-26 14:45:38 +03:00
gabime
65defd3806 Replaced SPDLOG_FINAL macro with final 2018-09-26 14:33:37 +03:00
Gabi Melman
be7e7237e9 Update README.md 2018-09-25 01:51:03 +03:00
gabime
234cb2dfba Updated becnhmark info 2018-09-25 01:43:05 +03:00
Gabi Melman
b922ae0fb8 Update README.md 2018-09-25 01:26:17 +03:00
gabime
8649fb5118 Added binary logging example 2018-09-25 01:25:10 +03:00
Gabi Melman
a4bae6aba9 Update bench.cpp 2018-09-25 01:22:28 +03:00
gabime
808bc1f4ed clang format 2018-09-25 01:11:36 +03:00
gabime
41d879e292 Added support for binary logging using to_hex(..) 2018-09-25 01:03:57 +03:00
Gabi Melman
2e7b3cae2a Update bench.cpp 2018-09-21 11:22:57 +03:00
gabime
a0ae62a733 format.sh 2018-09-18 00:19:16 +03:00
gabime
06eb69b93a format.sh 2018-09-18 00:18:22 +03:00
gabime
7025ff4280 format.sh don't format bundled src 2018-09-18 00:16:13 +03:00
gabime
2fa7410c0e Improve rotating sink error handling 2018-09-18 00:09:58 +03:00
gabime
3771d12992 Upgraded to fmt ver 5.2.0 2018-09-17 14:40:52 +03:00
Gabi Melman
f4ac67ae1c Merge pull request #837 from myrgy/missing_include_ansicolor_sing
ansicolor_sink.h - add missing sink include
2018-09-17 12:50:17 +03:00
Alexander Dalshov
d48d6939c2 ansicolor_sink.h - add missing sink include 2018-09-17 11:26:40 +03:00
Gabi Melman
188cff7d65 Merge pull request #831 from taketwo/fix-830
Change the default value for SPDLOG_BUILD_xxx
2018-09-12 23:33:36 +03:00
Sergey Alexandrov
75925762e8 Change the default value for SPDLOG_BUILD_xxx
The value based on whether spdlog is used as a third-party dependency or
as a standalone project. If spdlog is included through add_subdirectory,
the tests/examples/benchmarsk are disabled by default, and if spdlog is
configured standalone, then they are enabled by default.
2018-09-12 16:11:45 -04:00
Gabi Melman
f2ac7d730c Update README.md 2018-09-07 02:12:28 +03:00
Gabi Melman
c5c1c5458b Update README.md 2018-09-07 02:09:13 +03:00
Gabi Melman
1649597eae Update README.md 2018-09-07 02:07:25 +03:00
Gabi Melman
1cb49bfe72 Merge pull request #824 from gabime/revert-822-patch-1
Revert "Add `conda` to package managers in README"
2018-09-06 13:31:09 +03:00
Gabi Melman
1aa4b657d6 Revert "Add conda to package managers in README" 2018-09-06 13:30:25 +03:00
Gabi Melman
d803e7003f Merge pull request #822 from epruesse/patch-1
Add `conda` to package managers in README
2018-09-06 06:02:45 +03:00
Elmar Pruesse
18efcd62ff Add conda to package managers in README 2018-09-05 19:25:11 -06:00
Gabi Melman
9fda1cb421 Merge pull request #813 from jwnimmer-tri/dist_sink_reset_v1.x
Add set_sinks method to dist_sink
2018-09-04 23:56:03 +03:00
Gabi Melman
bcc6db4a06 Update README.md 2018-09-04 19:34:59 +03:00
Gabi Melman
37cd707294 Fix issue #819 2018-09-03 19:08:57 +03:00
gabime
3698c1d2f1 added spdlog namespace when calling make_unique 2018-09-02 01:27:28 +03:00
Gabi Melman
00acb8ba41 Update registry.h 2018-09-01 22:41:56 +03:00
Gabi Melman
a6ee1cf590 fix vc compliation error about make_unique 2018-09-01 21:56:19 +03:00
gabime
ebce97947d use make_unique 2018-09-01 21:30:05 +03:00
gabime
f4bbe8b2b3 Fixed some extra warnings from clang 2018-08-31 14:17:11 +03:00
Gabi Melman
e52e258f15 Update README.md 2018-08-31 04:14:23 +03:00
Jeremy Nimmer
679fcd787f Add set_sinks method to dist_sink
This allows users to set exactly the sinks they want, even if other
unknown application code has added bespoke sinks in the meantime.
2018-08-29 12:29:32 -04:00
Gabi Melman
f3798159e7 Merge pull request #814 from maciekgajewski/no-pessimizing-move
Pessimizing move removed
2018-08-29 19:21:56 +03:00
Maciej Gajewski
c4de214cea Pessimizing move removed 2018-08-29 17:21:38 +02:00
gabime
6c5bbca0c1 Added clone tests 2018-08-25 18:10:42 +03:00
gabime
447a6a15d9 Fixed readme 2018-08-25 17:57:41 +03:00
gabime
5d7845c138 Added "clone()" support to loggers 2018-08-25 17:55:31 +03:00
gabime
91d8869f36 Added "clone()" support to loggers 2018-08-25 17:35:20 +03:00
Gabi Melman
1f8b2cbb8b Update file_helper.h 2018-08-24 13:27:49 +03:00
Gabi Melman
d0cfca0820 Update file_helper.h 2018-08-24 13:27:10 +03:00
Gabi Melman
f6049cd333 Update file_helper.h 2018-08-24 13:26:45 +03:00
Gabi Melman
a25fd62349 Merge pull request #806 from emruiz81/v1.x
WIN32: Don't deny access to file sinks from other processes
2018-08-23 19:15:28 +03:00
eruiz
39492436ec WIN32: Don't deny access to file sinks from other processes 2018-08-23 12:20:26 -03:00
Gabi Melman
df962e5c53 Merge pull request #804 from DanielChabrowski/globals-include
Add missing include in console_globals.h
2018-08-23 00:12:17 +03:00
Daniel Chabrowski
2990126054 Change console_globals include to windows.h only 2018-08-22 22:47:16 +02:00
Daniel Chabrowski
3edc7f1d18 Add missing include in console_globals.h 2018-08-22 21:46:46 +02:00
Gabi Melman
2870afdeae Update stdout_sinks.h 2018-08-21 03:37:29 +03:00
gabime
d3c1ad29a0 Optimize logging for const char* messages 2018-08-20 12:43:31 +03:00
Gabi Melman
23db7a213d Merge pull request #801 from yhchen/v1.x
remove invalid files from project
2018-08-19 13:02:35 +03:00
yhchen
3151081ff3 remove invalid files from project 2018-08-19 17:21:15 +08:00
gabime
0758b39061 Stop compilation on first error 2018-08-18 02:19:52 +03:00
gabime
45d3c8341c Fixed mpmc_q test for osx in travis 2018-08-17 17:45:48 +03:00
gabime
8418131ae3 Fixed mpmc_q test for osx in travis 2018-08-17 17:30:33 +03:00
gabime
9ad9cfb898 Fixed mpmc_q test for osx in travis 2018-08-17 17:17:16 +03:00
gabime
a281d21fbf Removed valgrind from travis 2018-08-17 16:26:52 +03:00
gabime
af5962450e Try adding osx to travis 2018-08-17 16:15:02 +03:00
gabime
3b3af1ab1e Try adding osx to travis 2018-08-17 16:00:14 +03:00
gabime
acd7a88bf2 Try adding osx to travis 2018-08-17 15:59:52 +03:00
Gabi Melman
176cab4fee Update file_helper.h 2018-08-17 14:07:49 +03:00
Gabi Melman
28435dc736 Normalized spdlog includes in file_helper 2018-08-17 14:06:48 +03:00
gabime
a58d7594cb Fixed issue #798 and added -Wconversion compiler flag to build 2018-08-17 00:32:13 +03:00
Gabi Melman
06181720fb Merge pull request #800 from DanielChabrowski/fix-registry-test
Fix registry test
2018-08-16 19:25:34 +03:00
Daniel Chabrowski
b51c8cfd0f Fix registry test 2018-08-16 17:53:55 +02:00
61 changed files with 6669 additions and 7228 deletions

28
.clang-tidy Normal file
View File

@@ -0,0 +1,28 @@
Checks: 'modernize-*,modernize-use-override,google-*,-google-runtime-references,misc-*,clang-analyzer-*'
WarningsAsErrors: ''
HeaderFilterRegex: 'async.h|async_logger.h|common.h|details|formatter.h|logger.h|sinks|spdlog.h|tweakme.h|version.h'
AnalyzeTemporaryDtors: false
FormatStyle: none
CheckOptions:
- key: google-readability-braces-around-statements.ShortStatementLines
value: '1'
- key: google-readability-function-size.StatementThreshold
value: '800'
- key: google-readability-namespace-comments.ShortNamespaceLines
value: '10'
- key: google-readability-namespace-comments.SpacesBeforeComments
value: '2'
- key: modernize-loop-convert.MaxCopySize
value: '16'
- key: modernize-loop-convert.MinConfidence
value: reasonable
- key: modernize-loop-convert.NamingStyle
value: CamelCase
- key: modernize-pass-by-value.IncludeStyle
value: llvm
- key: modernize-replace-auto-ptr.IncludeStyle
value: llvm
- key: modernize-use-nullptr.NullMacros
value: 'NULL'

View File

@@ -9,7 +9,6 @@ addons: &gcc48
apt: apt:
packages: packages:
- g++-4.8 - g++-4.8
- valgrind
sources: sources:
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
@@ -17,7 +16,6 @@ addons: &gcc7
apt: apt:
packages: packages:
- g++-7 - g++-7
- valgrind
sources: sources:
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
@@ -25,7 +23,6 @@ addons: &clang35
apt: apt:
packages: packages:
- clang-3.5 - clang-3.5
- valgrind
sources: sources:
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.5 - llvm-toolchain-precise-3.5
@@ -34,11 +31,11 @@ addons: &clang6
apt: apt:
packages: packages:
- clang-6.0 - clang-6.0
- valgrind
sources: sources:
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
- llvm-toolchain-trusty-6.0 - llvm-toolchain-trusty-6.0
matrix: matrix:
include: include:
# Test gcc-4.8: C++11, Build=Debug/Release # Test gcc-4.8: C++11, Build=Debug/Release
@@ -81,16 +78,21 @@ matrix:
os: linux os: linux
addons: *clang6 addons: *clang6
# osx
- env: BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off
os: osx
before_script: before_script:
- if [ -n "$GCC_VERSION" ]; then export CXX="g++-${GCC_VERSION}" CC="gcc-${GCC_VERSION}"; fi - if [ -n "$GCC_VERSION" ]; then export CXX="g++-${GCC_VERSION}" CC="gcc-${GCC_VERSION}"; fi
- if [ -n "$CLANG_VERSION" ]; then export CXX="clang++-${CLANG_VERSION}" CC="clang-${CLANG_VERSION}"; fi - if [ -n "$CLANG_VERSION" ]; then export CXX="clang++-${CLANG_VERSION}" CC="clang-${CLANG_VERSION}"; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then export CXX="clang++" CC="clang"; fi
- which $CXX - which $CXX
- which $CC - which $CC
- which valgrind
- $CXX --version - $CXX --version
- cmake --version - cmake --version
- valgrind --version
script: script:
- cd ${TRAVIS_BUILD_DIR} - cd ${TRAVIS_BUILD_DIR}

View File

@@ -4,7 +4,7 @@
# #
cmake_minimum_required(VERSION 3.1) cmake_minimum_required(VERSION 3.1)
project(spdlog VERSION 1.1.0 LANGUAGES CXX) project(spdlog VERSION 1.2.0 LANGUAGES CXX)
include(CTest) include(CTest)
include(CMakeDependentOption) include(CMakeDependentOption)
include(GNUInstallDirs) include(GNUInstallDirs)
@@ -28,7 +28,10 @@ set(CMAKE_CXX_EXTENSIONS OFF)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
add_compile_options("-Wall") add_compile_options("-Wall")
add_compile_options("-Wextra") add_compile_options("-Wextra")
add_compile_options("-Wconversion")
add_compile_options("-pedantic") add_compile_options("-pedantic")
add_compile_options("-Wfatal-errors")
endif() endif()
#--------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------
@@ -42,11 +45,17 @@ include(cmake/sanitizers.cmake)
add_library(spdlog INTERFACE) add_library(spdlog INTERFACE)
add_library(spdlog::spdlog ALIAS spdlog) add_library(spdlog::spdlog ALIAS spdlog)
option(SPDLOG_BUILD_EXAMPLES "Build examples" ON) # Check if spdlog is being used directly or via add_subdirectory
option(SPDLOG_BUILD_BENCH "Build benchmarks" ON) set(SPDLOG_MASTER_PROJECT OFF)
if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(SPDLOG_MASTER_PROJECT ON)
endif()
option(SPDLOG_BUILD_EXAMPLES "Build examples" ${SPDLOG_MASTER_PROJECT})
option(SPDLOG_BUILD_BENCH "Build benchmarks" ${SPDLOG_MASTER_PROJECT})
cmake_dependent_option(SPDLOG_BUILD_TESTING cmake_dependent_option(SPDLOG_BUILD_TESTING
"Build spdlog tests" ON "Build spdlog tests" ${SPDLOG_MASTER_PROJECT}
"BUILD_TESTING" OFF "BUILD_TESTING" OFF
) )

View File

@@ -3,6 +3,7 @@
Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.org/gabime/spdlog.svg?branch=master)](https://travis-ci.org/gabime/spdlog)&nbsp; [![Build status](https://ci.appveyor.com/api/projects/status/d2jnxclg20vd0o50?svg=true)](https://ci.appveyor.com/project/gabime/spdlog) Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.org/gabime/spdlog.svg?branch=master)](https://travis-ci.org/gabime/spdlog)&nbsp; [![Build status](https://ci.appveyor.com/api/projects/status/d2jnxclg20vd0o50?svg=true)](https://ci.appveyor.com/project/gabime/spdlog)
## Install ## Install
#### Just copy the headers: #### Just copy the headers:
@@ -20,18 +21,17 @@ Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.
## Platforms ## Platforms
* Linux, FreeBSD, Solaris, AIX * Linux, FreeBSD, OpenBSD, Solaris, AIX
* Windows (vc 2013+, cygwin) * Windows (msvc 2013+, cygwin)
* Mac OSX (clang 3.5+) * macOS (clang 3.5+)
* Android * Android
## Features ## Features
* Very fast - performance is the primary goal (see [benchmarks](#benchmarks) below). * Very fast (see [benchmarks](#benchmarks) below).
* Headers only, just copy and use. * Headers only, just copy and use.
* Feature rich using the excellent [fmt](https://github.com/fmtlib/fmt) library. * Feature rich formatting, using the excellent [fmt](https://github.com/fmtlib/fmt) library.
* Fast asynchronous mode (optional) * Fast asynchronous mode (optional)
* [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting. * [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting.
* Conditional Logging
* Multi/Single threaded loggers. * Multi/Single threaded loggers.
* Various log targets: * Various log targets:
* Rotating log files. * Rotating log files.
@@ -41,7 +41,7 @@ Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.
* Windows debugger (```OutputDebugString(..)```) * Windows debugger (```OutputDebugString(..)```)
* Easily extendable with custom log targets (just implement a single function in the [sink](include/spdlog/sinks/sink.h) interface). * Easily extendable with custom log targets (just implement a single function in the [sink](include/spdlog/sinks/sink.h) interface).
* Severity based filtering - threshold levels can be modified in runtime as well as in compile time. * Severity based filtering - threshold levels can be modified in runtime as well as in compile time.
* Binary data logging.
## Benchmarks ## Benchmarks
@@ -53,28 +53,26 @@ Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/ben
******************************************************************************* *******************************************************************************
Single thread, 1,000,000 iterations Single thread, 1,000,000 iterations
******************************************************************************* *******************************************************************************
basic_st... Elapsed: 0.226664 4,411,806/sec basic_st... Elapsed: 0.181652 5,505,042/sec
rotating_st... Elapsed: 0.214339 4,665,499/sec rotating_st... Elapsed: 0.181781 5,501,117/sec
daily_st... Elapsed: 0.211292 4,732,797/sec daily_st... Elapsed: 0.187595 5,330,630/sec
null_st... Elapsed: 0.102815 9,726,227/sec null_st... Elapsed: 0.0504704 19,813,602/sec
******************************************************************************* *******************************************************************************
10 threads sharing same logger, 1,000,000 iterations 10 threads sharing same logger, 1,000,000 iterations
******************************************************************************* *******************************************************************************
basic_mt... Elapsed: 0.882268 1,133,441/sec basic_mt... Elapsed: 0.616035 1,623,284/sec
rotating_mt... Elapsed: 0.875515 1,142,184/sec rotating_mt... Elapsed: 0.620344 1,612,008/sec
daily_mt... Elapsed: 0.879573 1,136,915/sec daily_mt... Elapsed: 0.648353 1,542,369/sec
null_mt... Elapsed: 0.220114 4,543,105/sec null_mt... Elapsed: 0.151972 6,580,166/sec
``` ```
#### Asynchronous mode #### Asynchronous mode
``` ```
******************************************************************************* *******************************************************************************
10 threads sharing same logger, 1,000,000 iterations 10 threads sharing same logger, 1,000,000 iterations
******************************************************************************* *******************************************************************************
async... Elapsed: 0.429088 2,330,524/sec async... Elapsed: 0.350066 2,856,606/sec
async... Elapsed: 0.411501 2,430,126/sec async... Elapsed: 0.314865 3,175,960/sec
async... Elapsed: 0.428979 2,331,116/sec async... Elapsed: 0.349851 2,858,358/sec
``` ```
## Usage samples ## Usage samples
@@ -130,7 +128,6 @@ void basic_logfile_example()
catch (const spdlog::spdlog_ex &ex) catch (const spdlog::spdlog_ex &ex)
{ {
std::cout << "Log init failed: " << ex.what() << std::endl; std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
} }
} }
``` ```
@@ -158,6 +155,18 @@ void daily_example()
``` ```
---
#### Cloning loggers
```c++
// clone a logger and give it new name.
// Useful for creating subsystem loggers from some "root" logger
void clone_example()
{
auto network_logger = spdlog::get("root")->clone("network");
network_logger->info("Logging network stuff..");
}
```
--- ---
#### Periodic flush #### Periodic flush
```c++ ```c++
@@ -167,6 +176,33 @@ spdlog::flush_every(std::chrono::seconds(3));
``` ```
---
#### Binary logging
```c++
// log binary data as hex.
// many types of std::container<char> types can be used.
// ranges are supported too.
// format flags:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines.
#include "spdlog/fmt/bin_to_hex.h"
void binary_example()
{
auto console = spdlog::get("console");
std::array<char, 80> buf;
console->info("Binary example: {}", spdlog::to_hex(buf));
console->info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
// more examples:
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
}
```
--- ---
#### Logger with multi sinks - each with different format and log level #### Logger with multi sinks - each with different format and log level

View File

@@ -35,6 +35,7 @@ int count_lines(const char *filename)
if ('\n' == ch) if ('\n' == ch)
counter++; counter++;
} }
fclose(infile);
return counter; return counter;
} }

View File

@@ -35,8 +35,8 @@ int main(int argc, char *argv[])
int howmany = 1000000; int howmany = 1000000;
int queue_size = howmany + 2; int queue_size = howmany + 2;
int threads = 10; int threads = 10;
int file_size = 30 * 1024 * 1024; size_t file_size = 30 * 1024 * 1024;
int rotating_files = 5; size_t rotating_files = 5;
try try
{ {
@@ -54,7 +54,7 @@ int main(int argc, char *argv[])
cout << "******************************************************************" cout << "******************************************************************"
"*************\n"; "*************\n";
auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true); auto basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
bench(howmany, basic_st); bench(howmany, basic_st);
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
@@ -89,7 +89,7 @@ int main(int argc, char *argv[])
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
spdlog::init_thread_pool(queue_size, 1); spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true); auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, as, threads); bench_mt(howmany, as, threads);
spdlog::drop("async"); spdlog::drop("async");

View File

@@ -35,8 +35,8 @@ int main(int, char *[])
int howmany = 1000000; int howmany = 1000000;
int queue_size = howmany + 2; int queue_size = howmany + 2;
int threads = 10; int threads = 10;
int file_size = 30 * 1024 * 1024; size_t file_size = 30 * 1024 * 1024;
int rotating_files = 5; size_t rotating_files = 5;
try try
{ {
@@ -82,7 +82,7 @@ int main(int, char *[])
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
spdlog::init_thread_pool(queue_size, 1); spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true); auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, as, threads); bench_mt(howmany, as, threads);
spdlog::drop("async"); spdlog::drop("async");

2
clang_tidy.sh Executable file
View File

@@ -0,0 +1,2 @@
#!/bin/bash
clang-tidy example/example.cpp -- -I ./include

View File

@@ -32,7 +32,13 @@ endif()
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
add_executable(example example.cpp) add_executable(example example.cpp)
if(CMAKE_SYSTEM_NAME STREQUAL "Android")
find_library(log-lib log)
target_link_libraries(example spdlog::spdlog Threads::Threads log)
else()
target_link_libraries(example spdlog::spdlog Threads::Threads) target_link_libraries(example spdlog::spdlog Threads::Threads)
endif()
add_executable(multisink multisink.cpp) add_executable(multisink multisink.cpp)
target_link_libraries(multisink spdlog::spdlog Threads::Threads) target_link_libraries(multisink spdlog::spdlog Threads::Threads)

View File

@@ -1,5 +1,5 @@
CXX ?= g++ CXX ?= g++
CXX_FLAGS = -Wall -Wextra -pedantic -std=c++11 -pthread -I../include -fmax-errors=1 CXX_FLAGS = -Wall -Wextra -pedantic -std=c++11 -pthread -I../include -fmax-errors=1 -Wconversion
CXX_RELEASE_FLAGS = -O3 -march=native CXX_RELEASE_FLAGS = -O3 -march=native
CXX_DEBUG_FLAGS= -g CXX_DEBUG_FLAGS= -g

22
example/Makefile-all-warn Normal file
View File

@@ -0,0 +1,22 @@
#-Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded
CXX ?= g++
CXX_FLAGS = -Wall -Wextra -pedantic -std=c++11 -pthread -I../include -fmax-errors=1 -Wconversion -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-weak-vtables -Wno-global-constructors
CXX_RELEASE_FLAGS = -O3 -march=native
CXX_DEBUG_FLAGS= -g
all: example
debug: example-debug
example: example.cpp
$(CXX) example.cpp -o example $(CXX_FLAGS) $(CXX_RELEASE_FLAGS) $(CXXFLAGS)
example-debug: example.cpp
$(CXX) example.cpp -o example-debug $(CXX_FLAGS) $(CXX_DEBUG_FLAGS) $(CXXFLAGS)
clean:
rm -f *.o logs/*.txt example example-debug
rebuild: clean all
rebuild-debug: clean debug

View File

@@ -14,10 +14,12 @@ void basic_example();
void rotating_example(); void rotating_example();
void daily_example(); void daily_example();
void async_example(); void async_example();
void binary_example();
void multi_sink_example(); void multi_sink_example();
void user_defined_example(); void user_defined_example();
void err_handler_example(); void err_handler_example();
void syslog_example(); void syslog_example();
void clone_example();
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
@@ -34,9 +36,14 @@ int main(int, char *[])
rotating_example(); rotating_example();
daily_example(); daily_example();
clone_example();
// async logging using a backing thread pool // async logging using a backing thread pool
async_example(); async_example();
// log binary data
binary_example();
// a logger can have multiple targets with different formats // a logger can have multiple targets with different formats
multi_sink_example(); multi_sink_example();
@@ -94,6 +101,7 @@ void stdout_example()
// Customize msg format for all loggers // Customize msg format for all loggers
spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v"); spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v");
console->info("This an info message with custom format"); console->info("This an info message with custom format");
spdlog::set_pattern("%+"); // back to default format
// Compile time log levels // Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON // define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
@@ -122,6 +130,14 @@ void daily_example()
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
} }
// clone a logger and give it new name.
// Useful for creating component/subsystem loggers from some "root" logger
void clone_example()
{
auto network_logger = spdlog::get("console")->clone("network");
network_logger->info("Logging network stuff..");
}
#include "spdlog/async.h" #include "spdlog/async.h"
void async_example() void async_example()
{ {
@@ -137,6 +153,28 @@ void async_example()
} }
} }
// log binary data as hex.
// many types of std::container<char> types can be used.
// ranges are supported too.
// format flags:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines.
#include "spdlog/fmt/bin_to_hex.h"
void binary_example()
{
auto console = spdlog::get("console");
std::array<char, 80> buf;
console->info("Binary example: {}", spdlog::to_hex(buf));
console->info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
// more examples:
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
}
// create logger with 2 targets with different log levels and formats // create logger with 2 targets with different log levels and formats
// the console will show only warnings or errors, while the file will log all // the console will show only warnings or errors, while the file will log all

View File

@@ -1,9 +1,9 @@
#!/bin/bash #!/bin/bash
echo -n "Running dos2unix " echo -n "Running dos2unix "
find . -name "*\.h" -o -name "*\.cpp"|xargs -I {} sh -c "dos2unix '{}' 2>/dev/null; echo -n '.'" find . -name "*\.h" -o -name "*\.cpp"|grep -v bundled|xargs -I {} sh -c "dos2unix '{}' 2>/dev/null; echo -n '.'"
echo echo
echo -n "Running clang-format " echo -n "Running clang-format "
find . -name "*\.h" -o -name "*\.cpp"|xargs -I {} sh -c "clang-format -i {}; echo -n '.'" find . -name "*\.h" -o -name "*\.cpp"|grep -v bundled|xargs -I {} sh -c "clang-format -i {}; echo -n '.'"
echo echo

View File

@@ -40,13 +40,13 @@ namespace details {
class thread_pool; class thread_pool;
} }
class async_logger SPDLOG_FINAL : public std::enable_shared_from_this<async_logger>, public logger class async_logger final : public std::enable_shared_from_this<async_logger>, public logger
{ {
friend class details::thread_pool; friend class details::thread_pool;
public: public:
template<typename It> template<typename It>
async_logger(std::string logger_name, const It &begin, const It &end, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp,
async_overflow_policy overflow_policy = async_overflow_policy::block); async_overflow_policy overflow_policy = async_overflow_policy::block);
async_logger(std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp,
@@ -55,11 +55,13 @@ public:
async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp,
async_overflow_policy overflow_policy = async_overflow_policy::block); async_overflow_policy overflow_policy = async_overflow_policy::block);
std::shared_ptr<logger> clone(std::string new_name) override;
protected: protected:
void sink_it_(details::log_msg &msg) override; void sink_it_(details::log_msg &msg) override;
void flush_() override; void flush_() override;
void backend_log_(details::log_msg &incoming_log_msg); void backend_log_(const details::log_msg &incoming_log_msg);
void backend_flush_(); void backend_flush_();
private: private:

View File

@@ -14,6 +14,7 @@
#include <memory> #include <memory>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <type_traits>
#include <unordered_map> #include <unordered_map>
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) #if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
@@ -32,13 +33,6 @@
#define SPDLOG_CONSTEXPR constexpr #define SPDLOG_CONSTEXPR constexpr
#endif #endif
// final keyword support. On by default. See tweakme.h
#if defined(SPDLOG_NO_FINAL)
#define SPDLOG_FINAL
#else
#define SPDLOG_FINAL final
#endif
#if defined(__GNUC__) || defined(__clang__) #if defined(__GNUC__) || defined(__clang__)
#define SPDLOG_DEPRECATED __attribute__((deprecated)) #define SPDLOG_DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
@@ -91,17 +85,17 @@ static const char *level_names[] SPDLOG_LEVEL_NAMES;
static const char *short_level_names[]{"T", "D", "I", "W", "E", "C", "O"}; static const char *short_level_names[]{"T", "D", "I", "W", "E", "C", "O"};
inline const char *to_c_str(spdlog::level::level_enum l) inline const char *to_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
{ {
return level_names[l]; return level_names[l];
} }
inline const char *to_short_c_str(spdlog::level::level_enum l) inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
{ {
return short_level_names[l]; return short_level_names[l];
} }
inline spdlog::level::level_enum from_str(const std::string &name) inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT
{ {
static std::unordered_map<std::string, level_enum> name_to_level = // map string->level static std::unordered_map<std::string, level_enum> name_to_level = // map string->level
{{level_names[0], level::trace}, // trace {{level_names[0], level::trace}, // trace
@@ -135,8 +129,8 @@ enum class pattern_time_type
class spdlog_ex : public std::exception class spdlog_ex : public std::exception
{ {
public: public:
explicit spdlog_ex(const std::string &msg) explicit spdlog_ex(std::string msg)
: msg_(msg) : msg_(std::move(msg))
{ {
} }
@@ -174,4 +168,19 @@ using filename_t = std::string;
{ \ { \
err_handler_("Unknown exeption in logger"); \ err_handler_("Unknown exeption in logger"); \
} }
namespace details {
// make_unique support for pre c++14
#if __cplusplus >= 201402L // C++14 and beyond
using std::make_unique;
#else
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args &&... args)
{
static_assert(!std::is_array<T>::value, "arrays not supported");
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif
} // namespace details
} // namespace spdlog } // namespace spdlog

View File

@@ -16,7 +16,7 @@
template<typename It> template<typename It>
inline spdlog::async_logger::async_logger( inline spdlog::async_logger::async_logger(
std::string logger_name, const It &begin, const It &end, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: logger(std::move(logger_name), begin, end) : logger(std::move(logger_name), begin, end)
, thread_pool_(tp) , thread_pool_(tp)
, overflow_policy_(overflow_policy) , overflow_policy_(overflow_policy)
@@ -67,7 +67,7 @@ inline void spdlog::async_logger::flush_()
// //
// backend functions - called from the thread pool to do the actual job // backend functions - called from the thread pool to do the actual job
// //
inline void spdlog::async_logger::backend_log_(details::log_msg &incoming_log_msg) inline void spdlog::async_logger::backend_log_(const details::log_msg &incoming_log_msg)
{ {
try try
{ {
@@ -98,3 +98,13 @@ inline void spdlog::async_logger::backend_flush_()
} }
SPDLOG_CATCH_AND_HANDLE SPDLOG_CATCH_AND_HANDLE
} }
inline std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name)
{
auto cloned = std::make_shared<spdlog::async_logger>(std::move(new_name), sinks_.begin(), sinks_.end(), thread_pool_, overflow_policy_);
cloned->set_level(this->level());
cloned->flush_on(this->flush_level());
cloned->set_error_handler(this->error_handler());
return std::move(cloned);
}

View File

@@ -8,6 +8,19 @@
#include <cstdio> #include <cstdio>
#include <mutex> #include <mutex>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX // prevent windows redefining min/max
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
namespace spdlog { namespace spdlog {
namespace details { namespace details {
struct console_stdout struct console_stdout

View File

@@ -5,13 +5,12 @@
#pragma once #pragma once
// Helper class for file sink // Helper class for file sinks.
// When failing to open a file, retry several times(5) with small delay between // When failing to open a file, retry several times(5) with a delay interval(10 ms).
// the tries(10 ms) // Throw spdlog_ex exception on errors.
// Throw spdlog_ex exception on errors
#include "../details/log_msg.h" #include "spdlog/details/log_msg.h"
#include "../details/os.h" #include "spdlog/details/os.h"
#include <cerrno> #include <cerrno>
#include <chrono> #include <chrono>
@@ -146,7 +145,7 @@ public:
} }
private: private:
FILE *fd_{nullptr}; std::FILE *fd_{nullptr};
filename_t _filename; filename_t _filename;
}; };
} // namespace details } // namespace details

View File

@@ -22,12 +22,8 @@ inline void append_str(const std::string &str, fmt::basic_memory_buffer<char, Bu
template<size_t Buffer_Size> template<size_t Buffer_Size>
inline void append_c_str(const char *c_str, fmt::basic_memory_buffer<char, Buffer_Size> &dest) inline void append_c_str(const char *c_str, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
{ {
char ch; auto len = std::char_traits<char>::length(c_str);
while ((ch = *c_str) != '\0') dest.append(c_str, c_str + len);
{
dest.push_back(ch);
++c_str;
}
} }
template<size_t Buffer_Size1, size_t Buffer_Size2> template<size_t Buffer_Size1, size_t Buffer_Size2>
@@ -54,14 +50,14 @@ inline void pad2(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
} }
if (n > 9) // 10-99 if (n > 9) // 10-99
{ {
dest.push_back('0' + static_cast<char>(n / 10)); dest.push_back(static_cast<char>('0' + n / 10));
dest.push_back('0' + static_cast<char>(n % 10)); dest.push_back(static_cast<char>('0' + n % 10));
return; return;
} }
if (n >= 0) // 0-9 if (n >= 0) // 0-9
{ {
dest.push_back('0'); dest.push_back('0');
dest.push_back('0' + static_cast<char>(n)); dest.push_back(static_cast<char>('0' + n));
return; return;
} }
// negatives (unlikely, but just in case, let fmt deal with it) // negatives (unlikely, but just in case, let fmt deal with it)
@@ -79,22 +75,22 @@ inline void pad3(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
if (n > 99) // 100-999 if (n > 99) // 100-999
{ {
append_int(n / 100, dest); dest.push_back(static_cast<char>('0' + n / 100));
pad2(n % 100, dest); pad2(n % 100, dest);
return; return;
} }
if (n > 9) // 10-99 if (n > 9) // 10-99
{ {
dest.push_back('0'); dest.push_back('0');
dest.push_back('0' + static_cast<char>(n / 10)); dest.push_back(static_cast<char>('0' + n / 10));
dest.push_back('0' + static_cast<char>(n % 10)); dest.push_back(static_cast<char>('0' + n % 10));
return; return;
} }
if (n >= 0) if (n >= 0)
{ {
dest.push_back('0'); dest.push_back('0');
dest.push_back('0'); dest.push_back('0');
dest.push_back('0' + static_cast<char>(n)); dest.push_back(static_cast<char>('0' + n));
return; return;
} }
// negatives (unlikely, but just in case let fmt deal with it) // negatives (unlikely, but just in case let fmt deal with it)
@@ -119,7 +115,8 @@ inline void pad6(size_t n, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
template<typename ToDuration> template<typename ToDuration>
inline ToDuration time_fraction(const log_clock::time_point &tp) inline ToDuration time_fraction(const log_clock::time_point &tp)
{ {
using namespace std::chrono; using std::chrono::duration_cast;
using std::chrono::seconds;
auto duration = tp.time_since_epoch(); auto duration = tp.time_since_epoch();
auto secs = duration_cast<seconds>(duration); auto secs = duration_cast<seconds>(duration);
return duration_cast<ToDuration>(duration) - duration_cast<ToDuration>(secs); return duration_cast<ToDuration>(duration) - duration_cast<ToDuration>(secs);

View File

@@ -39,8 +39,9 @@ struct log_msg
log_clock::time_point time; log_clock::time_point time;
size_t thread_id; size_t thread_id;
fmt::memory_buffer raw; fmt::memory_buffer raw;
size_t msg_id{0}; size_t msg_id;
// info about wrapping the formatted text with color
// info about wrapping the formatted text with color (updated by pattern_formatter).
mutable size_t color_range_start{0}; mutable size_t color_range_start{0};
mutable size_t color_range_end{0}; mutable size_t color_range_end{0};
}; };

View File

@@ -5,13 +5,15 @@
#pragma once #pragma once
#include "spdlog/details/fmt_helper.h"
#include <memory> #include <memory>
#include <string> #include <string>
// create logger with given name, sinks and the default pattern formatter // create logger with given name, sinks and the default pattern formatter
// all other ctors will call this one // all other ctors will call this one
template<typename It> template<typename It>
inline spdlog::logger::logger(std::string logger_name, const It &begin, const It &end) inline spdlog::logger::logger(std::string logger_name, It begin, It end)
: name_(std::move(logger_name)) : name_(std::move(logger_name))
, sinks_(begin, end) , sinks_(begin, end)
, level_(level::info) , level_(level::info)
@@ -47,7 +49,8 @@ inline void spdlog::logger::set_formatter(std::unique_ptr<spdlog::formatter> f)
inline void spdlog::logger::set_pattern(std::string pattern, pattern_time_type time_type) inline void spdlog::logger::set_pattern(std::string pattern, pattern_time_type time_type)
{ {
set_formatter(std::unique_ptr<spdlog::formatter>(new pattern_formatter(std::move(pattern), time_type))); auto new_formatter = details::make_unique<spdlog::pattern_formatter>(std::move(pattern), time_type);
set_formatter(std::move(new_formatter));
} }
template<typename... Args> template<typename... Args>
@@ -77,7 +80,7 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *msg)
try try
{ {
details::log_msg log_msg(&name_, lvl); details::log_msg log_msg(&name_, lvl);
fmt::format_to(log_msg.raw, "{}", msg); details::fmt_helper::append_c_str(msg, log_msg.raw);
sink_it_(log_msg); sink_it_(log_msg);
} }
SPDLOG_CATCH_AND_HANDLE SPDLOG_CATCH_AND_HANDLE
@@ -172,6 +175,28 @@ inline void spdlog::logger::critical(const T &msg)
} }
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target)
{
int wbuf_size = static_cast<int>(wbuf.size());
if (wbuf_size == 0)
{
return;
}
auto result_size = ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, NULL, 0, NULL, NULL);
if (result_size > 0)
{
target.resize(result_size);
::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, &target.data()[0], result_size, NULL, NULL);
}
else
{
throw spdlog::spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
}
}
template<typename... Args> template<typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args)
{ {
@@ -180,15 +205,14 @@ inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const
return; return;
} }
decltype(wstring_converter_)::byte_string utf8_string;
try try
{ {
{ // format to wmemory_buffer and convert to utf8
std::lock_guard<std::mutex> lock(wstring_converter_mutex_); details::log_msg log_msg(&name_, lvl);
utf8_string = wstring_converter_.to_bytes(fmt); fmt::wmemory_buffer wbuf;
} fmt::format_to(wbuf, fmt, args...);
log(lvl, utf8_string.c_str(), args...); wbuf_to_utf8buf(wbuf, log_msg.raw);
sink_it_(log_msg);
} }
SPDLOG_CATCH_AND_HANDLE SPDLOG_CATCH_AND_HANDLE
} }
@@ -268,6 +292,11 @@ inline void spdlog::logger::flush_on(level::level_enum log_level)
flush_level_.store(log_level); flush_level_.store(log_level);
} }
inline spdlog::level::level_enum spdlog::logger::flush_level() const
{
return static_cast<spdlog::level::level_enum>(flush_level_.load(std::memory_order_relaxed));
}
inline bool spdlog::logger::should_flush_(const details::log_msg &msg) inline bool spdlog::logger::should_flush_(const details::log_msg &msg)
{ {
auto flush_level = flush_level_.load(std::memory_order_relaxed); auto flush_level = flush_level_.load(std::memory_order_relaxed);
@@ -343,3 +372,12 @@ inline std::vector<spdlog::sink_ptr> &spdlog::logger::sinks()
{ {
return sinks_; return sinks_;
} }
inline std::shared_ptr<spdlog::logger> spdlog::logger::clone(std::string logger_name)
{
auto cloned = std::make_shared<spdlog::logger>(std::move(logger_name), sinks_.begin(), sinks_.end());
cloned->set_level(this->level());
cloned->flush_on(this->flush_level());
cloned->set_error_handler(this->error_handler());
return cloned;
}

View File

@@ -57,7 +57,7 @@ namespace spdlog {
namespace details { namespace details {
namespace os { namespace os {
inline spdlog::log_clock::time_point now() inline spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT
{ {
#if defined __linux__ && defined SPDLOG_CLOCK_COARSE #if defined __linux__ && defined SPDLOG_CLOCK_COARSE
@@ -70,7 +70,7 @@ inline spdlog::log_clock::time_point now()
return log_clock::now(); return log_clock::now();
#endif #endif
} }
inline std::tm localtime(const std::time_t &time_tt) inline std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{ {
#ifdef _WIN32 #ifdef _WIN32
@@ -83,13 +83,13 @@ inline std::tm localtime(const std::time_t &time_tt)
return tm; return tm;
} }
inline std::tm localtime() inline std::tm localtime() SPDLOG_NOEXCEPT
{ {
std::time_t now_t = time(nullptr); std::time_t now_t = time(nullptr);
return localtime(now_t); return localtime(now_t);
} }
inline std::tm gmtime(const std::time_t &time_tt) inline std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{ {
#ifdef _WIN32 #ifdef _WIN32
@@ -102,21 +102,11 @@ inline std::tm gmtime(const std::time_t &time_tt)
return tm; return tm;
} }
inline std::tm gmtime() inline std::tm gmtime() SPDLOG_NOEXCEPT
{ {
std::time_t now_t = time(nullptr); std::time_t now_t = time(nullptr);
return gmtime(now_t); return gmtime(now_t);
} }
inline bool operator==(const std::tm &tm1, const std::tm &tm2)
{
return (tm1.tm_sec == tm2.tm_sec && tm1.tm_min == tm2.tm_min && tm1.tm_hour == tm2.tm_hour && tm1.tm_mday == tm2.tm_mday &&
tm1.tm_mon == tm2.tm_mon && tm1.tm_year == tm2.tm_year && tm1.tm_isdst == tm2.tm_isdst);
}
inline bool operator!=(const std::tm &tm1, const std::tm &tm2)
{
return !(tm1 == tm2);
}
// eol definition // eol definition
#if !defined(SPDLOG_EOL) #if !defined(SPDLOG_EOL)
@@ -159,9 +149,9 @@ inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mod
{ {
#ifdef _WIN32 #ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES #ifdef SPDLOG_WCHAR_FILENAMES
*fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYWR); *fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#else #else
*fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYWR); *fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#endif #endif
#else // unix #else // unix
*fp = fopen((filename.c_str()), mode.c_str()); *fp = fopen((filename.c_str()), mode.c_str());
@@ -176,7 +166,7 @@ inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mod
return *fp == nullptr; return *fp == nullptr;
} }
inline int remove(const filename_t &filename) inline int remove(const filename_t &filename) SPDLOG_NOEXCEPT
{ {
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wremove(filename.c_str()); return _wremove(filename.c_str());
@@ -185,7 +175,7 @@ inline int remove(const filename_t &filename)
#endif #endif
} }
inline int rename(const filename_t &filename1, const filename_t &filename2) inline int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT
{ {
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wrename(filename1.c_str(), filename2.c_str()); return _wrename(filename1.c_str(), filename2.c_str());
@@ -195,7 +185,7 @@ inline int rename(const filename_t &filename1, const filename_t &filename2)
} }
// Return if file exists // Return if file exists
inline bool file_exists(const filename_t &filename) inline bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT
{ {
#ifdef _WIN32 #ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES #ifdef SPDLOG_WCHAR_FILENAMES
@@ -323,7 +313,7 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
// Return current thread id as size_t // Return current thread id as size_t
// It exists because the std::this_thread::get_id() is much slower(especially // It exists because the std::this_thread::get_id() is much slower(especially
// under VS 2013) // under VS 2013)
inline size_t _thread_id() inline size_t _thread_id() SPDLOG_NOEXCEPT
{ {
#ifdef _WIN32 #ifdef _WIN32
return static_cast<size_t>(::GetCurrentThreadId()); return static_cast<size_t>(::GetCurrentThreadId());
@@ -346,7 +336,7 @@ inline size_t _thread_id()
} }
// Return current thread id as size_t (from thread local storage) // Return current thread id as size_t (from thread local storage)
inline size_t thread_id() inline size_t thread_id() SPDLOG_NOEXCEPT
{ {
#if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) || \ #if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) || \
(defined(__clang__) && !__has_feature(cxx_thread_local)) (defined(__clang__) && !__has_feature(cxx_thread_local))
@@ -359,7 +349,7 @@ inline size_t thread_id()
// This is avoid msvc issue in sleep_for that happens if the clock changes. // This is avoid msvc issue in sleep_for that happens if the clock changes.
// See https://github.com/gabime/spdlog/issues/609 // See https://github.com/gabime/spdlog/issues/609
inline void sleep_for_millis(int milliseconds) inline void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT
{ {
#if defined(_WIN32) #if defined(_WIN32)
::Sleep(milliseconds); ::Sleep(milliseconds);
@@ -396,7 +386,7 @@ inline int pid()
// Determine if the terminal supports colors // Determine if the terminal supports colors
// Source: https://github.com/agauniyal/rang/ // Source: https://github.com/agauniyal/rang/
inline bool is_color_terminal() inline bool is_color_terminal() SPDLOG_NOEXCEPT
{ {
#ifdef _WIN32 #ifdef _WIN32
return true; return true;
@@ -418,7 +408,7 @@ inline bool is_color_terminal()
// Detrmine if the terminal attached // Detrmine if the terminal attached
// Source: https://github.com/agauniyal/rang/ // Source: https://github.com/agauniyal/rang/
inline bool in_terminal(FILE *file) inline bool in_terminal(FILE *file) SPDLOG_NOEXCEPT
{ {
#ifdef _WIN32 #ifdef _WIN32

View File

@@ -116,7 +116,7 @@ class B_formatter : public flag_formatter
}; };
// Date and time representation (Thu Aug 23 15:35:46 2014) // Date and time representation (Thu Aug 23 15:35:46 2014)
class c_formatter SPDLOG_FINAL : public flag_formatter class c_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -142,7 +142,7 @@ class c_formatter SPDLOG_FINAL : public flag_formatter
}; };
// year - 2 digit // year - 2 digit
class C_formatter SPDLOG_FINAL : public flag_formatter class C_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -151,7 +151,7 @@ class C_formatter SPDLOG_FINAL : public flag_formatter
}; };
// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 // Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01
class D_formatter SPDLOG_FINAL : public flag_formatter class D_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -164,7 +164,7 @@ class D_formatter SPDLOG_FINAL : public flag_formatter
}; };
// year - 4 digit // year - 4 digit
class Y_formatter SPDLOG_FINAL : public flag_formatter class Y_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -173,7 +173,7 @@ class Y_formatter SPDLOG_FINAL : public flag_formatter
}; };
// month 1-12 // month 1-12
class m_formatter SPDLOG_FINAL : public flag_formatter class m_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -182,7 +182,7 @@ class m_formatter SPDLOG_FINAL : public flag_formatter
}; };
// day of month 1-31 // day of month 1-31
class d_formatter SPDLOG_FINAL : public flag_formatter class d_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -191,7 +191,7 @@ class d_formatter SPDLOG_FINAL : public flag_formatter
}; };
// hours in 24 format 0-23 // hours in 24 format 0-23
class H_formatter SPDLOG_FINAL : public flag_formatter class H_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -200,7 +200,7 @@ class H_formatter SPDLOG_FINAL : public flag_formatter
}; };
// hours in 12 format 1-12 // hours in 12 format 1-12
class I_formatter SPDLOG_FINAL : public flag_formatter class I_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -209,7 +209,7 @@ class I_formatter SPDLOG_FINAL : public flag_formatter
}; };
// minutes 0-59 // minutes 0-59
class M_formatter SPDLOG_FINAL : public flag_formatter class M_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -218,7 +218,7 @@ class M_formatter SPDLOG_FINAL : public flag_formatter
}; };
// seconds 0-59 // seconds 0-59
class S_formatter SPDLOG_FINAL : public flag_formatter class S_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -227,7 +227,7 @@ class S_formatter SPDLOG_FINAL : public flag_formatter
}; };
// milliseconds // milliseconds
class e_formatter SPDLOG_FINAL : public flag_formatter class e_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -237,7 +237,7 @@ class e_formatter SPDLOG_FINAL : public flag_formatter
}; };
// microseconds // microseconds
class f_formatter SPDLOG_FINAL : public flag_formatter class f_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -247,7 +247,7 @@ class f_formatter SPDLOG_FINAL : public flag_formatter
}; };
// nanoseconds // nanoseconds
class F_formatter SPDLOG_FINAL : public flag_formatter class F_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -257,7 +257,7 @@ class F_formatter SPDLOG_FINAL : public flag_formatter
}; };
// seconds since epoch // seconds since epoch
class E_formatter SPDLOG_FINAL : public flag_formatter class E_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -268,7 +268,7 @@ class E_formatter SPDLOG_FINAL : public flag_formatter
}; };
// AM/PM // AM/PM
class p_formatter SPDLOG_FINAL : public flag_formatter class p_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -277,7 +277,7 @@ class p_formatter SPDLOG_FINAL : public flag_formatter
}; };
// 12 hour clock 02:55:02 pm // 12 hour clock 02:55:02 pm
class r_formatter SPDLOG_FINAL : public flag_formatter class r_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -292,7 +292,7 @@ class r_formatter SPDLOG_FINAL : public flag_formatter
}; };
// 24-hour HH:MM time, equivalent to %H:%M // 24-hour HH:MM time, equivalent to %H:%M
class R_formatter SPDLOG_FINAL : public flag_formatter class R_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -303,7 +303,7 @@ class R_formatter SPDLOG_FINAL : public flag_formatter
}; };
// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S // ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
class T_formatter SPDLOG_FINAL : public flag_formatter class T_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
@@ -318,7 +318,7 @@ class T_formatter SPDLOG_FINAL : public flag_formatter
}; };
// ISO 8601 offset from UTC in timezone (+-HH:MM) // ISO 8601 offset from UTC in timezone (+-HH:MM)
class z_formatter SPDLOG_FINAL : public flag_formatter class z_formatter final : public flag_formatter
{ {
public: public:
const std::chrono::seconds cache_refresh = std::chrono::seconds(5); const std::chrono::seconds cache_refresh = std::chrono::seconds(5);
@@ -371,7 +371,7 @@ private:
}; };
// Thread id // Thread id
class t_formatter SPDLOG_FINAL : public flag_formatter class t_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -380,7 +380,7 @@ class t_formatter SPDLOG_FINAL : public flag_formatter
}; };
// Current pid // Current pid
class pid_formatter SPDLOG_FINAL : public flag_formatter class pid_formatter final : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -389,7 +389,7 @@ class pid_formatter SPDLOG_FINAL : public flag_formatter
}; };
// message counter formatter // message counter formatter
class i_formatter SPDLOG_FINAL : public flag_formatter class i_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -397,7 +397,7 @@ class i_formatter SPDLOG_FINAL : public flag_formatter
} }
}; };
class v_formatter SPDLOG_FINAL : public flag_formatter class v_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -405,7 +405,7 @@ class v_formatter SPDLOG_FINAL : public flag_formatter
} }
}; };
class ch_formatter SPDLOG_FINAL : public flag_formatter class ch_formatter final : public flag_formatter
{ {
public: public:
explicit ch_formatter(char ch) explicit ch_formatter(char ch)
@@ -422,7 +422,7 @@ private:
}; };
// aggregate user chars to display as is // aggregate user chars to display as is
class aggregate_formatter SPDLOG_FINAL : public flag_formatter class aggregate_formatter final : public flag_formatter
{ {
public: public:
aggregate_formatter() = default; aggregate_formatter() = default;
@@ -441,14 +441,14 @@ private:
}; };
// mark the color range. expect it to be in the form of "%^colored text%$" // mark the color range. expect it to be in the form of "%^colored text%$"
class color_start_formatter SPDLOG_FINAL : public flag_formatter class color_start_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
msg.color_range_start = dest.size(); msg.color_range_start = dest.size();
} }
}; };
class color_stop_formatter SPDLOG_FINAL : public flag_formatter class color_stop_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override
{ {
@@ -458,11 +458,14 @@ class color_stop_formatter SPDLOG_FINAL : public flag_formatter
// Full info formatter // Full info formatter
// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v // pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v
class full_formatter SPDLOG_FINAL : public flag_formatter class full_formatter final : public flag_formatter
{ {
void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
using namespace std::chrono; using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::seconds;
#ifndef SPDLOG_NO_DATETIME #ifndef SPDLOG_NO_DATETIME
// cache the date/time part for the next second. // cache the date/time part for the next second.
@@ -471,7 +474,7 @@ class full_formatter SPDLOG_FINAL : public flag_formatter
if (cache_timestamp_ != secs || cached_datetime_.size() == 0) if (cache_timestamp_ != secs || cached_datetime_.size() == 0)
{ {
cached_datetime_.resize(0); cached_datetime_.clear();
cached_datetime_.push_back('['); cached_datetime_.push_back('[');
fmt_helper::append_int(tm_time.tm_year + 1900, cached_datetime_); fmt_helper::append_int(tm_time.tm_year + 1900, cached_datetime_);
cached_datetime_.push_back('-'); cached_datetime_.push_back('-');
@@ -528,7 +531,7 @@ private:
} // namespace details } // namespace details
class pattern_formatter SPDLOG_FINAL : public formatter class pattern_formatter final : public formatter
{ {
public: public:
explicit pattern_formatter( explicit pattern_formatter(
@@ -547,7 +550,7 @@ public:
std::unique_ptr<formatter> clone() const override std::unique_ptr<formatter> clone() const override
{ {
return std::unique_ptr<formatter>(new pattern_formatter(pattern_, pattern_time_type_, eol_)); return details::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_);
} }
void format(const details::log_msg &msg, fmt::memory_buffer &dest) override void format(const details::log_msg &msg, fmt::memory_buffer &dest) override
@@ -588,146 +591,145 @@ private:
void handle_flag_(char flag) void handle_flag_(char flag)
{ {
using flag_formatter_ptr = std::unique_ptr<details::flag_formatter>;
switch (flag) switch (flag)
{ {
// logger name // logger name
case 'n': case 'n':
formatters_.push_back(flag_formatter_ptr(new details::name_formatter())); formatters_.push_back(details::make_unique<details::name_formatter>());
break; break;
case 'l': case 'l':
formatters_.push_back(flag_formatter_ptr(new details::level_formatter())); formatters_.push_back(details::make_unique<details::level_formatter>());
break; break;
case 'L': case 'L':
formatters_.push_back(flag_formatter_ptr(new details::short_level_formatter())); formatters_.push_back(details::make_unique<details::short_level_formatter>());
break; break;
case ('t'): case ('t'):
formatters_.push_back(flag_formatter_ptr(new details::t_formatter())); formatters_.push_back(details::make_unique<details::t_formatter>());
break; break;
case ('v'): case ('v'):
formatters_.push_back(flag_formatter_ptr(new details::v_formatter())); formatters_.push_back(details::make_unique<details::v_formatter>());
break; break;
case ('a'): case ('a'):
formatters_.push_back(flag_formatter_ptr(new details::a_formatter())); formatters_.push_back(details::make_unique<details::a_formatter>());
break; break;
case ('A'): case ('A'):
formatters_.push_back(flag_formatter_ptr(new details::A_formatter())); formatters_.push_back(details::make_unique<details::A_formatter>());
break; break;
case ('b'): case ('b'):
case ('h'): case ('h'):
formatters_.push_back(flag_formatter_ptr(new details::b_formatter())); formatters_.push_back(details::make_unique<details::b_formatter>());
break; break;
case ('B'): case ('B'):
formatters_.push_back(flag_formatter_ptr(new details::B_formatter())); formatters_.push_back(details::make_unique<details::B_formatter>());
break; break;
case ('c'): case ('c'):
formatters_.push_back(flag_formatter_ptr(new details::c_formatter())); formatters_.push_back(details::make_unique<details::c_formatter>());
break; break;
case ('C'): case ('C'):
formatters_.push_back(flag_formatter_ptr(new details::C_formatter())); formatters_.push_back(details::make_unique<details::C_formatter>());
break; break;
case ('Y'): case ('Y'):
formatters_.push_back(flag_formatter_ptr(new details::Y_formatter())); formatters_.push_back(details::make_unique<details::Y_formatter>());
break; break;
case ('D'): case ('D'):
case ('x'): case ('x'):
formatters_.push_back(flag_formatter_ptr(new details::D_formatter())); formatters_.push_back(details::make_unique<details::D_formatter>());
break; break;
case ('m'): case ('m'):
formatters_.push_back(flag_formatter_ptr(new details::m_formatter())); formatters_.push_back(details::make_unique<details::m_formatter>());
break; break;
case ('d'): case ('d'):
formatters_.push_back(flag_formatter_ptr(new details::d_formatter())); formatters_.push_back(details::make_unique<details::d_formatter>());
break; break;
case ('H'): case ('H'):
formatters_.push_back(flag_formatter_ptr(new details::H_formatter())); formatters_.push_back(details::make_unique<details::H_formatter>());
break; break;
case ('I'): case ('I'):
formatters_.push_back(flag_formatter_ptr(new details::I_formatter())); formatters_.push_back(details::make_unique<details::I_formatter>());
break; break;
case ('M'): case ('M'):
formatters_.push_back(flag_formatter_ptr(new details::M_formatter())); formatters_.push_back(details::make_unique<details::M_formatter>());
break; break;
case ('S'): case ('S'):
formatters_.push_back(flag_formatter_ptr(new details::S_formatter())); formatters_.push_back(details::make_unique<details::S_formatter>());
break; break;
case ('e'): case ('e'):
formatters_.push_back(flag_formatter_ptr(new details::e_formatter())); formatters_.push_back(details::make_unique<details::e_formatter>());
break; break;
case ('f'): case ('f'):
formatters_.push_back(flag_formatter_ptr(new details::f_formatter())); formatters_.push_back(details::make_unique<details::f_formatter>());
break; break;
case ('F'): case ('F'):
formatters_.push_back(flag_formatter_ptr(new details::F_formatter())); formatters_.push_back(details::make_unique<details::F_formatter>());
break; break;
case ('E'): case ('E'):
formatters_.push_back(flag_formatter_ptr(new details::E_formatter())); formatters_.push_back(details::make_unique<details::E_formatter>());
break; break;
case ('p'): case ('p'):
formatters_.push_back(flag_formatter_ptr(new details::p_formatter())); formatters_.push_back(details::make_unique<details::p_formatter>());
break; break;
case ('r'): case ('r'):
formatters_.push_back(flag_formatter_ptr(new details::r_formatter())); formatters_.push_back(details::make_unique<details::r_formatter>());
break; break;
case ('R'): case ('R'):
formatters_.push_back(flag_formatter_ptr(new details::R_formatter())); formatters_.push_back(details::make_unique<details::R_formatter>());
break; break;
case ('T'): case ('T'):
case ('X'): case ('X'):
formatters_.push_back(flag_formatter_ptr(new details::T_formatter())); formatters_.push_back(details::make_unique<details::T_formatter>());
break; break;
case ('z'): case ('z'):
formatters_.push_back(flag_formatter_ptr(new details::z_formatter())); formatters_.push_back(details::make_unique<details::z_formatter>());
break; break;
case ('+'): case ('+'):
formatters_.push_back(flag_formatter_ptr(new details::full_formatter())); formatters_.push_back(details::make_unique<details::full_formatter>());
break; break;
case ('P'): case ('P'):
formatters_.push_back(flag_formatter_ptr(new details::pid_formatter())); formatters_.push_back(details::make_unique<details::pid_formatter>());
break; break;
#ifdef SPDLOG_ENABLE_MESSAGE_COUNTER
case ('i'): case ('i'):
formatters_.push_back(flag_formatter_ptr(new details::i_formatter())); formatters_.push_back(details::make_unique<details::i_formatter>());
break; break;
#endif
case ('^'): case ('^'):
formatters_.push_back(flag_formatter_ptr(new details::color_start_formatter())); formatters_.push_back(details::make_unique<details::color_start_formatter>());
break; break;
case ('$'): case ('$'):
formatters_.push_back(flag_formatter_ptr(new details::color_stop_formatter())); formatters_.push_back(details::make_unique<details::color_stop_formatter>());
break; break;
default: // Unknown flag appears as is default: // Unknown flag appears as is
formatters_.push_back(flag_formatter_ptr(new details::ch_formatter('%'))); formatters_.push_back(details::make_unique<details::ch_formatter>('%'));
formatters_.push_back(flag_formatter_ptr(new details::ch_formatter(flag))); formatters_.push_back(details::make_unique<details::ch_formatter>(flag));
break; break;
} }
} }
@@ -758,7 +760,7 @@ private:
{ {
if (!user_chars) if (!user_chars)
{ {
user_chars = std::unique_ptr<details::aggregate_formatter>(new details::aggregate_formatter()); user_chars = details::make_unique<details::aggregate_formatter>();
} }
user_chars->add_ch(*it); user_chars->add_ch(*it);
} }

View File

@@ -113,7 +113,7 @@ public:
{ {
std::lock_guard<std::mutex> lock(flusher_mutex_); std::lock_guard<std::mutex> lock(flusher_mutex_);
std::function<void()> clbk = std::bind(&registry::flush_all, this); std::function<void()> clbk = std::bind(&registry::flush_all, this);
periodic_flusher_.reset(new periodic_worker(clbk, interval)); periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
} }
void set_error_handler(log_err_handler handler) void set_error_handler(log_err_handler handler)

View File

@@ -64,8 +64,8 @@ struct async_msg
return *this; return *this;
} }
#else // (_MSC_VER) && _MSC_VER <= 1800 #else // (_MSC_VER) && _MSC_VER <= 1800
async_msg(async_msg &&other) = default; async_msg(async_msg &&) = default;
async_msg &operator=(async_msg &&other) = default; async_msg &operator=(async_msg &&) = default;
#endif #endif
// construct from log_msg with given type // construct from log_msg with given type
@@ -75,13 +75,13 @@ struct async_msg
, time(m.time) , time(m.time)
, thread_id(m.thread_id) , thread_id(m.thread_id)
, msg_id(m.msg_id) , msg_id(m.msg_id)
, worker_ptr(std::forward<async_logger_ptr>(worker)) , worker_ptr(std::move(worker))
{ {
fmt_helper::append_buf(m.raw, raw); fmt_helper::append_buf(m.raw, raw);
} }
async_msg(async_logger_ptr &&worker, async_msg_type the_type) async_msg(async_logger_ptr &&worker, async_msg_type the_type)
: async_msg(std::forward<async_logger_ptr>(worker), the_type, details::log_msg()) : async_msg(std::move(worker), the_type, details::log_msg())
{ {
} }
@@ -146,9 +146,12 @@ public:
} }
} }
thread_pool(const thread_pool &) = delete;
thread_pool &operator=(thread_pool &&) = delete;
void post_log(async_logger_ptr &&worker_ptr, details::log_msg &&msg, async_overflow_policy overflow_policy) void post_log(async_logger_ptr &&worker_ptr, details::log_msg &&msg, async_overflow_policy overflow_policy)
{ {
async_msg async_m(std::forward<async_logger_ptr>(worker_ptr), async_msg_type::log, std::forward<log_msg>(msg)); async_msg async_m(std::move(worker_ptr), async_msg_type::log, std::move(msg));
post_async_msg_(std::move(async_m), overflow_policy); post_async_msg_(std::move(async_m), overflow_policy);
} }
@@ -198,6 +201,13 @@ private:
switch (incoming_async_msg.msg_type) switch (incoming_async_msg.msg_type)
{ {
case async_msg_type::log:
{
log_msg msg;
incoming_async_msg.to_log_msg(msg);
incoming_async_msg.worker_ptr->backend_log_(msg);
return true;
}
case async_msg_type::flush: case async_msg_type::flush:
{ {
incoming_async_msg.worker_ptr->backend_flush_(); incoming_async_msg.worker_ptr->backend_flush_();
@@ -208,17 +218,10 @@ private:
{ {
return false; return false;
} }
}
default: assert(false && "Unexpected async_msg_type");
{
log_msg msg;
incoming_async_msg.to_log_msg(msg);
incoming_async_msg.worker_ptr->backend_log_(msg);
return true; return true;
} }
}
return true; // should not be reached
}
}; };
} // namespace details } // namespace details

View File

@@ -0,0 +1,172 @@
//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// Support for logging binary data as hex
// format flags:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines.
//
// Examples:
//
// std::vector<char> v(200, 0x0b);
// logger->info("Some buffer {}", spdlog::to_hex(v));
// char buf[128];
// logger->info("Some buffer {:X}", spdlog::to_hex(std::begin(buf), std::end(buf)));
namespace spdlog {
namespace details {
template<typename It>
class bytes_range
{
public:
bytes_range(It range_begin, It range_end)
: begin_(range_begin)
, end_(range_end)
{
}
It begin() const
{
return begin_;
}
It end() const
{
return end_;
}
private:
It begin_, end_;
};
} // namespace details
// create a bytes_range that wraps the given container
template<typename Container>
inline details::bytes_range<typename Container::const_iterator> to_hex(const Container &container)
{
static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1");
using Iter = typename Container::const_iterator;
return details::bytes_range<Iter>(std::begin(container), std::end(container));
}
// create bytes_range from ranges
template<typename It>
inline details::bytes_range<It> to_hex(const It range_begin, const It range_end)
{
return details::bytes_range<It>(range_begin, range_end);
}
} // namespace spdlog
namespace fmt {
template<typename T>
struct formatter<spdlog::details::bytes_range<T>>
{
const std::size_t line_size = 100;
const char delimiter = ' ';
bool put_newlines = true;
bool put_delimiters = true;
bool use_uppercase = false;
bool put_positions = true; // position on start of each line
// parse the format string flags
template<typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin())
{
auto it = ctx.begin();
while (*it && *it != '}')
{
switch (*it)
{
case 'X':
use_uppercase = true;
break;
case 's':
put_delimiters = false;
break;
case 'p':
put_positions = false;
break;
case 'n':
put_newlines = false;
break;
}
++it;
}
return it;
}
// format the given bytes range as hex
template<typename FormatContext, typename Container>
auto format(const spdlog::details::bytes_range<Container> &the_range, FormatContext &ctx) -> decltype(ctx.out())
{
constexpr const char *hex_upper = "0123456789ABCDEF";
constexpr const char *hex_lower = "0123456789abcdef";
const char *hex_chars = use_uppercase ? hex_upper : hex_lower;
std::size_t pos = 0;
std::size_t column = line_size;
auto inserter = ctx.begin();
for (auto &item : the_range)
{
auto ch = static_cast<unsigned char>(item);
pos++;
if (put_newlines && column >= line_size)
{
column = put_newline(inserter, pos);
// put first byte without delimiter in front of it
*inserter++ = hex_chars[(ch >> 4) & 0x0f];
*inserter++ = hex_chars[ch & 0x0f];
column += 2;
continue;
}
if (put_delimiters)
{
*inserter++ = delimiter;
++column;
}
*inserter++ = hex_chars[(ch >> 4) & 0x0f];
*inserter++ = hex_chars[ch & 0x0f];
column += 2;
}
return inserter;
}
// put newline(and position header)
// return the next column
template<typename It>
std::size_t put_newline(It inserter, std::size_t pos)
{
#ifdef _WIN32
*inserter++ = '\r';
#endif
*inserter++ = '\n';
if (put_positions)
{
fmt::format_to(inserter, "{:<04X}: ", pos - 1);
return 7;
}
else
{
return 1;
}
}
};
} // namespace fmt

File diff suppressed because it is too large Load Diff

View File

@@ -18,10 +18,9 @@
#include <cmath> #include <cmath>
#include <cstdarg> #include <cstdarg>
#include <cstddef> // for std::ptrdiff_t #include <cstddef> // for std::ptrdiff_t
#include <cstring> // for std::memmove
#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
# include <locale> # include <locale>
#if defined(_WIN32) && defined(__MINGW32__)
#include <cstring>
#endif #endif
#if FMT_USE_WINDOWS_H #if FMT_USE_WINDOWS_H
@@ -56,12 +55,10 @@
// Dummy implementations of strerror_r and strerror_s called if corresponding // Dummy implementations of strerror_r and strerror_s called if corresponding
// system functions are not available. // system functions are not available.
inline fmt::internal::null<> strerror_r(int, char *, ...) inline fmt::internal::null<> strerror_r(int, char *, ...) {
{
return fmt::internal::null<>(); return fmt::internal::null<>();
} }
inline fmt::internal::null<> strerror_s(char *, std::size_t, ...) inline fmt::internal::null<> strerror_s(char *, std::size_t, ...) {
{
return fmt::internal::null<>(); return fmt::internal::null<>();
} }
@@ -72,8 +69,7 @@ namespace {
#ifndef _MSC_VER #ifndef _MSC_VER
# define FMT_SNPRINTF snprintf # define FMT_SNPRINTF snprintf
#else // _MSC_VER #else // _MSC_VER
inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) {
{
va_list args; va_list args;
va_start(args, format); va_start(args, format);
int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args);
@@ -100,12 +96,11 @@ typedef void (*FormatFunc)(internal::buffer &, int, string_view);
// ERANGE - buffer is not large enough to store the error message // ERANGE - buffer is not large enough to store the error message
// other - failure // other - failure
// Buffer should be at least of size 1. // Buffer should be at least of size 1.
int safe_strerror(int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT int safe_strerror(
{ int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT {
FMT_ASSERT(buffer != FMT_NULL && buffer_size != 0, "invalid buffer"); FMT_ASSERT(buffer != FMT_NULL && buffer_size != 0, "invalid buffer");
class dispatcher class dispatcher {
{
private: private:
int error_code_; int error_code_;
char *&buffer_; char *&buffer_;
@@ -115,15 +110,13 @@ int safe_strerror(int error_code, char *&buffer, std::size_t buffer_size) FMT_NO
void operator=(const dispatcher &) {} void operator=(const dispatcher &) {}
// Handle the result of XSI-compliant version of strerror_r. // Handle the result of XSI-compliant version of strerror_r.
int handle(int result) int handle(int result) {
{
// glibc versions before 2.13 return result in errno. // glibc versions before 2.13 return result in errno.
return result == -1 ? errno : result; return result == -1 ? errno : result;
} }
// Handle the result of GNU-specific version of strerror_r. // Handle the result of GNU-specific version of strerror_r.
int handle(char *message) int handle(char *message) {
{
// If the buffer is full then the message is probably truncated. // If the buffer is full then the message is probably truncated.
if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1)
return ERANGE; return ERANGE;
@@ -132,21 +125,19 @@ int safe_strerror(int error_code, char *&buffer, std::size_t buffer_size) FMT_NO
} }
// Handle the case when strerror_r is not available. // Handle the case when strerror_r is not available.
int handle(internal::null<>) int handle(internal::null<>) {
{
return fallback(strerror_s(buffer_, buffer_size_, error_code_)); return fallback(strerror_s(buffer_, buffer_size_, error_code_));
} }
// Fallback to strerror_s when strerror_r is not available. // Fallback to strerror_s when strerror_r is not available.
int fallback(int result) int fallback(int result) {
{
// If the buffer is full then the message is probably truncated. // If the buffer is full then the message is probably truncated.
return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE : result; return result == 0 && strlen(buffer_) == buffer_size_ - 1 ?
ERANGE : result;
} }
// Fallback to strerror if strerror_r and strerror_s are not available. // Fallback to strerror if strerror_r and strerror_s are not available.
int fallback(internal::null<>) int fallback(internal::null<>) {
{
errno = 0; errno = 0;
buffer_ = strerror(error_code_); buffer_ = strerror(error_code_);
return errno; return errno;
@@ -154,22 +145,17 @@ int safe_strerror(int error_code, char *&buffer, std::size_t buffer_size) FMT_NO
public: public:
dispatcher(int err_code, char *&buf, std::size_t buf_size) dispatcher(int err_code, char *&buf, std::size_t buf_size)
: error_code_(err_code) : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {}
, buffer_(buf)
, buffer_size_(buf_size)
{
}
int run() int run() {
{
return handle(strerror_r(error_code_, buffer_, buffer_size_)); return handle(strerror_r(error_code_, buffer_, buffer_size_));
} }
}; };
return dispatcher(error_code, buffer, buffer_size).run(); return dispatcher(error_code, buffer, buffer_size).run();
} }
void format_error_code(internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT void format_error_code(internal::buffer &out, int error_code,
{ string_view message) FMT_NOEXCEPT {
// Report error code making sure that the output fits into // Report error code making sure that the output fits into
// inline_buffer_size to avoid dynamic memory allocation and potential // inline_buffer_size to avoid dynamic memory allocation and potential
// bad_alloc. // bad_alloc.
@@ -180,15 +166,13 @@ void format_error_code(internal::buffer &out, int error_code, string_view messag
std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2;
typedef internal::int_traits<int>::main_type main_type; typedef internal::int_traits<int>::main_type main_type;
main_type abs_value = static_cast<main_type>(error_code); main_type abs_value = static_cast<main_type>(error_code);
if (internal::is_negative(error_code)) if (internal::is_negative(error_code)) {
{
abs_value = 0 - abs_value; abs_value = 0 - abs_value;
++error_code_size; ++error_code_size;
} }
error_code_size += internal::count_digits(abs_value); error_code_size += internal::count_digits(abs_value);
writer w(out); writer w(out);
if (message.size() <= inline_buffer_size - error_code_size) if (message.size() <= inline_buffer_size - error_code_size) {
{
w.write(message); w.write(message);
w.write(SEP); w.write(SEP);
} }
@@ -197,8 +181,8 @@ void format_error_code(internal::buffer &out, int error_code, string_view messag
assert(out.size() <= inline_buffer_size); assert(out.size() <= inline_buffer_size);
} }
void report_error(FormatFunc func, int error_code, string_view message) FMT_NOEXCEPT void report_error(FormatFunc func, int error_code,
{ string_view message) FMT_NOEXCEPT {
memory_buffer full_message; memory_buffer full_message;
func(full_message, error_code, message); func(full_message, error_code, message);
// Use Writer::data instead of Writer::c_str to avoid potential memory // Use Writer::data instead of Writer::c_str to avoid potential memory
@@ -208,31 +192,40 @@ void report_error(FormatFunc func, int error_code, string_view message) FMT_NOEX
} }
} // namespace } // namespace
class locale #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
{ class locale {
private: private:
std::locale locale_; std::locale locale_;
public: public:
explicit locale(std::locale loc = std::locale()) explicit locale(std::locale loc = std::locale()) : locale_(loc) {}
: locale_(loc) std::locale get() { return locale_; }
{
}
std::locale get()
{
return locale_;
}
}; };
FMT_FUNC size_t internal::count_code_points(u8string_view s) {
const char8_t *data = s.data();
int num_code_points = 0;
for (size_t i = 0, size = s.size(); i != size; ++i) {
if ((data[i].value & 0xc0) != 0x80)
++num_code_points;
}
return num_code_points;
}
template <typename Char> template <typename Char>
FMT_FUNC Char internal::thousands_sep(locale_provider *lp) FMT_FUNC Char internal::thousands_sep(locale_provider *lp) {
{
std::locale loc = lp ? lp->locale().get() : std::locale(); std::locale loc = lp ? lp->locale().get() : std::locale();
return std::use_facet<std::numpunct<Char>>(loc).thousands_sep(); return std::use_facet<std::numpunct<Char>>(loc).thousands_sep();
} }
#else
template <typename Char>
FMT_FUNC Char internal::thousands_sep(locale_provider *lp) {
return FMT_STATIC_THOUSANDS_SEPARATOR;
}
#endif
FMT_FUNC void system_error::init(int err_code, string_view format_str, format_args args) FMT_FUNC void system_error::init(
{ int err_code, string_view format_str, format_args args) {
error_code_ = err_code; error_code_ = err_code;
memory_buffer buffer; memory_buffer buffer;
format_system_error(buffer, err_code, vformat(format_str, args)); format_system_error(buffer, err_code, vformat(format_str, args));
@@ -242,68 +235,202 @@ FMT_FUNC void system_error::init(int err_code, string_view format_str, format_ar
namespace internal { namespace internal {
template <typename T> template <typename T>
int char_traits<char>::format_float(char *buffer, std::size_t size, const char *format, int precision, T value) int char_traits<char>::format_float(
{ char *buffer, std::size_t size, const char *format, int precision, T value) {
return precision < 0 ? FMT_SNPRINTF(buffer, size, format, value) : FMT_SNPRINTF(buffer, size, format, precision, value); return precision < 0 ?
FMT_SNPRINTF(buffer, size, format, value) :
FMT_SNPRINTF(buffer, size, format, precision, value);
} }
template <typename T> template <typename T>
int char_traits<wchar_t>::format_float(wchar_t *buffer, std::size_t size, const wchar_t *format, int precision, T value) int char_traits<wchar_t>::format_float(
{ wchar_t *buffer, std::size_t size, const wchar_t *format, int precision,
return precision < 0 ? FMT_SWPRINTF(buffer, size, format, value) : FMT_SWPRINTF(buffer, size, format, precision, value); T value) {
return precision < 0 ?
FMT_SWPRINTF(buffer, size, format, value) :
FMT_SWPRINTF(buffer, size, format, precision, value);
} }
template <typename T> template <typename T>
const char basic_data<T>::DIGITS[] = "0001020304050607080910111213141516171819" const char basic_data<T>::DIGITS[] =
"0001020304050607080910111213141516171819"
"2021222324252627282930313233343536373839" "2021222324252627282930313233343536373839"
"4041424344454647484950515253545556575859" "4041424344454647484950515253545556575859"
"6061626364656667686970717273747576777879" "6061626364656667686970717273747576777879"
"8081828384858687888990919293949596979899"; "8081828384858687888990919293949596979899";
#define FMT_POWERS_OF_10(factor) \ #define FMT_POWERS_OF_10(factor) \
factor * 10, factor * 100, factor * 1000, factor * 10000, factor * 100000, factor * 1000000, factor * 10000000, factor * 100000000, \ factor * 10, \
factor * 100, \
factor * 1000, \
factor * 10000, \
factor * 100000, \
factor * 1000000, \
factor * 10000000, \
factor * 100000000, \
factor * 1000000000 factor * 1000000000
template <typename T> template <typename T>
const uint32_t basic_data<T>::POWERS_OF_10_32[] = {0, FMT_POWERS_OF_10(1)}; const uint32_t basic_data<T>::POWERS_OF_10_32[] = {
1, FMT_POWERS_OF_10(1)
};
template <typename T> template <typename T>
const uint64_t basic_data<T>::POWERS_OF_10_64[] = {0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull), 10000000000000000000ull}; const uint32_t basic_data<T>::ZERO_OR_POWERS_OF_10_32[] = {
0, FMT_POWERS_OF_10(1)
};
template <typename T>
const uint64_t basic_data<T>::ZERO_OR_POWERS_OF_10_64[] = {
0,
FMT_POWERS_OF_10(1),
FMT_POWERS_OF_10(1000000000ull),
10000000000000000000ull
};
// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340. // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
// These are generated by support/compute-powers.py. // These are generated by support/compute-powers.py.
template <typename T> template <typename T>
const uint64_t basic_data<T>::POW10_SIGNIFICANDS[] = {0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76, 0xcf42894a5dce35ea, const uint64_t basic_data<T>::POW10_SIGNIFICANDS[] = {
0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c, 0x8dd01fad907ffc3c, 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
0xd3515c2831559a83, 0x9d71ac8fada6c9b5, 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57, 0xc21094364dfb5637, 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
0x9096ea6f3848984f, 0xd77485cb25823ac7, 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e, 0x84c8d4dfd2c63f3b, 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
0xc5dd44271ad3cdba, 0x936b9fcebb25c996, 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126, 0xb5b5ada8aaff80b8, 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
0x87625f056c7c4a8b, 0xc9bcff6034c13053, 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f, 0xf8a95fcf88747d94, 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06, 0xaa242499697392d3, 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
0xfd87b5f28300ca0e, 0xbce5086492111aeb, 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000, 0xe8d4a51000000000, 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
0xad78ebc5ac620000, 0x813f3978f8940984, 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068, 0x9f4f2726179a2245, 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
0xed63a231d4c4fb27, 0xb0de65388cc8ada8, 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758, 0xda01ee641a708dea, 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
0xa26da3999aef774a, 0xf209787bb47d6b85, 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d, 0x952ab45cfa97a0b3, 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
0xde469fbd99a05fe3, 0xa59bc234db398c25, 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2, 0xcc20ce9bd35c78a5, 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
0x98165af37b2153df, 0xe2a0b5dc971f303a, 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410, 0x8bab8eefb6409c1a, 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
0xd01fef10a657842c, 0x9b10a4e5e9913129, 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85, 0xbf21e44003acdd2d, 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b}; 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
};
// Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding // Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
// to significands above. // to significands above.
template <typename T> template <typename T>
const int16_t basic_data<T>::POW10_EXPONENTS[] = {-1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, -927, -901, const int16_t basic_data<T>::POW10_EXPONENTS[] = {
-874, -847, -821, -794, -768, -741, -715, -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, -343, -316, -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
-289, -263, -236, -210, -183, -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, 375, -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661,
402, 428, 455, 481, 508, 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066}; -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
-343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77,
-50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066
};
template<typename T> template <typename T> const char basic_data<T>::RESET_COLOR[] = "\x1b[0m";
const char basic_data<T>::RESET_COLOR[] = "\x1b[0m"; template <typename T> const wchar_t basic_data<T>::WRESET_COLOR[] = L"\x1b[0m";
template<typename T>
const wchar_t basic_data<T>::WRESET_COLOR[] = L"\x1b[0m";
FMT_FUNC fp operator*(fp x, fp y) // A handmade floating-point number f * pow(2, e).
{ class fp {
private:
typedef uint64_t significand_type;
// All sizes are in bits.
static FMT_CONSTEXPR_DECL const int char_size =
std::numeric_limits<unsigned char>::digits;
// Subtract 1 to account for an implicit most significant bit in the
// normalized form.
static FMT_CONSTEXPR_DECL const int double_significand_size =
std::numeric_limits<double>::digits - 1;
static FMT_CONSTEXPR_DECL const uint64_t implicit_bit =
1ull << double_significand_size;
public:
significand_type f;
int e;
static FMT_CONSTEXPR_DECL const int significand_size =
sizeof(significand_type) * char_size;
fp(): f(0), e(0) {}
fp(uint64_t f, int e): f(f), e(e) {}
// Constructs fp from an IEEE754 double. It is a template to prevent compile
// errors on platforms where double is not IEEE754.
template <typename Double>
explicit fp(Double d) {
// Assume double is in the format [sign][exponent][significand].
typedef std::numeric_limits<Double> limits;
const int double_size = static_cast<int>(sizeof(Double) * char_size);
const int exponent_size =
double_size - double_significand_size - 1; // -1 for sign
const uint64_t significand_mask = implicit_bit - 1;
const uint64_t exponent_mask = (~0ull >> 1) & ~significand_mask;
const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1;
auto u = bit_cast<uint64_t>(d);
auto biased_e = (u & exponent_mask) >> double_significand_size;
f = u & significand_mask;
if (biased_e != 0)
f += implicit_bit;
else
biased_e = 1; // Subnormals use biased exponent 1 (min exponent).
e = static_cast<int>(biased_e - exponent_bias - double_significand_size);
}
// Normalizes the value converted from double and multiplied by (1 << SHIFT).
template <int SHIFT = 0>
void normalize() {
// Handle subnormals.
auto shifted_implicit_bit = implicit_bit << SHIFT;
while ((f & shifted_implicit_bit) == 0) {
f <<= 1;
--e;
}
// Subtract 1 to account for hidden bit.
auto offset = significand_size - double_significand_size - SHIFT - 1;
f <<= offset;
e -= offset;
}
// Compute lower and upper boundaries (m^- and m^+ in the Grisu paper), where
// a boundary is a value half way between the number and its predecessor
// (lower) or successor (upper). The upper boundary is normalized and lower
// has the same exponent but may be not normalized.
void compute_boundaries(fp &lower, fp &upper) const {
lower = f == implicit_bit ?
fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1);
upper = fp((f << 1) + 1, e - 1);
upper.normalize<1>(); // 1 is to account for the exponent shift above.
lower.f <<= lower.e - upper.e;
lower.e = upper.e;
}
};
// Returns an fp number representing x - y. Result may not be normalized.
inline fp operator-(fp x, fp y) {
FMT_ASSERT(x.f >= y.f && x.e == y.e, "invalid operands");
return fp(x.f - y.f, x.e);
}
// Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest
// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be normalized.
FMT_API fp operator*(fp x, fp y);
// Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its
// (binary) exponent satisfies min_exponent <= c_k.e <= min_exponent + 3.
FMT_API fp get_cached_power(int min_exponent, int &pow10_exponent);
FMT_FUNC fp operator*(fp x, fp y) {
// Multiply 32-bit parts of significands. // Multiply 32-bit parts of significands.
uint64_t mask = (1ULL << 32) - 1; uint64_t mask = (1ULL << 32) - 1;
uint64_t a = x.f >> 32, b = x.f & mask; uint64_t a = x.f >> 32, b = x.f & mask;
@@ -314,81 +441,315 @@ FMT_FUNC fp operator*(fp x, fp y)
return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), x.e + y.e + 64); return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), x.e + y.e + 64);
} }
FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) {
{
const double one_over_log2_10 = 0.30102999566398114; // 1 / log2(10) const double one_over_log2_10 = 0.30102999566398114; // 1 / log2(10)
int index = static_cast<int>(std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10)); int index = static_cast<int>(std::ceil(
(min_exponent + fp::significand_size - 1) * one_over_log2_10));
// Decimal exponent of the first (smallest) cached power of 10. // Decimal exponent of the first (smallest) cached power of 10.
const int first_dec_exp = -348; const int first_dec_exp = -348;
// Difference between two consecutive decimal exponents in cached powers of // Difference between 2 consecutive decimal exponents in cached powers of 10.
// 10.
const int dec_exp_step = 8; const int dec_exp_step = 8;
index = (index - first_dec_exp - 1) / dec_exp_step + 1; index = (index - first_dec_exp - 1) / dec_exp_step + 1;
pow10_exponent = first_dec_exp + index * dec_exp_step; pow10_exponent = first_dec_exp + index * dec_exp_step;
return fp(data::POW10_SIGNIFICANDS[index], data::POW10_EXPONENTS[index]); return fp(data::POW10_SIGNIFICANDS[index], data::POW10_EXPONENTS[index]);
} }
// Generates output using Grisu2 digit-gen algorithm.
FMT_FUNC void grisu2_gen_digits(
const fp &scaled_value, const fp &scaled_upper, uint64_t delta,
char *buffer, size_t &size, int &dec_exp) {
internal::fp one(1ull << -scaled_upper.e, scaled_upper.e);
// hi (p1 in Grisu) contains the most significant digits of scaled_upper.
// hi = floor(scaled_upper / one).
uint32_t hi = static_cast<uint32_t>(scaled_upper.f >> -one.e);
// lo (p2 in Grisu) contains the least significants digits of scaled_upper.
// lo = scaled_upper mod 1.
uint64_t lo = scaled_upper.f & (one.f - 1);
size = 0;
auto exp = count_digits(hi); // kappa in Grisu.
while (exp > 0) {
uint32_t digit = 0;
// This optimization by miloyip reduces the number of integer divisions by
// one per iteration.
switch (exp) {
case 10: digit = hi / 1000000000; hi %= 1000000000; break;
case 9: digit = hi / 100000000; hi %= 100000000; break;
case 8: digit = hi / 10000000; hi %= 10000000; break;
case 7: digit = hi / 1000000; hi %= 1000000; break;
case 6: digit = hi / 100000; hi %= 100000; break;
case 5: digit = hi / 10000; hi %= 10000; break;
case 4: digit = hi / 1000; hi %= 1000; break;
case 3: digit = hi / 100; hi %= 100; break;
case 2: digit = hi / 10; hi %= 10; break;
case 1: digit = hi; hi = 0; break;
default:
FMT_ASSERT(false, "invalid number of digits");
}
if (digit != 0 || size != 0)
buffer[size++] = static_cast<char>('0' + digit);
--exp;
uint64_t remainder = (static_cast<uint64_t>(hi) << -one.e) + lo;
if (remainder <= delta) {
dec_exp += exp;
// TODO: use scaled_value
(void)scaled_value;
return;
}
}
for (;;) {
lo *= 10;
delta *= 10;
char digit = static_cast<char>(lo >> -one.e);
if (digit != 0 || size != 0)
buffer[size++] = static_cast<char>('0' + digit);
lo &= one.f - 1;
--exp;
if (lo < delta) {
dec_exp += exp;
return;
}
}
}
FMT_FUNC void grisu2_format_positive(double value, char *buffer, size_t &size,
int &dec_exp) {
FMT_ASSERT(value > 0, "value is nonpositive");
fp fp_value(value);
fp lower, upper; // w^- and w^+ in the Grisu paper.
fp_value.compute_boundaries(lower, upper);
// Find a cached power of 10 close to 1 / upper.
const int min_exp = -60; // alpha in Grisu.
auto dec_pow = get_cached_power( // \tilde{c}_{-k} in Grisu.
min_exp - (upper.e + fp::significand_size), dec_exp);
dec_exp = -dec_exp;
fp_value.normalize();
fp scaled_value = fp_value * dec_pow;
fp scaled_lower = lower * dec_pow; // \tilde{M}^- in Grisu.
fp scaled_upper = upper * dec_pow; // \tilde{M}^+ in Grisu.
++scaled_lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}.
--scaled_upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}.
uint64_t delta = scaled_upper.f - scaled_lower.f;
grisu2_gen_digits(scaled_value, scaled_upper, delta, buffer, size, dec_exp);
}
FMT_FUNC void round(char *buffer, size_t &size, int &exp,
int digits_to_remove) {
size -= to_unsigned(digits_to_remove);
exp += digits_to_remove;
int digit = buffer[size] - '0';
// TODO: proper rounding and carry
if (digit > 5 || (digit == 5 && (digits_to_remove > 1 ||
(buffer[size - 1] - '0') % 2) != 0)) {
++buffer[size - 1];
}
}
// Writes the exponent exp in the form "[+-]d{1,3}" to buffer.
FMT_FUNC char *write_exponent(char *buffer, int exp) {
FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range");
if (exp < 0) {
*buffer++ = '-';
exp = -exp;
} else {
*buffer++ = '+';
}
if (exp >= 100) {
*buffer++ = static_cast<char>('0' + exp / 100);
exp %= 100;
const char *d = data::DIGITS + exp * 2;
*buffer++ = d[0];
*buffer++ = d[1];
} else {
const char *d = data::DIGITS + exp * 2;
*buffer++ = d[0];
*buffer++ = d[1];
}
return buffer;
}
FMT_FUNC void format_exp_notation(
char *buffer, size_t &size, int exp, int precision, bool upper) {
// Insert a decimal point after the first digit and add an exponent.
std::memmove(buffer + 2, buffer + 1, size - 1);
buffer[1] = '.';
exp += static_cast<int>(size) - 1;
int num_digits = precision - static_cast<int>(size) + 1;
if (num_digits > 0) {
std::uninitialized_fill_n(buffer + size + 1, num_digits, '0');
size += to_unsigned(num_digits);
} else if (num_digits < 0) {
round(buffer, size, exp, -num_digits);
}
char *p = buffer + size + 1;
*p++ = upper ? 'E' : 'e';
size = to_unsigned(write_exponent(p, exp) - buffer);
}
// Prettifies the output of the Grisu2 algorithm.
// The number is given as v = buffer * 10^exp.
FMT_FUNC void grisu2_prettify(char *buffer, size_t &size, int exp,
int precision, bool upper) {
// pow(10, full_exp - 1) <= v <= pow(10, full_exp).
int int_size = static_cast<int>(size);
int full_exp = int_size + exp;
const int exp_threshold = 21;
if (int_size <= full_exp && full_exp <= exp_threshold) {
// 1234e7 -> 12340000000[.0+]
std::uninitialized_fill_n(buffer + int_size, full_exp - int_size, '0');
char *p = buffer + full_exp;
if (precision > 0) {
*p++ = '.';
std::uninitialized_fill_n(p, precision, '0');
p += precision;
}
size = to_unsigned(p - buffer);
} else if (0 < full_exp && full_exp <= exp_threshold) {
// 1234e-2 -> 12.34[0+]
int fractional_size = -exp;
std::memmove(buffer + full_exp + 1, buffer + full_exp,
to_unsigned(fractional_size));
buffer[full_exp] = '.';
int num_zeros = precision - fractional_size;
if (num_zeros > 0) {
std::uninitialized_fill_n(buffer + size + 1, num_zeros, '0');
size += to_unsigned(num_zeros);
}
++size;
} else if (-6 < full_exp && full_exp <= 0) {
// 1234e-6 -> 0.001234
int offset = 2 - full_exp;
std::memmove(buffer + offset, buffer, size);
buffer[0] = '0';
buffer[1] = '.';
std::uninitialized_fill_n(buffer + 2, -full_exp, '0');
size = to_unsigned(int_size + offset);
} else {
format_exp_notation(buffer, size, exp, precision, upper);
}
}
#if FMT_CLANG_VERSION
# define FMT_FALLTHROUGH [[clang::fallthrough]];
#elif FMT_GCC_VERSION >= 700
# define FMT_FALLTHROUGH [[gnu::fallthrough]];
#else
# define FMT_FALLTHROUGH
#endif
// Formats a nonnegative value using Grisu2 algorithm. Grisu2 doesn't give any
// guarantees on the shortness of the result.
FMT_FUNC void grisu2_format(double value, char *buffer, size_t &size, char type,
int precision, bool write_decimal_point) {
FMT_ASSERT(value >= 0, "value is negative");
int dec_exp = 0; // K in Grisu.
if (value > 0) {
grisu2_format_positive(value, buffer, size, dec_exp);
} else {
*buffer = '0';
size = 1;
}
const int default_precision = 6;
if (precision < 0)
precision = default_precision;
bool upper = false;
switch (type) {
case 'G':
upper = true;
FMT_FALLTHROUGH
case '\0': case 'g': {
int digits_to_remove = static_cast<int>(size) - precision;
if (digits_to_remove > 0) {
round(buffer, size, dec_exp, digits_to_remove);
// Remove trailing zeros.
while (size > 0 && buffer[size - 1] == '0') {
--size;
++dec_exp;
}
}
precision = 0;
break;
}
case 'F':
upper = true;
FMT_FALLTHROUGH
case 'f': {
int digits_to_remove = -dec_exp - precision;
if (digits_to_remove > 0) {
if (digits_to_remove >= static_cast<int>(size))
digits_to_remove = static_cast<int>(size) - 1;
round(buffer, size, dec_exp, digits_to_remove);
}
break;
}
case 'e': case 'E':
format_exp_notation(buffer, size, dec_exp, precision, type == 'E');
return;
}
if (write_decimal_point && precision < 1)
precision = 1;
grisu2_prettify(buffer, size, dec_exp, precision, upper);
}
} // namespace internal } // namespace internal
#if FMT_USE_WINDOWS_H #if FMT_USE_WINDOWS_H
FMT_FUNC internal::utf8_to_utf16::utf8_to_utf16(string_view s) FMT_FUNC internal::utf8_to_utf16::utf8_to_utf16(string_view s) {
{
static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16"; static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16";
if (s.size() > INT_MAX) if (s.size() > INT_MAX)
FMT_THROW(windows_error(ERROR_INVALID_PARAMETER, ERROR_MSG)); FMT_THROW(windows_error(ERROR_INVALID_PARAMETER, ERROR_MSG));
int s_size = static_cast<int>(s.size()); int s_size = static_cast<int>(s.size());
if (s_size == 0) if (s_size == 0) {
{
// MultiByteToWideChar does not support zero length, handle separately. // MultiByteToWideChar does not support zero length, handle separately.
buffer_.resize(1); buffer_.resize(1);
buffer_[0] = 0; buffer_[0] = 0;
return; return;
} }
int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, FMT_NULL, 0); int length = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, FMT_NULL, 0);
if (length == 0) if (length == 0)
FMT_THROW(windows_error(GetLastError(), ERROR_MSG)); FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
buffer_.resize(length + 1); buffer_.resize(length + 1);
length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, &buffer_[0], length); length = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, &buffer_[0], length);
if (length == 0) if (length == 0)
FMT_THROW(windows_error(GetLastError(), ERROR_MSG)); FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
buffer_[length] = 0; buffer_[length] = 0;
} }
FMT_FUNC internal::utf16_to_utf8::utf16_to_utf8(wstring_view s) FMT_FUNC internal::utf16_to_utf8::utf16_to_utf8(wstring_view s) {
{ if (int error_code = convert(s)) {
if (int error_code = convert(s)) FMT_THROW(windows_error(error_code,
{ "cannot convert string from UTF-16 to UTF-8"));
FMT_THROW(windows_error(error_code, "cannot convert string from UTF-16 to UTF-8"));
} }
} }
FMT_FUNC int internal::utf16_to_utf8::convert(wstring_view s) FMT_FUNC int internal::utf16_to_utf8::convert(wstring_view s) {
{
if (s.size() > INT_MAX) if (s.size() > INT_MAX)
return ERROR_INVALID_PARAMETER; return ERROR_INVALID_PARAMETER;
int s_size = static_cast<int>(s.size()); int s_size = static_cast<int>(s.size());
if (s_size == 0) if (s_size == 0) {
{
// WideCharToMultiByte does not support zero length, handle separately. // WideCharToMultiByte does not support zero length, handle separately.
buffer_.resize(1); buffer_.resize(1);
buffer_[0] = 0; buffer_[0] = 0;
return 0; return 0;
} }
int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, FMT_NULL, 0, FMT_NULL, FMT_NULL); int length = WideCharToMultiByte(
CP_UTF8, 0, s.data(), s_size, FMT_NULL, 0, FMT_NULL, FMT_NULL);
if (length == 0) if (length == 0)
return GetLastError(); return GetLastError();
buffer_.resize(length + 1); buffer_.resize(length + 1);
length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0], length, FMT_NULL, FMT_NULL); length = WideCharToMultiByte(
CP_UTF8, 0, s.data(), s_size, &buffer_[0], length, FMT_NULL, FMT_NULL);
if (length == 0) if (length == 0)
return GetLastError(); return GetLastError();
buffer_[length] = 0; buffer_[length] = 0;
return 0; return 0;
} }
FMT_FUNC void windows_error::init(int err_code, string_view format_str, format_args args) FMT_FUNC void windows_error::init(
{ int err_code, string_view format_str, format_args args) {
error_code_ = err_code; error_code_ = err_code;
memory_buffer buffer; memory_buffer buffer;
internal::format_windows_error(buffer, err_code, vformat(format_str, args)); internal::format_windows_error(buffer, err_code, vformat(format_str, args));
@@ -396,22 +757,20 @@ FMT_FUNC void windows_error::init(int err_code, string_view format_str, format_a
base = std::runtime_error(to_string(buffer)); base = std::runtime_error(to_string(buffer));
} }
FMT_FUNC void internal::format_windows_error(internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT FMT_FUNC void internal::format_windows_error(
{ internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT {
FMT_TRY FMT_TRY {
{
wmemory_buffer buf; wmemory_buffer buf;
buf.resize(inline_buffer_size); buf.resize(inline_buffer_size);
for (;;) for (;;) {
{
wchar_t *system_message = &buf[0]; wchar_t *system_message = &buf[0];
int result = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, FMT_NULL, error_code, int result = FormatMessageW(
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message, static_cast<uint32_t>(buf.size()), FMT_NULL); FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
if (result != 0) FMT_NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
{ system_message, static_cast<uint32_t>(buf.size()), FMT_NULL);
if (result != 0) {
utf16_to_utf8 utf8_message; utf16_to_utf8 utf8_message;
if (utf8_message.convert(system_message) == ERROR_SUCCESS) if (utf8_message.convert(system_message) == ERROR_SUCCESS) {
{
writer w(out); writer w(out);
w.write(message); w.write(message);
w.write(": "); w.write(": ");
@@ -424,25 +783,21 @@ FMT_FUNC void internal::format_windows_error(internal::buffer &out, int error_co
break; // Can't get error message, report error code instead. break; // Can't get error message, report error code instead.
buf.resize(buf.size() * 2); buf.resize(buf.size() * 2);
} }
} } FMT_CATCH(...) {}
FMT_CATCH(...) {}
format_error_code(out, error_code, message); format_error_code(out, error_code, message);
} }
#endif // FMT_USE_WINDOWS_H #endif // FMT_USE_WINDOWS_H
FMT_FUNC void format_system_error(internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT FMT_FUNC void format_system_error(
{ internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT {
FMT_TRY FMT_TRY {
{
memory_buffer buf; memory_buffer buf;
buf.resize(inline_buffer_size); buf.resize(inline_buffer_size);
for (;;) for (;;) {
{
char *system_message = &buf[0]; char *system_message = &buf[0];
int result = safe_strerror(error_code, system_message, buf.size()); int result = safe_strerror(error_code, system_message, buf.size());
if (result == 0) if (result == 0) {
{
writer w(out); writer w(out);
w.write(message); w.write(message);
w.write(": "); w.write(": ");
@@ -453,122 +808,55 @@ FMT_FUNC void format_system_error(internal::buffer &out, int error_code, string_
break; // Can't get error message, report error code instead. break; // Can't get error message, report error code instead.
buf.resize(buf.size() * 2); buf.resize(buf.size() * 2);
} }
} } FMT_CATCH(...) {}
FMT_CATCH(...) {}
format_error_code(out, error_code, message); format_error_code(out, error_code, message);
} }
template <typename Char> template <typename Char>
void basic_fixed_buffer<Char>::grow(std::size_t) void basic_fixed_buffer<Char>::grow(std::size_t) {
{
FMT_THROW(std::runtime_error("buffer overflow")); FMT_THROW(std::runtime_error("buffer overflow"));
} }
FMT_FUNC void internal::error_handler::on_error(const char *message) FMT_FUNC void internal::error_handler::on_error(const char *message) {
{
FMT_THROW(format_error(message)); FMT_THROW(format_error(message));
} }
FMT_FUNC void report_system_error(int error_code, fmt::string_view message) FMT_NOEXCEPT FMT_FUNC void report_system_error(
{ int error_code, fmt::string_view message) FMT_NOEXCEPT {
report_error(format_system_error, error_code, message); report_error(format_system_error, error_code, message);
} }
#if FMT_USE_WINDOWS_H #if FMT_USE_WINDOWS_H
FMT_FUNC void report_windows_error(int error_code, fmt::string_view message) FMT_NOEXCEPT FMT_FUNC void report_windows_error(
{ int error_code, fmt::string_view message) FMT_NOEXCEPT {
report_error(internal::format_windows_error, error_code, message); report_error(internal::format_windows_error, error_code, message);
} }
#endif #endif
FMT_FUNC void vprint(std::FILE *f, string_view format_str, format_args args) FMT_FUNC void vprint(std::FILE *f, string_view format_str, format_args args) {
{
memory_buffer buffer; memory_buffer buffer;
vformat_to(buffer, format_str, args); vformat_to(buffer, format_str, args);
std::fwrite(buffer.data(), 1, buffer.size(), f); std::fwrite(buffer.data(), 1, buffer.size(), f);
} }
FMT_FUNC void vprint(std::FILE *f, wstring_view format_str, wformat_args args) FMT_FUNC void vprint(std::FILE *f, wstring_view format_str, wformat_args args) {
{
wmemory_buffer buffer; wmemory_buffer buffer;
vformat_to(buffer, format_str, args); vformat_to(buffer, format_str, args);
std::fwrite(buffer.data(), sizeof(wchar_t), buffer.size(), f); std::fwrite(buffer.data(), sizeof(wchar_t), buffer.size(), f);
} }
FMT_FUNC void vprint(string_view format_str, format_args args) FMT_FUNC void vprint(string_view format_str, format_args args) {
{
vprint(stdout, format_str, args); vprint(stdout, format_str, args);
} }
FMT_FUNC void vprint(wstring_view format_str, wformat_args args) FMT_FUNC void vprint(wstring_view format_str, wformat_args args) {
{
vprint(stdout, format_str, args); vprint(stdout, format_str, args);
} }
#ifndef FMT_EXTENDED_COLORS #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
FMT_FUNC void vprint_colored(color c, string_view format, format_args args) FMT_FUNC locale locale_provider::locale() { return fmt::locale(); }
{
char escape[] = "\x1b[30m";
escape[3] = static_cast<char>('0' + c);
std::fputs(escape, stdout);
vprint(format, args);
std::fputs(internal::data::RESET_COLOR, stdout);
}
FMT_FUNC void vprint_colored(color c, wstring_view format, wformat_args args)
{
wchar_t escape[] = L"\x1b[30m";
escape[3] = static_cast<wchar_t>('0' + c);
std::fputws(escape, stdout);
vprint(format, args);
std::fputws(internal::data::WRESET_COLOR, stdout);
}
#else
namespace internal {
FMT_CONSTEXPR void to_esc(uint8_t c, char out[], int offset)
{
out[offset + 0] = static_cast<char>('0' + c / 100);
out[offset + 1] = static_cast<char>('0' + c / 10 % 10);
out[offset + 2] = static_cast<char>('0' + c % 10);
}
} // namespace internal
FMT_FUNC void vprint_rgb(rgb fd, string_view format, format_args args)
{
char escape_fd[] = "\x1b[38;2;000;000;000m";
internal::to_esc(fd.r, escape_fd, 7);
internal::to_esc(fd.g, escape_fd, 11);
internal::to_esc(fd.b, escape_fd, 15);
std::fputs(escape_fd, stdout);
vprint(format, args);
std::fputs(internal::data::RESET_COLOR, stdout);
}
FMT_FUNC void vprint_rgb(rgb fd, rgb bg, string_view format, format_args args)
{
char escape_fd[] = "\x1b[38;2;000;000;000m"; // foreground color
char escape_bg[] = "\x1b[48;2;000;000;000m"; // background color
internal::to_esc(fd.r, escape_fd, 7);
internal::to_esc(fd.g, escape_fd, 11);
internal::to_esc(fd.b, escape_fd, 15);
internal::to_esc(bg.r, escape_bg, 7);
internal::to_esc(bg.g, escape_bg, 11);
internal::to_esc(bg.b, escape_bg, 15);
std::fputs(escape_fd, stdout);
std::fputs(escape_bg, stdout);
vprint(format, args);
std::fputs(internal::data::RESET_COLOR, stdout);
}
#endif #endif
FMT_FUNC locale locale_provider::locale()
{
return fmt::locale();
}
FMT_END_NAMESPACE FMT_END_NAMESPACE
#ifdef _MSC_VER #ifdef _MSC_VER

File diff suppressed because it is too large Load Diff

View File

@@ -1,27 +0,0 @@
// Formatting library for C++ - locale support
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#include "format.h"
#include <locale>
namespace fmt {
class locale
{
private:
std::locale locale_;
public:
explicit locale(std::locale loc = std::locale())
: locale_(loc)
{
}
std::locale get()
{
return locale_;
}
};
} // namespace fmt

View File

@@ -15,8 +15,7 @@ FMT_BEGIN_NAMESPACE
namespace internal { namespace internal {
template <class Char> template <class Char>
class formatbuf : public std::basic_streambuf<Char> class formatbuf : public std::basic_streambuf<Char> {
{
private: private:
typedef typename std::basic_streambuf<Char>::int_type int_type; typedef typename std::basic_streambuf<Char>::int_type int_type;
typedef typename std::basic_streambuf<Char>::traits_type traits_type; typedef typename std::basic_streambuf<Char>::traits_type traits_type;
@@ -24,10 +23,7 @@ private:
basic_buffer<Char> &buffer_; basic_buffer<Char> &buffer_;
public: public:
formatbuf(basic_buffer<Char> &buffer) formatbuf(basic_buffer<Char> &buffer) : buffer_(buffer) {}
: buffer_(buffer)
{
}
protected: protected:
// The put-area is actually always empty. This makes the implementation // The put-area is actually always empty. This makes the implementation
@@ -37,37 +33,34 @@ protected:
// to overflow. There is no disadvantage here for sputn since this always // to overflow. There is no disadvantage here for sputn since this always
// results in a call to xsputn. // results in a call to xsputn.
int_type overflow(int_type ch = traits_type::eof()) FMT_OVERRIDE int_type overflow(int_type ch = traits_type::eof()) FMT_OVERRIDE {
{
if (!traits_type::eq_int_type(ch, traits_type::eof())) if (!traits_type::eq_int_type(ch, traits_type::eof()))
buffer_.push_back(static_cast<Char>(ch)); buffer_.push_back(static_cast<Char>(ch));
return ch; return ch;
} }
std::streamsize xsputn(const Char *s, std::streamsize count) FMT_OVERRIDE std::streamsize xsputn(const Char *s, std::streamsize count) FMT_OVERRIDE {
{
buffer_.append(s, s + count); buffer_.append(s, s + count);
return count; return count;
} }
}; };
template <typename Char> template <typename Char>
struct test_stream : std::basic_ostream<Char> struct test_stream : std::basic_ostream<Char> {
{
private: private:
struct null; struct null;
// Hide all operator<< from std::basic_ostream<Char>. // Hide all operator<< from std::basic_ostream<Char>.
void operator<<(null); void operator<<(null);
}; };
// Checks if T has a user-defined operator<< (e.g. not a member of // Checks if T has a user-defined operator<< (e.g. not a member of std::ostream).
// std::ostream).
template <typename T, typename Char> template <typename T, typename Char>
class is_streamable class is_streamable {
{
private: private:
template <typename U> template <typename U>
static decltype(internal::declval<test_stream<Char> &>() << internal::declval<U>(), std::true_type()) test(int); static decltype(
internal::declval<test_stream<Char>&>()
<< internal::declval<U>(), std::true_type()) test(int);
template <typename> template <typename>
static std::false_type test(...); static std::false_type test(...);
@@ -75,31 +68,18 @@ private:
typedef decltype(test<T>(0)) result; typedef decltype(test<T>(0)) result;
public: public:
// std::string operator<< is not considered user-defined because we handle static const bool value = result::value;
// strings
// specially.
static const bool value = result::value && !std::is_same<T, std::string>::value;
};
// Disable conversion to int if T has an overloaded operator<< which is a free
// function (not a member of std::ostream).
template<typename T, typename Char>
class convert_to_int<T, Char, true>
{
public:
static const bool value = convert_to_int<T, Char, false>::value && !is_streamable<T, Char>::value;
}; };
// Write the content of buf to os. // Write the content of buf to os.
template <typename Char> template <typename Char>
void write(std::basic_ostream<Char> &os, basic_buffer<Char> &buf) void write(std::basic_ostream<Char> &os, basic_buffer<Char> &buf) {
{
const Char *data = buf.data(); const Char *data = buf.data();
typedef std::make_unsigned<std::streamsize>::type UnsignedStreamSize; typedef std::make_unsigned<std::streamsize>::type UnsignedStreamSize;
UnsignedStreamSize size = buf.size(); UnsignedStreamSize size = buf.size();
UnsignedStreamSize max_size = internal::to_unsigned((std::numeric_limits<std::streamsize>::max)()); UnsignedStreamSize max_size =
do internal::to_unsigned((std::numeric_limits<std::streamsize>::max)());
{ do {
UnsignedStreamSize n = size <= max_size ? size : max_size; UnsignedStreamSize n = size <= max_size ? size : max_size;
os.write(data, static_cast<std::streamsize>(n)); os.write(data, static_cast<std::streamsize>(n));
data += n; data += n;
@@ -108,42 +88,46 @@ void write(std::basic_ostream<Char> &os, basic_buffer<Char> &buf)
} }
template <typename Char, typename T> template <typename Char, typename T>
void format_value(basic_buffer<Char> &buffer, const T &value) void format_value(basic_buffer<Char> &buffer, const T &value) {
{
internal::formatbuf<Char> format_buf(buffer); internal::formatbuf<Char> format_buf(buffer);
std::basic_ostream<Char> output(&format_buf); std::basic_ostream<Char> output(&format_buf);
output.exceptions(std::ios_base::failbit | std::ios_base::badbit); output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
output << value; output << value;
buffer.resize(buffer.size()); buffer.resize(buffer.size());
} }
// Disable builtin formatting of enums and use operator<< instead.
template<typename T>
struct format_enum<T, typename std::enable_if<std::is_enum<T>::value>::type> : std::false_type
{
};
} // namespace internal } // namespace internal
// Disable conversion to int if T has an overloaded operator<< which is a free
// function (not a member of std::ostream).
template <typename T, typename Char>
struct convert_to_int<T, Char, void> {
static const bool value =
convert_to_int<T, Char, int>::value &&
!internal::is_streamable<T, Char>::value;
};
// Formats an object of type T that has an overloaded ostream operator<<. // Formats an object of type T that has an overloaded ostream operator<<.
template <typename T, typename Char> template <typename T, typename Char>
struct formatter<T, Char, typename std::enable_if<internal::is_streamable<T, Char>::value>::type> : formatter<basic_string_view<Char>, Char> struct formatter<T, Char,
{ typename std::enable_if<
internal::is_streamable<T, Char>::value &&
!internal::format_type<
typename buffer_context<Char>::type, T>::value>::type>
: formatter<basic_string_view<Char>, Char> {
template <typename Context> template <typename Context>
auto format(const T &value, Context &ctx) -> decltype(ctx.out()) auto format(const T &value, Context &ctx) -> decltype(ctx.out()) {
{
basic_memory_buffer<Char> buffer; basic_memory_buffer<Char> buffer;
internal::format_value(buffer, value); internal::format_value(buffer, value);
basic_string_view<Char> str(buffer.data(), buffer.size()); basic_string_view<Char> str(buffer.data(), buffer.size());
formatter<basic_string_view<Char>, Char>::format(str, ctx); return formatter<basic_string_view<Char>, Char>::format(str, ctx);
return ctx.out();
} }
}; };
template <typename Char> template <typename Char>
inline void vprint( inline void vprint(std::basic_ostream<Char> &os,
std::basic_ostream<Char> &os, basic_string_view<Char> format_str, basic_format_args<typename buffer_context<Char>::type> args) basic_string_view<Char> format_str,
{ basic_format_args<typename buffer_context<Char>::type> args) {
basic_memory_buffer<Char> buffer; basic_memory_buffer<Char> buffer;
vformat_to(buffer, format_str, args); vformat_to(buffer, format_str, args);
internal::write(os, buffer); internal::write(os, buffer);
@@ -158,14 +142,14 @@ inline void vprint(
\endrst \endrst
*/ */
template <typename... Args> template <typename... Args>
inline void print(std::ostream &os, string_view format_str, const Args &... args) inline void print(std::ostream &os, string_view format_str,
{ const Args & ... args) {
vprint<char>(os, format_str, make_format_args<format_context>(args...)); vprint<char>(os, format_str, make_format_args<format_context>(args...));
} }
template <typename... Args> template <typename... Args>
inline void print(std::wostream &os, wstring_view format_str, const Args &... args) inline void print(std::wostream &os, wstring_view format_str,
{ const Args & ... args) {
vprint<wchar_t>(os, format_str, make_format_args<wformat_context>(args...)); vprint<wchar_t>(os, format_str, make_format_args<wformat_context>(args...));
} }
FMT_END_NAMESPACE FMT_END_NAMESPACE

View File

@@ -53,8 +53,7 @@
// equals to EINTR. // equals to EINTR.
#ifndef _WIN32 #ifndef _WIN32
# define FMT_RETRY_VAL(result, expression, error_result) \ # define FMT_RETRY_VAL(result, expression, error_result) \
do \ do { \
{ \
result = (expression); \ result = (expression); \
} while (result == error_result && errno == EINTR) } while (result == error_result && errno == EINTR)
#else #else
@@ -91,65 +90,47 @@ FMT_BEGIN_NAMESPACE
\endrst \endrst
*/ */
template <typename Char> template <typename Char>
class basic_cstring_view class basic_cstring_view {
{
private: private:
const Char *data_; const Char *data_;
public: public:
/** Constructs a string reference object from a C string. */ /** Constructs a string reference object from a C string. */
basic_cstring_view(const Char *s) basic_cstring_view(const Char *s) : data_(s) {}
: data_(s)
{
}
/** /**
\rst \rst
Constructs a string reference from an ``std::string`` object. Constructs a string reference from an ``std::string`` object.
\endrst \endrst
*/ */
basic_cstring_view(const std::basic_string<Char> &s) basic_cstring_view(const std::basic_string<Char> &s) : data_(s.c_str()) {}
: data_(s.c_str())
{
}
/** Returns the pointer to a C string. */ /** Returns the pointer to a C string. */
const Char *c_str() const const Char *c_str() const { return data_; }
{
return data_;
}
}; };
typedef basic_cstring_view<char> cstring_view; typedef basic_cstring_view<char> cstring_view;
typedef basic_cstring_view<wchar_t> wcstring_view; typedef basic_cstring_view<wchar_t> wcstring_view;
// An error code. // An error code.
class error_code class error_code {
{
private: private:
int value_; int value_;
public: public:
explicit error_code(int value = 0) FMT_NOEXCEPT : value_(value) {} explicit error_code(int value = 0) FMT_NOEXCEPT : value_(value) {}
int get() const FMT_NOEXCEPT int get() const FMT_NOEXCEPT { return value_; }
{
return value_;
}
}; };
// A buffered file. // A buffered file.
class buffered_file class buffered_file {
{
private: private:
FILE *file_; FILE *file_;
friend class file; friend class file;
explicit buffered_file(FILE *f) explicit buffered_file(FILE *f) : file_(f) {}
: file_(f)
{
}
public: public:
// Constructs a buffered_file object which doesn't represent any file. // Constructs a buffered_file object which doesn't represent any file.
@@ -158,73 +139,23 @@ public:
// Destroys the object closing the file it represents if any. // Destroys the object closing the file it represents if any.
FMT_API ~buffered_file() FMT_DTOR_NOEXCEPT; FMT_API ~buffered_file() FMT_DTOR_NOEXCEPT;
#if !FMT_USE_RVALUE_REFERENCES
// Emulate a move constructor and a move assignment operator if rvalue
// references are not supported.
private: private:
// A proxy object to emulate a move constructor. buffered_file(const buffered_file &) = delete;
// It is private to make it impossible call operator Proxy directly. void operator=(const buffered_file &) = delete;
struct Proxy
{
FILE *file;
};
public: public:
// A "move constructor" for moving from a temporary. buffered_file(buffered_file &&other) FMT_NOEXCEPT : file_(other.file_) {
buffered_file(Proxy p) FMT_NOEXCEPT : file_(p.file) {} other.file_ = FMT_NULL;
// A "move constructor" for moving from an lvalue.
buffered_file(buffered_file &f) FMT_NOEXCEPT : file_(f.file_)
{
f.file_ = FMT_NULL;
} }
// A "move assignment operator" for moving from a temporary. buffered_file& operator=(buffered_file &&other) {
buffered_file &operator=(Proxy p)
{
close();
file_ = p.file;
return *this;
}
// A "move assignment operator" for moving from an lvalue.
buffered_file &operator=(buffered_file &other)
{
close(); close();
file_ = other.file_; file_ = other.file_;
other.file_ = FMT_NULL; other.file_ = FMT_NULL;
return *this; return *this;
} }
// Returns a proxy object for moving from a temporary:
// buffered_file file = buffered_file(...);
operator Proxy() FMT_NOEXCEPT
{
Proxy p = {file_};
file_ = FMT_NULL;
return p;
}
#else
private:
FMT_DISALLOW_COPY_AND_ASSIGN(buffered_file);
public:
buffered_file(buffered_file &&other) FMT_NOEXCEPT : file_(other.file_)
{
other.file_ = FMT_NULL;
}
buffered_file &operator=(buffered_file &&other)
{
close();
file_ = other.file_;
other.file_ = FMT_NULL;
return *this;
}
#endif
// Opens a file. // Opens a file.
FMT_API buffered_file(cstring_view filename, cstring_view mode); FMT_API buffered_file(cstring_view filename, cstring_view mode);
@@ -232,23 +163,18 @@ public:
FMT_API void close(); FMT_API void close();
// Returns the pointer to a FILE object representing this file. // Returns the pointer to a FILE object representing this file.
FILE *get() const FMT_NOEXCEPT FILE *get() const FMT_NOEXCEPT { return file_; }
{
return file_;
}
// We place parentheses around fileno to workaround a bug in some versions // We place parentheses around fileno to workaround a bug in some versions
// of MinGW that define fileno as a macro. // of MinGW that define fileno as a macro.
FMT_API int (fileno)() const; FMT_API int (fileno)() const;
void vprint(string_view format_str, format_args args) void vprint(string_view format_str, format_args args) {
{
fmt::vprint(file_, format_str, args); fmt::vprint(file_, format_str, args);
} }
template <typename... Args> template <typename... Args>
inline void print(string_view format_str, const Args &... args) inline void print(string_view format_str, const Args & ... args) {
{
vprint(format_str, make_format_args(args...)); vprint(format_str, make_format_args(args...));
} }
}; };
@@ -259,21 +185,16 @@ public:
// closing the file multiple times will cause a crash on Windows rather // closing the file multiple times will cause a crash on Windows rather
// than an exception. You can get standard behavior by overriding the // than an exception. You can get standard behavior by overriding the
// invalid parameter handler with _set_invalid_parameter_handler. // invalid parameter handler with _set_invalid_parameter_handler.
class file class file {
{
private: private:
int fd_; // File descriptor. int fd_; // File descriptor.
// Constructs a file object with a given descriptor. // Constructs a file object with a given descriptor.
explicit file(int fd) explicit file(int fd) : fd_(fd) {}
: fd_(fd)
{
}
public: public:
// Possible values for the oflag argument to the constructor. // Possible values for the oflag argument to the constructor.
enum enum {
{
RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing.
@@ -285,81 +206,27 @@ public:
// Opens a file and constructs a file object representing this file. // Opens a file and constructs a file object representing this file.
FMT_API file(cstring_view path, int oflag); FMT_API file(cstring_view path, int oflag);
#if !FMT_USE_RVALUE_REFERENCES
// Emulate a move constructor and a move assignment operator if rvalue
// references are not supported.
private: private:
// A proxy object to emulate a move constructor. file(const file &) = delete;
// It is private to make it impossible call operator Proxy directly. void operator=(const file &) = delete;
struct Proxy
{
int fd;
};
public: public:
// A "move constructor" for moving from a temporary. file(file &&other) FMT_NOEXCEPT : fd_(other.fd_) {
file(Proxy p) FMT_NOEXCEPT : fd_(p.fd) {}
// A "move constructor" for moving from an lvalue.
file(file &other) FMT_NOEXCEPT : fd_(other.fd_)
{
other.fd_ = -1; other.fd_ = -1;
} }
// A "move assignment operator" for moving from a temporary. file& operator=(file &&other) {
file &operator=(Proxy p)
{
close();
fd_ = p.fd;
return *this;
}
// A "move assignment operator" for moving from an lvalue.
file &operator=(file &other)
{
close(); close();
fd_ = other.fd_; fd_ = other.fd_;
other.fd_ = -1; other.fd_ = -1;
return *this; return *this;
} }
// Returns a proxy object for moving from a temporary:
// file f = 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. // Destroys the object closing the file it represents if any.
FMT_API ~file() FMT_DTOR_NOEXCEPT; FMT_API ~file() FMT_DTOR_NOEXCEPT;
// Returns the file descriptor. // Returns the file descriptor.
int descriptor() const FMT_NOEXCEPT int descriptor() const FMT_NOEXCEPT { return fd_; }
{
return fd_;
}
// Closes the file. // Closes the file.
FMT_API void close(); FMT_API void close();
@@ -398,66 +265,53 @@ public:
// Returns the memory page size. // Returns the memory page size.
long getpagesize(); long getpagesize();
#if (defined(LC_NUMERIC_MASK) || defined(_MSC_VER)) && !defined(__ANDROID__) && !defined(__CYGWIN__) && !defined(__OpenBSD__) #if (defined(LC_NUMERIC_MASK) || defined(_MSC_VER)) && \
!defined(__ANDROID__) && !defined(__CYGWIN__) && !defined(__OpenBSD__) && \
!defined(__NEWLIB_H__)
# define FMT_LOCALE # define FMT_LOCALE
#endif #endif
#ifdef FMT_LOCALE #ifdef FMT_LOCALE
// A "C" numeric locale. // A "C" numeric locale.
class Locale class Locale {
{
private: private:
# ifdef _MSC_VER # ifdef _MSC_VER
typedef _locale_t locale_t; typedef _locale_t locale_t;
enum enum { LC_NUMERIC_MASK = LC_NUMERIC };
{
LC_NUMERIC_MASK = LC_NUMERIC
};
static locale_t newlocale(int category_mask, const char *locale, locale_t) static locale_t newlocale(int category_mask, const char *locale, locale_t) {
{
return _create_locale(category_mask, locale); return _create_locale(category_mask, locale);
} }
static void freelocale(locale_t locale) static void freelocale(locale_t locale) {
{
_free_locale(locale); _free_locale(locale);
} }
static double strtod_l(const char *nptr, char **endptr, _locale_t locale) static double strtod_l(const char *nptr, char **endptr, _locale_t locale) {
{
return _strtod_l(nptr, endptr, locale); return _strtod_l(nptr, endptr, locale);
} }
# endif # endif
locale_t locale_; locale_t locale_;
FMT_DISALLOW_COPY_AND_ASSIGN(Locale); Locale(const Locale &) = delete;
void operator=(const Locale &) = delete;
public: public:
typedef locale_t Type; typedef locale_t Type;
Locale() Locale() : locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL)) {
: locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL))
{
if (!locale_) if (!locale_)
FMT_THROW(system_error(errno, "cannot create locale")); FMT_THROW(system_error(errno, "cannot create locale"));
} }
~Locale() ~Locale() { freelocale(locale_); }
{
freelocale(locale_);
}
Type get() const Type get() const { return locale_; }
{
return locale_;
}
// Converts string to floating-point number and advances str past the end // Converts string to floating-point number and advances str past the end
// of the parsed input. // of the parsed input.
double strtod(const char *&str) const double strtod(const char *&str) const {
{
char *end = FMT_NULL; char *end = FMT_NULL;
double result = strtod_l(str, &end, locale_); double result = strtod_l(str, &end, locale_);
str = end; str = end;
@@ -467,18 +321,4 @@ public:
#endif // FMT_LOCALE #endif // FMT_LOCALE
FMT_END_NAMESPACE FMT_END_NAMESPACE
#if !FMT_USE_RVALUE_REFERENCES
namespace std {
// For compatibility with C++98.
inline fmt::buffered_file &move(fmt::buffered_file &f)
{
return f;
}
inline fmt::file &move(fmt::file &f)
{
return f;
}
} // namespace std
#endif
#endif // FMT_POSIX_H_ #endif // FMT_POSIX_H_

View File

@@ -19,84 +19,64 @@ namespace internal {
// Checks if a value fits in int - used to avoid warnings about comparing // Checks if a value fits in int - used to avoid warnings about comparing
// signed and unsigned integers. // signed and unsigned integers.
template <bool IsSigned> template <bool IsSigned>
struct int_checker struct int_checker {
{
template <typename T> template <typename T>
static bool fits_in_int(T value) static bool fits_in_int(T value) {
{
unsigned max = std::numeric_limits<int>::max(); unsigned max = std::numeric_limits<int>::max();
return value <= max; return value <= max;
} }
static bool fits_in_int(bool) static bool fits_in_int(bool) { return true; }
{
return true;
}
}; };
template <> template <>
struct int_checker<true> struct int_checker<true> {
{
template <typename T> template <typename T>
static bool fits_in_int(T value) static bool fits_in_int(T value) {
{ return value >= std::numeric_limits<int>::min() &&
return value >= std::numeric_limits<int>::min() && value <= std::numeric_limits<int>::max(); value <= std::numeric_limits<int>::max();
}
static bool fits_in_int(int)
{
return true;
} }
static bool fits_in_int(int) { return true; }
}; };
class printf_precision_handler : public function<int> class printf_precision_handler: public function<int> {
{
public: public:
template <typename T> template <typename T>
typename std::enable_if<std::is_integral<T>::value, int>::type operator()(T value) typename std::enable_if<std::is_integral<T>::value, int>::type
{ operator()(T value) {
if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value)) if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
FMT_THROW(format_error("number is too big")); FMT_THROW(format_error("number is too big"));
return static_cast<int>(value); return static_cast<int>(value);
} }
template <typename T> template <typename T>
typename std::enable_if<!std::is_integral<T>::value, int>::type operator()(T) typename std::enable_if<!std::is_integral<T>::value, int>::type operator()(T) {
{
FMT_THROW(format_error("precision is not integer")); FMT_THROW(format_error("precision is not integer"));
return 0; return 0;
} }
}; };
// An argument visitor that returns true iff arg is a zero integer. // An argument visitor that returns true iff arg is a zero integer.
class is_zero_int : public function<bool> class is_zero_int: public function<bool> {
{
public: public:
template <typename T> template <typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type operator()(T value) typename std::enable_if<std::is_integral<T>::value, bool>::type
{ operator()(T value) { return value == 0; }
return value == 0;
}
template <typename T> template <typename T>
typename std::enable_if<!std::is_integral<T>::value, bool>::type operator()(T) typename std::enable_if<!std::is_integral<T>::value, bool>::type
{ operator()(T) { return false; }
return false;
}
}; };
template <typename T> template <typename T>
struct make_unsigned_or_bool : std::make_unsigned<T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
{
};
template <> template <>
struct make_unsigned_or_bool<bool> struct make_unsigned_or_bool<bool> {
{
typedef bool type; typedef bool type;
}; };
template <typename T, typename Context> template <typename T, typename Context>
class arg_converter : public function<void> class arg_converter: public function<void> {
{
private: private:
typedef typename Context::char_type Char; typedef typename Context::char_type Char;
@@ -105,54 +85,44 @@ private:
public: public:
arg_converter(basic_format_arg<Context> &arg, Char type) arg_converter(basic_format_arg<Context> &arg, Char type)
: arg_(arg) : arg_(arg), type_(type) {}
, type_(type)
{
}
void operator()(bool value) void operator()(bool value) {
{
if (type_ != 's') if (type_ != 's')
operator()<bool>(value); operator()<bool>(value);
} }
template <typename U> template <typename U>
typename std::enable_if<std::is_integral<U>::value>::type operator()(U value) typename std::enable_if<std::is_integral<U>::value>::type
{ operator()(U value) {
bool is_signed = type_ == 'd' || type_ == 'i'; bool is_signed = type_ == 'd' || type_ == 'i';
typedef typename std::conditional<std::is_same<T, void>::value, U, T>::type TargetType; typedef typename std::conditional<
if (const_check(sizeof(TargetType) <= sizeof(int))) std::is_same<T, void>::value, U, T>::type TargetType;
{ if (const_check(sizeof(TargetType) <= sizeof(int))) {
// Extra casts are used to silence warnings. // Extra casts are used to silence warnings.
if (is_signed) if (is_signed) {
{ arg_ = internal::make_arg<Context>(
arg_ = internal::make_arg<Context>(static_cast<int>(static_cast<TargetType>(value))); static_cast<int>(static_cast<TargetType>(value)));
} } else {
else
{
typedef typename make_unsigned_or_bool<TargetType>::type Unsigned; typedef typename make_unsigned_or_bool<TargetType>::type Unsigned;
arg_ = internal::make_arg<Context>(static_cast<unsigned>(static_cast<Unsigned>(value))); arg_ = internal::make_arg<Context>(
static_cast<unsigned>(static_cast<Unsigned>(value)));
} }
} } else {
else if (is_signed) {
{
if (is_signed)
{
// glibc's printf doesn't sign extend arguments of smaller types: // glibc's printf doesn't sign extend arguments of smaller types:
// std::printf("%lld", -42); // prints "4294967254" // std::printf("%lld", -42); // prints "4294967254"
// but we don't have to do the same because it's a UB. // but we don't have to do the same because it's a UB.
arg_ = internal::make_arg<Context>(static_cast<long long>(value)); arg_ = internal::make_arg<Context>(static_cast<long long>(value));
} } else {
else arg_ = internal::make_arg<Context>(
{ static_cast<typename make_unsigned_or_bool<U>::type>(value));
arg_ = internal::make_arg<Context>(static_cast<typename make_unsigned_or_bool<U>::type>(value));
} }
} }
} }
template <typename U> template <typename U>
typename std::enable_if<!std::is_integral<U>::value>::type operator()(U) typename std::enable_if<!std::is_integral<U>::value>::type operator()(U) {
{
// No coversion needed for non-integral types. // No coversion needed for non-integral types.
} }
}; };
@@ -162,36 +132,28 @@ public:
// type depending on the type specifier: 'd' and 'i' - signed, other - // type depending on the type specifier: 'd' and 'i' - signed, other -
// unsigned). // unsigned).
template <typename T, typename Context, typename Char> template <typename T, typename Context, typename Char>
void convert_arg(basic_format_arg<Context> &arg, Char type) void convert_arg(basic_format_arg<Context> &arg, Char type) {
{ fmt::visit(arg_converter<T, Context>(arg, type), arg);
visit(arg_converter<T, Context>(arg, type), arg);
} }
// Converts an integer argument to char for printf. // Converts an integer argument to char for printf.
template <typename Context> template <typename Context>
class char_converter : public function<void> class char_converter: public function<void> {
{
private: private:
basic_format_arg<Context> &arg_; basic_format_arg<Context> &arg_;
FMT_DISALLOW_COPY_AND_ASSIGN(char_converter);
public: public:
explicit char_converter(basic_format_arg<Context> &arg) explicit char_converter(basic_format_arg<Context> &arg) : arg_(arg) {}
: arg_(arg)
{
}
template <typename T> template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type operator()(T value) typename std::enable_if<std::is_integral<T>::value>::type
{ operator()(T value) {
typedef typename Context::char_type Char; typedef typename Context::char_type Char;
arg_ = internal::make_arg<Context>(static_cast<Char>(value)); arg_ = internal::make_arg<Context>(static_cast<Char>(value));
} }
template <typename T> template <typename T>
typename std::enable_if<!std::is_integral<T>::value>::type operator()(T) typename std::enable_if<!std::is_integral<T>::value>::type operator()(T) {
{
// No coversion needed for non-integral types. // No coversion needed for non-integral types.
} }
}; };
@@ -199,28 +161,21 @@ public:
// Checks if an argument is a valid printf width specifier and sets // Checks if an argument is a valid printf width specifier and sets
// left alignment if it is negative. // left alignment if it is negative.
template <typename Char> template <typename Char>
class printf_width_handler : public function<unsigned> class printf_width_handler: public function<unsigned> {
{
private: private:
typedef basic_format_specs<Char> format_specs; typedef basic_format_specs<Char> format_specs;
format_specs &spec_; format_specs &spec_;
FMT_DISALLOW_COPY_AND_ASSIGN(printf_width_handler);
public: public:
explicit printf_width_handler(format_specs &spec) explicit printf_width_handler(format_specs &spec) : spec_(spec) {}
: spec_(spec)
{
}
template <typename T> template <typename T>
typename std::enable_if<std::is_integral<T>::value, unsigned>::type operator()(T value) typename std::enable_if<std::is_integral<T>::value, unsigned>::type
{ operator()(T value) {
typedef typename internal::int_traits<T>::main_type UnsignedType; typedef typename internal::int_traits<T>::main_type UnsignedType;
UnsignedType width = static_cast<UnsignedType>(value); UnsignedType width = static_cast<UnsignedType>(value);
if (internal::is_negative(value)) if (internal::is_negative(value)) {
{
spec_.align_ = ALIGN_LEFT; spec_.align_ = ALIGN_LEFT;
width = 0 - width; width = 0 - width;
} }
@@ -231,8 +186,8 @@ public:
} }
template <typename T> template <typename T>
typename std::enable_if<!std::is_integral<T>::value, unsigned>::type operator()(T) typename std::enable_if<!std::is_integral<T>::value, unsigned>::type
{ operator()(T) {
FMT_THROW(format_error("width is not integer")); FMT_THROW(format_error("width is not integer"));
return 0; return 0;
} }
@@ -242,7 +197,10 @@ public:
template <typename Range> template <typename Range>
class printf_arg_formatter; class printf_arg_formatter;
template<typename OutputIt, typename Char, typename ArgFormatter = printf_arg_formatter<back_insert_range<internal::basic_buffer<Char>>>> template <
typename OutputIt, typename Char,
typename ArgFormatter =
printf_arg_formatter<back_insert_range<internal::basic_buffer<Char>>>>
class basic_printf_context; class basic_printf_context;
/** /**
@@ -251,9 +209,10 @@ class basic_printf_context;
\endrst \endrst
*/ */
template <typename Range> template <typename Range>
class printf_arg_formatter : public internal::function<typename internal::arg_formatter_base<Range>::iterator>, class printf_arg_formatter:
public internal::arg_formatter_base<Range> public internal::function<
{ typename internal::arg_formatter_base<Range>::iterator>,
public internal::arg_formatter_base<Range> {
private: private:
typedef typename Range::value_type char_type; typedef typename Range::value_type char_type;
typedef decltype(internal::declval<Range>().begin()) iterator; typedef decltype(internal::declval<Range>().begin()) iterator;
@@ -262,15 +221,13 @@ private:
context_type &context_; context_type &context_;
void write_null_pointer(char) void write_null_pointer(char) {
{ this->spec()->type_ = 0;
this->spec().type_ = 0;
this->write("(nil)"); this->write("(nil)");
} }
void write_null_pointer(wchar_t) void write_null_pointer(wchar_t) {
{ this->spec()->type_ = 0;
this->spec().type_ = 0;
this->write(L"(nil)"); this->write(L"(nil)");
} }
@@ -284,53 +241,46 @@ public:
specifier information for standard argument types. specifier information for standard argument types.
\endrst \endrst
*/ */
printf_arg_formatter(internal::basic_buffer<char_type> &buffer, format_specs &spec, context_type &ctx) printf_arg_formatter(internal::basic_buffer<char_type> &buffer,
: base(back_insert_range<internal::basic_buffer<char_type>>(buffer), spec) format_specs &spec, context_type &ctx)
, context_(ctx) : base(back_insert_range<internal::basic_buffer<char_type>>(buffer), &spec),
{ context_(ctx) {}
}
template <typename T> template <typename T>
typename std::enable_if<std::is_integral<T>::value, iterator>::type operator()(T value) typename std::enable_if<std::is_integral<T>::value, iterator>::type
{ operator()(T value) {
// MSVC2013 fails to compile separate overloads for bool and char_type so // MSVC2013 fails to compile separate overloads for bool and char_type so
// use std::is_same instead. // use std::is_same instead.
if (std::is_same<T, bool>::value) if (std::is_same<T, bool>::value) {
{ format_specs &fmt_spec = *this->spec();
format_specs &fmt_spec = this->spec();
if (fmt_spec.type_ != 's') if (fmt_spec.type_ != 's')
return base::operator()(value ? 1 : 0); return base::operator()(value ? 1 : 0);
fmt_spec.type_ = 0; fmt_spec.type_ = 0;
this->write(value != 0); this->write(value != 0);
} } else if (std::is_same<T, char_type>::value) {
else if (std::is_same<T, char_type>::value) format_specs &fmt_spec = *this->spec();
{
format_specs &fmt_spec = this->spec();
if (fmt_spec.type_ && fmt_spec.type_ != 'c') if (fmt_spec.type_ && fmt_spec.type_ != 'c')
return (*this)(static_cast<int>(value)); return (*this)(static_cast<int>(value));
fmt_spec.flags_ = 0; fmt_spec.flags_ = 0;
fmt_spec.align_ = ALIGN_RIGHT; fmt_spec.align_ = ALIGN_RIGHT;
return base::operator()(value); return base::operator()(value);
} } else {
else
{
return base::operator()(value); return base::operator()(value);
} }
return this->out(); return this->out();
} }
template <typename T> template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, iterator>::type operator()(T value) typename std::enable_if<std::is_floating_point<T>::value, iterator>::type
{ operator()(T value) {
return base::operator()(value); return base::operator()(value);
} }
/** Formats a null-terminated C string. */ /** Formats a null-terminated C string. */
iterator operator()(const char *value) iterator operator()(const char *value) {
{
if (value) if (value)
base::operator()(value); base::operator()(value);
else if (this->spec().type_ == 'p') else if (this->spec()->type_ == 'p')
write_null_pointer(char_type()); write_null_pointer(char_type());
else else
this->write("(null)"); this->write("(null)");
@@ -338,57 +288,47 @@ public:
} }
/** Formats a null-terminated wide C string. */ /** Formats a null-terminated wide C string. */
iterator operator()(const wchar_t *value) iterator operator()(const wchar_t *value) {
{
if (value) if (value)
base::operator()(value); base::operator()(value);
else if (this->spec().type_ == 'p') else if (this->spec()->type_ == 'p')
write_null_pointer(char_type()); write_null_pointer(char_type());
else else
this->write(L"(null)"); this->write(L"(null)");
return this->out(); return this->out();
} }
iterator operator()(basic_string_view<char_type> value) iterator operator()(basic_string_view<char_type> value) {
{
return base::operator()(value); return base::operator()(value);
} }
iterator operator()(monostate value) iterator operator()(monostate value) {
{
return base::operator()(value); return base::operator()(value);
} }
/** Formats a pointer. */ /** Formats a pointer. */
iterator operator()(const void *value) iterator operator()(const void *value) {
{
if (value) if (value)
return base::operator()(value); return base::operator()(value);
this->spec().type_ = 0; this->spec()->type_ = 0;
write_null_pointer(char_type()); write_null_pointer(char_type());
return this->out(); return this->out();
} }
/** Formats an argument of a custom (user-defined) type. */ /** Formats an argument of a custom (user-defined) type. */
iterator operator()(typename basic_format_arg<context_type>::handle handle) iterator operator()(typename basic_format_arg<context_type>::handle handle) {
{
handle.format(context_); handle.format(context_);
return this->out(); return this->out();
} }
}; };
template <typename T> template <typename T>
struct printf_formatter struct printf_formatter {
{
template <typename ParseContext> template <typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin()) auto parse(ParseContext &ctx) -> decltype(ctx.begin()) { return ctx.begin(); }
{
return ctx.begin();
}
template <typename FormatContext> template <typename FormatContext>
auto format(const T &value, FormatContext &ctx) -> decltype(ctx.out()) auto format(const T &value, FormatContext &ctx) -> decltype(ctx.out()) {
{
internal::format_value(internal::get_container(ctx.out()), value); internal::format_value(internal::get_container(ctx.out()), value);
return ctx.out(); return ctx.out();
} }
@@ -396,17 +336,17 @@ struct printf_formatter
/** This template formats data and writes the output to a writer. */ /** This template formats data and writes the output to a writer. */
template <typename OutputIt, typename Char, typename ArgFormatter> template <typename OutputIt, typename Char, typename ArgFormatter>
class basic_printf_context : private internal::context_base<OutputIt, basic_printf_context<OutputIt, Char, ArgFormatter>, Char> class basic_printf_context :
{ // Inherit publicly as a workaround for the icc bug
// https://software.intel.com/en-us/forums/intel-c-compiler/topic/783476.
public internal::context_base<
OutputIt, basic_printf_context<OutputIt, Char, ArgFormatter>, Char> {
public: public:
/** The character type for the output. */ /** The character type for the output. */
typedef Char char_type; typedef Char char_type;
template <typename T> template <typename T>
struct formatter_type struct formatter_type { typedef printf_formatter<T> type; };
{
typedef printf_formatter<T> type;
};
private: private:
typedef internal::context_base<OutputIt, basic_printf_context, Char> base; typedef internal::context_base<OutputIt, basic_printf_context, Char> base;
@@ -418,7 +358,9 @@ private:
// Returns the argument with specified index or, if arg_index is equal // Returns the argument with specified index or, if arg_index is equal
// to the maximum unsigned value, the next argument. // to the maximum unsigned value, the next argument.
format_arg get_arg(iterator it, unsigned arg_index = (std::numeric_limits<unsigned>::max)()); format_arg get_arg(
iterator it,
unsigned arg_index = (std::numeric_limits<unsigned>::max)());
// Parses argument index, flags and width and returns the argument index. // Parses argument index, flags and width and returns the argument index.
unsigned parse_header(iterator &it, format_specs &spec); unsigned parse_header(iterator &it, format_specs &spec);
@@ -431,26 +373,23 @@ public:
appropriate lifetimes. appropriate lifetimes.
\endrst \endrst
*/ */
basic_printf_context(OutputIt out, basic_string_view<char_type> format_str, basic_format_args<basic_printf_context> args) basic_printf_context(OutputIt out, basic_string_view<char_type> format_str,
: base(out, format_str, args) basic_format_args<basic_printf_context> args)
{ : base(out, format_str, args) {}
}
using base::advance_to;
using base::out;
using base::parse_context; using base::parse_context;
using base::out;
using base::advance_to;
/** Formats stored arguments and writes the output to the range. */ /** Formats stored arguments and writes the output to the range. */
void format(); void format();
}; };
template <typename OutputIt, typename Char, typename AF> template <typename OutputIt, typename Char, typename AF>
void basic_printf_context<OutputIt, Char, AF>::parse_flags(format_specs &spec, iterator &it) void basic_printf_context<OutputIt, Char, AF>::parse_flags(
{ format_specs &spec, iterator &it) {
for (;;) for (;;) {
{ switch (*it++) {
switch (*it++)
{
case '-': case '-':
spec.align_ = ALIGN_LEFT; spec.align_ = ALIGN_LEFT;
break; break;
@@ -474,9 +413,9 @@ void basic_printf_context<OutputIt, Char, AF>::parse_flags(format_specs &spec, i
} }
template <typename OutputIt, typename Char, typename AF> template <typename OutputIt, typename Char, typename AF>
typename basic_printf_context<OutputIt, Char, AF>::format_arg basic_printf_context<OutputIt, Char, AF>::get_arg( typename basic_printf_context<OutputIt, Char, AF>::format_arg
iterator it, unsigned arg_index) basic_printf_context<OutputIt, Char, AF>::get_arg(
{ iterator it, unsigned arg_index) {
(void)it; (void)it;
if (arg_index == std::numeric_limits<unsigned>::max()) if (arg_index == std::numeric_limits<unsigned>::max())
return this->do_get_arg(this->parse_context().next_arg_id()); return this->do_get_arg(this->parse_context().next_arg_id());
@@ -484,27 +423,22 @@ typename basic_printf_context<OutputIt, Char, AF>::format_arg basic_printf_conte
} }
template <typename OutputIt, typename Char, typename AF> template <typename OutputIt, typename Char, typename AF>
unsigned basic_printf_context<OutputIt, Char, AF>::parse_header(iterator &it, format_specs &spec) unsigned basic_printf_context<OutputIt, Char, AF>::parse_header(
{ iterator &it, format_specs &spec) {
unsigned arg_index = std::numeric_limits<unsigned>::max(); unsigned arg_index = std::numeric_limits<unsigned>::max();
char_type c = *it; char_type c = *it;
if (c >= '0' && c <= '9') if (c >= '0' && c <= '9') {
{
// Parse an argument index (if followed by '$') or a width possibly // Parse an argument index (if followed by '$') or a width possibly
// preceded with '0' flag(s). // preceded with '0' flag(s).
internal::error_handler eh; internal::error_handler eh;
unsigned value = parse_nonnegative_int(it, eh); unsigned value = parse_nonnegative_int(it, eh);
if (*it == '$') if (*it == '$') { // value is an argument index
{ // value is an argument index
++it; ++it;
arg_index = value; arg_index = value;
} } else {
else
{
if (c == '0') if (c == '0')
spec.fill_ = '0'; spec.fill_ = '0';
if (value != 0) if (value != 0) {
{
// Nonzero value means that we parsed width and don't need to // Nonzero value means that we parsed width and don't need to
// parse it or flags again, so return now. // parse it or flags again, so return now.
spec.width_ = value; spec.width_ = value;
@@ -514,33 +448,27 @@ unsigned basic_printf_context<OutputIt, Char, AF>::parse_header(iterator &it, fo
} }
parse_flags(spec, it); parse_flags(spec, it);
// Parse width. // Parse width.
if (*it >= '0' && *it <= '9') if (*it >= '0' && *it <= '9') {
{
internal::error_handler eh; internal::error_handler eh;
spec.width_ = parse_nonnegative_int(it, eh); spec.width_ = parse_nonnegative_int(it, eh);
} } else if (*it == '*') {
else if (*it == '*')
{
++it; ++it;
spec.width_ = visit(internal::printf_width_handler<char_type>(spec), get_arg(it)); spec.width_ =
fmt::visit(internal::printf_width_handler<char_type>(spec), get_arg(it));
} }
return arg_index; return arg_index;
} }
template <typename OutputIt, typename Char, typename AF> template <typename OutputIt, typename Char, typename AF>
void basic_printf_context<OutputIt, Char, AF>::format() void basic_printf_context<OutputIt, Char, AF>::format() {
{
auto &buffer = internal::get_container(this->out()); auto &buffer = internal::get_container(this->out());
auto start = iterator(this->parse_context()); auto start = iterator(this->parse_context());
auto it = start; auto it = start;
using internal::pointer_from; using internal::pointer_from;
while (*it) while (*it) {
{
char_type c = *it++; char_type c = *it++;
if (c != '%') if (c != '%') continue;
continue; if (*it == c) {
if (*it == c)
{
buffer.append(pointer_from(start), pointer_from(it)); buffer.append(pointer_from(start), pointer_from(it));
start = ++it; start = ++it;
continue; continue;
@@ -554,30 +482,24 @@ void basic_printf_context<OutputIt, Char, AF>::format()
unsigned arg_index = parse_header(it, spec); unsigned arg_index = parse_header(it, spec);
// Parse precision. // Parse precision.
if (*it == '.') if (*it == '.') {
{
++it; ++it;
if ('0' <= *it && *it <= '9') if ('0' <= *it && *it <= '9') {
{
internal::error_handler eh; internal::error_handler eh;
spec.precision_ = static_cast<int>(parse_nonnegative_int(it, eh)); spec.precision_ = static_cast<int>(parse_nonnegative_int(it, eh));
} } else if (*it == '*') {
else if (*it == '*')
{
++it; ++it;
spec.precision_ = visit(internal::printf_precision_handler(), get_arg(it)); spec.precision_ =
} fmt::visit(internal::printf_precision_handler(), get_arg(it));
else } else {
{
spec.precision_ = 0; spec.precision_ = 0;
} }
} }
format_arg arg = get_arg(it, arg_index); format_arg arg = get_arg(it, arg_index);
if (spec.flag(HASH_FLAG) && visit(internal::is_zero_int(), arg)) if (spec.flag(HASH_FLAG) && fmt::visit(internal::is_zero_int(), arg))
spec.flags_ &= ~internal::to_unsigned<int>(HASH_FLAG); spec.flags_ &= ~internal::to_unsigned<int>(HASH_FLAG);
if (spec.fill_ == '0') if (spec.fill_ == '0') {
{
if (arg.is_arithmetic()) if (arg.is_arithmetic())
spec.align_ = ALIGN_NUMERIC; spec.align_ = ALIGN_NUMERIC;
else else
@@ -586,8 +508,7 @@ void basic_printf_context<OutputIt, Char, AF>::format()
// Parse length and convert the argument to the required type. // Parse length and convert the argument to the required type.
using internal::convert_arg; using internal::convert_arg;
switch (*it++) switch (*it++) {
{
case 'h': case 'h':
if (*it == 'h') if (*it == 'h')
convert_arg<signed char>(arg, *++it); convert_arg<signed char>(arg, *++it);
@@ -622,18 +543,15 @@ void basic_printf_context<OutputIt, Char, AF>::format()
if (!*it) if (!*it)
FMT_THROW(format_error("invalid format string")); FMT_THROW(format_error("invalid format string"));
spec.type_ = static_cast<char>(*it++); spec.type_ = static_cast<char>(*it++);
if (arg.is_integral()) if (arg.is_integral()) {
{
// Normalize type. // Normalize type.
switch (spec.type_) switch (spec.type_) {
{ case 'i': case 'u':
case 'i':
case 'u':
spec.type_ = 'd'; spec.type_ = 'd';
break; break;
case 'c': case 'c':
// TODO: handle wchar_t better? // TODO: handle wchar_t better?
visit(internal::char_converter<basic_printf_context>(arg), arg); fmt::visit(internal::char_converter<basic_printf_context>(arg), arg);
break; break;
} }
} }
@@ -641,33 +559,33 @@ void basic_printf_context<OutputIt, Char, AF>::format()
start = it; start = it;
// Format argument. // Format argument.
visit(AF(buffer, spec, *this), arg); fmt::visit(AF(buffer, spec, *this), arg);
} }
buffer.append(pointer_from(start), pointer_from(it)); buffer.append(pointer_from(start), pointer_from(it));
} }
template <typename Char, typename Context> template <typename Char, typename Context>
void printf(internal::basic_buffer<Char> &buf, basic_string_view<Char> format, basic_format_args<Context> args) void printf(internal::basic_buffer<Char> &buf, basic_string_view<Char> format,
{ basic_format_args<Context> args) {
Context(std::back_inserter(buf), format, args).format(); Context(std::back_inserter(buf), format, args).format();
} }
template <typename Buffer> template <typename Buffer>
struct printf_context struct printf_context {
{ typedef basic_printf_context<
typedef basic_printf_context<std::back_insert_iterator<Buffer>, typename Buffer::value_type> type; std::back_insert_iterator<Buffer>, typename Buffer::value_type> type;
}; };
template <typename ...Args> template <typename ...Args>
inline format_arg_store<printf_context<internal::buffer>::type, Args...> make_printf_args(const Args &... args) inline format_arg_store<printf_context<internal::buffer>::type, Args...>
{ make_printf_args(const Args & ... args) {
return format_arg_store<printf_context<internal::buffer>::type, Args...>(args...); return format_arg_store<printf_context<internal::buffer>::type, Args...>(
args...);
} }
typedef basic_format_args<printf_context<internal::buffer>::type> printf_args; typedef basic_format_args<printf_context<internal::buffer>::type> printf_args;
typedef basic_format_args<printf_context<internal::wbuffer>::type> wprintf_args; typedef basic_format_args<printf_context<internal::wbuffer>::type> wprintf_args;
inline std::string vsprintf(string_view format, printf_args args) inline std::string vsprintf(string_view format, printf_args args) {
{
memory_buffer buffer; memory_buffer buffer;
printf(buffer, format, args); printf(buffer, format, args);
return to_string(buffer); return to_string(buffer);
@@ -683,32 +601,32 @@ inline std::string vsprintf(string_view format, printf_args args)
\endrst \endrst
*/ */
template <typename... Args> template <typename... Args>
inline std::string sprintf(string_view format_str, const Args &... args) inline std::string sprintf(string_view format_str, const Args & ... args) {
{ return vsprintf(format_str,
return vsprintf(format_str, make_format_args<typename printf_context<internal::buffer>::type>(args...)); make_format_args<typename printf_context<internal::buffer>::type>(args...));
} }
inline std::wstring vsprintf(wstring_view format, wprintf_args args) inline std::wstring vsprintf(wstring_view format, wprintf_args args) {
{
wmemory_buffer buffer; wmemory_buffer buffer;
printf(buffer, format, args); printf(buffer, format, args);
return to_string(buffer); return to_string(buffer);
} }
template <typename... Args> template <typename... Args>
inline std::wstring sprintf(wstring_view format_str, const Args &... args) inline std::wstring sprintf(wstring_view format_str, const Args & ... args) {
{ return vsprintf(format_str,
return vsprintf(format_str, make_format_args<typename printf_context<internal::wbuffer>::type>(args...)); make_format_args<typename printf_context<internal::wbuffer>::type>(args...));
} }
template <typename Char> template <typename Char>
inline int vfprintf( inline int vfprintf(std::FILE *f, basic_string_view<Char> format,
std::FILE *f, basic_string_view<Char> format, basic_format_args<typename printf_context<internal::basic_buffer<Char>>::type> args) basic_format_args<typename printf_context<
{ internal::basic_buffer<Char>>::type> args) {
basic_memory_buffer<Char> buffer; basic_memory_buffer<Char> buffer;
printf(buffer, format, args); printf(buffer, format, args);
std::size_t size = buffer.size(); std::size_t size = buffer.size();
return std::fwrite(buffer.data(), sizeof(Char), size, f) < size ? -1 : static_cast<int>(size); return std::fwrite(
buffer.data(), sizeof(Char), size, f) < size ? -1 : static_cast<int>(size);
} }
/** /**
@@ -721,25 +639,24 @@ inline int vfprintf(
\endrst \endrst
*/ */
template <typename... Args> template <typename... Args>
inline int fprintf(std::FILE *f, string_view format_str, const Args &... args) inline int fprintf(std::FILE *f, string_view format_str, const Args & ... args) {
{ auto vargs = make_format_args<
auto vargs = make_format_args<typename printf_context<internal::buffer>::type>(args...); typename printf_context<internal::buffer>::type>(args...);
return vfprintf<char>(f, format_str, vargs); return vfprintf<char>(f, format_str, vargs);
} }
template <typename... Args> template <typename... Args>
inline int fprintf(std::FILE *f, wstring_view format_str, const Args &... args) inline int fprintf(std::FILE *f, wstring_view format_str,
{ const Args & ... args) {
return vfprintf(f, format_str, make_format_args<typename printf_context<internal::wbuffer>::type>(args...)); return vfprintf(f, format_str,
make_format_args<typename printf_context<internal::wbuffer>::type>(args...));
} }
inline int vprintf(string_view format, printf_args args) inline int vprintf(string_view format, printf_args args) {
{
return vfprintf(stdout, format, args); return vfprintf(stdout, format, args);
} }
inline int vprintf(wstring_view format, wprintf_args args) inline int vprintf(wstring_view format, wprintf_args args) {
{
return vfprintf(stdout, format, args); return vfprintf(stdout, format, args);
} }
@@ -753,27 +670,27 @@ inline int vprintf(wstring_view format, wprintf_args args)
\endrst \endrst
*/ */
template <typename... Args> template <typename... Args>
inline int printf(string_view format_str, const Args &... args) inline int printf(string_view format_str, const Args & ... args) {
{ return vprintf(format_str,
return vprintf(format_str, make_format_args<typename printf_context<internal::buffer>::type>(args...)); make_format_args<typename printf_context<internal::buffer>::type>(args...));
} }
template <typename... Args> template <typename... Args>
inline int printf(wstring_view format_str, const Args &... args) inline int printf(wstring_view format_str, const Args & ... args) {
{ return vprintf(format_str,
return vprintf(format_str, make_format_args<typename printf_context<internal::wbuffer>::type>(args...)); make_format_args<typename printf_context<internal::wbuffer>::type>(args...));
} }
inline int vfprintf(std::ostream &os, string_view format_str, printf_args args) inline int vfprintf(std::ostream &os, string_view format_str,
{ printf_args args) {
memory_buffer buffer; memory_buffer buffer;
printf(buffer, format_str, args); printf(buffer, format_str, args);
internal::write(os, buffer); internal::write(os, buffer);
return static_cast<int>(buffer.size()); return static_cast<int>(buffer.size());
} }
inline int vfprintf(std::wostream &os, wstring_view format_str, wprintf_args args) inline int vfprintf(std::wostream &os, wstring_view format_str,
{ wprintf_args args) {
wmemory_buffer buffer; wmemory_buffer buffer;
printf(buffer, format_str, args); printf(buffer, format_str, args);
internal::write(os, buffer); internal::write(os, buffer);
@@ -790,16 +707,18 @@ inline int vfprintf(std::wostream &os, wstring_view format_str, wprintf_args arg
\endrst \endrst
*/ */
template <typename... Args> template <typename... Args>
inline int fprintf(std::ostream &os, string_view format_str, const Args &... args) inline int fprintf(std::ostream &os, string_view format_str,
{ const Args & ... args) {
auto vargs = make_format_args<typename printf_context<internal::buffer>::type>(args...); auto vargs = make_format_args<
typename printf_context<internal::buffer>::type>(args...);
return vfprintf(os, format_str, vargs); return vfprintf(os, format_str, vargs);
} }
template <typename... Args> template <typename... Args>
inline int fprintf(std::wostream &os, wstring_view format_str, const Args &... args) inline int fprintf(std::wostream &os, wstring_view format_str,
{ const Args & ... args) {
auto vargs = make_format_args<typename printf_context<internal::buffer>::type>(args...); auto vargs = make_format_args<
typename printf_context<internal::buffer>::type>(args...);
return vfprintf(os, format_str, vargs); return vfprintf(os, format_str, vargs);
} }
FMT_END_NAMESPACE FMT_END_NAMESPACE

View File

@@ -23,45 +23,31 @@
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
template <typename Char> template <typename Char>
struct formatting_base struct formatting_base {
{
template <typename ParseContext> template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
{
return ctx.begin(); return ctx.begin();
} }
}; };
template <typename Char, typename Enable = void> template <typename Char, typename Enable = void>
struct formatting_range : formatting_base<Char> struct formatting_range : formatting_base<Char> {
{ static FMT_CONSTEXPR_DECL const std::size_t range_length_limit =
static FMT_CONSTEXPR_DECL const std::size_t range_length_limit = FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the range.
// range.
Char prefix; Char prefix;
Char delimiter; Char delimiter;
Char postfix; Char postfix;
formatting_range() formatting_range() : prefix('{'), delimiter(','), postfix('}') {}
: prefix('{')
, delimiter(',')
, postfix('}')
{
}
static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true; static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true;
static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false; static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false;
}; };
template <typename Char, typename Enable = void> template <typename Char, typename Enable = void>
struct formatting_tuple : formatting_base<Char> struct formatting_tuple : formatting_base<Char> {
{
Char prefix; Char prefix;
Char delimiter; Char delimiter;
Char postfix; Char postfix;
formatting_tuple() formatting_tuple() : prefix('('), delimiter(','), postfix(')') {}
: prefix('(')
, delimiter(',')
, postfix(')')
{
}
static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true; static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true;
static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false; static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false;
}; };
@@ -69,71 +55,69 @@ struct formatting_tuple : formatting_base<Char>
namespace internal { namespace internal {
template <typename RangeT, typename OutputIterator> template <typename RangeT, typename OutputIterator>
void copy(const RangeT &range, OutputIterator out) void copy(const RangeT &range, OutputIterator out) {
{
for (auto it = range.begin(), end = range.end(); it != end; ++it) for (auto it = range.begin(), end = range.end(); it != end; ++it)
*out++ = *it; *out++ = *it;
} }
template <typename OutputIterator> template <typename OutputIterator>
void copy(const char *str, OutputIterator out) void copy(const char *str, OutputIterator out) {
{
const char *p_curr = str; const char *p_curr = str;
while (*p_curr) while (*p_curr) {
{
*out++ = *p_curr++; *out++ = *p_curr++;
} }
} }
template <typename OutputIterator> template <typename OutputIterator>
void copy(char ch, OutputIterator out) void copy(char ch, OutputIterator out) {
{
*out++ = ch; *out++ = ch;
} }
/// Return true value if T has std::string interface, like std::string_view. /// Return true value if T has std::string interface, like std::string_view.
template <typename T> template <typename T>
class is_like_std_string class is_like_std_string {
{
template <typename U> template <typename U>
static auto check(U *p) -> decltype(p->find('a'), p->length(), p->data(), int()); static auto check(U *p) ->
decltype(p->find('a'), p->length(), p->data(), int());
template <typename> template <typename>
static void check(...); static void check(...);
public: public:
static FMT_CONSTEXPR_DECL const bool value = !std::is_void<decltype(check<T>(FMT_NULL))>::value; static FMT_CONSTEXPR_DECL const bool value =
!std::is_void<decltype(check<T>(FMT_NULL))>::value;
}; };
template <typename Char>
struct is_like_std_string<fmt::basic_string_view<Char>> : std::true_type {};
template <typename... Ts> template <typename... Ts>
struct conditional_helper struct conditional_helper {};
{
};
template <typename T, typename _ = void> template <typename T, typename _ = void>
struct is_range_ : std::false_type struct is_range_ : std::false_type {};
{
};
#if !FMT_MSC_VER || FMT_MSC_VER > 1800 #if !FMT_MSC_VER || FMT_MSC_VER > 1800
template <typename T> template <typename T>
struct is_range_<T, typename std::conditional<false, struct is_range_<T, typename std::conditional<
conditional_helper<decltype(internal::declval<T>().begin()), decltype(internal::declval<T>().end())>, void>::type> false,
: std::true_type conditional_helper<decltype(internal::declval<T>().begin()),
{ decltype(internal::declval<T>().end())>,
}; void>::type> : std::true_type {};
#endif #endif
/// tuple_size and tuple_element check. /// tuple_size and tuple_element check.
template <typename T> template <typename T>
class is_tuple_like_ class is_tuple_like_ {
{
template <typename U> template <typename U>
static auto check(U *p) -> decltype(std::tuple_size<U>::value, internal::declval<typename std::tuple_element<0, U>::type>(), int()); static auto check(U *p) ->
decltype(std::tuple_size<U>::value,
internal::declval<typename std::tuple_element<0, U>::type>(), int());
template <typename> template <typename>
static void check(...); static void check(...);
public: public:
static FMT_CONSTEXPR_DECL const bool value = !std::is_void<decltype(check<T>(FMT_NULL))>::value; static FMT_CONSTEXPR_DECL const bool value =
!std::is_void<decltype(check<T>(FMT_NULL))>::value;
}; };
// Check for integer_sequence // Check for integer_sequence
@@ -146,12 +130,10 @@ template<std::size_t N>
using make_index_sequence = std::make_index_sequence<N>; using make_index_sequence = std::make_index_sequence<N>;
#else #else
template <typename T, T... N> template <typename T, T... N>
struct integer_sequence struct integer_sequence {
{
typedef T value_type; typedef T value_type;
static FMT_CONSTEXPR std::size_t size() static FMT_CONSTEXPR std::size_t size() {
{
return sizeof...(N); return sizeof...(N);
} }
}; };
@@ -160,21 +142,16 @@ template<std::size_t... N>
using index_sequence = integer_sequence<std::size_t, N...>; using index_sequence = integer_sequence<std::size_t, N...>;
template <typename T, std::size_t N, T... Ns> template <typename T, std::size_t N, T... Ns>
struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
{
};
template <typename T, T... Ns> template <typename T, T... Ns>
struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
{
};
template <std::size_t N> template <std::size_t N>
using make_index_sequence = make_integer_sequence<std::size_t, N>; using make_index_sequence = make_integer_sequence<std::size_t, N>;
#endif #endif
template <class Tuple, class F, size_t... Is> template <class Tuple, class F, size_t... Is>
void for_each(index_sequence<Is...>, Tuple &&tup, F &&f) FMT_NOEXCEPT void for_each(index_sequence<Is...>, Tuple &&tup, F &&f) FMT_NOEXCEPT {
{
using std::get; using std::get;
// using free function get<I>(T) now. // using free function get<I>(T) now.
const int _[] = {0, ((void)f(get<Is>(tup)), 0)...}; const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
@@ -182,78 +159,70 @@ void for_each(index_sequence<Is...>, Tuple &&tup, F &&f) FMT_NOEXCEPT
} }
template <class T> template <class T>
FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(T const &) FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value>
{ get_indexes(T const &) { return {}; }
return {};
}
template <class Tuple, class F> template <class Tuple, class F>
void for_each(Tuple &&tup, F &&f) void for_each(Tuple &&tup, F &&f) {
{
const auto indexes = get_indexes(tup); const auto indexes = get_indexes(tup);
for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f)); for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
} }
template<typename Arg> template<typename Arg>
FMT_CONSTEXPR const char *format_str_quoted( FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
bool add_space, const Arg &, typename std::enable_if<!is_like_std_string<typename std::decay<Arg>::type>::value>::type * = nullptr) typename std::enable_if<
{ !is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
return add_space ? " {}" : "{}"; return add_space ? " {}" : "{}";
} }
template<typename Arg> template<typename Arg>
FMT_CONSTEXPR const char *format_str_quoted( FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
bool add_space, const Arg &, typename std::enable_if<is_like_std_string<typename std::decay<Arg>::type>::value>::type * = nullptr) typename std::enable_if<
{ is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
return add_space ? " \"{}\"" : "\"{}\""; return add_space ? " \"{}\"" : "\"{}\"";
} }
FMT_CONSTEXPR const char *format_str_quoted(bool add_space, const char *) FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char*) {
{
return add_space ? " \"{}\"" : "\"{}\""; return add_space ? " \"{}\"" : "\"{}\"";
} }
FMT_CONSTEXPR const wchar_t *format_str_quoted(bool add_space, const wchar_t *) FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t*) {
{
return add_space ? L" \"{}\"" : L"\"{}\""; return add_space ? L" \"{}\"" : L"\"{}\"";
} }
FMT_CONSTEXPR const char *format_str_quoted(bool add_space, const char) FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char) {
{
return add_space ? " '{}'" : "'{}'"; return add_space ? " '{}'" : "'{}'";
} }
FMT_CONSTEXPR const wchar_t *format_str_quoted(bool add_space, const wchar_t) FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) {
{
return add_space ? L" '{}'" : L"'{}'"; return add_space ? L" '{}'" : L"'{}'";
} }
} // namespace internal } // namespace internal
template <typename T> template <typename T>
struct is_tuple_like struct is_tuple_like {
{ static FMT_CONSTEXPR_DECL const bool value =
static FMT_CONSTEXPR_DECL const bool value = internal::is_tuple_like_<T>::value && !internal::is_range_<T>::value; internal::is_tuple_like_<T>::value && !internal::is_range_<T>::value;
}; };
template <typename TupleT, typename Char> template <typename TupleT, typename Char>
struct formatter<TupleT, Char, typename std::enable_if<fmt::is_tuple_like<TupleT>::value>::type> struct formatter<TupleT, Char,
{ typename std::enable_if<fmt::is_tuple_like<TupleT>::value>::type> {
private: private:
// C++11 generic lambda for format() // C++11 generic lambda for format()
template <typename FormatContext> template <typename FormatContext>
struct format_each struct format_each {
{
template <typename T> template <typename T>
void operator()(const T &v) void operator()(const T& v) {
{ if (i > 0) {
if (i > 0) if (formatting.add_prepostfix_space) {
{
if (formatting.add_prepostfix_space)
{
*out++ = ' '; *out++ = ' ';
} }
internal::copy(formatting.delimiter, out); internal::copy(formatting.delimiter, out);
} }
format_to(out, internal::format_str_quoted((formatting.add_delimiter_spaces && i > 0), v), v); format_to(out,
internal::format_str_quoted(
(formatting.add_delimiter_spaces && i > 0), v),
v);
++i; ++i;
} }
@@ -266,21 +235,18 @@ public:
formatting_tuple<Char> formatting; formatting_tuple<Char> formatting;
template <typename ParseContext> template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
{
return formatting.parse(ctx); return formatting.parse(ctx);
} }
template <typename FormatContext = format_context> template <typename FormatContext = format_context>
auto format(const TupleT &values, FormatContext &ctx) -> decltype(ctx.out()) auto format(const TupleT &values, FormatContext &ctx) -> decltype(ctx.out()) {
{
auto out = ctx.out(); auto out = ctx.out();
std::size_t i = 0; std::size_t i = 0;
internal::copy(formatting.prefix, out); internal::copy(formatting.prefix, out);
internal::for_each(values, format_each<FormatContext>{formatting, i, out}); internal::for_each(values, format_each<FormatContext>{formatting, i, out});
if (formatting.add_prepostfix_space) if (formatting.add_prepostfix_space) {
{
*out++ = ' '; *out++ = ' ';
} }
internal::copy(formatting.postfix, out); internal::copy(formatting.postfix, out);
@@ -290,48 +256,45 @@ public:
}; };
template <typename T> template <typename T>
struct is_range struct is_range {
{ static FMT_CONSTEXPR_DECL const bool value =
static FMT_CONSTEXPR_DECL const bool value = internal::is_range_<T>::value && !internal::is_like_std_string<T>::value; internal::is_range_<T>::value && !internal::is_like_std_string<T>::value;
}; };
template <typename RangeT, typename Char> template <typename RangeT, typename Char>
struct formatter<RangeT, Char, typename std::enable_if<fmt::is_range<RangeT>::value>::type> struct formatter<RangeT, Char,
{ typename std::enable_if<fmt::is_range<RangeT>::value>::type> {
formatting_range<Char> formatting; formatting_range<Char> formatting;
template <typename ParseContext> template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
{
return formatting.parse(ctx); return formatting.parse(ctx);
} }
template <typename FormatContext> template <typename FormatContext>
typename FormatContext::iterator format(const RangeT &values, FormatContext &ctx) typename FormatContext::iterator format(
{ const RangeT &values, FormatContext &ctx) {
auto out = ctx.out(); auto out = ctx.out();
internal::copy(formatting.prefix, out); internal::copy(formatting.prefix, out);
std::size_t i = 0; std::size_t i = 0;
for (auto it = values.begin(), end = values.end(); it != end; ++it) for (auto it = values.begin(), end = values.end(); it != end; ++it) {
{ if (i > 0) {
if (i > 0) if (formatting.add_prepostfix_space) {
{
if (formatting.add_prepostfix_space)
{
*out++ = ' '; *out++ = ' ';
} }
internal::copy(formatting.delimiter, out); internal::copy(formatting.delimiter, out);
} }
format_to(out, internal::format_str_quoted((formatting.add_delimiter_spaces && i > 0), *it), *it); format_to(out,
if (++i > formatting.range_length_limit) internal::format_str_quoted(
{ (formatting.add_delimiter_spaces && i > 0), *it),
*it);
if (++i > formatting.range_length_limit) {
format_to(out, " ... <other elements>"); format_to(out, " ... <other elements>");
break; break;
} }
} }
if (formatting.add_prepostfix_space) if (formatting.add_prepostfix_space) {
{
*out++ = ' '; *out++ = ' ';
} }
internal::copy(formatting.postfix, out); internal::copy(formatting.postfix, out);
@@ -342,3 +305,4 @@ struct formatter<RangeT, Char, typename std::enable_if<fmt::is_range<RangeT>::va
FMT_END_NAMESPACE FMT_END_NAMESPACE
#endif // FMT_RANGES_H_ #endif // FMT_RANGES_H_

View File

@@ -13,66 +13,43 @@
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
// Prevents expansion of a preceding token as a function-style macro.
// Usage: f FMT_NOMACRO()
#define FMT_NOMACRO
namespace internal{ namespace internal{
inline null<> localtime_r(...) inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
{ inline null<> localtime_s(...) { return null<>(); }
return null<>(); inline null<> gmtime_r(...) { return null<>(); }
inline null<> gmtime_s(...) { return null<>(); }
} }
inline null<> localtime_s(...)
{
return null<>();
}
inline null<> gmtime_r(...)
{
return null<>();
}
inline null<> gmtime_s(...)
{
return null<>();
}
} // namespace internal
// Thread-safe replacement for std::localtime // Thread-safe replacement for std::localtime
inline std::tm localtime(std::time_t time) inline std::tm localtime(std::time_t time) {
{ struct dispatcher {
struct dispatcher
{
std::time_t time_; std::time_t time_;
std::tm tm_; std::tm tm_;
dispatcher(std::time_t t) dispatcher(std::time_t t): time_(t) {}
: time_(t)
{
}
bool run() bool run() {
{
using namespace fmt::internal; using namespace fmt::internal;
return handle(localtime_r(&time_, &tm_)); return handle(localtime_r(&time_, &tm_));
} }
bool handle(std::tm *tm) bool handle(std::tm *tm) { return tm != FMT_NULL; }
{
return tm != FMT_NULL;
}
bool handle(internal::null<>) bool handle(internal::null<>) {
{
using namespace fmt::internal; using namespace fmt::internal;
return fallback(localtime_s(&tm_, &time_)); return fallback(localtime_s(&tm_, &time_));
} }
bool fallback(int res) bool fallback(int res) { return res == 0; }
{
return res == 0;
}
bool fallback(internal::null<>) bool fallback(internal::null<>) {
{
using namespace fmt::internal; using namespace fmt::internal;
std::tm *tm = std::localtime(&time_); std::tm *tm = std::localtime(&time_);
if (tm) if (tm) tm_ = *tm;
tm_ = *tm;
return tm != FMT_NULL; return tm != FMT_NULL;
} }
}; };
@@ -84,45 +61,30 @@ inline std::tm localtime(std::time_t time)
} }
// Thread-safe replacement for std::gmtime // Thread-safe replacement for std::gmtime
inline std::tm gmtime(std::time_t time) inline std::tm gmtime(std::time_t time) {
{ struct dispatcher {
struct dispatcher
{
std::time_t time_; std::time_t time_;
std::tm tm_; std::tm tm_;
dispatcher(std::time_t t) dispatcher(std::time_t t): time_(t) {}
: time_(t)
{
}
bool run() bool run() {
{
using namespace fmt::internal; using namespace fmt::internal;
return handle(gmtime_r(&time_, &tm_)); return handle(gmtime_r(&time_, &tm_));
} }
bool handle(std::tm *tm) bool handle(std::tm *tm) { return tm != FMT_NULL; }
{
return tm != FMT_NULL;
}
bool handle(internal::null<>) bool handle(internal::null<>) {
{
using namespace fmt::internal; using namespace fmt::internal;
return fallback(gmtime_s(&tm_, &time_)); return fallback(gmtime_s(&tm_, &time_));
} }
bool fallback(int res) bool fallback(int res) { return res == 0; }
{
return res == 0;
}
bool fallback(internal::null<>) bool fallback(internal::null<>) {
{
std::tm *tm = std::gmtime(&time_); std::tm *tm = std::gmtime(&time_);
if (tm) if (tm) tm_ = *tm;
tm_ = *tm;
return tm != FMT_NULL; return tm != FMT_NULL;
} }
}; };
@@ -134,23 +96,21 @@ inline std::tm gmtime(std::time_t time)
} }
namespace internal { namespace internal {
inline std::size_t strftime(char *str, std::size_t count, const char *format, const std::tm *time) inline std::size_t strftime(char *str, std::size_t count, const char *format,
{ const std::tm *time) {
return std::strftime(str, count, format, time); return std::strftime(str, count, format, time);
} }
inline std::size_t strftime(wchar_t *str, std::size_t count, const wchar_t *format, const std::tm *time) inline std::size_t strftime(wchar_t *str, std::size_t count,
{ const wchar_t *format, const std::tm *time) {
return std::wcsftime(str, count, format, time); return std::wcsftime(str, count, format, time);
} }
} // namespace internal }
template <typename Char> template <typename Char>
struct formatter<std::tm, Char> struct formatter<std::tm, Char> {
{
template <typename ParseContext> template <typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin()) auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
{
auto it = internal::null_terminating_iterator<Char>(ctx); auto it = internal::null_terminating_iterator<Char>(ctx);
if (*it == ':') if (*it == ':')
++it; ++it;
@@ -165,21 +125,18 @@ struct formatter<std::tm, Char>
} }
template <typename FormatContext> template <typename FormatContext>
auto format(const std::tm &tm, FormatContext &ctx) -> decltype(ctx.out()) auto format(const std::tm &tm, FormatContext &ctx) -> decltype(ctx.out()) {
{
internal::basic_buffer<Char> &buf = internal::get_container(ctx.out()); internal::basic_buffer<Char> &buf = internal::get_container(ctx.out());
std::size_t start = buf.size(); std::size_t start = buf.size();
for (;;) for (;;) {
{
std::size_t size = buf.capacity() - start; std::size_t size = buf.capacity() - start;
std::size_t count = internal::strftime(&buf[start], size, &tm_format[0], &tm); std::size_t count =
if (count != 0) internal::strftime(&buf[start], size, &tm_format[0], &tm);
{ if (count != 0) {
buf.resize(start + count); buf.resize(start + count);
break; break;
} }
if (size >= tm_format.size() * 256) if (size >= tm_format.size() * 256) {
{
// If the buffer is 256 times larger than the format string, assume // If the buffer is 256 times larger than the format string, assume
// that `strftime` gives an empty result. There doesn't seem to be a // that `strftime` gives an empty result. There doesn't seem to be a
// better way to distinguish the two cases: // better way to distinguish the two cases:

View File

@@ -22,6 +22,7 @@
#include "spdlog/formatter.h" #include "spdlog/formatter.h"
#include "spdlog/sinks/sink.h" #include "spdlog/sinks/sink.h"
#include <locale>
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -35,7 +36,7 @@ public:
logger(std::string name, sinks_init_list sinks); logger(std::string name, sinks_init_list sinks);
template<typename It> template<typename It>
logger(std::string name, const It &begin, const It &end); logger(std::string name, It begin, It end);
virtual ~logger(); virtual ~logger();
@@ -67,6 +68,9 @@ public:
void critical(const char *fmt, const Args &... args); void critical(const char *fmt, const Args &... args);
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
#ifndef _WIN32
#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
#else
template<typename... Args> template<typename... Args>
void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args);
@@ -87,6 +91,7 @@ public:
template<typename... Args> template<typename... Args>
void critical(const wchar_t *fmt, const Args &... args); void critical(const wchar_t *fmt, const Args &... args);
#endif // _WIN32
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
template<typename T> template<typename T>
@@ -120,16 +125,22 @@ public:
void set_formatter(std::unique_ptr<formatter> formatter); void set_formatter(std::unique_ptr<formatter> formatter);
void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local); void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);
// flush functions
void flush(); void flush();
void flush_on(level::level_enum log_level); void flush_on(level::level_enum log_level);
level::level_enum flush_level() const;
// sinks
const std::vector<sink_ptr> &sinks() const; const std::vector<sink_ptr> &sinks() const;
std::vector<sink_ptr> &sinks(); std::vector<sink_ptr> &sinks();
// error handler
void set_error_handler(log_err_handler err_handler); void set_error_handler(log_err_handler err_handler);
log_err_handler error_handler(); log_err_handler error_handler();
// create new logger with same sinks and configuration.
virtual std::shared_ptr<logger> clone(std::string logger_name);
protected: protected:
virtual void sink_it_(details::log_msg &msg); virtual void sink_it_(details::log_msg &msg);
virtual void flush_(); virtual void flush_();
@@ -140,8 +151,7 @@ protected:
// message/minute // message/minute
void default_err_handler_(const std::string &msg); void default_err_handler_(const std::string &msg);
// increment the message count (only if // increment the message count (only if defined(SPDLOG_ENABLE_MESSAGE_COUNTER))
// defined(SPDLOG_ENABLE_MESSAGE_COUNTER))
void incr_msg_counter_(details::log_msg &msg); void incr_msg_counter_(details::log_msg &msg);
const std::string name_; const std::string name_;
@@ -151,11 +161,6 @@ protected:
log_err_handler err_handler_; log_err_handler err_handler_;
std::atomic<time_t> last_err_time_; std::atomic<time_t> last_err_time_;
std::atomic<size_t> msg_counter_; std::atomic<size_t> msg_counter_;
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
std::wstring_convert<std::codecvt_utf8<wchar_t>> wstring_converter_;
std::mutex wstring_converter_mutex_;
#endif
}; };
} // namespace spdlog } // namespace spdlog

View File

@@ -27,7 +27,7 @@ namespace sinks {
* Android sink (logging using __android_log_write) * Android sink (logging using __android_log_write)
*/ */
template<typename Mutex> template<typename Mutex>
class android_sink SPDLOG_FINAL : public base_sink<Mutex> class android_sink final : public base_sink<Mutex>
{ {
public: public:
explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false) explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false)

View File

@@ -8,6 +8,7 @@
#include "spdlog/details/console_globals.h" #include "spdlog/details/console_globals.h"
#include "spdlog/details/null_mutex.h" #include "spdlog/details/null_mutex.h"
#include "spdlog/details/os.h" #include "spdlog/details/os.h"
#include "spdlog/sinks/sink.h"
#include <memory> #include <memory>
#include <mutex> #include <mutex>
@@ -24,7 +25,7 @@ namespace sinks {
* If no color terminal detected, omit the escape codes. * If no color terminal detected, omit the escape codes.
*/ */
template<typename TargetStream, class ConsoleMutex> template<typename TargetStream, class ConsoleMutex>
class ansicolor_sink SPDLOG_FINAL : public sink class ansicolor_sink final : public sink
{ {
public: public:
using mutex_t = typename ConsoleMutex::mutex_t; using mutex_t = typename ConsoleMutex::mutex_t;
@@ -116,7 +117,7 @@ public:
fflush(target_file_); fflush(target_file_);
} }
void set_pattern(const std::string &pattern) SPDLOG_FINAL void set_pattern(const std::string &pattern) final
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern)); formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));

View File

@@ -22,41 +22,47 @@ template<typename Mutex>
class base_sink : public sink class base_sink : public sink
{ {
public: public:
base_sink() base_sink() = default;
: sink()
{
}
base_sink(const base_sink &) = delete; base_sink(const base_sink &) = delete;
base_sink &operator=(const base_sink &) = delete; base_sink &operator=(const base_sink &) = delete;
void log(const details::log_msg &msg) SPDLOG_FINAL void log(const details::log_msg &msg) final
{ {
std::lock_guard<Mutex> lock(mutex_); std::lock_guard<Mutex> lock(mutex_);
sink_it_(msg); sink_it_(msg);
} }
void flush() SPDLOG_FINAL override void flush() final
{ {
std::lock_guard<Mutex> lock(mutex_); std::lock_guard<Mutex> lock(mutex_);
flush_(); flush_();
} }
void set_pattern(const std::string &pattern) SPDLOG_FINAL override void set_pattern(const std::string &pattern) final
{ {
std::lock_guard<Mutex> lock(mutex_); std::lock_guard<Mutex> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern)); set_pattern_(pattern);
} }
void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) SPDLOG_FINAL override void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) final
{ {
std::lock_guard<Mutex> lock(mutex_); std::lock_guard<Mutex> lock(mutex_);
formatter_ = std::move(sink_formatter); set_formatter_(std::move(sink_formatter));
} }
protected: protected:
virtual void sink_it_(const details::log_msg &msg) = 0; virtual void sink_it_(const details::log_msg &msg) = 0;
virtual void flush_() = 0; virtual void flush_() = 0;
virtual void set_pattern_(const std::string &pattern)
{
set_formatter_(details::make_unique<spdlog::pattern_formatter>(pattern));
}
virtual void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter)
{
formatter_ = std::move(sink_formatter);
}
Mutex mutex_; Mutex mutex_;
}; };
} // namespace sinks } // namespace sinks

View File

@@ -18,7 +18,7 @@ namespace sinks {
* Trivial file sink with single file as target * Trivial file sink with single file as target
*/ */
template<typename Mutex> template<typename Mutex>
class basic_file_sink SPDLOG_FINAL : public base_sink<Mutex> class basic_file_sink final : public base_sink<Mutex>
{ {
public: public:
explicit basic_file_sink(const filename_t &filename, bool truncate = false) explicit basic_file_sink(const filename_t &filename, bool truncate = false)

View File

@@ -40,7 +40,7 @@ struct daily_filename_calculator
* Rotating file sink based on date. rotates at midnight * Rotating file sink based on date. rotates at midnight
*/ */
template<typename Mutex, typename FileNameCalc = daily_filename_calculator> template<typename Mutex, typename FileNameCalc = daily_filename_calculator>
class daily_file_sink SPDLOG_FINAL : public base_sink<Mutex> class daily_file_sink final : public base_sink<Mutex>
{ {
public: public:
// create daily file sink which rotates on given time // create daily file sink which rotates on given time

View File

@@ -40,6 +40,12 @@ public:
sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end()); sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end());
} }
void set_sinks(std::vector<std::shared_ptr<sink>> sinks)
{
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
sinks_ = std::move(sinks);
}
protected: protected:
void sink_it_(const details::log_msg &msg) override void sink_it_(const details::log_msg &msg) override
{ {
@@ -56,8 +62,24 @@ protected:
void flush_() override void flush_() override
{ {
for (auto &sink : sinks_) for (auto &sink : sinks_)
{
sink->flush(); sink->flush();
} }
}
void set_pattern_(const std::string &pattern) override
{
set_formatter_(details::make_unique<spdlog::pattern_formatter>(pattern));
}
void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter) override
{
base_sink<Mutex>::formatter_ = std::move(sink_formatter);
for (auto &sink : sinks_)
{
sink->set_formatter(base_sink<Mutex>::formatter_->clone());
}
}
std::vector<std::shared_ptr<sink>> sinks_; std::vector<std::shared_ptr<sink>> sinks_;
}; };

View File

@@ -14,7 +14,7 @@
namespace spdlog { namespace spdlog {
namespace sinks { namespace sinks {
template<typename Mutex> template<typename Mutex>
class ostream_sink SPDLOG_FINAL : public base_sink<Mutex> class ostream_sink final : public base_sink<Mutex>
{ {
public: public:
explicit ostream_sink(std::ostream &os, bool force_flush = false) explicit ostream_sink(std::ostream &os, bool force_flush = false)
@@ -30,10 +30,12 @@ protected:
{ {
fmt::memory_buffer formatted; fmt::memory_buffer formatted;
sink::formatter_->format(msg, formatted); sink::formatter_->format(msg, formatted);
ostream_.write(formatted.data(), formatted.size()); ostream_.write(formatted.data(), static_cast<std::streamsize>(formatted.size()));
if (force_flush_) if (force_flush_)
{
ostream_.flush(); ostream_.flush();
} }
}
void flush_() override void flush_() override
{ {

View File

@@ -24,7 +24,7 @@ namespace sinks {
// Rotating file sink based on size // Rotating file sink based on size
// //
template<typename Mutex> template<typename Mutex>
class rotating_file_sink SPDLOG_FINAL : public base_sink<Mutex> class rotating_file_sink final : public base_sink<Mutex>
{ {
public: public:
rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files) rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files)
@@ -86,24 +86,21 @@ private:
for (auto i = max_files_; i > 0; --i) for (auto i = max_files_; i > 0; --i)
{ {
filename_t src = calc_filename(base_filename_, i - 1); filename_t src = calc_filename(base_filename_, i - 1);
if (!details::file_helper::file_exists(src))
{
continue;
}
filename_t target = calc_filename(base_filename_, i); filename_t target = calc_filename(base_filename_, i);
if (details::file_helper::file_exists(target)) if (!rename_file(src, target))
{ {
if (details::os::remove(target) != 0) // if failed try again after a small delay.
{
throw spdlog_ex("rotating_file_sink: failed removing " + filename_to_str(target), errno);
}
}
if (details::file_helper::file_exists(src) && details::os::rename(src, target) != 0)
{
// if failed try again after small delay.
// this is a workaround to a windows issue, where very high rotation // this is a workaround to a windows issue, where very high rotation
// rates sometimes fail (because of antivirus?). // rates can cause the rename to fail with permission denied (because of antivirus?).
details::os::sleep_for_millis(20); details::os::sleep_for_millis(100);
details::os::remove(target); if (!rename_file(src, target))
if (details::os::rename(src, target) != 0)
{ {
file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit!
throw spdlog_ex( throw spdlog_ex(
"rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno); "rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno);
} }
@@ -112,6 +109,15 @@ private:
file_helper_.reopen(true); file_helper_.reopen(true);
} }
// delete the target if exists, and rename the src file to target
// return true on success, false otherwise.
bool rename_file(const filename_t &src_filename, const filename_t &target_filename)
{
// try to delete the target file in case it already exists.
(void)details::os::remove(target_filename);
return details::os::rename(src_filename, target_filename) == 0;
}
filename_t base_filename_; filename_t base_filename_;
std::size_t max_size_; std::size_t max_size_;
std::size_t max_files_; std::size_t max_files_;

View File

@@ -22,7 +22,9 @@ public:
explicit sink(std::unique_ptr<spdlog::pattern_formatter> formatter) explicit sink(std::unique_ptr<spdlog::pattern_formatter> formatter)
: level_(level::trace) : level_(level::trace)
, formatter_(std::move(formatter)){}; , formatter_(std::move(formatter))
{
}
virtual ~sink() = default; virtual ~sink() = default;
virtual void log(const details::log_msg &msg) = 0; virtual void log(const details::log_msg &msg) = 0;

View File

@@ -12,14 +12,13 @@
#include <cstdio> #include <cstdio>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <spdlog/details/console_globals.h>
namespace spdlog { namespace spdlog {
namespace sinks { namespace sinks {
template<typename TargetStream, typename ConsoleMutex> template<typename TargetStream, typename ConsoleMutex>
class stdout_sink SPDLOG_FINAL : public sink class stdout_sink final : public sink
{ {
public: public:
using mutex_t = typename ConsoleMutex::mutex_t; using mutex_t = typename ConsoleMutex::mutex_t;

View File

@@ -61,7 +61,7 @@ public:
colors_[level] = color; colors_[level] = color;
} }
void log(const details::log_msg &msg) SPDLOG_FINAL override void log(const details::log_msg &msg) final override
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
fmt::memory_buffer formatted; fmt::memory_buffer formatted;
@@ -85,18 +85,18 @@ public:
} }
} }
void flush() SPDLOG_FINAL override void flush() final override
{ {
// windows console always flushed? // windows console always flushed?
} }
void set_pattern(const std::string &pattern) override SPDLOG_FINAL void set_pattern(const std::string &pattern) override final
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern)); formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
} }
void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override SPDLOG_FINAL void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override final
{ {
std::lock_guard<mutex_t> lock(mutex_); std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter); formatter_ = std::move(sink_formatter);

View File

@@ -108,15 +108,6 @@
// #define SPDLOG_PREVENT_CHILD_FD // #define SPDLOG_PREVENT_CHILD_FD
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Uncomment if your compiler doesn't support the "final" keyword.
// The final keyword allows more optimizations in release
// mode with recent compilers. See GCC's documentation for -Wsuggest-final-types
// for instance.
//
// #define SPDLOG_NO_FINAL
///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Uncomment to enable message counting feature. // Uncomment to enable message counting feature.
// Use the %i in the logger pattern to display log message sequence id. // Use the %i in the logger pattern to display log message sequence id.

View File

@@ -6,7 +6,7 @@
#pragma once #pragma once
#define SPDLOG_VER_MAJOR 1 #define SPDLOG_VER_MAJOR 1
#define SPDLOG_VER_MINOR 1 #define SPDLOG_VER_MINOR 2
#define SPDLOG_VER_PATCH 0 #define SPDLOG_VER_PATCH 0
#define SPDLOG_VERSION (SPDLOG_VER_MAJOR * 10000 + SPDLOG_VER_MINOR * 100 + SPDLOG_VER_PATCH) #define SPDLOG_VERSION (SPDLOG_VER_MAJOR * 10000 + SPDLOG_VER_MINOR * 100 + SPDLOG_VER_PATCH)

View File

@@ -17,7 +17,7 @@ set(SPDLOG_UTESTS_SOURCES
main.cpp main.cpp
test_mpmc_q.cpp test_mpmc_q.cpp
test_sink.h test_sink.h
) test_fmt_helper.cpp)
add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES}) add_executable(${PROJECT_NAME} ${SPDLOG_UTESTS_SOURCES})
target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads)

View File

@@ -1,5 +1,5 @@
CXX ?= g++ CXX ?= g++
CXXFLAGS = -Wall -pedantic -std=c++11 -pthread -O3 -I../include -fmax-errors=1 CXXFLAGS = -Wall -pedantic -std=c++11 -pthread -Wconversion -O3 -I../include -fmax-errors=1
LDPFALGS = -pthread LDPFALGS = -pthread
CPP_FILES := $(wildcard *.cpp) CPP_FILES := $(wildcard *.cpp)

View File

@@ -83,7 +83,9 @@ TEST_CASE("async_error_handler", "[errors]]")
logger->set_error_handler([=](const std::string &) { logger->set_error_handler([=](const std::string &) {
std::ofstream ofs("logs/custom_err.txt"); std::ofstream ofs("logs/custom_err.txt");
if (!ofs) if (!ofs)
{
throw std::runtime_error("Failed open logs/custom_err.txt"); throw std::runtime_error("Failed open logs/custom_err.txt");
}
ofs << err_msg; ofs << err_msg;
}); });
logger->info("Good message #1"); logger->info("Good message #1");

View File

@@ -62,7 +62,9 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]")
std::string basename = "logs/rotating_log"; std::string basename = "logs/rotating_log";
auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 1); auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 1);
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
{
logger->info("Test message {}", i); logger->info("Test message {}", i);
}
logger->flush(); logger->flush();
auto filename = basename; auto filename = basename;

View File

@@ -6,11 +6,13 @@
#include <cstdio> #include <cstdio>
#include <exception> #include <exception>
#include <fstream> #include <fstream>
#include <iostream>
#include <ostream> #include <ostream>
#include <string> #include <string>
#define SPDLOG_TRACE_ON #define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON #define SPDLOG_DEBUG_ON
#define SPDLOG_ENABLE_MESSAGE_COUNTER
#include "spdlog/async.h" #include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/basic_file_sink.h"

View File

@@ -62,7 +62,7 @@ TEST_CASE("drop_all"
spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name2); spdlog::create<spdlog::sinks::null_sink_mt>(tested_logger_name2);
spdlog::drop_all(); spdlog::drop_all();
REQUIRE_FALSE(spdlog::get(tested_logger_name)); REQUIRE_FALSE(spdlog::get(tested_logger_name));
REQUIRE_FALSE(spdlog::get(tested_logger_name)); REQUIRE_FALSE(spdlog::get(tested_logger_name2));
} }
TEST_CASE("drop non existing" TEST_CASE("drop non existing"

54
tests/test_fmt_helper.cpp Normal file
View File

@@ -0,0 +1,54 @@
#include "includes.h"
void test_pad2(int n, const char *expected)
{
fmt::memory_buffer buf;
spdlog::details::fmt_helper::pad2(n, buf);
REQUIRE(fmt::to_string(buf) == expected);
}
void test_pad3(int n, const char *expected)
{
fmt::memory_buffer buf;
spdlog::details::fmt_helper::pad3(n, buf);
REQUIRE(fmt::to_string(buf) == expected);
}
void test_pad6(std::size_t n, const char *expected)
{
fmt::memory_buffer buf;
spdlog::details::fmt_helper::pad6(n, buf);
REQUIRE(fmt::to_string(buf) == expected);
}
TEST_CASE("pad2", "[fmt_helper]")
{
test_pad2(0, "00");
test_pad2(3, "03");
test_pad2(23, "23");
test_pad2(123, "123");
test_pad2(1234, "1234");
test_pad2(-5, "-5");
}
TEST_CASE("pad3", "[fmt_helper]")
{
test_pad3(0, "000");
test_pad3(3, "003");
test_pad3(23, "023");
test_pad3(123, "123");
test_pad3(1234, "1234");
test_pad3(-5, "-05");
}
TEST_CASE("pad6", "[fmt_helper]")
{
test_pad6(0, "000000");
test_pad6(3, "000003");
test_pad6(23, "000023");
test_pad6(123, "000123");
test_pad6(1234, "001234");
test_pad6(12345, "012345");
test_pad6(123456, "123456");
}

View File

@@ -91,3 +91,103 @@ TEST_CASE("periodic flush", "[periodic_flush]")
spdlog::flush_every(std::chrono::seconds(0)); spdlog::flush_every(std::chrono::seconds(0));
spdlog::drop_all(); spdlog::drop_all();
} }
TEST_CASE("clone", "[clone]")
{
using namespace spdlog;
auto logger = spdlog::create<sinks::test_sink_mt>("orig");
auto cloned = logger->clone("clone");
REQUIRE(cloned->name() == "clone");
REQUIRE(logger->sinks() == cloned->sinks());
REQUIRE(logger->level() == cloned->level());
REQUIRE(logger->flush_level() == cloned->flush_level());
logger->info("Some message 1");
cloned->info("Some message 2");
auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]);
REQUIRE(test_sink->msg_counter() == 2);
spdlog::drop_all();
}
TEST_CASE("clone async", "[clone]")
{
using namespace spdlog;
auto logger = spdlog::create_async<sinks::test_sink_mt>("orig");
auto cloned = logger->clone("clone");
REQUIRE(cloned->name() == "clone");
REQUIRE(logger->sinks() == cloned->sinks());
REQUIRE(logger->level() == cloned->level());
REQUIRE(logger->flush_level() == cloned->flush_level());
logger->info("Some message 1");
cloned->info("Some message 2");
spdlog::details::os::sleep_for_millis(10);
auto test_sink = std::static_pointer_cast<sinks::test_sink_mt>(cloned->sinks()[0]);
REQUIRE(test_sink->msg_counter() == 2);
spdlog::drop_all();
}
#include "spdlog/fmt/bin_to_hex.h"
TEST_CASE("to_hex", "[to_hex]")
{
std::ostringstream oss;
auto oss_sink = std::make_shared<spdlog::sinks::ostream_sink_mt>(oss);
spdlog::logger oss_logger("oss", oss_sink);
std::vector<unsigned char> v{9, 0xa, 0xb, 0xc, 0xff, 0xff};
oss_logger.info("{}", spdlog::to_hex(v));
auto output = oss.str();
REQUIRE(ends_with(output, "0000: 09 0a 0b 0c ff ff" + std::string(spdlog::details::os::default_eol)));
}
TEST_CASE("to_hex_upper", "[to_hex]")
{
std::ostringstream oss;
auto oss_sink = std::make_shared<spdlog::sinks::ostream_sink_mt>(oss);
spdlog::logger oss_logger("oss", oss_sink);
std::vector<unsigned char> v{9, 0xa, 0xb, 0xc, 0xff, 0xff};
oss_logger.info("{:X}", spdlog::to_hex(v));
auto output = oss.str();
REQUIRE(ends_with(output, "0000: 09 0A 0B 0C FF FF" + std::string(spdlog::details::os::default_eol)));
}
TEST_CASE("to_hex_no_delimiter", "[to_hex]")
{
std::ostringstream oss;
auto oss_sink = std::make_shared<spdlog::sinks::ostream_sink_mt>(oss);
spdlog::logger oss_logger("oss", oss_sink);
std::vector<unsigned char> v{9, 0xa, 0xb, 0xc, 0xff, 0xff};
oss_logger.info("{:sX}", spdlog::to_hex(v));
auto output = oss.str();
REQUIRE(ends_with(output, "0000: 090A0B0CFFFF" + std::string(spdlog::details::os::default_eol)));
}
TEST_CASE("message_counter", "[message_counter]")
{
std::ostringstream oss;
auto oss_sink = std::make_shared<spdlog::sinks::ostream_sink_mt>(oss);
spdlog::logger oss_logger("oss", oss_sink);
oss_logger.set_pattern("%i %v");
oss_logger.info("Hello");
REQUIRE(oss.str() == "000001 Hello" + std::string(spdlog::details::os::default_eol));
oss.str("");
oss_logger.info("Hello again");
REQUIRE(oss.str() == "000002 Hello again" + std::string(spdlog::details::os::default_eol));
}

View File

@@ -2,11 +2,11 @@
using namespace std::chrono; using namespace std::chrono;
using std::chrono::milliseconds; using std::chrono::milliseconds;
using std::chrono::system_clock; using test_clock = std::chrono::high_resolution_clock;
system_clock::time_point now_millis() static milliseconds millis_from(const test_clock::time_point &tp0)
{ {
return time_point_cast<milliseconds>(system_clock::now()); return std::chrono::duration_cast<milliseconds>(test_clock::now() - tp0);
} }
TEST_CASE("dequeue-empty-nowait", "[mpmc_blocking_q]") TEST_CASE("dequeue-empty-nowait", "[mpmc_blocking_q]")
{ {
@@ -15,12 +15,13 @@ TEST_CASE("dequeue-empty-nowait", "[mpmc_blocking_q]")
spdlog::details::mpmc_blocking_queue<int> q(q_size); spdlog::details::mpmc_blocking_queue<int> q(q_size);
int popped_item; int popped_item;
auto millis_0 = now_millis(); auto start = test_clock::now();
auto rv = q.dequeue_for(popped_item, milliseconds::zero()); auto rv = q.dequeue_for(popped_item, milliseconds::zero());
auto millis_1 = now_millis(); auto delta_ms = millis_from(start);
REQUIRE(rv == false); REQUIRE(rv == false);
REQUIRE((millis_1 - millis_0) <= tolerance_wait); INFO("Delta " << delta_ms.count() << " millis");
REQUIRE(delta_ms <= tolerance_wait);
} }
TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]") TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]")
@@ -28,17 +29,18 @@ TEST_CASE("dequeue-empty-wait", "[mpmc_blocking_q]")
size_t q_size = 100; size_t q_size = 100;
milliseconds wait_ms(250); milliseconds wait_ms(250);
milliseconds tolerance_wait(10); milliseconds tolerance_wait(50);
spdlog::details::mpmc_blocking_queue<int> q(q_size); spdlog::details::mpmc_blocking_queue<int> q(q_size);
int popped_item; int popped_item;
auto millis_0 = now_millis(); auto start = test_clock::now();
auto rv = q.dequeue_for(popped_item, wait_ms); auto rv = q.dequeue_for(popped_item, wait_ms);
auto millis_1 = now_millis(); auto delta_ms = millis_from(start);
auto delta_ms = millis_1 - millis_0;
REQUIRE(rv == false); REQUIRE(rv == false);
REQUIRE(delta_ms >= wait_ms);
INFO("Delta " << delta_ms.count() << " millis");
REQUIRE(delta_ms >= wait_ms - tolerance_wait);
REQUIRE(delta_ms <= wait_ms + tolerance_wait); REQUIRE(delta_ms <= wait_ms + tolerance_wait);
} }
@@ -52,10 +54,12 @@ TEST_CASE("enqueue_nowait", "[mpmc_blocking_q]")
q.enqueue(1); q.enqueue(1);
REQUIRE(q.overrun_counter() == 0); REQUIRE(q.overrun_counter() == 0);
auto millis_0 = now_millis(); auto start = test_clock::now();
q.enqueue_nowait(2); q.enqueue_nowait(2);
auto millis_1 = now_millis(); auto delta_ms = millis_from(start);
REQUIRE((millis_1 - millis_0) <= tolerance_wait);
INFO("Delta " << delta_ms.count() << " millis");
REQUIRE(delta_ms <= tolerance_wait);
REQUIRE(q.overrun_counter() == 1); REQUIRE(q.overrun_counter() == 1);
} }

View File

@@ -20,9 +20,6 @@ TEST_CASE("custom eol", "[pattern_formatter]")
{ {
std::string msg = "Hello custom eol test"; std::string msg = "Hello custom eol test";
std::string eol = ";)"; std::string eol = ";)";
// auto formatter = std::make_shared<spdlog::pattern_formatter>("%v", spdlog::pattern_time_type::local, ";)");
std::unique_ptr<spdlog::formatter>(new spdlog::pattern_formatter("%v", spdlog::pattern_time_type::local, ";)"));
REQUIRE(log_to_str(msg, "%v", spdlog::pattern_time_type::local, ";)") == msg + eol); REQUIRE(log_to_str(msg, "%v", spdlog::pattern_time_type::local, ";)") == msg + eol);
} }

View File

@@ -56,7 +56,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{093AE34A
..\include\spdlog\sinks\ansicolor_sink.h = ..\include\spdlog\sinks\ansicolor_sink.h ..\include\spdlog\sinks\ansicolor_sink.h = ..\include\spdlog\sinks\ansicolor_sink.h
..\include\spdlog\sinks\base_sink.h = ..\include\spdlog\sinks\base_sink.h ..\include\spdlog\sinks\base_sink.h = ..\include\spdlog\sinks\base_sink.h
..\include\spdlog\sinks\dist_sink.h = ..\include\spdlog\sinks\dist_sink.h ..\include\spdlog\sinks\dist_sink.h = ..\include\spdlog\sinks\dist_sink.h
..\include\spdlog\sinks\file_sinks.h = ..\include\spdlog\sinks\file_sinks.h
..\include\spdlog\sinks\msvc_sink.h = ..\include\spdlog\sinks\msvc_sink.h ..\include\spdlog\sinks\msvc_sink.h = ..\include\spdlog\sinks\msvc_sink.h
..\include\spdlog\sinks\null_sink.h = ..\include\spdlog\sinks\null_sink.h ..\include\spdlog\sinks\null_sink.h = ..\include\spdlog\sinks\null_sink.h
..\include\spdlog\sinks\ostream_sink.h = ..\include\spdlog\sinks\ostream_sink.h ..\include\spdlog\sinks\ostream_sink.h = ..\include\spdlog\sinks\ostream_sink.h
@@ -65,7 +64,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{093AE34A
..\include\spdlog\sinks\stdout_sinks.h = ..\include\spdlog\sinks\stdout_sinks.h ..\include\spdlog\sinks\stdout_sinks.h = ..\include\spdlog\sinks\stdout_sinks.h
..\include\spdlog\sinks\syslog_sink.h = ..\include\spdlog\sinks\syslog_sink.h ..\include\spdlog\sinks\syslog_sink.h = ..\include\spdlog\sinks\syslog_sink.h
..\include\spdlog\sinks\wincolor_sink.h = ..\include\spdlog\sinks\wincolor_sink.h ..\include\spdlog\sinks\wincolor_sink.h = ..\include\spdlog\sinks\wincolor_sink.h
..\include\spdlog\sinks\windebug_sink.h = ..\include\spdlog\sinks\windebug_sink.h
EndProjectSection EndProjectSection
EndProject EndProject
Global Global

View File

@@ -8,8 +8,15 @@ void prepare_logdir()
system("del /F /Q logs\\*"); system("del /F /Q logs\\*");
#else #else
auto rv = system("mkdir -p logs"); auto rv = system("mkdir -p logs");
if (rv != 0)
{
throw std::runtime_error("Failed to mkdir -p logs");
}
rv = system("rm -f logs/*"); rv = system("rm -f logs/*");
(void)rv; if (rv != 0)
{
throw std::runtime_error("Failed to rm -f logs/*");
}
#endif #endif
} }
@@ -17,7 +24,9 @@ std::string file_contents(const std::string &filename)
{ {
std::ifstream ifs(filename); std::ifstream ifs(filename);
if (!ifs) if (!ifs)
{
throw std::runtime_error("Failed open file "); throw std::runtime_error("Failed open file ");
}
return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
} }
@@ -25,7 +34,9 @@ std::size_t count_lines(const std::string &filename)
{ {
std::ifstream ifs(filename); std::ifstream ifs(filename);
if (!ifs) if (!ifs)
{
throw std::runtime_error("Failed open file "); throw std::runtime_error("Failed open file ");
}
std::string line; std::string line;
size_t counter = 0; size_t counter = 0;
@@ -38,7 +49,9 @@ std::size_t get_filesize(const std::string &filename)
{ {
std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary); std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary);
if (!ifs) if (!ifs)
{
throw std::runtime_error("Failed open file "); throw std::runtime_error("Failed open file ");
}
return static_cast<std::size_t>(ifs.tellg()); return static_cast<std::size_t>(ifs.tellg());
} }
@@ -47,6 +60,8 @@ std::size_t get_filesize(const std::string &filename)
bool ends_with(std::string const &value, std::string const &ending) bool ends_with(std::string const &value, std::string const &ending)
{ {
if (ending.size() > value.size()) if (ending.size() > value.size())
{
return false; return false;
}
return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
} }