From 4a34cd06624d17545fbd17ee0cc35eb7ae7176d5 Mon Sep 17 00:00:00 2001 From: gabime Date: Mon, 12 Nov 2018 16:44:34 +0200 Subject: [PATCH 01/83] Optimized nano seconds formatting --- bench/formatter-bench.cpp | 5 ++--- include/spdlog/details/fmt_helper.h | 13 ++++++++++++ include/spdlog/details/pattern_formatter.h | 3 ++- tests/test_fmt_helper.cpp | 23 ++++++++++++++++++++++ 4 files changed, 40 insertions(+), 4 deletions(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index 0dbf6d82..11ec2a31 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -50,8 +50,7 @@ void bench_formatters() for(auto &flag:all_flags) { auto pattern = std::string("%") + flag; - benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); - + benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern)->Iterations(2500000); } // complex patterns @@ -62,7 +61,7 @@ void bench_formatters() }; for(auto &pattern:patterns) { - benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); + benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern)->Iterations(2500000); } } diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index 1f716ac5..de6f998f 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -110,6 +110,19 @@ inline void pad6(size_t n, fmt::basic_memory_buffer &dest) pad3(static_cast(n % 1000), dest); } + +template +inline void pad9(size_t n, fmt::basic_memory_buffer &dest) +{ + if (n > 99999999) + { + append_int(n, dest); + return; + } + pad6(static_cast(n / 1000), dest); + pad3(static_cast(n % 1000), dest); +} + // return fraction of a second of the given time_point. // e.g. // fraction(tp) -> will return the millis part of the second diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 9d018fb8..a9b1a49c 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -486,7 +486,8 @@ public: scoped_pad p(field_size, padinfo_, dest); auto ns = fmt_helper::time_fraction(msg.time); - fmt::format_to(dest, "{:09}", ns.count()); + fmt_helper::pad9(static_cast(ns.count()), dest); + } }; diff --git a/tests/test_fmt_helper.cpp b/tests/test_fmt_helper.cpp index 415638ae..9ebbcf73 100644 --- a/tests/test_fmt_helper.cpp +++ b/tests/test_fmt_helper.cpp @@ -22,6 +22,13 @@ void test_pad6(std::size_t n, const char *expected) REQUIRE(fmt::to_string(buf) == expected); } +void test_pad9(std::size_t n, const char *expected) +{ + fmt::memory_buffer buf; + spdlog::details::fmt_helper::pad9(n, buf); + REQUIRE(fmt::to_string(buf) == expected); +} + TEST_CASE("pad2", "[fmt_helper]") { test_pad2(0, "00"); @@ -52,3 +59,19 @@ TEST_CASE("pad6", "[fmt_helper]") test_pad6(12345, "012345"); test_pad6(123456, "123456"); } + + +TEST_CASE("pad9", "[fmt_helper]") +{ + test_pad9(0,"000000000"); + test_pad9(3, "000000003"); + test_pad9(23, "000000023"); + test_pad9(123, "000000123"); + test_pad9(1234, "000001234"); + test_pad9(12345, "000012345"); + test_pad9(123456, "000123456"); + test_pad9(1234567, "001234567"); + test_pad9(12345678, "012345678"); + test_pad9(123456789, "123456789"); + test_pad9(1234567891, "1234567891"); +} From 8a0fc92f207a4af5825d6231020e3c4ea8d3c08e Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 15 Nov 2018 16:42:42 +0200 Subject: [PATCH 02/83] Replaced SPDLOG_DISABLE_TID_CACHING with SPDLOG_NO_TLS --- include/spdlog/details/os.h | 4 ++-- include/spdlog/tweakme.h | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 23e011be..5e11da60 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -338,8 +338,7 @@ inline size_t _thread_id() SPDLOG_NOEXCEPT // Return current thread id as size_t (from thread local storage) inline size_t thread_id() SPDLOG_NOEXCEPT { -#if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) || \ - (defined(__clang__) && !__has_feature(cxx_thread_local)) +#if defined(SPDLOG_NO_TLS) return _thread_id(); #else // cache thread id in tls static thread_local const size_t tid = _thread_id(); @@ -384,6 +383,7 @@ inline int pid() #endif } + // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ inline bool is_color_terminal() SPDLOG_NOEXCEPT diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h index 0d77dadc..f76cd0c4 100644 --- a/include/spdlog/tweakme.h +++ b/include/spdlog/tweakme.h @@ -45,13 +45,12 @@ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -// Uncomment to prevent spdlog from caching thread ids in thread local storage. -// By default spdlog saves thread ids in tls to gain a few micros for each call. +// Uncomment to prevent spdlog from using thread local storage. // // WARNING: if your program forks, UNCOMMENT this flag to prevent undefined // thread ids in the children logs. // -// #define SPDLOG_DISABLE_TID_CACHING +// #define SPDLOG_NO_TLS /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// From b5224130854e2363c9e5e95f135e510df0eba6f5 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Nov 2018 10:07:31 +0200 Subject: [PATCH 03/83] Replaced SPDLOG_DISABLE_TID_CACHING with SPDLOG_NO_TLS --- include/spdlog/common.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 0ce54a9b..1c1da08b 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -41,6 +41,13 @@ #define SPDLOG_DEPRECATED #endif +// disable thread local on msvc 2013 +#ifndef SPDLOG_NO_TLS +#if (defined(_MSC_VER) && (_MSC_VER < 1900)) +#define SPDLOG_NO_TLS 1 +#endif +#endif + #include "spdlog/fmt/fmt.h" namespace spdlog { From 552416bda48408d8308c7b260549757f2d618ec9 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Nov 2018 12:55:19 +0200 Subject: [PATCH 04/83] fmt_helper cleanup --- include/spdlog/details/fmt_helper.h | 90 ++++++++-------------- include/spdlog/details/pattern_formatter.h | 4 +- 2 files changed, 36 insertions(+), 58 deletions(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index de6f998f..8632f01d 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -4,7 +4,8 @@ #pragma once -#include "chrono" +#include +#include #include "spdlog/fmt/fmt.h" // Some fmt helpers to efficiently format and pad ints and strings @@ -41,88 +42,65 @@ inline void append_int(T n, fmt::basic_memory_buffer &dest) dest.append(i.data(), i.data() + i.size()); } -template -inline void pad2(int n, fmt::basic_memory_buffer &dest) + + +template +inline void append_uint(T n, unsigned int width, fmt::basic_memory_buffer &dest) { - if (n > 99) - { - append_int(n, dest); - return; - } - if (n > 9) // 10-99 - { - dest.push_back(static_cast('0' + n / 10)); - dest.push_back(static_cast('0' + n % 10)); - return; - } - if (n >= 0) // 0-9 + static_assert(std::is_unsigned::value, "append_uint must get unsigned T"); + auto digits = fmt::internal::count_digits(n); + if(width > digits) { - dest.push_back('0'); - dest.push_back(static_cast('0' + n)); - return; + const char* zeroes = "0000000000000000000"; + dest.append(zeroes, zeroes + width-digits); } - // negatives (unlikely, but just in case, let fmt deal with it) - fmt::format_to(dest, "{:02}", n); + append_int(n, dest); } template -inline void pad3(int n, fmt::basic_memory_buffer &dest) +inline void pad2(int n, fmt::basic_memory_buffer &dest) { - if (n > 999) + if (n > 99) { append_int(n, dest); - return; - } - - if (n > 99) // 100-999 - { - dest.push_back(static_cast('0' + n / 100)); - pad2(n % 100, dest); - return; } - if (n > 9) // 10-99 + else if (n > 9) // 10-99 { - dest.push_back('0'); dest.push_back(static_cast('0' + n / 10)); dest.push_back(static_cast('0' + n % 10)); - return; } - if (n >= 0) + else if (n >= 0) // 0-9 { - dest.push_back('0'); dest.push_back('0'); dest.push_back(static_cast('0' + n)); - return; } - // negatives (unlikely, but just in case let fmt deal with it) - fmt::format_to(dest, "{:03}", n); + else // negatives (unlikely, but just in case, let fmt deal with it) + { + fmt::format_to(dest, "{:02}", n); + } } -template -inline void pad6(size_t n, fmt::basic_memory_buffer &dest) +template +inline void pad3(T n, fmt::basic_memory_buffer &dest) { - if (n > 99999) - { - append_int(n, dest); - return; - } - pad3(static_cast(n / 1000), dest); - pad3(static_cast(n % 1000), dest); + append_uint(n, 3, dest); } -template -inline void pad9(size_t n, fmt::basic_memory_buffer &dest) +template +inline void pad6(T n, fmt::basic_memory_buffer &dest) { - if (n > 99999999) - { - append_int(n, dest); - return; - } - pad6(static_cast(n / 1000), dest); - pad3(static_cast(n % 1000), dest); + append_uint(n, 6, dest); +} + +template +inline void pad9(T n, fmt::basic_memory_buffer &dest) +{ + append_uint(n, 9, dest); } + + // return fraction of a second of the given time_point. // e.g. // fraction(tp) -> will return the millis part of the second diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index a9b1a49c..ead3c4bf 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -452,7 +452,7 @@ public: scoped_pad p(field_size, padinfo_, dest); auto millis = fmt_helper::time_fraction(msg.time); - fmt_helper::pad3(static_cast(millis.count()), dest); + fmt_helper::pad3(static_cast(millis.count()), dest); } }; @@ -818,7 +818,7 @@ public: fmt_helper::append_buf(cached_datetime_, dest); auto millis = fmt_helper::time_fraction(msg.time); - fmt_helper::pad3(static_cast(millis.count()), dest); + fmt_helper::pad3(static_cast(millis.count()), dest); dest.push_back(']'); dest.push_back(' '); From b2735eb30ca01c0762f636c9a5a8fd9706002752 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Nov 2018 12:56:36 +0200 Subject: [PATCH 05/83] Fixed fmt_helper tests --- tests/test_fmt_helper.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/test_fmt_helper.cpp b/tests/test_fmt_helper.cpp index 9ebbcf73..97a61960 100644 --- a/tests/test_fmt_helper.cpp +++ b/tests/test_fmt_helper.cpp @@ -8,7 +8,7 @@ void test_pad2(int n, const char *expected) REQUIRE(fmt::to_string(buf) == expected); } -void test_pad3(int n, const char *expected) +void test_pad3(uint32_t n, const char *expected) { fmt::memory_buffer buf; spdlog::details::fmt_helper::pad3(n, buf); @@ -46,7 +46,6 @@ TEST_CASE("pad3", "[fmt_helper]") test_pad3(23, "023"); test_pad3(123, "123"); test_pad3(1234, "1234"); - test_pad3(-5, "-05"); } TEST_CASE("pad6", "[fmt_helper]") @@ -60,10 +59,9 @@ TEST_CASE("pad6", "[fmt_helper]") test_pad6(123456, "123456"); } - TEST_CASE("pad9", "[fmt_helper]") { - test_pad9(0,"000000000"); + test_pad9(0, "000000000"); test_pad9(3, "000000003"); test_pad9(23, "000000023"); test_pad9(123, "000000123"); From 3bfcb0468ebc391f9fc1f818f23c35753270cd07 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Nov 2018 12:56:57 +0200 Subject: [PATCH 06/83] clang-format --- tests/test_pattern_formatter.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/test_pattern_formatter.cpp b/tests/test_pattern_formatter.cpp index 0aa209ed..fb6f75da 100644 --- a/tests/test_pattern_formatter.cpp +++ b/tests/test_pattern_formatter.cpp @@ -16,7 +16,6 @@ static std::string log_to_str(const std::string &msg, const Args &... args) return oss.str(); } - TEST_CASE("custom eol", "[pattern_formatter]") { std::string msg = "Hello custom eol test"; @@ -208,7 +207,7 @@ TEST_CASE("clone-default-formatter", "[pattern_formatter]") formatter_1->format(msg, formatted_1); formatter_2->format(msg, formatted_2); - REQUIRE( fmt::to_string(formatted_1) == fmt::to_string(formatted_2)); + REQUIRE(fmt::to_string(formatted_1) == fmt::to_string(formatted_2)); } TEST_CASE("clone-default-formatter2", "[pattern_formatter]") @@ -223,7 +222,7 @@ TEST_CASE("clone-default-formatter2", "[pattern_formatter]") formatter_1->format(msg, formatted_1); formatter_2->format(msg, formatted_2); - REQUIRE( fmt::to_string(formatted_1) == fmt::to_string(formatted_2)); + REQUIRE(fmt::to_string(formatted_1) == fmt::to_string(formatted_2)); } TEST_CASE("clone-formatter", "[pattern_formatter]") @@ -240,7 +239,6 @@ TEST_CASE("clone-formatter", "[pattern_formatter]") REQUIRE(fmt::to_string(formatted_1) == fmt::to_string(formatted_2)); } - TEST_CASE("clone-formatter-2", "[pattern_formatter]") { using spdlog::pattern_time_type; From 7068c45115c961b93f610c3bcadfbb5343a70001 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Nov 2018 13:28:34 +0200 Subject: [PATCH 07/83] Fixed issue #908 --- include/spdlog/details/fmt_helper.h | 35 +++++++++++----------- include/spdlog/details/pattern_formatter.h | 9 +++--- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index 8632f01d..63c94c7b 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -43,20 +43,6 @@ inline void append_int(T n, fmt::basic_memory_buffer &dest) } - -template -inline void append_uint(T n, unsigned int width, fmt::basic_memory_buffer &dest) -{ - static_assert(std::is_unsigned::value, "append_uint must get unsigned T"); - auto digits = fmt::internal::count_digits(n); - if(width > digits) - { - const char* zeroes = "0000000000000000000"; - dest.append(zeroes, zeroes + width-digits); - } - append_int(n, dest); -} - template inline void pad2(int n, fmt::basic_memory_buffer &dest) { @@ -80,23 +66,38 @@ inline void pad2(int n, fmt::basic_memory_buffer &dest) } } + + +template +inline void pad_uint(T n, unsigned int width, fmt::basic_memory_buffer &dest) +{ + static_assert(std::is_unsigned::value, "append_uint must get unsigned T"); + auto digits = fmt::internal::count_digits(n); + if(width > digits) + { + const char* zeroes = "0000000000000000000"; + dest.append(zeroes, zeroes + width-digits); + } + append_int(n, dest); +} + template inline void pad3(T n, fmt::basic_memory_buffer &dest) { - append_uint(n, 3, dest); + pad_uint(n, 3, dest); } template inline void pad6(T n, fmt::basic_memory_buffer &dest) { - append_uint(n, 6, dest); + pad_uint(n, 6, dest); } template inline void pad9(T n, fmt::basic_memory_buffer &dest) { - append_uint(n, 9, dest); + pad_uint(n, 9, dest); } diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index ead3c4bf..925b23bc 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -653,9 +653,9 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - const size_t field_size = 6; + const size_t field_size = fmt::internal::count_digits(msg.thread_id); scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad6(msg.thread_id, dest); + fmt_helper::append_int(msg.thread_id, dest); } }; @@ -668,9 +668,10 @@ public: void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override { - const size_t field_size = 6; + const auto pid = static_cast(details::os::pid()); + const size_t field_size = fmt::internal::count_digits(pid); scoped_pad p(field_size, padinfo_, dest); - fmt_helper::pad6(static_cast(details::os::pid()), dest); + fmt_helper::append_int(pid, dest); } }; From e601ebe19b8afe8198f8df4e6c2523bbdd23a196 Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 16 Nov 2018 14:13:29 +0200 Subject: [PATCH 08/83] Updated formatter-bench --- bench/formatter-bench.cpp | 43 ++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index 11ec2a31..e484041b 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -50,9 +50,17 @@ void bench_formatters() for(auto &flag:all_flags) { auto pattern = std::string("%") + flag; - benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern)->Iterations(2500000); + benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); + //bench left padding + pattern = std::string("%16") + flag; + benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); + + //bench center padding + pattern = std::string("%=16") + flag; + benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); } + // complex patterns std::vector patterns = { "[%D %X] [%l] [%n] %v", @@ -65,34 +73,19 @@ void bench_formatters() } } -void bench_padders() + +int main(int argc, char *argv[]) { - using spdlog::details::padding_info; - std::vector sizes = {0, 2, 4, 8, 16, 32, 64, 128}; - for (auto size : sizes) + if(argc > 1) //bench given pattern { - size_t wrapped_size = 8; - size_t padding_size = wrapped_size + size; - - std::string title = "scoped_pad::left::" + std::to_string(size); - - benchmark::RegisterBenchmark(title.c_str(), bench_scoped_pad, wrapped_size, padding_info(padding_size, padding_info::left)); - - title = "scoped_pad::right::" + std::to_string(size); - benchmark::RegisterBenchmark(title.c_str(), bench_scoped_pad, wrapped_size, padding_info(padding_size, padding_info::right)); - - title = "scoped_pad::center::" + std::to_string(size); - benchmark::RegisterBenchmark(title.c_str(), bench_scoped_pad, wrapped_size, padding_info(padding_size, padding_info::center)); + std::string pattern = argv[1]; + benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); + } + else //bench all flags + { + bench_formatters(); } -} - - - -int main(int argc, char *argv[]) -{ - bench_formatters(); - //bench_padders(); benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); } From 14a071c4786f1714543df5249abe394da8c54fc1 Mon Sep 17 00:00:00 2001 From: Daniel Chabrowski Date: Mon, 19 Nov 2018 02:29:36 +0100 Subject: [PATCH 09/83] Fix osx build --- include/spdlog/details/fmt_helper.h | 16 +++++----------- include/spdlog/details/pattern_formatter.h | 3 +-- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index 63c94c7b..c8db3109 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -42,7 +42,6 @@ inline void append_int(T n, fmt::basic_memory_buffer &dest) dest.append(i.data(), i.data() + i.size()); } - template inline void pad2(int n, fmt::basic_memory_buffer &dest) { @@ -60,23 +59,21 @@ inline void pad2(int n, fmt::basic_memory_buffer &dest) dest.push_back('0'); dest.push_back(static_cast('0' + n)); } - else // negatives (unlikely, but just in case, let fmt deal with it) + else // negatives (unlikely, but just in case, let fmt deal with it) { fmt::format_to(dest, "{:02}", n); } } - - template inline void pad_uint(T n, unsigned int width, fmt::basic_memory_buffer &dest) { static_assert(std::is_unsigned::value, "append_uint must get unsigned T"); - auto digits = fmt::internal::count_digits(n); - if(width > digits) + auto digits = fmt::internal::count_digits(static_cast(n)); + if (width > digits) { - const char* zeroes = "0000000000000000000"; - dest.append(zeroes, zeroes + width-digits); + const char *zeroes = "0000000000000000000"; + dest.append(zeroes, zeroes + width - digits); } append_int(n, dest); } @@ -87,7 +84,6 @@ inline void pad3(T n, fmt::basic_memory_buffer &dest) pad_uint(n, 3, dest); } - template inline void pad6(T n, fmt::basic_memory_buffer &dest) { @@ -100,8 +96,6 @@ inline void pad9(T n, fmt::basic_memory_buffer &dest) pad_uint(n, 9, dest); } - - // return fraction of a second of the given time_point. // e.g. // fraction(tp) -> will return the millis part of the second diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 925b23bc..bbc07b3a 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -487,7 +487,6 @@ public: auto ns = fmt_helper::time_fraction(msg.time); fmt_helper::pad9(static_cast(ns.count()), dest); - } }; @@ -653,7 +652,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - const size_t field_size = fmt::internal::count_digits(msg.thread_id); + const auto field_size = fmt::internal::count_digits(static_cast(msg.thread_id)); scoped_pad p(field_size, padinfo_, dest); fmt_helper::append_int(msg.thread_id, dest); } From f09d0f230163c6e09a8d83d0bbe94ac7162cc9ed Mon Sep 17 00:00:00 2001 From: Daniel Chabrowski Date: Mon, 19 Nov 2018 17:15:39 +0100 Subject: [PATCH 10/83] Add helper for count_digits --- include/spdlog/details/fmt_helper.h | 10 +++++++++- include/spdlog/details/pattern_formatter.h | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index c8db3109..f786c4ee 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -18,6 +18,7 @@ inline spdlog::string_view_t to_string_view(const fmt::basic_memory_buffer inline void append_buf(const fmt::basic_memory_buffer &buf, fmt::basic_memory_buffer &dest) { @@ -42,6 +43,13 @@ inline void append_int(T n, fmt::basic_memory_buffer &dest) dest.append(i.data(), i.data() + i.size()); } +template +inline unsigned count_digits(T n) +{ + using count_type = std::conditional<(sizeof(std::size_t) > sizeof(std::uint32_t)), std::uint64_t, std::uint32_t>::type; + return fmt::internal::count_digits(static_cast(n)); +} + template inline void pad2(int n, fmt::basic_memory_buffer &dest) { @@ -69,7 +77,7 @@ template inline void pad_uint(T n, unsigned int width, fmt::basic_memory_buffer &dest) { static_assert(std::is_unsigned::value, "append_uint must get unsigned T"); - auto digits = fmt::internal::count_digits(static_cast(n)); + auto digits = count_digits(n); if (width > digits) { const char *zeroes = "0000000000000000000"; diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index bbc07b3a..a51b2132 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -652,7 +652,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - const auto field_size = fmt::internal::count_digits(static_cast(msg.thread_id)); + const auto field_size = fmt_helper::count_digits(msg.thread_id); scoped_pad p(field_size, padinfo_, dest); fmt_helper::append_int(msg.thread_id, dest); } From 6232ec78f79a7c426789bb9b35a6c7b4cfa51ce5 Mon Sep 17 00:00:00 2001 From: Daniel Chabrowski Date: Mon, 19 Nov 2018 18:34:52 +0100 Subject: [PATCH 11/83] Change count_digits to depend on template param, not size_t --- include/spdlog/details/fmt_helper.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index f786c4ee..fb9946a4 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -46,7 +46,7 @@ inline void append_int(T n, fmt::basic_memory_buffer &dest) template inline unsigned count_digits(T n) { - using count_type = std::conditional<(sizeof(std::size_t) > sizeof(std::uint32_t)), std::uint64_t, std::uint32_t>::type; + using count_type = std::conditional<(sizeof(T) > sizeof(std::uint32_t)), std::uint64_t, std::uint32_t>::type; return fmt::internal::count_digits(static_cast(n)); } From e751461ff1be9b977d39d92b785733121bf0ef41 Mon Sep 17 00:00:00 2001 From: Daniel Chabrowski Date: Mon, 19 Nov 2018 18:59:17 +0100 Subject: [PATCH 12/83] Fix template error --- include/spdlog/details/fmt_helper.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index fb9946a4..afc76b25 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -46,7 +46,7 @@ inline void append_int(T n, fmt::basic_memory_buffer &dest) template inline unsigned count_digits(T n) { - using count_type = std::conditional<(sizeof(T) > sizeof(std::uint32_t)), std::uint64_t, std::uint32_t>::type; + using count_type = typename std::conditional<(sizeof(T) > sizeof(std::uint32_t)), std::uint64_t, std::uint32_t>::type; return fmt::internal::count_digits(static_cast(n)); } From b64e4464a77caca658982b8fe919db05c4f29f36 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Tue, 20 Nov 2018 10:26:10 +0200 Subject: [PATCH 13/83] Update current_size_ to 0 in after of truncating in rotation error --- include/spdlog/sinks/rotating_file_sink.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index 14fd0bb6..ef210d83 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -105,6 +105,7 @@ private: if (!rename_file(src, target)) { file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit! + current_size_ = 0; throw spdlog_ex( "rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno); } From 52e2722412c08d72a2dca5153fd222e53c7b96f3 Mon Sep 17 00:00:00 2001 From: gabime Date: Tue, 20 Nov 2018 12:14:21 +0200 Subject: [PATCH 14/83] Renamed test filenames --- tests/CMakeLists.txt | 4 +- tests/file_log.cpp | 173 -------------------------- tests/{errors.cpp => test_errors.cpp} | 0 3 files changed, 2 insertions(+), 175 deletions(-) delete mode 100644 tests/file_log.cpp rename tests/{errors.cpp => test_errors.cpp} (100%) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ea9ffb35..1fb93c8e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -3,9 +3,9 @@ project(spdlog-utests CXX) find_package(Threads REQUIRED) set(SPDLOG_UTESTS_SOURCES - errors.cpp + test_errors.cpp file_helper.cpp - file_log.cpp + test_file_logging.cpp test_misc.cpp test_pattern_formatter.cpp test_async.cpp diff --git a/tests/file_log.cpp b/tests/file_log.cpp deleted file mode 100644 index c5886f5f..00000000 --- a/tests/file_log.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* - * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE - */ -#include "includes.h" - -TEST_CASE("simple_file_logger", "[simple_logger]]") -{ - prepare_logdir(); - std::string filename = "logs/simple_log"; - - auto logger = spdlog::create("logger", filename); - logger->set_pattern("%v"); - - logger->info("Test message {}", 1); - logger->info("Test message {}", 2); - - logger->flush(); - REQUIRE(file_contents(filename) == std::string("Test message 1\nTest message 2\n")); - REQUIRE(count_lines(filename) == 2); -} - -TEST_CASE("flush_on", "[flush_on]]") -{ - prepare_logdir(); - std::string filename = "logs/simple_log"; - - auto logger = spdlog::create("logger", filename); - logger->set_pattern("%v"); - logger->set_level(spdlog::level::trace); - logger->flush_on(spdlog::level::info); - logger->trace("Should not be flushed"); - REQUIRE(count_lines(filename) == 0); - - logger->info("Test message {}", 1); - logger->info("Test message {}", 2); - - REQUIRE(file_contents(filename) == std::string("Should not be flushed\nTest message 1\nTest message 2\n")); - REQUIRE(count_lines(filename) == 3); -} - -TEST_CASE("rotating_file_logger1", "[rotating_logger]]") -{ - prepare_logdir(); - size_t max_size = 1024 * 10; - std::string basename = "logs/rotating_log"; - auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 0); - - for (int i = 0; i < 10; ++i) - { - logger->info("Test message {}", i); - } - - logger->flush(); - auto filename = basename; - REQUIRE(count_lines(filename) == 10); -} - -TEST_CASE("rotating_file_logger2", "[rotating_logger]]") -{ - prepare_logdir(); - size_t max_size = 1024 * 10; - std::string basename = "logs/rotating_log"; - auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 1); - for (int i = 0; i < 10; ++i) - { - logger->info("Test message {}", i); - } - - logger->flush(); - auto filename = basename; - REQUIRE(count_lines(filename) == 10); - for (int i = 0; i < 1000; i++) - { - - logger->info("Test message {}", i); - } - - logger->flush(); - REQUIRE(get_filesize(filename) <= max_size); - auto filename1 = basename + ".1"; - REQUIRE(get_filesize(filename1) <= max_size); -} - -TEST_CASE("daily_logger with dateonly calculator", "[daily_logger_dateonly]]") -{ - using sink_type = spdlog::sinks::daily_file_sink; - - prepare_logdir(); - // calculate filename (time based) - std::string basename = "logs/daily_dateonly"; - std::tm tm = spdlog::details::os::localtime(); - fmt::memory_buffer w; - fmt::format_to(w, "{}_{:04d}-{:02d}-{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); - - auto logger = spdlog::create("logger", basename, 0, 0); - for (int i = 0; i < 10; ++i) - { - - logger->info("Test message {}", i); - } - logger->flush(); - auto filename = fmt::to_string(w); - REQUIRE(count_lines(filename) == 10); -} - -struct custom_daily_file_name_calculator -{ - static spdlog::filename_t calc_filename(const spdlog::filename_t &basename, const tm &now_tm) - { - fmt::memory_buffer w; - fmt::format_to(w, "{}{:04d}{:02d}{:02d}", basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday); - return fmt::to_string(w); - } -}; - -TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") -{ - using sink_type = spdlog::sinks::daily_file_sink; - - prepare_logdir(); - // calculate filename (time based) - std::string basename = "logs/daily_dateonly"; - std::tm tm = spdlog::details::os::localtime(); - fmt::memory_buffer w; - fmt::format_to(w, "{}{:04d}{:02d}{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); - - auto logger = spdlog::create("logger", basename, 0, 0); - for (int i = 0; i < 10; ++i) - { - logger->info("Test message {}", i); - } - - logger->flush(); - auto filename = fmt::to_string(w); - REQUIRE(count_lines(filename) == 10); -} - -/* - * File name calculations - */ - -TEST_CASE("rotating_file_sink::calc_filename1", "[rotating_file_sink]]") -{ - auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename("rotated.txt", 3); - REQUIRE(filename == "rotated.3.txt"); -} - -TEST_CASE("rotating_file_sink::calc_filename2", "[rotating_file_sink]]") -{ - auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename("rotated", 3); - REQUIRE(filename == "rotated.3"); -} - -TEST_CASE("rotating_file_sink::calc_filename3", "[rotating_file_sink]]") -{ - auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename("rotated.txt", 0); - REQUIRE(filename == "rotated.txt"); -} - -// regex supported only from gcc 4.9 and above -#if defined(_MSC_VER) || !(__GNUC__ <= 4 && __GNUC_MINOR__ < 9) -#include - -TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]]") -{ - // daily_YYYY-MM-DD_hh-mm.txt - auto filename = spdlog::sinks::daily_filename_calculator::calc_filename("daily.txt", spdlog::details::os::localtime()); - // date regex based on https://www.regular-expressions.info/dates.html - std::regex re(R"(^daily_(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\.txt$)"); - std::smatch match; - REQUIRE(std::regex_match(filename, match, re)); -} -#endif diff --git a/tests/errors.cpp b/tests/test_errors.cpp similarity index 100% rename from tests/errors.cpp rename to tests/test_errors.cpp From fb1a3a3a121ade2da2f6b23ce75f8dd306115972 Mon Sep 17 00:00:00 2001 From: gabime Date: Tue, 20 Nov 2018 15:40:51 +0200 Subject: [PATCH 15/83] Micro optimized some formatter flags --- include/spdlog/details/pattern_formatter.h | 68 ++++++++++++++++------ 1 file changed, 50 insertions(+), 18 deletions(-) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index a51b2132..7c841030 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -448,11 +448,17 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - const size_t field_size = 3; - scoped_pad p(field_size, padinfo_, dest); - auto millis = fmt_helper::time_fraction(msg.time); - fmt_helper::pad3(static_cast(millis.count()), dest); + if (padinfo_.width_) + { + const size_t field_size = 3; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad3(static_cast(millis.count()), dest); + } + else + { + fmt_helper::pad3(static_cast(millis.count()), dest); + } } }; @@ -465,11 +471,17 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - const size_t field_size = 6; - scoped_pad p(field_size, padinfo_, dest); - auto micros = fmt_helper::time_fraction(msg.time); - fmt_helper::pad6(static_cast(micros.count()), dest); + if (padinfo_.width_) + { + const size_t field_size = 6; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad6(static_cast(micros.count()), dest); + } + else + { + fmt_helper::pad6(static_cast(micros.count()), dest); + } } }; @@ -482,11 +494,17 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - const size_t field_size = 9; - scoped_pad p(field_size, padinfo_, dest); - auto ns = fmt_helper::time_fraction(msg.time); - fmt_helper::pad9(static_cast(ns.count()), dest); + if (padinfo_.width_) + { + const size_t field_size = 9; + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::pad9(static_cast(ns.count()), dest); + } + else + { + fmt_helper::pad9(static_cast(ns.count()), dest); + } } }; @@ -652,9 +670,16 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - const auto field_size = fmt_helper::count_digits(msg.thread_id); - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::append_int(msg.thread_id, dest); + if (padinfo_.width_) + { + const auto field_size = fmt_helper::count_digits(msg.thread_id); + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_int(msg.thread_id, dest); + } + else + { + fmt_helper::append_int(msg.thread_id, dest); + } } }; @@ -668,9 +693,16 @@ public: void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override { const auto pid = static_cast(details::os::pid()); - const size_t field_size = fmt::internal::count_digits(pid); - scoped_pad p(field_size, padinfo_, dest); - fmt_helper::append_int(pid, dest); + if (padinfo_.width_) + { + const size_t field_size = fmt::internal::count_digits(pid); + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_int(pid, dest); + } + else + { + fmt_helper::append_int(pid, dest); + } } }; From 0a8cce698439370d322c9a20b3ac9c6ddd7278bc Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 21 Nov 2018 14:21:26 +0200 Subject: [PATCH 16/83] comments --- include/spdlog/spdlog.h | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 200cbd1d..0b6a564a 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -291,9 +291,18 @@ inline void critical(const wchar_t *fmt, const Args &... args) #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT // -// compile time macros. -// can be enabled/disabled using SPDLOG_ACTIVE_LEVEL (info by default). +// enable/disable log calls at compile time according to global level. // +// define SPDLOG_ACTIVE_LEVEL to one of those (before including spdlog.h): +// SPDLOG_LEVEL_TRACE, +// SPDLOG_LEVEL_DEBUG, +// SPDLOG_LEVEL_INFO, +// SPDLOG_LEVEL_WARN, +// SPDLOG_LEVEL_ERROR, +// SPDLOG_LEVEL_CRITICAL, +// SPDLOG_LEVEL_OFF +// + #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE #define SPDLOG_LOGGER_TRACE(logger, ...) logger->trace(__VA_ARGS__) From 70d03fd9c3b88c052a2fef6b84b3381180ba75c3 Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 21 Nov 2018 16:01:28 +0200 Subject: [PATCH 17/83] Minor optimization --- include/spdlog/details/pattern_formatter.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 7c841030..d6a723ae 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -729,8 +729,14 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - scoped_pad p(msg.payload, padinfo_, dest); - fmt_helper::append_string_view(msg.payload, dest); + if(padinfo_.width_) { + scoped_pad p(msg.payload, padinfo_, dest); + fmt_helper::append_string_view(msg.payload, dest); + } + else + { + fmt_helper::append_string_view(msg.payload, dest); + } } }; From 50648553cfb5c01775d32ca5bd19fe3e2fbd7a0c Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 21 Nov 2018 16:02:02 +0200 Subject: [PATCH 18/83] clang-format --- bench/formatter-bench.cpp | 29 +++++++++------------- include/spdlog/details/os.h | 1 - include/spdlog/details/pattern_formatter.h | 3 ++- include/spdlog/spdlog.h | 1 - 4 files changed, 14 insertions(+), 20 deletions(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index e484041b..ccdc9fb1 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -21,18 +21,16 @@ void bench_scoped_pad(benchmark::State &state, size_t wrapped_size, spdlog::deta } } - void bench_formatter(benchmark::State &state, std::string pattern) { auto formatter = spdlog::details::make_unique(pattern); fmt::memory_buffer dest; std::string logger_name = "logger-name"; - const char* text = "Hello. This is some message with length of 80 "; - + const char *text = "Hello. This is some message with length of 80 "; spdlog::details::log_msg msg(&logger_name, spdlog::level::info, text); -// formatter->format(msg, dest); -// printf("%s\n", fmt::to_string(dest).c_str()); + // formatter->format(msg, dest); + // printf("%s\n", fmt::to_string(dest).c_str()); for (auto _ : state) { @@ -47,46 +45,43 @@ void bench_formatters() // basic patterns(single flag) std::string all_flags = "+vtPnlLaAbBcCYDmdHIMSefFprRTXzEi%"; std::vector basic_patterns; - for(auto &flag:all_flags) + for (auto &flag : all_flags) { auto pattern = std::string("%") + flag; benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); - //bench left padding + // bench left padding pattern = std::string("%16") + flag; benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); - //bench center padding + // bench center padding pattern = std::string("%=16") + flag; benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); } - // complex patterns std::vector patterns = { - "[%D %X] [%l] [%n] %v", - "[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] %v", - "[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] [%t] %v", + "[%D %X] [%l] [%n] %v", + "[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] %v", + "[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] [%t] %v", }; - for(auto &pattern:patterns) + for (auto &pattern : patterns) { benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern)->Iterations(2500000); } } - int main(int argc, char *argv[]) { - if(argc > 1) //bench given pattern + if (argc > 1) // bench given pattern { std::string pattern = argv[1]; benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); } - else //bench all flags + else // bench all flags { bench_formatters(); } benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); } - diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 5e11da60..f2422904 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -383,7 +383,6 @@ inline int pid() #endif } - // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ inline bool is_color_terminal() SPDLOG_NOEXCEPT diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index d6a723ae..5d71ecf0 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -729,7 +729,8 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - if(padinfo_.width_) { + if (padinfo_.width_) + { scoped_pad p(msg.payload, padinfo_, dest); fmt_helper::append_string_view(msg.payload, dest); } diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 0b6a564a..c314c07b 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -303,7 +303,6 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // - #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE #define SPDLOG_LOGGER_TRACE(logger, ...) logger->trace(__VA_ARGS__) #define SPDLOG_TRACE(...) spdlog::trace(__VA_ARGS__) From 3fa76b2d8fc70c5e06df37b69abd135ccf9eda3a Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 12:31:16 +0200 Subject: [PATCH 19/83] Renamed test filename --- tests/CMakeLists.txt | 2 +- tests/{file_helper.cpp => test_file_helper.cpp} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename tests/{file_helper.cpp => test_file_helper.cpp} (100%) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1fb93c8e..48f80e0e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -4,7 +4,7 @@ find_package(Threads REQUIRED) set(SPDLOG_UTESTS_SOURCES test_errors.cpp - file_helper.cpp + test_file_helper.cpp test_file_logging.cpp test_misc.cpp test_pattern_formatter.cpp diff --git a/tests/file_helper.cpp b/tests/test_file_helper.cpp similarity index 100% rename from tests/file_helper.cpp rename to tests/test_file_helper.cpp From 3a8f9484d2d872b39cbaf466c4721762a382b504 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 16:58:20 +0200 Subject: [PATCH 20/83] Cleaned bench.cpp a little --- bench/bench.cpp | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/bench/bench.cpp b/bench/bench.cpp index 756b04a2..814851f7 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -67,23 +67,9 @@ int main(int argc, char *argv[]) bench(howmany, spdlog::create("null_st")); - spdlog::info("**************************************************************"); - spdlog::info("Default API. Single thread, {:n} iterations", howmany); - spdlog::info("**************************************************************"); - - basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true); - bench_default_api(howmany, std::move(basic_st)); - - rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); - bench_default_api(howmany, std::move(rotating_st)); - - daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log"); - bench_default_api(howmany, std::move(daily_st)); - - bench_default_api(howmany, spdlog::create("null_st")); spdlog::info("**************************************************************"); - spdlog::info("C-string (500 bytes). Single thread, {:n} iterations", howmany); + spdlog::info("C-string (400 bytes). Single thread, {:n} iterations", howmany); spdlog::info("**************************************************************"); basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_cs.log", true); From 216cd6935fb39f98abeeb77e9bf46d83557d002f Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 17:05:27 +0200 Subject: [PATCH 21/83] Updated formatter-bench to include source location --- bench/formatter-bench.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index ccdc9fb1..c42ba503 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -28,7 +28,7 @@ void bench_formatter(benchmark::State &state, std::string pattern) std::string logger_name = "logger-name"; const char *text = "Hello. This is some message with length of 80 "; - spdlog::details::log_msg msg(&logger_name, spdlog::level::info, text); + spdlog::details::log_msg msg(spdlog::source_loc{__FILE__, __LINE__}, &logger_name, spdlog::level::info, text); // formatter->format(msg, dest); // printf("%s\n", fmt::to_string(dest).c_str()); From f2305fe5bfb7dbadec37ef350f15cbceba2c4645 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 18:47:50 +0200 Subject: [PATCH 22/83] Support for source file/line logging --- include/spdlog/common.h | 9 +++ include/spdlog/details/log_msg.h | 7 +- include/spdlog/details/logger_impl.h | 51 ++++++++++++--- include/spdlog/details/pattern_formatter.h | 74 ++++++++++++++++++++++ include/spdlog/logger.h | 16 +++++ include/spdlog/spdlog.h | 35 ++++++---- 6 files changed, 168 insertions(+), 24 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 1c1da08b..ee4bc249 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -185,6 +185,15 @@ using filename_t = std::wstring; using filename_t = std::string; #endif + +struct source_loc +{ + SPDLOG_CONSTEXPR source_loc(): filename(""), line(0) {} + SPDLOG_CONSTEXPR source_loc(const char *filename, int line) : filename(filename), line(line) {} + const char* const filename ; + const uint32_t line; +}; + namespace details { // make_unique support for pre c++14 diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 6244f3a9..56f4729a 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -16,7 +16,7 @@ namespace details { struct log_msg { - log_msg(const std::string *loggers_name, level::level_enum lvl, string_view_t view) + log_msg(source_loc loc, const std::string *loggers_name, level::level_enum lvl, string_view_t view) : logger_name(loggers_name) , level(lvl) #ifndef SPDLOG_NO_DATETIME @@ -25,11 +25,15 @@ struct log_msg #ifndef SPDLOG_NO_THREAD_ID , thread_id(os::thread_id()) + , source(loc) , payload(view) #endif { } + log_msg(const std::string *loggers_name, level::level_enum lvl, string_view_t view): + log_msg(source_loc{}, loggers_name, lvl, view){} + log_msg(const log_msg &other) = default; log_msg &operator=(const log_msg &other) = default; @@ -43,6 +47,7 @@ struct log_msg mutable size_t color_range_start{0}; mutable size_t color_range_end{0}; + source_loc source; const string_view_t payload; }; } // namespace details diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index efe6a66a..de2f76ff 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -57,8 +57,9 @@ inline void spdlog::logger::set_pattern(std::string pattern, pattern_time_type t set_formatter(std::move(new_formatter)); } + template -inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) +inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -70,13 +71,20 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Ar using details::fmt_helper::to_string_view; fmt::memory_buffer buf; fmt::format_to(buf, fmt, args...); - details::log_msg log_msg(&name_, lvl, to_string_view(buf)); + details::log_msg log_msg(source, &name_, lvl, to_string_view(buf)); sink_it_(log_msg); } SPDLOG_CATCH_AND_HANDLE } -inline void spdlog::logger::log(level::level_enum lvl, const char *msg) + +template +inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) +{ + log(source_loc{}, lvl, fmt, args...); +} + +inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *msg) { if (!should_log(lvl)) { @@ -85,14 +93,19 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *msg) try { - details::log_msg log_msg(&name_, lvl, spdlog::string_view_t(msg)); + details::log_msg log_msg(source, &name_, lvl, spdlog::string_view_t(msg)); sink_it_(log_msg); } SPDLOG_CATCH_AND_HANDLE } +inline void spdlog::logger::log(level::level_enum lvl, const char *msg) +{ + log(source_loc{}, lvl, msg); +} + template::value, T>::type *> -inline void spdlog::logger::log(level::level_enum lvl, const T &msg) +inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const T &msg) { if (!should_log(lvl)) { @@ -100,14 +113,20 @@ inline void spdlog::logger::log(level::level_enum lvl, const T &msg) } try { - details::log_msg log_msg(&name_, lvl, msg); + details::log_msg log_msg(source, &name_, lvl, msg); sink_it_(log_msg); } SPDLOG_CATCH_AND_HANDLE } -template::value, T>::type *> +template::value, T>::type *> inline void spdlog::logger::log(level::level_enum lvl, const T &msg) +{ + log(source_loc{}, lvl, msg); +} + +template::value, T>::type *> +inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const T &msg) { if (!should_log(lvl)) { @@ -118,12 +137,18 @@ inline void spdlog::logger::log(level::level_enum lvl, const T &msg) using details::fmt_helper::to_string_view; fmt::memory_buffer buf; fmt::format_to(buf, "{}", msg); - details::log_msg log_msg(&name_, lvl, to_string_view(buf)); + details::log_msg log_msg(source, &name_, lvl, to_string_view(buf)); sink_it_(log_msg); } SPDLOG_CATCH_AND_HANDLE } +template::value, T>::type *> +inline void spdlog::logger::log(level::level_enum lvl, const T &msg) +{ + log(source_loc{}, lvl, msg); +} + template inline void spdlog::logger::trace(const char *fmt, const Args &... args) { @@ -220,7 +245,7 @@ inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer } template -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) +inline void spdlog::logger::log(source_location source, level::level_enum lvl, const wchar_t *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -235,12 +260,18 @@ inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const fmt::format_to(wbuf, fmt, args...); fmt::memory_buffer buf; wbuf_to_utf8buf(wbuf, buf); - details::log_msg log_msg(&name_, lvl, to_string_view(buf)); + details::log_msg log_msg(source, &name_, lvl, to_string_view(buf)); sink_it_(log_msg); } SPDLOG_CATCH_AND_HANDLE } +template +inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) +{ + log(source_location{}, lvl, fmt, args...); +} + template inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) { diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 5d71ecf0..044006c5 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -808,6 +808,68 @@ public: } }; +// print soruce location +class source_location_formatter final : public flag_formatter +{ +public: + explicit source_location_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + +void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override +{ + if(padinfo_.width_) + { + const auto text_size = std::char_traits::length(msg.source.filename) + + fmt_helper::count_digits(msg.source.line) + +1; + scoped_pad p(text_size, padinfo_, dest); + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + } + else + { + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + } +} +}; +// print soruce filename +class source_filename_formatter final : public flag_formatter +{ +public: + explicit source_filename_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + scoped_pad p(msg.source.filename, padinfo_, dest); + fmt_helper::append_string_view(msg.source.filename, dest); + } +}; + +class source_linenum_formatter final : public flag_formatter +{ +public: + explicit source_linenum_formatter(padding_info padinfo) + : flag_formatter(padinfo){}; + + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override + { + + if(padinfo_.width_) { + const size_t field_size = fmt::internal::count_digits(msg.source.line); + scoped_pad p(field_size, padinfo_, dest); + fmt_helper::append_int(msg.source.line, dest); + } + else + { + fmt_helper::append_int(msg.source.line, dest); + } + } +}; + // Full info formatter // pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v class full_formatter final : public flag_formatter @@ -1102,6 +1164,18 @@ private: formatters_.push_back(details::make_unique(padding)); break; + case ('@'): + formatters_.push_back(details::make_unique(padding)); + break; + + case ('s'): + formatters_.push_back(details::make_unique(padding)); + break; + + case ('#'): + formatters_.push_back(details::make_unique(padding)); + break; + case ('%'): formatters_.push_back(details::make_unique('%')); break; diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index d1da624f..640895a3 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -46,8 +46,13 @@ public: template void log(level::level_enum lvl, const char *fmt, const Args &... args); + template + void log(source_loc loc, level::level_enum lvl, const char *fmt, const Args &... args); + void log(level::level_enum lvl, const char *msg); + void log(source_loc loc, level::level_enum lvl, const char *msg); + template void trace(const char *fmt, const Args &... args); @@ -73,6 +78,9 @@ public: template void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); + template + void log(source_location soruce, level::level_enum lvl, const wchar_t *fmt, const Args &... args); + template void trace(const wchar_t *fmt, const Args &... args); @@ -97,10 +105,18 @@ public: template::value, T>::type * = nullptr> void log(level::level_enum lvl, const T &); + // T can be statically converted to string_view + template::value, T>::type * = nullptr> + void log(source_loc loc, level::level_enum lvl, const T &); + // T cannot be statically converted to string_view template::value, T>::type * = nullptr> void log(level::level_enum lvl, const T &); + // T cannot be statically converted to string_view + template::value, T>::type * = nullptr> + void log(source_loc loc, level::level_enum lvl, const T &); + template void trace(const T &msg); diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index c314c07b..64a53fbe 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -161,10 +161,16 @@ inline void set_default_logger(std::shared_ptr default_logger) details::registry::instance().set_default_logger(std::move(default_logger)); } +template +inline void log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args) +{ + default_logger_raw()->log(source, lvl, fmt, args...); +} + template inline void log(level::level_enum lvl, const char *fmt, const Args &... args) { - default_logger_raw()->log(lvl, fmt, args...); + default_logger_raw()->log(source_loc{}, lvl, fmt, args...); } template @@ -303,49 +309,52 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // + +#define SPDLOG_LOGGER_LOG(logger, level, ...) logger->log(spdlog::source_loc{__FILE__, __LINE__}, level, __VA_ARGS__) + #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE -#define SPDLOG_LOGGER_TRACE(logger, ...) logger->trace(__VA_ARGS__) -#define SPDLOG_TRACE(...) spdlog::trace(__VA_ARGS__) +#define SPDLOG_LOGGER_TRACE(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::trace, __VA_ARGS__) +#define SPDLOG_TRACE(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::trace, __VA_ARGS__) #else #define SPDLOG_LOGGER_TRACE(logger, ...) (void)0 #define SPDLOG_TRACE(...) (void)0 #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG -#define SPDLOG_LOGGER_DEBUG(logger, ...) logger->debug(__VA_ARGS__) -#define SPDLOG_DEBUG(...) spdlog::debug(__VA_ARGS__) +#define SPDLOG_LOGGER_DEBUG(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::debug, __VA_ARGS__) +#define SPDLOG_DEBUG(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::debug, __VA_ARGS__) #else #define SPDLOG_LOGGER_DEBUG(logger, ...) (void)0 #define SPDLOG_DEBUG(...) (void)0 #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO -#define SPDLOG_LOGGER_INFO(logger, ...) logger->info(__VA_ARGS__) -#define SPDLOG_INFO(...) spdlog::info(__VA_ARGS__) +#define SPDLOG_LOGGER_INFO(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::info, __VA_ARGS__) +#define SPDLOG_INFO(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::info, __VA_ARGS__) #else #define SPDLOG_LOGGER_INFO(logger, ...) (void)0 #define SPDLOG_INFO(...) (void)0 #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_WARN -#define SPDLOG_LOGGER_WARN(logger, ...) logger->warn(__VA_ARGS__) -#define SPDLOG_WARN(...) spdlog::warn(__VA_ARGS__) +#define SPDLOG_LOGGER_WARN(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::warn, __VA_ARGS__) +#define SPDLOG_WARN(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::warn, __VA_ARGS__) #else #define SPDLOG_LOGGER_WARN(logger, ...) (void)0 #define SPDLOG_WARN(...) (void)0 #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_ERROR -#define SPDLOG_LOGGER_ERROR(logger, ...) logger->error(__VA_ARGS__) -#define SPDLOG_ERROR(...) spdlog::error(__VA_ARGS__) +#define SPDLOG_LOGGER_ERROR(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::err, __VA_ARGS__) +#define SPDLOG_ERROR(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::err, __VA_ARGS__) #else #define SPDLOG_LOGGER_ERROR(logger, ...) (void)0 #define SPDLOG_ERROR(...) (void)0 #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_CRITICAL -#define SPDLOG_LOGGER_CRITICAL(logger, ...) logger->critical(__VA_ARGS__) -#define SPDLOG_CRITICAL(...) spdlog::critical(__VA_ARGS__) +#define SPDLOG_LOGGER_CRITICAL(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::critical, __VA_ARGS__) +#define SPDLOG_CRITICAL(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::critical, __VA_ARGS__) #else #define SPDLOG_LOGGER_CRITICAL(logger, ...) (void)0 #define SPDLOG_CRITICAL(...) (void)0 From f97cb00737c818dcd707fc2750bb32aafd6afe9e Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 18:48:32 +0200 Subject: [PATCH 23/83] Updated macros tests --- tests/test_macros.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/test_macros.cpp b/tests/test_macros.cpp index cf2bb136..cf917069 100644 --- a/tests/test_macros.cpp +++ b/tests/test_macros.cpp @@ -24,6 +24,16 @@ TEST_CASE("debug and trace w/o format string", "[macros]]") REQUIRE(ends_with(file_contents(filename), "Test message 2\n")); REQUIRE(count_lines(filename) == 1); + + spdlog::set_default_logger(logger); + + SPDLOG_TRACE("Test message 3"); + SPDLOG_DEBUG("Test message {}", 4); + logger->flush(); + + REQUIRE(ends_with(file_contents(filename), "Test message 4\n")); + REQUIRE(count_lines(filename) == 2); + } TEST_CASE("disable param evaluation", "[macros]") From a31719b54680d85729534254bf3ee0d9762dd33e Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 18:49:14 +0200 Subject: [PATCH 24/83] clang-format --- bench/bench.cpp | 1 - include/spdlog/common.h | 15 +++++--- include/spdlog/details/log_msg.h | 6 ++-- include/spdlog/details/logger_impl.h | 4 +-- include/spdlog/details/pattern_formatter.h | 41 +++++++++++----------- include/spdlog/logger.h | 6 ++-- include/spdlog/spdlog.h | 1 - tests/test_macros.cpp | 1 - 8 files changed, 39 insertions(+), 36 deletions(-) diff --git a/bench/bench.cpp b/bench/bench.cpp index 814851f7..bebfd745 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -67,7 +67,6 @@ int main(int argc, char *argv[]) bench(howmany, spdlog::create("null_st")); - spdlog::info("**************************************************************"); spdlog::info("C-string (400 bytes). Single thread, {:n} iterations", howmany); spdlog::info("**************************************************************"); diff --git a/include/spdlog/common.h b/include/spdlog/common.h index ee4bc249..34c0862f 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -185,12 +185,19 @@ using filename_t = std::wstring; using filename_t = std::string; #endif - struct source_loc { - SPDLOG_CONSTEXPR source_loc(): filename(""), line(0) {} - SPDLOG_CONSTEXPR source_loc(const char *filename, int line) : filename(filename), line(line) {} - const char* const filename ; + SPDLOG_CONSTEXPR source_loc() + : filename("") + , line(0) + { + } + SPDLOG_CONSTEXPR source_loc(const char *filename, int line) + : filename(filename) + , line(line) + { + } + const char *const filename; const uint32_t line; }; diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 56f4729a..affeb514 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -31,8 +31,10 @@ struct log_msg { } - log_msg(const std::string *loggers_name, level::level_enum lvl, string_view_t view): - log_msg(source_loc{}, loggers_name, lvl, view){} + log_msg(const std::string *loggers_name, level::level_enum lvl, string_view_t view) + : log_msg(source_loc{}, loggers_name, lvl, view) + { + } log_msg(const log_msg &other) = default; log_msg &operator=(const log_msg &other) = default; diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index de2f76ff..a7435f2e 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -57,7 +57,6 @@ inline void spdlog::logger::set_pattern(std::string pattern, pattern_time_type t set_formatter(std::move(new_formatter)); } - template inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args) { @@ -77,11 +76,10 @@ inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const SPDLOG_CATCH_AND_HANDLE } - template inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) { - log(source_loc{}, lvl, fmt, args...); + log(source_loc{}, lvl, fmt, args...); } inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *msg) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 044006c5..e0e72081 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -813,34 +813,32 @@ class source_location_formatter final : public flag_formatter { public: explicit source_location_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){}; -void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override -{ - if(padinfo_.width_) - { - const auto text_size = std::char_traits::length(msg.source.filename) - + fmt_helper::count_digits(msg.source.line) - +1; - scoped_pad p(text_size, padinfo_, dest); - fmt_helper::append_string_view(msg.source.filename, dest); - dest.push_back(':'); - fmt_helper::append_int(msg.source.line, dest); - } - else + void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - fmt_helper::append_string_view(msg.source.filename, dest); - dest.push_back(':'); - fmt_helper::append_int(msg.source.line, dest); + if (padinfo_.width_) + { + const auto text_size = std::char_traits::length(msg.source.filename) + fmt_helper::count_digits(msg.source.line) + 1; + scoped_pad p(text_size, padinfo_, dest); + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + } + else + { + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + } } -} }; // print soruce filename class source_filename_formatter final : public flag_formatter { public: explicit source_filename_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){}; void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { @@ -853,12 +851,13 @@ class source_linenum_formatter final : public flag_formatter { public: explicit source_linenum_formatter(padding_info padinfo) - : flag_formatter(padinfo){}; + : flag_formatter(padinfo){}; void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - if(padinfo_.width_) { + if (padinfo_.width_) + { const size_t field_size = fmt::internal::count_digits(msg.source.line); scoped_pad p(field_size, padinfo_, dest); fmt_helper::append_int(msg.source.line, dest); diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 640895a3..0f75a6f0 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -105,9 +105,9 @@ public: template::value, T>::type * = nullptr> void log(level::level_enum lvl, const T &); - // T can be statically converted to string_view - template::value, T>::type * = nullptr> - void log(source_loc loc, level::level_enum lvl, const T &); + // T can be statically converted to string_view + template::value, T>::type * = nullptr> + void log(source_loc loc, level::level_enum lvl, const T &); // T cannot be statically converted to string_view template::value, T>::type * = nullptr> diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 64a53fbe..301ae97d 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -309,7 +309,6 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // - #define SPDLOG_LOGGER_LOG(logger, level, ...) logger->log(spdlog::source_loc{__FILE__, __LINE__}, level, __VA_ARGS__) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE diff --git a/tests/test_macros.cpp b/tests/test_macros.cpp index cf917069..22a5ccbf 100644 --- a/tests/test_macros.cpp +++ b/tests/test_macros.cpp @@ -33,7 +33,6 @@ TEST_CASE("debug and trace w/o format string", "[macros]]") REQUIRE(ends_with(file_contents(filename), "Test message 4\n")); REQUIRE(count_lines(filename) == 2); - } TEST_CASE("disable param evaluation", "[macros]") From a463989278537ba1fc0fa4fc371fe4a6270eb8de Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 18:50:56 +0200 Subject: [PATCH 25/83] keep clang-tidy happy --- include/spdlog/common.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 34c0862f..5bd24c0f 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -188,8 +188,8 @@ using filename_t = std::string; struct source_loc { SPDLOG_CONSTEXPR source_loc() - : filename("") - , line(0) + : filename{""} + , line{0} { } SPDLOG_CONSTEXPR source_loc(const char *filename, int line) From 521b0733d4a5e5eb404e927fe0fb682a4ad86061 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 19:17:41 +0200 Subject: [PATCH 26/83] Support for source location in async loggers --- include/spdlog/common.h | 9 +++++++-- include/spdlog/details/thread_pool.h | 6 ++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 5bd24c0f..3bd9e7d9 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -197,8 +197,13 @@ struct source_loc , line(line) { } - const char *const filename; - const uint32_t line; +// +// source_loc (const source_loc&) = default; +// source_loc& operator=(const source_loc&) = default; +// source_loc& operator=(source_loc&&) = default; + + const char *filename; + uint32_t line; }; namespace details { diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h index a1c07d3f..35578971 100644 --- a/include/spdlog/details/thread_pool.h +++ b/include/spdlog/details/thread_pool.h @@ -33,6 +33,7 @@ struct async_msg fmt::basic_memory_buffer raw; size_t msg_id; + source_loc source; async_logger_ptr worker_ptr; async_msg() = default; @@ -49,6 +50,7 @@ struct async_msg thread_id(other.thread_id), raw(move(other.raw)), msg_id(other.msg_id), + source(other.source), worker_ptr(std::move(other.worker_ptr)) { } @@ -61,6 +63,7 @@ struct async_msg thread_id = other.thread_id; raw = std::move(other.raw); msg_id = other.msg_id; + source = other.source; worker_ptr = std::move(other.worker_ptr); return *this; } @@ -76,6 +79,7 @@ struct async_msg , time(m.time) , thread_id(m.thread_id) , msg_id(m.msg_id) + , source(m.source) , worker_ptr(std::move(worker)) { fmt_helper::append_string_view(m.payload, raw); @@ -87,6 +91,7 @@ struct async_msg , time() , thread_id(0) , msg_id(0) + , source() , worker_ptr(std::move(worker)) { } @@ -103,6 +108,7 @@ struct async_msg msg.time = time; msg.thread_id = thread_id; msg.msg_id = msg_id; + msg.source = source; msg.color_range_start = 0; msg.color_range_end = 0; return msg; From 9484c4dc058f6a641baffaf2c1d178060141c7e5 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 19:18:43 +0200 Subject: [PATCH 27/83] clang-format --- include/spdlog/common.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 3bd9e7d9..7621309f 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -197,10 +197,10 @@ struct source_loc , line(line) { } -// -// source_loc (const source_loc&) = default; -// source_loc& operator=(const source_loc&) = default; -// source_loc& operator=(source_loc&&) = default; + // + // source_loc (const source_loc&) = default; + // source_loc& operator=(const source_loc&) = default; + // source_loc& operator=(source_loc&&) = default; const char *filename; uint32_t line; From 2998815166868e7122a0e8653e86e41dcf6ddb5f Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 22 Nov 2018 21:35:11 +0200 Subject: [PATCH 28/83] Added missing test file --- tests/test_file_logging.cpp | 173 ++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 tests/test_file_logging.cpp diff --git a/tests/test_file_logging.cpp b/tests/test_file_logging.cpp new file mode 100644 index 00000000..c5886f5f --- /dev/null +++ b/tests/test_file_logging.cpp @@ -0,0 +1,173 @@ +/* + * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + */ +#include "includes.h" + +TEST_CASE("simple_file_logger", "[simple_logger]]") +{ + prepare_logdir(); + std::string filename = "logs/simple_log"; + + auto logger = spdlog::create("logger", filename); + logger->set_pattern("%v"); + + logger->info("Test message {}", 1); + logger->info("Test message {}", 2); + + logger->flush(); + REQUIRE(file_contents(filename) == std::string("Test message 1\nTest message 2\n")); + REQUIRE(count_lines(filename) == 2); +} + +TEST_CASE("flush_on", "[flush_on]]") +{ + prepare_logdir(); + std::string filename = "logs/simple_log"; + + auto logger = spdlog::create("logger", filename); + logger->set_pattern("%v"); + logger->set_level(spdlog::level::trace); + logger->flush_on(spdlog::level::info); + logger->trace("Should not be flushed"); + REQUIRE(count_lines(filename) == 0); + + logger->info("Test message {}", 1); + logger->info("Test message {}", 2); + + REQUIRE(file_contents(filename) == std::string("Should not be flushed\nTest message 1\nTest message 2\n")); + REQUIRE(count_lines(filename) == 3); +} + +TEST_CASE("rotating_file_logger1", "[rotating_logger]]") +{ + prepare_logdir(); + size_t max_size = 1024 * 10; + std::string basename = "logs/rotating_log"; + auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 0); + + for (int i = 0; i < 10; ++i) + { + logger->info("Test message {}", i); + } + + logger->flush(); + auto filename = basename; + REQUIRE(count_lines(filename) == 10); +} + +TEST_CASE("rotating_file_logger2", "[rotating_logger]]") +{ + prepare_logdir(); + size_t max_size = 1024 * 10; + std::string basename = "logs/rotating_log"; + auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 1); + for (int i = 0; i < 10; ++i) + { + logger->info("Test message {}", i); + } + + logger->flush(); + auto filename = basename; + REQUIRE(count_lines(filename) == 10); + for (int i = 0; i < 1000; i++) + { + + logger->info("Test message {}", i); + } + + logger->flush(); + REQUIRE(get_filesize(filename) <= max_size); + auto filename1 = basename + ".1"; + REQUIRE(get_filesize(filename1) <= max_size); +} + +TEST_CASE("daily_logger with dateonly calculator", "[daily_logger_dateonly]]") +{ + using sink_type = spdlog::sinks::daily_file_sink; + + prepare_logdir(); + // calculate filename (time based) + std::string basename = "logs/daily_dateonly"; + std::tm tm = spdlog::details::os::localtime(); + fmt::memory_buffer w; + fmt::format_to(w, "{}_{:04d}-{:02d}-{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); + + auto logger = spdlog::create("logger", basename, 0, 0); + for (int i = 0; i < 10; ++i) + { + + logger->info("Test message {}", i); + } + logger->flush(); + auto filename = fmt::to_string(w); + REQUIRE(count_lines(filename) == 10); +} + +struct custom_daily_file_name_calculator +{ + static spdlog::filename_t calc_filename(const spdlog::filename_t &basename, const tm &now_tm) + { + fmt::memory_buffer w; + fmt::format_to(w, "{}{:04d}{:02d}{:02d}", basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday); + return fmt::to_string(w); + } +}; + +TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") +{ + using sink_type = spdlog::sinks::daily_file_sink; + + prepare_logdir(); + // calculate filename (time based) + std::string basename = "logs/daily_dateonly"; + std::tm tm = spdlog::details::os::localtime(); + fmt::memory_buffer w; + fmt::format_to(w, "{}{:04d}{:02d}{:02d}", basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); + + auto logger = spdlog::create("logger", basename, 0, 0); + for (int i = 0; i < 10; ++i) + { + logger->info("Test message {}", i); + } + + logger->flush(); + auto filename = fmt::to_string(w); + REQUIRE(count_lines(filename) == 10); +} + +/* + * File name calculations + */ + +TEST_CASE("rotating_file_sink::calc_filename1", "[rotating_file_sink]]") +{ + auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename("rotated.txt", 3); + REQUIRE(filename == "rotated.3.txt"); +} + +TEST_CASE("rotating_file_sink::calc_filename2", "[rotating_file_sink]]") +{ + auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename("rotated", 3); + REQUIRE(filename == "rotated.3"); +} + +TEST_CASE("rotating_file_sink::calc_filename3", "[rotating_file_sink]]") +{ + auto filename = spdlog::sinks::rotating_file_sink_st::calc_filename("rotated.txt", 0); + REQUIRE(filename == "rotated.txt"); +} + +// regex supported only from gcc 4.9 and above +#if defined(_MSC_VER) || !(__GNUC__ <= 4 && __GNUC_MINOR__ < 9) +#include + +TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]]") +{ + // daily_YYYY-MM-DD_hh-mm.txt + auto filename = spdlog::sinks::daily_filename_calculator::calc_filename("daily.txt", spdlog::details::os::localtime()); + // date regex based on https://www.regular-expressions.info/dates.html + std::regex re(R"(^daily_(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\.txt$)"); + std::smatch match; + REQUIRE(std::regex_match(filename, match, re)); +} +#endif From 1293af093c11cecca0058980f6e1521cc857ef43 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sat, 24 Nov 2018 11:11:03 +0200 Subject: [PATCH 29/83] call flush_() instead of flush() from looger::sink_it_() --- include/spdlog/details/logger_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index a7435f2e..b236db9a 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -390,7 +390,7 @@ inline void spdlog::logger::sink_it_(details::log_msg &msg) if (should_flush_(msg)) { - flush(); + flush_(); } } From dc1370009471703491b24a510be6b8be22dafa99 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 17:08:13 +0200 Subject: [PATCH 30/83] Fixed source location and make SPDLOG_TRACE: that only one that inject source location info. --- include/spdlog/common.h | 10 +++++----- include/spdlog/details/logger_impl.h | 4 ++-- include/spdlog/details/pattern_formatter.h | 13 ++++++++++++- include/spdlog/logger.h | 2 +- include/spdlog/spdlog.h | 17 +++++++++-------- 5 files changed, 29 insertions(+), 17 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 7621309f..621336cc 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -197,11 +197,11 @@ struct source_loc , line(line) { } - // - // source_loc (const source_loc&) = default; - // source_loc& operator=(const source_loc&) = default; - // source_loc& operator=(source_loc&&) = default; - + + SPDLOG_CONSTEXPR bool empty() const + { + return line == 0; + } const char *filename; uint32_t line; }; diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index b236db9a..0212ede5 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -243,7 +243,7 @@ inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer } template -inline void spdlog::logger::log(source_location source, level::level_enum lvl, const wchar_t *fmt, const Args &... args) +inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args) { if (!should_log(lvl)) { @@ -267,7 +267,7 @@ inline void spdlog::logger::log(source_location source, level::level_enum lvl, c template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) { - log(source_location{}, lvl, fmt, args...); + log(source_loc{}, lvl, fmt, args...); } template diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index e0e72081..5e25f590 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -817,6 +817,10 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { + if (msg.source.empty()) + { + return; + } if (padinfo_.width_) { const auto text_size = std::char_traits::length(msg.source.filename) + fmt_helper::count_digits(msg.source.line) + 1; @@ -842,6 +846,10 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { + if (msg.source.empty()) + { + return; + } scoped_pad p(msg.source.filename, padinfo_, dest); fmt_helper::append_string_view(msg.source.filename, dest); } @@ -855,7 +863,10 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - + if (msg.source.empty()) + { + return; + } if (padinfo_.width_) { const size_t field_size = fmt::internal::count_digits(msg.source.line); diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 0f75a6f0..1b762429 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -79,7 +79,7 @@ public: void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); template - void log(source_location soruce, level::level_enum lvl, const wchar_t *fmt, const Args &... args); + void log(source_loc soruce, level::level_enum lvl, const wchar_t *fmt, const Args &... args); template void trace(const wchar_t *fmt, const Args &... args); diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 301ae97d..923b5c3d 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -309,19 +309,20 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // -#define SPDLOG_LOGGER_LOG(logger, level, ...) logger->log(spdlog::source_loc{__FILE__, __LINE__}, level, __VA_ARGS__) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE -#define SPDLOG_LOGGER_TRACE(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::trace, __VA_ARGS__) -#define SPDLOG_TRACE(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::trace, __VA_ARGS__) +#define SPDLOG_LOGGER_TRACE(logger, ...) logger->log(spdlog::source_loc{__FILE__, __LINE__}, spdlog::level::trace, __VA_ARGS__) +#define SPDLOG_TRACE(...) SPDLOG_LOGGER_TRACE(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_TRACE(logger, ...) (void)0 #define SPDLOG_TRACE(...) (void)0 #endif +#define SPDLOG_LOGGER_LOG(logger, level, ...) logger->log(level, __VA_ARGS__) + #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG #define SPDLOG_LOGGER_DEBUG(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::debug, __VA_ARGS__) -#define SPDLOG_DEBUG(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::debug, __VA_ARGS__) +#define SPDLOG_DEBUG(...) SPDLOG_LOGGER_DEBUG(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_DEBUG(logger, ...) (void)0 #define SPDLOG_DEBUG(...) (void)0 @@ -329,7 +330,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO #define SPDLOG_LOGGER_INFO(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::info, __VA_ARGS__) -#define SPDLOG_INFO(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::info, __VA_ARGS__) +#define SPDLOG_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_INFO(logger, ...) (void)0 #define SPDLOG_INFO(...) (void)0 @@ -337,7 +338,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_WARN #define SPDLOG_LOGGER_WARN(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::warn, __VA_ARGS__) -#define SPDLOG_WARN(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::warn, __VA_ARGS__) +#define SPDLOG_WARN(...) SPDLOG_ACTIVE_LEVEL(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_WARN(logger, ...) (void)0 #define SPDLOG_WARN(...) (void)0 @@ -345,7 +346,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_ERROR #define SPDLOG_LOGGER_ERROR(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::err, __VA_ARGS__) -#define SPDLOG_ERROR(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::err, __VA_ARGS__) +#define SPDLOG_ERROR(...) SPDLOG_LOGGER_ERROR(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_ERROR(logger, ...) (void)0 #define SPDLOG_ERROR(...) (void)0 @@ -353,7 +354,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_CRITICAL #define SPDLOG_LOGGER_CRITICAL(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::critical, __VA_ARGS__) -#define SPDLOG_CRITICAL(...) SPDLOG_LOGGER_LOG(spdlog::default_logger_raw(), spdlog::level::critical, __VA_ARGS__) +#define SPDLOG_CRITICAL(...) SPDLOG_LOGGER_CRITICAL(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_CRITICAL(logger, ...) (void)0 #define SPDLOG_CRITICAL(...) (void)0 From 01583ef5402b0edfbef349896851f360e5b6ecff Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 17:15:58 +0200 Subject: [PATCH 31/83] Clean macros --- include/spdlog/spdlog.h | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 923b5c3d..cbb57664 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -309,7 +309,6 @@ inline void critical(const wchar_t *fmt, const Args &... args) // SPDLOG_LEVEL_OFF // - #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE #define SPDLOG_LOGGER_TRACE(logger, ...) logger->log(spdlog::source_loc{__FILE__, __LINE__}, spdlog::level::trace, __VA_ARGS__) #define SPDLOG_TRACE(...) SPDLOG_LOGGER_TRACE(spdlog::default_logger_raw(), __VA_ARGS__) @@ -318,10 +317,8 @@ inline void critical(const wchar_t *fmt, const Args &... args) #define SPDLOG_TRACE(...) (void)0 #endif -#define SPDLOG_LOGGER_LOG(logger, level, ...) logger->log(level, __VA_ARGS__) - #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG -#define SPDLOG_LOGGER_DEBUG(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::debug, __VA_ARGS__) +#define SPDLOG_LOGGER_DEBUG(logger, ...) logger->log(spdlog::level::debug, __VA_ARGS__) #define SPDLOG_DEBUG(...) SPDLOG_LOGGER_DEBUG(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_DEBUG(logger, ...) (void)0 @@ -329,7 +326,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO -#define SPDLOG_LOGGER_INFO(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::info, __VA_ARGS__) +#define SPDLOG_LOGGER_INFO(logger, ...) logger->log(spdlog::level::info, __VA_ARGS__) #define SPDLOG_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_INFO(logger, ...) (void)0 @@ -337,15 +334,15 @@ inline void critical(const wchar_t *fmt, const Args &... args) #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_WARN -#define SPDLOG_LOGGER_WARN(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::warn, __VA_ARGS__) -#define SPDLOG_WARN(...) SPDLOG_ACTIVE_LEVEL(spdlog::default_logger_raw(), __VA_ARGS__) +#define SPDLOG_LOGGER_WARN(logger, ...) logger->log(spdlog::level::warn, __VA_ARGS__) +#define SPDLOG_WARN(...) SPDLOG_LOGGER_WARN(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_WARN(logger, ...) (void)0 #define SPDLOG_WARN(...) (void)0 #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_ERROR -#define SPDLOG_LOGGER_ERROR(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::err, __VA_ARGS__) +#define SPDLOG_LOGGER_ERROR(logger, ...) logger->log(spdlog::level::err, __VA_ARGS__) #define SPDLOG_ERROR(...) SPDLOG_LOGGER_ERROR(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_ERROR(logger, ...) (void)0 @@ -353,7 +350,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) #endif #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_CRITICAL -#define SPDLOG_LOGGER_CRITICAL(logger, ...) SPDLOG_LOGGER_LOG(logger, spdlog::level::critical, __VA_ARGS__) +#define SPDLOG_LOGGER_CRITICAL(logger, ...) logger->log(spdlog::level::critical, __VA_ARGS__) #define SPDLOG_CRITICAL(...) SPDLOG_LOGGER_CRITICAL(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_CRITICAL(logger, ...) (void)0 From 3218caf34a050214134e209cb45b71e67037318a Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 17:34:33 +0200 Subject: [PATCH 32/83] Added some comments --- include/spdlog/details/pattern_formatter.h | 83 +++++++++++----------- 1 file changed, 43 insertions(+), 40 deletions(-) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 5e25f590..c1e89e79 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -1040,153 +1040,156 @@ private: { switch (flag) { - // logger name - case 'n': + + case ('+'): // default formatter + formatters_.push_back(details::make_unique(padding)); + break; + + case 'n': // logger name formatters_.push_back(details::make_unique(padding)); break; - case 'l': + case 'l': // level formatters_.push_back(details::make_unique(padding)); break; - case 'L': + case 'L': // short level formatters_.push_back(details::make_unique(padding)); break; - case ('t'): + case ('t'): // thread id formatters_.push_back(details::make_unique(padding)); break; - case ('v'): + case ('v'): // the message text formatters_.push_back(details::make_unique(padding)); break; - case ('a'): + case ('a'): // weekday formatters_.push_back(details::make_unique(padding)); break; - case ('A'): + case ('A'): // short weekday formatters_.push_back(details::make_unique(padding)); break; case ('b'): - case ('h'): + case ('h'): // month formatters_.push_back(details::make_unique(padding)); break; - case ('B'): + case ('B'): // short month formatters_.push_back(details::make_unique(padding)); break; - case ('c'): + + case ('c'): // datetime formatters_.push_back(details::make_unique(padding)); break; - case ('C'): + case ('C'): // year 2 digits formatters_.push_back(details::make_unique(padding)); break; - case ('Y'): + case ('Y'): // year 4 digits formatters_.push_back(details::make_unique(padding)); break; case ('D'): - case ('x'): + case ('x'): // datetime MM/DD/YY formatters_.push_back(details::make_unique(padding)); break; - case ('m'): + case ('m'): // month 1-12 formatters_.push_back(details::make_unique(padding)); break; - case ('d'): + case ('d'): // day of month 1-31 formatters_.push_back(details::make_unique(padding)); break; - case ('H'): + case ('H'): // hours 24 formatters_.push_back(details::make_unique(padding)); break; - case ('I'): + case ('I'): // hours 12 formatters_.push_back(details::make_unique(padding)); break; - case ('M'): + case ('M'): // minutes formatters_.push_back(details::make_unique(padding)); break; - case ('S'): + case ('S'): // seconds formatters_.push_back(details::make_unique(padding)); break; - case ('e'): + case ('e'): // milliseconds formatters_.push_back(details::make_unique(padding)); break; - case ('f'): + case ('f'): // microseconds formatters_.push_back(details::make_unique(padding)); break; - case ('F'): + + case ('F'): // nanoseconds formatters_.push_back(details::make_unique(padding)); break; - case ('E'): + case ('E'): // seconds since epoch formatters_.push_back(details::make_unique(padding)); break; - case ('p'): + case ('p'): // am/pm formatters_.push_back(details::make_unique(padding)); break; - case ('r'): + case ('r'): // 12 hour clock 02:55:02 pm formatters_.push_back(details::make_unique(padding)); break; - case ('R'): + case ('R'): // 24-hour HH:MM time formatters_.push_back(details::make_unique(padding)); break; case ('T'): - case ('X'): + case ('X'): // ISO 8601 time format (HH:MM:SS) formatters_.push_back(details::make_unique(padding)); break; - case ('z'): + case ('z'): // timezone formatters_.push_back(details::make_unique(padding)); break; - case ('+'): - formatters_.push_back(details::make_unique(padding)); - break; - - case ('P'): + case ('P'): // pid formatters_.push_back(details::make_unique(padding)); break; + #ifdef SPDLOG_ENABLE_MESSAGE_COUNTER case ('i'): formatters_.push_back(details::make_unique(padding)); break; #endif - case ('^'): + case ('^'): // color range start formatters_.push_back(details::make_unique(padding)); break; - case ('$'): + case ('$'): // color range end formatters_.push_back(details::make_unique(padding)); break; - case ('@'): + case ('@'): // source location (filename:filenumber) formatters_.push_back(details::make_unique(padding)); break; - case ('s'): + case ('s'): // source filename formatters_.push_back(details::make_unique(padding)); break; - case ('#'): + case ('#'): // source line number formatters_.push_back(details::make_unique(padding)); break; - case ('%'): + case ('%'): // % char formatters_.push_back(details::make_unique('%')); break; From a16ff07a0616e088dfa40765c103ca100f59b04e Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 18:00:56 +0200 Subject: [PATCH 33/83] Show source location if present in default formatter --- include/spdlog/common.h | 2 +- include/spdlog/details/pattern_formatter.h | 44 +++++++++++++--------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 621336cc..63e3df4e 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -198,7 +198,7 @@ struct source_loc { } - SPDLOG_CONSTEXPR bool empty() const + SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT { return line == 0; } diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index c1e89e79..2d811144 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -817,10 +817,10 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - if (msg.source.empty()) - { - return; - } + if (msg.source.empty()) + { + return; + } if (padinfo_.width_) { const auto text_size = std::char_traits::length(msg.source.filename) + fmt_helper::count_digits(msg.source.line) + 1; @@ -846,7 +846,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - if (msg.source.empty()) + if (msg.source.empty()) { return; } @@ -863,7 +863,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - if (msg.source.empty()) + if (msg.source.empty()) { return; } @@ -891,11 +891,12 @@ public: } void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override - { + { using std::chrono::duration_cast; using std::chrono::milliseconds; using std::chrono::seconds; - + + #ifndef SPDLOG_NO_DATETIME // cache the date/time part for the next second. @@ -930,8 +931,9 @@ public: auto millis = fmt_helper::time_fraction(msg.time); fmt_helper::pad3(static_cast(millis.count()), dest); - dest.push_back(']'); - dest.push_back(' '); + + SPDLOG_CONSTEXPR string_view_t closing_bracket{"] "}; + fmt_helper::append_string_view(closing_bracket, dest); #else // no datetime needed (void)tm_time; @@ -943,8 +945,7 @@ public: dest.push_back('['); // fmt_helper::append_str(*msg.logger_name, dest); fmt_helper::append_string_view(*msg.logger_name, dest); - dest.push_back(']'); - dest.push_back(' '); + fmt_helper::append_string_view(closing_bracket, dest); } #endif @@ -954,8 +955,17 @@ public: // fmt_helper::append_string_view(level::to_c_str(msg.level), dest); fmt_helper::append_string_view(level::to_c_str(msg.level), dest); msg.color_range_end = dest.size(); - dest.push_back(']'); - dest.push_back(' '); + fmt_helper::append_string_view(closing_bracket, dest); + + // add soruce location if present + if (!msg.source.empty()) + { + dest.push_back('['); + fmt_helper::append_string_view(msg.source.filename, dest); + dest.push_back(':'); + fmt_helper::append_int(msg.source.line, dest); + fmt_helper::append_string_view(closing_bracket, dest); + } // fmt_helper::append_string_view(msg.msg(), dest); fmt_helper::append_string_view(msg.payload, dest); } @@ -1040,11 +1050,11 @@ private: { switch (flag) { - - case ('+'): // default formatter + + case ('+'): // default formatter formatters_.push_back(details::make_unique(padding)); break; - + case 'n': // logger name formatters_.push_back(details::make_unique(padding)); break; From a1a463787feef1e320b5f2b211047e4bbbd9236c Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 18:15:24 +0200 Subject: [PATCH 34/83] Updated example's comment --- example/example.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 8a103fc3..026004b8 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -161,11 +161,10 @@ void binary_example() // define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE) void trace_example() { - // trace from default logger - SPDLOG_TRACE("Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23); + SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23); // debug from default logger - SPDLOG_DEBUG("Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23); + SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23); // trace from logger object auto logger = spdlog::get("file_logger"); From e3c333be4722a66514fb8b6be9ab1120c0b75561 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 18:21:25 +0200 Subject: [PATCH 35/83] pattern_formatter - padding_info small refactor --- include/spdlog/details/pattern_formatter.h | 64 ++++++++++++++-------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 2d811144..73e16084 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -41,6 +41,11 @@ struct padding_info , side_(side) { } + + bool enabled() const + { + return width_ != 0; + } const size_t width_ = 0; const pad_side side_ = left; }; @@ -131,8 +136,15 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - scoped_pad p(*msg.logger_name, padinfo_, dest); - fmt_helper::append_string_view(*msg.logger_name, dest); + if (padinfo_.enabled()) + { + scoped_pad p(*msg.logger_name, padinfo_, dest); + fmt_helper::append_string_view(*msg.logger_name, dest); + } + else + { + fmt_helper::append_string_view(*msg.logger_name, dest); + } } }; @@ -148,8 +160,15 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { string_view_t level_name{level::to_c_str(msg.level)}; - scoped_pad p(level_name, padinfo_, dest); - fmt_helper::append_string_view(level_name, dest); + if (padinfo_.enabled()) + { + scoped_pad p(level_name, padinfo_, dest); + fmt_helper::append_string_view(level_name, dest); + } + else + { + fmt_helper::append_string_view(level_name, dest); + } } }; @@ -337,7 +356,7 @@ public: void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { - const size_t field_size = 4; + const size_t field_size = 4; scoped_pad p(field_size, padinfo_, dest); fmt_helper::append_int(tm_time.tm_year + 1900, dest); } @@ -449,7 +468,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { auto millis = fmt_helper::time_fraction(msg.time); - if (padinfo_.width_) + if (padinfo_.enabled()) { const size_t field_size = 3; scoped_pad p(field_size, padinfo_, dest); @@ -472,7 +491,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { auto micros = fmt_helper::time_fraction(msg.time); - if (padinfo_.width_) + if (padinfo_.enabled()) { const size_t field_size = 6; scoped_pad p(field_size, padinfo_, dest); @@ -495,7 +514,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { auto ns = fmt_helper::time_fraction(msg.time); - if (padinfo_.width_) + if (padinfo_.enabled()) { const size_t field_size = 9; scoped_pad p(field_size, padinfo_, dest); @@ -519,7 +538,6 @@ public: { const size_t field_size = 10; scoped_pad p(field_size, padinfo_, dest); - auto duration = msg.time.time_since_epoch(); auto seconds = std::chrono::duration_cast(duration).count(); fmt_helper::append_int(seconds, dest); @@ -590,7 +608,6 @@ public: void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { - const size_t field_size = 8; scoped_pad p(field_size, padinfo_, dest); @@ -670,7 +687,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - if (padinfo_.width_) + if (padinfo_.enabled()) { const auto field_size = fmt_helper::count_digits(msg.thread_id); scoped_pad p(field_size, padinfo_, dest); @@ -693,7 +710,7 @@ public: void format(const details::log_msg &, const std::tm &, fmt::memory_buffer &dest) override { const auto pid = static_cast(details::os::pid()); - if (padinfo_.width_) + if (padinfo_.enabled()) { const size_t field_size = fmt::internal::count_digits(pid); scoped_pad p(field_size, padinfo_, dest); @@ -729,7 +746,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - if (padinfo_.width_) + if (padinfo_.enabled()) { scoped_pad p(msg.payload, padinfo_, dest); fmt_helper::append_string_view(msg.payload, dest); @@ -821,7 +838,7 @@ public: { return; } - if (padinfo_.width_) + if (padinfo_.enabled()) { const auto text_size = std::char_traits::length(msg.source.filename) + fmt_helper::count_digits(msg.source.line) + 1; scoped_pad p(text_size, padinfo_, dest); @@ -867,7 +884,7 @@ public: { return; } - if (padinfo_.width_) + if (padinfo_.enabled()) { const size_t field_size = fmt::internal::count_digits(msg.source.line); scoped_pad p(field_size, padinfo_, dest); @@ -891,12 +908,11 @@ public: } void format(const details::log_msg &msg, const std::tm &tm_time, fmt::memory_buffer &dest) override - { + { using std::chrono::duration_cast; using std::chrono::milliseconds; using std::chrono::seconds; - - + #ifndef SPDLOG_NO_DATETIME // cache the date/time part for the next second. @@ -932,7 +948,7 @@ public: auto millis = fmt_helper::time_fraction(msg.time); fmt_helper::pad3(static_cast(millis.count()), dest); - SPDLOG_CONSTEXPR string_view_t closing_bracket{"] "}; + SPDLOG_CONSTEXPR string_view_t closing_bracket{"] "}; fmt_helper::append_string_view(closing_bracket, dest); #else // no datetime needed @@ -956,16 +972,16 @@ public: fmt_helper::append_string_view(level::to_c_str(msg.level), dest); msg.color_range_end = dest.size(); fmt_helper::append_string_view(closing_bracket, dest); - - // add soruce location if present - if (!msg.source.empty()) - { + + // add soruce location if present + if (!msg.source.empty()) + { dest.push_back('['); fmt_helper::append_string_view(msg.source.filename, dest); dest.push_back(':'); fmt_helper::append_int(msg.source.line, dest); fmt_helper::append_string_view(closing_bracket, dest); - } + } // fmt_helper::append_string_view(msg.msg(), dest); fmt_helper::append_string_view(msg.payload, dest); } From 382478259f90e35aa31b8a4d52d16efc70132484 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 18:27:27 +0200 Subject: [PATCH 36/83] Fix compilation for msvc 2015 --- include/spdlog/details/pattern_formatter.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 73e16084..4d355bc5 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -948,7 +948,7 @@ public: auto millis = fmt_helper::time_fraction(msg.time); fmt_helper::pad3(static_cast(millis.count()), dest); - SPDLOG_CONSTEXPR string_view_t closing_bracket{"] "}; + string_view_t closing_bracket{"] ", 2}; fmt_helper::append_string_view(closing_bracket, dest); #else // no datetime needed From 2671b48a6cdca45fdbc037ff604a28aaf3117f72 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 24 Nov 2018 23:57:39 +0200 Subject: [PATCH 37/83] Minor performance fix in full formatter --- include/spdlog/details/pattern_formatter.h | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 4d355bc5..e89a5416 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -947,9 +947,8 @@ public: auto millis = fmt_helper::time_fraction(msg.time); fmt_helper::pad3(static_cast(millis.count()), dest); - - string_view_t closing_bracket{"] ", 2}; - fmt_helper::append_string_view(closing_bracket, dest); + dest.push_back(']'); + dest.push_back(' '); #else // no datetime needed (void)tm_time; @@ -961,7 +960,8 @@ public: dest.push_back('['); // fmt_helper::append_str(*msg.logger_name, dest); fmt_helper::append_string_view(*msg.logger_name, dest); - fmt_helper::append_string_view(closing_bracket, dest); + dest.push_back(']'); + dest.push_back(' '); } #endif @@ -971,16 +971,18 @@ public: // fmt_helper::append_string_view(level::to_c_str(msg.level), dest); fmt_helper::append_string_view(level::to_c_str(msg.level), dest); msg.color_range_end = dest.size(); - fmt_helper::append_string_view(closing_bracket, dest); + dest.push_back(']'); + dest.push_back(' '); - // add soruce location if present + // add source location if present if (!msg.source.empty()) { dest.push_back('['); fmt_helper::append_string_view(msg.source.filename, dest); dest.push_back(':'); fmt_helper::append_int(msg.source.line, dest); - fmt_helper::append_string_view(closing_bracket, dest); + dest.push_back(']'); + dest.push_back(' '); } // fmt_helper::append_string_view(msg.msg(), dest); fmt_helper::append_string_view(msg.payload, dest); From 0ce670e45aa2791d299ee1eaa6ca19ef0a2006b3 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 00:36:14 +0200 Subject: [PATCH 38/83] Store level names as string_views --- include/spdlog/common.h | 27 +++++++++++----------- include/spdlog/details/pattern_formatter.h | 4 ++-- tests/test_misc.cpp | 16 ++++++------- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 63e3df4e..49ebf1c0 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -107,13 +107,13 @@ enum level_enum "trace", "debug", "info", "warning", "error", "critical", "off" \ } #endif -static const char *level_names[] SPDLOG_LEVEL_NAMES; +static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES; static const char *short_level_names[]{"T", "D", "I", "W", "E", "C", "O"}; -inline const char *to_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT +inline string_view_t& to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT { - return level_names[l]; + return level_string_views[l]; } inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT @@ -123,17 +123,16 @@ inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT { - static std::unordered_map name_to_level = // map string->level - {{level_names[0], level::trace}, // trace - {level_names[1], level::debug}, // debug - {level_names[2], level::info}, // info - {level_names[3], level::warn}, // warn - {level_names[4], level::err}, // err - {level_names[5], level::critical}, // critical - {level_names[6], level::off}}; // off - - auto lvl_it = name_to_level.find(name); - return lvl_it != name_to_level.end() ? lvl_it->second : level::off; + int level = 0; + for(const auto &level_str : level_string_views) + { + if(level_str == name) + { + return static_cast(level); + } + level++; + } + return level::off; } using level_hasher = std::hash; diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index e89a5416..d31d5d1c 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -159,7 +159,7 @@ public: void format(const details::log_msg &msg, const std::tm &, fmt::memory_buffer &dest) override { - string_view_t level_name{level::to_c_str(msg.level)}; + string_view_t &level_name = level::to_string_view(msg.level); if (padinfo_.enabled()) { scoped_pad p(level_name, padinfo_, dest); @@ -969,7 +969,7 @@ public: // wrap the level name with color msg.color_range_start = dest.size(); // fmt_helper::append_string_view(level::to_c_str(msg.level), dest); - fmt_helper::append_string_view(level::to_c_str(msg.level), dest); + fmt_helper::append_string_view(level::to_string_view(msg.level), dest); msg.color_range_end = dest.size(); dest.push_back(']'); dest.push_back(' '); diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index f46410b5..9e097a45 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -43,15 +43,15 @@ TEST_CASE("log_levels", "[log_levels]") REQUIRE(log_info("Hello", spdlog::level::trace) == "Hello"); } -TEST_CASE("to_c_str", "[convert_to_c_str]") +TEST_CASE("level_to_string_view", "[convert_to_string_view") { - REQUIRE(std::string(spdlog::level::to_c_str(spdlog::level::trace)) == "trace"); - REQUIRE(std::string(spdlog::level::to_c_str(spdlog::level::debug)) == "debug"); - REQUIRE(std::string(spdlog::level::to_c_str(spdlog::level::info)) == "info"); - REQUIRE(std::string(spdlog::level::to_c_str(spdlog::level::warn)) == "warning"); - REQUIRE(std::string(spdlog::level::to_c_str(spdlog::level::err)) == "error"); - REQUIRE(std::string(spdlog::level::to_c_str(spdlog::level::critical)) == "critical"); - REQUIRE(std::string(spdlog::level::to_c_str(spdlog::level::off)) == "off"); + REQUIRE(spdlog::level::to_string_view(spdlog::level::trace) == "trace"); + REQUIRE(spdlog::level::to_string_view(spdlog::level::debug) == "debug"); + REQUIRE(spdlog::level::to_string_view(spdlog::level::info) == "info"); + REQUIRE(spdlog::level::to_string_view(spdlog::level::warn) == "warning"); + REQUIRE(spdlog::level::to_string_view(spdlog::level::err) == "error"); + REQUIRE(spdlog::level::to_string_view(spdlog::level::critical) == "critical"); + REQUIRE(spdlog::level::to_string_view(spdlog::level::off) == "off"); } TEST_CASE("to_short_c_str", "[convert_to_short_c_str]") From c251c4ccbb5e2e3d3340a3db1ee0f8df3cbefd21 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 00:44:27 +0200 Subject: [PATCH 39/83] Added the all flag to bench formatter --- bench/formatter-bench.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index c42ba503..2256b026 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -28,9 +28,7 @@ void bench_formatter(benchmark::State &state, std::string pattern) std::string logger_name = "logger-name"; const char *text = "Hello. This is some message with length of 80 "; - spdlog::details::log_msg msg(spdlog::source_loc{__FILE__, __LINE__}, &logger_name, spdlog::level::info, text); - // formatter->format(msg, dest); - // printf("%s\n", fmt::to_string(dest).c_str()); + spdlog::details::log_msg msg(&logger_name, spdlog::level::info, text); for (auto _ : state) { @@ -73,15 +71,22 @@ void bench_formatters() int main(int argc, char *argv[]) { - if (argc > 1) // bench given pattern + spdlog::set_pattern("[%^%l%$] %v"); + if(argc != 2) { - std::string pattern = argv[1]; - benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); + spdlog::error("Usage: {} format-flag (or \"all\" to bench all)", argv[0]); + exit(1); } - else // bench all flags + + std::string pattern = argv[1]; + if(pattern == "all") { bench_formatters(); } + else + { + benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); + } benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); } From 92921f767e934b1bc169b1f51d3eef0f9826692a Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 00:44:51 +0200 Subject: [PATCH 40/83] clang-format --- include/spdlog/common.h | 16 ++++++++-------- include/spdlog/details/pattern_formatter.h | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 49ebf1c0..4a9110b6 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -111,7 +111,7 @@ enum level_enum static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES; static const char *short_level_names[]{"T", "D", "I", "W", "E", "C", "O"}; -inline string_view_t& to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT +inline string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT { return level_string_views[l]; } @@ -124,9 +124,9 @@ inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT { int level = 0; - for(const auto &level_str : level_string_views) + for (const auto &level_str : level_string_views) { - if(level_str == name) + if (level_str == name) { return static_cast(level); } @@ -196,11 +196,11 @@ struct source_loc , line(line) { } - - SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT - { - return line == 0; - } + + SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT + { + return line == 0; + } const char *filename; uint32_t line; }; diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index d31d5d1c..429a6c3c 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -356,7 +356,7 @@ public: void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override { - const size_t field_size = 4; + const size_t field_size = 4; scoped_pad p(field_size, padinfo_, dest); fmt_helper::append_int(tm_time.tm_year + 1900, dest); } From 6453d396bfafeea26841de450bfb7d1f69cb63fd Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 00:45:43 +0200 Subject: [PATCH 41/83] Added the all flag to bench formatter --- bench/formatter-bench.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index 2256b026..6a8170a1 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -74,7 +74,7 @@ int main(int argc, char *argv[]) spdlog::set_pattern("[%^%l%$] %v"); if(argc != 2) { - spdlog::error("Usage: {} format-flag (or \"all\" to bench all)", argv[0]); + spdlog::error("Usage: {} pattern (or \"all\" to bench all)", argv[0]); exit(1); } From 4643f74a036722eb6668f4548d0585db786252fb Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 00:46:24 +0200 Subject: [PATCH 42/83] Added the all flag to bench formatter --- bench/formatter-bench.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index 6a8170a1..63299a48 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -74,7 +74,7 @@ int main(int argc, char *argv[]) spdlog::set_pattern("[%^%l%$] %v"); if(argc != 2) { - spdlog::error("Usage: {} pattern (or \"all\" to bench all)", argv[0]); + spdlog::error("Usage: {} (or \"all\" to bench all)", argv[0]); exit(1); } From 1e385851d763e7438d5a31658105cd780b28c67b Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 01:12:12 +0200 Subject: [PATCH 43/83] Removed padding from from bench_formatters/all --- bench/formatter-bench.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bench/formatter-bench.cpp b/bench/formatter-bench.cpp index 63299a48..fff16e4b 100644 --- a/bench/formatter-bench.cpp +++ b/bench/formatter-bench.cpp @@ -47,13 +47,13 @@ void bench_formatters() { auto pattern = std::string("%") + flag; benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); - // bench left padding - pattern = std::string("%16") + flag; - benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); - // bench center padding - pattern = std::string("%=16") + flag; - benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); +// pattern = std::string("%16") + flag; +// benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); +// +// // bench center padding +// pattern = std::string("%=16") + flag; +// benchmark::RegisterBenchmark(pattern.c_str(), bench_formatter, pattern); } // complex patterns From 4ba19821cecec09b0f1185e11e458f9a722894b5 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 10:54:06 +0200 Subject: [PATCH 44/83] Fixed compilation for vs2013 --- include/spdlog/details/fmt_helper.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index afc76b25..ed9df2c5 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -46,7 +46,7 @@ inline void append_int(T n, fmt::basic_memory_buffer &dest) template inline unsigned count_digits(T n) { - using count_type = typename std::conditional<(sizeof(T) > sizeof(std::uint32_t)), std::uint64_t, std::uint32_t>::type; + using count_type = typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type; return fmt::internal::count_digits(static_cast(n)); } From cff78f5833b6b2f46a3a9222b8083b24d12d0632 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 25 Nov 2018 11:20:27 +0200 Subject: [PATCH 45/83] Move logging macros outside the spdlog namespace --- include/spdlog/spdlog.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index cbb57664..f745a5fe 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -296,6 +296,10 @@ inline void critical(const wchar_t *fmt, const Args &... args) #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT +} // namespace spdlog + + + // // enable/disable log calls at compile time according to global level. // @@ -357,5 +361,4 @@ inline void critical(const wchar_t *fmt, const Args &... args) #define SPDLOG_CRITICAL(...) (void)0 #endif -} // namespace spdlog #endif // SPDLOG_H From b492642282e6be0f86e1d53b9132b7dd1cff6a85 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Tue, 27 Nov 2018 11:37:09 +0200 Subject: [PATCH 46/83] Update fmt_helper.h --- include/spdlog/details/fmt_helper.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h index ed9df2c5..6f0f6bcc 100644 --- a/include/spdlog/details/fmt_helper.h +++ b/include/spdlog/details/fmt_helper.h @@ -76,7 +76,7 @@ inline void pad2(int n, fmt::basic_memory_buffer &dest) template inline void pad_uint(T n, unsigned int width, fmt::basic_memory_buffer &dest) { - static_assert(std::is_unsigned::value, "append_uint must get unsigned T"); + static_assert(std::is_unsigned::value, "pad_uint must get unsigned T"); auto digits = count_digits(n); if (width > digits) { From 26d7c27bee77ed6320a3f60492ed1db1c20dba9b Mon Sep 17 00:00:00 2001 From: Adi Lester Date: Tue, 27 Nov 2018 14:16:25 +0200 Subject: [PATCH 47/83] Use _filelengthi64 instead of _fstat64 to calculate file size on x64 machines For some reason, `_fstat64` fails with errno 22 on Windows Server 2003 x64 when compiled using the `v141_xp` toolset. Using `_filelengthi64` instead solves this issue --- include/spdlog/details/os.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index f2422904..573224ad 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -210,10 +210,10 @@ inline size_t filesize(FILE *f) #if defined(_WIN32) && !defined(__CYGWIN__) int fd = _fileno(f); #if _WIN64 // 64 bits - struct _stat64 st; - if (_fstat64(fd, &st) == 0) + long long ret = _filelengthi64(fd); + if (ret >= 0) { - return st.st_size; + return static_cast(ret); } #else // windows 32 bits From 247c4e55e7d306947cbb3fc4964579a0df23701b Mon Sep 17 00:00:00 2001 From: Adi Lester Date: Tue, 27 Nov 2018 14:39:41 +0200 Subject: [PATCH 48/83] Update os.h --- include/spdlog/details/os.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 573224ad..646805e6 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -210,7 +210,7 @@ inline size_t filesize(FILE *f) #if defined(_WIN32) && !defined(__CYGWIN__) int fd = _fileno(f); #if _WIN64 // 64 bits - long long ret = _filelengthi64(fd); + __int64 ret = _filelengthi64(fd); if (ret >= 0) { return static_cast(ret); From 63a475d88c2bf5be21bf6abd4a487909862e97de Mon Sep 17 00:00:00 2001 From: "David P. Sicilia" Date: Tue, 27 Nov 2018 20:23:51 -0500 Subject: [PATCH 49/83] Do not attempt to default operator= when it is implicitly deleted --- include/spdlog/details/log_msg.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index affeb514..5913c3b0 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -37,7 +37,6 @@ struct log_msg } log_msg(const log_msg &other) = default; - log_msg &operator=(const log_msg &other) = default; const std::string *logger_name{nullptr}; level::level_enum level{level::off}; From a6152ebadd676d7f5a3a50e49eb995aa05d97112 Mon Sep 17 00:00:00 2001 From: "David P. Sicilia" Date: Tue, 27 Nov 2018 20:24:21 -0500 Subject: [PATCH 50/83] Make an implicit cast from int --> uint32_t explicit. Perhaps this casting should not happen to begin with, but better to make it explicit where it is happening for readability. This fixes a compiler warning. --- include/spdlog/common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 4a9110b6..350ae08b 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -193,7 +193,7 @@ struct source_loc } SPDLOG_CONSTEXPR source_loc(const char *filename, int line) : filename(filename) - , line(line) + , line(static_cast(line)) { } From f0c962d2741a189421ecdc1df6f117ad71cfdb21 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 29 Nov 2018 12:55:14 +0200 Subject: [PATCH 51/83] source_loc ctor: brace init members --- include/spdlog/common.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 350ae08b..157ce8e9 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -192,8 +192,8 @@ struct source_loc { } SPDLOG_CONSTEXPR source_loc(const char *filename, int line) - : filename(filename) - , line(static_cast(line)) + : filename{filename} + , line{static_cast(line)} { } From 85b4d7c8d6e45ba32c65b1b75c6e48377c50506c Mon Sep 17 00:00:00 2001 From: "David P. Sicilia" Date: Sat, 1 Dec 2018 20:37:06 -0500 Subject: [PATCH 52/83] CMake: include(CTest) only when building tests. This is needed in order to support usage of this library as a subdirectory in a parent project. In that situation, prior to this change, the inclusion of CTest would unconditionally enable BUILD_TESTING which would then bleed into other parts of the project. Also added some comments explaining how this logic works. --- CMakeLists.txt | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1dc01f87..7fda48a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,7 +5,6 @@ cmake_minimum_required(VERSION 3.1) project(spdlog VERSION 1.3.0 LANGUAGES CXX) -include(CTest) include(CMakeDependentOption) include(GNUInstallDirs) @@ -54,10 +53,22 @@ endif() option(SPDLOG_BUILD_EXAMPLES "Build examples" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_BUILD_BENCH "Build benchmarks" ${SPDLOG_MASTER_PROJECT}) +# Logic for enabling tests: If the user does not explicitly +# specify the value of the SPDLOG_BUILD_TESTING variable then the +# logic is simpler to reason about: that is, testing will be +# built if and only if BUILD_TESTING is ON and we are a Master +# Project. On the other hand, if the user overrides the value of +# SPDLOG_BUILD_TESTING then it can get a bit more tricky due to +# caching. + cmake_dependent_option(SPDLOG_BUILD_TESTING "Build spdlog tests" ${SPDLOG_MASTER_PROJECT} "BUILD_TESTING" OFF ) +if(SPDLOG_BUILD_TESTING) + # Include CTest conditionally since it will enable BUILD_TESTING. + include(CTest) +endif() target_include_directories( spdlog From f5dc16603ee97b77f9945e29b4f4864afdde2652 Mon Sep 17 00:00:00 2001 From: "David P. Sicilia" Date: Sat, 1 Dec 2018 20:57:45 -0500 Subject: [PATCH 53/83] Enable testing in the Travis config file. This is needed because ENABLE_TESTING is no longer enabled by default. --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 49ea5476..c578ce26 100644 --- a/.travis.yml +++ b/.travis.yml @@ -104,6 +104,7 @@ script: -DCMAKE_CXX_STANDARD=$CPP \ -DSPDLOG_BUILD_EXAMPLES=ON \ -DSPDLOG_BUILD_BENCH=OFF \ + -DBUILD_TESTING=ON \ -DSPDLOG_SANITIZE_ADDRESS=$ASAN \ -DSPDLOG_SANITIZE_THREAD=$TSAN - make VERBOSE=1 -j2 From 7275fb6f52e026b957c0dd09a7ab2c2d2fc34d12 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 2 Dec 2018 12:25:46 +0200 Subject: [PATCH 54/83] simplify SPDLOG_BUILD_TESTS Cmake option --- .travis.yml | 2 +- CMakeLists.txt | 20 +++----------------- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/.travis.yml b/.travis.yml index c578ce26..68d5b3c4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -104,7 +104,7 @@ script: -DCMAKE_CXX_STANDARD=$CPP \ -DSPDLOG_BUILD_EXAMPLES=ON \ -DSPDLOG_BUILD_BENCH=OFF \ - -DBUILD_TESTING=ON \ + -DBUILD_BUILD_TESTS=ON \ -DSPDLOG_SANITIZE_ADDRESS=$ASAN \ -DSPDLOG_SANITIZE_THREAD=$TSAN - make VERBOSE=1 -j2 diff --git a/CMakeLists.txt b/CMakeLists.txt index 7fda48a8..3a0531dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -52,23 +52,8 @@ endif() option(SPDLOG_BUILD_EXAMPLES "Build examples" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_BUILD_BENCH "Build benchmarks" ${SPDLOG_MASTER_PROJECT}) +option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) -# Logic for enabling tests: If the user does not explicitly -# specify the value of the SPDLOG_BUILD_TESTING variable then the -# logic is simpler to reason about: that is, testing will be -# built if and only if BUILD_TESTING is ON and we are a Master -# Project. On the other hand, if the user overrides the value of -# SPDLOG_BUILD_TESTING then it can get a bit more tricky due to -# caching. - -cmake_dependent_option(SPDLOG_BUILD_TESTING - "Build spdlog tests" ${SPDLOG_MASTER_PROJECT} - "BUILD_TESTING" OFF -) -if(SPDLOG_BUILD_TESTING) - # Include CTest conditionally since it will enable BUILD_TESTING. - include(CTest) -endif() target_include_directories( spdlog @@ -83,7 +68,8 @@ if(SPDLOG_BUILD_EXAMPLES) add_subdirectory(example) endif() -if(SPDLOG_BUILD_TESTING) +if(SPDLOG_BUILD_TESTS) + include(CTest) add_subdirectory(tests) endif() From bbc859ca19eafa7bfca8372740bf368079b02082 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 2 Dec 2018 15:25:03 +0200 Subject: [PATCH 55/83] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 68d5b3c4..2a0a35b7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -104,7 +104,7 @@ script: -DCMAKE_CXX_STANDARD=$CPP \ -DSPDLOG_BUILD_EXAMPLES=ON \ -DSPDLOG_BUILD_BENCH=OFF \ - -DBUILD_BUILD_TESTS=ON \ + -DSPDLOG_BUILD_TESTS=ON \ -DSPDLOG_SANITIZE_ADDRESS=$ASAN \ -DSPDLOG_SANITIZE_THREAD=$TSAN - make VERBOSE=1 -j2 From 7442d720f451751074eb3df695df7f794ff21045 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 2 Dec 2018 16:30:07 +0200 Subject: [PATCH 56/83] Update appveyor.yml --- appveyor.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index d7843cde..d7ce7a31 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,4 +29,7 @@ build_script: cmake .. -G %GENERATOR% -DCMAKE_BUILD_TYPE=%BUILD_TYPE% -DSPDLOG_BUILD_BENCH=OFF cmake --build . --config %BUILD_TYPE% -test: off + +test_script: +- cmd: cd build +- ctest -VV -C "%BUILD_TYPE%" From 5191948b64fd098a5bd31c9c2b680475a6b3e599 Mon Sep 17 00:00:00 2001 From: Gabi Melman Date: Sun, 2 Dec 2018 16:40:02 +0200 Subject: [PATCH 57/83] Update appveyor.yml --- appveyor.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index d7ce7a31..98ce69ba 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -31,5 +31,4 @@ build_script: cmake --build . --config %BUILD_TYPE% test_script: -- cmd: cd build - ctest -VV -C "%BUILD_TYPE%" From d8eb0558e918a01aa1ae1d96cdc7c5ec2b24c03c Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 2 Dec 2018 17:13:50 +0200 Subject: [PATCH 58/83] Fix test for mingw --- tests/test_misc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 9e097a45..342b3dac 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -86,7 +86,7 @@ TEST_CASE("periodic flush", "[periodic_flush]") auto test_sink = std::static_pointer_cast(logger->sinks()[0]); spdlog::flush_every(std::chrono::seconds(1)); - std::this_thread::sleep_for(std::chrono::milliseconds(1100)); + std::this_thread::sleep_for(std::chrono::milliseconds(1500)); REQUIRE(test_sink->flush_counter() == 1); spdlog::flush_every(std::chrono::seconds(0)); spdlog::drop_all(); From fcb661d0e9e38498ec50138f9eb2c27850a300c2 Mon Sep 17 00:00:00 2001 From: gabime Date: Sun, 2 Dec 2018 19:04:44 +0200 Subject: [PATCH 59/83] Fixed tests --- tests/test_misc.cpp | 2 +- tests/test_registry.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_misc.cpp b/tests/test_misc.cpp index 342b3dac..1b880835 100644 --- a/tests/test_misc.cpp +++ b/tests/test_misc.cpp @@ -86,7 +86,7 @@ TEST_CASE("periodic flush", "[periodic_flush]") auto test_sink = std::static_pointer_cast(logger->sinks()[0]); spdlog::flush_every(std::chrono::seconds(1)); - std::this_thread::sleep_for(std::chrono::milliseconds(1500)); + std::this_thread::sleep_for(std::chrono::milliseconds(1250)); REQUIRE(test_sink->flush_counter() == 1); spdlog::flush_every(std::chrono::seconds(0)); spdlog::drop_all(); diff --git a/tests/test_registry.cpp b/tests/test_registry.cpp index d306dba2..bd326ef0 100644 --- a/tests/test_registry.cpp +++ b/tests/test_registry.cpp @@ -110,4 +110,5 @@ TEST_CASE("disable automatic registration", "[registry]") REQUIRE(logger1->level() == log_level); REQUIRE(logger2->level() == log_level); spdlog::set_level(spdlog::level::info); + spdlog::set_automatic_registration(true); } From ec3f2b76b0cfdb55134e5d32aef1b0d3612f003c Mon Sep 17 00:00:00 2001 From: gabime Date: Tue, 4 Dec 2018 12:28:21 +0200 Subject: [PATCH 60/83] Strip path from __FILE__ in SPDLOG_TRACE macros --- include/spdlog/common.h | 17 ++++++++++++++++- include/spdlog/spdlog.h | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index 157ce8e9..ff76ccc3 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -24,6 +25,8 @@ #include "spdlog/details/null_mutex.h" +#include "spdlog/fmt/fmt.h" + // visual studio upto 2013 does not support noexcept nor constexpr #if defined(_MSC_VER) && (_MSC_VER < 1900) #define SPDLOG_NOEXCEPT throw() @@ -48,7 +51,19 @@ #endif #endif -#include "spdlog/fmt/fmt.h" + +// Get the basename of __FILE__ (at compile time if possible) +#if FMT_HAS_FEATURE(__builtin_strrchr) +#define SPDLOG_STRRCHR(str, sep) __builtin_strrchr(str, sep) +#else +#define SPDLOG_STRRCHR(str, sep) strrchr(str, sep) +#endif //__builtin_strrchr not defined + +#ifdef _WIN32 +#define SPDLOG_FILE_BASENAME SPDLOG_STRRCHR("\\" __FILE__, '\\') + 1 +#else +#define SPDLOG_FILE_BASENAME SPDLOG_STRRCHR("/" __FILE__, '/') + 1 +#endif namespace spdlog { diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index f745a5fe..506242ff 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -314,7 +314,7 @@ inline void critical(const wchar_t *fmt, const Args &... args) // #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE -#define SPDLOG_LOGGER_TRACE(logger, ...) logger->log(spdlog::source_loc{__FILE__, __LINE__}, spdlog::level::trace, __VA_ARGS__) +#define SPDLOG_LOGGER_TRACE(logger, ...) logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME, __LINE__}, spdlog::level::trace, __VA_ARGS__) #define SPDLOG_TRACE(...) SPDLOG_LOGGER_TRACE(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_TRACE(logger, ...) (void)0 From bd6d88b8843b740da907cefc528399575ba5b0d8 Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 5 Dec 2018 18:03:56 +0200 Subject: [PATCH 61/83] Removed uneeded locale include --- include/spdlog/logger.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 1b762429..c7c2966f 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -22,7 +22,6 @@ #include "spdlog/formatter.h" #include "spdlog/sinks/sink.h" -#include #include #include #include From 8d6086da4856df510657ffe4ef6b894e902b4b83 Mon Sep 17 00:00:00 2001 From: Budo Zindovic Date: Thu, 6 Dec 2018 01:30:07 +0100 Subject: [PATCH 62/83] Corrected the text alignment in the example I've changed the alignment character in the example to illustrate left alignment of text. --- example/example.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/example.cpp b/example/example.cpp index 026004b8..345f8bd1 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -31,7 +31,7 @@ int main(int, char *[]) spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); spdlog::info("Support for floats {:03.2f}", 1.23456); spdlog::info("Positional args are {1} {0}..", "too", "supported"); - spdlog::info("{:>8} aligned, {:>8} aligned", "right", "left"); + spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left"); // Runtime log levels spdlog::set_level(spdlog::level::info); // Set global log level to info From 058d2d1bd4beeada1ec7e725742e2d7a1964dce2 Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 6 Dec 2018 11:37:49 +0200 Subject: [PATCH 63/83] Use default pattern in latency test --- bench/latency.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bench/latency.cpp b/bench/latency.cpp index 25b99f5c..67274b62 100644 --- a/bench/latency.cpp +++ b/bench/latency.cpp @@ -73,8 +73,7 @@ void bench_disabled_macro(benchmark::State &state, std::shared_ptr Date: Thu, 6 Dec 2018 13:27:00 +0200 Subject: [PATCH 64/83] SPDLOG_TRACE to check log level before calling the logger --- include/spdlog/common.h | 4 ++-- include/spdlog/spdlog.h | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/include/spdlog/common.h b/include/spdlog/common.h index ff76ccc3..d066e903 100644 --- a/include/spdlog/common.h +++ b/include/spdlog/common.h @@ -60,9 +60,9 @@ #endif //__builtin_strrchr not defined #ifdef _WIN32 -#define SPDLOG_FILE_BASENAME SPDLOG_STRRCHR("\\" __FILE__, '\\') + 1 +#define SPDLOG_FILE_BASENAME(file) SPDLOG_STRRCHR("\\" file, '\\') + 1 #else -#define SPDLOG_FILE_BASENAME SPDLOG_STRRCHR("/" __FILE__, '/') + 1 +#define SPDLOG_FILE_BASENAME(file) SPDLOG_STRRCHR("/" file, '/') + 1 #endif namespace spdlog { diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 506242ff..408c86e2 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -314,7 +314,9 @@ inline void critical(const wchar_t *fmt, const Args &... args) // #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE -#define SPDLOG_LOGGER_TRACE(logger, ...) logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME, __LINE__}, spdlog::level::trace, __VA_ARGS__) +#define SPDLOG_LOGGER_TRACE(logger, ...)\ + if(logger->should_log(spdlog::level::trace))\ + logger->log(spdlog::source_loc{SPDLOG_FILE_BASENAME(__FILE__), __LINE__}, spdlog::level::trace, __VA_ARGS__) #define SPDLOG_TRACE(...) SPDLOG_LOGGER_TRACE(spdlog::default_logger_raw(), __VA_ARGS__) #else #define SPDLOG_LOGGER_TRACE(logger, ...) (void)0 From ce8cf1e152b3b51f4121f6b58ddcf3797090a1f4 Mon Sep 17 00:00:00 2001 From: Jerome Meyer Date: Thu, 6 Dec 2018 16:06:01 -0500 Subject: [PATCH 65/83] Fix typos --- include/spdlog/details/pattern_formatter.h | 5 ++--- include/spdlog/logger.h | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/include/spdlog/details/pattern_formatter.h b/include/spdlog/details/pattern_formatter.h index 429a6c3c..9bc34a55 100644 --- a/include/spdlog/details/pattern_formatter.h +++ b/include/spdlog/details/pattern_formatter.h @@ -760,7 +760,6 @@ public: class ch_formatter final : public flag_formatter { -public: public: explicit ch_formatter(char ch) : ch_(ch) @@ -825,7 +824,7 @@ public: } }; -// print soruce location +// print source location class source_location_formatter final : public flag_formatter { public: @@ -854,7 +853,7 @@ public: } } }; -// print soruce filename +// print source filename class source_filename_formatter final : public flag_formatter { public: diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index c7c2966f..3dbaaa64 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -78,7 +78,7 @@ public: void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); template - void log(source_loc soruce, level::level_enum lvl, const wchar_t *fmt, const Args &... args); + void log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args); template void trace(const wchar_t *fmt, const Args &... args); From 084bc72d90ccc829b8605297cbef4ef6cc3093b9 Mon Sep 17 00:00:00 2001 From: Carsten Neumann Date: Mon, 17 Dec 2018 10:18:16 -0600 Subject: [PATCH 66/83] Fix handling of external fmt lib Using an external fmt lib should cause the spdlog::spdlog target to have a dependency on fmt lib - so that a consuming project does not need to call find_package(fmt) and target_link_libraries(... fmt::fmt). To this end a new cmake option SPDLOG_FMT_EXTERNAL is introduced which makes spdlog depend on fmt lib and defines the SPDLOG_FMT_EXTERNAL macro to avoid using the bundled fmt lib. The value of SPDLOG_FMT_EXTERNAL is also stored in the installed spdlogConfig.cmake and if it is ON find_dependency() is used to ensure the fmt::fmt target is imported. --- CMakeLists.txt | 26 +++++++++++++++++++------- cmake/Config.cmake.in | 7 +++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3a0531dd..e1d96563 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,7 +53,11 @@ endif() option(SPDLOG_BUILD_EXAMPLES "Build examples" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_BUILD_BENCH "Build benchmarks" ${SPDLOG_MASTER_PROJECT}) option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT}) +option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF) +if(SPDLOG_FMT_EXTERNAL) + find_package(fmt REQUIRED CONFIG) +endif() target_include_directories( spdlog @@ -62,6 +66,11 @@ target_include_directories( "$" ) +if(SPDLOG_FMT_EXTERNAL) + target_compile_definitions(spdlog INTERFACE SPDLOG_FMT_EXTERNAL) + target_link_libraries(spdlog INTERFACE fmt::fmt) +endif() + set(HEADER_BASE "${CMAKE_CURRENT_SOURCE_DIR}/include") if(SPDLOG_BUILD_EXAMPLES) @@ -85,7 +94,8 @@ set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") set(include_install_dir "${CMAKE_INSTALL_INCLUDEDIR}") set(pkgconfig_install_dir "${CMAKE_INSTALL_LIBDIR}/pkgconfig") set(version_config "${CMAKE_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake") -set(project_config "${PROJECT_NAME}Config.cmake") +set(project_config "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake") +set(targets_config "${PROJECT_NAME}Targets.cmake") set(pkg_config "${CMAKE_BINARY_DIR}/${PROJECT_NAME}.pc") set(targets_export_name "${PROJECT_NAME}Targets") set(namespace "${PROJECT_NAME}::") @@ -98,6 +108,8 @@ write_basic_package_version_file( # configure pkg config file configure_file("cmake/spdlog.pc.in" "${pkg_config}" @ONLY) +# configure spdlogConfig.cmake file +configure_file("cmake/Config.cmake.in" "${project_config}" @ONLY) # install targets install( @@ -111,9 +123,9 @@ install( DESTINATION "${include_install_dir}" ) -# install project version file +# install project config and version file install( - FILES "${version_config}" + FILES "${project_config}" "${version_config}" DESTINATION "${config_install_dir}" ) @@ -123,19 +135,19 @@ install( DESTINATION "${pkgconfig_install_dir}" ) -# install project config file +# install targets config file install( EXPORT "${targets_export_name}" NAMESPACE "${namespace}" DESTINATION "${config_install_dir}" - FILE ${project_config} + FILE ${targets_config} ) -# export build directory config file +# export build directory targets file export( EXPORT ${targets_export_name} NAMESPACE "${namespace}" - FILE ${project_config} + FILE ${targets_config} ) # register project in CMake user registry diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in index ba0b36f2..0b0fd119 100644 --- a/cmake/Config.cmake.in +++ b/cmake/Config.cmake.in @@ -21,4 +21,11 @@ # * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ # *************************************************************************/ +set(SPDLOG_FMT_EXTERNAL @SPDLOG_FMT_EXTERNAL@) + include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") + +if(SPDLOG_FMT_EXTERNAL) + include(CMakeFindDependencyMacro) + find_dependency(fmt CONFIG) +endif() From 2ac42c0d14b1eb738719cb131a6006ad508d102e Mon Sep 17 00:00:00 2001 From: gabime Date: Tue, 8 Jan 2019 17:09:07 +0200 Subject: [PATCH 67/83] Bumped fmt to version 5.3.0 --- include/spdlog/fmt/bundled/chrono.h | 452 +++++++ include/spdlog/fmt/bundled/color.h | 577 +++++++++ include/spdlog/fmt/bundled/core.h | 854 ++++++------- include/spdlog/fmt/bundled/format-inl.h | 504 +++++--- include/spdlog/fmt/bundled/format.h | 1465 ++++++++++------------- include/spdlog/fmt/bundled/locale.h | 77 ++ include/spdlog/fmt/bundled/ostream.h | 20 +- include/spdlog/fmt/bundled/posix.h | 4 +- include/spdlog/fmt/bundled/printf.h | 367 ++++-- include/spdlog/fmt/bundled/time.h | 38 +- 10 files changed, 2767 insertions(+), 1591 deletions(-) create mode 100644 include/spdlog/fmt/bundled/chrono.h create mode 100644 include/spdlog/fmt/bundled/color.h create mode 100644 include/spdlog/fmt/bundled/locale.h diff --git a/include/spdlog/fmt/bundled/chrono.h b/include/spdlog/fmt/bundled/chrono.h new file mode 100644 index 00000000..209cdc25 --- /dev/null +++ b/include/spdlog/fmt/bundled/chrono.h @@ -0,0 +1,452 @@ +// Formatting library for C++ - chrono support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CHRONO_H_ +#define FMT_CHRONO_H_ + +#include "format.h" +#include "locale.h" + +#include +#include +#include +#include + +FMT_BEGIN_NAMESPACE + +namespace internal{ + +enum class numeric_system { + standard, + // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale. + alternative +}; + +// Parses a put_time-like format string and invokes handler actions. +template +FMT_CONSTEXPR const Char *parse_chrono_format( + const Char *begin, const Char *end, Handler &&handler) { + auto ptr = begin; + while (ptr != end) { + auto c = *ptr; + if (c == '}') break; + if (c != '%') { + ++ptr; + continue; + } + if (begin != ptr) + handler.on_text(begin, ptr); + ++ptr; // consume '%' + if (ptr == end) + throw format_error("invalid format"); + c = *ptr++; + switch (c) { + case '%': + handler.on_text(ptr - 1, ptr); + break; + case 'n': { + const char newline[] = "\n"; + handler.on_text(newline, newline + 1); + break; + } + case 't': { + const char tab[] = "\t"; + handler.on_text(tab, tab + 1); + break; + } + // Day of the week: + case 'a': + handler.on_abbr_weekday(); + break; + case 'A': + handler.on_full_weekday(); + break; + case 'w': + handler.on_dec0_weekday(numeric_system::standard); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::standard); + break; + // Month: + case 'b': + handler.on_abbr_month(); + break; + case 'B': + handler.on_full_month(); + break; + // Hour, minute, second: + case 'H': + handler.on_24_hour(numeric_system::standard); + break; + case 'I': + handler.on_12_hour(numeric_system::standard); + break; + case 'M': + handler.on_minute(numeric_system::standard); + break; + case 'S': + handler.on_second(numeric_system::standard); + break; + // Other: + case 'c': + handler.on_datetime(numeric_system::standard); + break; + case 'x': + handler.on_loc_date(numeric_system::standard); + break; + case 'X': + handler.on_loc_time(numeric_system::standard); + break; + case 'D': + handler.on_us_date(); + break; + case 'F': + handler.on_iso_date(); + break; + case 'r': + handler.on_12_hour_time(); + break; + case 'R': + handler.on_24_hour_time(); + break; + case 'T': + handler.on_iso_time(); + break; + case 'p': + handler.on_am_pm(); + break; + case 'z': + handler.on_utc_offset(); + break; + case 'Z': + handler.on_tz_name(); + break; + // Alternative representation: + case 'E': { + if (ptr == end) + throw format_error("invalid format"); + c = *ptr++; + switch (c) { + case 'c': + handler.on_datetime(numeric_system::alternative); + break; + case 'x': + handler.on_loc_date(numeric_system::alternative); + break; + case 'X': + handler.on_loc_time(numeric_system::alternative); + break; + default: + throw format_error("invalid format"); + } + break; + } + case 'O': + if (ptr == end) + throw format_error("invalid format"); + c = *ptr++; + switch (c) { + case 'w': + handler.on_dec0_weekday(numeric_system::alternative); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::alternative); + break; + case 'H': + handler.on_24_hour(numeric_system::alternative); + break; + case 'I': + handler.on_12_hour(numeric_system::alternative); + break; + case 'M': + handler.on_minute(numeric_system::alternative); + break; + case 'S': + handler.on_second(numeric_system::alternative); + break; + default: + throw format_error("invalid format"); + } + break; + default: + throw format_error("invalid format"); + } + begin = ptr; + } + if (begin != ptr) + handler.on_text(begin, ptr); + return ptr; +} + +struct chrono_format_checker { + void report_no_date() { throw format_error("no date"); } + + template + void on_text(const Char *, const Char *) {} + void on_abbr_weekday() { report_no_date(); } + void on_full_weekday() { report_no_date(); } + void on_dec0_weekday(numeric_system) { report_no_date(); } + void on_dec1_weekday(numeric_system) { report_no_date(); } + void on_abbr_month() { report_no_date(); } + void on_full_month() { report_no_date(); } + void on_24_hour(numeric_system) {} + void on_12_hour(numeric_system) {} + void on_minute(numeric_system) {} + void on_second(numeric_system) {} + void on_datetime(numeric_system) { report_no_date(); } + void on_loc_date(numeric_system) { report_no_date(); } + void on_loc_time(numeric_system) { report_no_date(); } + void on_us_date() { report_no_date(); } + void on_iso_date() { report_no_date(); } + void on_12_hour_time() {} + void on_24_hour_time() {} + void on_iso_time() {} + void on_am_pm() {} + void on_utc_offset() { report_no_date(); } + void on_tz_name() { report_no_date(); } +}; + +template +inline int to_int(Int value) { + FMT_ASSERT(value >= (std::numeric_limits::min)() && + value <= (std::numeric_limits::max)(), "invalid value"); + return static_cast(value); +} + +template +struct chrono_formatter { + FormatContext &context; + OutputIt out; + std::chrono::seconds s; + std::chrono::milliseconds ms; + + typedef typename FormatContext::char_type char_type; + + explicit chrono_formatter(FormatContext &ctx, OutputIt o) + : context(ctx), out(o) {} + + int hour() const { return to_int((s.count() / 3600) % 24); } + + int hour12() const { + auto hour = to_int((s.count() / 3600) % 12); + return hour > 0 ? hour : 12; + } + + int minute() const { return to_int((s.count() / 60) % 60); } + int second() const { return to_int(s.count() % 60); } + + std::tm time() const { + auto time = std::tm(); + time.tm_hour = hour(); + time.tm_min = minute(); + time.tm_sec = second(); + return time; + } + + void write(int value, int width) { + typedef typename int_traits::main_type main_type; + main_type n = to_unsigned(value); + int num_digits = internal::count_digits(n); + if (width > num_digits) + out = std::fill_n(out, width - num_digits, '0'); + out = format_decimal(out, n, num_digits); + } + + void format_localized(const tm &time, const char *format) { + auto locale = context.locale().template get(); + auto &facet = std::use_facet>(locale); + std::basic_ostringstream os; + os.imbue(locale); + facet.put(os, os, ' ', &time, format, format + std::strlen(format)); + auto str = os.str(); + std::copy(str.begin(), str.end(), out); + } + + void on_text(const char_type *begin, const char_type *end) { + std::copy(begin, end, out); + } + + // These are not implemented because durations don't have date information. + void on_abbr_weekday() {} + void on_full_weekday() {} + void on_dec0_weekday(numeric_system) {} + void on_dec1_weekday(numeric_system) {} + void on_abbr_month() {} + void on_full_month() {} + void on_datetime(numeric_system) {} + void on_loc_date(numeric_system) {} + void on_loc_time(numeric_system) {} + void on_us_date() {} + void on_iso_date() {} + void on_utc_offset() {} + void on_tz_name() {} + + void on_24_hour(numeric_system ns) { + if (ns == numeric_system::standard) + return write(hour(), 2); + auto time = tm(); + time.tm_hour = hour(); + format_localized(time, "%OH"); + } + + void on_12_hour(numeric_system ns) { + if (ns == numeric_system::standard) + return write(hour12(), 2); + auto time = tm(); + time.tm_hour = hour(); + format_localized(time, "%OI"); + } + + void on_minute(numeric_system ns) { + if (ns == numeric_system::standard) + return write(minute(), 2); + auto time = tm(); + time.tm_min = minute(); + format_localized(time, "%OM"); + } + + void on_second(numeric_system ns) { + if (ns == numeric_system::standard) { + write(second(), 2); + if (ms != std::chrono::milliseconds(0)) { + *out++ = '.'; + write(to_int(ms.count()), 3); + } + return; + } + auto time = tm(); + time.tm_sec = second(); + format_localized(time, "%OS"); + } + + void on_12_hour_time() { format_localized(time(), "%r"); } + + void on_24_hour_time() { + write(hour(), 2); + *out++ = ':'; + write(minute(), 2); + } + + void on_iso_time() { + on_24_hour_time(); + *out++ = ':'; + write(second(), 2); + } + + void on_am_pm() { format_localized(time(), "%p"); } +}; +} // namespace internal + +template FMT_CONSTEXPR const char *get_units() { + return FMT_NULL; +} +template <> FMT_CONSTEXPR const char *get_units() { return "as"; } +template <> FMT_CONSTEXPR const char *get_units() { return "fs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ps"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ns"; } +template <> FMT_CONSTEXPR const char *get_units() { return "µs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ms"; } +template <> FMT_CONSTEXPR const char *get_units() { return "cs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ds"; } +template <> FMT_CONSTEXPR const char *get_units>() { return "s"; } +template <> FMT_CONSTEXPR const char *get_units() { return "das"; } +template <> FMT_CONSTEXPR const char *get_units() { return "hs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ks"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ms"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Gs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ts"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ps"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Es"; } +template <> FMT_CONSTEXPR const char *get_units>() { + return "m"; +} +template <> FMT_CONSTEXPR const char *get_units>() { + return "h"; +} + +template +struct formatter, Char> { + private: + align_spec spec; + internal::arg_ref width_ref; + mutable basic_string_view format_str; + typedef std::chrono::duration duration; + + struct spec_handler { + formatter &f; + basic_parse_context &context; + + typedef internal::arg_ref arg_ref_type; + + template + FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(internal::auto_id) { + return arg_ref_type(context.next_arg_id()); + } + + void on_error(const char *msg) { throw format_error(msg); } + void on_fill(Char fill) { f.spec.fill_ = fill; } + void on_align(alignment align) { f.spec.align_ = align; } + void on_width(unsigned width) { f.spec.width_ = width; } + + template + void on_dynamic_width(Id arg_id) { + f.width_ref = make_arg_ref(arg_id); + } + }; + + public: + formatter() : spec() {} + + FMT_CONSTEXPR auto parse(basic_parse_context &ctx) + -> decltype(ctx.begin()) { + auto begin = ctx.begin(), end = ctx.end(); + if (begin == end) return begin; + spec_handler handler{*this, ctx}; + begin = internal::parse_align(begin, end, handler); + if (begin == end) return begin; + begin = internal::parse_width(begin, end, handler); + end = parse_chrono_format(begin, end, internal::chrono_format_checker()); + format_str = basic_string_view(&*begin, internal::to_unsigned(end - begin)); + return end; + } + + template + auto format(const duration &d, FormatContext &ctx) + -> decltype(ctx.out()) { + auto begin = format_str.begin(), end = format_str.end(); + memory_buffer buf; + typedef output_range range; + basic_writer w(range(ctx.out())); + if (begin == end || *begin == '}') { + if (const char *unit = get_units()) + format_to(buf, "{}{}", d.count(), unit); + else if (Period::den == 1) + format_to(buf, "{}[{}]s", d.count(), Period::num); + else + format_to(buf, "{}[{}/{}]s", d.count(), Period::num, Period::den); + internal::handle_dynamic_spec( + spec.width_, width_ref, ctx); + } else { + auto out = std::back_inserter(buf); + internal::chrono_formatter f(ctx, out); + f.s = std::chrono::duration_cast(d); + f.ms = std::chrono::duration_cast(d - f.s); + parse_chrono_format(begin, end, f); + } + w.write(buf.data(), buf.size(), spec); + return w.out(); + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/include/spdlog/fmt/bundled/color.h b/include/spdlog/fmt/bundled/color.h new file mode 100644 index 00000000..5db861c9 --- /dev/null +++ b/include/spdlog/fmt/bundled/color.h @@ -0,0 +1,577 @@ +// Formatting library for C++ - color support +// +// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COLOR_H_ +#define FMT_COLOR_H_ + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +#ifdef FMT_DEPRECATED_COLORS + +// color and (v)print_colored are deprecated. +enum color { black, red, green, yellow, blue, magenta, cyan, white }; +FMT_API void vprint_colored(color c, string_view format, format_args args); +FMT_API void vprint_colored(color c, wstring_view format, wformat_args args); +template +inline void print_colored(color c, string_view format_str, + const Args & ... args) { + vprint_colored(c, format_str, make_format_args(args...)); +} +template +inline void print_colored(color c, wstring_view format_str, + const Args & ... args) { + vprint_colored(c, format_str, make_format_args(args...)); +} + +inline void vprint_colored(color c, string_view format, format_args args) { + char escape[] = "\x1b[30m"; + escape[3] = static_cast('0' + c); + std::fputs(escape, stdout); + vprint(format, args); + std::fputs(internal::data::RESET_COLOR, stdout); +} + +inline void vprint_colored(color c, wstring_view format, wformat_args args) { + wchar_t escape[] = L"\x1b[30m"; + escape[3] = static_cast('0' + c); + std::fputws(escape, stdout); + vprint(format, args); + std::fputws(internal::data::WRESET_COLOR, stdout); +} + +#else + +enum class color : uint32_t { + alice_blue = 0xF0F8FF, // rgb(240,248,255) + antique_white = 0xFAEBD7, // rgb(250,235,215) + aqua = 0x00FFFF, // rgb(0,255,255) + aquamarine = 0x7FFFD4, // rgb(127,255,212) + azure = 0xF0FFFF, // rgb(240,255,255) + beige = 0xF5F5DC, // rgb(245,245,220) + bisque = 0xFFE4C4, // rgb(255,228,196) + black = 0x000000, // rgb(0,0,0) + blanched_almond = 0xFFEBCD, // rgb(255,235,205) + blue = 0x0000FF, // rgb(0,0,255) + blue_violet = 0x8A2BE2, // rgb(138,43,226) + brown = 0xA52A2A, // rgb(165,42,42) + burly_wood = 0xDEB887, // rgb(222,184,135) + cadet_blue = 0x5F9EA0, // rgb(95,158,160) + chartreuse = 0x7FFF00, // rgb(127,255,0) + chocolate = 0xD2691E, // rgb(210,105,30) + coral = 0xFF7F50, // rgb(255,127,80) + cornflower_blue = 0x6495ED, // rgb(100,149,237) + cornsilk = 0xFFF8DC, // rgb(255,248,220) + crimson = 0xDC143C, // rgb(220,20,60) + cyan = 0x00FFFF, // rgb(0,255,255) + dark_blue = 0x00008B, // rgb(0,0,139) + dark_cyan = 0x008B8B, // rgb(0,139,139) + dark_golden_rod = 0xB8860B, // rgb(184,134,11) + dark_gray = 0xA9A9A9, // rgb(169,169,169) + dark_green = 0x006400, // rgb(0,100,0) + dark_khaki = 0xBDB76B, // rgb(189,183,107) + dark_magenta = 0x8B008B, // rgb(139,0,139) + dark_olive_green = 0x556B2F, // rgb(85,107,47) + dark_orange = 0xFF8C00, // rgb(255,140,0) + dark_orchid = 0x9932CC, // rgb(153,50,204) + dark_red = 0x8B0000, // rgb(139,0,0) + dark_salmon = 0xE9967A, // rgb(233,150,122) + dark_sea_green = 0x8FBC8F, // rgb(143,188,143) + dark_slate_blue = 0x483D8B, // rgb(72,61,139) + dark_slate_gray = 0x2F4F4F, // rgb(47,79,79) + dark_turquoise = 0x00CED1, // rgb(0,206,209) + dark_violet = 0x9400D3, // rgb(148,0,211) + deep_pink = 0xFF1493, // rgb(255,20,147) + deep_sky_blue = 0x00BFFF, // rgb(0,191,255) + dim_gray = 0x696969, // rgb(105,105,105) + dodger_blue = 0x1E90FF, // rgb(30,144,255) + fire_brick = 0xB22222, // rgb(178,34,34) + floral_white = 0xFFFAF0, // rgb(255,250,240) + forest_green = 0x228B22, // rgb(34,139,34) + fuchsia = 0xFF00FF, // rgb(255,0,255) + gainsboro = 0xDCDCDC, // rgb(220,220,220) + ghost_white = 0xF8F8FF, // rgb(248,248,255) + gold = 0xFFD700, // rgb(255,215,0) + golden_rod = 0xDAA520, // rgb(218,165,32) + gray = 0x808080, // rgb(128,128,128) + green = 0x008000, // rgb(0,128,0) + green_yellow = 0xADFF2F, // rgb(173,255,47) + honey_dew = 0xF0FFF0, // rgb(240,255,240) + hot_pink = 0xFF69B4, // rgb(255,105,180) + indian_red = 0xCD5C5C, // rgb(205,92,92) + indigo = 0x4B0082, // rgb(75,0,130) + ivory = 0xFFFFF0, // rgb(255,255,240) + khaki = 0xF0E68C, // rgb(240,230,140) + lavender = 0xE6E6FA, // rgb(230,230,250) + lavender_blush = 0xFFF0F5, // rgb(255,240,245) + lawn_green = 0x7CFC00, // rgb(124,252,0) + lemon_chiffon = 0xFFFACD, // rgb(255,250,205) + light_blue = 0xADD8E6, // rgb(173,216,230) + light_coral = 0xF08080, // rgb(240,128,128) + light_cyan = 0xE0FFFF, // rgb(224,255,255) + light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210) + light_gray = 0xD3D3D3, // rgb(211,211,211) + light_green = 0x90EE90, // rgb(144,238,144) + light_pink = 0xFFB6C1, // rgb(255,182,193) + light_salmon = 0xFFA07A, // rgb(255,160,122) + light_sea_green = 0x20B2AA, // rgb(32,178,170) + light_sky_blue = 0x87CEFA, // rgb(135,206,250) + light_slate_gray = 0x778899, // rgb(119,136,153) + light_steel_blue = 0xB0C4DE, // rgb(176,196,222) + light_yellow = 0xFFFFE0, // rgb(255,255,224) + lime = 0x00FF00, // rgb(0,255,0) + lime_green = 0x32CD32, // rgb(50,205,50) + linen = 0xFAF0E6, // rgb(250,240,230) + magenta = 0xFF00FF, // rgb(255,0,255) + maroon = 0x800000, // rgb(128,0,0) + medium_aquamarine = 0x66CDAA, // rgb(102,205,170) + medium_blue = 0x0000CD, // rgb(0,0,205) + medium_orchid = 0xBA55D3, // rgb(186,85,211) + medium_purple = 0x9370DB, // rgb(147,112,219) + medium_sea_green = 0x3CB371, // rgb(60,179,113) + medium_slate_blue = 0x7B68EE, // rgb(123,104,238) + medium_spring_green = 0x00FA9A, // rgb(0,250,154) + medium_turquoise = 0x48D1CC, // rgb(72,209,204) + medium_violet_red = 0xC71585, // rgb(199,21,133) + midnight_blue = 0x191970, // rgb(25,25,112) + mint_cream = 0xF5FFFA, // rgb(245,255,250) + misty_rose = 0xFFE4E1, // rgb(255,228,225) + moccasin = 0xFFE4B5, // rgb(255,228,181) + navajo_white = 0xFFDEAD, // rgb(255,222,173) + navy = 0x000080, // rgb(0,0,128) + old_lace = 0xFDF5E6, // rgb(253,245,230) + olive = 0x808000, // rgb(128,128,0) + olive_drab = 0x6B8E23, // rgb(107,142,35) + orange = 0xFFA500, // rgb(255,165,0) + orange_red = 0xFF4500, // rgb(255,69,0) + orchid = 0xDA70D6, // rgb(218,112,214) + pale_golden_rod = 0xEEE8AA, // rgb(238,232,170) + pale_green = 0x98FB98, // rgb(152,251,152) + pale_turquoise = 0xAFEEEE, // rgb(175,238,238) + pale_violet_red = 0xDB7093, // rgb(219,112,147) + papaya_whip = 0xFFEFD5, // rgb(255,239,213) + peach_puff = 0xFFDAB9, // rgb(255,218,185) + peru = 0xCD853F, // rgb(205,133,63) + pink = 0xFFC0CB, // rgb(255,192,203) + plum = 0xDDA0DD, // rgb(221,160,221) + powder_blue = 0xB0E0E6, // rgb(176,224,230) + purple = 0x800080, // rgb(128,0,128) + rebecca_purple = 0x663399, // rgb(102,51,153) + red = 0xFF0000, // rgb(255,0,0) + rosy_brown = 0xBC8F8F, // rgb(188,143,143) + royal_blue = 0x4169E1, // rgb(65,105,225) + saddle_brown = 0x8B4513, // rgb(139,69,19) + salmon = 0xFA8072, // rgb(250,128,114) + sandy_brown = 0xF4A460, // rgb(244,164,96) + sea_green = 0x2E8B57, // rgb(46,139,87) + sea_shell = 0xFFF5EE, // rgb(255,245,238) + sienna = 0xA0522D, // rgb(160,82,45) + silver = 0xC0C0C0, // rgb(192,192,192) + sky_blue = 0x87CEEB, // rgb(135,206,235) + slate_blue = 0x6A5ACD, // rgb(106,90,205) + slate_gray = 0x708090, // rgb(112,128,144) + snow = 0xFFFAFA, // rgb(255,250,250) + spring_green = 0x00FF7F, // rgb(0,255,127) + steel_blue = 0x4682B4, // rgb(70,130,180) + tan = 0xD2B48C, // rgb(210,180,140) + teal = 0x008080, // rgb(0,128,128) + thistle = 0xD8BFD8, // rgb(216,191,216) + tomato = 0xFF6347, // rgb(255,99,71) + turquoise = 0x40E0D0, // rgb(64,224,208) + violet = 0xEE82EE, // rgb(238,130,238) + wheat = 0xF5DEB3, // rgb(245,222,179) + white = 0xFFFFFF, // rgb(255,255,255) + white_smoke = 0xF5F5F5, // rgb(245,245,245) + yellow = 0xFFFF00, // rgb(255,255,0) + yellow_green = 0x9ACD32 // rgb(154,205,50) +}; // enum class color + +enum class terminal_color : uint8_t { + black = 30, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + bright_black = 90, + bright_red, + bright_green, + bright_yellow, + bright_blue, + bright_magenta, + bright_cyan, + bright_white +}; // enum class terminal_color + +enum class emphasis : uint8_t { + bold = 1, + italic = 1 << 1, + underline = 1 << 2, + strikethrough = 1 << 3 +}; // enum class emphasis + +// rgb is a struct for red, green and blue colors. +// We use rgb as name because some editors will show it as color direct in the +// editor. +struct rgb { + FMT_CONSTEXPR_DECL rgb() : r(0), g(0), b(0) {} + FMT_CONSTEXPR_DECL rgb(uint8_t r_, uint8_t g_, uint8_t b_) + : r(r_), g(g_), b(b_) {} + FMT_CONSTEXPR_DECL rgb(uint32_t hex) + : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b((hex) & 0xFF) {} + FMT_CONSTEXPR_DECL rgb(color hex) + : r((uint32_t(hex) >> 16) & 0xFF), g((uint32_t(hex) >> 8) & 0xFF), + b(uint32_t(hex) & 0xFF) {} + uint8_t r; + uint8_t g; + uint8_t b; +}; + +namespace internal { + +// color is a struct of either a rgb color or a terminal color. +struct color_type { + FMT_CONSTEXPR color_type() FMT_NOEXCEPT + : is_rgb(), value{} {} + FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT + : is_rgb(true), value{} { + value.rgb_color = static_cast(rgb_color); + } + FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT + : is_rgb(true), value{} { + value.rgb_color = (static_cast(rgb_color.r) << 16) + | (static_cast(rgb_color.g) << 8) | rgb_color.b; + } + FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT + : is_rgb(), value{} { + value.term_color = static_cast(term_color); + } + bool is_rgb; + union color_union { + uint8_t term_color; + uint32_t rgb_color; + } value; +}; +} // namespace internal + +// Experimental text formatting support. +class text_style { + public: + FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT + : set_foreground_color(), set_background_color(), ems(em) {} + + FMT_CONSTEXPR text_style &operator|=(const text_style &rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + throw format_error("can't OR a terminal color"); + foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + throw format_error("can't OR a terminal color"); + background_color.value.rgb_color |= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) | + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR + text_style operator|(text_style lhs, const text_style &rhs) { + return lhs |= rhs; + } + + FMT_CONSTEXPR text_style &operator&=(const text_style &rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + throw format_error("can't AND a terminal color"); + foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + throw format_error("can't AND a terminal color"); + background_color.value.rgb_color &= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) & + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR + text_style operator&(text_style lhs, const text_style &rhs) { + return lhs &= rhs; + } + + FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT { + return set_foreground_color; + } + FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT { + return set_background_color; + } + FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT { + return static_cast(ems) != 0; + } + FMT_CONSTEXPR internal::color_type get_foreground() const FMT_NOEXCEPT { + assert(has_foreground() && "no foreground specified for this style"); + return foreground_color; + } + FMT_CONSTEXPR internal::color_type get_background() const FMT_NOEXCEPT { + assert(has_background() && "no background specified for this style"); + return background_color; + } + FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT { + assert(has_emphasis() && "no emphasis specified for this style"); + return ems; + } + +private: + FMT_CONSTEXPR text_style(bool is_foreground, + internal::color_type text_color) FMT_NOEXCEPT + : set_foreground_color(), + set_background_color(), + ems() { + if (is_foreground) { + foreground_color = text_color; + set_foreground_color = true; + } else { + background_color = text_color; + set_background_color = true; + } + } + + friend FMT_CONSTEXPR_DECL text_style fg(internal::color_type foreground) + FMT_NOEXCEPT; + friend FMT_CONSTEXPR_DECL text_style bg(internal::color_type background) + FMT_NOEXCEPT; + + internal::color_type foreground_color; + internal::color_type background_color; + bool set_foreground_color; + bool set_background_color; + emphasis ems; +}; + +FMT_CONSTEXPR text_style fg(internal::color_type foreground) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/true, foreground); +} + +FMT_CONSTEXPR text_style bg(internal::color_type background) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/false, background); +} + +FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT { + return text_style(lhs) | rhs; +} + +namespace internal { + +template +struct ansi_color_escape { + FMT_CONSTEXPR ansi_color_escape(internal::color_type text_color, + const char * esc) FMT_NOEXCEPT { + // If we have a terminal color, we need to output another escape code + // sequence. + if (!text_color.is_rgb) { + bool is_background = esc == internal::data::BACKGROUND_COLOR; + uint32_t value = text_color.value.term_color; + // Background ASCII codes are the same as the foreground ones but with + // 10 more. + if (is_background) + value += 10u; + + std::size_t index = 0; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + + if (value >= 100u) { + buffer[index++] = static_cast('1'); + value %= 100u; + } + buffer[index++] = static_cast('0' + value / 10u); + buffer[index++] = static_cast('0' + value % 10u); + + buffer[index++] = static_cast('m'); + buffer[index++] = static_cast('\0'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast(esc[i]); + } + rgb color(text_color.value.rgb_color); + to_esc(color.r, buffer + 7, ';'); + to_esc(color.g, buffer + 11, ';'); + to_esc(color.b, buffer + 15, 'm'); + buffer[19] = static_cast(0); + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT { + uint8_t em_codes[4] = {}; + uint8_t em_bits = static_cast(em); + if (em_bits & static_cast(emphasis::bold)) + em_codes[0] = 1; + if (em_bits & static_cast(emphasis::italic)) + em_codes[1] = 3; + if (em_bits & static_cast(emphasis::underline)) + em_codes[2] = 4; + if (em_bits & static_cast(emphasis::strikethrough)) + em_codes[3] = 9; + + std::size_t index = 0; + for (int i = 0; i < 4; ++i) { + if (!em_codes[i]) + continue; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + buffer[index++] = static_cast('0' + em_codes[i]); + buffer[index++] = static_cast('m'); + } + buffer[index++] = static_cast(0); + } + FMT_CONSTEXPR operator const Char *() const FMT_NOEXCEPT { return buffer; } + +private: + Char buffer[7u + 3u * 4u + 1u]; + + static FMT_CONSTEXPR void to_esc(uint8_t c, Char *out, + char delimiter) FMT_NOEXCEPT { + out[0] = static_cast('0' + c / 100); + out[1] = static_cast('0' + c / 10 % 10); + out[2] = static_cast('0' + c % 10); + out[3] = static_cast(delimiter); + } +}; + +template +FMT_CONSTEXPR ansi_color_escape +make_foreground_color(internal::color_type foreground) FMT_NOEXCEPT { + return ansi_color_escape(foreground, internal::data::FOREGROUND_COLOR); +} + +template +FMT_CONSTEXPR ansi_color_escape +make_background_color(internal::color_type background) FMT_NOEXCEPT { + return ansi_color_escape(background, internal::data::BACKGROUND_COLOR); +} + +template +FMT_CONSTEXPR ansi_color_escape +make_emphasis(emphasis em) FMT_NOEXCEPT { + return ansi_color_escape(em); +} + +template +inline void fputs(const Char *chars, FILE *stream) FMT_NOEXCEPT { + std::fputs(chars, stream); +} + +template <> +inline void fputs(const wchar_t *chars, FILE *stream) FMT_NOEXCEPT { + std::fputws(chars, stream); +} + +template +inline void reset_color(FILE *stream) FMT_NOEXCEPT { + fputs(internal::data::RESET_COLOR, stream); +} + +template <> +inline void reset_color(FILE *stream) FMT_NOEXCEPT { + fputs(internal::data::WRESET_COLOR, stream); +} + +// The following specialiazation disables using std::FILE as a character type, +// which is needed because or else +// fmt::print(stderr, fmt::emphasis::bold, ""); +// would take stderr (a std::FILE *) as the format string. +template <> +struct is_string : std::false_type {}; +template <> +struct is_string : std::false_type {}; +} // namespace internal + +template < + typename S, typename Char = typename internal::char_t::type> +void vprint(std::FILE *f, const text_style &ts, const S &format, + basic_format_args::type> args) { + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + internal::fputs( + internal::make_emphasis(ts.get_emphasis()), f); + } + if (ts.has_foreground()) { + has_style = true; + internal::fputs( + internal::make_foreground_color(ts.get_foreground()), f); + } + if (ts.has_background()) { + has_style = true; + internal::fputs( + internal::make_background_color(ts.get_background()), f); + } + vprint(f, format, args); + if (has_style) { + internal::reset_color(f); + } +} + +/** + Formats a string and prints it to the specified file stream using ANSI + escape sequences to specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template +typename std::enable_if::value>::type print( + std::FILE *f, const text_style &ts, const String &format_str, + const Args &... args) { + internal::check_format_string(format_str); + typedef typename internal::char_t::type char_t; + typedef typename buffer_context::type context_t; + format_arg_store as{args...}; + vprint(f, ts, format_str, basic_format_args(as)); +} + +/** + Formats a string and prints it to stdout using ANSI escape sequences to + specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template +typename std::enable_if::value>::type print( + const text_style &ts, const String &format_str, + const Args &... args) { + return print(stdout, ts, format_str, args...); +} + +#endif + +FMT_END_NAMESPACE + +#endif // FMT_COLOR_H_ diff --git a/include/spdlog/fmt/bundled/core.h b/include/spdlog/fmt/bundled/core.h index 5912afef..50b79351 100644 --- a/include/spdlog/fmt/bundled/core.h +++ b/include/spdlog/fmt/bundled/core.h @@ -16,7 +16,7 @@ #include // The fmt library version in the form major * 10000 + minor * 100 + patch. -#define FMT_VERSION 50201 +#define FMT_VERSION 50300 #ifdef __has_feature # define FMT_HAS_FEATURE(x) __has_feature(x) @@ -25,7 +25,7 @@ #endif #if defined(__has_include) && !defined(__INTELLISENSE__) && \ - (!defined(__INTEL_COMPILER) || __INTEL_COMPILER >= 1600) + !(defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1600) # define FMT_HAS_INCLUDE(x) __has_include(x) #else # define FMT_HAS_INCLUDE(x) 0 @@ -72,7 +72,7 @@ #ifndef FMT_USE_CONSTEXPR11 # define FMT_USE_CONSTEXPR11 \ - (FMT_MSC_VER >= 1900 || FMT_GCC_VERSION >= 406 || FMT_USE_CONSTEXPR) + (FMT_USE_CONSTEXPR || FMT_GCC_VERSION >= 406 || FMT_MSC_VER >= 1900) #endif #if FMT_USE_CONSTEXPR11 # define FMT_CONSTEXPR11 constexpr @@ -89,9 +89,12 @@ # endif #endif -#if FMT_HAS_FEATURE(cxx_explicit_conversions) || FMT_MSC_VER >= 1800 +#if FMT_HAS_FEATURE(cxx_explicit_conversions) || \ + FMT_GCC_VERSION >= 405 || FMT_MSC_VER >= 1800 +# define FMT_USE_EXPLICIT 1 # define FMT_EXPLICIT explicit #else +# define FMT_USE_EXPLICIT 0 # define FMT_EXPLICIT #endif @@ -104,25 +107,18 @@ # define FMT_NULL NULL # endif #endif - #ifndef FMT_USE_NULLPTR # define FMT_USE_NULLPTR 0 #endif -#if FMT_HAS_CPP_ATTRIBUTE(noreturn) -# define FMT_NORETURN [[noreturn]] -#else -# define FMT_NORETURN -#endif - // Check if exceptions are disabled. -#if defined(__GNUC__) && !defined(__EXCEPTIONS) -# define FMT_EXCEPTIONS 0 -#elif FMT_MSC_VER && !_HAS_EXCEPTIONS -# define FMT_EXCEPTIONS 0 -#endif #ifndef FMT_EXCEPTIONS -# define FMT_EXCEPTIONS 1 +# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ + FMT_MSC_VER && !_HAS_EXCEPTIONS +# define FMT_EXCEPTIONS 0 +# else +# define FMT_EXCEPTIONS 1 +# endif #endif // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). @@ -147,14 +143,6 @@ # endif #endif -// This is needed because GCC still uses throw() in its headers when exceptions -// are disabled. -#if FMT_GCC_VERSION -# define FMT_DTOR_NOEXCEPT FMT_DETECTED_NOEXCEPT -#else -# define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT -#endif - #ifndef FMT_BEGIN_NAMESPACE # if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \ FMT_MSC_VER >= 1900 @@ -187,11 +175,10 @@ (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) # include -# define FMT_USE_STD_STRING_VIEW -#elif (FMT_HAS_INCLUDE() && \ - __cplusplus >= 201402L) +# define FMT_STRING_VIEW std::basic_string_view +#elif FMT_HAS_INCLUDE() && __cplusplus >= 201402L # include -# define FMT_USE_EXPERIMENTAL_STRING_VIEW +# define FMT_STRING_VIEW std::experimental::basic_string_view #endif // std::result_of is defined in in gcc 4.4. @@ -223,18 +210,135 @@ FMT_CONSTEXPR typename std::make_unsigned::type to_unsigned(Int value) { return static_cast::type>(value); } -// A constexpr std::char_traits::length replacement for pre-C++17. -template -FMT_CONSTEXPR size_t length(const Char *s) { - const Char *start = s; - while (*s) ++s; - return s - start; +/** A contiguous memory buffer with an optional growing ability. */ +template +class basic_buffer { + private: + basic_buffer(const basic_buffer &) = delete; + void operator=(const basic_buffer &) = delete; + + T *ptr_; + std::size_t size_; + std::size_t capacity_; + + protected: + // Don't initialize ptr_ since it is not accessed to save a few cycles. + basic_buffer(std::size_t sz) FMT_NOEXCEPT: size_(sz), capacity_(sz) {} + + basic_buffer(T *p = FMT_NULL, std::size_t sz = 0, std::size_t cap = 0) + FMT_NOEXCEPT: ptr_(p), size_(sz), capacity_(cap) {} + + /** Sets the buffer data and capacity. */ + void set(T *buf_data, std::size_t buf_capacity) FMT_NOEXCEPT { + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + /** Increases the buffer capacity to hold at least *capacity* elements. */ + virtual void grow(std::size_t capacity) = 0; + + public: + typedef T value_type; + typedef const T &const_reference; + + virtual ~basic_buffer() {} + + T *begin() FMT_NOEXCEPT { return ptr_; } + T *end() FMT_NOEXCEPT { return ptr_ + size_; } + + /** Returns the size of this buffer. */ + std::size_t size() const FMT_NOEXCEPT { return size_; } + + /** Returns the capacity of this buffer. */ + std::size_t capacity() const FMT_NOEXCEPT { return capacity_; } + + /** Returns a pointer to the buffer data. */ + T *data() FMT_NOEXCEPT { return ptr_; } + + /** Returns a pointer to the buffer data. */ + const T *data() const FMT_NOEXCEPT { return ptr_; } + + /** + Resizes the buffer. If T is a POD type new elements may not be initialized. + */ + void resize(std::size_t new_size) { + reserve(new_size); + size_ = new_size; + } + + /** Clears this buffer. */ + void clear() { size_ = 0; } + + /** Reserves space to store at least *capacity* elements. */ + void reserve(std::size_t new_capacity) { + if (new_capacity > capacity_) + grow(new_capacity); + } + + void push_back(const T &value) { + reserve(size_ + 1); + ptr_[size_++] = value; + } + + /** Appends data to the end of the buffer. */ + template + void append(const U *begin, const U *end); + + T &operator[](std::size_t index) { return ptr_[index]; } + const T &operator[](std::size_t index) const { return ptr_[index]; } +}; + +typedef basic_buffer buffer; +typedef basic_buffer wbuffer; + +// A container-backed buffer. +template +class container_buffer : public basic_buffer { + private: + Container &container_; + + protected: + void grow(std::size_t capacity) FMT_OVERRIDE { + container_.resize(capacity); + this->set(&container_[0], capacity); + } + + public: + explicit container_buffer(Container &c) + : basic_buffer(c.size()), container_(c) {} +}; + +// Extracts a reference to the container from back_insert_iterator. +template +inline Container &get_container(std::back_insert_iterator it) { + typedef std::back_insert_iterator bi_iterator; + struct accessor: bi_iterator { + accessor(bi_iterator iter) : bi_iterator(iter) {} + using bi_iterator::container; + }; + return *accessor(it).container; } -#if FMT_GCC_VERSION -FMT_CONSTEXPR size_t length(const char *s) { return std::strlen(s); } -#endif + +struct error_handler { + FMT_CONSTEXPR error_handler() {} + FMT_CONSTEXPR error_handler(const error_handler &) {} + + // This function is intentionally not constexpr to give a compile-time error. + FMT_API void on_error(const char *message); +}; + +template +struct no_formatter_error : std::false_type {}; } // namespace internal +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 405 +template +struct is_constructible: std::false_type {}; +#else +template +struct is_constructible : std::is_constructible {}; +#endif + /** An implementation of ``std::basic_string_view`` for pre-C++17. It provides a subset of the API. ``fmt::basic_string_view`` is used for format strings even @@ -252,18 +356,6 @@ class basic_string_view { typedef Char char_type; typedef const Char *iterator; - // Standard basic_string_view type. -#if defined(FMT_USE_STD_STRING_VIEW) - typedef std::basic_string_view type; -#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) - typedef std::experimental::basic_string_view type; -#else - struct type { - const char *data() const { return FMT_NULL; } - size_t size() const { return 0; } - }; -#endif - FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(FMT_NULL), size_(0) {} /** Constructs a string reference object from a C string and a size. */ @@ -276,8 +368,8 @@ class basic_string_view { the size with ``std::char_traits::length``. \endrst */ - FMT_CONSTEXPR basic_string_view(const Char *s) - : data_(s), size_(internal::length(s)) {} + basic_string_view(const Char *s) + : data_(s), size_(std::char_traits::length(s)) {} /** Constructs a string reference from a ``std::basic_string`` object. */ template @@ -285,8 +377,10 @@ class basic_string_view { const std::basic_string &s) FMT_NOEXCEPT : data_(s.data()), size_(s.size()) {} - FMT_CONSTEXPR basic_string_view(type s) FMT_NOEXCEPT +#ifdef FMT_STRING_VIEW + FMT_CONSTEXPR basic_string_view(FMT_STRING_VIEW s) FMT_NOEXCEPT : data_(s.data()), size_(s.size()) {} +#endif /** Returns a pointer to the string data. */ FMT_CONSTEXPR const Char *data() const { return data_; } @@ -334,19 +428,68 @@ class basic_string_view { typedef basic_string_view string_view; typedef basic_string_view wstring_view; +/** + \rst + The function ``to_string_view`` adapts non-intrusively any kind of string or + string-like type if the user provides a (possibly templated) overload of + ``to_string_view`` which takes an instance of the string class + ``StringType`` and returns a ``fmt::basic_string_view``. + The conversion function must live in the very same namespace as + ``StringType`` to be picked up by ADL. Non-templated string types + like f.e. QString must return a ``basic_string_view`` with a fixed matching + char type. + + **Example**:: + + namespace my_ns { + inline string_view to_string_view(const my_string &s) { + return {s.data(), s.length()}; + } + } + + std::string message = fmt::format(my_string("The answer is {}"), 42); + \endrst + */ +template +inline basic_string_view + to_string_view(basic_string_view s) { return s; } + +template +inline basic_string_view + to_string_view(const std::basic_string &s) { return s; } + +template +inline basic_string_view to_string_view(const Char *s) { return s; } + +#ifdef FMT_STRING_VIEW +template +inline basic_string_view + to_string_view(FMT_STRING_VIEW s) { return s; } +#endif + +// A base class for compile-time strings. It is defined in the fmt namespace to +// make formatting functions visible via ADL, e.g. format(fmt("{}"), 42). +struct compile_string {}; + +template +struct is_compile_string : std::is_base_of {}; + +template < + typename S, + typename Enable = typename std::enable_if::value>::type> +FMT_CONSTEXPR basic_string_view + to_string_view(const S &s) { return s; } + template class basic_format_arg; template class basic_format_args; -template -struct no_formatter_error : std::false_type {}; - // A formatter for objects of type T. template struct formatter { - static_assert(no_formatter_error::value, + static_assert(internal::no_formatter_error::value, "don't know how to format the type, include fmt/ostream.h if it provides " "an operator<< that should be used"); @@ -358,143 +501,32 @@ struct formatter { }; template -struct convert_to_int { - enum { - value = !std::is_arithmetic::value && std::is_convertible::value - }; -}; +struct convert_to_int: std::integral_constant< + bool, !std::is_arithmetic::value && std::is_convertible::value> {}; namespace internal { -/** A contiguous memory buffer with an optional growing ability. */ -template -class basic_buffer { - private: - basic_buffer(const basic_buffer &) = delete; - void operator=(const basic_buffer &) = delete; - - T *ptr_; - std::size_t size_; - std::size_t capacity_; - - protected: - // Don't initialize ptr_ since it is not accessed to save a few cycles. - basic_buffer(std::size_t sz) FMT_NOEXCEPT: size_(sz), capacity_(sz) {} - - basic_buffer(T *p = FMT_NULL, std::size_t sz = 0, std::size_t cap = 0) - FMT_NOEXCEPT: ptr_(p), size_(sz), capacity_(cap) {} +struct dummy_string_view { typedef void char_type; }; +dummy_string_view to_string_view(...); +using fmt::v5::to_string_view; - /** Sets the buffer data and capacity. */ - void set(T *buf_data, std::size_t buf_capacity) FMT_NOEXCEPT { - ptr_ = buf_data; - capacity_ = buf_capacity; - } - - /** Increases the buffer capacity to hold at least *capacity* elements. */ - virtual void grow(std::size_t capacity) = 0; - - public: - typedef T value_type; - typedef const T &const_reference; - - virtual ~basic_buffer() {} - - T *begin() FMT_NOEXCEPT { return ptr_; } - T *end() FMT_NOEXCEPT { return ptr_ + size_; } - - /** Returns the size of this buffer. */ - std::size_t size() const FMT_NOEXCEPT { return size_; } - - /** Returns the capacity of this buffer. */ - std::size_t capacity() const FMT_NOEXCEPT { return capacity_; } - - /** Returns a pointer to the buffer data. */ - T *data() FMT_NOEXCEPT { return ptr_; } - - /** Returns a pointer to the buffer data. */ - const T *data() const FMT_NOEXCEPT { return ptr_; } - - /** - Resizes the buffer. If T is a POD type new elements may not be initialized. - */ - void resize(std::size_t new_size) { - reserve(new_size); - size_ = new_size; - } - - /** Clears this buffer. */ - void clear() { size_ = 0; } - - /** Reserves space to store at least *capacity* elements. */ - void reserve(std::size_t new_capacity) { - if (new_capacity > capacity_) - grow(new_capacity); - } - - void push_back(const T &value) { - reserve(size_ + 1); - ptr_[size_++] = value; - } - - /** Appends data to the end of the buffer. */ - template - void append(const U *begin, const U *end); - - T &operator[](std::size_t index) { return ptr_[index]; } - const T &operator[](std::size_t index) const { return ptr_[index]; } -}; - -typedef basic_buffer buffer; -typedef basic_buffer wbuffer; - -// A container-backed buffer. -template -class container_buffer : public basic_buffer { - private: - Container &container_; - - protected: - void grow(std::size_t capacity) FMT_OVERRIDE { - container_.resize(capacity); - this->set(&container_[0], capacity); - } - - public: - explicit container_buffer(Container &c) - : basic_buffer(c.size()), container_(c) {} -}; - -struct error_handler { - FMT_CONSTEXPR error_handler() {} - FMT_CONSTEXPR error_handler(const error_handler &) {} +// Specifies whether S is a string type convertible to fmt::basic_string_view. +template +struct is_string : std::integral_constant()))>::value> {}; - // This function is intentionally not constexpr to give a compile-time error. - FMT_API void on_error(const char *message); +template +struct char_t { + typedef decltype(to_string_view(declval())) result; + typedef typename result::char_type type; }; -// Formatting of wide characters and strings into a narrow output is disallowed: -// fmt::format("{}", L"test"); // error -// To fix this, use a wide format string: -// fmt::format(L"{}", L"test"); -template -inline void require_wchar() { - static_assert( - std::is_same::value, - "formatting of wide characters into a narrow output is disallowed"); -} - template struct named_arg_base; template struct named_arg; -template -struct is_named_arg : std::false_type {}; - -template -struct is_named_arg> : std::true_type {}; - enum type { none_type, named_arg_type, // Integer types should go first, @@ -639,15 +671,17 @@ FMT_MAKE_VALUE_SAME(long_long_type, long long) FMT_MAKE_VALUE_SAME(ulong_long_type, unsigned long long) FMT_MAKE_VALUE(int_type, signed char, int) FMT_MAKE_VALUE(uint_type, unsigned char, unsigned) -FMT_MAKE_VALUE(char_type, char, int) -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// This doesn't use FMT_MAKE_VALUE because of ambiguity in gcc 4.4. +template +FMT_CONSTEXPR typename std::enable_if< + std::is_same::value, + init>::type make_value(Char val) { return val; } + template -inline init make_value(wchar_t val) { - require_wchar(); - return static_cast(val); -} -#endif +FMT_CONSTEXPR typename std::enable_if< + !std::is_same::value, + init>::type make_value(char val) { return val; } FMT_MAKE_VALUE(double_type, float, double) FMT_MAKE_VALUE_SAME(double_type, double) @@ -695,15 +729,17 @@ inline typename std::enable_if< template inline typename std::enable_if< - std::is_constructible, T>::value, + is_constructible, T>::value && + !internal::is_string::value, init, string_type>>::type make_value(const T &val) { return basic_string_view(val); } template inline typename std::enable_if< - !convert_to_int::value && + !convert_to_int::value && !std::is_same::value && !std::is_convertible>::value && - !std::is_constructible, T>::value, + !is_constructible, T>::value && + !internal::is_string::value, // Implicit conversion to std::string is not handled here because it's // unsafe: https://github.com/fmtlib/fmt/issues/729 init>::type @@ -717,8 +753,21 @@ init return static_cast(&val); } +template +FMT_CONSTEXPR11 typename std::enable_if< + internal::is_string::value, + init, string_type>>::type + make_value(const S &val) { + // Handle adapted strings. + static_assert(std::is_same< + typename C::char_type, typename internal::char_t::type>::value, + "mismatch between char-types of context and argument"); + return to_string_view(val); +} + // Maximum number of arguments with packed types. enum { max_packed_args = 15 }; +enum : unsigned long long { is_unpacked_bit = 1ull << 63 }; template class arg_map; @@ -738,7 +787,7 @@ class basic_format_arg { template friend FMT_CONSTEXPR typename internal::result_of::type - visit(Visitor &&vis, const basic_format_arg &arg); + visit_format_arg(Visitor &&vis, const basic_format_arg &arg); friend class basic_format_args; friend class internal::arg_map; @@ -779,7 +828,7 @@ struct monostate {}; */ template FMT_CONSTEXPR typename internal::result_of::type - visit(Visitor &&vis, const basic_format_arg &arg) { + visit_format_arg(Visitor &&vis, const basic_format_arg &arg) { typedef typename Context::char_type char_type; switch (arg.type_) { case internal::none_type: @@ -816,6 +865,13 @@ FMT_CONSTEXPR typename internal::result_of::type return vis(monostate()); } +// DEPRECATED! +template +FMT_CONSTEXPR typename internal::result_of::type + visit(Visitor &&vis, const basic_format_arg &arg) { + return visit_format_arg(std::forward(vis), arg); +} + // Parsing context consisting of a format string range being parsed and an // argument counter for automatic indexing. template @@ -866,6 +922,10 @@ class basic_parse_context : private ErrorHandler { FMT_CONSTEXPR ErrorHandler error_handler() const { return *this; } }; +typedef basic_parse_context format_parse_context; +typedef basic_parse_context wformat_parse_context; + +// DEPRECATED! typedef basic_parse_context parse_context; typedef basic_parse_context wparse_context; @@ -904,10 +964,26 @@ class arg_map { if (it->name == name) return it->arg; } - return basic_format_arg(); + return {}; } }; +// A type-erased reference to an std::locale to avoid heavy include. +class locale_ref { + private: + const void *locale_; // A type-erased pointer to std::locale. + friend class locale; + + public: + locale_ref() : locale_(FMT_NULL) {} + + template + explicit locale_ref(const Locale &loc); + + template + Locale get() const; +}; + template class context_base { public: @@ -917,14 +993,16 @@ class context_base { basic_parse_context parse_context_; iterator out_; basic_format_args args_; + locale_ref loc_; protected: typedef Char char_type; typedef basic_format_arg format_arg; context_base(OutputIt out, basic_string_view format_str, - basic_format_args ctx_args) - : parse_context_(format_str), out_(out), args_(ctx_args) {} + basic_format_args ctx_args, + locale_ref loc = locale_ref()) + : parse_context_(format_str), out_(out), args_(ctx_args), loc_(loc) {} // Returns the argument with specified index. format_arg do_get_arg(unsigned arg_id) { @@ -942,9 +1020,9 @@ class context_base { } public: - basic_parse_context &parse_context() { - return parse_context_; - } + basic_parse_context &parse_context() { return parse_context_; } + basic_format_args args() const { return args_; } // DEPRECATED! + basic_format_arg arg(unsigned id) const { return args_.get(id); } internal::error_handler error_handler() { return parse_context_.error_handler(); @@ -959,18 +1037,42 @@ class context_base { // Advances the begin iterator to ``it``. void advance_to(iterator it) { out_ = it; } - basic_format_args args() const { return args_; } + locale_ref locale() { return loc_; } }; -// Extracts a reference to the container from back_insert_iterator. -template -inline Container &get_container(std::back_insert_iterator it) { - typedef std::back_insert_iterator bi_iterator; - struct accessor: bi_iterator { - accessor(bi_iterator iter) : bi_iterator(iter) {} - using bi_iterator::container; - }; - return *accessor(it).container; +template +struct get_type { + typedef decltype(make_value( + declval::type&>())) value_type; + static const type value = value_type::type_tag; +}; + +template +FMT_CONSTEXPR11 unsigned long long get_types() { return 0; } + +template +FMT_CONSTEXPR11 unsigned long long get_types() { + return get_type::value | (get_types() << 4); +} + +template +FMT_CONSTEXPR basic_format_arg make_arg(const T &value) { + basic_format_arg arg; + arg.type_ = get_type::value; + arg.value_ = make_value(value); + return arg; +} + +template +inline typename std::enable_if>::type + make_arg(const T &value) { + return make_value(value); +} + +template +inline typename std::enable_if>::type + make_arg(const T &value) { + return make_arg(value); } } // namespace internal @@ -1005,8 +1107,9 @@ class basic_format_context : stored in the object so make sure they have appropriate lifetimes. */ basic_format_context(OutputIt out, basic_string_view format_str, - basic_format_args ctx_args) - : base(out, format_str, ctx_args) {} + basic_format_args ctx_args, + internal::locale_ref loc = internal::locale_ref()) + : base(out, format_str, ctx_args, loc) {} format_arg next_arg() { return this->do_get_arg(this->parse_context().next_arg_id()); @@ -1026,43 +1129,6 @@ struct buffer_context { typedef buffer_context::type format_context; typedef buffer_context::type wformat_context; -namespace internal { -template -struct get_type { - typedef decltype(make_value( - declval::type&>())) value_type; - static const type value = value_type::type_tag; -}; - -template -FMT_CONSTEXPR11 unsigned long long get_types() { return 0; } - -template -FMT_CONSTEXPR11 unsigned long long get_types() { - return get_type::value | (get_types() << 4); -} - -template -FMT_CONSTEXPR basic_format_arg make_arg(const T &value) { - basic_format_arg arg; - arg.type_ = get_type::value; - arg.value_ = make_value(value); - return arg; -} - -template -inline typename std::enable_if>::type - make_arg(const T &value) { - return make_value(value); -} - -template -inline typename std::enable_if>::type - make_arg(const T &value) { - return make_arg(value); -} -} // namespace internal - /** \rst An array of references to arguments. It can be implicitly converted into @@ -1088,17 +1154,17 @@ class format_arg_store { friend class basic_format_args; - static FMT_CONSTEXPR11 long long get_types() { + static FMT_CONSTEXPR11 unsigned long long get_types() { return IS_PACKED ? - static_cast(internal::get_types()) : - -static_cast(NUM_ARGS); + internal::get_types() : + internal::is_unpacked_bit | NUM_ARGS; } public: #if FMT_USE_CONSTEXPR11 - static FMT_CONSTEXPR11 long long TYPES = get_types(); + static FMT_CONSTEXPR11 unsigned long long TYPES = get_types(); #else - static const long long TYPES; + static const unsigned long long TYPES; #endif #if (FMT_GCC_VERSION && FMT_GCC_VERSION <= 405) || \ @@ -1117,7 +1183,8 @@ class format_arg_store { #if !FMT_USE_CONSTEXPR11 template -const long long format_arg_store::TYPES = get_types(); +const unsigned long long format_arg_store::TYPES = + get_types(); #endif /** @@ -1127,17 +1194,9 @@ const long long format_arg_store::TYPES = get_types(); can be omitted in which case it defaults to `~fmt::context`. \endrst */ -template +template inline format_arg_store - make_format_args(const Args & ... args) { - return format_arg_store(args...); -} - -template -inline format_arg_store - make_format_args(const Args & ... args) { - return format_arg_store(args...); -} + make_format_args(const Args &... args) { return {args...}; } /** Formatting arguments. */ template @@ -1160,11 +1219,12 @@ class basic_format_args { const format_arg *args_; }; + bool is_packed() const { return (types_ & internal::is_unpacked_bit) == 0; } + typename internal::type type(unsigned index) const { unsigned shift = index * 4; - unsigned long long mask = 0xf; return static_cast( - (types_ & (mask << shift)) >> shift); + (types_ & (0xfull << shift)) >> shift); } friend class internal::arg_map; @@ -1174,10 +1234,8 @@ class basic_format_args { format_arg do_get(size_type index) const { format_arg arg; - long long signed_types = static_cast(types_); - if (signed_types < 0) { - unsigned long long num_args = - static_cast(-signed_types); + if (!is_packed()) { + auto num_args = max_size(); if (index < num_args) arg = args_[index]; return arg; @@ -1212,7 +1270,7 @@ class basic_format_args { \endrst */ basic_format_args(const format_arg *args, size_type count) - : types_(-static_cast(count)) { + : types_(internal::is_unpacked_bit | count) { set_data(args); } @@ -1224,34 +1282,52 @@ class basic_format_args { return arg; } - unsigned max_size() const { - long long signed_types = static_cast(types_); - return static_cast( - signed_types < 0 ? - -signed_types : static_cast(internal::max_packed_args)); + size_type max_size() const { + unsigned long long max_packed = internal::max_packed_args; + return static_cast( + is_packed() ? max_packed : types_ & ~internal::is_unpacked_bit); } }; /** An alias to ``basic_format_args``. */ // It is a separate type rather than a typedef to make symbols readable. -struct format_args: basic_format_args { +struct format_args : basic_format_args { template - format_args(Args && ... arg) + format_args(Args &&... arg) : basic_format_args(std::forward(arg)...) {} }; struct wformat_args : basic_format_args { template - wformat_args(Args && ... arg) + wformat_args(Args &&... arg) : basic_format_args(std::forward(arg)...) {} }; +#define FMT_ENABLE_IF_T(B, T) typename std::enable_if::type + +#ifndef FMT_USE_ALIAS_TEMPLATES +# define FMT_USE_ALIAS_TEMPLATES FMT_HAS_FEATURE(cxx_alias_templates) +#endif +#if FMT_USE_ALIAS_TEMPLATES +/** String's character type. */ +template +using char_t = FMT_ENABLE_IF_T( + internal::is_string::value, typename internal::char_t::type); +#define FMT_CHAR(S) fmt::char_t +#else +template +struct char_t : std::enable_if< + internal::is_string::value, typename internal::char_t::type> {}; +#define FMT_CHAR(S) typename char_t::type +#endif + namespace internal { template struct named_arg_base { basic_string_view name; // Serialized value. - mutable char data[sizeof(basic_format_arg)]; + mutable char data[ + sizeof(basic_format_arg::type>)]; named_arg_base(basic_string_view nm) : name(nm) {} @@ -1270,6 +1346,36 @@ struct named_arg : named_arg_base { named_arg(basic_string_view name, const T &val) : named_arg_base(name), value(val) {} }; + +template +inline typename std::enable_if::value>::type + check_format_string(const S &) {} +template +typename std::enable_if::value>::type + check_format_string(S); + +template +struct checked_args : format_arg_store< + typename buffer_context::type, Args...> { + typedef typename buffer_context::type context; + + checked_args(const S &format_str, const Args &... args): + format_arg_store(args...) { + internal::check_format_string(format_str); + } + + basic_format_args operator*() const { return *this; } +}; + +template +std::basic_string vformat( + basic_string_view format_str, + basic_format_args::type> args); + +template +typename buffer_context::type::iterator vformat_to( + internal::basic_buffer &buf, basic_string_view format_str, + basic_format_args::type> args); } /** @@ -1283,142 +1389,55 @@ struct named_arg : named_arg_base { */ template inline internal::named_arg arg(string_view name, const T &arg) { - return internal::named_arg(name, arg); + return {name, arg}; } template inline internal::named_arg arg(wstring_view name, const T &arg) { - return internal::named_arg(name, arg); + return {name, arg}; } -// This function template is deleted intentionally to disable nested named -// arguments as in ``format("{}", arg("a", arg("b", 42)))``. +// Disable nested named arguments, e.g. ``arg("a", arg("b", 42))``. template void arg(S, internal::named_arg) = delete; -// A base class for compile-time strings. It is defined in the fmt namespace to -// make formatting functions visible via ADL, e.g. format(fmt("{}"), 42). -struct compile_string {}; - -namespace internal { -// If S is a format string type, format_string_traints::char_type gives its -// character type. -template -struct format_string_traits { - private: - // Use constructability as a way to detect if format_string_traits is - // specialized because other methods are broken on MSVC2013. - format_string_traits(); -}; - -template -struct format_string_traits_base { typedef Char char_type; }; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits> : - format_string_traits_base {}; - -template -struct format_string_traits< - S, typename std::enable_if, S>::value>::type> : - format_string_traits_base {}; - -template -struct is_format_string : - std::integral_constant< - bool, std::is_constructible>::value> {}; - -template -struct is_compile_string : - std::integral_constant::value> {}; - -template -inline typename std::enable_if::value>::type - check_format_string(const S &) {} -template -typename std::enable_if::value>::type - check_format_string(S); - -template -std::basic_string vformat( - basic_string_view format_str, - basic_format_args::type> args); -} // namespace internal - -format_context::iterator vformat_to( - internal::buffer &buf, string_view format_str, format_args args); -wformat_context::iterator vformat_to( - internal::wbuffer &buf, wstring_view format_str, wformat_args args); - template -struct is_contiguous : std::false_type {}; +struct is_contiguous: std::false_type {}; template -struct is_contiguous> : std::true_type {}; +struct is_contiguous >: std::true_type {}; template -struct is_contiguous> : std::true_type {}; +struct is_contiguous >: std::true_type {}; /** Formats a string and writes the output to ``out``. */ -template -typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - vformat_to(std::back_insert_iterator out, - string_view format_str, format_args args) { - internal::container_buffer buf(internal::get_container(out)); - vformat_to(buf, format_str, args); - return out; -} - -template +template typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - vformat_to(std::back_insert_iterator out, - wstring_view format_str, wformat_args args) { + is_contiguous::value, std::back_insert_iterator>::type + vformat_to( + std::back_insert_iterator out, + const S &format_str, + basic_format_args::type> args) { internal::container_buffer buf(internal::get_container(out)); - vformat_to(buf, format_str, args); + internal::vformat_to(buf, to_string_view(format_str), args); return out; } -template -inline typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - format_to(std::back_insert_iterator out, - string_view format_str, const Args & ... args) { - format_arg_store as{args...}; - return vformat_to(out, format_str, as); -} - -template +template inline typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - format_to(std::back_insert_iterator out, - wstring_view format_str, const Args & ... args) { - return vformat_to(out, format_str, - make_format_args(args...)); + is_contiguous::value && internal::is_string::value, + std::back_insert_iterator>::type + format_to(std::back_insert_iterator out, const S &format_str, + const Args &... args) { + internal::checked_args ca(format_str, args...); + return vformat_to(out, to_string_view(format_str), *ca); } -template < - typename String, - typename Char = typename internal::format_string_traits::char_type> +template inline std::basic_string vformat( - const String &format_str, + const S &format_str, basic_format_args::type> args) { - // Convert format string to string_view to reduce the number of overloads. - return internal::vformat(basic_string_view(format_str), args); + return internal::vformat(to_string_view(format_str), args); } /** @@ -1431,19 +1450,12 @@ inline std::basic_string vformat( std::string message = fmt::format("The answer is {}", 42); \endrst */ -template -inline std::basic_string< - typename internal::format_string_traits::char_type> - format(const String &format_str, const Args & ... args) { - internal::check_format_string(format_str); - // This should be just - // return vformat(format_str, make_format_args(args...)); - // but gcc has trouble optimizing the latter, so break it down. - typedef typename internal::format_string_traits::char_type char_t; - typedef typename buffer_context::type context_t; - format_arg_store as{args...}; +template +inline std::basic_string format( + const S &format_str, const Args &... args) { return internal::vformat( - basic_string_view(format_str), basic_format_args(as)); + to_string_view(format_str), + *internal::checked_args(format_str, args...)); } FMT_API void vprint(std::FILE *f, string_view format_str, format_args args); @@ -1451,27 +1463,20 @@ FMT_API void vprint(std::FILE *f, wstring_view format_str, wformat_args args); /** \rst - Prints formatted data to the file *f*. + Prints formatted data to the file *f*. For wide format strings, + *f* should be in wide-oriented mode set via ``fwide(f, 1)`` or + ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. **Example**:: fmt::print(stderr, "Don't {}!", "panic"); \endrst */ -template -inline void print(std::FILE *f, string_view format_str, const Args & ... args) { - format_arg_store as(args...); - vprint(f, format_str, as); -} -/** - Prints formatted data to the file *f* which should be in wide-oriented mode - set via ``fwide(f, 1)`` or ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. - */ -template -inline void print(std::FILE *f, wstring_view format_str, - const Args & ... args) { - format_arg_store as(args...); - vprint(f, format_str, as); +template +inline FMT_ENABLE_IF_T(internal::is_string::value, void) + print(std::FILE *f, const S &format_str, const Args &... args) { + vprint(f, to_string_view(format_str), + internal::checked_args(format_str, args...)); } FMT_API void vprint(string_view format_str, format_args args); @@ -1486,16 +1491,11 @@ FMT_API void vprint(wstring_view format_str, wformat_args args); fmt::print("Elapsed time: {0:.2f} seconds", 1.23); \endrst */ -template -inline void print(string_view format_str, const Args & ... args) { - format_arg_store as{args...}; - vprint(format_str, as); -} - -template -inline void print(wstring_view format_str, const Args & ... args) { - format_arg_store as(args...); - vprint(format_str, as); +template +inline FMT_ENABLE_IF_T(internal::is_string::value, void) + print(const S &format_str, const Args &... args) { + vprint(to_string_view(format_str), + internal::checked_args(format_str, args...)); } FMT_END_NAMESPACE diff --git a/include/spdlog/fmt/bundled/format-inl.h b/include/spdlog/fmt/bundled/format-inl.h index 56c4d581..552c9430 100644 --- a/include/spdlog/fmt/bundled/format-inl.h +++ b/include/spdlog/fmt/bundled/format-inl.h @@ -136,12 +136,14 @@ int safe_strerror( ERANGE : result; } +#if !FMT_MSC_VER // Fallback to strerror if strerror_r and strerror_s are not available. int fallback(internal::null<>) { errno = 0; buffer_ = strerror(error_code_); return errno; } +#endif public: dispatcher(int err_code, char *&buf, std::size_t buf_size) @@ -170,7 +172,7 @@ void format_error_code(internal::buffer &out, int error_code, abs_value = 0 - abs_value; ++error_code_size; } - error_code_size += internal::count_digits(abs_value); + error_code_size += internal::to_unsigned(internal::count_digits(abs_value)); writer w(out); if (message.size() <= inline_buffer_size - error_code_size) { w.write(message); @@ -192,34 +194,39 @@ void report_error(FormatFunc func, int error_code, } } // namespace -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) -class locale { - private: - std::locale locale_; - - public: - explicit locale(std::locale loc = std::locale()) : locale_(loc) {} - std::locale get() { return locale_; } -}; - -FMT_FUNC size_t internal::count_code_points(u8string_view s) { +FMT_FUNC size_t internal::count_code_points(basic_string_view s) { const char8_t *data = s.data(); - int num_code_points = 0; + size_t num_code_points = 0; for (size_t i = 0, size = s.size(); i != size; ++i) { - if ((data[i].value & 0xc0) != 0x80) + if ((data[i] & 0xc0) != 0x80) ++num_code_points; } return num_code_points; } +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) +namespace internal { + +template +locale_ref::locale_ref(const Locale &loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} + +template +Locale locale_ref::get() const { + static_assert(std::is_same::value, ""); + return locale_ ? *static_cast(locale_) : std::locale(); +} + template -FMT_FUNC Char internal::thousands_sep(locale_provider *lp) { - std::locale loc = lp ? lp->locale().get() : std::locale(); - return std::use_facet>(loc).thousands_sep(); +FMT_FUNC Char thousands_sep_impl(locale_ref loc) { + return std::use_facet >( + loc.get()).thousands_sep(); +} } #else template -FMT_FUNC Char internal::thousands_sep(locale_provider *lp) { +FMT_FUNC Char internal::thousands_sep_impl(locale_ref) { return FMT_STATIC_THOUSANDS_SEPARATOR; } #endif @@ -236,19 +243,19 @@ FMT_FUNC void system_error::init( namespace internal { template int char_traits::format_float( - char *buffer, std::size_t size, const char *format, int precision, T value) { + char *buf, 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); + FMT_SNPRINTF(buf, size, format, value) : + FMT_SNPRINTF(buf, size, format, precision, value); } template int char_traits::format_float( - wchar_t *buffer, std::size_t size, const wchar_t *format, int precision, + wchar_t *buf, std::size_t size, const wchar_t *format, int precision, T value) { return precision < 0 ? - FMT_SWPRINTF(buffer, size, format, value) : - FMT_SWPRINTF(buffer, size, format, precision, value); + FMT_SWPRINTF(buf, size, format, value) : + FMT_SWPRINTF(buf, size, format, precision, value); } template @@ -337,6 +344,8 @@ const int16_t basic_data::POW10_EXPONENTS[] = { 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066 }; +template const char basic_data::FOREGROUND_COLOR[] = "\x1b[38;2;"; +template const char basic_data::BACKGROUND_COLOR[] = "\x1b[48;2;"; template const char basic_data::RESET_COLOR[] = "\x1b[0m"; template const wchar_t basic_data::WRESET_COLOR[] = L"\x1b[0m"; @@ -363,7 +372,7 @@ class fp { sizeof(significand_type) * char_size; fp(): f(0), e(0) {} - fp(uint64_t f, int e): f(f), e(e) {} + fp(uint64_t f_val, int e_val): f(f_val), e(e_val) {} // Constructs fp from an IEEE754 double. It is a template to prevent compile // errors on platforms where double is not IEEE754. @@ -454,19 +463,28 @@ FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) { return fp(data::POW10_SIGNIFICANDS[index], data::POW10_EXPONENTS[index]); } +FMT_FUNC bool grisu2_round( + char *buf, int &size, int max_digits, uint64_t delta, + uint64_t remainder, uint64_t exp, uint64_t diff, int &exp10) { + while (remainder < diff && delta - remainder >= exp && + (remainder + exp < diff || diff - remainder > remainder + exp - diff)) { + --buf[size - 1]; + remainder += exp; + } + if (size > max_digits) { + --size; + ++exp10; + if (buf[size] >= '5') + return false; + } + return true; +} + // 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(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. +FMT_FUNC bool grisu2_gen_digits( + char *buf, int &size, uint32_t hi, uint64_t lo, int &exp, + uint64_t delta, const fp &one, const fp &diff, int max_digits) { + // Generate digits for the most significant part (hi). while (exp > 0) { uint32_t digit = 0; // This optimization by miloyip reduces the number of integer divisions by @@ -486,208 +504,304 @@ FMT_FUNC void grisu2_gen_digits( FMT_ASSERT(false, "invalid number of digits"); } if (digit != 0 || size != 0) - buffer[size++] = static_cast('0' + digit); + buf[size++] = static_cast('0' + digit); --exp; uint64_t remainder = (static_cast(hi) << -one.e) + lo; - if (remainder <= delta) { - dec_exp += exp; - // TODO: use scaled_value - (void)scaled_value; - return; + if (remainder <= delta || size > max_digits) { + return grisu2_round( + buf, size, max_digits, delta, remainder, + static_cast(data::POWERS_OF_10_32[exp]) << -one.e, + diff.f, exp); } } + // Generate digits for the least significant part (lo). for (;;) { lo *= 10; delta *= 10; char digit = static_cast(lo >> -one.e); if (digit != 0 || size != 0) - buffer[size++] = static_cast('0' + digit); + buf[size++] = static_cast('0' + digit); lo &= one.f - 1; --exp; - if (lo < delta) { - dec_exp += exp; - return; + if (lo < delta || size > max_digits) { + return grisu2_round(buf, size, max_digits, delta, lo, one.f, + diff.f * data::POWERS_OF_10_32[-exp], exp); } } } -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]; +#if FMT_CLANG_VERSION +# define FMT_FALLTHROUGH [[clang::fallthrough]]; +#elif FMT_GCC_VERSION >= 700 +# define FMT_FALLTHROUGH [[gnu::fallthrough]]; +#else +# define FMT_FALLTHROUGH +#endif + +struct gen_digits_params { + int num_digits; + bool fixed; + bool upper; + bool trailing_zeros; +}; + +struct prettify_handler { + char *data; + ptrdiff_t size; + buffer &buf; + + explicit prettify_handler(buffer &b, ptrdiff_t n) + : data(b.data()), size(n), buf(b) {} + ~prettify_handler() { + assert(buf.size() >= to_unsigned(size)); + buf.resize(to_unsigned(size)); } -} -// Writes the exponent exp in the form "[+-]d{1,3}" to buffer. -FMT_FUNC char *write_exponent(char *buffer, int exp) { + template + void insert(ptrdiff_t pos, ptrdiff_t n, F f) { + std::memmove(data + pos + n, data + pos, to_unsigned(size - pos)); + f(data + pos); + size += n; + } + + void insert(ptrdiff_t pos, char c) { + std::memmove(data + pos + 1, data + pos, to_unsigned(size - pos)); + data[pos] = c; + ++size; + } + + void append(ptrdiff_t n, char c) { + std::uninitialized_fill_n(data + size, n, c); + size += n; + } + + void append(char c) { data[size++] = c; } + + void remove_trailing(char c) { + while (data[size - 1] == c) --size; + } +}; + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template +FMT_FUNC void write_exponent(int exp, Handler &&h) { FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range"); if (exp < 0) { - *buffer++ = '-'; + h.append('-'); exp = -exp; } else { - *buffer++ = '+'; + h.append('+'); } if (exp >= 100) { - *buffer++ = static_cast('0' + exp / 100); + h.append(static_cast('0' + exp / 100)); exp %= 100; const char *d = data::DIGITS + exp * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; + h.append(d[0]); + h.append(d[1]); } else { const char *d = data::DIGITS + exp * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; + h.append(d[0]); + h.append(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(size) - 1; - int num_digits = precision - static_cast(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) { +struct fill { + size_t n; + void operator()(char *buf) const { + buf[0] = '0'; + buf[1] = '.'; + std::uninitialized_fill_n(buf + 2, n, '0'); + } +}; + +// The number is given as v = f * pow(10, exp), where f has size digits. +template +FMT_FUNC void grisu2_prettify(const gen_digits_params ¶ms, + int size, int exp, Handler &&handler) { + if (!params.fixed) { + // Insert a decimal point after the first digit and add an exponent. + handler.insert(1, '.'); + exp += size - 1; + if (size < params.num_digits) + handler.append(params.num_digits - size, '0'); + handler.append(params.upper ? 'E' : 'e'); + write_exponent(exp, handler); + return; + } // pow(10, full_exp - 1) <= v <= pow(10, full_exp). - int int_size = static_cast(size); - int full_exp = int_size + exp; + int full_exp = size + exp; const int exp_threshold = 21; - if (int_size <= full_exp && full_exp <= exp_threshold) { + if (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; + handler.append(full_exp - size, '0'); + int num_zeros = params.num_digits - full_exp; + if (num_zeros > 0 && params.trailing_zeros) { + handler.append('.'); + handler.append(num_zeros, '0'); } - size = to_unsigned(p - buffer); - } else if (0 < full_exp && full_exp <= exp_threshold) { + } else if (full_exp > 0) { // 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); + handler.insert(full_exp, '.'); + if (!params.trailing_zeros) { + // Remove trailing zeros. + handler.remove_trailing('0'); + } else if (params.num_digits > size) { + // Add trailing zeros. + ptrdiff_t num_zeros = params.num_digits - size; + handler.append(num_zeros, '0'); } - ++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); + // 1234e-6 -> 0.001234 + handler.insert(0, 2 - full_exp, fill{to_unsigned(-full_exp)}); } } -#if FMT_CLANG_VERSION -# define FMT_FALLTHROUGH [[clang::fallthrough]]; -#elif FMT_GCC_VERSION >= 700 -# define FMT_FALLTHROUGH [[gnu::fallthrough]]; -#else -# define FMT_FALLTHROUGH -#endif +struct char_counter { + ptrdiff_t size; -// 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) { + template + void insert(ptrdiff_t, ptrdiff_t n, F) { size += n; } + void insert(ptrdiff_t, char) { ++size; } + void append(ptrdiff_t n, char) { size += n; } + void append(char) { ++size; } + void remove_trailing(char) {} +}; + +// Converts format specifiers into parameters for digit generation and computes +// output buffer size for a number in the range [pow(10, exp - 1), pow(10, exp) +// or 0 if exp == 1. +FMT_FUNC gen_digits_params process_specs(const core_format_specs &specs, + int exp, buffer &buf) { + auto params = gen_digits_params(); + int num_digits = specs.precision >= 0 ? specs.precision : 6; + switch (specs.type) { case 'G': - upper = true; + params.upper = true; FMT_FALLTHROUGH - case '\0': case 'g': { - int digits_to_remove = static_cast(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; - } + case '\0': case 'g': + params.trailing_zeros = (specs.flags & HASH_FLAG) != 0; + if (-4 <= exp && exp < num_digits + 1) { + params.fixed = true; + if (!specs.type && params.trailing_zeros && exp >= 0) + num_digits = exp + 1; } - precision = 0; break; - } case 'F': - upper = true; + params.upper = true; FMT_FALLTHROUGH case 'f': { - int digits_to_remove = -dec_exp - precision; - if (digits_to_remove > 0) { - if (digits_to_remove >= static_cast(size)) - digits_to_remove = static_cast(size) - 1; - round(buffer, size, dec_exp, digits_to_remove); - } + params.fixed = true; + params.trailing_zeros = true; + int adjusted_min_digits = num_digits + exp; + if (adjusted_min_digits > 0) + num_digits = adjusted_min_digits; break; } - case 'e': case 'E': - format_exp_notation(buffer, size, dec_exp, precision, type == 'E'); - return; + case 'E': + params.upper = true; + FMT_FALLTHROUGH + case 'e': + ++num_digits; + break; + } + params.num_digits = num_digits; + char_counter counter{num_digits}; + grisu2_prettify(params, params.num_digits, exp - num_digits, counter); + buf.resize(to_unsigned(counter.size)); + return params; +} + +template +FMT_FUNC typename std::enable_if::type + grisu2_format(Double value, buffer &buf, core_format_specs specs) { + FMT_ASSERT(value >= 0, "value is negative"); + if (value == 0) { + gen_digits_params params = process_specs(specs, 1, buf); + const size_t size = 1; + buf[0] = '0'; + grisu2_prettify(params, size, 0, prettify_handler(buf, size)); + return true; + } + + fp fp_value(value); + fp lower, upper; // w^- and w^+ in the Grisu paper. + fp_value.compute_boundaries(lower, upper); + + // Find a cached power of 10 close to 1 / upper and use it to scale upper. + const int min_exp = -60; // alpha in Grisu. + int cached_exp = 0; // K in Grisu. + auto cached_pow = get_cached_power( // \tilde{c}_{-k} in Grisu. + min_exp - (upper.e + fp::significand_size), cached_exp); + cached_exp = -cached_exp; + upper = upper * cached_pow; // \tilde{M}^+ in Grisu. + --upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}. + fp one(1ull << -upper.e, upper.e); + // hi (p1 in Grisu) contains the most significant digits of scaled_upper. + // hi = floor(upper / one). + uint32_t hi = static_cast(upper.f >> -one.e); + int exp = count_digits(hi); // kappa in Grisu. + gen_digits_params params = process_specs(specs, cached_exp + exp, buf); + fp_value.normalize(); + fp scaled_value = fp_value * cached_pow; + lower = lower * cached_pow; // \tilde{M}^- in Grisu. + ++lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}. + uint64_t delta = upper.f - lower.f; + fp diff = upper - scaled_value; // wp_w in Grisu. + // lo (p2 in Grisu) contains the least significants digits of scaled_upper. + // lo = supper % one. + uint64_t lo = upper.f & (one.f - 1); + int size = 0; + if (!grisu2_gen_digits(buf.data(), size, hi, lo, exp, delta, one, diff, + params.num_digits)) { + buf.clear(); + return false; + } + grisu2_prettify(params, size, cached_exp + exp, prettify_handler(buf, size)); + return true; +} + +template +void sprintf_format(Double value, internal::buffer &buf, + core_format_specs spec) { + // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. + FMT_ASSERT(buf.capacity() != 0, "empty buffer"); + + // Build format string. + enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg + char format[MAX_FORMAT_SIZE]; + char *format_ptr = format; + *format_ptr++ = '%'; + if (spec.has(HASH_FLAG)) + *format_ptr++ = '#'; + if (spec.precision >= 0) { + *format_ptr++ = '.'; + *format_ptr++ = '*'; + } + if (std::is_same::value) + *format_ptr++ = 'L'; + *format_ptr++ = spec.type; + *format_ptr = '\0'; + + // Format using snprintf. + char *start = FMT_NULL; + for (;;) { + std::size_t buffer_size = buf.capacity(); + start = &buf[0]; + int result = internal::char_traits::format_float( + start, buffer_size, format, spec.precision, value); + if (result >= 0) { + unsigned n = internal::to_unsigned(result); + if (n < buf.capacity()) { + buf.resize(n); + break; // The buffer is large enough - continue with formatting. + } + buf.reserve(n + 1); + } else { + // If result is negative we ask to increase the capacity by at least 1, + // but as std::vector, the buffer grows exponentially. + buf.reserve(buf.capacity() + 1); + } } - if (write_decimal_point && precision < 1) - precision = 1; - grisu2_prettify(buffer, size, dec_exp, precision, upper); } } // namespace internal @@ -812,11 +926,6 @@ FMT_FUNC void format_system_error( format_error_code(out, error_code, message); } -template -void basic_fixed_buffer::grow(std::size_t) { - FMT_THROW(std::runtime_error("buffer overflow")); -} - FMT_FUNC void internal::error_handler::on_error(const char *message) { FMT_THROW(format_error(message)); } @@ -835,13 +944,14 @@ FMT_FUNC void report_windows_error( FMT_FUNC void vprint(std::FILE *f, string_view format_str, format_args args) { memory_buffer buffer; - vformat_to(buffer, format_str, args); + internal::vformat_to(buffer, format_str, + basic_format_args::type>(args)); std::fwrite(buffer.data(), 1, buffer.size(), f); } FMT_FUNC void vprint(std::FILE *f, wstring_view format_str, wformat_args args) { wmemory_buffer buffer; - vformat_to(buffer, format_str, args); + internal::vformat_to(buffer, format_str, args); std::fwrite(buffer.data(), sizeof(wchar_t), buffer.size(), f); } @@ -853,10 +963,6 @@ FMT_FUNC void vprint(wstring_view format_str, wformat_args args) { vprint(stdout, format_str, args); } -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) -FMT_FUNC locale locale_provider::locale() { return fmt::locale(); } -#endif - FMT_END_NAMESPACE #ifdef _MSC_VER diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index 9f522f39..1bb24a52 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -66,9 +66,9 @@ // many valid cases. # pragma GCC diagnostic ignored "-Wshadow" -// Disable the warning about implicit conversions that may change the sign of -// an integer; silencing it otherwise would require many explicit casts. -# pragma GCC diagnostic ignored "-Wsign-conversion" +// Disable the warning about nonliteral format strings because we construct +// them dynamically when falling back to snprintf for FP formatting. +# pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif # if FMT_CLANG_VERSION @@ -163,6 +163,7 @@ FMT_END_NAMESPACE #ifndef FMT_USE_GRISU # define FMT_USE_GRISU 0 +//# define FMT_USE_GRISU std::numeric_limits::is_iec559 #endif // __builtin_clz is broken in clang with Microsoft CodeGen: @@ -177,14 +178,6 @@ FMT_END_NAMESPACE # endif #endif -// A workaround for gcc 4.4 that doesn't support union members with ctors. -#if (FMT_GCC_VERSION && FMT_GCC_VERSION <= 404) || \ - (FMT_MSC_VER && FMT_MSC_VER <= 1800) -# define FMT_UNION struct -#else -# define FMT_UNION union -#endif - // Some compilers masquerade as both MSVC and GCC-likes or otherwise support // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the // MSVC intrinsics if the clz and clzll builtins are not available. @@ -278,24 +271,13 @@ struct dummy_int { }; typedef std::numeric_limits fputil; -// Dummy implementations of system functions such as signbit and ecvt called -// if the latter are not available. -inline dummy_int signbit(...) { return dummy_int(); } -inline dummy_int _ecvt_s(...) { return dummy_int(); } +// Dummy implementations of system functions called if the latter are not +// available. inline dummy_int isinf(...) { return dummy_int(); } inline dummy_int _finite(...) { return dummy_int(); } inline dummy_int isnan(...) { return dummy_int(); } inline dummy_int _isnan(...) { return dummy_int(); } -inline bool use_grisu() { - return FMT_USE_GRISU && std::numeric_limits::is_iec559; -} - -// Formats value using Grisu2 algorithm: -// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf -FMT_API void grisu2_format(double value, char *buffer, size_t &size, char type, - int precision, bool write_decimal_point); - template typename Allocator::value_type *allocate(Allocator& alloc, std::size_t n) { #if __cplusplus >= 201103L || FMT_MSC_VER >= 1700 @@ -316,7 +298,7 @@ namespace std { // Standard permits specialization of std::numeric_limits. This specialization // is used to resolve ambiguity between isinf and std::isinf in glibc: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 -// and the same for isnan and signbit. +// and the same for isnan. template <> class numeric_limits : public std::numeric_limits { @@ -327,7 +309,7 @@ class numeric_limits : using namespace fmt::internal; // The resolution "priority" is: // isinf macro > std::isinf > ::isinf > fmt::internal::isinf - if (const_check(sizeof(isinf(x)) != sizeof(dummy_int))) + if (const_check(sizeof(isinf(x)) != sizeof(fmt::internal::dummy_int))) return isinf(x) != 0; return !_finite(static_cast(x)); } @@ -340,19 +322,6 @@ class numeric_limits : return isnan(x) != 0; return _isnan(static_cast(x)) != 0; } - - // Portable version of signbit. - static bool isnegative(double x) { - using namespace fmt::internal; - if (const_check(sizeof(signbit(x)) != sizeof(fmt::internal::dummy_int))) - return signbit(x) != 0; - if (x < 0) return true; - if (!isnotanumber(x)) return false; - int dec = 0, sign = 0; - char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. - _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign); - return sign != 0; - } }; } // namespace std @@ -431,48 +400,32 @@ void basic_buffer::append(const U *begin, const U *end) { } } // namespace internal +// C++20 feature test, since r346892 Clang considers char8_t a fundamental +// type in this mode. If this is the case __cpp_char8_t will be defined. +#if !defined(__cpp_char8_t) // A UTF-8 code unit type. -struct char8_t { - char value; - FMT_CONSTEXPR explicit operator bool() const FMT_NOEXCEPT { - return value != 0; - } -}; +enum char8_t: unsigned char {}; +#endif // A UTF-8 string view. class u8string_view : public basic_string_view { - private: - typedef basic_string_view base; - public: - using basic_string_view::basic_string_view; - using basic_string_view::char_type; - - u8string_view(const char *s) - : base(reinterpret_cast(s)) {} + typedef char8_t char_type; - u8string_view(const char *s, size_t count) FMT_NOEXCEPT - : base(reinterpret_cast(s), count) {} + u8string_view(const char *s): + basic_string_view(reinterpret_cast(s)) {} + u8string_view(const char *s, size_t count) FMT_NOEXCEPT: + basic_string_view(reinterpret_cast(s), count) {} }; #if FMT_USE_USER_DEFINED_LITERALS inline namespace literals { inline u8string_view operator"" _u(const char *s, std::size_t n) { - return u8string_view(s, n); + return {s, n}; } } #endif -// A wrapper around std::locale used to reduce compile times since -// is very heavy. -class locale; - -class locale_provider { - public: - virtual ~locale_provider() {} - virtual fmt::locale locale(); -}; - // The number of characters to store in the basic_memory_buffer object itself // to avoid dynamic memory allocation. enum { inline_buffer_size = 500 }; @@ -497,7 +450,7 @@ enum { inline_buffer_size = 500 }; fmt::memory_buffer out; format_to(out, "The answer is {}.", 42); - This will write the following output to the ``out`` object: + This will append the following output to the ``out`` object: .. code-block:: none @@ -522,6 +475,9 @@ class basic_memory_buffer: private Allocator, public internal::basic_buffer { void grow(std::size_t size) FMT_OVERRIDE; public: + typedef T value_type; + typedef const T &const_reference; + explicit basic_memory_buffer(const Allocator &alloc = Allocator()) : Allocator(alloc) { this->set(store_, SIZE); @@ -597,43 +553,6 @@ void basic_memory_buffer::grow(std::size_t size) { typedef basic_memory_buffer memory_buffer; typedef basic_memory_buffer wmemory_buffer; -/** - \rst - A fixed-size memory buffer. For a dynamically growing buffer use - :class:`fmt::basic_memory_buffer`. - - Trying to increase the buffer size past the initial capacity will throw - ``std::runtime_error``. - \endrst - */ -template -class basic_fixed_buffer : public internal::basic_buffer { - public: - /** - \rst - Constructs a :class:`fmt::basic_fixed_buffer` object for *array* of the - given size. - \endrst - */ - basic_fixed_buffer(Char *array, std::size_t size) { - this->set(array, size); - } - - /** - \rst - Constructs a :class:`fmt::basic_fixed_buffer` object for *array* of the - size known at compile time. - \endrst - */ - template - explicit basic_fixed_buffer(Char (&array)[SIZE]) { - this->set(array, SIZE); - } - - protected: - FMT_API void grow(std::size_t size) FMT_OVERRIDE; -}; - namespace internal { template @@ -690,98 +609,6 @@ class null_terminating_iterator; template FMT_CONSTEXPR_DECL const Char *pointer_from(null_terminating_iterator it); -// An iterator that produces a null terminator on *end. This simplifies parsing -// and allows comparing the performance of processing a null-terminated string -// vs string_view. -template -class null_terminating_iterator { - public: - typedef std::ptrdiff_t difference_type; - typedef Char value_type; - typedef const Char* pointer; - typedef const Char& reference; - typedef std::random_access_iterator_tag iterator_category; - - null_terminating_iterator() : ptr_(0), end_(0) {} - - FMT_CONSTEXPR null_terminating_iterator(const Char *ptr, const Char *end) - : ptr_(ptr), end_(end) {} - - template - FMT_CONSTEXPR explicit null_terminating_iterator(const Range &r) - : ptr_(r.begin()), end_(r.end()) {} - - FMT_CONSTEXPR null_terminating_iterator &operator=(const Char *ptr) { - assert(ptr <= end_); - ptr_ = ptr; - return *this; - } - - FMT_CONSTEXPR Char operator*() const { - return ptr_ != end_ ? *ptr_ : 0; - } - - FMT_CONSTEXPR null_terminating_iterator operator++() { - ++ptr_; - return *this; - } - - FMT_CONSTEXPR null_terminating_iterator operator++(int) { - null_terminating_iterator result(*this); - ++ptr_; - return result; - } - - FMT_CONSTEXPR null_terminating_iterator operator--() { - --ptr_; - return *this; - } - - FMT_CONSTEXPR null_terminating_iterator operator+(difference_type n) { - return null_terminating_iterator(ptr_ + n, end_); - } - - FMT_CONSTEXPR null_terminating_iterator operator-(difference_type n) { - return null_terminating_iterator(ptr_ - n, end_); - } - - FMT_CONSTEXPR null_terminating_iterator operator+=(difference_type n) { - ptr_ += n; - return *this; - } - - FMT_CONSTEXPR difference_type operator-( - null_terminating_iterator other) const { - return ptr_ - other.ptr_; - } - - FMT_CONSTEXPR bool operator!=(null_terminating_iterator other) const { - return ptr_ != other.ptr_; - } - - bool operator>=(null_terminating_iterator other) const { - return ptr_ >= other.ptr_; - } - - // This should be a friend specialization pointer_from but the latter - // doesn't compile by gcc 5.1 due to a compiler bug. - template - friend FMT_CONSTEXPR_DECL const CharT *pointer_from( - null_terminating_iterator it); - - private: - const Char *ptr_; - const Char *end_; -}; - -template -FMT_CONSTEXPR const T *pointer_from(const T *p) { return p; } - -template -FMT_CONSTEXPR const Char *pointer_from(null_terminating_iterator it) { - return it.ptr_; -} - // An output iterator that counts the number of objects written to it and // discards them. template @@ -816,35 +643,49 @@ class counting_iterator { T &operator*() const { return blackhole_; } }; +template +class truncating_iterator_base { + protected: + OutputIt out_; + std::size_t limit_; + std::size_t count_; + + truncating_iterator_base(OutputIt out, std::size_t limit) + : out_(out), limit_(limit), count_(0) {} + + public: + typedef std::output_iterator_tag iterator_category; + typedef void difference_type; + typedef void pointer; + typedef void reference; + typedef truncating_iterator_base _Unchecked_type; // Mark iterator as checked. + + OutputIt base() const { return out_; } + std::size_t count() const { return count_; } +}; + // An output iterator that truncates the output and counts the number of objects // written to it. +template ::value_type>::type> +class truncating_iterator; + template -class truncating_iterator { - private: +class truncating_iterator: + public truncating_iterator_base { typedef std::iterator_traits traits; - OutputIt out_; - std::size_t limit_; - std::size_t count_; mutable typename traits::value_type blackhole_; public: - typedef std::output_iterator_tag iterator_category; typedef typename traits::value_type value_type; - typedef typename traits::difference_type difference_type; - typedef typename traits::pointer pointer; - typedef typename traits::reference reference; - typedef truncating_iterator _Unchecked_type; // Mark iterator as checked. truncating_iterator(OutputIt out, std::size_t limit) - : out_(out), limit_(limit), count_(0) {} - - OutputIt base() const { return out_; } - std::size_t count() const { return count_; } + : truncating_iterator_base(out, limit) {} truncating_iterator& operator++() { - if (count_++ < limit_) - ++out_; + if (this->count_++ < this->limit_) + ++this->out_; return *this; } @@ -854,7 +695,29 @@ class truncating_iterator { return it; } - reference operator*() const { return count_ < limit_ ? *out_ : blackhole_; } + value_type& operator*() const { + return this->count_ < this->limit_ ? *this->out_ : blackhole_; + } +}; + +template +class truncating_iterator: + public truncating_iterator_base { + public: + typedef typename OutputIt::container_type::value_type value_type; + + truncating_iterator(OutputIt out, std::size_t limit) + : truncating_iterator_base(out, limit) {} + + truncating_iterator& operator=(value_type val) { + if (this->count_++ < this->limit_) + this->out_ = val; + return *this; + } + + truncating_iterator& operator++() { return *this; } + truncating_iterator& operator++(int) { return *this; } + truncating_iterator& operator*() { return *this; } }; // Returns true if value is negative, false otherwise. @@ -888,6 +751,8 @@ struct FMT_API basic_data { static const uint64_t POW10_SIGNIFICANDS[]; static const int16_t POW10_EXPONENTS[]; static const char DIGITS[]; + static const char FOREGROUND_COLOR[]; + static const char BACKGROUND_COLOR[]; static const char RESET_COLOR[]; static const wchar_t WRESET_COLOR[]; }; @@ -901,16 +766,16 @@ typedef basic_data<> data; #ifdef FMT_BUILTIN_CLZLL // Returns the number of decimal digits in n. Leading zeros are not counted // except for n == 0 in which case count_digits returns 1. -inline unsigned count_digits(uint64_t n) { +inline int count_digits(uint64_t n) { // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < data::ZERO_OR_POWERS_OF_10_64[t]) + 1; + return t - (n < data::ZERO_OR_POWERS_OF_10_64[t]) + 1; } #else // Fallback version of count_digits used when __builtin_clz is not available. -inline unsigned count_digits(uint64_t n) { - unsigned count = 1; +inline int count_digits(uint64_t n) { + int count = 1; for (;;) { // Integer division is slow so do it for a group of four digits instead // of for every digit. The idea comes from the talk by Alexandrescu @@ -925,8 +790,33 @@ inline unsigned count_digits(uint64_t n) { } #endif +template +inline size_t count_code_points(basic_string_view s) { return s.size(); } + // Counts the number of code points in a UTF-8 string. -FMT_API size_t count_code_points(u8string_view s); +FMT_API size_t count_code_points(basic_string_view s); + +inline char8_t to_char8_t(char c) { return static_cast(c); } + +template +struct needs_conversion: std::integral_constant::value_type, char>::value && + std::is_same::value> {}; + +template +typename std::enable_if< + !needs_conversion::value, OutputIt>::type + copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::copy(begin, end, it); +} + +template +typename std::enable_if< + needs_conversion::value, OutputIt>::type + copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::transform(begin, end, it, to_char8_t); +} #if FMT_HAS_CPP_ATTRIBUTE(always_inline) # define FMT_ALWAYS_INLINE __attribute__((always_inline)) @@ -1006,9 +896,9 @@ class decimal_formatter_null : public decimal_formatter { #ifdef FMT_BUILTIN_CLZ // Optional version of count_digits for better performance on 32-bit platforms. -inline unsigned count_digits(uint32_t n) { +inline int count_digits(uint32_t n) { int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < data::ZERO_OR_POWERS_OF_10_32[t]) + 1; + return t - (n < data::ZERO_OR_POWERS_OF_10_32[t]) + 1; } #endif @@ -1018,6 +908,8 @@ struct no_thousands_sep { template void operator()(Char *) {} + + enum { size = 0 }; }; // A functor that adds a thousands separator. @@ -1042,17 +934,30 @@ class add_thousands_sep { std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), internal::make_checked(buffer, sep_.size())); } + + enum { size = 1 }; }; template -FMT_API Char thousands_sep(locale_provider *lp); +FMT_API Char thousands_sep_impl(locale_ref loc); + +template +inline Char thousands_sep(locale_ref loc) { + return Char(thousands_sep_impl(loc)); +} + +template <> +inline wchar_t thousands_sep(locale_ref loc) { + return thousands_sep_impl(loc); +} // Formats a decimal unsigned integer value writing into buffer. // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. template -inline Char *format_decimal(Char *buffer, UInt value, unsigned num_digits, +inline Char *format_decimal(Char *buffer, UInt value, int num_digits, ThousandsSep thousands_sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); buffer += num_digits; Char *end = buffer; while (value >= 100) { @@ -1061,58 +966,63 @@ inline Char *format_decimal(Char *buffer, UInt value, unsigned num_digits, // "Three Optimization Tips for C++". See speed-test for a comparison. unsigned index = static_cast((value % 100) * 2); value /= 100; - *--buffer = data::DIGITS[index + 1]; + *--buffer = static_cast(data::DIGITS[index + 1]); thousands_sep(buffer); - *--buffer = data::DIGITS[index]; + *--buffer = static_cast(data::DIGITS[index]); thousands_sep(buffer); } if (value < 10) { - *--buffer = static_cast('0' + value); + *--buffer = static_cast('0' + value); return end; } unsigned index = static_cast(value * 2); - *--buffer = data::DIGITS[index + 1]; + *--buffer = static_cast(data::DIGITS[index + 1]); thousands_sep(buffer); - *--buffer = data::DIGITS[index]; + *--buffer = static_cast(data::DIGITS[index]); return end; } -template +template inline Iterator format_decimal( - Iterator out, UInt value, unsigned num_digits, ThousandsSep sep) { + Iterator out, UInt value, int num_digits, ThousandsSep sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); typedef typename ThousandsSep::char_type char_type; - // Buffer should be large enough to hold all digits (digits10 + 1) and null. - char_type buffer[std::numeric_limits::digits10 + 2]; - format_decimal(buffer, value, num_digits, sep); - return std::copy_n(buffer, num_digits, out); + // Buffer should be large enough to hold all digits (<= digits10 + 1). + enum { max_size = std::numeric_limits::digits10 + 1 }; + FMT_ASSERT(ThousandsSep::size <= 1, "invalid separator"); + char_type buffer[max_size + max_size / 3]; + auto end = format_decimal(buffer, value, num_digits, sep); + return internal::copy_str(buffer, end, out); } -template -inline It format_decimal(It out, UInt value, unsigned num_digits) { - return format_decimal(out, value, num_digits, no_thousands_sep()); +template +inline It format_decimal(It out, UInt value, int num_digits) { + return format_decimal(out, value, num_digits, no_thousands_sep()); } template -inline Char *format_uint(Char *buffer, UInt value, unsigned num_digits, +inline Char *format_uint(Char *buffer, UInt value, int num_digits, bool upper = false) { buffer += num_digits; Char *end = buffer; do { const char *digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; unsigned digit = (value & ((1 << BASE_BITS) - 1)); - *--buffer = BASE_BITS < 4 ? static_cast('0' + digit) : digits[digit]; + *--buffer = static_cast(BASE_BITS < 4 ? static_cast('0' + digit) + : digits[digit]); } while ((value >>= BASE_BITS) != 0); return end; } -template -inline It format_uint(It out, UInt value, unsigned num_digits, +template +inline It format_uint(It out, UInt value, int num_digits, bool upper = false) { // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1) // and null. char buffer[std::numeric_limits::digits / BASE_BITS + 2]; format_uint(buffer, value, num_digits, upper); - return std::copy_n(buffer, num_digits, out); + return internal::copy_str(buffer, buffer + num_digits, out); } #ifndef _WIN32 @@ -1171,72 +1081,35 @@ enum alignment { }; // Flags. -enum {SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8}; - -enum format_spec_tag {fill_tag, align_tag, width_tag, type_tag}; - -// Format specifier. -template -class format_spec { - private: - T value_; - - public: - typedef T value_type; - - explicit format_spec(T value) : value_(value) {} - - T value() const { return value_; } -}; - -// template -// typedef format_spec fill_spec; -template -class fill_spec : public format_spec { - public: - explicit fill_spec(Char value) : format_spec(value) {} -}; - -typedef format_spec width_spec; -typedef format_spec type_spec; - -// An empty format specifier. -struct empty_spec {}; +enum { SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8 }; // An alignment specifier. -struct align_spec : empty_spec { +struct align_spec { unsigned width_; // Fill is always wchar_t and cast to char if necessary to avoid having // two specialization of AlignSpec and its subclasses. wchar_t fill_; alignment align_; - FMT_CONSTEXPR align_spec( - unsigned width, wchar_t fill, alignment align = ALIGN_DEFAULT) - : width_(width), fill_(fill), align_(align) {} - + FMT_CONSTEXPR align_spec() : width_(0), fill_(' '), align_(ALIGN_DEFAULT) {} FMT_CONSTEXPR unsigned width() const { return width_; } FMT_CONSTEXPR wchar_t fill() const { return fill_; } FMT_CONSTEXPR alignment align() const { return align_; } +}; + +struct core_format_specs { + int precision; + uint_least8_t flags; + char type; - int precision() const { return -1; } + FMT_CONSTEXPR core_format_specs() : precision(-1), flags(0), type(0) {} + FMT_CONSTEXPR bool has(unsigned f) const { return (flags & f) != 0; } }; // Format specifiers. template -class basic_format_specs : public align_spec { - public: - unsigned flags_; - int precision_; - Char type_; - - FMT_CONSTEXPR basic_format_specs( - unsigned width = 0, char type = 0, wchar_t fill = ' ') - : align_spec(width, fill), flags_(0), precision_(-1), type_(type) {} - - FMT_CONSTEXPR bool flag(unsigned f) const { return (flags_ & f) != 0; } - FMT_CONSTEXPR int precision() const { return precision_; } - FMT_CONSTEXPR Char type() const { return type_; } +struct basic_format_specs : align_spec, core_format_specs { + FMT_CONSTEXPR basic_format_specs() {} }; typedef basic_format_specs format_specs; @@ -1251,13 +1124,20 @@ FMT_CONSTEXPR unsigned basic_parse_context::next_arg_id() { namespace internal { -template -struct format_string_traits< - S, typename std::enable_if::value>::type>: - format_string_traits_base {}; +// Formats value using Grisu2 algorithm: +// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf +template +FMT_API typename std::enable_if::type + grisu2_format(Double value, buffer &buf, core_format_specs); +template +inline typename std::enable_if::type + grisu2_format(Double, buffer &, core_format_specs) { return false; } -template -FMT_CONSTEXPR void handle_int_type_spec(Char spec, Handler &&handler) { +template +void sprintf_format(Double, internal::buffer &, core_format_specs); + +template +FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler &&handler) { switch (spec) { case 0: case 'd': handler.on_dec(); @@ -1279,8 +1159,8 @@ FMT_CONSTEXPR void handle_int_type_spec(Char spec, Handler &&handler) { } } -template -FMT_CONSTEXPR void handle_float_type_spec(Char spec, Handler &&handler) { +template +FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler &&handler) { switch (spec) { case 0: case 'g': case 'G': handler.on_general(); @@ -1304,8 +1184,8 @@ template FMT_CONSTEXPR void handle_char_specs( const basic_format_specs *specs, Handler &&handler) { if (!specs) return handler.on_char(); - if (specs->type() && specs->type() != 'c') return handler.on_int(); - if (specs->align() == ALIGN_NUMERIC || specs->flag(~0u) != 0) + if (specs->type && specs->type != 'c') return handler.on_int(); + if (specs->align() == ALIGN_NUMERIC || specs->flags != 0) handler.on_error("invalid format specifier for char"); handler.on_char(); } @@ -1364,13 +1244,13 @@ class float_type_checker : private ErrorHandler { } }; -template +template class char_specs_checker : public ErrorHandler { private: - CharType type_; + char type_; public: - FMT_CONSTEXPR char_specs_checker(CharType type, ErrorHandler eh) + FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh) : ErrorHandler(eh), type_(type) {} FMT_CONSTEXPR void on_int() { @@ -1394,8 +1274,7 @@ void arg_map::init(const basic_format_args &args) { if (map_) return; map_ = new entry[args.max_size()]; - bool use_values = args.type(max_packed_args - 1) == internal::none_type; - if (use_values) { + if (args.is_packed()) { for (unsigned i = 0;/*nothing*/; ++i) { internal::type arg_type = args.type(i); switch (arg_type) { @@ -1436,21 +1315,25 @@ class arg_formatter_base { struct char_writer { char_type value; + + size_t size() const { return 1; } + size_t width() const { return 1; } + template void operator()(It &&it) const { *it++ = value; } }; void write_char(char_type value) { if (specs_) - writer_.write_padded(1, *specs_, char_writer{value}); + writer_.write_padded(*specs_, char_writer{value}); else writer_.write(value); } void write_pointer(const void *p) { format_specs specs = specs_ ? *specs_ : format_specs(); - specs.flags_ = HASH_FLAG; - specs.type_ = 'x'; + specs.flags = HASH_FLAG; + specs.type = 'x'; writer_.write_int(reinterpret_cast(p), specs); } @@ -1461,7 +1344,7 @@ class arg_formatter_base { void write(bool value) { string_view sv(value ? "true" : "false"); - specs_ ? writer_.write_str(sv, *specs_) : writer_.write(sv); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); } void write(const char_type *value) { @@ -1469,11 +1352,12 @@ class arg_formatter_base { FMT_THROW(format_error("string pointer is null")); auto length = std::char_traits::length(value); basic_string_view sv(value, length); - specs_ ? writer_.write_str(sv, *specs_) : writer_.write(sv); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); } public: - arg_formatter_base(Range r, format_specs *s): writer_(r), specs_(s) {} + arg_formatter_base(Range r, format_specs *s, locale_ref loc) + : writer_(r, loc), specs_(s) {} iterator operator()(monostate) { FMT_ASSERT(false, "invalid argument type"); @@ -1481,12 +1365,13 @@ class arg_formatter_base { } template - typename std::enable_if::value, iterator>::type - operator()(T value) { + typename std::enable_if< + std::is_integral::value || std::is_same::value, + iterator>::type operator()(T value) { // MSVC2013 fails to compile separate overloads for bool and char_type so // use std::is_same instead. if (std::is_same::value) { - if (specs_ && specs_->type_) + if (specs_ && specs_->type) return (*this)(value ? 1 : 0); write(value != 0); } else if (std::is_same::value) { @@ -1535,15 +1420,15 @@ class arg_formatter_base { iterator operator()(const char_type *value) { if (!specs_) return write(value), out(); internal::handle_cstring_type_spec( - specs_->type_, cstring_spec_handler(*this, value)); + specs_->type, cstring_spec_handler(*this, value)); return out(); } iterator operator()(basic_string_view value) { if (specs_) { internal::check_string_type_spec( - specs_->type_, internal::error_handler()); - writer_.write_str(value, *specs_); + specs_->type, internal::error_handler()); + writer_.write(value, *specs_); } else { writer_.write(value); } @@ -1552,7 +1437,7 @@ class arg_formatter_base { iterator operator()(const void *value) { if (specs_) - check_pointer_type_spec(specs_->type_, internal::error_handler()); + check_pointer_type_spec(specs_->type, internal::error_handler()); write_pointer(value); return out(); } @@ -1563,40 +1448,16 @@ FMT_CONSTEXPR bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } -// DEPRECATED: Parses the input as an unsigned integer. This function assumes -// that the first character is a digit and presence of a non-digit character at -// the end. -// it: an iterator pointing to the beginning of the input range. -template -FMT_CONSTEXPR unsigned parse_nonnegative_int(Iterator &it, ErrorHandler &&eh) { - assert('0' <= *it && *it <= '9'); - unsigned value = 0; - // Convert to unsigned to prevent a warning. - unsigned max_int = (std::numeric_limits::max)(); - unsigned big = max_int / 10; - do { - // Check for overflow. - if (value > big) { - value = max_int + 1; - break; - } - value = value * 10 + unsigned(*it - '0'); - // Workaround for MSVC "setup_exception stack overflow" error: - auto next = it; - ++next; - it = next; - } while ('0' <= *it && *it <= '9'); - if (value > max_int) - eh.on_error("number is too big"); - return value; -} - // Parses the range [begin, end) as an unsigned integer. This function assumes // that the range is non-empty and the first character is a digit. template FMT_CONSTEXPR unsigned parse_nonnegative_int( const Char *&begin, const Char *end, ErrorHandler &&eh) { assert(begin != end && '0' <= *begin && *begin <= '9'); + if (*begin == '0') { + ++begin; + return 0; + } unsigned value = 0; // Convert to unsigned to prevent a warning. unsigned max_int = (std::numeric_limits::max)(); @@ -1607,7 +1468,8 @@ FMT_CONSTEXPR unsigned parse_nonnegative_int( value = max_int + 1; break; } - value = value * 10 + unsigned(*begin++ - '0'); + value = value * 10 + unsigned(*begin - '0'); + ++begin; } while (begin != end && '0' <= *begin && *begin <= '9'); if (value > max_int) eh.on_error("number is too big"); @@ -1695,14 +1557,14 @@ class specs_setter { explicit FMT_CONSTEXPR specs_setter(basic_format_specs &specs): specs_(specs) {} - FMT_CONSTEXPR specs_setter(const specs_setter &other) : specs_(other.specs_) {} + FMT_CONSTEXPR specs_setter(const specs_setter &other): specs_(other.specs_) {} FMT_CONSTEXPR void on_align(alignment align) { specs_.align_ = align; } FMT_CONSTEXPR void on_fill(Char fill) { specs_.fill_ = fill; } - FMT_CONSTEXPR void on_plus() { specs_.flags_ |= SIGN_FLAG | PLUS_FLAG; } - FMT_CONSTEXPR void on_minus() { specs_.flags_ |= MINUS_FLAG; } - FMT_CONSTEXPR void on_space() { specs_.flags_ |= SIGN_FLAG; } - FMT_CONSTEXPR void on_hash() { specs_.flags_ |= HASH_FLAG; } + FMT_CONSTEXPR void on_plus() { specs_.flags |= SIGN_FLAG | PLUS_FLAG; } + FMT_CONSTEXPR void on_minus() { specs_.flags |= MINUS_FLAG; } + FMT_CONSTEXPR void on_space() { specs_.flags |= SIGN_FLAG; } + FMT_CONSTEXPR void on_hash() { specs_.flags |= HASH_FLAG; } FMT_CONSTEXPR void on_zero() { specs_.align_ = ALIGN_NUMERIC; @@ -1711,11 +1573,13 @@ class specs_setter { FMT_CONSTEXPR void on_width(unsigned width) { specs_.width_ = width; } FMT_CONSTEXPR void on_precision(unsigned precision) { - specs_.precision_ = static_cast(precision); + specs_.precision = static_cast(precision); } FMT_CONSTEXPR void end_precision() {} - FMT_CONSTEXPR void on_type(Char type) { specs_.type_ = type; } + FMT_CONSTEXPR void on_type(Char type) { + specs_.type = static_cast(type); + } protected: basic_format_specs &specs_; @@ -1789,8 +1653,9 @@ template