From a2653d409ffa04b6543cde83db3e24f4c47d258f Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 9 Mar 2018 15:26:33 +0200 Subject: [PATCH] clang-format --- bench/boost-bench-mt.cpp | 45 +- bench/boost-bench.cpp | 28 +- bench/easylogging-bench-mt.cpp | 17 +- bench/easylogging-bench.cpp | 5 +- bench/g2log-async.cpp | 30 +- bench/glog-bench-mt.cpp | 17 +- bench/glog-bench.cpp | 6 +- bench/latency/g3log-crush.cpp | 11 +- bench/latency/g3log-latency.cpp | 69 +- bench/latency/spdlog-latency.cpp | 49 +- bench/latency/utils.h | 13 +- bench/spdlog-async.cpp | 27 +- bench/spdlog-bench-mt.cpp | 24 +- bench/spdlog-bench.cpp | 7 +- bench/spdlog-null-async.cpp | 47 +- bench/utils.h | 13 +- example/bench.cpp | 48 +- example/example.cpp | 37 +- example/jni/example.cpp | 157 +- example/multisink.cpp | 29 +- example/utils.h | 13 +- include/spdlog/async_logger.h | 57 +- include/spdlog/details/async_log_helper.h | 156 +- include/spdlog/details/async_logger_impl.h | 66 +- include/spdlog/details/file_helper.h | 30 +- include/spdlog/details/log_msg.h | 25 +- include/spdlog/details/logger_impl.h | 149 +- include/spdlog/details/mpmc_bounded_q.h | 59 +- include/spdlog/details/null_mutex.h | 14 +- include/spdlog/details/os.h | 174 +- .../spdlog/details/pattern_formatter_impl.h | 216 +- include/spdlog/details/registry.h | 82 +- include/spdlog/details/spdlog_impl.h | 97 +- include/spdlog/fmt/bundled/format.h | 1930 ++++++++--------- include/spdlog/fmt/bundled/ostream.h | 35 +- include/spdlog/fmt/bundled/posix.h | 123 +- include/spdlog/fmt/bundled/printf.h | 146 +- include/spdlog/fmt/bundled/time.h | 40 +- include/spdlog/fmt/fmt.h | 3 +- include/spdlog/fmt/ostr.h | 4 +- include/spdlog/formatter.h | 27 +- include/spdlog/logger.h | 80 +- include/spdlog/sinks/android_sink.h | 36 +- include/spdlog/sinks/ansicolor_sink.h | 44 +- include/spdlog/sinks/base_sink.h | 23 +- include/spdlog/sinks/dist_sink.h | 26 +- include/spdlog/sinks/file_sinks.h | 70 +- include/spdlog/sinks/msvc_sink.h | 26 +- include/spdlog/sinks/null_sink.h | 21 +- include/spdlog/sinks/ostream_sink.h | 27 +- include/spdlog/sinks/sink.h | 12 +- include/spdlog/sinks/stdout_sinks.h | 18 +- include/spdlog/sinks/syslog_sink.h | 30 +- include/spdlog/sinks/wincolor_sink.h | 48 +- include/spdlog/sinks/windebug_sink.h | 15 +- include/spdlog/spdlog.h | 109 +- include/spdlog/tweakme.h | 17 - tests/errors.cpp | 48 +- tests/file_helper.cpp | 8 +- tests/file_log.cpp | 28 +- tests/includes.h | 15 +- tests/registry.cpp | 39 +- tests/test_macros.cpp | 12 +- tests/test_pattern_formatter.cpp | 8 +- tests/utils.cpp | 20 +- tests/utils.h | 12 +- 66 files changed, 2330 insertions(+), 2587 deletions(-) mode change 120000 => 100644 example/jni/example.cpp diff --git a/bench/boost-bench-mt.cpp b/bench/boost-bench-mt.cpp index d845fcec..73219b91 100644 --- a/bench/boost-bench-mt.cpp +++ b/bench/boost-bench-mt.cpp @@ -3,18 +3,18 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include #include #include -#include #include -#include #include #include -#include -#include -#include #include +#include +#include +#include +#include namespace logging = boost::log; namespace src = boost::log::sources; @@ -23,62 +23,49 @@ namespace keywords = boost::log::keywords; void init() { - logging::add_file_log - ( - keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ - keywords::auto_flush = false, - keywords::format = "[%TimeStamp%]: %Message%" - ); + logging::add_file_log(keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ + keywords::auto_flush = false, keywords::format = "[%TimeStamp%]: %Message%"); - logging::core::get()->set_filter - ( - logging::trivial::severity >= logging::trivial::info - ); + logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info); } - - using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; - init(); logging::add_common_attributes(); - using namespace logging::trivial; - src::severity_logger_mt< severity_level > lg; + src::severity_logger_mt lg; - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; BOOST_LOG_SEV(lg, info) << "boost message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - return 0; } diff --git a/bench/boost-bench.cpp b/bench/boost-bench.cpp index 32c5b692..cb432578 100644 --- a/bench/boost-bench.cpp +++ b/bench/boost-bench.cpp @@ -3,13 +3,13 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // #include -#include #include #include -#include -#include -#include #include +#include +#include +#include +#include namespace logging = boost::log; namespace src = boost::log::sources; @@ -18,29 +18,21 @@ namespace keywords = boost::log::keywords; void init() { - logging::add_file_log - ( - keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ - keywords::auto_flush = false, - keywords::format = "[%TimeStamp%]: %Message%" - ); + logging::add_file_log(keywords::file_name = "logs/boost-sample_%N.log", /*< file name pattern >*/ + keywords::auto_flush = false, keywords::format = "[%TimeStamp%]: %Message%"); - logging::core::get()->set_filter - ( - logging::trivial::severity >= logging::trivial::info - ); + logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info); } - -int main(int argc, char* []) +int main(int argc, char *[]) { int howmany = 1000000; init(); logging::add_common_attributes(); using namespace logging::trivial; - src::severity_logger_mt< severity_level > lg; - for(int i = 0 ; i < howmany; ++i) + src::severity_logger_mt lg; + for (int i = 0; i < howmany; ++i) BOOST_LOG_SEV(lg, info) << "boost message #" << i << ": This is some text for your pleasure"; return 0; diff --git a/bench/easylogging-bench-mt.cpp b/bench/easylogging-bench-mt.cpp index 98d1ae35..00f507c6 100644 --- a/bench/easylogging-bench-mt.cpp +++ b/bench/easylogging-bench-mt.cpp @@ -3,9 +3,9 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include #include #include -#include #define _ELPP_THREAD_SAFE #include "easylogging++.h" @@ -13,11 +13,11 @@ _INITIALIZE_EASYLOGGINGPP using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; @@ -26,24 +26,23 @@ int main(int argc, char* argv[]) el::Configurations conf("easyl.conf"); el::Loggers::reconfigureLogger("default", conf); - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; LOG(INFO) << "easylog message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; diff --git a/bench/easylogging-bench.cpp b/bench/easylogging-bench.cpp index a952cbd5..5306435f 100644 --- a/bench/easylogging-bench.cpp +++ b/bench/easylogging-bench.cpp @@ -3,12 +3,11 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // - #include "easylogging++.h" _INITIALIZE_EASYLOGGINGPP -int main(int, char* []) +int main(int, char *[]) { int howmany = 1000000; @@ -16,7 +15,7 @@ int main(int, char* []) el::Configurations conf("easyl.conf"); el::Loggers::reconfigureLogger("default", conf); - for(int i = 0 ; i < howmany; ++i) + for (int i = 0; i < howmany; ++i) LOG(INFO) << "easylog message #" << i << ": This is some text for your pleasure"; return 0; } diff --git a/bench/g2log-async.cpp b/bench/g2log-async.cpp index 9f9eb71e..97cac5dc 100644 --- a/bench/g2log-async.cpp +++ b/bench/g2log-async.cpp @@ -3,57 +3,55 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include +#include +#include #include #include -#include -#include -#include -#include "g2logworker.h" #include "g2log.h" +#include "g2logworker.h" using namespace std; -template std::string format(const T& value); +template std::string format(const T &value); -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { using namespace std::chrono; - using clock=steady_clock; + using clock = steady_clock; int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; g2LogWorker g2log(argv[0], "logs"); g2::initializeLogging(&g2log); - - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; LOG(INFO) << "g2log message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; duration delta = clock::now() - start; float deltaf = delta.count(); - auto rate = howmany/deltaf; + auto rate = howmany / deltaf; cout << "Total: " << howmany << std::endl; cout << "Threads: " << thread_count << std::endl; diff --git a/bench/glog-bench-mt.cpp b/bench/glog-bench-mt.cpp index db193aeb..5e43de78 100644 --- a/bench/glog-bench-mt.cpp +++ b/bench/glog-bench-mt.cpp @@ -3,19 +3,19 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // +#include #include #include -#include #include "glog/logging.h" using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = atoi(argv[1]); int howmany = 1000000; @@ -24,24 +24,23 @@ int main(int argc, char* argv[]) FLAGS_log_dir = "logs"; google::InitGoogleLogging(argv[0]); - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; LOG(INFO) << "glog message #" << counter << ": This is some text for your pleasure"; } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; diff --git a/bench/glog-bench.cpp b/bench/glog-bench.cpp index cf7e70a2..2a8db891 100644 --- a/bench/glog-bench.cpp +++ b/bench/glog-bench.cpp @@ -5,16 +5,14 @@ #include "glog/logging.h" - -int main(int, char* argv[]) +int main(int, char *argv[]) { int howmany = 1000000; - FLAGS_logtostderr = 0; FLAGS_log_dir = "logs"; google::InitGoogleLogging(argv[0]); - for(int i = 0 ; i < howmany; ++i) + for (int i = 0; i < howmany; ++i) LOG(INFO) << "glog message # " << i << ": This is some text for your pleasure"; return 0; diff --git a/bench/latency/g3log-crush.cpp b/bench/latency/g3log-crush.cpp index 417b014c..5ab85d7a 100644 --- a/bench/latency/g3log-crush.cpp +++ b/bench/latency/g3log-crush.cpp @@ -9,29 +9,26 @@ void CrusherLoop() while (true) { LOGF(INFO, "Some text to crush you machine. thread:"); - if(++counter % 1000000 == 0) + if (++counter % 1000000 == 0) { std::cout << "Wrote " << counter << " entries" << std::endl; } } } - -int main(int argc, char** argv) +int main(int argc, char **argv) { std::cout << "WARNING: This test will exaust all your machine memory and will crush it!" << std::endl; std::cout << "Are you sure you want to continue ? " << std::endl; char c; std::cin >> c; - if (toupper( c ) != 'Y') + if (toupper(c) != 'Y') return 0; auto worker = g3::LogWorker::createLogWorker(); - auto handle= worker->addDefaultLogger(argv[0], "g3log.txt"); + auto handle = worker->addDefaultLogger(argv[0], "g3log.txt"); g3::initializeLogging(worker.get()); CrusherLoop(); return 0; } - - diff --git a/bench/latency/g3log-latency.cpp b/bench/latency/g3log-latency.cpp index e96e421b..fe067f77 100644 --- a/bench/latency/g3log-latency.cpp +++ b/bench/latency/g3log-latency.cpp @@ -1,32 +1,26 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "utils.h" +#include +#include +#include +#include +#include +#include #include #include +#include +#include +#include +#include +#include +#include +#include - -namespace -{ +namespace { const uint64_t g_iterations = 1000000; - std::atomic g_counter = {0}; - -void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) +void MeasurePeakDuringLogWrites(const size_t id, std::vector &result) { while (true) @@ -45,14 +39,12 @@ void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) } } - - -void PrintResults(const std::map>& threads_result, size_t total_us) +void PrintResults(const std::map> &threads_result, size_t total_us) { std::vector all_measurements; all_measurements.reserve(g_iterations); - for (auto& t_result : threads_result) + for (auto &t_result : threads_result) { all_measurements.insert(all_measurements.end(), t_result.second.begin(), t_result.second.end()); } @@ -62,13 +54,12 @@ void PrintResults(const std::map>& threads_result, // calc avg auto total = accumulate(begin(all_measurements), end(all_measurements), 0, std::plus()); - auto avg = double(total)/all_measurements.size(); - - std::cout << "[g3log] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) << " us" << std::endl; + auto avg = double(total) / all_measurements.size(); + std::cout << "[g3log] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) + << " us" << std::endl; } -}// anonymous - +} // namespace // The purpose of this test is NOT to see how fast // each thread can possibly write. It is to see what @@ -78,9 +69,9 @@ void PrintResults(const std::map>& threads_result, // an atomic counter is used to give each thread what // it is to write next. The overhead of atomic // synchronization between the threads are not counted in the worst case latency -int main(int argc, char** argv) +int main(int argc, char **argv) { - size_t number_of_threads {0}; + size_t number_of_threads{0}; if (argc == 2) { number_of_threads = atoi(argv[1]); @@ -91,7 +82,6 @@ int main(int argc, char** argv) return 1; } - std::vector threads(number_of_threads); std::map> threads_result; @@ -102,12 +92,12 @@ int main(int argc, char** argv) threads_result[idx].reserve(g_iterations); } - const std::string g_path = "./" ; - const std::string g_prefix_log_name = "g3log-performance-"; - const std::string g_measurement_dump = g_path + g_prefix_log_name + "_RESULT.txt"; + const std::string g_path = "./"; + const std::string g_prefix_log_name = "g3log-performance-"; + const std::string g_measurement_dump = g_path + g_prefix_log_name + "_RESULT.txt"; auto worker = g3::LogWorker::createLogWorker(); - auto handle= worker->addDefaultLogger(argv[0], "g3log.txt"); + auto handle = worker->addDefaultLogger(argv[0], "g3log.txt"); g3::initializeLogging(worker.get()); auto start_time_application_total = std::chrono::high_resolution_clock::now(); @@ -121,9 +111,8 @@ int main(int argc, char** argv) } auto stop_time_application_total = std::chrono::high_resolution_clock::now(); - uint64_t total_time_in_us = std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); + uint64_t total_time_in_us = + std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); PrintResults(threads_result, total_time_in_us); return 0; } - - diff --git a/bench/latency/spdlog-latency.cpp b/bench/latency/spdlog-latency.cpp index ed4966cc..a2200c5d 100644 --- a/bench/latency/spdlog-latency.cpp +++ b/bench/latency/spdlog-latency.cpp @@ -1,31 +1,26 @@ -#include -#include -#include -#include -#include +#include "utils.h" #include -#include +#include +#include #include +#include +#include #include #include -#include -#include "utils.h" #include +#include #include "spdlog/spdlog.h" namespace spd = spdlog; -namespace -{ +namespace { const uint64_t g_iterations = 1000000; - std::atomic g_counter = {0}; - -void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) +void MeasurePeakDuringLogWrites(const size_t id, std::vector &result) { auto logger = spd::get("file_logger"); while (true) @@ -44,13 +39,12 @@ void MeasurePeakDuringLogWrites(const size_t id, std::vector& result) } } - -void PrintResults(const std::map>& threads_result, size_t total_us) +void PrintResults(const std::map> &threads_result, size_t total_us) { std::vector all_measurements; all_measurements.reserve(g_iterations); - for (auto& t_result : threads_result) + for (auto &t_result : threads_result) { all_measurements.insert(all_measurements.end(), t_result.second.begin(), t_result.second.end()); } @@ -60,13 +54,12 @@ void PrintResults(const std::map>& threads_result, // calc avg auto total = accumulate(begin(all_measurements), end(all_measurements), 0, std::plus()); - auto avg = double(total)/all_measurements.size(); - - std::cout << "[spdlog] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) << " us" << std::endl; + auto avg = double(total) / all_measurements.size(); + std::cout << "[spdlog] worst: " << std::setw(10) << std::right << worst << "\tAvg: " << avg << "\tTotal: " << utils::format(total_us) + << " us" << std::endl; } -}// anonymous - +} // namespace // The purpose of this test is NOT to see how fast // each thread can possibly write. It is to see what @@ -76,9 +69,9 @@ void PrintResults(const std::map>& threads_result, // an atomic counter is used to give each thread what // it is to write next. The overhead of atomic // synchronization between the threads are not counted in the worst case latency -int main(int argc, char** argv) +int main(int argc, char **argv) { - size_t number_of_threads {0}; + size_t number_of_threads{0}; if (argc == 2) { number_of_threads = atoi(argv[1]); @@ -89,7 +82,6 @@ int main(int argc, char** argv) return 1; } - std::vector threads(number_of_threads); std::map> threads_result; @@ -104,8 +96,8 @@ int main(int argc, char** argv) spdlog::set_async_mode(queue_size); auto logger = spdlog::create("file_logger", "spdlog.log", true); - //force flush on every call to compare with g3log - auto s = (spd::sinks::simple_file_sink_mt*)logger->sinks()[0].get(); + // force flush on every call to compare with g3log + auto s = (spd::sinks::simple_file_sink_mt *)logger->sinks()[0].get(); s->set_force_flush(true); auto start_time_application_total = std::chrono::high_resolution_clock::now(); @@ -119,10 +111,9 @@ int main(int argc, char** argv) } auto stop_time_application_total = std::chrono::high_resolution_clock::now(); - uint64_t total_time_in_us = std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); + uint64_t total_time_in_us = + std::chrono::duration_cast(stop_time_application_total - start_time_application_total).count(); PrintResults(threads_result, total_time_in_us); return 0; } - - diff --git a/bench/latency/utils.h b/bench/latency/utils.h index b260f724..6d6ee85d 100644 --- a/bench/latency/utils.h +++ b/bench/latency/utils.h @@ -5,15 +5,13 @@ #pragma once -#include #include #include +#include -namespace utils -{ +namespace utils { -template -inline std::string format(const T& value) +template inline std::string format(const T &value) { static std::locale loc(""); std::stringstream ss; @@ -22,8 +20,7 @@ inline std::string format(const T& value) return ss.str(); } -template<> -inline std::string format(const double & value) +template <> inline std::string format(const double &value) { static std::locale loc(""); std::stringstream ss; @@ -32,4 +29,4 @@ inline std::string format(const double & value) return ss.str(); } -} +} // namespace utils diff --git a/bench/spdlog-async.cpp b/bench/spdlog-async.cpp index f788e4df..0db4f6c6 100644 --- a/bench/spdlog-async.cpp +++ b/bench/spdlog-async.cpp @@ -3,25 +3,25 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include -#include +#include "spdlog/spdlog.h" #include -#include #include #include -#include "spdlog/spdlog.h" +#include +#include +#include using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { using namespace std::chrono; - using clock=steady_clock; + using clock = steady_clock; namespace spd = spdlog; int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = ::atoi(argv[1]); int howmany = 1000000; @@ -29,31 +29,30 @@ int main(int argc, char* argv[]) auto logger = spdlog::create("file_logger", "logs/spd-bench-async.txt", false); logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); - - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; logger->info("spdlog message #{}: This is some text for your pleasure", counter); } })); } - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; duration delta = clock::now() - start; float deltaf = delta.count(); - auto rate = howmany/deltaf; + auto rate = howmany / deltaf; cout << "Total: " << howmany << std::endl; cout << "Threads: " << thread_count << std::endl; diff --git a/bench/spdlog-bench-mt.cpp b/bench/spdlog-bench-mt.cpp index e28e7bb8..5feb7044 100644 --- a/bench/spdlog-bench-mt.cpp +++ b/bench/spdlog-bench-mt.cpp @@ -3,20 +3,19 @@ // Distributed under the MIT License (http://opensource.org/licenses/MIT) // -#include -#include +#include "spdlog/spdlog.h" #include #include -#include "spdlog/spdlog.h" - +#include +#include using namespace std; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int thread_count = 10; - if(argc > 1) + if (argc > 1) thread_count = std::atoi(argv[1]); int howmany = 1000000; @@ -27,29 +26,26 @@ int main(int argc, char* argv[]) logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; std::vector threads; for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { + threads.push_back(std::thread([&]() { while (true) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; logger->info("spdlog message #{}: This is some text for your pleasure", counter); } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - - return 0; } diff --git a/bench/spdlog-bench.cpp b/bench/spdlog-bench.cpp index 4ac95f6a..8d122249 100644 --- a/bench/spdlog-bench.cpp +++ b/bench/spdlog-bench.cpp @@ -5,16 +5,15 @@ #include "spdlog/spdlog.h" - -int main(int, char* []) +int main(int, char *[]) { int howmany = 1000000; namespace spd = spdlog; - ///Create a file rotating logger with 5mb size max and 3 rotated files + /// Create a file rotating logger with 5mb size max and 3 rotated files auto logger = spdlog::create("file_logger", "logs/spd-bench-st.txt", false); logger->set_pattern("[%Y-%b-%d %T.%e]: %v"); - for(int i = 0 ; i < howmany; ++i) + for (int i = 0; i < howmany; ++i) logger->info("spdlog message #{} : This is some text for your pleasure", i); return 0; } diff --git a/bench/spdlog-null-async.cpp b/bench/spdlog-null-async.cpp index 3874371a..df07f834 100644 --- a/bench/spdlog-null-async.cpp +++ b/bench/spdlog-null-async.cpp @@ -6,17 +6,16 @@ // // bench.cpp : spdlog benchmarks // +#include "spdlog/async_logger.h" +#include "spdlog/sinks/null_sink.h" +#include "spdlog/spdlog.h" +#include "utils.h" #include #include // EXIT_FAILURE #include #include #include #include -#include "spdlog/spdlog.h" -#include "spdlog/async_logger.h" -#include "spdlog/sinks/null_sink.h" -#include "utils.h" - using namespace std; using namespace std::chrono; @@ -24,11 +23,9 @@ using namespace spdlog; using namespace spdlog::sinks; using namespace utils; - - size_t bench_as(int howmany, std::shared_ptr log, int thread_count); -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int queue_size = 1048576; @@ -39,14 +36,13 @@ int main(int argc, char* argv[]) try { - if(argc > 1) + if (argc > 1) howmany = atoi(argv[1]); if (argc > 2) - threads = atoi(argv[2]); + threads = atoi(argv[2]); if (argc > 3) queue_size = atoi(argv[3]); - cout << "\n*******************************************************************************\n"; cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " messages " << endl; cout << "*******************************************************************************\n"; @@ -55,16 +51,15 @@ int main(int argc, char* argv[]) size_t total_rate = 0; - for(int i = 0; i < iters; ++i) + for (int i = 0; i < iters; ++i) { - //auto as = spdlog::daily_logger_st("as", "logs/daily_async"); + // auto as = spdlog::daily_logger_st("as", "logs/daily_async"); auto as = spdlog::create("async(null-sink)"); - total_rate+= bench_as(howmany, as, threads); + total_rate += bench_as(howmany, as, threads); spdlog::drop("async(null-sink)"); } std::cout << endl; - std::cout << "Avg rate: " << format(total_rate/iters) << "/sec" < log, int thread_count) { cout << log->name() << "...\t\t" << flush; - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = system_clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { - for(;;) + threads.push_back(std::thread([&]() { + for (;;) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; log->info("Hello logger: msg number {}", counter); } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - auto delta = system_clock::now() - start; - auto delta_d = duration_cast> (delta).count(); + auto delta_d = duration_cast>(delta).count(); auto per_sec = size_t(howmany / delta_d); cout << format(per_sec) << "/sec" << endl; return per_sec; diff --git a/bench/utils.h b/bench/utils.h index b260f724..6d6ee85d 100644 --- a/bench/utils.h +++ b/bench/utils.h @@ -5,15 +5,13 @@ #pragma once -#include #include #include +#include -namespace utils -{ +namespace utils { -template -inline std::string format(const T& value) +template inline std::string format(const T &value) { static std::locale loc(""); std::stringstream ss; @@ -22,8 +20,7 @@ inline std::string format(const T& value) return ss.str(); } -template<> -inline std::string format(const double & value) +template <> inline std::string format(const double &value) { static std::locale loc(""); std::stringstream ss; @@ -32,4 +29,4 @@ inline std::string format(const double & value) return ss.str(); } -} +} // namespace utils diff --git a/example/bench.cpp b/example/bench.cpp index e42bec1f..49385e0f 100644 --- a/example/bench.cpp +++ b/example/bench.cpp @@ -6,18 +6,17 @@ // // bench.cpp : spdlog benchmarks // +#include "spdlog/async_logger.h" +#include "spdlog/sinks/file_sinks.h" +#include "spdlog/sinks/null_sink.h" +#include "spdlog/spdlog.h" +#include "utils.h" #include #include // EXIT_FAILURE #include #include #include #include -#include "spdlog/spdlog.h" -#include "spdlog/async_logger.h" -#include "spdlog/sinks/file_sinks.h" -#include "spdlog/sinks/null_sink.h" -#include "utils.h" - using namespace std; using namespace std::chrono; @@ -25,11 +24,10 @@ using namespace spdlog; using namespace spdlog::sinks; using namespace utils; - void bench(int howmany, std::shared_ptr log); void bench_mt(int howmany, std::shared_ptr log, int thread_count); -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int queue_size = 1048576; @@ -41,16 +39,15 @@ int main(int argc, char* argv[]) try { - if(argc > 1) + if (argc > 1) howmany = atoi(argv[1]); if (argc > 2) - threads = atoi(argv[2]); + threads = atoi(argv[2]); if (argc > 3) queue_size = atoi(argv[3]); - cout << "*******************************************************************************\n"; - cout << "Single thread, " << format(howmany) << " iterations" << endl; + cout << "Single thread, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); @@ -60,13 +57,12 @@ int main(int argc, char* argv[]) bench(howmany, spdlog::create("null_st")); cout << "\n*******************************************************************************\n"; - cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; + cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files); bench_mt(howmany, rotating_mt, threads); - auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log"); bench_mt(howmany, daily_mt, threads); bench(howmany, spdlog::create("null_mt")); @@ -75,10 +71,9 @@ int main(int argc, char* argv[]) cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl; cout << "*******************************************************************************\n"; - spdlog::set_async_mode(queue_size); - for(int i = 0; i < 3; ++i) + for (int i = 0; i < 3; ++i) { auto as = spdlog::daily_logger_st("as", "logs/daily_async.log"); bench_mt(howmany, as, threads); @@ -94,7 +89,6 @@ int main(int argc, char* argv[]) return EXIT_SUCCESS; } - void bench(int howmany, std::shared_ptr log) { cout << log->name() << "...\t\t" << flush; @@ -104,41 +98,37 @@ void bench(int howmany, std::shared_ptr log) log->info("Hello logger: msg number {}", i); } - auto delta = system_clock::now() - start; - auto delta_d = duration_cast> (delta).count(); + auto delta_d = duration_cast>(delta).count(); cout << format(int(howmany / delta_d)) << "/sec" << endl; } - void bench_mt(int howmany, std::shared_ptr log, int thread_count) { cout << log->name() << "...\t\t" << flush; - std::atomic msg_counter {0}; + std::atomic msg_counter{0}; vector threads; auto start = system_clock::now(); for (int t = 0; t < thread_count; ++t) { - threads.push_back(std::thread([&]() - { - for(;;) + threads.push_back(std::thread([&]() { + for (;;) { int counter = ++msg_counter; - if (counter > howmany) break; + if (counter > howmany) + break; log->info("Hello logger: msg number {}", counter); } })); } - - for(auto &t:threads) + for (auto &t : threads) { t.join(); }; - auto delta = system_clock::now() - start; - auto delta_d = duration_cast> (delta).count(); + auto delta_d = duration_cast>(delta).count(); cout << format(int(howmany / delta_d)) << "/sec" << endl; } diff --git a/example/example.cpp b/example/example.cpp index cf747834..937c69f9 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -22,7 +22,7 @@ void user_defined_example(); void err_handler_example(); namespace spd = spdlog; -int main(int, char*[]) +int main(int, char *[]) { try { @@ -31,7 +31,6 @@ int main(int, char*[]) console->info("Welcome to spdlog!"); console->error("Some error message with arg{}..", 1); - // Formatting examples console->warn("Easy padding in numbers like {:08d}", 12); console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); @@ -41,7 +40,6 @@ int main(int, char*[]) spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function"); - // Create basic file logger (not rotated) auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt"); my_logger->info("Some log message"); @@ -49,7 +47,7 @@ int main(int, char*[]) // Create a file rotating logger with 5mb size max and 3 rotated files auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); for (int i = 0; i < 10; ++i) - rotating_logger->info("{} * {} equals {:>10}", i, i, i*i); + rotating_logger->info("{} * {} equals {:>10}", i, i, i * i); // Create a daily logger - a new file is created every day on 2:30am auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); @@ -61,9 +59,8 @@ int main(int, char*[]) spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***"); rotating_logger->info("This is another message with custom format"); - // Runtime log levels - spd::set_level(spd::level::info); //Set global log level to info + spd::set_level(spd::level::info); // Set global log level to info console->debug("This message should not be displayed!"); console->set_level(spd::level::debug); // Set specific logger's log level console->debug("This message should be displayed.."); @@ -73,7 +70,6 @@ int main(int, char*[]) SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23); SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23); - // Asynchronous logging is very fast.. // Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous.. async_example(); @@ -91,16 +87,13 @@ int main(int, char*[]) err_handler_example(); // Apply a function on all registered loggers - spd::apply_all([&](std::shared_ptr l) - { - l->info("End of example."); - }); + spd::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); // Release and close all loggers spdlog::drop_all(); } // Exceptions will only be thrown upon failed logger or sink construction (not during logging) - catch (const spd::spdlog_ex& ex) + catch (const spd::spdlog_ex &ex) { std::cout << "Log init failed: " << ex.what() << std::endl; return 1; @@ -109,14 +102,14 @@ int main(int, char*[]) void async_example() { - size_t q_size = 4096; //queue size must be power of 2 + size_t q_size = 4096; // queue size must be power of 2 spdlog::set_async_mode(q_size); auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt"); for (int i = 0; i < 100; ++i) async_file->info("Async message #{}", i); } -//syslog example (linux/osx/freebsd) +// syslog example (linux/osx/freebsd) void syslog_example() { #ifdef SPDLOG_ENABLE_SYSLOG @@ -140,28 +133,24 @@ void android_example() struct my_type { int i; - template - friend OStream& operator<<(OStream& os, const my_type &c) + template friend OStream &operator<<(OStream &os, const my_type &c) { - return os << "[my_type i="<info("user defined type: {}", my_type { 14 }); + spd::get("console")->info("user defined type: {}", my_type{14}); } // -//custom error handler +// custom error handler // void err_handler_example() { - //can be set globaly or per logger(logger->set_error_handler(..)) - spdlog::set_error_handler([](const std::string& msg) - { - std::cerr << "my err handler: " << msg << std::endl; - }); + // can be set globaly or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; }); spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3); } diff --git a/example/jni/example.cpp b/example/jni/example.cpp deleted file mode 120000 index 6170abce..00000000 --- a/example/jni/example.cpp +++ /dev/null @@ -1 +0,0 @@ -../example.cpp \ No newline at end of file diff --git a/example/jni/example.cpp b/example/jni/example.cpp new file mode 100644 index 00000000..937c69f9 --- /dev/null +++ b/example/jni/example.cpp @@ -0,0 +1,156 @@ +// +// Copyright(c) 2015 Gabi Melman. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) +// +// +// spdlog usage example +// +// + +#define SPDLOG_TRACE_ON +#define SPDLOG_DEBUG_ON + +#include "spdlog/spdlog.h" + +#include +#include + +void async_example(); +void syslog_example(); +void android_example(); +void user_defined_example(); +void err_handler_example(); + +namespace spd = spdlog; +int main(int, char *[]) +{ + try + { + // Console logger with color + auto console = spd::stdout_color_mt("console"); + console->info("Welcome to spdlog!"); + console->error("Some error message with arg{}..", 1); + + // Formatting examples + console->warn("Easy padding in numbers like {:08d}", 12); + console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); + console->info("Support for floats {:03.2f}", 1.23456); + console->info("Positional args are {1} {0}..", "too", "supported"); + console->info("{:<30}", "left aligned"); + + spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function"); + + // Create basic file logger (not rotated) + auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt"); + my_logger->info("Some log message"); + + // Create a file rotating logger with 5mb size max and 3 rotated files + auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); + for (int i = 0; i < 10; ++i) + rotating_logger->info("{} * {} equals {:>10}", i, i, i * i); + + // Create a daily logger - a new file is created every day on 2:30am + auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); + // trigger flush if the log severity is error or higher + daily_logger->flush_on(spd::level::err); + daily_logger->info(123.44); + + // Customize msg format for all messages + spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***"); + rotating_logger->info("This is another message with custom format"); + + // Runtime log levels + spd::set_level(spd::level::info); // Set global log level to info + console->debug("This message should not be displayed!"); + console->set_level(spd::level::debug); // Set specific logger's log level + console->debug("This message should be displayed.."); + + // Compile time log levels + // define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON + SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23); + SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23); + + // Asynchronous logging is very fast.. + // Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous.. + async_example(); + + // syslog example. linux/osx only + syslog_example(); + + // android example. compile with NDK + android_example(); + + // Log user-defined types example + user_defined_example(); + + // Change default log error handler + err_handler_example(); + + // Apply a function on all registered loggers + spd::apply_all([&](std::shared_ptr l) { l->info("End of example."); }); + + // Release and close all loggers + spdlog::drop_all(); + } + // Exceptions will only be thrown upon failed logger or sink construction (not during logging) + catch (const spd::spdlog_ex &ex) + { + std::cout << "Log init failed: " << ex.what() << std::endl; + return 1; + } +} + +void async_example() +{ + size_t q_size = 4096; // queue size must be power of 2 + spdlog::set_async_mode(q_size); + auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt"); + for (int i = 0; i < 100; ++i) + async_file->info("Async message #{}", i); +} + +// syslog example (linux/osx/freebsd) +void syslog_example() +{ +#ifdef SPDLOG_ENABLE_SYSLOG + std::string ident = "spdlog-example"; + auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID); + syslog_logger->warn("This is warning that will end up in syslog."); +#endif +} + +// Android example +void android_example() +{ +#if defined(__ANDROID__) + std::string tag = "spdlog-android"; + auto android_logger = spd::android_logger("android", tag); + android_logger->critical("Use \"adb shell logcat\" to view this message."); +#endif +} + +// user defined types logging by implementing operator<< +struct my_type +{ + int i; + template friend OStream &operator<<(OStream &os, const my_type &c) + { + return os << "[my_type i=" << c.i << "]"; + } +}; + +#include "spdlog/fmt/ostr.h" // must be included +void user_defined_example() +{ + spd::get("console")->info("user defined type: {}", my_type{14}); +} + +// +// custom error handler +// +void err_handler_example() +{ + // can be set globaly or per logger(logger->set_error_handler(..)) + spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; }); + spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3); +} diff --git a/example/multisink.cpp b/example/multisink.cpp index fe6539b5..d634bc36 100644 --- a/example/multisink.cpp +++ b/example/multisink.cpp @@ -4,7 +4,7 @@ #include namespace spd = spdlog; -int main(int, char*[]) +int main(int, char *[]) { bool enable_debug = true; try @@ -13,24 +13,24 @@ int main(int, char*[]) // This means that the same log_msg is forwarded to multiple sinks; // Each sink can have it's own log level and a message will be logged. std::vector sinks; - sinks.push_back( std::make_shared() ); - sinks.push_back( std::make_shared("./log_regular_file.txt") ); - sinks.push_back( std::make_shared("./log_debug_file.txt") ); + sinks.push_back(std::make_shared()); + sinks.push_back(std::make_shared("./log_regular_file.txt")); + sinks.push_back(std::make_shared("./log_debug_file.txt")); - spdlog::logger console_multisink("multisink", sinks.begin(), sinks.end() ); - console_multisink.set_level( spdlog::level::warn); + spdlog::logger console_multisink("multisink", sinks.begin(), sinks.end()); + console_multisink.set_level(spdlog::level::warn); - sinks[0]->set_level( spdlog::level::trace); // console. Allow everything. Default value - sinks[1]->set_level( spdlog::level::trace); // regular file. Allow everything. Default value - sinks[2]->set_level( spdlog::level::off); // regular file. Ignore everything. + sinks[0]->set_level(spdlog::level::trace); // console. Allow everything. Default value + sinks[1]->set_level(spdlog::level::trace); // regular file. Allow everything. Default value + sinks[2]->set_level(spdlog::level::off); // regular file. Ignore everything. console_multisink.warn("warn: will print only on console and regular file"); - if( enable_debug ) + if (enable_debug) { - console_multisink.set_level( spdlog::level::debug); // level of the logger - sinks[1]->set_level( spdlog::level::debug); // regular file - sinks[2]->set_level( spdlog::level::debug); // debug file + console_multisink.set_level(spdlog::level::debug); // level of the logger + sinks[1]->set_level(spdlog::level::debug); // regular file + sinks[2]->set_level(spdlog::level::debug); // debug file } console_multisink.debug("Debug: you should see this on console and both files"); @@ -38,10 +38,9 @@ int main(int, char*[]) spdlog::drop_all(); } // Exceptions will only be thrown upon failed logger or sink construction (not during logging) - catch (const spd::spdlog_ex& ex) + catch (const spd::spdlog_ex &ex) { std::cout << "Log init failed: " << ex.what() << std::endl; return 1; } } - diff --git a/example/utils.h b/example/utils.h index b260f724..6d6ee85d 100644 --- a/example/utils.h +++ b/example/utils.h @@ -5,15 +5,13 @@ #pragma once -#include #include #include +#include -namespace utils -{ +namespace utils { -template -inline std::string format(const T& value) +template inline std::string format(const T &value) { static std::locale loc(""); std::stringstream ss; @@ -22,8 +20,7 @@ inline std::string format(const T& value) return ss.str(); } -template<> -inline std::string format(const double & value) +template <> inline std::string format(const double &value) { static std::locale loc(""); std::stringstream ss; @@ -32,4 +29,4 @@ inline std::string format(const double & value) return ss.str(); } -} +} // namespace utils diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index be577a3b..78765972 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -20,48 +20,39 @@ #include #include -#include #include +#include -namespace spdlog -{ +namespace spdlog { -namespace details -{ +namespace details { class async_log_helper; } class async_logger SPDLOG_FINAL : public logger { public: - template - async_logger(const std::string& logger_name, - const It& begin, - const It& end, - size_t queue_size, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - const std::function& worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - const std::function& worker_teardown_cb = nullptr); + template + async_logger(const std::string &logger_name, const It &begin, const It &end, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); - async_logger(const std::string& logger_name, - sinks_init_list sinks, - size_t queue_size, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - const std::function& worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - const std::function& worker_teardown_cb = nullptr); + async_logger(const std::string &logger_name, sinks_init_list sinks, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); - async_logger(const std::string& logger_name, - sink_ptr single_sink, - size_t queue_size, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - const std::function& worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - const std::function& worker_teardown_cb = nullptr); + async_logger(const std::string &logger_name, sink_ptr single_sink, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); - //Wait for the queue to be empty, and flush synchronously - //Warning: this can potentially last forever as we wait it to complete + // Wait for the queue to be empty, and flush synchronously + // Warning: this can potentially last forever as we wait it to complete void flush() override; // Error handler @@ -69,13 +60,13 @@ public: log_err_handler error_handler() override; protected: - void _sink_it(details::log_msg& msg) override; + void _sink_it(details::log_msg &msg) override; void _set_formatter(spdlog::formatter_ptr msg_formatter) override; - void _set_pattern(const std::string& pattern, pattern_time_type pattern_time) override; + void _set_pattern(const std::string &pattern, pattern_time_type pattern_time) override; private: std::unique_ptr _async_log_helper; }; -} +} // namespace spdlog #include "details/async_logger_impl.h" diff --git a/include/spdlog/details/async_log_helper.h b/include/spdlog/details/async_log_helper.h index 6faf2f7c..78058975 100644 --- a/include/spdlog/details/async_log_helper.h +++ b/include/spdlog/details/async_log_helper.h @@ -13,11 +13,11 @@ #pragma once #include "../common.h" -#include "../sinks/sink.h" -#include "../details/mpmc_bounded_q.h" #include "../details/log_msg.h" +#include "../details/mpmc_bounded_q.h" #include "../details/os.h" #include "../formatter.h" +#include "../sinks/sink.h" #include #include @@ -28,10 +28,7 @@ #include #include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { class async_log_helper { @@ -57,24 +54,25 @@ class async_log_helper async_msg() = default; ~async_msg() = default; - explicit async_msg(async_msg_type m_type) : - level(level::info), - thread_id(0), - msg_type(m_type), - msg_id(0) - {} + explicit async_msg(async_msg_type m_type) + : level(level::info) + , thread_id(0) + , msg_type(m_type) + , msg_id(0) + { + } -async_msg(async_msg&& other) SPDLOG_NOEXCEPT : - logger_name(std::move(other.logger_name)), - level(std::move(other.level)), - time(std::move(other.time)), - thread_id(other.thread_id), - txt(std::move(other.txt)), - msg_type(std::move(other.msg_type)), - msg_id(other.msg_id) - {} + async_msg(async_msg &&other) SPDLOG_NOEXCEPT : logger_name(std::move(other.logger_name)), + level(std::move(other.level)), + time(std::move(other.time)), + thread_id(other.thread_id), + txt(std::move(other.txt)), + msg_type(std::move(other.msg_type)), + msg_id(other.msg_id) + { + } - async_msg& operator=(async_msg&& other) SPDLOG_NOEXCEPT + async_msg &operator=(async_msg &&other) SPDLOG_NOEXCEPT { logger_name = std::move(other.logger_name); level = other.level; @@ -87,17 +85,17 @@ async_msg(async_msg&& other) SPDLOG_NOEXCEPT : } // never copy or assign. should only be moved.. - async_msg(const async_msg&) = delete; - async_msg& operator=(const async_msg& other) = delete; + async_msg(const async_msg &) = delete; + async_msg &operator=(const async_msg &other) = delete; // construct from log_msg - explicit async_msg(const details::log_msg& m): - level(m.level), - time(m.time), - thread_id(m.thread_id), - txt(m.raw.data(), m.raw.size()), - msg_type(async_msg_type::log), - msg_id(m.msg_id) + explicit async_msg(const details::log_msg &m) + : level(m.level) + , time(m.time) + , thread_id(m.thread_id) + , txt(m.raw.data(), m.raw.size()) + , msg_type(async_msg_type::log) + , msg_id(m.msg_id) { #ifndef SPDLOG_NO_NAME logger_name = *m.logger_name; @@ -122,22 +120,18 @@ public: using clock = std::chrono::steady_clock; - async_log_helper(formatter_ptr formatter, - std::vector sinks, - size_t queue_size, - const log_err_handler err_handler, - const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, - std::function worker_warmup_cb = nullptr, - const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), - std::function worker_teardown_cb = nullptr); + async_log_helper(formatter_ptr formatter, std::vector sinks, size_t queue_size, const log_err_handler err_handler, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, std::function worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + std::function worker_teardown_cb = nullptr); - void log(const details::log_msg& msg); + void log(const details::log_msg &msg); // stop logging and join the back thread ~async_log_helper(); - async_log_helper(const async_log_helper&) = delete; - async_log_helper& operator=(const async_log_helper&) = delete; + async_log_helper(const async_log_helper &) = delete; + async_log_helper &operator=(const async_log_helper &) = delete; void set_formatter(formatter_ptr msg_formatter); @@ -173,49 +167,41 @@ private: // worker thread std::thread _worker_thread; - void push_msg(async_msg&& new_msg); + void push_msg(async_msg &&new_msg); // worker thread main loop void worker_loop(); // pop next message from the queue and process it. will set the last_pop to the pop time // return false if termination of the queue is required - bool process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush); + bool process_next_msg(log_clock::time_point &last_pop, log_clock::time_point &last_flush); - void handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush); + void handle_flush_interval(log_clock::time_point &now, log_clock::time_point &last_flush); // sleep,yield or return immediately using the time passed since last message as a hint - static void sleep_or_yield(const spdlog::log_clock::time_point& now, const log_clock::time_point& last_op_time); + static void sleep_or_yield(const spdlog::log_clock::time_point &now, const log_clock::time_point &last_op_time); // wait until the queue is empty void wait_empty_q(); - }; -} -} +}} // namespace spdlog::details /////////////////////////////////////////////////////////////////////////////// // async_sink class implementation /////////////////////////////////////////////////////////////////////////////// -inline spdlog::details::async_log_helper::async_log_helper( - formatter_ptr formatter, - std::vector sinks, - size_t queue_size, - log_err_handler err_handler, - const async_overflow_policy overflow_policy, - std::function worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - std::function worker_teardown_cb): - _formatter(std::move(formatter)), - _sinks(std::move(sinks)), - _q(queue_size), - _err_handler(std::move(err_handler)), - _flush_requested(false), - _terminate_requested(false), - _overflow_policy(overflow_policy), - _worker_warmup_cb(std::move(worker_warmup_cb)), - _flush_interval_ms(flush_interval_ms), - _worker_teardown_cb(std::move(worker_teardown_cb)) +inline spdlog::details::async_log_helper::async_log_helper(formatter_ptr formatter, std::vector sinks, size_t queue_size, + log_err_handler err_handler, const async_overflow_policy overflow_policy, std::function worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, std::function worker_teardown_cb) + : _formatter(std::move(formatter)) + , _sinks(std::move(sinks)) + , _q(queue_size) + , _err_handler(std::move(err_handler)) + , _flush_requested(false) + , _terminate_requested(false) + , _overflow_policy(overflow_policy) + , _worker_warmup_cb(std::move(worker_warmup_cb)) + , _flush_interval_ms(flush_interval_ms) + , _worker_teardown_cb(std::move(worker_teardown_cb)) { _worker_thread = std::thread(&async_log_helper::worker_loop, this); } @@ -234,14 +220,13 @@ inline spdlog::details::async_log_helper::~async_log_helper() } } - -//Try to push and block until succeeded (if the policy is not to discard when the queue is full) -inline void spdlog::details::async_log_helper::log(const details::log_msg& msg) +// Try to push and block until succeeded (if the policy is not to discard when the queue is full) +inline void spdlog::details::async_log_helper::log(const details::log_msg &msg) { push_msg(async_msg(msg)); } -inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg&& new_msg) +inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg &&new_msg) { if (!_q.enqueue(std::move(new_msg)) && _overflow_policy != async_overflow_policy::discard_log_msg) { @@ -251,8 +236,7 @@ inline void spdlog::details::async_log_helper::push_msg(details::async_log_helpe { now = details::os::now(); sleep_or_yield(now, last_op_time); - } - while (!_q.enqueue(std::move(new_msg))); + } while (!_q.enqueue(std::move(new_msg))); } } @@ -261,12 +245,13 @@ inline void spdlog::details::async_log_helper::flush(bool wait_for_q) { push_msg(async_msg(async_msg_type::flush)); if (wait_for_q) - wait_empty_q(); //return when queue is empty + wait_empty_q(); // return when queue is empty } inline void spdlog::details::async_log_helper::worker_loop() { - if (_worker_warmup_cb) _worker_warmup_cb(); + if (_worker_warmup_cb) + _worker_warmup_cb(); auto last_pop = details::os::now(); auto last_flush = last_pop; auto active = true; @@ -280,19 +265,18 @@ inline void spdlog::details::async_log_helper::worker_loop() { _err_handler(ex.what()); } - catch(...) + catch (...) { _err_handler("Unknown exeption in async logger worker loop."); } } - if (_worker_teardown_cb) _worker_teardown_cb(); - - + if (_worker_teardown_cb) + _worker_teardown_cb(); } // process next message in the queue // return true if this thread should still be active (while no terminate msg was received) -inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush) +inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_point &last_pop, log_clock::time_point &last_flush) { async_msg incoming_async_msg; @@ -334,9 +318,10 @@ inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_ } // flush all sinks if _flush_interval_ms has expired -inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush) +inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::time_point &now, log_clock::time_point &last_flush) { - auto should_flush = _flush_requested || (_flush_interval_ms != std::chrono::milliseconds::zero() && now - last_flush >= _flush_interval_ms); + auto should_flush = + _flush_requested || (_flush_interval_ms != std::chrono::milliseconds::zero() && now - last_flush >= _flush_interval_ms); if (should_flush) { for (auto &s : _sinks) @@ -352,10 +337,11 @@ inline void spdlog::details::async_log_helper::set_formatter(formatter_ptr msg_f } // spin, yield or sleep. use the time passed since last message as a hint -inline void spdlog::details::async_log_helper::sleep_or_yield(const spdlog::log_clock::time_point& now, const spdlog::log_clock::time_point& last_op_time) +inline void spdlog::details::async_log_helper::sleep_or_yield( + const spdlog::log_clock::time_point &now, const spdlog::log_clock::time_point &last_op_time) { - using std::chrono::milliseconds; using std::chrono::microseconds; + using std::chrono::milliseconds; auto time_since_op = now - last_op_time; diff --git a/include/spdlog/details/async_logger_impl.h b/include/spdlog/details/async_logger_impl.h index 72bd4f98..ca458740 100644 --- a/include/spdlog/details/async_logger_impl.h +++ b/include/spdlog/details/async_logger_impl.h @@ -8,49 +8,39 @@ // Async Logger implementation // Use an async_sink (queue per logger) to perform the logging in a worker thread -#include "../details/async_log_helper.h" #include "../async_logger.h" +#include "../details/async_log_helper.h" -#include -#include #include +#include #include +#include -template -inline spdlog::async_logger::async_logger(const std::string& logger_name, - const It& begin, - const It& end, - size_t queue_size, - const async_overflow_policy overflow_policy, - const std::function& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function& worker_teardown_cb) : - logger(logger_name, begin, end), - _async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb)) +template +inline spdlog::async_logger::async_logger(const std::string &logger_name, const It &begin, const It &end, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) + : logger(logger_name, begin, end) + , _async_log_helper(new details::async_log_helper( + _formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb)) { } -inline spdlog::async_logger::async_logger(const std::string& logger_name, - sinks_init_list sinks_list, - size_t queue_size, - const async_overflow_policy overflow_policy, - const std::function& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function& worker_teardown_cb) : - async_logger(logger_name, sinks_list.begin(), sinks_list.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {} - -inline spdlog::async_logger::async_logger(const std::string& logger_name, - sink_ptr single_sink, - size_t queue_size, - const async_overflow_policy overflow_policy, - const std::function& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function& worker_teardown_cb) : - async_logger(logger_name, +inline spdlog::async_logger::async_logger(const std::string &logger_name, sinks_init_list sinks_list, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) + : async_logger(logger_name, sinks_list.begin(), sinks_list.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, + worker_teardown_cb) { - std::move(single_sink) -}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {} +} +inline spdlog::async_logger::async_logger(const std::string &logger_name, sink_ptr single_sink, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) + : async_logger( + logger_name, {std::move(single_sink)}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) +{ +} inline void spdlog::async_logger::flush() { @@ -62,28 +52,25 @@ inline void spdlog::async_logger::set_error_handler(spdlog::log_err_handler err_ { _err_handler = err_handler; _async_log_helper->set_error_handler(err_handler); - } inline spdlog::log_err_handler spdlog::async_logger::error_handler() { return _err_handler; } - inline void spdlog::async_logger::_set_formatter(spdlog::formatter_ptr msg_formatter) { _formatter = msg_formatter; _async_log_helper->set_formatter(_formatter); } -inline void spdlog::async_logger::_set_pattern(const std::string& pattern, pattern_time_type pattern_time) +inline void spdlog::async_logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time) { _formatter = std::make_shared(pattern, pattern_time); _async_log_helper->set_formatter(_formatter); } - -inline void spdlog::async_logger::_sink_it(details::log_msg& msg) +inline void spdlog::async_logger::_sink_it(details::log_msg &msg) { try { @@ -98,10 +85,9 @@ inline void spdlog::async_logger::_sink_it(details::log_msg& msg) { _err_handler(ex.what()); } - catch(...) + catch (...) { _err_handler("Unknown exception in logger " + _name); throw; } - } diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index d7ccf59b..0d24a91b 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -9,20 +9,17 @@ // When failing to open a file, retry several times(5) with small delay between the tries(10 ms) // Throw spdlog_ex exception on errors -#include "../details/os.h" #include "../details/log_msg.h" +#include "../details/os.h" +#include #include #include #include #include #include -#include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { class file_helper { @@ -33,16 +30,15 @@ public: explicit file_helper() = default; - file_helper(const file_helper&) = delete; - file_helper& operator=(const file_helper&) = delete; + file_helper(const file_helper &) = delete; + file_helper &operator=(const file_helper &) = delete; ~file_helper() { close(); } - - void open(const filename_t& fname, bool truncate = false) + void open(const filename_t &fname, bool truncate = false) { close(); auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab"); @@ -63,7 +59,6 @@ public: if (_filename.empty()) throw spdlog_ex("Failed re opening file - was not opened before"); open(_filename, truncate); - } void flush() @@ -80,7 +75,7 @@ public: } } - void write(const log_msg& msg) + void write(const log_msg &msg) { size_t msg_size = msg.formatted.size(); auto data = msg.formatted.data(); @@ -97,12 +92,12 @@ public: return os::filesize(_fd); } - const filename_t& filename() const + const filename_t &filename() const { return _filename; } - static bool file_exists(const filename_t& fname) + static bool file_exists(const filename_t &fname) { return os::file_exists(fname); } @@ -120,7 +115,7 @@ public: // ".mylog" => (".mylog". "") // "my_folder/.mylog" => ("my_folder/.mylog", "") // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt") - static std::tuple split_by_extenstion(const spdlog::filename_t& fname) + static std::tuple split_by_extenstion(const spdlog::filename_t &fname) { auto ext_index = fname.rfind('.'); @@ -138,8 +133,7 @@ public: } private: - FILE* _fd{ nullptr }; + FILE *_fd{nullptr}; filename_t _filename; }; -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h index 8b441cab..a1e8b2ee 100644 --- a/include/spdlog/details/log_msg.h +++ b/include/spdlog/details/log_msg.h @@ -11,16 +11,13 @@ #include #include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { struct log_msg { log_msg() = default; - log_msg(const std::string *loggers_name, level::level_enum lvl) : - logger_name(loggers_name), - level(lvl) + log_msg(const std::string *loggers_name, level::level_enum lvl) + : logger_name(loggers_name) + , level(lvl) { #ifndef SPDLOG_NO_DATETIME time = os::now(); @@ -31,18 +28,16 @@ struct log_msg #endif } - log_msg(const log_msg& other) = delete; - log_msg& operator=(log_msg&& other) = delete; - log_msg(log_msg&& other) = delete; + log_msg(const log_msg &other) = delete; + log_msg &operator=(log_msg &&other) = delete; + log_msg(log_msg &&other) = delete; - - const std::string *logger_name{ nullptr }; + const std::string *logger_name{nullptr}; level::level_enum level; log_clock::time_point time; size_t thread_id; fmt::MemoryWriter raw; fmt::MemoryWriter formatted; - size_t msg_id{ 0 }; + size_t msg_id{0}; }; -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/logger_impl.h b/include/spdlog/details/logger_impl.h index 11cbc7e4..3b64543d 100644 --- a/include/spdlog/details/logger_impl.h +++ b/include/spdlog/details/logger_impl.h @@ -13,54 +13,47 @@ // create logger with given name, sinks and the default pattern formatter // all other ctors will call this one -template -inline spdlog::logger::logger(std::string logger_name, const It& begin, const It& end): - _name(std::move(logger_name)), - _sinks(begin, end), - _formatter(std::make_shared("%+")), - _level(level::info), - _flush_level(level::off), - _last_err_time(0), - _msg_counter(1) // message counter will start from 1. 0-message id will be reserved for controll messages +template +inline spdlog::logger::logger(std::string logger_name, const It &begin, const It &end) + : _name(std::move(logger_name)) + , _sinks(begin, end) + , _formatter(std::make_shared("%+")) + , _level(level::info) + , _flush_level(level::off) + , _last_err_time(0) + , _msg_counter(1) // message counter will start from 1. 0-message id will be reserved for controll messages { - _err_handler = [this](const std::string &msg) - { - this->_default_err_handler(msg); - }; + _err_handler = [this](const std::string &msg) { this->_default_err_handler(msg); }; } // ctor with sinks as init list -inline spdlog::logger::logger(const std::string& logger_name, sinks_init_list sinks_list): - logger(logger_name, sinks_list.begin(), sinks_list.end()) -{} - +inline spdlog::logger::logger(const std::string &logger_name, sinks_init_list sinks_list) + : logger(logger_name, sinks_list.begin(), sinks_list.end()) +{ +} // ctor with single sink -inline spdlog::logger::logger(const std::string& logger_name, spdlog::sink_ptr single_sink): - logger(logger_name, +inline spdlog::logger::logger(const std::string &logger_name, spdlog::sink_ptr single_sink) + : logger(logger_name, {std::move(single_sink)}) { - std::move(single_sink) -}) -{} - +} inline spdlog::logger::~logger() = default; - inline void spdlog::logger::set_formatter(spdlog::formatter_ptr msg_formatter) { _set_formatter(std::move(msg_formatter)); } -inline void spdlog::logger::set_pattern(const std::string& pattern, pattern_time_type pattern_time) +inline void spdlog::logger::set_pattern(const std::string &pattern, pattern_time_type pattern_time) { _set_pattern(pattern, pattern_time); } -template -inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Args&... args) +template inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) { - if (!should_log(lvl)) return; + if (!should_log(lvl)) + return; try { @@ -77,17 +70,17 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Ar { _err_handler(ex.what()); } - catch(...) + catch (...) { _err_handler("Unknown exception in logger " + _name); throw; } } -template -inline void spdlog::logger::log(level::level_enum lvl, const char* msg) +template inline void spdlog::logger::log(level::level_enum lvl, const char *msg) { - if (!should_log(lvl)) return; + if (!should_log(lvl)) + return; try { details::log_msg log_msg(&_name, lvl); @@ -105,10 +98,10 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* msg) } } -template -inline void spdlog::logger::log(level::level_enum lvl, const T& msg) +template inline void spdlog::logger::log(level::level_enum lvl, const T &msg) { - if (!should_log(lvl)) return; + if (!should_log(lvl)) + return; try { details::log_msg log_msg(&_name, lvl); @@ -126,98 +119,78 @@ inline void spdlog::logger::log(level::level_enum lvl, const T& msg) } } - -template -inline void spdlog::logger::trace(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::trace(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::trace, fmt, arg1, args...); } -template -inline void spdlog::logger::debug(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::debug(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::debug, fmt, arg1, args...); } -template -inline void spdlog::logger::info(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::info(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::info, fmt, arg1, args...); } -template -inline void spdlog::logger::warn(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::warn(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::warn, fmt, arg1, args...); } -template -inline void spdlog::logger::error(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::error(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::err, fmt, arg1, args...); } -template -inline void spdlog::logger::critical(const char* fmt, const Arg1 &arg1, const Args&... args) +template inline void spdlog::logger::critical(const char *fmt, const Arg1 &arg1, const Args &... args) { log(level::critical, fmt, arg1, args...); } - -template -inline void spdlog::logger::trace(const T& msg) +template inline void spdlog::logger::trace(const T &msg) { log(level::trace, msg); } -template -inline void spdlog::logger::debug(const T& msg) +template inline void spdlog::logger::debug(const T &msg) { log(level::debug, msg); } - -template -inline void spdlog::logger::info(const T& msg) +template inline void spdlog::logger::info(const T &msg) { log(level::info, msg); } - -template -inline void spdlog::logger::warn(const T& msg) +template inline void spdlog::logger::warn(const T &msg) { log(level::warn, msg); } -template -inline void spdlog::logger::error(const T& msg) +template inline void spdlog::logger::error(const T &msg) { log(level::err, msg); } -template -inline void spdlog::logger::critical(const T& msg) +template inline void spdlog::logger::critical(const T &msg) { log(level::critical, msg); } - - #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT #include #include -template -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* msg) +template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *msg) { - std::wstring_convert > conv; + std::wstring_convert> conv; log(lvl, conv.to_bytes(msg)); } -template -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args) { fmt::WMemoryWriter wWriter; @@ -225,51 +198,42 @@ inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const log(lvl, wWriter.c_str()); } -template -inline void spdlog::logger::trace(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args) { log(level::trace, fmt, args...); } -template -inline void spdlog::logger::debug(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args) { log(level::debug, fmt, args...); } -template -inline void spdlog::logger::info(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args) { log(level::info, fmt, args...); } - -template -inline void spdlog::logger::warn(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args) { log(level::warn, fmt, args...); } -template -inline void spdlog::logger::error(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args) { log(level::err, fmt, args...); } -template -inline void spdlog::logger::critical(const wchar_t* fmt, const Args&... args) +template inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args) { log(level::critical, fmt, args...); } #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - - // // name and level // -inline const std::string& spdlog::logger::name() const +inline const std::string &spdlog::logger::name() const { return _name; } @@ -307,7 +271,7 @@ inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) cons // // protected virtual called at end of each user log call (if enabled) by the line_logger // -inline void spdlog::logger::_sink_it(details::log_msg& msg) +inline void spdlog::logger::_sink_it(details::log_msg &msg) { #if defined(SPDLOG_ENABLE_MESSAGE_COUNTER) _incr_msg_counter(msg); @@ -315,17 +279,17 @@ inline void spdlog::logger::_sink_it(details::log_msg& msg) _formatter->format(msg); for (auto &sink : _sinks) { - if( sink->should_log( msg.level)) + if (sink->should_log(msg.level)) { sink->log(msg); } } - if(_should_flush_on(msg)) + if (_should_flush_on(msg)) flush(); } -inline void spdlog::logger::_set_pattern(const std::string& pattern, pattern_time_type pattern_time) +inline void spdlog::logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time) { _formatter = std::make_shared(pattern, pattern_time); } @@ -337,7 +301,7 @@ inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter) inline void spdlog::logger::flush() { - for (auto& sink : _sinks) + for (auto &sink : _sinks) sink->flush(); } @@ -366,8 +330,7 @@ inline void spdlog::logger::_incr_msg_counter(details::log_msg &msg) msg.msg_id = _msg_counter.fetch_add(1, std::memory_order_relaxed); } -inline const std::vector& spdlog::logger::sinks() const +inline const std::vector &spdlog::logger::sinks() const { return _sinks; } - diff --git a/include/spdlog/details/mpmc_bounded_q.h b/include/spdlog/details/mpmc_bounded_q.h index 6187f3b9..567f292f 100644 --- a/include/spdlog/details/mpmc_bounded_q.h +++ b/include/spdlog/details/mpmc_bounded_q.h @@ -48,23 +48,19 @@ Distributed under the MIT License (http://opensource.org/licenses/MIT) #include #include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { -template -class mpmc_bounded_queue +template class mpmc_bounded_queue { public: using item_type = T; explicit mpmc_bounded_queue(size_t buffer_size) - :max_size_(buffer_size), - buffer_(new cell_t[buffer_size]), - buffer_mask_(buffer_size - 1) + : max_size_(buffer_size) + , buffer_(new cell_t[buffer_size]) + , buffer_mask_(buffer_size - 1) { - //queue size must be power of two + // queue size must be power of two if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0))) throw spdlog_ex("async logger queue size must be power of two"); @@ -79,12 +75,12 @@ public: delete[] buffer_; } - mpmc_bounded_queue(mpmc_bounded_queue const&) = delete; - void operator=(mpmc_bounded_queue const&) = delete; + mpmc_bounded_queue(mpmc_bounded_queue const &) = delete; + void operator=(mpmc_bounded_queue const &) = delete; - bool enqueue(T&& data) + bool enqueue(T &&data) { - cell_t* cell; + cell_t *cell; size_t pos = enqueue_pos_.load(std::memory_order_relaxed); for (;;) { @@ -110,15 +106,14 @@ public: return true; } - bool dequeue(T& data) + bool dequeue(T &data) { - cell_t* cell; + cell_t *cell; size_t pos = dequeue_pos_.load(std::memory_order_relaxed); for (;;) { cell = &buffer_[pos & buffer_mask_]; - size_t seq = - cell->sequence_.load(std::memory_order_acquire); + size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = static_cast(seq) - static_cast(pos + 1); if (dif == 0) { @@ -144,32 +139,30 @@ public: front = enqueue_pos_.load(std::memory_order_acquire); back = dequeue_pos_.load(std::memory_order_acquire); front1 = enqueue_pos_.load(std::memory_order_relaxed); - } - while (front != front1); + } while (front != front1); return back == front; } private: struct cell_t { - std::atomic sequence_; - T data_; + std::atomic sequence_; + T data_; }; size_t const max_size_; - static size_t const cacheline_size = 64; + static size_t const cacheline_size = 64; using cacheline_pad_t = char[cacheline_size]; - cacheline_pad_t pad0_; - cell_t* const buffer_; - size_t const buffer_mask_; - cacheline_pad_t pad1_; - std::atomic enqueue_pos_; - cacheline_pad_t pad2_; - std::atomic dequeue_pos_; - cacheline_pad_t pad3_; + cacheline_pad_t pad0_; + cell_t *const buffer_; + size_t const buffer_mask_; + cacheline_pad_t pad1_; + std::atomic enqueue_pos_; + cacheline_pad_t pad2_; + std::atomic dequeue_pos_; + cacheline_pad_t pad3_; }; -} // ns details -} // ns spdlog +}} // namespace spdlog::details diff --git a/include/spdlog/details/null_mutex.h b/include/spdlog/details/null_mutex.h index 82b0ed84..5f4ce46a 100644 --- a/include/spdlog/details/null_mutex.h +++ b/include/spdlog/details/null_mutex.h @@ -8,10 +8,7 @@ #include // null, no cost dummy "mutex" and dummy "atomic" int -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { struct null_mutex { void lock() {} @@ -27,8 +24,10 @@ struct null_atomic_int int value; null_atomic_int() = default; - explicit null_atomic_int(int val) : value(val) - {} + explicit null_atomic_int(int val) + : value(val) + { + } int load(std::memory_order) const { @@ -41,5 +40,4 @@ struct null_atomic_int } }; -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index 4de7b9f8..271348da 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -6,30 +6,30 @@ #include "../common.h" +#include +#include #include +#include +#include #include #include #include -#include -#include -#include -#include -#include #include #include +#include #ifdef _WIN32 #ifndef NOMINMAX -#define NOMINMAX //prevent windows redefining min/max +#define NOMINMAX // prevent windows redefining min/max #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif -#include +#include // _get_osfhandle and _isatty support #include // _get_pid support -#include // _get_osfhandle and _isatty support +#include #ifdef __MINGW32__ #include @@ -37,8 +37,8 @@ #else // unix -#include #include +#include #ifdef __linux__ #include //Use gettid() syscall under linux to get thread id @@ -47,19 +47,13 @@ #include //Use thr_self() syscall under FreeBSD to get thread id #endif -#endif //unix +#endif // unix -#ifndef __has_feature // Clang - feature checking macros. -#define __has_feature(x) 0 // Compatibility with non-clang compilers. +#ifndef __has_feature // Clang - feature checking macros. +#define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif - -namespace spdlog -{ -namespace details -{ -namespace os -{ +namespace spdlog { namespace details { namespace os { inline spdlog::log_clock::time_point now() { @@ -68,14 +62,11 @@ inline spdlog::log_clock::time_point now() timespec ts; ::clock_gettime(CLOCK_REALTIME_COARSE, &ts); return std::chrono::time_point( - std::chrono::duration_cast( - std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec))); - + std::chrono::duration_cast(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec))); #else return log_clock::now(); #endif - } inline std::tm localtime(const std::time_t &time_tt) { @@ -114,24 +105,19 @@ inline std::tm gmtime() std::time_t now_t = time(nullptr); return gmtime(now_t); } -inline bool operator==(const std::tm& tm1, const std::tm& tm2) +inline bool operator==(const std::tm &tm1, const std::tm &tm2) { - return (tm1.tm_sec == tm2.tm_sec && - tm1.tm_min == tm2.tm_min && - tm1.tm_hour == tm2.tm_hour && - tm1.tm_mday == tm2.tm_mday && - tm1.tm_mon == tm2.tm_mon && - tm1.tm_year == tm2.tm_year && - tm1.tm_isdst == tm2.tm_isdst); + return (tm1.tm_sec == tm2.tm_sec && tm1.tm_min == tm2.tm_min && tm1.tm_hour == tm2.tm_hour && tm1.tm_mday == tm2.tm_mday && + tm1.tm_mon == tm2.tm_mon && tm1.tm_year == tm2.tm_year && tm1.tm_isdst == tm2.tm_isdst); } -inline bool operator!=(const std::tm& tm1, const std::tm& tm2) +inline bool operator!=(const std::tm &tm1, const std::tm &tm2) { return !(tm1 == tm2); } // eol definition -#if !defined (SPDLOG_EOL) +#if !defined(SPDLOG_EOL) #ifdef _WIN32 #define SPDLOG_EOL "\r\n" #else @@ -139,9 +125,7 @@ inline bool operator!=(const std::tm& tm1, const std::tm& tm2) #endif #endif -SPDLOG_CONSTEXPR static const char* default_eol = SPDLOG_EOL; - - +SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL; // folder separator #ifdef _WIN32 @@ -150,7 +134,6 @@ SPDLOG_CONSTEXPR static const char folder_sep = '\\'; SPDLOG_CONSTEXPR static const char folder_sep = '/'; #endif - inline void prevent_child_fd(FILE *f) { @@ -167,9 +150,8 @@ inline void prevent_child_fd(FILE *f) #endif } - -//fopen_s on non windows for writing -inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mode) +// fopen_s on non windows for writing +inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode) { #ifdef _WIN32 #ifdef SPDLOG_WCHAR_FILENAMES @@ -177,7 +159,7 @@ inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mod #else *fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYWR); #endif -#else //unix +#else // unix *fp = fopen((filename.c_str()), mode.c_str()); #endif @@ -188,7 +170,6 @@ inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mod return *fp == nullptr; } - inline int remove(const filename_t &filename) { #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) @@ -198,7 +179,7 @@ inline int remove(const filename_t &filename) #endif } -inline int rename(const filename_t& filename1, const filename_t& filename2) +inline int rename(const filename_t &filename1, const filename_t &filename2) { #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) return _wrename(filename1.c_str(), filename2.c_str()); @@ -207,9 +188,8 @@ inline int rename(const filename_t& filename1, const filename_t& filename2) #endif } - -//Return if file exists -inline bool file_exists(const filename_t& filename) +// Return if file exists +inline bool file_exists(const filename_t &filename) { #ifdef _WIN32 #ifdef SPDLOG_WCHAR_FILENAMES @@ -218,28 +198,25 @@ inline bool file_exists(const filename_t& filename) auto attribs = GetFileAttributesA(filename.c_str()); #endif return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY)); -#else //common linux/unix all have the stat system call +#else // common linux/unix all have the stat system call struct stat buffer; return (stat(filename.c_str(), &buffer) == 0); #endif } - - - -//Return file size according to open FILE* object +// Return file size according to open FILE* object inline size_t filesize(FILE *f) { if (f == nullptr) throw spdlog_ex("Failed getting file size. fd is null"); -#if defined ( _WIN32) && !defined(__CYGWIN__) +#if defined(_WIN32) && !defined(__CYGWIN__) int fd = _fileno(f); -#if _WIN64 //64 bits +#if _WIN64 // 64 bits struct _stat64 st; if (_fstat64(fd, &st) == 0) return st.st_size; -#else //windows 32 bits +#else // windows 32 bits long ret = _filelength(fd); if (ret >= 0) return static_cast(ret); @@ -247,9 +224,9 @@ inline size_t filesize(FILE *f) #else // unix int fd = fileno(f); - //64 bits(but not in osx or cygwin, where fstat64 is deprecated) + // 64 bits(but not in osx or cygwin, where fstat64 is deprecated) #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) - struct stat64 st ; + struct stat64 st; if (fstat64(fd, &st) == 0) return static_cast(st.st_size); #else // unix 32 bits or cygwin @@ -261,11 +238,8 @@ inline size_t filesize(FILE *f) throw spdlog_ex("Failed getting file size from fd", errno); } - - - -//Return utc offset in minutes or throw spdlog_ex on failure -inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) +// Return utc offset in minutes or throw spdlog_ex on failure +inline int utc_minutes_offset(const std::tm &tm = details::os::localtime()) { #ifdef _WIN32 @@ -291,23 +265,22 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris struct helper { - static long int calculate_gmt_offset(const std::tm & localtm = details::os::localtime(), const std::tm & gmtm = details::os::gmtime()) + static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime()) { int local_year = localtm.tm_year + (1900 - 1); int gmt_year = gmtm.tm_year + (1900 - 1); long int days = ( - // difference in day of year - localtm.tm_yday - gmtm.tm_yday + // difference in day of year + localtm.tm_yday - + gmtm.tm_yday - // + intervening leap days - + ((local_year >> 2) - (gmt_year >> 2)) - - (local_year / 100 - gmt_year / 100) - + ((local_year / 100 >> 2) - (gmt_year / 100 >> 2)) + // + intervening leap days + + ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) + + ((local_year / 100 >> 2) - (gmt_year / 100 >> 2)) - // + difference in years * 365 */ - + (long int)(local_year - gmt_year) * 365 - ); + // + difference in years * 365 */ + + (long int)(local_year - gmt_year) * 365); long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour); long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min); @@ -326,16 +299,16 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) #endif } -//Return current thread id as size_t -//It exists because the std::this_thread::get_id() is much slower(especially under VS 2013) +// Return current thread id as size_t +// It exists because the std::this_thread::get_id() is much slower(especially under VS 2013) inline size_t _thread_id() { #ifdef _WIN32 return static_cast(::GetCurrentThreadId()); #elif __linux__ -# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) -# define SYS_gettid __NR_gettid -# endif +#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) +#define SYS_gettid __NR_gettid +#endif return static_cast(syscall(SYS_gettid)); #elif __FreeBSD__ long tid; @@ -345,25 +318,23 @@ inline size_t _thread_id() uint64_t tid; pthread_threadid_np(nullptr, &tid); return static_cast(tid); -#else //Default to standard C++11 (other Unix) +#else // Default to standard C++11 (other Unix) return static_cast(std::hash()(std::this_thread::get_id())); #endif } -//Return current thread id as size_t (from thread local storage) +// Return current thread id as size_t (from thread local storage) inline size_t thread_id() { -#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_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) || \ + (defined(__clang__) && !__has_feature(cxx_thread_local)) return _thread_id(); #else // cache thread id in tls static thread_local const size_t tid = _thread_id(); return tid; #endif - - } - // This is avoid msvc issue in sleep_for that happens if the clock changes. // See https://github.com/gabime/spdlog/issues/609 inline void sleep_for_millis(int milliseconds) @@ -377,21 +348,21 @@ inline void sleep_for_millis(int milliseconds) // wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined) #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) -#define SPDLOG_FILENAME_T(s) L ## s -inline std::string filename_to_str(const filename_t& filename) +#define SPDLOG_FILENAME_T(s) L##s +inline std::string filename_to_str(const filename_t &filename) { std::wstring_convert, wchar_t> c; return c.to_bytes(filename); } #else #define SPDLOG_FILENAME_T(s) s -inline std::string filename_to_str(const filename_t& filename) +inline std::string filename_to_str(const filename_t &filename) { return filename; } #endif -inline std::string errno_to_string(char[256], char* res) +inline std::string errno_to_string(char[256], char *res) { return std::string(res); } @@ -417,17 +388,17 @@ inline std::string errno_str(int err_num) else return "Unknown error"; -#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \ - ((_POSIX_C_SOURCE >= 200112L) && ! defined(_GNU_SOURCE)) // posix version +#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \ + ((_POSIX_C_SOURCE >= 200112L) && !defined(_GNU_SOURCE)) // posix version if (strerror_r(err_num, buf, buf_size) == 0) return std::string(buf); else return "Unknown error"; -#else // gnu version (might not use the given buf, so its retval pointer must be used) +#else // gnu version (might not use the given buf, so its retval pointer must be used) auto err = strerror_r(err_num, buf, buf_size); // let compiler choose type - return errno_to_string(buf, err); // use overloading to select correct stringify function + return errno_to_string(buf, err); // use overloading to select correct stringify function #endif } @@ -439,10 +410,8 @@ inline int pid() #else return static_cast(::getpid()); #endif - } - // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ inline bool is_color_terminal() @@ -450,11 +419,8 @@ inline bool is_color_terminal() #ifdef _WIN32 return true; #else - static constexpr const char* Terms[] = - { - "ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", - "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm" - }; + static constexpr const char *Terms[] = { + "ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"}; const char *env_p = std::getenv("TERM"); if (env_p == nullptr) @@ -462,19 +428,15 @@ inline bool is_color_terminal() return false; } - static const bool result = std::any_of( - std::begin(Terms), std::end(Terms), [&](const char* term) - { - return std::strstr(env_p, term) != nullptr; - }); + static const bool result = + std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; }); return result; #endif } - // Detrmine if the terminal attached // Source: https://github.com/agauniyal/rang/ -inline bool in_terminal(FILE* file) +inline bool in_terminal(FILE *file) { #ifdef _WIN32 @@ -483,6 +445,4 @@ inline bool in_terminal(FILE* file) return isatty(fileno(file)) != 0; #endif } -} //os -} //details -} //spdlog +}}} // namespace spdlog::details::os diff --git a/include/spdlog/details/pattern_formatter_impl.h b/include/spdlog/details/pattern_formatter_impl.h index b5ee6d02..670538d5 100644 --- a/include/spdlog/details/pattern_formatter_impl.h +++ b/include/spdlog/details/pattern_formatter_impl.h @@ -5,11 +5,12 @@ #pragma once -#include "../formatter.h" #include "../details/log_msg.h" #include "../details/os.h" #include "../fmt/fmt.h" +#include "../formatter.h" +#include #include #include #include @@ -18,17 +19,13 @@ #include #include #include -#include -namespace spdlog -{ -namespace details -{ +namespace spdlog { namespace details { class flag_formatter { public: virtual ~flag_formatter() = default; - virtual void format(details::log_msg& msg, const std::tm& tm_time) = 0; + virtual void format(details::log_msg &msg, const std::tm &tm_time) = 0; }; /////////////////////////////////////////////////////////////////////// @@ -36,7 +33,7 @@ public: /////////////////////////////////////////////////////////////////////// class name_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << *msg.logger_name; } @@ -45,7 +42,7 @@ class name_formatter : public flag_formatter // log level appender class level_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << level::to_str(msg.level); } @@ -54,7 +51,7 @@ class level_formatter : public flag_formatter // short log level appender class short_level_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << level::to_short_str(msg.level); } @@ -64,74 +61,75 @@ class short_level_formatter : public flag_formatter // Date time pattern appenders /////////////////////////////////////////////////////////////////////// -static const char* ampm(const tm& t) +static const char *ampm(const tm &t) { return t.tm_hour >= 12 ? "PM" : "AM"; } -static int to12h(const tm& t) +static int to12h(const tm &t) { return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour; } -//Abbreviated weekday name -static const std::string days[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; +// Abbreviated weekday name +static const std::string days[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; class a_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << days[tm_time.tm_wday]; } }; -//Full weekday name -static const std::string full_days[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; +// Full weekday name +static const std::string full_days[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; class A_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << full_days[tm_time.tm_wday]; } }; -//Abbreviated month -static const std::string months[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" }; +// Abbreviated month +static const std::string months[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}; class b_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << months[tm_time.tm_mon]; } }; -//Full month name -static const std::string full_months[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; +// Full month name +static const std::string full_months[]{ + "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; class B_formatter : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << full_months[tm_time.tm_mon]; } }; -//write 2 ints separated by sep with padding of 2 -static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, char sep) +// write 2 ints separated by sep with padding of 2 +static fmt::MemoryWriter &pad_n_join(fmt::MemoryWriter &w, int v1, int v2, char sep) { w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0'); return w; } -//write 3 ints separated by sep with padding of 2 -static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, int v3, char sep) +// write 3 ints separated by sep with padding of 2 +static fmt::MemoryWriter &pad_n_join(fmt::MemoryWriter &w, int v1, int v2, int v3, char sep) { w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0') << sep << fmt::pad(v3, 2, '0'); return w; } -//Date and time representation (Thu Aug 23 15:35:46 2014) +// Date and time representation (Thu Aug 23 15:35:46 2014) class c_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << days[tm_time.tm_wday] << ' ' << months[tm_time.tm_mon] << ' ' << tm_time.tm_mday << ' '; pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << tm_time.tm_year + 1900; @@ -141,7 +139,7 @@ class c_formatter SPDLOG_FINAL : public flag_formatter // year - 2 digit class C_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_year % 100, 2, '0'); } @@ -150,7 +148,7 @@ class C_formatter SPDLOG_FINAL : public flag_formatter // Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 class D_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_year % 100, '/'); } @@ -159,7 +157,7 @@ class D_formatter SPDLOG_FINAL : public flag_formatter // year - 4 digit class Y_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << tm_time.tm_year + 1900; } @@ -168,7 +166,7 @@ class Y_formatter SPDLOG_FINAL : public flag_formatter // month 1-12 class m_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_mon + 1, 2, '0'); } @@ -177,7 +175,7 @@ class m_formatter SPDLOG_FINAL : public flag_formatter // day of month 1-31 class d_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_mday, 2, '0'); } @@ -186,7 +184,7 @@ class d_formatter SPDLOG_FINAL : public flag_formatter // hours in 24 format 0-23 class H_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_hour, 2, '0'); } @@ -195,7 +193,7 @@ class H_formatter SPDLOG_FINAL : public flag_formatter // hours in 12 format 1-12 class I_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(to12h(tm_time), 2, '0'); } @@ -204,7 +202,7 @@ class I_formatter SPDLOG_FINAL : public flag_formatter // minutes 0-59 class M_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_min, 2, '0'); } @@ -213,7 +211,7 @@ class M_formatter SPDLOG_FINAL : public flag_formatter // seconds 0-59 class S_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << fmt::pad(tm_time.tm_sec, 2, '0'); } @@ -222,7 +220,7 @@ class S_formatter SPDLOG_FINAL : public flag_formatter // milliseconds class e_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto millis = std::chrono::duration_cast(duration).count() % 1000; @@ -233,7 +231,7 @@ class e_formatter SPDLOG_FINAL : public flag_formatter // microseconds class f_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto micros = std::chrono::duration_cast(duration).count() % 1000000; @@ -244,7 +242,7 @@ class f_formatter SPDLOG_FINAL : public flag_formatter // nanoseconds class F_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto ns = std::chrono::duration_cast(duration).count() % 1000000000; @@ -254,7 +252,7 @@ class F_formatter SPDLOG_FINAL : public flag_formatter class E_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { auto duration = msg.time.time_since_epoch(); auto seconds = std::chrono::duration_cast(duration).count(); @@ -265,7 +263,7 @@ class E_formatter SPDLOG_FINAL : public flag_formatter // AM/PM class p_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { msg.formatted << ampm(tm_time); } @@ -274,7 +272,7 @@ class p_formatter SPDLOG_FINAL : public flag_formatter // 12 hour clock 02:55:02 pm class r_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, to12h(tm_time), tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << ampm(tm_time); } @@ -283,7 +281,7 @@ class r_formatter SPDLOG_FINAL : public flag_formatter // 24-hour HH:MM time, equivalent to %H:%M class R_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, ':'); } @@ -292,7 +290,7 @@ class R_formatter SPDLOG_FINAL : public flag_formatter // ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S class T_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':'); } @@ -305,10 +303,10 @@ public: const std::chrono::seconds cache_refresh = std::chrono::seconds(5); z_formatter() = default; - z_formatter(const z_formatter&) = delete; - z_formatter& operator=(const z_formatter&) = delete; + z_formatter(const z_formatter &) = delete; + z_formatter &operator=(const z_formatter &) = delete; - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { #ifdef _WIN32 int total_minutes = get_cached_offset(msg, tm_time); @@ -334,12 +332,13 @@ public: msg.formatted << sign; pad_n_join(msg.formatted, h, m, ':'); } + private: - log_clock::time_point _last_update{ std::chrono::seconds(0) }; - int _offset_minutes{ 0 }; + log_clock::time_point _last_update{std::chrono::seconds(0)}; + int _offset_minutes{0}; std::mutex _mutex; - int get_cached_offset(const log_msg& msg, const std::tm& tm_time) + int get_cached_offset(const log_msg &msg, const std::tm &tm_time) { std::lock_guard l(_mutex); if (msg.time - _last_update >= cache_refresh) @@ -354,7 +353,7 @@ private: // Thread id class t_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << msg.thread_id; } @@ -363,7 +362,7 @@ class t_formatter SPDLOG_FINAL : public flag_formatter // Current pid class pid_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << details::os::pid(); } @@ -372,7 +371,7 @@ class pid_formatter SPDLOG_FINAL : public flag_formatter // message counter formatter class i_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << fmt::pad(msg.msg_id, 6, '0'); } @@ -380,7 +379,7 @@ class i_formatter SPDLOG_FINAL : public flag_formatter class v_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size()); } @@ -389,18 +388,20 @@ class v_formatter SPDLOG_FINAL : public flag_formatter class ch_formatter SPDLOG_FINAL : public flag_formatter { public: - explicit ch_formatter(char ch): _ch(ch) - {} - void format(details::log_msg& msg, const std::tm&) override + explicit ch_formatter(char ch) + : _ch(ch) + { + } + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << _ch; } + private: char _ch; }; - -//aggregate user chars to display as is +// aggregate user chars to display as is class aggregate_formatter SPDLOG_FINAL : public flag_formatter { public: @@ -410,10 +411,11 @@ public: { _str += ch; } - void format(details::log_msg& msg, const std::tm&) override + void format(details::log_msg &msg, const std::tm &) override { msg.formatted << _str; } + private: std::string _str; }; @@ -422,7 +424,7 @@ private: // pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v class full_formatter SPDLOG_FINAL : public flag_formatter { - void format(details::log_msg& msg, const std::tm& tm_time) override + void format(details::log_msg &msg, const std::tm &tm_time) override { #ifndef SPDLOG_NO_DATETIME auto duration = msg.time.time_since_epoch(); @@ -441,7 +443,6 @@ class full_formatter SPDLOG_FINAL : public flag_formatter level::to_str(msg.level), msg.raw.str());*/ - // Faster (albeit uglier) way to format the line (5.6 million lines/sec under 10 threads) msg.formatted << '[' << static_cast(tm_time.tm_year + 1900) << '-' << fmt::pad(static_cast(tm_time.tm_mon + 1), 2, '0') << '-' @@ -451,7 +452,7 @@ class full_formatter SPDLOG_FINAL : public flag_formatter << fmt::pad(static_cast(tm_time.tm_sec), 2, '0') << '.' << fmt::pad(static_cast(millis), 3, '0') << "] "; - //no datetime needed + // no datetime needed #else (void)tm_time; #endif @@ -465,21 +466,18 @@ class full_formatter SPDLOG_FINAL : public flag_formatter } }; - - -} -} +}} // namespace spdlog::details /////////////////////////////////////////////////////////////////////////////// // pattern_formatter inline impl /////////////////////////////////////////////////////////////////////////////// -inline spdlog::pattern_formatter::pattern_formatter(const std::string& pattern, pattern_time_type pattern_time, std::string eol) : - _eol(std::move(eol)), - _pattern_time(pattern_time) +inline spdlog::pattern_formatter::pattern_formatter(const std::string &pattern, pattern_time_type pattern_time, std::string eol) + : _eol(std::move(eol)) + , _pattern_time(pattern_time) { compile_pattern(pattern); } -inline void spdlog::pattern_formatter::compile_pattern(const std::string& pattern) +inline void spdlog::pattern_formatter::compile_pattern(const std::string &pattern) { auto end = pattern.end(); std::unique_ptr user_chars; @@ -487,7 +485,7 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter { if (*it == '%') { - if (user_chars) //append user chars found so far + if (user_chars) // append user chars found so far _formatters.push_back(std::move(user_chars)); if (++it != end) handle_flag(*it); @@ -501,11 +499,10 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter user_chars->add_ch(*it); } } - if (user_chars) //append raw chars found so far + if (user_chars) // append raw chars found so far { _formatters.push_back(std::move(user_chars)); } - } inline void spdlog::pattern_formatter::handle_flag(char flag) { @@ -524,105 +521,105 @@ inline void spdlog::pattern_formatter::handle_flag(char flag) _formatters.emplace_back(new details::short_level_formatter()); break; - case('t'): + case ('t'): _formatters.emplace_back(new details::t_formatter()); break; - case('v'): + case ('v'): _formatters.emplace_back(new details::v_formatter()); break; - case('a'): + case ('a'): _formatters.emplace_back(new details::a_formatter()); break; - case('A'): + case ('A'): _formatters.emplace_back(new details::A_formatter()); break; - case('b'): - case('h'): + case ('b'): + case ('h'): _formatters.emplace_back(new details::b_formatter()); break; - case('B'): + case ('B'): _formatters.emplace_back(new details::B_formatter()); break; - case('c'): + case ('c'): _formatters.emplace_back(new details::c_formatter()); break; - case('C'): + case ('C'): _formatters.emplace_back(new details::C_formatter()); break; - case('Y'): + case ('Y'): _formatters.emplace_back(new details::Y_formatter()); break; - case('D'): - case('x'): + case ('D'): + case ('x'): _formatters.emplace_back(new details::D_formatter()); break; - case('m'): + case ('m'): _formatters.emplace_back(new details::m_formatter()); break; - case('d'): + case ('d'): _formatters.emplace_back(new details::d_formatter()); break; - case('H'): + case ('H'): _formatters.emplace_back(new details::H_formatter()); break; - case('I'): + case ('I'): _formatters.emplace_back(new details::I_formatter()); break; - case('M'): + case ('M'): _formatters.emplace_back(new details::M_formatter()); break; - case('S'): + case ('S'): _formatters.emplace_back(new details::S_formatter()); break; - case('e'): + case ('e'): _formatters.emplace_back(new details::e_formatter()); break; - case('f'): + case ('f'): _formatters.emplace_back(new details::f_formatter()); break; - case('F'): + case ('F'): _formatters.emplace_back(new details::F_formatter()); break; - case('E'): + case ('E'): _formatters.emplace_back(new details::E_formatter()); break; - case('p'): + case ('p'): _formatters.emplace_back(new details::p_formatter()); break; - case('r'): + case ('r'): _formatters.emplace_back(new details::r_formatter()); break; - case('R'): + case ('R'): _formatters.emplace_back(new details::R_formatter()); break; - case('T'): - case('X'): + case ('T'): + case ('X'): _formatters.emplace_back(new details::T_formatter()); break; - case('z'): + case ('z'): _formatters.emplace_back(new details::z_formatter()); break; @@ -634,19 +631,18 @@ inline void spdlog::pattern_formatter::handle_flag(char flag) _formatters.emplace_back(new details::pid_formatter()); break; - case ('i'): _formatters.emplace_back(new details::i_formatter()); break; - default: //Unknown flag appears as is + default: // Unknown flag appears as is _formatters.emplace_back(new details::ch_formatter('%')); _formatters.emplace_back(new details::ch_formatter(flag)); break; } } -inline std::tm spdlog::pattern_formatter::get_time(details::log_msg& msg) +inline std::tm spdlog::pattern_formatter::get_time(details::log_msg &msg) { if (_pattern_time == pattern_time_type::local) { @@ -655,7 +651,7 @@ inline std::tm spdlog::pattern_formatter::get_time(details::log_msg& msg) return details::os::gmtime(log_clock::to_time_t(msg.time)); } -inline void spdlog::pattern_formatter::format(details::log_msg& msg) +inline void spdlog::pattern_formatter::format(details::log_msg &msg) { #ifndef SPDLOG_NO_DATETIME @@ -667,6 +663,6 @@ inline void spdlog::pattern_formatter::format(details::log_msg& msg) { f->format(msg, tm_time); } - //write eol + // write eol msg.formatted.write(_eol.data(), _eol.size()); } diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 6bd8bb2d..300e4fd7 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -10,10 +10,10 @@ // If user requests a non existing logger, nullptr will be returned // This class is thread safe -#include "../details/null_mutex.h" -#include "../logger.h" #include "../async_logger.h" #include "../common.h" +#include "../details/null_mutex.h" +#include "../logger.h" #include #include @@ -22,16 +22,12 @@ #include #include -namespace spdlog -{ -namespace details -{ -template -class registry_t +namespace spdlog { namespace details { +template class registry_t { public: - registry_t(const registry_t&) = delete; - registry_t& operator=(const registry_t&) = delete; + registry_t(const registry_t &) = delete; + registry_t &operator=(const registry_t &) = delete; void register_logger(std::shared_ptr logger) { @@ -41,21 +37,21 @@ public: _loggers[logger_name] = logger; } - std::shared_ptr get(const std::string& logger_name) + std::shared_ptr get(const std::string &logger_name) { std::lock_guard lock(_mutex); auto found = _loggers.find(logger_name); return found == _loggers.end() ? nullptr : found->second; } - template - std::shared_ptr create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end) + template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) { std::lock_guard lock(_mutex); throw_if_exists(logger_name); std::shared_ptr new_logger; if (_async_mode) - new_logger = std::make_shared(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb); + new_logger = std::make_shared(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, + _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb); else new_logger = std::make_shared(logger_name, sinks_begin, sinks_end); @@ -68,18 +64,21 @@ public: new_logger->set_level(_level); new_logger->flush_on(_flush_level); - - //Add to registry + // Add to registry _loggers[logger_name] = new_logger; return new_logger; } - template - std::shared_ptr create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb, const It& sinks_begin, const It& sinks_end) + template + std::shared_ptr create_async(const std::string &logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb, const It &sinks_begin, + const It &sinks_end) { std::lock_guard lock(_mutex); throw_if_exists(logger_name); - auto new_logger = std::make_shared(logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); + auto new_logger = std::make_shared( + logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); if (_formatter) new_logger->set_formatter(_formatter); @@ -90,7 +89,7 @@ public: new_logger->set_level(_level); new_logger->flush_on(_flush_level); - //Add to registry + // Add to registry _loggers[logger_name] = new_logger; return new_logger; } @@ -102,7 +101,7 @@ public: fun(l.second); } - void drop(const std::string& logger_name) + void drop(const std::string &logger_name) { std::lock_guard lock(_mutex); _loggers.erase(logger_name); @@ -114,46 +113,51 @@ public: _loggers.clear(); } - std::shared_ptr create(const std::string& logger_name, sinks_init_list sinks) + std::shared_ptr create(const std::string &logger_name, sinks_init_list sinks) { return create(logger_name, sinks.begin(), sinks.end()); } - std::shared_ptr create(const std::string& logger_name, sink_ptr sink) + std::shared_ptr create(const std::string &logger_name, sink_ptr sink) { - return create(logger_name, { sink }); + return create(logger_name, {sink}); } - std::shared_ptr create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb, sinks_init_list sinks) + std::shared_ptr create_async(const std::string &logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb, sinks_init_list sinks) { - return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks.begin(), sinks.end()); + return create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks.begin(), sinks.end()); } - std::shared_ptr create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb, sink_ptr sink) + std::shared_ptr create_async(const std::string &logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb, sink_ptr sink) { - return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, { sink }); + return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, {sink}); } void formatter(formatter_ptr f) { std::lock_guard lock(_mutex); _formatter = f; - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_formatter(_formatter); } - void set_pattern(const std::string& pattern) + void set_pattern(const std::string &pattern) { std::lock_guard lock(_mutex); _formatter = std::make_shared(pattern); - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_formatter(_formatter); } void set_level(level::level_enum log_level) { std::lock_guard lock(_mutex); - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_level(log_level); _level = log_level; } @@ -161,19 +165,20 @@ public: void flush_on(level::level_enum log_level) { std::lock_guard lock(_mutex); - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->flush_on(log_level); _flush_level = log_level; } void set_error_handler(log_err_handler handler) { - for (auto& l : _loggers) + for (auto &l : _loggers) l.second->set_error_handler(handler); _err_handler = handler; } - void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) + void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { std::lock_guard lock(_mutex); _async_mode = true; @@ -190,7 +195,7 @@ public: _async_mode = false; } - static registry_t& instance() + static registry_t &instance() { static registry_t s_instance; return s_instance; @@ -206,7 +211,7 @@ private: } Mutex _mutex; - std::unordered_map > _loggers; + std::unordered_map> _loggers; formatter_ptr _formatter; level::level_enum _level = level::info; level::level_enum _flush_level = level::off; @@ -225,5 +230,4 @@ using registry = registry_t; using registry = registry_t; #endif -} -} +}} // namespace spdlog::details diff --git a/include/spdlog/details/spdlog_impl.h b/include/spdlog/details/spdlog_impl.h index 003aff16..114498b1 100644 --- a/include/spdlog/details/spdlog_impl.h +++ b/include/spdlog/details/spdlog_impl.h @@ -8,10 +8,10 @@ // // Global registry functions // -#include "../spdlog.h" #include "../details/registry.h" #include "../sinks/file_sinks.h" #include "../sinks/stdout_sinks.h" +#include "../spdlog.h" #ifdef SPDLOG_ENABLE_SYSLOG #include "../sinks/syslog_sink.h" #endif @@ -22,7 +22,6 @@ #include "../sinks/ansicolor_sink.h" #endif - #ifdef __ANDROID__ #include "../sinks/android_sink.h" #endif @@ -37,7 +36,7 @@ inline void spdlog::register_logger(std::shared_ptr logger) return details::registry::instance().register_logger(std::move(logger)); } -inline std::shared_ptr spdlog::get(const std::string& name) +inline std::shared_ptr spdlog::get(const std::string &name) { return details::registry::instance().get(name); } @@ -48,58 +47,61 @@ inline void spdlog::drop(const std::string &name) } // Create multi/single threaded simple file logger -inline std::shared_ptr spdlog::basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate) +inline std::shared_ptr spdlog::basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate) { return create(logger_name, filename, truncate); } -inline std::shared_ptr spdlog::basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate) +inline std::shared_ptr spdlog::basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate) { return create(logger_name, filename, truncate); } // Create multi/single threaded rotating file logger -inline std::shared_ptr spdlog::rotating_logger_mt(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files) +inline std::shared_ptr spdlog::rotating_logger_mt( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files) { return create(logger_name, filename, max_file_size, max_files); } -inline std::shared_ptr spdlog::rotating_logger_st(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files) +inline std::shared_ptr spdlog::rotating_logger_st( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files) { return create(logger_name, filename, max_file_size, max_files); } // Create file logger which creates new file at midnight): -inline std::shared_ptr spdlog::daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour, int minute) +inline std::shared_ptr spdlog::daily_logger_mt( + const std::string &logger_name, const filename_t &filename, int hour, int minute) { return create(logger_name, filename, hour, minute); } -inline std::shared_ptr spdlog::daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour, int minute) +inline std::shared_ptr spdlog::daily_logger_st( + const std::string &logger_name, const filename_t &filename, int hour, int minute) { return create(logger_name, filename, hour, minute); } - // // stdout/stderr loggers // -inline std::shared_ptr spdlog::stdout_logger_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_logger_mt(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stdout_sink_mt::instance()); } -inline std::shared_ptr spdlog::stdout_logger_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_logger_st(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stdout_sink_st::instance()); } -inline std::shared_ptr spdlog::stderr_logger_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_logger_mt(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stderr_sink_mt::instance()); } -inline std::shared_ptr spdlog::stderr_logger_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_logger_st(const std::string &logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stderr_sink_st::instance()); } @@ -109,52 +111,51 @@ inline std::shared_ptr spdlog::stderr_logger_st(const std::strin // #if defined _WIN32 && !defined(__cplusplus_winrt) -inline std::shared_ptr spdlog::stdout_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stdout_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stderr_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } - -inline std::shared_ptr spdlog::stderr_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -#else //ansi terminal colors +#else // ansi terminal colors -inline std::shared_ptr spdlog::stdout_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stdout_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stdout_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stderr_color_mt(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_mt(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr spdlog::stderr_color_st(const std::string& logger_name) +inline std::shared_ptr spdlog::stderr_color_st(const std::string &logger_name) { auto sink = std::make_shared(); return spdlog::details::registry::instance().create(logger_name, sink); @@ -163,60 +164,70 @@ inline std::shared_ptr spdlog::stderr_color_st(const std::string #ifdef SPDLOG_ENABLE_SYSLOG // Create syslog logger -inline std::shared_ptr spdlog::syslog_logger(const std::string& logger_name, const std::string& syslog_ident, int syslog_option, int syslog_facility) +inline std::shared_ptr spdlog::syslog_logger( + const std::string &logger_name, const std::string &syslog_ident, int syslog_option, int syslog_facility) { return create(logger_name, syslog_ident, syslog_option, syslog_facility); } #endif #ifdef __ANDROID__ -inline std::shared_ptr spdlog::android_logger(const std::string& logger_name, const std::string& tag) +inline std::shared_ptr spdlog::android_logger(const std::string &logger_name, const std::string &tag) { return create(logger_name, tag); } #endif // Create and register a logger a single sink -inline std::shared_ptr spdlog::create(const std::string& logger_name, const spdlog::sink_ptr& sink) +inline std::shared_ptr spdlog::create(const std::string &logger_name, const spdlog::sink_ptr &sink) { return details::registry::instance().create(logger_name, sink); } -//Create logger with multiple sinks -inline std::shared_ptr spdlog::create(const std::string& logger_name, spdlog::sinks_init_list sinks) +// Create logger with multiple sinks +inline std::shared_ptr spdlog::create(const std::string &logger_name, spdlog::sinks_init_list sinks) { return details::registry::instance().create(logger_name, sinks); } template -inline std::shared_ptr spdlog::create(const std::string& logger_name, Args... args) +inline std::shared_ptr spdlog::create(const std::string &logger_name, Args... args) { sink_ptr sink = std::make_shared(args...); - return details::registry::instance().create(logger_name, { sink }); + return details::registry::instance().create(logger_name, {sink}); } -template -inline std::shared_ptr spdlog::create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end) +template +inline std::shared_ptr spdlog::create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end) { return details::registry::instance().create(logger_name, sinks_begin, sinks_end); } // Create and register an async logger with a single sink -inline std::shared_ptr spdlog::create_async(const std::string& logger_name, const sink_ptr& sink, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) +inline std::shared_ptr spdlog::create_async(const std::string &logger_name, const sink_ptr &sink, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { - return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sink); + return details::registry::instance().create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sink); } // Create and register an async logger with multiple sinks -inline std::shared_ptr spdlog::create_async(const std::string& logger_name, sinks_init_list sinks, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb ) +inline std::shared_ptr spdlog::create_async(const std::string &logger_name, sinks_init_list sinks, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { - return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks); + return details::registry::instance().create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks); } -template -inline std::shared_ptr spdlog::create_async(const std::string& logger_name, const It& sinks_begin, const It& sinks_end, size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) +template +inline std::shared_ptr spdlog::create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end, + size_t queue_size, const async_overflow_policy overflow_policy, const std::function &worker_warmup_cb, + const std::chrono::milliseconds &flush_interval_ms, const std::function &worker_teardown_cb) { - return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks_begin, sinks_end); + return details::registry::instance().create_async( + logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks_begin, sinks_end); } inline void spdlog::set_formatter(spdlog::formatter_ptr f) @@ -224,7 +235,7 @@ inline void spdlog::set_formatter(spdlog::formatter_ptr f) details::registry::instance().formatter(std::move(f)); } -inline void spdlog::set_pattern(const std::string& format_string) +inline void spdlog::set_pattern(const std::string &format_string) { return details::registry::instance().set_pattern(format_string); } @@ -244,7 +255,9 @@ inline void spdlog::set_error_handler(log_err_handler handler) return details::registry::instance().set_error_handler(std::move(handler)); } -inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, const std::function& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function& worker_teardown_cb) +inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, + const std::function &worker_warmup_cb, const std::chrono::milliseconds &flush_interval_ms, + const std::function &worker_teardown_cb) { details::registry::instance().set_async_mode(queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); } diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index 971c58e2..bc84c7b5 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -38,273 +38,264 @@ #include #include #include +#include // for std::pair #include -#include // for std::pair #undef FMT_INCLUDE // The fmt library version in the form major * 10000 + minor * 100 + patch. #define FMT_VERSION 40100 #if defined(__has_include) -# define FMT_HAS_INCLUDE(x) __has_include(x) +#define FMT_HAS_INCLUDE(x) __has_include(x) #else -# define FMT_HAS_INCLUDE(x) 0 +#define FMT_HAS_INCLUDE(x) 0 #endif -#if (FMT_HAS_INCLUDE() && __cplusplus > 201402L) || \ - (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) -# include -# define FMT_HAS_STRING_VIEW 1 +#if (FMT_HAS_INCLUDE() && __cplusplus > 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) +#include +#define FMT_HAS_STRING_VIEW 1 #else -# define FMT_HAS_STRING_VIEW 0 +#define FMT_HAS_STRING_VIEW 0 #endif #if defined _SECURE_SCL && _SECURE_SCL -# define FMT_SECURE_SCL _SECURE_SCL +#define FMT_SECURE_SCL _SECURE_SCL #else -# define FMT_SECURE_SCL 0 +#define FMT_SECURE_SCL 0 #endif #if FMT_SECURE_SCL -# include +#include #endif #ifdef _MSC_VER -# define FMT_MSC_VER _MSC_VER +#define FMT_MSC_VER _MSC_VER #else -# define FMT_MSC_VER 0 +#define FMT_MSC_VER 0 #endif #if FMT_MSC_VER && FMT_MSC_VER <= 1500 typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; -typedef __int64 intmax_t; +typedef __int64 intmax_t; #else #include #endif #if !defined(FMT_HEADER_ONLY) && defined(_WIN32) -# ifdef FMT_EXPORT -# define FMT_API __declspec(dllexport) -# elif defined(FMT_SHARED) -# define FMT_API __declspec(dllimport) -# endif +#ifdef FMT_EXPORT +#define FMT_API __declspec(dllexport) +#elif defined(FMT_SHARED) +#define FMT_API __declspec(dllimport) +#endif #endif #ifndef FMT_API -# define FMT_API +#define FMT_API #endif #ifdef __GNUC__ -# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -# define FMT_GCC_EXTENSION __extension__ -# if FMT_GCC_VERSION >= 406 -# pragma GCC diagnostic push +#define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#define FMT_GCC_EXTENSION __extension__ +#if FMT_GCC_VERSION >= 406 +#pragma GCC diagnostic push // Disable the warning about "long long" which is sometimes reported even // when using __extension__. -# pragma GCC diagnostic ignored "-Wlong-long" +#pragma GCC diagnostic ignored "-Wlong-long" // Disable the warning about declaration shadowing because it affects too // many valid cases. -# pragma GCC diagnostic ignored "-Wshadow" +#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" -# endif -# if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ -# define FMT_HAS_GXX_CXX11 1 -# endif +#pragma GCC diagnostic ignored "-Wsign-conversion" +#endif +#if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ +#define FMT_HAS_GXX_CXX11 1 +#endif #else -# define FMT_GCC_VERSION 0 -# define FMT_GCC_EXTENSION -# define FMT_HAS_GXX_CXX11 0 +#define FMT_GCC_VERSION 0 +#define FMT_GCC_EXTENSION +#define FMT_HAS_GXX_CXX11 0 #endif #if defined(__INTEL_COMPILER) -# define FMT_ICC_VERSION __INTEL_COMPILER +#define FMT_ICC_VERSION __INTEL_COMPILER #elif defined(__ICL) -# define FMT_ICC_VERSION __ICL +#define FMT_ICC_VERSION __ICL #endif #if defined(__clang__) && !defined(FMT_ICC_VERSION) -# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdocumentation-unknown-command" -# pragma clang diagnostic ignored "-Wpadded" +#define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#pragma clang diagnostic ignored "-Wpadded" #endif #ifdef __GNUC_LIBSTD__ -# define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) +#define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) #endif #ifdef __has_feature -# define FMT_HAS_FEATURE(x) __has_feature(x) +#define FMT_HAS_FEATURE(x) __has_feature(x) #else -# define FMT_HAS_FEATURE(x) 0 +#define FMT_HAS_FEATURE(x) 0 #endif #ifdef __has_builtin -# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#define FMT_HAS_BUILTIN(x) __has_builtin(x) #else -# define FMT_HAS_BUILTIN(x) 0 +#define FMT_HAS_BUILTIN(x) 0 #endif #ifdef __has_cpp_attribute -# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) #else -# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#define FMT_HAS_CPP_ATTRIBUTE(x) 0 #endif #if FMT_HAS_CPP_ATTRIBUTE(maybe_unused) -# define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED +#define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED // VC++ 1910 support /std: option and that will set _MSVC_LANG macro // Clang with Microsoft CodeGen doesn't define _MSVC_LANG macro #elif defined(_MSVC_LANG) && _MSVC_LANG > 201402 && _MSC_VER >= 1910 -# define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED +#define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED #endif #ifdef FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED -# define FMT_MAYBE_UNUSED [[maybe_unused]] +#define FMT_MAYBE_UNUSED [[maybe_unused]] // g++/clang++ also support [[gnu::unused]]. However, we don't use it. #elif defined(__GNUC__) -# define FMT_MAYBE_UNUSED __attribute__((unused)) +#define FMT_MAYBE_UNUSED __attribute__((unused)) #else -# define FMT_MAYBE_UNUSED +#define FMT_MAYBE_UNUSED #endif // Use the compiler's attribute noreturn #if defined(__MINGW32__) || defined(__MINGW64__) -# define FMT_NORETURN __attribute__((noreturn)) +#define FMT_NORETURN __attribute__((noreturn)) #elif FMT_HAS_CPP_ATTRIBUTE(noreturn) && __cplusplus >= 201103L -# define FMT_NORETURN [[noreturn]] +#define FMT_NORETURN [[noreturn]] #else -# define FMT_NORETURN +#define FMT_NORETURN #endif #ifndef FMT_USE_VARIADIC_TEMPLATES // Variadic templates are available in GCC since version 4.4 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++ // since version 2013. -# define FMT_USE_VARIADIC_TEMPLATES \ - (FMT_HAS_FEATURE(cxx_variadic_templates) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800) +#define FMT_USE_VARIADIC_TEMPLATES \ + (FMT_HAS_FEATURE(cxx_variadic_templates) || (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800) #endif #ifndef FMT_USE_RVALUE_REFERENCES // Don't use rvalue references when compiling with clang and an old libstdc++ // as the latter doesn't provide std::move. -# if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 -# define FMT_USE_RVALUE_REFERENCES 0 -# else -# define FMT_USE_RVALUE_REFERENCES \ - (FMT_HAS_FEATURE(cxx_rvalue_references) || \ - (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600) -# endif +#if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 +#define FMT_USE_RVALUE_REFERENCES 0 +#else +#define FMT_USE_RVALUE_REFERENCES \ + (FMT_HAS_FEATURE(cxx_rvalue_references) || (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600) +#endif #endif #if __cplusplus >= 201103L || FMT_MSC_VER >= 1700 -# define FMT_USE_ALLOCATOR_TRAITS 1 +#define FMT_USE_ALLOCATOR_TRAITS 1 #else -# define FMT_USE_ALLOCATOR_TRAITS 0 +#define FMT_USE_ALLOCATOR_TRAITS 0 #endif // Check if exceptions are disabled. #if defined(__GNUC__) && !defined(__EXCEPTIONS) -# define FMT_EXCEPTIONS 0 +#define FMT_EXCEPTIONS 0 #endif #if FMT_MSC_VER && !_HAS_EXCEPTIONS -# define FMT_EXCEPTIONS 0 +#define FMT_EXCEPTIONS 0 #endif #ifndef FMT_EXCEPTIONS -# define FMT_EXCEPTIONS 1 +#define FMT_EXCEPTIONS 1 #endif #ifndef FMT_THROW -# if FMT_EXCEPTIONS -# define FMT_THROW(x) throw x -# else -# define FMT_THROW(x) assert(false) -# endif +#if FMT_EXCEPTIONS +#define FMT_THROW(x) throw x +#else +#define FMT_THROW(x) assert(false) +#endif #endif // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). #ifndef FMT_USE_NOEXCEPT -# define FMT_USE_NOEXCEPT 0 +#define FMT_USE_NOEXCEPT 0 #endif -#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ - FMT_MSC_VER >= 1900 -# define FMT_DETECTED_NOEXCEPT noexcept +#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +#define FMT_DETECTED_NOEXCEPT noexcept #else -# define FMT_DETECTED_NOEXCEPT throw() +#define FMT_DETECTED_NOEXCEPT throw() #endif #ifndef FMT_NOEXCEPT -# if FMT_EXCEPTIONS -# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT -# else -# define FMT_NOEXCEPT -# endif +#if FMT_EXCEPTIONS +#define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT +#else +#define FMT_NOEXCEPT +#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 +#define FMT_DTOR_NOEXCEPT FMT_DETECTED_NOEXCEPT #else -# define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT +#define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT #endif #ifndef FMT_OVERRIDE -# if (defined(FMT_USE_OVERRIDE) && FMT_USE_OVERRIDE) || FMT_HAS_FEATURE(cxx_override) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ - FMT_MSC_VER >= 1900 -# define FMT_OVERRIDE override -# else -# define FMT_OVERRIDE -# endif +#if (defined(FMT_USE_OVERRIDE) && FMT_USE_OVERRIDE) || FMT_HAS_FEATURE(cxx_override) || (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ + FMT_MSC_VER >= 1900 +#define FMT_OVERRIDE override +#else +#define FMT_OVERRIDE +#endif #endif #ifndef FMT_NULL -# if FMT_HAS_FEATURE(cxx_nullptr) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ - FMT_MSC_VER >= 1600 -# define FMT_NULL nullptr -# else -# define FMT_NULL NULL -# endif +#if FMT_HAS_FEATURE(cxx_nullptr) || (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600 +#define FMT_NULL nullptr +#else +#define FMT_NULL NULL +#endif #endif // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #ifndef FMT_USE_DELETED_FUNCTIONS -# define FMT_USE_DELETED_FUNCTIONS 0 +#define FMT_USE_DELETED_FUNCTIONS 0 #endif -#if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800 -# define FMT_DELETED_OR_UNDEFINED = delete -# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&) = delete; \ - TypeName& operator=(const TypeName&) = delete +#if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || \ + FMT_MSC_VER >= 1800 +#define FMT_DELETED_OR_UNDEFINED = delete +#define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName &) = delete; \ + TypeName &operator=(const TypeName &) = delete #else -# define FMT_DELETED_OR_UNDEFINED -# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - TypeName& operator=(const TypeName&) +#define FMT_DELETED_OR_UNDEFINED +#define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName &); \ + TypeName &operator=(const TypeName &) #endif #ifndef FMT_USE_DEFAULTED_FUNCTIONS -# define FMT_USE_DEFAULTED_FUNCTIONS 0 +#define FMT_USE_DEFAULTED_FUNCTIONS 0 #endif #ifndef FMT_DEFAULTED_COPY_CTOR -# if FMT_USE_DEFAULTED_FUNCTIONS || FMT_HAS_FEATURE(cxx_defaulted_functions) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800 -# define FMT_DEFAULTED_COPY_CTOR(TypeName) \ - TypeName(const TypeName&) = default; -# else -# define FMT_DEFAULTED_COPY_CTOR(TypeName) -# endif +#if FMT_USE_DEFAULTED_FUNCTIONS || FMT_HAS_FEATURE(cxx_defaulted_functions) || (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || \ + FMT_MSC_VER >= 1800 +#define FMT_DEFAULTED_COPY_CTOR(TypeName) TypeName(const TypeName &) = default; +#else +#define FMT_DEFAULTED_COPY_CTOR(TypeName) +#endif #endif #ifndef FMT_USE_USER_DEFINED_LITERALS @@ -312,41 +303,39 @@ typedef __int64 intmax_t; // makes the fmt::literals implementation easier. However, an explicit check // for variadic templates is added here just in case. // For Intel's compiler both it and the system gcc/msc must support UDLs. -# if FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \ - (FMT_HAS_FEATURE(cxx_user_literals) || \ - (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \ - (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500) -# define FMT_USE_USER_DEFINED_LITERALS 1 -# else -# define FMT_USE_USER_DEFINED_LITERALS 0 -# endif +#if FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \ + (FMT_HAS_FEATURE(cxx_user_literals) || (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \ + (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500) +#define FMT_USE_USER_DEFINED_LITERALS 1 +#else +#define FMT_USE_USER_DEFINED_LITERALS 0 +#endif #endif #ifndef FMT_USE_EXTERN_TEMPLATES -# define FMT_USE_EXTERN_TEMPLATES \ - (FMT_CLANG_VERSION >= 209 || (FMT_GCC_VERSION >= 303 && FMT_HAS_GXX_CXX11)) +#define FMT_USE_EXTERN_TEMPLATES (FMT_CLANG_VERSION >= 209 || (FMT_GCC_VERSION >= 303 && FMT_HAS_GXX_CXX11)) #endif #ifdef FMT_HEADER_ONLY // If header only do not use extern templates. -# undef FMT_USE_EXTERN_TEMPLATES -# define FMT_USE_EXTERN_TEMPLATES 0 +#undef FMT_USE_EXTERN_TEMPLATES +#define FMT_USE_EXTERN_TEMPLATES 0 #endif #ifndef FMT_ASSERT -# define FMT_ASSERT(condition, message) assert((condition) && message) +#define FMT_ASSERT(condition, message) assert((condition) && message) #endif // __builtin_clz is broken in clang with Microsoft CodeGen: // https://github.com/fmtlib/fmt/issues/519 #ifndef _MSC_VER -# if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) -# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) -# endif +#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) +#define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +#endif -# if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) -# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) -# endif +#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) +#define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +#endif #endif // Some compilers masquerade as both MSVC and GCC-likes or @@ -354,16 +343,14 @@ typedef __int64 intmax_t; // only define FMT_BUILTIN_CLZ using the MSVC intrinsics // if the clz and clzll builtins are not available. #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED) -# include // _BitScanReverse, _BitScanReverse64 +#include // _BitScanReverse, _BitScanReverse64 -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { // avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning -# ifndef __clang__ -# pragma intrinsic(_BitScanReverse) -# endif +#ifndef __clang__ +#pragma intrinsic(_BitScanReverse) +#endif inline uint32_t clz(uint32_t x) { unsigned long r = 0; @@ -373,46 +360,43 @@ inline uint32_t clz(uint32_t x) // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. -# pragma warning(suppress: 6102) +#pragma warning(suppress : 6102) return 31 - r; } -# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) +#define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) // avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning -# if defined(_WIN64) && !defined(__clang__) -# pragma intrinsic(_BitScanReverse64) -# endif +#if defined(_WIN64) && !defined(__clang__) +#pragma intrinsic(_BitScanReverse64) +#endif inline uint32_t clzll(uint64_t x) { unsigned long r = 0; -# ifdef _WIN64 +#ifdef _WIN64 _BitScanReverse64(&r, x); -# else +#else // Scan the high 32 bits. if (_BitScanReverse(&r, static_cast(x >> 32))) return 63 - (r + 32); // Scan the low 32 bits. _BitScanReverse(&r, static_cast(x)); -# endif +#endif assert(x != 0); // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. -# pragma warning(suppress: 6102) +#pragma warning(suppress : 6102) return 63 - r; } -# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) -} +#define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) } +} // namespace fmt #endif -namespace fmt -{ -namespace internal -{ +namespace fmt { namespace internal { struct DummyInt { int data[2]; @@ -452,34 +436,27 @@ inline DummyInt _isnan(...) // A helper function to suppress bogus "conditional expression is constant" // warnings. -template -inline T const_check(T value) +template inline T const_check(T value) { return value; } -} -} // namespace fmt +}} // namespace fmt::internal -namespace std -{ +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. -template <> -class numeric_limits : - public std::numeric_limits +template <> class numeric_limits : public std::numeric_limits { public: // Portable version of isinf. - template - static bool isinfinity(T x) + template static bool isinfinity(T x) { using namespace fmt::internal; // The resolution "priority" is: // isinf macro > std::isinf > ::isinf > fmt::internal::isinf - if (const_check(sizeof(isinf(x)) == sizeof(bool) || - sizeof(isinf(x)) == sizeof(int))) + if (const_check(sizeof(isinf(x)) == sizeof(bool) || sizeof(isinf(x)) == sizeof(int))) { return isinf(x) != 0; } @@ -487,12 +464,10 @@ public: } // Portable version of isnan. - template - static bool isnotanumber(T x) + template static bool isnotanumber(T x) { using namespace fmt::internal; - if (const_check(sizeof(isnan(x)) == sizeof(bool) || - sizeof(isnan(x)) == sizeof(int))) + if (const_check(sizeof(isnan(x)) == sizeof(bool) || sizeof(isnan(x)) == sizeof(int))) { return isnan(x) != 0; } @@ -503,23 +478,23 @@ public: static bool isnegative(double x) { using namespace fmt::internal; - if (const_check(sizeof(signbit(x)) == sizeof(bool) || - sizeof(signbit(x)) == sizeof(int))) + if (const_check(sizeof(signbit(x)) == sizeof(bool) || sizeof(signbit(x)) == sizeof(int))) { return signbit(x) != 0; } - if (x < 0) return true; - if (!isnotanumber(x)) return false; + 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. + 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 +} // namespace std -namespace fmt -{ +namespace fmt { // Fix the warning about long long on older versions of GCC // that don't support the diagnostic pragma. @@ -530,23 +505,18 @@ FMT_GCC_EXTENSION typedef unsigned long long ULongLong; using std::move; #endif -template -class BasicWriter; +template class BasicWriter; typedef BasicWriter Writer; typedef BasicWriter WWriter; -template -class ArgFormatter; +template class ArgFormatter; struct FormatSpec; -template -class BasicPrintfArgFormatter; +template class BasicPrintfArgFormatter; -template > -class BasicFormatter; +template > class BasicFormatter; /** \rst @@ -573,8 +543,7 @@ class BasicFormatter; format(std::string("{}"), 42); \endrst */ -template -class BasicStringRef +template class BasicStringRef { private: const Char *data_; @@ -582,7 +551,11 @@ private: public: /** Constructs a string reference object from a C string and a size. */ - BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {} + BasicStringRef(const Char *s, std::size_t size) + : data_(s) + , size_(size) + { + } /** \rst @@ -591,7 +564,10 @@ public: \endrst */ BasicStringRef(const Char *s) - : data_(s), size_(std::char_traits::length(s)) {} + : data_(s) + , size_(std::char_traits::length(s)) + { + } /** \rst @@ -599,9 +575,11 @@ public: \endrst */ template - BasicStringRef( - const std::basic_string, Allocator> &s) - : data_(s.c_str()), size_(s.size()) {} + BasicStringRef(const std::basic_string, Allocator> &s) + : data_(s.c_str()) + , size_(s.size()) + { + } #if FMT_HAS_STRING_VIEW /** @@ -609,9 +587,11 @@ public: Constructs a string reference from a ``std::basic_string_view`` object. \endrst */ - BasicStringRef( - const std::basic_string_view> &s) - : data_(s.data()), size_(s.size()) {} + BasicStringRef(const std::basic_string_view> &s) + : data_(s.data()) + , size_(s.size()) + { + } /** \rst @@ -710,15 +690,17 @@ typedef BasicStringRef WStringRef; format(std::string("{}"), 42); \endrst */ -template -class BasicCStringRef +template class BasicCStringRef { private: const Char *data_; public: /** Constructs a string reference object from a C string. */ - BasicCStringRef(const Char *s) : data_(s) {} + BasicCStringRef(const Char *s) + : data_(s) + { + } /** \rst @@ -726,9 +708,10 @@ public: \endrst */ template - BasicCStringRef( - const std::basic_string, Allocator> &s) - : data_(s.c_str()) {} + BasicCStringRef(const std::basic_string, Allocator> &s) + : data_(s.c_str()) + { + } /** Returns the pointer to a C string. */ const Char *c_str() const @@ -745,24 +728,29 @@ class FormatError : public std::runtime_error { public: explicit FormatError(CStringRef message) - : std::runtime_error(message.c_str()) {} - FormatError(const FormatError &ferr) : std::runtime_error(ferr) {} + : std::runtime_error(message.c_str()) + { + } + FormatError(const FormatError &ferr) + : std::runtime_error(ferr) + { + } FMT_API ~FormatError() FMT_DTOR_NOEXCEPT FMT_OVERRIDE; }; -namespace internal -{ +namespace internal { // MakeUnsigned::Type gives an unsigned type corresponding to integer type T. -template -struct MakeUnsigned +template struct MakeUnsigned { typedef T Type; }; -#define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ - template <> \ - struct MakeUnsigned { typedef U Type; } +#define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ + template <> struct MakeUnsigned \ + { \ + typedef U Type; \ + } FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char); FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char); @@ -772,8 +760,7 @@ FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); // Casts nonnegative integer to unsigned. -template -inline typename MakeUnsigned::Type to_unsigned(Int value) +template inline typename MakeUnsigned::Type to_unsigned(Int value) { FMT_ASSERT(value >= 0, "negative value"); return static_cast::Type>(value); @@ -781,31 +768,31 @@ inline typename MakeUnsigned::Type to_unsigned(Int value) // The number of characters to store in the MemoryBuffer object itself // to avoid dynamic memory allocation. -enum { INLINE_BUFFER_SIZE = 500 }; +enum +{ + INLINE_BUFFER_SIZE = 500 +}; #if FMT_SECURE_SCL // Use checked iterator to avoid warnings on MSVC. -template -inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) +template inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) { - return stdext::checked_array_iterator(ptr, size); + return stdext::checked_array_iterator(ptr, size); } #else -template -inline T *make_ptr(T *ptr, std::size_t) +template inline T *make_ptr(T *ptr, std::size_t) { return ptr; } #endif -} // namespace internal +} // namespace internal /** \rst A buffer supporting a subset of ``std::vector``'s operations. \endrst */ -template -class Buffer +template class Buffer { private: FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); @@ -816,7 +803,11 @@ protected: std::size_t capacity_; Buffer(T *ptr = FMT_NULL, std::size_t capacity = 0) - : ptr_(ptr), size_(0), capacity_(capacity) {} + : ptr_(ptr) + , size_(0) + , capacity_(capacity) + { + } /** \rst @@ -862,7 +853,10 @@ public: grow(capacity); } - void clear() FMT_NOEXCEPT { size_ = 0; } + void clear() FMT_NOEXCEPT + { + size_ = 0; + } void push_back(const T &value) { @@ -872,8 +866,7 @@ public: } /** Appends data to the end of the buffer. */ - template - void append(const U *begin, const U *end); + template void append(const U *begin, const U *end); T &operator[](std::size_t index) { @@ -885,26 +878,21 @@ public: } }; -template -template -void Buffer::append(const U *begin, const U *end) +template template void Buffer::append(const U *begin, const U *end) { FMT_ASSERT(end >= begin, "negative value"); std::size_t new_size = size_ + static_cast(end - begin); if (new_size > capacity_) grow(new_size); - std::uninitialized_copy(begin, end, - internal::make_ptr(ptr_, capacity_) + size_); + std::uninitialized_copy(begin, end, internal::make_ptr(ptr_, capacity_) + size_); size_ = new_size; } -namespace internal -{ +namespace internal { // A memory buffer for trivially copyable/constructible types with the first // SIZE elements stored in the object itself. -template > -class MemoryBuffer : private Allocator, public Buffer +template > class MemoryBuffer : private Allocator, public Buffer { private: T data_[SIZE]; @@ -912,7 +900,8 @@ private: // Deallocate memory allocated by the buffer. void deallocate() { - if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_); + if (this->ptr_ != data_) + Allocator::deallocate(this->ptr_, this->capacity_); } protected: @@ -920,8 +909,14 @@ protected: public: explicit MemoryBuffer(const Allocator &alloc = Allocator()) - : Allocator(alloc), Buffer(data_, SIZE) {} - ~MemoryBuffer() FMT_OVERRIDE { deallocate(); } + : Allocator(alloc) + , Buffer(data_, SIZE) + { + } + ~MemoryBuffer() FMT_OVERRIDE + { + deallocate(); + } #if FMT_USE_RVALUE_REFERENCES private: @@ -935,8 +930,7 @@ private: if (other.ptr_ == other.data_) { this->ptr_ = data_; - std::uninitialized_copy(other.data_, other.data_ + this->size_, - make_ptr(data_, this->capacity_)); + std::uninitialized_copy(other.data_, other.data_ + this->size_, make_ptr(data_, this->capacity_)); } else { @@ -969,21 +963,18 @@ public: } }; -template -void MemoryBuffer::grow(std::size_t size) +template void MemoryBuffer::grow(std::size_t size) { std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; if (size > new_capacity) new_capacity = size; #if FMT_USE_ALLOCATOR_TRAITS - T *new_ptr = - std::allocator_traits::allocate(*this, new_capacity, FMT_NULL); + T *new_ptr = std::allocator_traits::allocate(*this, new_capacity, FMT_NULL); #else T *new_ptr = this->allocate(new_capacity, FMT_NULL); #endif // The following code doesn't throw, so the raw pointer above doesn't leak. - std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, - make_ptr(new_ptr, new_capacity)); + std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, make_ptr(new_ptr, new_capacity)); std::size_t old_capacity = this->capacity_; T *old_ptr = this->ptr_; this->capacity_ = new_capacity; @@ -996,22 +987,23 @@ void MemoryBuffer::grow(std::size_t size) } // A fixed-size buffer. -template -class FixedBuffer : public fmt::Buffer +template class FixedBuffer : public fmt::Buffer { public: - FixedBuffer(Char *array, std::size_t size) : fmt::Buffer(array, size) {} + FixedBuffer(Char *array, std::size_t size) + : fmt::Buffer(array, size) + { + } protected: FMT_API void grow(std::size_t size) FMT_OVERRIDE; }; -template -class BasicCharTraits +template class BasicCharTraits { public: #if FMT_SECURE_SCL - typedef stdext::checked_array_iterator CharPtr; + typedef stdext::checked_array_iterator CharPtr; #else typedef Char *CharPtr; #endif @@ -1021,11 +1013,9 @@ public: } }; -template -class CharTraits; +template class CharTraits; -template <> -class CharTraits : public BasicCharTraits +template <> class CharTraits : public BasicCharTraits { private: // Conversion from wchar_t to char is not allowed. @@ -1039,21 +1029,17 @@ public: // Formats a floating-point number. template - FMT_API static int format_float(char *buffer, std::size_t size, - const char *format, unsigned width, int precision, T value); + FMT_API static int format_float(char *buffer, std::size_t size, const char *format, unsigned width, int precision, T value); }; #if FMT_USE_EXTERN_TEMPLATES -extern template int CharTraits::format_float -(char *buffer, std::size_t size, - const char* format, unsigned width, int precision, double value); -extern template int CharTraits::format_float -(char *buffer, std::size_t size, - const char* format, unsigned width, int precision, long double value); +extern template int CharTraits::format_float( + char *buffer, std::size_t size, const char *format, unsigned width, int precision, double value); +extern template int CharTraits::format_float( + char *buffer, std::size_t size, const char *format, unsigned width, int precision, long double value); #endif -template <> -class CharTraits : public BasicCharTraits +template <> class CharTraits : public BasicCharTraits { public: static wchar_t convert(char value) @@ -1066,35 +1052,28 @@ public: } template - FMT_API static int format_float(wchar_t *buffer, std::size_t size, - const wchar_t *format, unsigned width, int precision, T value); + FMT_API static int format_float(wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, T value); }; #if FMT_USE_EXTERN_TEMPLATES -extern template int CharTraits::format_float -(wchar_t *buffer, std::size_t size, - const wchar_t* format, unsigned width, int precision, double value); -extern template int CharTraits::format_float -(wchar_t *buffer, std::size_t size, - const wchar_t* format, unsigned width, int precision, long double value); +extern template int CharTraits::format_float( + wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, double value); +extern template int CharTraits::format_float( + wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, long double value); #endif // Checks if a number is negative - used to avoid warnings. -template -struct SignChecker +template struct SignChecker { - template - static bool is_negative(T value) + template static bool is_negative(T value) { return value < 0; } }; -template <> -struct SignChecker +template <> struct SignChecker { - template - static bool is_negative(T) + template static bool is_negative(T) { return false; } @@ -1102,40 +1081,34 @@ struct SignChecker // Returns true if value is negative, false otherwise. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. -template -inline bool is_negative(T value) +template inline bool is_negative(T value) { return SignChecker::is_signed>::is_negative(value); } // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. -template -struct TypeSelector +template struct TypeSelector { typedef uint32_t Type; }; -template <> -struct TypeSelector +template <> struct TypeSelector { typedef uint64_t Type; }; -template -struct IntTraits +template struct IntTraits { // Smallest of uint32_t and uint64_t that is large enough to represent // all values of T. - typedef typename - TypeSelector::digits <= 32>::Type MainType; + typedef typename TypeSelector::digits <= 32>::Type MainType; }; FMT_API FMT_NORETURN void report_unknown_type(char code, const char *type); // Static data is placed in this class template to allow header-only // configuration. -template -struct FMT_API BasicData +template struct FMT_API BasicData { static const uint32_t POWERS_OF_10_32[]; static const uint64_t POWERS_OF_10_64[]; @@ -1168,10 +1141,14 @@ inline unsigned count_digits(uint64_t n) // Integer division is slow so do it for a group of four digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. - if (n < 10) return count; - if (n < 100) return count + 1; - if (n < 1000) return count + 2; - if (n < 10000) return count + 3; + if (n < 10) + return count; + if (n < 100) + return count + 1; + if (n < 1000) + return count + 2; + if (n < 10000) + return count + 3; n /= 10000u; count += 4; } @@ -1190,8 +1167,7 @@ inline unsigned count_digits(uint32_t n) // A functor that doesn't add a thousands separator. struct NoThousandsSep { - template - void operator()(Char *) {} + template void operator()(Char *) {} }; // A functor that adds a thousands separator. @@ -1204,16 +1180,18 @@ private: unsigned digit_index_; public: - explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {} + explicit ThousandsSep(fmt::StringRef sep) + : sep_(sep) + , digit_index_(0) + { + } - template - void operator()(Char *&buffer) + template void operator()(Char *&buffer) { if (++digit_index_ % 3 != 0) return; buffer -= sep_.size(); - std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), - internal::make_ptr(buffer, sep_.size())); + std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), internal::make_ptr(buffer, sep_.size())); } }; @@ -1221,8 +1199,7 @@ public: // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. template -inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, - ThousandsSep thousands_sep) +inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, ThousandsSep thousands_sep) { buffer += num_digits; while (value >= 100) @@ -1248,17 +1225,16 @@ inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, *--buffer = Data::DIGITS[index]; } -template -inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) +template inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { format_decimal(buffer, value, num_digits, NoThousandsSep()); return; } #ifndef _WIN32 -# define FMT_USE_WINDOWS_H 0 +#define FMT_USE_WINDOWS_H 0 #elif !defined(FMT_USE_WINDOWS_H) -# define FMT_USE_WINDOWS_H 1 +#define FMT_USE_WINDOWS_H 1 #endif // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h. @@ -1324,22 +1300,19 @@ public: FMT_API int convert(WStringRef s); }; -FMT_API void format_windows_error(fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT; +FMT_API void format_windows_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; #endif // A formatting argument value. struct Value { - template - struct StringValue + template struct StringValue { const Char *value; std::size_t size; }; - typedef void (*FormatFunc)( - void *formatter, const void *arg, void *format_str_ptr); + typedef void (*FormatFunc)(void *formatter, const void *arg, void *format_str_ptr); struct CustomValue { @@ -1365,12 +1338,25 @@ struct Value enum Type { - NONE, NAMED_ARG, + NONE, + NAMED_ARG, // Integer types should go first, - INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR, + INT, + UINT, + LONG_LONG, + ULONG_LONG, + BOOL, + CHAR, + LAST_INTEGER_TYPE = CHAR, // followed by floating-point types. - DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE, - CSTRING, STRING, WSTRING, POINTER, CUSTOM + DOUBLE, + LONG_DOUBLE, + LAST_NUMERIC_TYPE = LONG_DOUBLE, + CSTRING, + STRING, + WSTRING, + POINTER, + CUSTOM }; }; @@ -1381,25 +1367,22 @@ struct Arg : Value Type type; }; -template -struct NamedArg; -template -struct NamedArgWithType; +template struct NamedArg; +template struct NamedArgWithType; -template -struct Null {}; +template struct Null +{ +}; // A helper class template to enable or disable overloads taking wide // characters and strings in MakeValue. -template -struct WCharHelper +template struct WCharHelper { typedef Null Supported; typedef T Unsupported; }; -template -struct WCharHelper +template struct WCharHelper { typedef T Supported; typedef Null Unsupported; @@ -1408,27 +1391,29 @@ struct WCharHelper typedef char Yes[1]; typedef char No[2]; -template -T &get(); +template T &get(); // These are non-members to workaround an overload resolution bug in bcc32. Yes &convert(fmt::ULongLong); No &convert(...); -template -struct ConvertToIntImpl +template struct ConvertToIntImpl { - enum { value = ENABLE_CONVERSION }; + enum + { + value = ENABLE_CONVERSION + }; }; -template -struct ConvertToIntImpl2 +template struct ConvertToIntImpl2 { - enum { value = false }; + enum + { + value = false + }; }; -template -struct ConvertToIntImpl2 +template struct ConvertToIntImpl2 { enum { @@ -1437,63 +1422,74 @@ struct ConvertToIntImpl2 }; }; -template -struct ConvertToInt +template struct ConvertToInt { enum { enable_conversion = sizeof(fmt::internal::convert(get())) == sizeof(Yes) }; - enum { value = ConvertToIntImpl2::value }; + enum + { + value = ConvertToIntImpl2::value + }; }; -#define FMT_DISABLE_CONVERSION_TO_INT(Type) \ - template <> \ - struct ConvertToInt { enum { value = 0 }; } +#define FMT_DISABLE_CONVERSION_TO_INT(Type) \ + template <> struct ConvertToInt \ + { \ + enum \ + { \ + value = 0 \ + }; \ + } // Silence warnings about convering float to int. FMT_DISABLE_CONVERSION_TO_INT(float); FMT_DISABLE_CONVERSION_TO_INT(double); FMT_DISABLE_CONVERSION_TO_INT(long double); -template -struct EnableIf {}; +template struct EnableIf +{ +}; -template -struct EnableIf +template struct EnableIf { typedef T type; }; -template -struct Conditional +template struct Conditional { typedef T type; }; -template -struct Conditional +template struct Conditional { typedef F type; }; // For bcc32 which doesn't understand ! in template arguments. -template -struct Not +template struct Not { - enum { value = 0 }; + enum + { + value = 0 + }; }; -template <> -struct Not +template <> struct Not { - enum { value = 1 }; + enum + { + value = 1 + }; }; -template -struct FalseType +template struct FalseType { - enum { value = 0 }; + enum + { + value = 0 + }; }; template struct LConvCheck @@ -1504,9 +1500,7 @@ template struct LConvCheck // Returns the thousands separator for the current locale. // We check if ``lconv`` contains ``thousands_sep`` because on Android // ``lconv`` is stubbed as an empty struct. -template -inline StringRef thousands_sep( - LConv *lc, LConvCheck = 0) +template inline StringRef thousands_sep(LConv *lc, LConvCheck = 0) { return lc->thousands_sep; } @@ -1519,36 +1513,31 @@ inline fmt::StringRef thousands_sep(...) #define FMT_CONCAT(a, b) a##b #if FMT_GCC_VERSION >= 303 -# define FMT_UNUSED __attribute__((unused)) +#define FMT_UNUSED __attribute__((unused)) #else -# define FMT_UNUSED +#define FMT_UNUSED #endif #ifndef FMT_USE_STATIC_ASSERT -# define FMT_USE_STATIC_ASSERT 0 +#define FMT_USE_STATIC_ASSERT 0 #endif -#if FMT_USE_STATIC_ASSERT || FMT_HAS_FEATURE(cxx_static_assert) || \ - (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600 -# define FMT_STATIC_ASSERT(cond, message) static_assert(cond, message) +#if FMT_USE_STATIC_ASSERT || FMT_HAS_FEATURE(cxx_static_assert) || (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600 +#define FMT_STATIC_ASSERT(cond, message) static_assert(cond, message) #else -# define FMT_CONCAT_(a, b) FMT_CONCAT(a, b) -# define FMT_STATIC_ASSERT(cond, message) \ - typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED +#define FMT_CONCAT_(a, b) FMT_CONCAT(a, b) +#define FMT_STATIC_ASSERT(cond, message) typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED #endif -template -void format_arg(Formatter&, ...) +template void format_arg(Formatter &, ...) { - FMT_STATIC_ASSERT(FalseType::value, - "Cannot format argument. To enable the use of ostream " - "operator<< include fmt/ostream.h. Otherwise provide " - "an overload of format_arg."); + FMT_STATIC_ASSERT(FalseType::value, "Cannot format argument. To enable the use of ostream " + "operator<< include fmt/ostream.h. Otherwise provide " + "an overload of format_arg."); } // Makes an Arg object from any type. -template -class MakeValue : public Arg +template class MakeValue : public Arg { public: typedef typename Formatter::Char Char; @@ -1559,10 +1548,8 @@ private: // "void *" or "const void *". In particular, this forbids formatting // of "[const] volatile char *" which is printed as bool by iostreams. // Do not implement! - template - MakeValue(const T *value); - template - MakeValue(T *value); + template MakeValue(const T *value); + template MakeValue(T *value); // The following methods are private to disallow formatting of wide // characters and strings into narrow strings as in @@ -1592,24 +1579,25 @@ private: } // Formats an argument of a custom type, such as a user-defined class. - template - static void format_custom_arg( - void *formatter, const void *arg, void *format_str_ptr) + template static void format_custom_arg(void *formatter, const void *arg, void *format_str_ptr) { - format_arg(*static_cast(formatter), - *static_cast(format_str_ptr), - *static_cast(arg)); + format_arg(*static_cast(formatter), *static_cast(format_str_ptr), *static_cast(arg)); } public: MakeValue() {} -#define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ - MakeValue(Type value) { field = rhs; } \ - static uint64_t type(Type) { return Arg::TYPE; } +#define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ + MakeValue(Type value) \ + { \ + field = rhs; \ + } \ + static uint64_t type(Type) \ + { \ + return Arg::TYPE; \ + } -#define FMT_MAKE_VALUE(Type, field, TYPE) \ - FMT_MAKE_VALUE_(Type, field, TYPE, value) +#define FMT_MAKE_VALUE(Type, field, TYPE) FMT_MAKE_VALUE_(Type, field, TYPE, value) FMT_MAKE_VALUE(bool, int_value, BOOL) FMT_MAKE_VALUE(short, int_value, INT) @@ -1640,8 +1628,7 @@ public: } static uint64_t type(unsigned long) { - return sizeof(unsigned long) == sizeof(unsigned) ? - Arg::UINT : Arg::ULONG_LONG; + return sizeof(unsigned long) == sizeof(unsigned) ? Arg::UINT : Arg::ULONG_LONG; } FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG) @@ -1654,19 +1641,12 @@ public: FMT_MAKE_VALUE(char, int_value, CHAR) #if __cplusplus >= 201103L - template < - typename T, - typename = typename std::enable_if< - std::is_enum::value && ConvertToInt::value>::type> - MakeValue(T value) + template ::value && ConvertToInt::value>::type> MakeValue(T value) { int_value = value; } - template < - typename T, - typename = typename std::enable_if< - std::is_enum::value && ConvertToInt::value>::type> + template ::value && ConvertToInt::value>::type> static uint64_t type(T) { return Arg::INT; @@ -1684,9 +1664,15 @@ public: } #endif -#define FMT_MAKE_STR_VALUE(Type, TYPE) \ - MakeValue(Type value) { set_string(value); } \ - static uint64_t type(Type) { return Arg::TYPE; } +#define FMT_MAKE_STR_VALUE(Type, TYPE) \ + MakeValue(Type value) \ + { \ + set_string(value); \ + } \ + static uint64_t type(Type) \ + { \ + return Arg::TYPE; \ + } FMT_MAKE_VALUE(char *, string.value, CSTRING) FMT_MAKE_VALUE(const char *, string.value, CSTRING) @@ -1701,11 +1687,15 @@ public: FMT_MAKE_STR_VALUE(StringRef, STRING) FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str()) -#define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ - MakeValue(typename WCharHelper::Supported value) { \ - set_string(value); \ - } \ - static uint64_t type(Type) { return Arg::TYPE; } +#define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ + MakeValue(typename WCharHelper::Supported value) \ + { \ + set_string(value); \ + } \ + static uint64_t type(Type) \ + { \ + return Arg::TYPE; \ + } FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) @@ -1718,49 +1708,39 @@ public: FMT_MAKE_VALUE(void *, pointer, POINTER) FMT_MAKE_VALUE(const void *, pointer, POINTER) - template - MakeValue(const T &value, - typename EnableIf::value>::value, int>::type = 0) + template MakeValue(const T &value, typename EnableIf::value>::value, int>::type = 0) { custom.value = &value; custom.format = &format_custom_arg; } - template - static typename EnableIf::value>::value, uint64_t>::type - type(const T &) + template static typename EnableIf::value>::value, uint64_t>::type type(const T &) { return Arg::CUSTOM; } // Additional template param `Char_` is needed here because make_type always // uses char. - template - MakeValue(const NamedArg &value) + template MakeValue(const NamedArg &value) { pointer = &value; } - template - MakeValue(const NamedArgWithType &value) + template MakeValue(const NamedArgWithType &value) { pointer = &value; } - template - static uint64_t type(const NamedArg &) + template static uint64_t type(const NamedArg &) { return Arg::NAMED_ARG; } - template - static uint64_t type(const NamedArgWithType &) + template static uint64_t type(const NamedArgWithType &) { return Arg::NAMED_ARG; } }; -template -class MakeArg : public Arg +template class MakeArg : public Arg { public: MakeArg() @@ -1776,34 +1756,42 @@ public: } }; -template -struct NamedArg : Arg +template struct NamedArg : Arg { BasicStringRef name; template NamedArg(BasicStringRef argname, const T &value) - : Arg(MakeArg< BasicFormatter >(value)), name(argname) {} + : Arg(MakeArg>(value)) + , name(argname) + { + } }; -template -struct NamedArgWithType : NamedArg +template struct NamedArgWithType : NamedArg { NamedArgWithType(BasicStringRef argname, const T &value) - : NamedArg(argname, value) {} + : NamedArg(argname, value) + { + } }; class RuntimeError : public std::runtime_error { protected: - RuntimeError() : std::runtime_error("") {} - RuntimeError(const RuntimeError &rerr) : std::runtime_error(rerr) {} + RuntimeError() + : std::runtime_error("") + { + } + RuntimeError(const RuntimeError &rerr) + : std::runtime_error(rerr) + { + } FMT_API ~RuntimeError() FMT_DTOR_NOEXCEPT FMT_OVERRIDE; }; -template -class ArgMap; -} // namespace internal +template class ArgMap; +} // namespace internal /** An argument list. */ class ArgList @@ -1828,19 +1816,30 @@ private: return type(types_, index); } - template - friend class internal::ArgMap; + template friend class internal::ArgMap; public: // Maximum number of arguments with packed types. - enum { MAX_PACKED_ARGS = 16 }; + enum + { + MAX_PACKED_ARGS = 16 + }; - ArgList() : types_(0) {} + ArgList() + : types_(0) + { + } ArgList(ULongLong types, const internal::Value *values) - : types_(types), values_(values) {} + : types_(types) + , values_(values) + { + } ArgList(ULongLong types, const internal::Arg *args) - : types_(types), args_(args) {} + : types_(types) + , args_(args) + { + } uint64_t types() const { @@ -1881,12 +1880,11 @@ public: { unsigned shift = index * 4; uint64_t mask = 0xf; - return static_cast( - (types & (mask << shift)) >> shift); + return static_cast((types & (mask << shift)) >> shift); } }; -#define FMT_DISPATCH(call) static_cast(this)->call +#define FMT_DISPATCH(call) static_cast(this)->call /** \rst @@ -1912,8 +1910,7 @@ public: }; \endrst */ -template -class ArgVisitor +template class ArgVisitor { private: typedef internal::Arg Arg; @@ -1964,8 +1961,7 @@ public: } /** Visits an argument of any integral type. **/ - template - Result visit_any_int(T) + template Result visit_any_int(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -1983,8 +1979,7 @@ public: } /** Visits a ``double`` or ``long double`` argument. **/ - template - Result visit_any_double(T) + template Result visit_any_double(T) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -2068,22 +2063,30 @@ public: enum Alignment { - ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC + ALIGN_DEFAULT, + ALIGN_LEFT, + ALIGN_RIGHT, + ALIGN_CENTER, + ALIGN_NUMERIC }; // Flags. enum { - SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, - CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. + SIGN_FLAG = 1, + PLUS_FLAG = 2, + MINUS_FLAG = 4, + HASH_FLAG = 8, + CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. }; // An empty format specifier. -struct EmptySpec {}; +struct EmptySpec +{ +}; // A type specifier. -template -struct TypeSpec : EmptySpec +template struct TypeSpec : EmptySpec { Alignment align() const { @@ -2123,7 +2126,11 @@ struct WidthSpec // two specialization of WidthSpec and its subclasses. wchar_t fill_; - WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} + WidthSpec(unsigned width, wchar_t fill) + : width_(width) + , fill_(fill) + { + } unsigned width() const { @@ -2141,7 +2148,10 @@ struct AlignSpec : WidthSpec Alignment align_; AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) - : WidthSpec(width, fill), align_(align) {} + : WidthSpec(width, fill) + , align_(align) + { + } Alignment align() const { @@ -2155,10 +2165,12 @@ struct AlignSpec : WidthSpec }; // An alignment and type specifier. -template -struct AlignTypeSpec : AlignSpec +template struct AlignTypeSpec : AlignSpec { - AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} + AlignTypeSpec(unsigned width, wchar_t fill) + : AlignSpec(width, fill) + { + } bool flag(unsigned) const { @@ -2181,9 +2193,13 @@ struct FormatSpec : AlignSpec int precision_; char type_; - FormatSpec( - unsigned width = 0, char type = 0, wchar_t fill = ' ') - : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} + FormatSpec(unsigned width = 0, char type = 0, wchar_t fill = ' ') + : AlignSpec(width, fill) + , flags_(0) + , precision_(-1) + , type_(type) + { + } bool flag(unsigned f) const { @@ -2204,15 +2220,17 @@ struct FormatSpec : AlignSpec }; // An integer format specifier. -template , typename Char = char> -class IntFormatSpec : public SpecT +template , typename Char = char> class IntFormatSpec : public SpecT { private: T value_; public: IntFormatSpec(T val, const SpecT &spec = SpecT()) - : SpecT(spec), value_(val) {} + : SpecT(spec) + , value_(val) + { + } T value() const { @@ -2221,8 +2239,7 @@ public: }; // A string format specifier. -template -class StrFormatSpec : public AlignSpec +template class StrFormatSpec : public AlignSpec { private: const Char *str_; @@ -2230,7 +2247,8 @@ private: public: template StrFormatSpec(const Char *str, unsigned width, FillChar fill) - : AlignSpec(width, fill), str_(str) + : AlignSpec(width, fill) + , str_(str) { internal::CharTraits::convert(FillChar()); } @@ -2244,24 +2262,24 @@ public: /** Returns an integer format specifier to format the value in base 2. */ -IntFormatSpec > bin(int value); +IntFormatSpec> bin(int value); /** Returns an integer format specifier to format the value in base 8. */ -IntFormatSpec > oct(int value); +IntFormatSpec> oct(int value); /** Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9. */ -IntFormatSpec > hex(int value); +IntFormatSpec> hex(int value); /** Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9. */ -IntFormatSpec > hexu(int value); +IntFormatSpec> hexu(int value); /** \rst @@ -2277,58 +2295,55 @@ IntFormatSpec > hexu(int value); \endrst */ -template -IntFormatSpec, Char> pad( - int value, unsigned width, Char fill = ' '); +template IntFormatSpec, Char> pad(int value, unsigned width, Char fill = ' '); -#define FMT_DEFINE_INT_FORMATTERS(TYPE) \ -inline IntFormatSpec > bin(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'b'>()); \ -} \ - \ -inline IntFormatSpec > oct(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'o'>()); \ -} \ - \ -inline IntFormatSpec > hex(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'x'>()); \ -} \ - \ -inline IntFormatSpec > hexu(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'X'>()); \ -} \ - \ -template \ -inline IntFormatSpec > pad( \ - IntFormatSpec > f, unsigned width) { \ - return IntFormatSpec >( \ - f.value(), AlignTypeSpec(width, ' ')); \ -} \ - \ -/* For compatibility with older compilers we provide two overloads for pad, */ \ -/* one that takes a fill character and one that doesn't. In the future this */ \ -/* can be replaced with one overload making the template argument Char */ \ -/* default to char (C++11). */ \ -template \ -inline IntFormatSpec, Char> pad( \ - IntFormatSpec, Char> f, \ - unsigned width, Char fill) { \ - return IntFormatSpec, Char>( \ - f.value(), AlignTypeSpec(width, fill)); \ -} \ - \ -inline IntFormatSpec > pad( \ - TYPE value, unsigned width) { \ - return IntFormatSpec >( \ - value, AlignTypeSpec<0>(width, ' ')); \ -} \ - \ -template \ -inline IntFormatSpec, Char> pad( \ - TYPE value, unsigned width, Char fill) { \ - return IntFormatSpec, Char>( \ - value, AlignTypeSpec<0>(width, fill)); \ -} +#define FMT_DEFINE_INT_FORMATTERS(TYPE) \ + inline IntFormatSpec> bin(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'b'>()); \ + } \ + \ + inline IntFormatSpec> oct(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'o'>()); \ + } \ + \ + inline IntFormatSpec> hex(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'x'>()); \ + } \ + \ + inline IntFormatSpec> hexu(TYPE value) \ + { \ + return IntFormatSpec>(value, TypeSpec<'X'>()); \ + } \ + \ + template \ + inline IntFormatSpec> pad(IntFormatSpec> f, unsigned width) \ + { \ + return IntFormatSpec>(f.value(), AlignTypeSpec(width, ' ')); \ + } \ + \ + /* For compatibility with older compilers we provide two overloads for pad, */ \ + /* one that takes a fill character and one that doesn't. In the future this */ \ + /* can be replaced with one overload making the template argument Char */ \ + /* default to char (C++11). */ \ + template \ + inline IntFormatSpec, Char> pad( \ + IntFormatSpec, Char> f, unsigned width, Char fill) \ + { \ + return IntFormatSpec, Char>(f.value(), AlignTypeSpec(width, fill)); \ + } \ + \ + inline IntFormatSpec> pad(TYPE value, unsigned width) \ + { \ + return IntFormatSpec>(value, AlignTypeSpec<0>(width, ' ')); \ + } \ + \ + template inline IntFormatSpec, Char> pad(TYPE value, unsigned width, Char fill) \ + { \ + return IntFormatSpec, Char>(value, AlignTypeSpec<0>(width, fill)); \ + } FMT_DEFINE_INT_FORMATTERS(int) FMT_DEFINE_INT_FORMATTERS(long) @@ -2349,28 +2364,22 @@ FMT_DEFINE_INT_FORMATTERS(ULongLong) \endrst */ -template -inline StrFormatSpec pad( - const Char *str, unsigned width, Char fill = ' ') +template inline StrFormatSpec pad(const Char *str, unsigned width, Char fill = ' ') { return StrFormatSpec(str, width, fill); } -inline StrFormatSpec pad( - const wchar_t *str, unsigned width, char fill = ' ') +inline StrFormatSpec pad(const wchar_t *str, unsigned width, char fill = ' ') { return StrFormatSpec(str, width, fill); } -namespace internal -{ +namespace internal { -template -class ArgMap +template class ArgMap { private: - typedef std::vector< - std::pair, internal::Arg> > MapType; + typedef std::vector, internal::Arg>> MapType; typedef typename MapType::value_type Pair; MapType map_; @@ -2381,8 +2390,7 @@ public: const internal::Arg *find(const fmt::BasicStringRef &name) const { // The list is unsorted, so just return the first matching name. - for (typename MapType::const_iterator it = map_.begin(), end = map_.end(); - it != end; ++it) + for (typename MapType::const_iterator it = map_.begin(), end = map_.end(); it != end; ++it) { if (it->first == name) return &it->second; @@ -2391,18 +2399,16 @@ public: } }; -template -void ArgMap::init(const ArgList &args) +template void ArgMap::init(const ArgList &args) { if (!map_.empty()) return; typedef internal::NamedArg NamedArg; const NamedArg *named_arg = FMT_NULL; - bool use_values = - args.type(ArgList::MAX_PACKED_ARGS - 1) == internal::Arg::NONE; + bool use_values = args.type(ArgList::MAX_PACKED_ARGS - 1) == internal::Arg::NONE; if (use_values) { - for (unsigned i = 0;/*nothing*/; ++i) + for (unsigned i = 0; /*nothing*/; ++i) { internal::Arg::Type arg_type = args.type(i); switch (arg_type) @@ -2410,7 +2416,7 @@ void ArgMap::init(const ArgList &args) case internal::Arg::NONE: return; case internal::Arg::NAMED_ARG: - named_arg = static_cast(args.values_[i].pointer); + named_arg = static_cast(args.values_[i].pointer); map_.push_back(Pair(named_arg->name, *named_arg)); break; default: @@ -2425,18 +2431,18 @@ void ArgMap::init(const ArgList &args) internal::Arg::Type arg_type = args.type(i); if (arg_type == internal::Arg::NAMED_ARG) { - named_arg = static_cast(args.args_[i].pointer); + named_arg = static_cast(args.args_[i].pointer); map_.push_back(Pair(named_arg->name, *named_arg)); } } - for (unsigned i = ArgList::MAX_PACKED_ARGS;/*nothing*/; ++i) + for (unsigned i = ArgList::MAX_PACKED_ARGS; /*nothing*/; ++i) { switch (args.args_[i].type) { case internal::Arg::NONE: return; case internal::Arg::NAMED_ARG: - named_arg = static_cast(args.args_[i].pointer); + named_arg = static_cast(args.args_[i].pointer); map_.push_back(Pair(named_arg->name, *named_arg)); break; default: @@ -2446,8 +2452,7 @@ void ArgMap::init(const ArgList &args) } } -template -class ArgFormatterBase : public ArgVisitor +template class ArgFormatterBase : public ArgVisitor { private: BasicWriter &writer_; @@ -2478,7 +2483,7 @@ protected: void write(bool value) { const char *str_value = value ? "true" : "false"; - Arg::StringValue str = { str_value, std::strlen(str_value) }; + Arg::StringValue str = {str_value, std::strlen(str_value)}; writer_.write_str(str, spec_); } @@ -2492,16 +2497,17 @@ public: typedef Spec SpecType; ArgFormatterBase(BasicWriter &w, Spec &s) - : writer_(w), spec_(s) {} + : writer_(w) + , spec_(s) + { + } - template - void visit_any_int(T value) + template void visit_any_int(T value) { writer_.write_int(value, spec_); } - template - void visit_any_double(T value) + template void visit_any_double(T value) { writer_.write_double(value, spec_); } @@ -2540,13 +2546,11 @@ public: } else if (spec_.align_ == ALIGN_CENTER) { - out = writer_.fill_padding(out, spec_.width_, - internal::const_check(CHAR_SIZE), fill); + out = writer_.fill_padding(out, spec_.width_, internal::const_check(CHAR_SIZE), fill); } else { - std::uninitialized_fill_n(out + CHAR_SIZE, - spec_.width_ - CHAR_SIZE, fill); + std::uninitialized_fill_n(out + CHAR_SIZE, spec_.width_ - CHAR_SIZE, fill); } } else @@ -2632,14 +2636,13 @@ protected: return true; } - template - void write(BasicWriter &w, const Char *start, const Char *end) + template void write(BasicWriter &w, const Char *start, const Char *end) { if (start != end) w << BasicStringRef(start, internal::to_unsigned(end - start)); } }; -} // namespace internal +} // namespace internal /** \rst @@ -2674,10 +2677,12 @@ public: to the part of the format string being parsed for custom argument types. \endrst */ - BasicArgFormatter(BasicFormatter &formatter, - Spec &spec, const Char *fmt) - : internal::ArgFormatterBase(formatter.writer(), spec), - formatter_(formatter), format_(fmt) {} + BasicArgFormatter(BasicFormatter &formatter, Spec &spec, const Char *fmt) + : internal::ArgFormatterBase(formatter.writer(), spec) + , formatter_(formatter) + , format_(fmt) + { + } /** Formats an argument of a custom (user-defined) type. */ void visit_custom(internal::Arg::CustomValue c) @@ -2687,21 +2692,18 @@ public: }; /** The default argument formatter. */ -template -class ArgFormatter : - public BasicArgFormatter, Char, FormatSpec> +template class ArgFormatter : public BasicArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ - ArgFormatter(BasicFormatter &formatter, - FormatSpec &spec, const Char *fmt) - : BasicArgFormatter, - Char, FormatSpec>(formatter, spec, fmt) {} + ArgFormatter(BasicFormatter &formatter, FormatSpec &spec, const Char *fmt) + : BasicArgFormatter, Char, FormatSpec>(formatter, spec, fmt) + { + } }; /** This template formats data and writes the output to a writer. */ -template -class BasicFormatter : private internal::FormatterBase +template class BasicFormatter : private internal::FormatterBase { public: /** The character type for the output. */ @@ -2734,7 +2736,10 @@ public: \endrst */ BasicFormatter(const ArgList &args, BasicWriter &w) - : internal::FormatterBase(args), writer_(w) {} + : internal::FormatterBase(args) + , writer_(w) + { + } /** Returns a reference to the writer associated with this formatter. */ BasicWriter &writer() @@ -2751,75 +2756,67 @@ public: // Generates a comma-separated list with results of applying f to // numbers 0..n-1. -# define FMT_GEN(n, f) FMT_GEN##n(f) -# define FMT_GEN1(f) f(0) -# define FMT_GEN2(f) FMT_GEN1(f), f(1) -# define FMT_GEN3(f) FMT_GEN2(f), f(2) -# define FMT_GEN4(f) FMT_GEN3(f), f(3) -# define FMT_GEN5(f) FMT_GEN4(f), f(4) -# define FMT_GEN6(f) FMT_GEN5(f), f(5) -# define FMT_GEN7(f) FMT_GEN6(f), f(6) -# define FMT_GEN8(f) FMT_GEN7(f), f(7) -# define FMT_GEN9(f) FMT_GEN8(f), f(8) -# define FMT_GEN10(f) FMT_GEN9(f), f(9) -# define FMT_GEN11(f) FMT_GEN10(f), f(10) -# define FMT_GEN12(f) FMT_GEN11(f), f(11) -# define FMT_GEN13(f) FMT_GEN12(f), f(12) -# define FMT_GEN14(f) FMT_GEN13(f), f(13) -# define FMT_GEN15(f) FMT_GEN14(f), f(14) +#define FMT_GEN(n, f) FMT_GEN##n(f) +#define FMT_GEN1(f) f(0) +#define FMT_GEN2(f) FMT_GEN1(f), f(1) +#define FMT_GEN3(f) FMT_GEN2(f), f(2) +#define FMT_GEN4(f) FMT_GEN3(f), f(3) +#define FMT_GEN5(f) FMT_GEN4(f), f(4) +#define FMT_GEN6(f) FMT_GEN5(f), f(5) +#define FMT_GEN7(f) FMT_GEN6(f), f(6) +#define FMT_GEN8(f) FMT_GEN7(f), f(7) +#define FMT_GEN9(f) FMT_GEN8(f), f(8) +#define FMT_GEN10(f) FMT_GEN9(f), f(9) +#define FMT_GEN11(f) FMT_GEN10(f), f(10) +#define FMT_GEN12(f) FMT_GEN11(f), f(11) +#define FMT_GEN13(f) FMT_GEN12(f), f(12) +#define FMT_GEN14(f) FMT_GEN13(f), f(13) +#define FMT_GEN15(f) FMT_GEN14(f), f(14) -namespace internal -{ +namespace internal { inline uint64_t make_type() { return 0; } -template -inline uint64_t make_type(const T &arg) +template inline uint64_t make_type(const T &arg) { - return MakeValue< BasicFormatter >::type(arg); + return MakeValue>::type(arg); } -template - struct ArgArray; +template struct ArgArray; -template -struct ArgArray +template struct ArgArray { // '+' is used to silence GCC -Wduplicated-branches warning. typedef Value Type[N > 0 ? N : +1]; -template -static Value make(const T &value) -{ + template static Value make(const T &value) + { #ifdef __clang__ - Value result = MakeValue(value); - // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: - // https://github.com/fmtlib/fmt/issues/276 - (void)result.custom.format; - return result; + Value result = MakeValue(value); + // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: + // https://github.com/fmtlib/fmt/issues/276 + (void)result.custom.format; + return result; #else - return MakeValue(value); + return MakeValue(value); #endif -} - }; + } +}; -template -struct ArgArray +template struct ArgArray { typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE - template - static Arg make(const T &value) + template static Arg make(const T &value) { return MakeArg(value); } }; #if FMT_USE_VARIADIC_TEMPLATES -template -inline uint64_t make_type(const Arg &first, const Args & ... tail) +template inline uint64_t make_type(const Arg &first, const Args &... tail) { return make_type(first) | (make_type(tail...) << 4); } @@ -2830,121 +2827,113 @@ struct ArgType { uint64_t type; - ArgType() : type(0) {} + ArgType() + : type(0) + { + } template - ArgType(const T &arg) : type(make_type(arg)) {} + ArgType(const T &arg) + : type(make_type(arg)) + { + } }; -# define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() +#define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) { - return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | - (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) | - (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | - (t12.type << 48) | (t13.type << 52) | (t14.type << 56); + return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | + (t7.type << 28) | (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | (t12.type << 48) | (t13.type << 52) | + (t14.type << 56); } #endif -} // namespace internal +} // namespace internal -# define FMT_MAKE_TEMPLATE_ARG(n) typename T##n -# define FMT_MAKE_ARG_TYPE(n) T##n -# define FMT_MAKE_ARG(n) const T##n &v##n -# define FMT_ASSIGN_char(n) \ - arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) -# define FMT_ASSIGN_wchar_t(n) \ - arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) +#define FMT_MAKE_TEMPLATE_ARG(n) typename T##n +#define FMT_MAKE_ARG_TYPE(n) T##n +#define FMT_MAKE_ARG(n) const T##n &v##n +#define FMT_ASSIGN_char(n) arr[n] = fmt::internal::MakeValue>(v##n) +#define FMT_ASSIGN_wchar_t(n) arr[n] = fmt::internal::MakeValue>(v##n) #if FMT_USE_VARIADIC_TEMPLATES // Defines a variadic function returning void. -# define FMT_VARIADIC_VOID(func, arg_type) \ - template \ - void func(arg_type arg0, const Args & ... args) { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } +#define FMT_VARIADIC_VOID(func, arg_type) \ + template void func(arg_type arg0, const Args &... args) \ + { \ + typedef fmt::internal::ArgArray ArgArray; \ + typename ArgArray::Type array{ArgArray::template make>(args)...}; \ + func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \ + } // Defines a variadic constructor. -# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - template \ - ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } +#define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ + template ctor(arg0_type arg0, arg1_type arg1, const Args &... args) \ + { \ + typedef fmt::internal::ArgArray ArgArray; \ + typename ArgArray::Type array{ArgArray::template make>(args)...}; \ + func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \ + } #else -# define FMT_MAKE_REF(n) \ - fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) -# define FMT_MAKE_REF2(n) v##n +#define FMT_MAKE_REF(n) fmt::internal::MakeValue>(v##n) +#define FMT_MAKE_REF2(n) v##n // Defines a wrapper for a function taking one argument of type arg_type // and n additional arguments of arbitrary types. -# define FMT_WRAP1(func, arg_type, n) \ - template \ - inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ - const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ - func(arg1, fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ - } +#define FMT_WRAP1(func, arg_type, n) \ + template inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + { \ + const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ + func(arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ + } // Emulates a variadic function returning void on a pre-C++11 compiler. -# define FMT_VARIADIC_VOID(func, arg_type) \ - inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \ - FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \ - FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \ - FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \ - FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ - FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) +#define FMT_VARIADIC_VOID(func, arg_type) \ + inline void func(arg_type arg) \ + { \ + func(arg, fmt::ArgList()); \ + } \ + FMT_WRAP1(func, arg_type, 1) \ + FMT_WRAP1(func, arg_type, 2) \ + FMT_WRAP1(func, arg_type, 3) \ + FMT_WRAP1(func, arg_type, 4) FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) FMT_WRAP1(func, arg_type, 7) \ + FMT_WRAP1(func, arg_type, 8) FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) -# define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ - template \ - ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ - const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ - func(arg0, arg1, fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ - } +#define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ + template ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) \ + { \ + const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ + func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ + } // Emulates a variadic constructor on a pre-C++11 compiler. -# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) +#define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) #endif // Generates a comma-separated list with results of applying f to pairs // (argument, index). #define FMT_FOR_EACH1(f, x0) f(x0, 0) -#define FMT_FOR_EACH2(f, x0, x1) \ - FMT_FOR_EACH1(f, x0), f(x1, 1) -#define FMT_FOR_EACH3(f, x0, x1, x2) \ - FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2) -#define FMT_FOR_EACH4(f, x0, x1, x2, x3) \ - FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) -#define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \ - FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) -#define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \ - FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) -#define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \ - FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) -#define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \ - FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) -#define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \ - FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) -#define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \ - FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) +#define FMT_FOR_EACH2(f, x0, x1) FMT_FOR_EACH1(f, x0), f(x1, 1) +#define FMT_FOR_EACH3(f, x0, x1, x2) FMT_FOR_EACH2(f, x0, x1), f(x2, 2) +#define FMT_FOR_EACH4(f, x0, x1, x2, x3) FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) +#define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) +#define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) +#define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) +#define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) +#define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) +#define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) /** An error returned by an operating system or a language runtime, @@ -2958,7 +2947,7 @@ private: protected: int error_code_; - typedef char Char; // For FMT_VARIADIC_CTOR. + typedef char Char; // For FMT_VARIADIC_CTOR. SystemError() {} @@ -3012,8 +3001,7 @@ public: may look like "Unknown error -1" and is platform-dependent. \endrst */ -FMT_API void format_system_error(fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT; +FMT_API void format_system_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; /** \rst @@ -3033,8 +3021,7 @@ FMT_API void format_system_error(fmt::Writer &out, int error_code, \endrst */ -template -class BasicWriter +template class BasicWriter { private: // Output buffer. @@ -3059,8 +3046,7 @@ private: // Fills the padding around the content and returns the pointer to the // content area. - static CharPtr fill_padding(CharPtr buffer, - unsigned total_size, std::size_t content_size, wchar_t fill); + static CharPtr fill_padding(CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill); // Grows the buffer by n characters and returns a pointer to the newly // allocated area. @@ -3072,8 +3058,7 @@ private: } // Writes an unsigned decimal integer. - template - Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) + template Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) { unsigned num_digits = internal::count_digits(value); Char *ptr = get(grow_buffer(prefix_size + num_digits)); @@ -3082,8 +3067,7 @@ private: } // Writes a decimal integer. - template - void write_decimal(Int value) + template void write_decimal(Int value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -3099,8 +3083,7 @@ private: } // Prepare a buffer for integer formatting. - CharPtr prepare_int_buffer(unsigned num_digits, - const EmptySpec &, const char *prefix, unsigned prefix_size) + CharPtr prepare_int_buffer(unsigned num_digits, const EmptySpec &, const char *prefix, unsigned prefix_size) { unsigned size = prefix_size + num_digits; CharPtr p = grow_buffer(size); @@ -3108,33 +3091,25 @@ private: return p + size - 1; } - template - CharPtr prepare_int_buffer(unsigned num_digits, - const Spec &spec, const char *prefix, unsigned prefix_size); + template CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); // Formats an integer. - template - void write_int(T value, Spec spec); + template void write_int(T value, Spec spec); // Formats a floating-point number (double or long double). - template - void write_double(T value, const Spec &spec); + template void write_double(T value, const Spec &spec); // Writes a formatted string. - template - CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); + template CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); - template - void write_str(const internal::Arg::StringValue &str, - const Spec &spec); + template void write_str(const internal::Arg::StringValue &str, const Spec &spec); // This following methods are private to disallow writing wide characters // and strings to a char stream. If you want to print a wide string as a // pointer as std::ostream does, cast it to const void*. // Do not implement! void operator<<(typename internal::WCharHelper::Unsupported); - void operator<<( - typename internal::WCharHelper::Unsupported); + void operator<<(typename internal::WCharHelper::Unsupported); // Appends floating-point length specifier to the format string. // The second argument is only used for overload resolution. @@ -3143,20 +3118,20 @@ private: *format_ptr++ = 'L'; } - template - void append_float_length(Char *&, T) {} + template void append_float_length(Char *&, T) {} - template - friend class internal::ArgFormatterBase; + template friend class internal::ArgFormatterBase; - template - friend class BasicPrintfArgFormatter; + template friend class BasicPrintfArgFormatter; protected: /** Constructs a ``BasicWriter`` object. */ - explicit BasicWriter(Buffer &b) : buffer_(b) {} + explicit BasicWriter(Buffer &b) + : buffer_(b) + { + } public: /** @@ -3297,8 +3272,7 @@ public: return *this; } - BasicWriter &operator<<( - typename internal::WCharHelper::Supported value) + BasicWriter &operator<<(typename internal::WCharHelper::Supported value) { buffer_.push_back(value); return *this; @@ -3316,39 +3290,41 @@ public: return *this; } - BasicWriter &operator<<( - typename internal::WCharHelper::Supported value) + BasicWriter &operator<<(typename internal::WCharHelper::Supported value) { const char *str = value.data(); buffer_.append(str, str + value.size()); return *this; } - template - BasicWriter &operator<<(IntFormatSpec spec) + template BasicWriter &operator<<(IntFormatSpec spec) { internal::CharTraits::convert(FillChar()); write_int(spec.value(), spec); return *this; } - template - BasicWriter &operator<<(const StrFormatSpec &spec) + template BasicWriter &operator<<(const StrFormatSpec &spec) { const StrChar *s = spec.str(); write_str(s, std::char_traits::length(s), spec); return *this; } - void clear() FMT_NOEXCEPT { buffer_.clear(); } + void clear() FMT_NOEXCEPT + { + buffer_.clear(); + } - Buffer &buffer() FMT_NOEXCEPT { return buffer_; } + Buffer &buffer() FMT_NOEXCEPT + { + return buffer_; + } }; template template -typename BasicWriter::CharPtr BasicWriter::write_str( - const StrChar *s, std::size_t size, const AlignSpec &spec) +typename BasicWriter::CharPtr BasicWriter::write_str(const StrChar *s, std::size_t size, const AlignSpec &spec) { CharPtr out = CharPtr(); if (spec.width() > size) @@ -3379,8 +3355,7 @@ typename BasicWriter::CharPtr BasicWriter::write_str( template template -void BasicWriter::write_str( - const internal::Arg::StringValue &s, const Spec &spec) +void BasicWriter::write_str(const internal::Arg::StringValue &s, const Spec &spec) { // Check if StrChar is convertible to Char. internal::CharTraits::convert(StrChar()); @@ -3402,10 +3377,8 @@ void BasicWriter::write_str( } template -typename BasicWriter::CharPtr -BasicWriter::fill_padding( - CharPtr buffer, unsigned total_size, - std::size_t content_size, wchar_t fill) +typename BasicWriter::CharPtr BasicWriter::fill_padding( + CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill) { std::size_t padding = total_size - content_size; std::size_t left_padding = padding / 2; @@ -3413,17 +3386,14 @@ BasicWriter::fill_padding( std::uninitialized_fill_n(buffer, left_padding, fill_char); buffer += left_padding; CharPtr content = buffer; - std::uninitialized_fill_n(buffer + content_size, - padding - left_padding, fill_char); + std::uninitialized_fill_n(buffer + content_size, padding - left_padding, fill_char); return content; } template template -typename BasicWriter::CharPtr -BasicWriter::prepare_int_buffer( - unsigned num_digits, const Spec &spec, - const char *prefix, unsigned prefix_size) +typename BasicWriter::CharPtr BasicWriter::prepare_int_buffer( + unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size) { unsigned width = spec.width(); Alignment align = spec.align(); @@ -3434,8 +3404,7 @@ BasicWriter::prepare_int_buffer( // is specified. if (prefix_size > 0 && prefix[prefix_size - 1] == '0') --prefix_size; - unsigned number_size = - prefix_size + internal::to_unsigned(spec.precision()); + unsigned number_size = prefix_size + internal::to_unsigned(spec.precision()); AlignSpec subspec(number_size, '0', ALIGN_NUMERIC); if (number_size >= width) return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); @@ -3446,8 +3415,7 @@ BasicWriter::prepare_int_buffer( CharPtr p = grow_buffer(fill_size); std::uninitialized_fill(p, p + fill_size, fill); } - CharPtr result = prepare_int_buffer( - num_digits, subspec, prefix, prefix_size); + CharPtr result = prepare_int_buffer(num_digits, subspec, prefix, prefix_size); if (align == ALIGN_LEFT) { CharPtr p = grow_buffer(fill_size); @@ -3496,9 +3464,7 @@ BasicWriter::prepare_int_buffer( return p - 1; } -template -template -void BasicWriter::write_int(T value, Spec spec) +template template void BasicWriter::write_int(T value, Spec spec) { unsigned prefix_size = 0; typedef typename internal::IntTraits::MainType UnsignedType; @@ -3538,18 +3504,14 @@ void BasicWriter::write_int(T value, Spec spec) do { ++num_digits; - } - while ((n >>= 4) != 0); - Char *p = get(prepare_int_buffer( - num_digits, spec, prefix, prefix_size)); + } while ((n >>= 4) != 0); + Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; - const char *digits = spec.type() == 'x' ? - "0123456789abcdef" : "0123456789ABCDEF"; + const char *digits = spec.type() == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; do { *p-- = digits[n & 0xf]; - } - while ((n >>= 4) != 0); + } while ((n >>= 4) != 0); break; } case 'b': @@ -3565,15 +3527,13 @@ void BasicWriter::write_int(T value, Spec spec) do { ++num_digits; - } - while ((n >>= 1) != 0); + } while ((n >>= 1) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = static_cast('0' + (n & 1)); - } - while ((n >>= 1) != 0); + } while ((n >>= 1) != 0); break; } case 'o': @@ -3585,15 +3545,13 @@ void BasicWriter::write_int(T value, Spec spec) do { ++num_digits; - } - while ((n >>= 3) != 0); + } while ((n >>= 3) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = static_cast('0' + (n & 7)); - } - while ((n >>= 3) != 0); + } while ((n >>= 3) != 0); break; } case 'n': @@ -3603,22 +3561,18 @@ void BasicWriter::write_int(T value, Spec spec) #if !(defined(ANDROID) || defined(__ANDROID__)) sep = internal::thousands_sep(std::localeconv()); #endif - unsigned size = static_cast( - num_digits + sep.size() * ((num_digits - 1) / 3)); + unsigned size = static_cast(num_digits + sep.size() * ((num_digits - 1) / 3)); CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1; internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep)); break; } default: - internal::report_unknown_type( - spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); + internal::report_unknown_type(spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); break; } } -template -template -void BasicWriter::write_double(T value, const Spec &spec) +template template void BasicWriter::write_double(T value, const Spec &spec) { // Check type. char type = spec.type(); @@ -3707,7 +3661,10 @@ void BasicWriter::write_double(T value, const Spec &spec) } // Build format string. - enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg + enum + { + MAX_FORMAT_SIZE = 10 + }; // longest format: %#-*.*Lg Char format[MAX_FORMAT_SIZE]; Char *format_ptr = format; *format_ptr++ = '%'; @@ -3753,13 +3710,12 @@ void BasicWriter::write_double(T value, const Spec &spec) } #endif start = &buffer_[offset]; - int result = internal::CharTraits::format_float( - start, buffer_size, format, width_for_sprintf, spec.precision(), value); + int result = internal::CharTraits::format_float(start, buffer_size, format, width_for_sprintf, spec.precision(), value); if (result >= 0) { n = internal::to_unsigned(result); if (offset + n < buffer_.capacity()) - break; // The buffer is large enough - continue with formatting. + break; // The buffer is large enough - continue with formatting. buffer_.reserve(offset + n + 1); } else @@ -3771,8 +3727,7 @@ void BasicWriter::write_double(T value, const Spec &spec) } if (sign) { - if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || - *start != ' ') + if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || *start != ' ') { *(start - 1) = sign; sign = 0; @@ -3835,15 +3790,17 @@ void BasicWriter::write_double(T value, const Spec &spec) accessed as a C string with ``out.c_str()``. \endrst */ -template > -class BasicMemoryWriter : public BasicWriter +template > class BasicMemoryWriter : public BasicWriter { private: internal::MemoryBuffer buffer_; public: - explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) - : BasicWriter(buffer_), buffer_(alloc) {} + explicit BasicMemoryWriter(const Allocator &alloc = Allocator()) + : BasicWriter(buffer_) + , buffer_(alloc) + { + } #if FMT_USE_RVALUE_REFERENCES /** @@ -3853,7 +3810,8 @@ public: \endrst */ BasicMemoryWriter(BasicMemoryWriter &&other) - : BasicWriter(buffer_), buffer_(std::move(other.buffer_)) + : BasicWriter(buffer_) + , buffer_(std::move(other.buffer_)) { } @@ -3893,8 +3851,7 @@ typedef BasicMemoryWriter WMemoryWriter; +--------------+---------------------------+ \endrst */ -template -class BasicArrayWriter : public BasicWriter +template class BasicArrayWriter : public BasicWriter { private: internal::FixedBuffer buffer_; @@ -3907,7 +3864,10 @@ public: \endrst */ BasicArrayWriter(Char *array, std::size_t size) - : BasicWriter(buffer_), buffer_(array, size) {} + : BasicWriter(buffer_) + , buffer_(array, size) + { + } /** \rst @@ -3917,7 +3877,10 @@ public: */ template explicit BasicArrayWriter(Char (&array)[SIZE]) - : BasicWriter(buffer_), buffer_(array, SIZE) {} + : BasicWriter(buffer_) + , buffer_(array, SIZE) + { + } }; typedef BasicArrayWriter ArrayWriter; @@ -3925,8 +3888,7 @@ typedef BasicArrayWriter WArrayWriter; // Reports a system error without throwing an exception. // Can be used to report errors from destructors. -FMT_API void report_system_error(int error_code, - StringRef message) FMT_NOEXCEPT; +FMT_API void report_system_error(int error_code, StringRef message) FMT_NOEXCEPT; #if FMT_USE_WINDOWS_H @@ -3974,12 +3936,21 @@ public: // Reports a Windows error without throwing an exception. // Can be used to report errors from destructors. -FMT_API void report_windows_error(int error_code, - StringRef message) FMT_NOEXCEPT; +FMT_API void report_windows_error(int error_code, StringRef message) FMT_NOEXCEPT; #endif -enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; +enum Color +{ + BLACK, + RED, + GREEN, + YELLOW, + BLUE, + MAGENTA, + CYAN, + WHITE +}; /** Formats a string and prints it to stdout using ANSI escape sequences @@ -4042,7 +4013,10 @@ class FormatInt private: // Buffer should be large enough to hold all digits (digits10 + 1), // a sign and a null character. - enum {BUFFER_SIZE = std::numeric_limits::digits10 + 3}; + enum + { + BUFFER_SIZE = std::numeric_limits::digits10 + 3 + }; mutable char buffer_[BUFFER_SIZE]; char *str_; @@ -4095,9 +4069,18 @@ public: { FormatSigned(value); } - explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} - explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {} - explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} + explicit FormatInt(unsigned value) + : str_(format_decimal(value)) + { + } + explicit FormatInt(unsigned long value) + : str_(format_decimal(value)) + { + } + explicit FormatInt(ULongLong value) + : str_(format_decimal(value)) + { + } /** Returns the number of characters written to the output buffer. */ std::size_t size() const @@ -4138,8 +4121,7 @@ public: // Formats a decimal integer value writing into buffer and returns // a pointer to the end of the formatted string. This function doesn't // write a terminating null character. -template -inline void format_decimal(char *&buffer, T value) +template inline void format_decimal(char *&buffer, T value) { typedef typename internal::IntTraits::MainType MainType; MainType abs_value = static_cast(value); @@ -4175,32 +4157,28 @@ inline void format_decimal(char *&buffer, T value) \endrst */ -template -inline internal::NamedArgWithType arg(StringRef name, const T &arg) +template inline internal::NamedArgWithType arg(StringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } -template -inline internal::NamedArgWithType arg(WStringRef name, const T &arg) +template inline internal::NamedArgWithType arg(WStringRef name, const T &arg) { return internal::NamedArgWithType(name, arg); } // The following two functions are deleted intentionally to disable // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``. -template -void arg(StringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; -template -void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; -} +template void arg(StringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +template void arg(WStringRef, const internal::NamedArg &) FMT_DELETED_OR_UNDEFINED; +} // namespace fmt #if FMT_GCC_VERSION // Use the system_header pragma to suppress warnings about variadic macros // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't // work. It is used at the end because we want to suppress as little warnings // as possible. -# pragma GCC system_header +#pragma GCC system_header #endif // This is used to work around VC++ bugs in handling variadic macros. @@ -4213,58 +4191,53 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 -#define FMT_FOR_EACH_(N, f, ...) \ - FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) -#define FMT_FOR_EACH(f, ...) \ - FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) +#define FMT_FOR_EACH_(N, f, ...) FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) +#define FMT_FOR_EACH(f, ...) FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) #define FMT_ADD_ARG_NAME(type, index) type arg##index #define FMT_GET_ARG_NAME(type, index) arg##index #if FMT_USE_VARIADIC_TEMPLATES -# define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ - template \ - ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - const Args & ... args) Const { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \ - fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } +#define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ + template ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), const Args &... args) Const \ + { \ + typedef fmt::internal::ArgArray ArgArray; \ + typename ArgArray::Type array{ArgArray::template make>(args)...}; \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList(fmt::internal::make_type(args...), array)); \ + } #else // Defines a wrapper for a function taking __VA_ARGS__ arguments // and n additional arguments of arbitrary types. -# define FMT_WRAP(Const, Char, ReturnType, func, call, n, ...) \ - template \ - inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - FMT_GEN(n, FMT_MAKE_ARG)) Const { \ - fmt::internal::ArgArray::Type arr; \ - FMT_GEN(n, FMT_ASSIGN_##Char); \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ - } +#define FMT_WRAP(Const, Char, ReturnType, func, call, n, ...) \ + template \ + inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), FMT_GEN(n, FMT_MAKE_ARG)) Const \ + { \ + fmt::internal::ArgArray::Type arr; \ + FMT_GEN(n, FMT_ASSIGN_##Char); \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList(fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ + } -# define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ - inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) Const { \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ - } \ - FMT_WRAP(Const, Char, ReturnType, func, call, 1, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 2, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 3, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 4, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 5, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 6, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 7, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 8, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 9, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 10, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 11, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 12, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 13, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 14, __VA_ARGS__) \ - FMT_WRAP(Const, Char, ReturnType, func, call, 15, __VA_ARGS__) -#endif // FMT_USE_VARIADIC_TEMPLATES +#define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ + inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) Const \ + { \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ + } \ + FMT_WRAP(Const, Char, ReturnType, func, call, 1, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 2, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 3, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 4, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 5, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 6, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 7, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 8, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 9, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 10, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 11, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 12, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 13, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 14, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 15, __VA_ARGS__) +#endif // FMT_USE_VARIADIC_TEMPLATES /** \rst @@ -4293,21 +4266,17 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; } \endrst */ -#define FMT_VARIADIC(ReturnType, func, ...) \ - FMT_VARIADIC_(, char, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC(ReturnType, func, ...) FMT_VARIADIC_(, char, ReturnType, func, return func, __VA_ARGS__) -#define FMT_VARIADIC_CONST(ReturnType, func, ...) \ - FMT_VARIADIC_(const, char, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC_CONST(ReturnType, func, ...) FMT_VARIADIC_(const, char, ReturnType, func, return func, __VA_ARGS__) -#define FMT_VARIADIC_W(ReturnType, func, ...) \ - FMT_VARIADIC_(, wchar_t, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC_W(ReturnType, func, ...) FMT_VARIADIC_(, wchar_t, ReturnType, func, return func, __VA_ARGS__) -#define FMT_VARIADIC_CONST_W(ReturnType, func, ...) \ - FMT_VARIADIC_(const, wchar_t, ReturnType, func, return func, __VA_ARGS__) +#define FMT_VARIADIC_CONST_W(ReturnType, func, ...) FMT_VARIADIC_(const, wchar_t, ReturnType, func, return func, __VA_ARGS__) #define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id) -#define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L###id, id) +#define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L## #id, id) /** \rst @@ -4327,26 +4296,22 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; #define FMT_CAPTURE_W(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_W_, __VA_ARGS__) -namespace fmt -{ +namespace fmt { FMT_VARIADIC(std::string, format, CStringRef) FMT_VARIADIC_W(std::wstring, format, WCStringRef) FMT_VARIADIC(void, print, CStringRef) FMT_VARIADIC(void, print, std::FILE *, CStringRef) FMT_VARIADIC(void, print_colored, Color, CStringRef) -namespace internal -{ -template -inline bool is_name_start(Char c) +namespace internal { +template inline bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } // Parses an unsigned integer advancing s to the end of the parsed input. // This function assumes that the first character of s is a digit. -template -unsigned parse_nonnegative_int(const Char *&s) +template unsigned parse_nonnegative_int(const Char *&s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; @@ -4363,8 +4328,7 @@ unsigned parse_nonnegative_int(const Char *&s) } value = value * 10 + (*s - '0'); ++s; - } - while ('0' <= *s && *s <= '9'); + } while ('0' <= *s && *s <= '9'); // Convert to unsigned to prevent a warning. if (value > max_int) FMT_THROW(FormatError("number is too big")); @@ -4375,29 +4339,25 @@ inline void require_numeric_argument(const Arg &arg, char spec) { if (arg.type > Arg::LAST_NUMERIC_TYPE) { - std::string message = - fmt::format("format specifier '{}' requires numeric argument", spec); + std::string message = fmt::format("format specifier '{}' requires numeric argument", spec); FMT_THROW(fmt::FormatError(message)); } } -template -void check_sign(const Char *&s, const Arg &arg) +template void check_sign(const Char *&s, const Arg &arg) { char sign = static_cast(*s); require_numeric_argument(arg, sign); if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { - FMT_THROW(FormatError(fmt::format( - "format specifier '{}' requires signed argument", sign))); + FMT_THROW(FormatError(fmt::format("format specifier '{}' requires signed argument", sign))); } ++s; } -} // namespace internal +} // namespace internal template -inline internal::Arg BasicFormatter::get_arg( - BasicStringRef arg_name, const char *&error) +inline internal::Arg BasicFormatter::get_arg(BasicStringRef arg_name, const char *&error) { if (check_no_auto_index(error)) { @@ -4410,22 +4370,18 @@ inline internal::Arg BasicFormatter::get_arg( return internal::Arg(); } -template -inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) +template inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) { const char *error = FMT_NULL; - internal::Arg arg = *s < '0' || *s > '9' ? - next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); + internal::Arg arg = *s < '0' || *s > '9' ? next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); if (error) { - FMT_THROW(FormatError( - *s != '}' && *s != ':' ? "invalid format string" : error)); + FMT_THROW(FormatError(*s != '}' && *s != ':' ? "invalid format string" : error)); } return arg; } -template -inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) +template inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) { assert(internal::is_name_start(*s)); const Char *start = s; @@ -4433,8 +4389,7 @@ inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) do { c = *++s; - } - while (internal::is_name_start(c) || ('0' <= c && c <= '9')); + } while (internal::is_name_start(c) || ('0' <= c && c <= '9')); const char *error = FMT_NULL; internal::Arg arg = get_arg(BasicStringRef(start, s - start), error); if (error) @@ -4443,8 +4398,7 @@ inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) } template -const Char *BasicFormatter::format( - const Char *&format_str, const internal::Arg &arg) +const Char *BasicFormatter::format(const Char *&format_str, const internal::Arg &arg) { using internal::Arg; const Char *s = format_str; @@ -4483,19 +4437,20 @@ const Char *BasicFormatter::format( { if (p != s) { - if (c == '}') break; + if (c == '}') + break; if (c == '{') FMT_THROW(FormatError("invalid fill character '{'")); s += 2; spec.fill_ = c; } - else ++s; + else + ++s; if (spec.align_ == ALIGN_NUMERIC) require_numeric_argument(arg, '='); break; } - } - while (--p >= s); + } while (--p >= s); } // Parse sign. @@ -4539,8 +4494,7 @@ const Char *BasicFormatter::format( else if (*s == '{') { ++s; - Arg width_arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); + Arg width_arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); if (*s++ != '}') FMT_THROW(FormatError("invalid format string")); ULongLong value = 0; @@ -4583,8 +4537,7 @@ const Char *BasicFormatter::format( else if (*s == '{') { ++s; - Arg precision_arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); + Arg precision_arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); if (*s++ != '}') FMT_THROW(FormatError("invalid format string")); ULongLong value = 0; @@ -4621,8 +4574,7 @@ const Char *BasicFormatter::format( if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) { FMT_THROW(FormatError( - fmt::format("precision not allowed in {} format specifier", - arg.type == Arg::POINTER ? "pointer" : "integer"))); + fmt::format("precision not allowed in {} format specifier", arg.type == Arg::POINTER ? "pointer" : "integer"))); } } @@ -4639,15 +4591,15 @@ const Char *BasicFormatter::format( return s; } -template -void BasicFormatter::format(BasicCStringRef format_str) +template void BasicFormatter::format(BasicCStringRef format_str) { const Char *s = format_str.c_str(); const Char *start = s; while (*s) { Char c = *s++; - if (c != '{' && c != '}') continue; + if (c != '{' && c != '}') + continue; if (*s == c) { write(writer_, start, s); @@ -4657,59 +4609,53 @@ void BasicFormatter::format(BasicCStringRef format_str) if (c == '}') FMT_THROW(FormatError("unmatched '}' in format string")); write(writer_, start, s - 1); - internal::Arg arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); + internal::Arg arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); start = s = format(s, arg); } write(writer_, start, s); } -template -struct ArgJoin +template struct ArgJoin { It first; It last; BasicCStringRef sep; - ArgJoin(It first, It last, const BasicCStringRef& sep) : - first(first), - last(last), - sep(sep) {} + ArgJoin(It first, It last, const BasicCStringRef &sep) + : first(first) + , last(last) + , sep(sep) + { + } }; -template -ArgJoin join(It first, It last, const BasicCStringRef& sep) +template ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } -template -ArgJoin join(It first, It last, const BasicCStringRef& sep) +template ArgJoin join(It first, It last, const BasicCStringRef &sep) { return ArgJoin(first, last, sep); } #if FMT_HAS_GXX_CXX11 -template -auto join(const Range& range, const BasicCStringRef& sep) --> ArgJoin +template auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } template -auto join(const Range& range, const BasicCStringRef& sep) --> ArgJoin +auto join(const Range &range, const BasicCStringRef &sep) -> ArgJoin { return join(std::begin(range), std::end(range), sep); } #endif template -void format_arg(fmt::BasicFormatter &f, - const Char *&format_str, const ArgJoin& e) +void format_arg(fmt::BasicFormatter &f, const Char *&format_str, const ArgJoin &e) { - const Char* end = format_str; + const Char *end = format_str; if (*end == ':') ++end; while (*end && *end != '}') @@ -4720,45 +4666,38 @@ void format_arg(fmt::BasicFormatter &f, It it = e.first; if (it != e.last) { - const Char* save = format_str; - f.format(format_str, internal::MakeArg >(*it++)); + const Char *save = format_str; + f.format(format_str, internal::MakeArg>(*it++)); while (it != e.last) { f.writer().write(e.sep); format_str = save; - f.format(format_str, internal::MakeArg >(*it++)); + f.format(format_str, internal::MakeArg>(*it++)); } } format_str = end + 1; } -} // namespace fmt +} // namespace fmt #if FMT_USE_USER_DEFINED_LITERALS -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { -template -struct UdlFormat +template struct UdlFormat { const Char *str; - template - auto operator()(Args && ... args) const - -> decltype(format(str, std::forward(args)...)) + template auto operator()(Args &&... args) const -> decltype(format(str, std::forward(args)...)) { return format(str, std::forward(args)...); } }; -template -struct UdlArg +template struct UdlArg { const Char *str; - template - NamedArgWithType operator=(T &&value) const + template NamedArgWithType operator=(T &&value) const { return {str, std::forward(value)}; } @@ -4766,8 +4705,7 @@ struct UdlArg } // namespace internal -inline namespace literals -{ +inline namespace literals { /** \rst @@ -4779,13 +4717,11 @@ inline namespace literals std::string message = "The answer is {}"_format(42); \endrst */ -inline internal::UdlFormat -operator"" _format(const char *s, std::size_t) +inline internal::UdlFormat operator"" _format(const char *s, std::size_t) { return {s}; } -inline internal::UdlFormat -operator"" _format(const wchar_t *s, std::size_t) +inline internal::UdlFormat operator"" _format(const wchar_t *s, std::size_t) { return {s}; } @@ -4800,35 +4736,33 @@ operator"" _format(const wchar_t *s, std::size_t) print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); \endrst */ -inline internal::UdlArg -operator"" _a(const char *s, std::size_t) +inline internal::UdlArg operator"" _a(const char *s, std::size_t) { return {s}; } -inline internal::UdlArg -operator"" _a(const wchar_t *s, std::size_t) +inline internal::UdlArg operator"" _a(const wchar_t *s, std::size_t) { return {s}; } -} // inline namespace literals +} // namespace literals } // namespace fmt #endif // FMT_USE_USER_DEFINED_LITERALS // Restore warnings. #if FMT_GCC_VERSION >= 406 -# pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif #if defined(__clang__) && !defined(FMT_ICC_VERSION) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif #ifdef FMT_HEADER_ONLY -# define FMT_FUNC inline -# include "format.cc" +#define FMT_FUNC inline +#include "format.cc" #else -# define FMT_FUNC +#define FMT_FUNC #endif -#endif // FMT_FORMAT_H_ +#endif // FMT_FORMAT_H_ diff --git a/include/spdlog/fmt/bundled/ostream.h b/include/spdlog/fmt/bundled/ostream.h index f1b09dfc..1a21f984 100644 --- a/include/spdlog/fmt/bundled/ostream.h +++ b/include/spdlog/fmt/bundled/ostream.h @@ -13,14 +13,11 @@ #include "format.h" #include -namespace fmt -{ +namespace fmt { -namespace internal -{ +namespace internal { -template -class FormatBuf : public std::basic_streambuf +template class FormatBuf : public std::basic_streambuf { private: typedef typename std::basic_streambuf::int_type int_type; @@ -29,7 +26,10 @@ private: Buffer &buffer_; public: - FormatBuf(Buffer &buffer) : buffer_(buffer) {} + FormatBuf(Buffer &buffer) + : buffer_(buffer) + { + } protected: // The put-area is actually always empty. This makes the implementation @@ -57,17 +57,15 @@ Yes &convert(std::ostream &); struct DummyStream : std::ostream { - DummyStream(); // Suppress a bogus warning in MSVC. + DummyStream(); // Suppress a bogus warning in MSVC. // Hide all operator<< overloads from std::ostream. - template - typename EnableIf::type operator<<(const T &); + template typename EnableIf::type operator<<(const T &); }; No &operator<<(std::ostream &, int); -template -struct ConvertToIntImpl +template struct ConvertToIntImpl { // Convert to int only if T doesn't have an overloaded operator<<. enum @@ -78,12 +76,11 @@ struct ConvertToIntImpl // Write the content of w to os. FMT_API void write(std::ostream &os, Writer &w); -} // namespace internal +} // namespace internal // Formats a value. template -void format_arg(BasicFormatter &f, - const Char *&format_str, const T &value) +void format_arg(BasicFormatter &f, const Char *&format_str, const T &value) { internal::MemoryBuffer buffer; @@ -93,7 +90,7 @@ void format_arg(BasicFormatter &f, output << value; BasicStringRef str(&buffer[0], buffer.size()); - typedef internal::MakeArg< BasicFormatter > MakeArg; + typedef internal::MakeArg> MakeArg; format_str = f.format(format_str, MakeArg(str)); } @@ -108,10 +105,10 @@ void format_arg(BasicFormatter &f, */ FMT_API void print(std::ostream &os, CStringRef format_str, ArgList args); FMT_VARIADIC(void, print, std::ostream &, CStringRef) -} // namespace fmt +} // namespace fmt #ifdef FMT_HEADER_ONLY -# include "ostream.cc" +#include "ostream.cc" #endif -#endif // FMT_OSTREAM_H_ +#endif // FMT_OSTREAM_H_ diff --git a/include/spdlog/fmt/bundled/posix.h b/include/spdlog/fmt/bundled/posix.h index 69327250..20af016c 100644 --- a/include/spdlog/fmt/bundled/posix.h +++ b/include/spdlog/fmt/bundled/posix.h @@ -12,60 +12,60 @@ #if defined(__MINGW32__) || defined(__CYGWIN__) // Workaround MinGW bug https://sourceforge.net/p/mingw/bugs/2024/. -# undef __STRICT_ANSI__ +#undef __STRICT_ANSI__ #endif #include -#include // for O_RDONLY -#include // for locale_t +#include // for O_RDONLY +#include // for locale_t #include -#include // for strtod_l +#include // for strtod_l #include #if defined __APPLE__ || defined(__FreeBSD__) -# include // for LC_NUMERIC_MASK on OS X +#include // for LC_NUMERIC_MASK on OS X #endif #include "format.h" #ifndef FMT_POSIX -# if defined(_WIN32) && !defined(__MINGW32__) +#if defined(_WIN32) && !defined(__MINGW32__) // Fix warnings about deprecated symbols. -# define FMT_POSIX(call) _##call -# else -# define FMT_POSIX(call) call -# endif +#define FMT_POSIX(call) _##call +#else +#define FMT_POSIX(call) call +#endif #endif // Calls to system functions are wrapped in FMT_SYSTEM for testability. #ifdef FMT_SYSTEM -# define FMT_POSIX_CALL(call) FMT_SYSTEM(call) +#define FMT_POSIX_CALL(call) FMT_SYSTEM(call) #else -# define FMT_SYSTEM(call) call -# ifdef _WIN32 +#define FMT_SYSTEM(call) call +#ifdef _WIN32 // Fix warnings about deprecated symbols. -# define FMT_POSIX_CALL(call) ::_##call -# else -# define FMT_POSIX_CALL(call) ::call -# endif +#define FMT_POSIX_CALL(call) ::_##call +#else +#define FMT_POSIX_CALL(call) ::call +#endif #endif // Retries the expression while it evaluates to error_result and errno // equals to EINTR. #ifndef _WIN32 -# define FMT_RETRY_VAL(result, expression, error_result) \ - do { \ - result = (expression); \ - } while (result == error_result && errno == EINTR) +#define FMT_RETRY_VAL(result, expression, error_result) \ + do \ + { \ + result = (expression); \ + } while (result == error_result && errno == EINTR) #else -# define FMT_RETRY_VAL(result, expression, error_result) result = (expression) +#define FMT_RETRY_VAL(result, expression, error_result) result = (expression) #endif #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) -namespace fmt -{ +namespace fmt { // An error code. class ErrorCode @@ -74,8 +74,7 @@ private: int value_; public: -explicit ErrorCode(int value = 0) FMT_NOEXCEPT : - value_(value) {} + explicit ErrorCode(int value = 0) FMT_NOEXCEPT : value_(value) {} int get() const FMT_NOEXCEPT { @@ -91,12 +90,14 @@ private: friend class File; - explicit BufferedFile(FILE *f) : file_(f) {} + explicit BufferedFile(FILE *f) + : file_(f) + { + } public: // Constructs a BufferedFile object which doesn't represent any file. -BufferedFile() FMT_NOEXCEPT : - file_(FMT_NULL) {} + BufferedFile() FMT_NOEXCEPT : file_(FMT_NULL) {} // Destroys the object closing the file it represents if any. FMT_API ~BufferedFile() FMT_NOEXCEPT; @@ -115,12 +116,10 @@ private: public: // A "move constructor" for moving from a temporary. -BufferedFile(Proxy p) FMT_NOEXCEPT : - file_(p.file) {} + BufferedFile(Proxy p) FMT_NOEXCEPT : file_(p.file) {} // A "move constructor" for moving from an lvalue. -BufferedFile(BufferedFile &f) FMT_NOEXCEPT : - file_(f.file_) + BufferedFile(BufferedFile &f) FMT_NOEXCEPT : file_(f.file_) { f.file_ = FMT_NULL; } @@ -156,13 +155,12 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(BufferedFile); public: -BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : - file_(other.file_) + BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : file_(other.file_) { other.file_ = FMT_NULL; } - BufferedFile& operator=(BufferedFile &&other) + BufferedFile &operator=(BufferedFile &&other) { close(); file_ = other.file_; @@ -185,7 +183,7 @@ BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : // We place parentheses around fileno to workaround a bug in some versions // of MinGW that define fileno as a macro. - FMT_API int (fileno)() const; + FMT_API int(fileno)() const; void print(CStringRef format_str, const ArgList &args) { @@ -203,10 +201,13 @@ BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : class File { private: - int fd_; // File descriptor. + int fd_; // File descriptor. // Constructs a File object with a given descriptor. - explicit File(int fd) : fd_(fd) {} + explicit File(int fd) + : fd_(fd) + { + } public: // Possible values for the oflag argument to the constructor. @@ -214,12 +215,11 @@ public: { RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. - RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. + RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. }; // Constructs a File object which doesn't represent any file. -File() FMT_NOEXCEPT : - fd_(-1) {} + File() FMT_NOEXCEPT : fd_(-1) {} // Opens a file and constructs a File object representing this file. FMT_API File(CStringRef path, int oflag); @@ -238,12 +238,10 @@ private: public: // A "move constructor" for moving from a temporary. -File(Proxy p) FMT_NOEXCEPT : - fd_(p.fd) {} + File(Proxy p) FMT_NOEXCEPT : fd_(p.fd) {} // A "move constructor" for moving from an lvalue. -File(File &other) FMT_NOEXCEPT : - fd_(other.fd_) + File(File &other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } @@ -279,13 +277,12 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(File); public: -File(File &&other) FMT_NOEXCEPT : - fd_(other.fd_) + File(File &&other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } - File& operator=(File &&other) + File &operator=(File &&other) { close(); fd_ = other.fd_; @@ -340,9 +337,8 @@ File(File &&other) FMT_NOEXCEPT : // Returns the memory page size. long getpagesize(); -#if (defined(LC_NUMERIC_MASK) || defined(_MSC_VER)) && \ - !defined(__ANDROID__) && !defined(__CYGWIN__) -# define FMT_LOCALE +#if (defined(LC_NUMERIC_MASK) || defined(_MSC_VER)) && !defined(__ANDROID__) && !defined(__CYGWIN__) +#define FMT_LOCALE #endif #ifdef FMT_LOCALE @@ -350,10 +346,13 @@ long getpagesize(); class Locale { private: -# ifdef _MSC_VER +#ifdef _MSC_VER typedef _locale_t locale_t; - enum { LC_NUMERIC_MASK = LC_NUMERIC }; + enum + { + LC_NUMERIC_MASK = LC_NUMERIC + }; static locale_t newlocale(int category_mask, const char *locale, locale_t) { @@ -369,7 +368,7 @@ private: { return _strtod_l(nptr, endptr, locale); } -# endif +#endif locale_t locale_; @@ -378,7 +377,8 @@ private: public: typedef locale_t Type; - Locale() : locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL)) + Locale() + : locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL)) { if (!locale_) FMT_THROW(fmt::SystemError(errno, "cannot create locale")); @@ -403,12 +403,11 @@ public: return result; } }; -#endif // FMT_LOCALE -} // namespace fmt +#endif // FMT_LOCALE +} // namespace fmt #if !FMT_USE_RVALUE_REFERENCES -namespace std -{ +namespace std { // For compatibility with C++98. inline fmt::BufferedFile &move(fmt::BufferedFile &f) { @@ -418,7 +417,7 @@ inline fmt::File &move(fmt::File &f) { return f; } -} +} // namespace std #endif -#endif // FMT_POSIX_H_ +#endif // FMT_POSIX_H_ diff --git a/include/spdlog/fmt/bundled/printf.h b/include/spdlog/fmt/bundled/printf.h index 14242143..4f540048 100644 --- a/include/spdlog/fmt/bundled/printf.h +++ b/include/spdlog/fmt/bundled/printf.h @@ -10,23 +10,19 @@ #ifndef FMT_PRINTF_H_ #define FMT_PRINTF_H_ -#include // std::fill_n -#include // std::numeric_limits +#include // std::fill_n +#include // std::numeric_limits #include "ostream.h" -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { // Checks if a value fits in int - used to avoid warnings about comparing // signed and unsigned integers. -template -struct IntChecker +template struct IntChecker { - template - static bool fits_in_int(T value) + template static bool fits_in_int(T value) { unsigned max = std::numeric_limits::max(); return value <= max; @@ -37,14 +33,11 @@ struct IntChecker } }; -template <> -struct IntChecker +template <> struct IntChecker { - template - static bool fits_in_int(T value) + template static bool fits_in_int(T value) { - return value >= std::numeric_limits::min() && - value <= std::numeric_limits::max(); + return value >= std::numeric_limits::min() && value <= std::numeric_limits::max(); } static bool fits_in_int(int) { @@ -60,8 +53,7 @@ public: FMT_THROW(FormatError("precision is not integer")); } - template - int visit_any_int(T value) + template int visit_any_int(T value) { if (!IntChecker::is_signed>::fits_in_int(value)) FMT_THROW(FormatError("number is too big")); @@ -73,8 +65,7 @@ public: class IsZeroInt : public ArgVisitor { public: - template - bool visit_any_int(T value) + template bool visit_any_int(T value) { return value == 0; } @@ -99,14 +90,12 @@ public: return 'p'; } - template - char visit_any_int(T) + template char visit_any_int(T) { return 'd'; } - template - char visit_any_double(T) + template char visit_any_double(T) { return 'g'; } @@ -117,24 +106,27 @@ public: } }; -template -struct is_same +template struct is_same { - enum { value = 0 }; + enum + { + value = 0 + }; }; -template -struct is_same +template struct is_same { - enum { value = 1 }; + enum + { + value = 1 + }; }; // An argument visitor that converts an integer argument to T for printf, // if T is an integral type. If T is void, the argument is converted to // corresponding signed or unsigned type depending on the type specifier: // 'd' and 'i' - signed, other - unsigned) -template -class ArgConverter : public ArgVisitor, void> +template class ArgConverter : public ArgVisitor, void> { private: internal::Arg &arg_; @@ -144,7 +136,10 @@ private: public: ArgConverter(internal::Arg &arg, wchar_t type) - : arg_(arg), type_(type) {} + : arg_(arg) + , type_(type) + { + } void visit_bool(bool value) { @@ -158,8 +153,7 @@ public: visit_any_int(value); } - template - void visit_any_int(U value) + template void visit_any_int(U value) { bool is_signed = type_ == 'd' || type_ == 'i'; if (type_ == 's') @@ -168,8 +162,7 @@ public: } using internal::Arg; - typedef typename internal::Conditional< - is_same::value, U, T>::type TargetType; + typedef typename internal::Conditional::value, U, T>::type TargetType; if (const_check(sizeof(TargetType) <= sizeof(int))) { // Extra casts are used to silence warnings. @@ -198,8 +191,7 @@ public: else { arg_.type = Arg::ULONG_LONG; - arg_.ulong_long_value = - static_cast::Type>(value); + arg_.ulong_long_value = static_cast::Type>(value); } } } @@ -214,10 +206,12 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter); public: - explicit CharConverter(internal::Arg &arg) : arg_(arg) {} + explicit CharConverter(internal::Arg &arg) + : arg_(arg) + { + } - template - void visit_any_int(T value) + template void visit_any_int(T value) { arg_.type = internal::Arg::CHAR; arg_.int_value = static_cast(value); @@ -234,15 +228,17 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler); public: - explicit WidthHandler(FormatSpec &spec) : spec_(spec) {} + explicit WidthHandler(FormatSpec &spec) + : spec_(spec) + { + } void report_unhandled_arg() { FMT_THROW(FormatError("width is not integer")); } - template - unsigned visit_any_int(T value) + template unsigned visit_any_int(T value) { typedef typename internal::IntTraits::MainType UnsignedType; UnsignedType width = static_cast(value); @@ -257,7 +253,7 @@ public: return static_cast(width); } }; -} // namespace internal +} // namespace internal /** \rst @@ -276,9 +272,7 @@ public: superclass will be called. \endrst */ -template -class BasicPrintfArgFormatter : - public internal::ArgFormatterBase +template class BasicPrintfArgFormatter : public internal::ArgFormatterBase { private: void write_null_pointer() @@ -298,7 +292,9 @@ public: \endrst */ BasicPrintfArgFormatter(BasicWriter &w, Spec &s) - : internal::ArgFormatterBase(w, s) {} + : internal::ArgFormatterBase(w, s) + { + } /** Formats an argument of type ``bool``. */ void visit_bool(bool value) @@ -371,19 +367,18 @@ public: }; /** The default printf argument formatter. */ -template -class PrintfArgFormatter : - public BasicPrintfArgFormatter, Char, FormatSpec> +template class PrintfArgFormatter : public BasicPrintfArgFormatter, Char, FormatSpec> { public: /** Constructs an argument formatter object. */ PrintfArgFormatter(BasicWriter &w, FormatSpec &s) - : BasicPrintfArgFormatter, Char, FormatSpec>(w, s) {} + : BasicPrintfArgFormatter, Char, FormatSpec>(w, s) + { + } }; /** This template formats data and writes the output to a writer. */ -template > -class PrintfFormatter : private internal::FormatterBase +template > class PrintfFormatter : private internal::FormatterBase { private: BasicWriter &writer_; @@ -392,9 +387,7 @@ private: // Returns the argument with specified index or, if arg_index is equal // to the maximum unsigned value, the next argument. - internal::Arg get_arg( - const Char *s, - unsigned arg_index = (std::numeric_limits::max)()); + internal::Arg get_arg(const Char *s, unsigned arg_index = (std::numeric_limits::max)()); // Parses argument index, flags and width and returns the argument index. unsigned parse_header(const Char *&s, FormatSpec &spec); @@ -408,14 +401,16 @@ public: \endrst */ explicit PrintfFormatter(const ArgList &al, BasicWriter &w) - : FormatterBase(al), writer_(w) {} + : FormatterBase(al) + , writer_(w) + { + } /** Formats stored arguments and writes the output to the writer. */ void format(BasicCStringRef format_str); }; -template -void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) +template void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) { for (;;) { @@ -443,22 +438,17 @@ void PrintfFormatter::parse_flags(FormatSpec &spec, const Char *&s) } } -template -internal::Arg PrintfFormatter::get_arg(const Char *s, - unsigned arg_index) +template internal::Arg PrintfFormatter::get_arg(const Char *s, unsigned arg_index) { (void)s; const char *error = FMT_NULL; - internal::Arg arg = arg_index == std::numeric_limits::max() ? - next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); + internal::Arg arg = arg_index == std::numeric_limits::max() ? next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); if (error) FMT_THROW(FormatError(!*s ? "invalid format string" : error)); return arg; } -template -unsigned PrintfFormatter::parse_header( - const Char *&s, FormatSpec &spec) +template unsigned PrintfFormatter::parse_header(const Char *&s, FormatSpec &spec) { unsigned arg_index = std::numeric_limits::max(); Char c = *s; @@ -467,7 +457,7 @@ unsigned PrintfFormatter::parse_header( // Parse an argument index (if followed by '$') or a width possibly // preceded with '0' flag(s). unsigned value = internal::parse_nonnegative_int(s); - if (*s == '$') // value is an argument index + if (*s == '$') // value is an argument index { ++s; arg_index = value; @@ -499,15 +489,15 @@ unsigned PrintfFormatter::parse_header( return arg_index; } -template -void PrintfFormatter::format(BasicCStringRef format_str) +template void PrintfFormatter::format(BasicCStringRef format_str) { const Char *start = format_str.c_str(); const Char *s = start; while (*s) { Char c = *s++; - if (c != '%') continue; + if (c != '%') + continue; if (*s == c) { write(writer_, start, s); @@ -550,7 +540,7 @@ void PrintfFormatter::format(BasicCStringRef format_str) if (arg.type <= Arg::LAST_NUMERIC_TYPE) spec.align_ = ALIGN_NUMERIC; else - spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. + spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. } // Parse length and convert the argument to the required type. @@ -703,10 +693,10 @@ inline int fprintf(std::ostream &os, CStringRef format_str, ArgList args) return static_cast(w.size()); } FMT_VARIADIC(int, fprintf, std::ostream &, CStringRef) -} // namespace fmt +} // namespace fmt #ifdef FMT_HEADER_ONLY -# include "printf.cc" +#include "printf.cc" #endif -#endif // FMT_PRINTF_H_ +#endif // FMT_PRINTF_H_ diff --git a/include/spdlog/fmt/bundled/time.h b/include/spdlog/fmt/bundled/time.h index 206d0920..e06fa5b4 100644 --- a/include/spdlog/fmt/bundled/time.h +++ b/include/spdlog/fmt/bundled/time.h @@ -14,16 +14,13 @@ #include #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4702) // unreachable code -# pragma warning(disable: 4996) // "deprecated" functions +#pragma warning(push) +#pragma warning(disable : 4702) // unreachable code +#pragma warning(disable : 4996) // "deprecated" functions #endif -namespace fmt -{ -template -void format_arg(BasicFormatter &f, - const char *&format_str, const std::tm &tm) +namespace fmt { +template void format_arg(BasicFormatter &f, const char *&format_str, const std::tm &tm) { if (*format_str == ':') ++format_str; @@ -60,8 +57,7 @@ void format_arg(BasicFormatter &f, format_str = end + 1; } -namespace internal -{ +namespace internal { inline Null<> localtime_r(...) { return Null<>(); @@ -78,7 +74,7 @@ inline Null<> gmtime_s(...) { return Null<>(); } -} +} // namespace internal // Thread-safe replacement for std::localtime inline std::tm localtime(std::time_t time) @@ -88,7 +84,10 @@ inline std::tm localtime(std::time_t time) std::time_t time_; std::tm tm_; - LocalTime(std::time_t t): time_(t) {} + LocalTime(std::time_t t) + : time_(t) + { + } bool run() { @@ -116,7 +115,8 @@ inline std::tm localtime(std::time_t time) { using namespace fmt::internal; std::tm *tm = std::localtime(&time_); - if (tm) tm_ = *tm; + if (tm) + tm_ = *tm; return tm != FMT_NULL; } }; @@ -136,7 +136,10 @@ inline std::tm gmtime(std::time_t time) std::time_t time_; std::tm tm_; - GMTime(std::time_t t): time_(t) {} + GMTime(std::time_t t) + : time_(t) + { + } bool run() { @@ -163,7 +166,8 @@ inline std::tm gmtime(std::time_t time) bool fallback(internal::Null<>) { std::tm *tm = std::gmtime(&time_); - if (tm != FMT_NULL) tm_ = *tm; + if (tm != FMT_NULL) + tm_ = *tm; return tm != FMT_NULL; } }; @@ -174,10 +178,10 @@ inline std::tm gmtime(std::time_t time) FMT_THROW(fmt::FormatError("time_t value out of range")); return std::tm(); } -} //namespace fmt +} // namespace fmt #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif -#endif // FMT_TIME_H_ +#endif // FMT_TIME_H_ diff --git a/include/spdlog/fmt/fmt.h b/include/spdlog/fmt/fmt.h index 92ca4e50..e2e04854 100644 --- a/include/spdlog/fmt/fmt.h +++ b/include/spdlog/fmt/fmt.h @@ -23,7 +23,7 @@ #include "bundled/printf.h" #endif -#else //external fmtlib +#else // external fmtlib #include #if defined(SPDLOG_FMT_PRINTF) @@ -31,4 +31,3 @@ #endif #endif - diff --git a/include/spdlog/fmt/ostr.h b/include/spdlog/fmt/ostr.h index 5cdd5cd0..cf4c32c5 100644 --- a/include/spdlog/fmt/ostr.h +++ b/include/spdlog/fmt/ostr.h @@ -8,10 +8,8 @@ // include external or bundled copy of fmtlib's ostream support // #if !defined(SPDLOG_FMT_EXTERNAL) -#include "fmt.h" #include "bundled/ostream.h" +#include "fmt.h" #else #include #endif - - diff --git a/include/spdlog/formatter.h b/include/spdlog/formatter.h index 203dc31a..55388ec5 100644 --- a/include/spdlog/formatter.h +++ b/include/spdlog/formatter.h @@ -7,14 +7,12 @@ #include "details/log_msg.h" -#include -#include #include +#include +#include -namespace spdlog -{ -namespace details -{ +namespace spdlog { +namespace details { class flag_formatter; } @@ -22,26 +20,27 @@ class formatter { public: virtual ~formatter() = default; - virtual void format(details::log_msg& msg) = 0; + virtual void format(details::log_msg &msg) = 0; }; class pattern_formatter SPDLOG_FINAL : public formatter { public: - explicit pattern_formatter(const std::string& pattern, pattern_time_type pattern_time = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol); - pattern_formatter(const pattern_formatter&) = delete; - pattern_formatter& operator=(const pattern_formatter&) = delete; - void format(details::log_msg& msg) override; + explicit pattern_formatter(const std::string &pattern, pattern_time_type pattern_time = pattern_time_type::local, + std::string eol = spdlog::details::os::default_eol); + pattern_formatter(const pattern_formatter &) = delete; + pattern_formatter &operator=(const pattern_formatter &) = delete; + void format(details::log_msg &msg) override; private: const std::string _eol; const std::string _pattern; const pattern_time_type _pattern_time; std::vector> _formatters; - std::tm get_time(details::log_msg& msg); + std::tm get_time(details::log_msg &msg); void handle_flag(char flag); - void compile_pattern(const std::string& pattern); + void compile_pattern(const std::string &pattern); }; -} +} // namespace spdlog #include "details/pattern_formatter_impl.h" diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 5502d273..4f3bfa56 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -12,63 +12,61 @@ // 2. Format the message using the formatter function // 3. Pass the formatted message to its sinks to performa the actual logging -#include "sinks/base_sink.h" #include "common.h" +#include "sinks/base_sink.h" -#include #include #include +#include -namespace spdlog -{ +namespace spdlog { class logger { public: - logger(const std::string& name, sink_ptr single_sink); - logger(const std::string& name, sinks_init_list sinks); + logger(const std::string &name, sink_ptr single_sink); + logger(const std::string &name, sinks_init_list sinks); - template - logger(std::string name, const It& begin, const It& end); + template logger(std::string name, const It &begin, const It &end); virtual ~logger(); - logger(const logger&) = delete; - logger& operator=(const logger&) = delete; + logger(const logger &) = delete; + logger &operator=(const logger &) = delete; - template void log(level::level_enum lvl, const char* fmt, const Args&... args); - template void log(level::level_enum lvl, const char* msg); - template void trace(const char* fmt, const Arg1&, const Args&... args); - template void debug(const char* fmt, const Arg1&, const Args&... args); - template void info(const char* fmt, const Arg1&, const Args&... args); - template void warn(const char* fmt, const Arg1&, const Args&... args); - template void error(const char* fmt, const Arg1&, const Args&... args); - template void critical(const char* fmt, const Arg1&, const Args&... args); + template void log(level::level_enum lvl, const char *fmt, const Args &... args); + template void log(level::level_enum lvl, const char *msg); + template void trace(const char *fmt, const Arg1 &, const Args &... args); + template void debug(const char *fmt, const Arg1 &, const Args &... args); + template void info(const char *fmt, const Arg1 &, const Args &... args); + template void warn(const char *fmt, const Arg1 &, const Args &... args); + template void error(const char *fmt, const Arg1 &, const Args &... args); + template void critical(const char *fmt, const Arg1 &, const Args &... args); #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT - template void log(level::level_enum lvl, const wchar_t* msg); - template void log(level::level_enum lvl, const wchar_t* fmt, const Args&... args); - template void trace(const wchar_t* fmt, const Args&... args); - template void debug(const wchar_t* fmt, const Args&... args); - template void info(const wchar_t* fmt, const Args&... args); - template void warn(const wchar_t* fmt, const Args&... args); - template void error(const wchar_t* fmt, const Args&... args); - template void critical(const wchar_t* fmt, const Args&... args); + template void log(level::level_enum lvl, const wchar_t *msg); + template void log(level::level_enum lvl, const wchar_t *fmt, const Args &... args); + template void trace(const wchar_t *fmt, const Args &... args); + template void debug(const wchar_t *fmt, const Args &... args); + template void info(const wchar_t *fmt, const Args &... args); + template void warn(const wchar_t *fmt, const Args &... args); + template void error(const wchar_t *fmt, const Args &... args); + template void critical(const wchar_t *fmt, const Args &... args); #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT - template void log(level::level_enum lvl, const T&); - template void trace(const T& msg); - template void debug(const T& msg); - template void info(const T& msg); - template void warn(const T& msg); - template void error(const T& msg); - template void critical(const T& msg); + template void log(level::level_enum lvl, const T &); + template void trace(const T &msg); + template void debug(const T &msg); + template void info(const T &msg); + template void warn(const T &msg); + template void error(const T &msg); + template void critical(const T &msg); bool should_log(level::level_enum msg_level) const; void set_level(level::level_enum log_level); level::level_enum level() const; - const std::string& name() const; - void set_pattern(const std::string& pattern, pattern_time_type pattern_time = pattern_time_type::local); + const std::string &name() const; + void set_pattern(const std::string &pattern, pattern_time_type pattern_time = pattern_time_type::local); void set_formatter(formatter_ptr msg_formatter); // automatically call flush() if message level >= log_level @@ -76,25 +74,25 @@ public: virtual void flush(); - const std::vector& sinks() const; + const std::vector &sinks() const; // error handler virtual void set_error_handler(log_err_handler err_handler); virtual log_err_handler error_handler(); protected: - virtual void _sink_it(details::log_msg& msg); - virtual void _set_pattern(const std::string& pattern, pattern_time_type pattern_time); + virtual void _sink_it(details::log_msg &msg); + virtual void _set_pattern(const std::string &pattern, pattern_time_type pattern_time); virtual void _set_formatter(formatter_ptr msg_formatter); // default error handler: print the error to stderr with the max rate of 1 message/minute virtual void _default_err_handler(const std::string &msg); // return true if the given message level should trigger a flush - bool _should_flush_on(const details::log_msg& msg); + bool _should_flush_on(const details::log_msg &msg); // increment the message count (only if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)) - void _incr_msg_counter(details::log_msg& msg); + void _incr_msg_counter(details::log_msg &msg); const std::string _name; std::vector _sinks; @@ -105,6 +103,6 @@ protected: std::atomic _last_err_time; std::atomic _msg_counter; }; -} +} // namespace spdlog #include "details/logger_impl.h" diff --git a/include/spdlog/sinks/android_sink.h b/include/spdlog/sinks/android_sink.h index e3766755..1284441e 100644 --- a/include/spdlog/sinks/android_sink.h +++ b/include/spdlog/sinks/android_sink.h @@ -7,34 +7,35 @@ #if defined(__ANDROID__) -#include "sink.h" #include "../details/os.h" +#include "sink.h" +#include +#include #include #include -#include #include -#include #if !defined(SPDLOG_ANDROID_RETRIES) #define SPDLOG_ANDROID_RETRIES 2 #endif -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* -* Android sink (logging using __android_log_write) -* __android_log_write is thread-safe. No lock is needed. -*/ + * Android sink (logging using __android_log_write) + * __android_log_write is thread-safe. No lock is needed. + */ class android_sink : public sink { public: - explicit android_sink(const std::string& tag = "spdlog", bool use_raw_msg = false): _tag(tag), _use_raw_msg(use_raw_msg) {} + explicit android_sink(const std::string &tag = "spdlog", bool use_raw_msg = false) + : _tag(tag) + , _use_raw_msg(use_raw_msg) + { + } - void log(const details::log_msg& msg) override + void log(const details::log_msg &msg) override { const android_LogPriority priority = convert_to_android(msg.level); const char *msg_output = (_use_raw_msg ? msg.raw.c_str() : msg.formatted.c_str()); @@ -42,7 +43,7 @@ public: // See system/core/liblog/logger_write.c for explanation of return value int ret = __android_log_write(priority, _tag.c_str(), msg_output); int retry_count = 0; - while ((ret == -11/*EAGAIN*/) && (retry_count < SPDLOG_ANDROID_RETRIES)) + while ((ret == -11 /*EAGAIN*/) && (retry_count < SPDLOG_ANDROID_RETRIES)) { details::os::sleep_for_millis(5); ret = __android_log_write(priority, _tag.c_str(), msg_output); @@ -55,14 +56,12 @@ public: } } - void flush() override - { - } + void flush() override {} private: static android_LogPriority convert_to_android(spdlog::level::level_enum level) { - switch(level) + switch (level) { case spdlog::level::trace: return ANDROID_LOG_VERBOSE; @@ -85,7 +84,6 @@ private: bool _use_raw_msg; }; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index 4bd884cc..7cb2b3e7 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -5,28 +5,25 @@ #pragma once -#include "base_sink.h" #include "../common.h" #include "../details/os.h" +#include "base_sink.h" #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /** * This sink prefixes the output with an ANSI escape sequence color code depending on the severity * of the message. * If no color terminal detected, omit the escape codes. */ -template -class ansicolor_sink : public base_sink +template class ansicolor_sink : public base_sink { public: - explicit ansicolor_sink(FILE* file) : target_file_(file) + explicit ansicolor_sink(FILE *file) + : target_file_(file) { should_do_colors_ = details::os::in_terminal(file) && details::os::is_color_terminal(); colors_[level::trace] = cyan; @@ -43,7 +40,7 @@ public: _flush(); } - void set_color(level::level_enum color_level, const std::string& color) + void set_color(level::level_enum color_level, const std::string &color) { std::lock_guard lock(base_sink::_mutex); colors_[color_level] = color; @@ -80,13 +77,13 @@ public: const std::string on_white = "\033[47m"; protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { // Wrap the originally formatted message in color codes. // If color is not supported in the terminal, log as is instead. if (should_do_colors_) { - const std::string& prefix = colors_[msg.level]; + const std::string &prefix = colors_[msg.level]; fwrite(prefix.data(), sizeof(char), prefix.size(), target_file_); fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), target_file_); fwrite(reset.data(), sizeof(char), reset.size(), target_file_); @@ -104,34 +101,33 @@ protected: fflush(target_file_); } - FILE* target_file_; + FILE *target_file_; bool should_do_colors_; std::unordered_map colors_; }; - -template -class ansicolor_stdout_sink: public ansicolor_sink +template class ansicolor_stdout_sink : public ansicolor_sink { public: - ansicolor_stdout_sink(): ansicolor_sink(stdout) - {} + ansicolor_stdout_sink() + : ansicolor_sink(stdout) + { + } }; using ansicolor_stdout_sink_mt = ansicolor_stdout_sink; using ansicolor_stdout_sink_st = ansicolor_stdout_sink; -template -class ansicolor_stderr_sink: public ansicolor_sink +template class ansicolor_stderr_sink : public ansicolor_sink { public: - ansicolor_stderr_sink(): ansicolor_sink(stderr) - {} + ansicolor_stderr_sink() + : ansicolor_sink(stderr) + { + } }; using ansicolor_stderr_sink_mt = ansicolor_stderr_sink; using ansicolor_stderr_sink_st = ansicolor_stderr_sink; -} // namespace sinks -} // namespace spdlog - +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h index 1d975892..bf67a59c 100644 --- a/include/spdlog/sinks/base_sink.h +++ b/include/spdlog/sinks/base_sink.h @@ -10,27 +10,23 @@ // all locking is taken care of here so no locking needed by the implementers.. // -#include "sink.h" -#include "../formatter.h" #include "../common.h" #include "../details/log_msg.h" +#include "../formatter.h" +#include "sink.h" #include -namespace spdlog -{ -namespace sinks -{ -template -class base_sink : public sink +namespace spdlog { namespace sinks { +template class base_sink : public sink { public: base_sink() = default; - base_sink(const base_sink&) = delete; - base_sink& operator=(const base_sink&) = delete; + base_sink(const base_sink &) = delete; + base_sink &operator=(const base_sink &) = delete; - void log(const details::log_msg& msg) SPDLOG_FINAL override + void log(const details::log_msg &msg) SPDLOG_FINAL override { std::lock_guard lock(_mutex); _sink_it(msg); @@ -43,9 +39,8 @@ public: } protected: - virtual void _sink_it(const details::log_msg& msg) = 0; + virtual void _sink_it(const details::log_msg &msg) = 0; virtual void _flush() = 0; Mutex _mutex; }; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/dist_sink.h b/include/spdlog/sinks/dist_sink.h index 39f162c5..b204790b 100644 --- a/include/spdlog/sinks/dist_sink.h +++ b/include/spdlog/sinks/dist_sink.h @@ -11,32 +11,31 @@ #include "sink.h" #include -#include #include +#include #include // Distribution sink (mux). Stores a vector of sinks which get called when log is called -namespace spdlog -{ -namespace sinks -{ -template -class dist_sink : public base_sink +namespace spdlog { namespace sinks { +template class dist_sink : public base_sink { public: - explicit dist_sink() :_sinks() {} - dist_sink(const dist_sink&) = delete; - dist_sink& operator=(const dist_sink&) = delete; + explicit dist_sink() + : _sinks() + { + } + dist_sink(const dist_sink &) = delete; + dist_sink &operator=(const dist_sink &) = delete; protected: std::vector> _sinks; - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { for (auto &sink : _sinks) { - if( sink->should_log( msg.level)) + if (sink->should_log(msg.level)) { sink->log(msg); } @@ -66,5 +65,4 @@ public: using dist_sink_mt = dist_sink; using dist_sink_st = dist_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/file_sinks.h b/include/spdlog/sinks/file_sinks.h index 39f7b7bb..48322e83 100644 --- a/include/spdlog/sinks/file_sinks.h +++ b/include/spdlog/sinks/file_sinks.h @@ -5,31 +5,28 @@ #pragma once -#include "base_sink.h" -#include "../details/null_mutex.h" #include "../details/file_helper.h" +#include "../details/null_mutex.h" #include "../fmt/fmt.h" +#include "base_sink.h" #include +#include #include #include #include #include #include -#include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* * Trivial file sink with single file as target */ -template -class simple_file_sink SPDLOG_FINAL : public base_sink +template class simple_file_sink SPDLOG_FINAL : public base_sink { public: - explicit simple_file_sink(const filename_t &filename, bool truncate = false):_force_flush(false) + explicit simple_file_sink(const filename_t &filename, bool truncate = false) + : _force_flush(false) { _file_helper.open(filename, truncate); } @@ -40,10 +37,10 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { _file_helper.write(msg); - if(_force_flush) + if (_force_flush) _file_helper.flush(); } @@ -63,23 +60,21 @@ using simple_file_sink_st = simple_file_sink; /* * Rotating file sink based on size */ -template -class rotating_file_sink SPDLOG_FINAL : public base_sink +template class rotating_file_sink SPDLOG_FINAL : public base_sink { public: - rotating_file_sink(filename_t base_filename, - std::size_t max_size, std::size_t max_files) : - _base_filename(std::move(base_filename)), - _max_size(max_size), - _max_files(max_files) + rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files) + : _base_filename(std::move(base_filename)) + , _max_size(max_size) + , _max_files(max_files) { _file_helper.open(calc_filename(_base_filename, 0)); - _current_size = _file_helper.size(); //expensive. called only once + _current_size = _file_helper.size(); // expensive. called only once } // calc filename according to index and file extension if exists. // e.g. calc_filename("logs/mylog.txt, 3) => "logs/mylog.3.txt". - static filename_t calc_filename(const filename_t& filename, std::size_t index) + static filename_t calc_filename(const filename_t &filename, std::size_t index) { typename std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; if (index != 0u) @@ -96,7 +91,7 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { _current_size += msg.formatted.size(); if (_current_size > _max_size) @@ -158,13 +153,14 @@ using rotating_file_sink_st = rotating_file_sink; struct default_daily_file_name_calculator { // Create filename for the form filename.YYYY-MM-DD_hh-mm.ext - static filename_t calc_filename(const filename_t& filename) + static filename_t calc_filename(const filename_t &filename) { std::tm tm = spdlog::details::os::localtime(); filename_t basename, ext; std::tie(basename, ext) = details::file_helper::split_by_extenstion(filename); std::conditional::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; - w.write(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}{}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, ext); + w.write(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}-{:02d}{}"), basename, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, ext); return w.str(); } }; @@ -175,7 +171,7 @@ struct default_daily_file_name_calculator struct dateonly_daily_file_name_calculator { // Create filename for the form basename.YYYY-MM-DD - static filename_t calc_filename(const filename_t& filename) + static filename_t calc_filename(const filename_t &filename) { std::tm tm = spdlog::details::os::localtime(); filename_t basename, ext; @@ -189,18 +185,14 @@ struct dateonly_daily_file_name_calculator /* * Rotating file sink based on date. rotates at midnight */ -template -class daily_file_sink SPDLOG_FINAL :public base_sink < Mutex > +template class daily_file_sink SPDLOG_FINAL : public base_sink { public: - //create daily file sink which rotates on given time - daily_file_sink( - filename_t base_filename, - int rotation_hour, - int rotation_minute) : - _base_filename(std::move(base_filename)), - _rotation_h(rotation_hour), - _rotation_m(rotation_minute) + // create daily file sink which rotates on given time + daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute) + : _base_filename(std::move(base_filename)) + , _rotation_h(rotation_hour) + , _rotation_m(rotation_minute) { if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59) throw spdlog_ex("daily_file_sink: Invalid rotation time in ctor"); @@ -208,9 +200,8 @@ public: _file_helper.open(FileNameCalc::calc_filename(_base_filename)); } - protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { if (std::chrono::system_clock::now() >= _rotation_tp) { @@ -239,7 +230,7 @@ private: { return rotation_time; } - return{ rotation_time + std::chrono::hours(24) }; + return {rotation_time + std::chrono::hours(24)}; } filename_t _base_filename; @@ -252,5 +243,4 @@ private: using daily_file_sink_mt = daily_file_sink; using daily_file_sink_st = daily_file_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/msvc_sink.h b/include/spdlog/sinks/msvc_sink.h index d230613e..e58d49ce 100644 --- a/include/spdlog/sinks/msvc_sink.h +++ b/include/spdlog/sinks/msvc_sink.h @@ -7,43 +7,35 @@ #if defined(_WIN32) -#include "base_sink.h" #include "../details/null_mutex.h" +#include "base_sink.h" #include #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* -* MSVC sink (logging using OutputDebugStringA) -*/ -template -class msvc_sink : public base_sink + * MSVC sink (logging using OutputDebugStringA) + */ +template class msvc_sink : public base_sink { public: - explicit msvc_sink() - { - } + explicit msvc_sink() {} protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { OutputDebugStringA(msg.formatted.c_str()); } - void _flush() override - {} + void _flush() override {} }; using msvc_sink_mt = msvc_sink; using msvc_sink_st = msvc_sink; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/sinks/null_sink.h b/include/spdlog/sinks/null_sink.h index 9a4fd08d..d8eab97c 100644 --- a/include/spdlog/sinks/null_sink.h +++ b/include/spdlog/sinks/null_sink.h @@ -5,31 +5,22 @@ #pragma once -#include "base_sink.h" #include "../details/null_mutex.h" +#include "base_sink.h" #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { -template -class null_sink : public base_sink +template class null_sink : public base_sink { protected: - void _sink_it(const details::log_msg&) override - {} - - void _flush() override - {} + void _sink_it(const details::log_msg &) override {} + void _flush() override {} }; using null_sink_mt = null_sink; using null_sink_st = null_sink; -} -} - +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h index 9648cc05..bb79de76 100644 --- a/include/spdlog/sinks/ostream_sink.h +++ b/include/spdlog/sinks/ostream_sink.h @@ -8,23 +8,23 @@ #include "../details/null_mutex.h" #include "base_sink.h" -#include #include +#include -namespace spdlog -{ -namespace sinks -{ -template -class ostream_sink : public base_sink +namespace spdlog { namespace sinks { +template class ostream_sink : public base_sink { public: - explicit ostream_sink(std::ostream& os, bool force_flush=false) :_ostream(os), _force_flush(force_flush) {} - ostream_sink(const ostream_sink&) = delete; - ostream_sink& operator=(const ostream_sink&) = delete; + explicit ostream_sink(std::ostream &os, bool force_flush = false) + : _ostream(os) + , _force_flush(force_flush) + { + } + ostream_sink(const ostream_sink &) = delete; + ostream_sink &operator=(const ostream_sink &) = delete; protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { _ostream.write(msg.formatted.data(), msg.formatted.size()); if (_force_flush) @@ -36,12 +36,11 @@ protected: _ostream.flush(); } - std::ostream& _ostream; + std::ostream &_ostream; bool _force_flush; }; using ostream_sink_mt = ostream_sink; using ostream_sink_st = ostream_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h index ff7a144e..f3c146d9 100644 --- a/include/spdlog/sinks/sink.h +++ b/include/spdlog/sinks/sink.h @@ -7,16 +7,13 @@ #include "../details/log_msg.h" -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { class sink { public: virtual ~sink() = default; - virtual void log(const details::log_msg& msg) = 0; + virtual void log(const details::log_msg &msg) = 0; virtual void flush() = 0; bool should_log(level::level_enum msg_level) const; @@ -24,7 +21,7 @@ public: level::level_enum level() const; private: - level_t _level{ level::trace }; + level_t _level{level::trace}; }; inline bool sink::should_log(level::level_enum msg_level) const @@ -42,5 +39,4 @@ inline level::level_enum sink::level() const return static_cast(_level.load(std::memory_order_relaxed)); } -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h index 0567a05d..4494323b 100644 --- a/include/spdlog/sinks/stdout_sinks.h +++ b/include/spdlog/sinks/stdout_sinks.h @@ -12,13 +12,9 @@ #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { -template -class stdout_sink SPDLOG_FINAL : public base_sink +template class stdout_sink SPDLOG_FINAL : public base_sink { using MyType = stdout_sink; @@ -32,7 +28,7 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), stdout); _flush(); @@ -47,8 +43,7 @@ protected: using stdout_sink_mt = stdout_sink; using stdout_sink_st = stdout_sink; -template -class stderr_sink SPDLOG_FINAL : public base_sink +template class stderr_sink SPDLOG_FINAL : public base_sink { using MyType = stderr_sink; @@ -62,7 +57,7 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), stderr); _flush(); @@ -77,5 +72,4 @@ protected: using stderr_sink_mt = stderr_sink; using stderr_sink_st = stderr_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/syslog_sink.h b/include/spdlog/sinks/syslog_sink.h index d1ffc5c8..e4472f2f 100644 --- a/include/spdlog/sinks/syslog_sink.h +++ b/include/spdlog/sinks/syslog_sink.h @@ -9,18 +9,14 @@ #ifdef SPDLOG_ENABLE_SYSLOG -#include "sink.h" #include "../details/log_msg.h" +#include "sink.h" #include #include #include - -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /** * Sink that write to syslog using the `syscall()` library call. * @@ -30,8 +26,8 @@ class syslog_sink : public sink { public: // - syslog_sink(const std::string& ident = "", int syslog_option=0, int syslog_facility=LOG_USER): - _ident(ident) + syslog_sink(const std::string &ident = "", int syslog_option = 0, int syslog_facility = LOG_USER) + : _ident(ident) { _priorities[static_cast(level::trace)] = LOG_DEBUG; _priorities[static_cast(level::debug)] = LOG_DEBUG; @@ -41,8 +37,8 @@ public: _priorities[static_cast(level::critical)] = LOG_CRIT; _priorities[static_cast(level::off)] = LOG_INFO; - //set ident to be program name if empty - ::openlog(_ident.empty()? nullptr:_ident.c_str(), syslog_option, syslog_facility); + // set ident to be program name if empty + ::openlog(_ident.empty() ? nullptr : _ident.c_str(), syslog_option, syslog_facility); } ~syslog_sink() override @@ -50,22 +46,19 @@ public: ::closelog(); } - syslog_sink(const syslog_sink&) = delete; - syslog_sink& operator=(const syslog_sink&) = delete; + syslog_sink(const syslog_sink &) = delete; + syslog_sink &operator=(const syslog_sink &) = delete; void log(const details::log_msg &msg) override { ::syslog(syslog_prio_from_level(msg), "%s", msg.raw.str().c_str()); } - void flush() override - { - } - + void flush() override {} private: std::array _priorities; - //must store the ident because the man says openlog might use the pointer as is and not a string copy + // must store the ident because the man says openlog might use the pointer as is and not a string copy const std::string _ident; // @@ -76,7 +69,6 @@ private: return _priorities[static_cast(msg.level)]; } }; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 3b4495b0..77ae59e1 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -5,24 +5,20 @@ #pragma once -#include "base_sink.h" -#include "../details/null_mutex.h" #include "../common.h" +#include "../details/null_mutex.h" +#include "base_sink.h" #include #include #include #include -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* * Windows color console sink. Uses WriteConsoleA to write to the console with colors */ -template -class wincolor_sink : public base_sink +template class wincolor_sink : public base_sink { public: const WORD BOLD = FOREGROUND_INTENSITY; @@ -31,13 +27,14 @@ public: const WORD WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; const WORD YELLOW = FOREGROUND_RED | FOREGROUND_GREEN; - wincolor_sink(HANDLE std_handle): out_handle_(std_handle) + wincolor_sink(HANDLE std_handle) + : out_handle_(std_handle) { colors_[level::trace] = CYAN; colors_[level::debug] = CYAN; colors_[level::info] = WHITE | BOLD; colors_[level::warn] = YELLOW | BOLD; - colors_[level::err] = RED | BOLD; // red bold + colors_[level::err] = RED | BOLD; // red bold colors_[level::critical] = BACKGROUND_RED | WHITE | BOLD; // white bold on red background colors_[level::off] = 0; } @@ -47,8 +44,8 @@ public: this->flush(); } - wincolor_sink(const wincolor_sink& other) = delete; - wincolor_sink& operator=(const wincolor_sink& other) = delete; + wincolor_sink(const wincolor_sink &other) = delete; + wincolor_sink &operator=(const wincolor_sink &other) = delete; // change the color for the given level void set_color(level::level_enum level, WORD color) @@ -58,12 +55,12 @@ public: } protected: - void _sink_it(const details::log_msg& msg) override + void _sink_it(const details::log_msg &msg) override { auto color = colors_[msg.level]; auto orig_attribs = set_console_attribs(color); WriteConsoleA(out_handle_, msg.formatted.data(), static_cast(msg.formatted.size()), nullptr, nullptr); - SetConsoleTextAttribute(out_handle_, orig_attribs); //reset to orig colors + SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors } void _flush() override @@ -85,19 +82,20 @@ private: back_color &= static_cast(~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)); // keep the background color unchanged SetConsoleTextAttribute(out_handle_, attribs | back_color); - return orig_buffer_info.wAttributes; //return orig attribs + return orig_buffer_info.wAttributes; // return orig attribs } }; // // windows color console to stdout // -template -class wincolor_stdout_sink : public wincolor_sink +template class wincolor_stdout_sink : public wincolor_sink { public: - wincolor_stdout_sink() : wincolor_sink(GetStdHandle(STD_OUTPUT_HANDLE)) - {} + wincolor_stdout_sink() + : wincolor_sink(GetStdHandle(STD_OUTPUT_HANDLE)) + { + } }; using wincolor_stdout_sink_mt = wincolor_stdout_sink; @@ -106,16 +104,16 @@ using wincolor_stdout_sink_st = wincolor_stdout_sink; // // windows color console to stderr // -template -class wincolor_stderr_sink : public wincolor_sink +template class wincolor_stderr_sink : public wincolor_sink { public: - wincolor_stderr_sink() : wincolor_sink(GetStdHandle(STD_ERROR_HANDLE)) - {} + wincolor_stderr_sink() + : wincolor_sink(GetStdHandle(STD_ERROR_HANDLE)) + { + } }; using wincolor_stderr_sink_mt = wincolor_stderr_sink; using wincolor_stderr_sink_st = wincolor_stderr_sink; -} -} +}} // namespace spdlog::sinks diff --git a/include/spdlog/sinks/windebug_sink.h b/include/spdlog/sinks/windebug_sink.h index 37d67245..5bd58042 100644 --- a/include/spdlog/sinks/windebug_sink.h +++ b/include/spdlog/sinks/windebug_sink.h @@ -9,21 +9,16 @@ #include "msvc_sink.h" -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { namespace sinks { /* -* Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) -*/ -template -using windebug_sink = msvc_sink; + * Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) + */ +template using windebug_sink = msvc_sink; using windebug_sink_mt = msvc_sink_mt; using windebug_sink_st = msvc_sink_st; -} -} +}} // namespace spdlog::sinks #endif diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index 8965e59f..34706a38 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -7,30 +7,27 @@ #pragma once - #include "common.h" #include "logger.h" -#include -#include #include +#include +#include #include -namespace spdlog -{ +namespace spdlog { // // Return an existing logger or nullptr if a logger with such name doesn't exist. // example: spdlog::get("my_logger")->info("hello {}", "world"); // -std::shared_ptr get(const std::string& name); - +std::shared_ptr get(const std::string &name); // // Set global formatting // example: spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%e %l : %v"); // -void set_pattern(const std::string& format_string); +void set_pattern(const std::string &format_string); void set_formatter(formatter_ptr f); // @@ -64,80 +61,93 @@ void set_error_handler(log_err_handler handler); // worker_teardown_cb (optional): // callback function that will be called in worker thread upon exit // -void set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); +void set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); // Turn off async mode void set_sync_mode(); - // // Create and register multi/single threaded basic file logger. // Basic logger simply writes to given file without any limitations or rotations. // -std::shared_ptr basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate = false); -std::shared_ptr basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate = false); +std::shared_ptr basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false); +std::shared_ptr basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false); // // Create and register multi/single threaded rotating file logger // -std::shared_ptr rotating_logger_mt(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files); -std::shared_ptr rotating_logger_st(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files); +std::shared_ptr rotating_logger_mt( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files); +std::shared_ptr rotating_logger_st( + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files); // // Create file logger which creates new file on the given time (default in midnight): // -std::shared_ptr daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour=0, int minute=0); -std::shared_ptr daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour=0, int minute=0); +std::shared_ptr daily_logger_mt(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); +std::shared_ptr daily_logger_st(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0); // // Create and register stdout/stderr loggers // -std::shared_ptr stdout_logger_mt(const std::string& logger_name); -std::shared_ptr stdout_logger_st(const std::string& logger_name); -std::shared_ptr stderr_logger_mt(const std::string& logger_name); -std::shared_ptr stderr_logger_st(const std::string& logger_name); +std::shared_ptr stdout_logger_mt(const std::string &logger_name); +std::shared_ptr stdout_logger_st(const std::string &logger_name); +std::shared_ptr stderr_logger_mt(const std::string &logger_name); +std::shared_ptr stderr_logger_st(const std::string &logger_name); // // Create and register colored stdout/stderr loggers // -std::shared_ptr stdout_color_mt(const std::string& logger_name); -std::shared_ptr stdout_color_st(const std::string& logger_name); -std::shared_ptr stderr_color_mt(const std::string& logger_name); -std::shared_ptr stderr_color_st(const std::string& logger_name); - +std::shared_ptr stdout_color_mt(const std::string &logger_name); +std::shared_ptr stdout_color_st(const std::string &logger_name); +std::shared_ptr stderr_color_mt(const std::string &logger_name); +std::shared_ptr stderr_color_st(const std::string &logger_name); // // Create and register a syslog logger // #ifdef SPDLOG_ENABLE_SYSLOG -std::shared_ptr syslog_logger(const std::string& logger_name, const std::string& ident = "", int syslog_option = 0, int syslog_facilty = (1<<3)); +std::shared_ptr syslog_logger( + const std::string &logger_name, const std::string &ident = "", int syslog_option = 0, int syslog_facilty = (1 << 3)); #endif #if defined(__ANDROID__) -std::shared_ptr android_logger(const std::string& logger_name, const std::string& tag = "spdlog"); +std::shared_ptr android_logger(const std::string &logger_name, const std::string &tag = "spdlog"); #endif // Create and register a logger with a single sink -std::shared_ptr create(const std::string& logger_name, const sink_ptr& sink); +std::shared_ptr create(const std::string &logger_name, const sink_ptr &sink); // Create and register a logger with multiple sinks -std::shared_ptr create(const std::string& logger_name, sinks_init_list sinks); -template -std::shared_ptr create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end); - +std::shared_ptr create(const std::string &logger_name, sinks_init_list sinks); +template std::shared_ptr create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end); // Create and register a logger with templated sink type // Example: // spdlog::create("mylog", "dailylog_filename"); -template -std::shared_ptr create(const std::string& logger_name, Args... args); +template std::shared_ptr create(const std::string &logger_name, Args... args); // Create and register an async logger with a single sink -std::shared_ptr create_async(const std::string& logger_name, const sink_ptr& sink, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); +std::shared_ptr create_async(const std::string &logger_name, const sink_ptr &sink, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); // Create and register an async logger with multiple sinks -std::shared_ptr create_async(const std::string& logger_name, sinks_init_list sinks, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); -template -std::shared_ptr create_async(const std::string& logger_name, const It& sinks_begin, const It& sinks_end, size_t queue_size, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, const std::function& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function& worker_teardown_cb = nullptr); +std::shared_ptr create_async(const std::string &logger_name, sinks_init_list sinks, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); +template +std::shared_ptr create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end, size_t queue_size, + const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, + const std::function &worker_warmup_cb = nullptr, + const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function &worker_teardown_cb = nullptr); // Register the given logger with the given name void register_logger(std::shared_ptr logger); @@ -153,7 +163,6 @@ void drop(const std::string &name); // Drop all references from the registry void drop_all(); - /////////////////////////////////////////////////////////////////////////////// // // Trace & Debug can be switched on/off at compile time for zero cost debug statements. @@ -168,23 +177,23 @@ void drop_all(); /////////////////////////////////////////////////////////////////////////////// #ifdef SPDLOG_TRACE_ON -# define SPDLOG_STR_H(x) #x -# define SPDLOG_STR_HELPER(x) SPDLOG_STR_H(x) -# ifdef _MSC_VER -# define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ "(" SPDLOG_STR_HELPER(__LINE__) ") ] " __VA_ARGS__) -# else -# define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ ":" SPDLOG_STR_HELPER(__LINE__) " ] " __VA_ARGS__) -# endif +#define SPDLOG_STR_H(x) #x +#define SPDLOG_STR_HELPER(x) SPDLOG_STR_H(x) +#ifdef _MSC_VER +#define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ "(" SPDLOG_STR_HELPER(__LINE__) ") ] " __VA_ARGS__) #else -# define SPDLOG_TRACE(logger, ...) (void)0 +#define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ ":" SPDLOG_STR_HELPER(__LINE__) " ] " __VA_ARGS__) +#endif +#else +#define SPDLOG_TRACE(logger, ...) (void)0 #endif #ifdef SPDLOG_DEBUG_ON -# define SPDLOG_DEBUG(logger, ...) logger->debug(__VA_ARGS__) +#define SPDLOG_DEBUG(logger, ...) logger->debug(__VA_ARGS__) #else -# define SPDLOG_DEBUG(logger, ...) (void)0 +#define SPDLOG_DEBUG(logger, ...) (void)0 #endif -} +} // namespace spdlog #include "details/spdlog_impl.h" diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h index c5509622..50ad3fb4 100644 --- a/include/spdlog/tweakme.h +++ b/include/spdlog/tweakme.h @@ -11,7 +11,6 @@ // /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Under Linux, the much faster CLOCK_REALTIME_COARSE clock can be used. // This clock is less accurate - can be off by dozens of millis - depending on the kernel HZ. @@ -20,7 +19,6 @@ // #define SPDLOG_CLOCK_COARSE /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if date/time logging is not needed and never appear in the log pattern. // This will prevent spdlog from querying the clock on each log call. @@ -31,7 +29,6 @@ // #define SPDLOG_NO_DATETIME /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if thread id logging is not needed (i.e. no %t in the log pattern). // This will prevent spdlog from querying the thread id on each log call. @@ -41,7 +38,6 @@ // #define SPDLOG_NO_THREAD_ID /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // 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. @@ -51,7 +47,6 @@ // #define SPDLOG_DISABLE_TID_CACHING /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if logger name logging is not needed. // This will prevent spdlog from copying the logger name on each log call. @@ -66,7 +61,6 @@ // #define SPDLOG_TRACE_ON /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to avoid locking in the registry operations (spdlog::get(), spdlog::drop() spdlog::register()). // Use only if your code never modifies concurrently the registry. @@ -75,7 +69,6 @@ // #define SPDLOG_NO_REGISTRY_MUTEX /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to avoid spdlog's usage of atomic log levels // Use only if your code never modifies a logger's log levels concurrently by different threads. @@ -83,21 +76,18 @@ // #define SPDLOG_NO_ATOMIC_LEVELS /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable usage of wchar_t for file names on Windows. // // #define SPDLOG_WCHAR_FILENAMES /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to override default eol ("\n" or "\r\n" under Linux/Windows) // // #define SPDLOG_EOL ";-)\n" /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to use your own copy of the fmt library instead of spdlog's copy. // In this case spdlog will try to include so set your -I flag accordingly. @@ -105,7 +95,6 @@ // #define SPDLOG_FMT_EXTERNAL /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to use printf-style messages in your logs instead of the usual // format-style used by default. @@ -113,28 +102,24 @@ // #define SPDLOG_FMT_PRINTF /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable syslog (disabled by default) // // #define SPDLOG_ENABLE_SYSLOG /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable wchar_t support (convert to utf8) // // #define SPDLOG_WCHAR_TO_UTF8_SUPPORT /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to prevent child processes from inheriting log file descriptors // // #define SPDLOG_PREVENT_CHILD_FD /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment if your compiler doesn't support the "final" keyword. // The final keyword allows more optimizations in release @@ -144,7 +129,6 @@ // #define SPDLOG_NO_FINAL /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to enable message counting feature. // Use the %i in the logger pattern to display log message sequence id. @@ -152,7 +136,6 @@ // #define SPDLOG_ENABLE_MESSAGE_COUNTER /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// // Uncomment to customize level names (e.g. "MT TRACE") // diff --git a/tests/errors.cpp b/tests/errors.cpp index c8281d63..1e1826fb 100644 --- a/tests/errors.cpp +++ b/tests/errors.cpp @@ -1,22 +1,18 @@ /* -* This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE -*/ + * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + */ #include "includes.h" -#include +#include - - - -class failing_sink: public spdlog::sinks::sink +class failing_sink : public spdlog::sinks::sink { - void log(const spdlog::details::log_msg& msg) override + void log(const spdlog::details::log_msg &msg) override { throw std::runtime_error("some error happened during log"); } - void flush() override - {} + void flush() override {} }; TEST_CASE("default_error_handler", "[errors]]") @@ -39,21 +35,16 @@ TEST_CASE("default_error_handler", "[errors]]") REQUIRE(count_lines(filename) == 1); } - - - struct custom_ex -{}; +{ +}; TEST_CASE("custom_error_handler", "[errors]]") { prepare_logdir(); std::string filename = "logs/simple_log.txt"; auto logger = spdlog::create("logger", filename, true); logger->flush_on(spdlog::level::info); - logger->set_error_handler([=](const std::string& msg) - { - throw custom_ex(); - }); + logger->set_error_handler([=](const std::string &msg) { throw custom_ex(); }); logger->info("Good message #1"); #if !defined(SPDLOG_FMT_PRINTF) REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex); @@ -68,10 +59,7 @@ TEST_CASE("default_error_handler2", "[errors]]") { auto logger = spdlog::create("failed_logger"); - logger->set_error_handler([=](const std::string& msg) - { - throw custom_ex(); - }); + logger->set_error_handler([=](const std::string &msg) { throw custom_ex(); }); REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex); } @@ -83,10 +71,10 @@ TEST_CASE("async_error_handler", "[errors]]") std::string filename = "logs/simple_async_log.txt"; { auto logger = spdlog::create("logger", filename, true); - logger->set_error_handler([=](const std::string& msg) - { + logger->set_error_handler([=](const std::string &msg) { std::ofstream ofs("logs/custom_err.txt"); - if (!ofs) throw std::runtime_error("Failed open logs/custom_err.txt"); + if (!ofs) + throw std::runtime_error("Failed open logs/custom_err.txt"); ofs << err_msg; }); logger->info("Good message #1"); @@ -96,7 +84,7 @@ TEST_CASE("async_error_handler", "[errors]]") logger->info("Bad format msg %s %s", "xxx"); #endif logger->info("Good message #2"); - spdlog::drop("logger"); //force logger to drain the queue and shutdown + spdlog::drop("logger"); // force logger to drain the queue and shutdown spdlog::set_sync_mode(); } REQUIRE(count_lines(filename) == 2); @@ -111,14 +99,14 @@ TEST_CASE("async_error_handler2", "[errors]]") spdlog::set_async_mode(128); { auto logger = spdlog::create("failed_logger"); - logger->set_error_handler([=](const std::string& msg) - { + logger->set_error_handler([=](const std::string &msg) { std::ofstream ofs("logs/custom_err2.txt"); - if (!ofs) throw std::runtime_error("Failed open logs/custom_err2.txt"); + if (!ofs) + throw std::runtime_error("Failed open logs/custom_err2.txt"); ofs << err_msg; }); logger->info("Hello failure"); - spdlog::drop("failed_logger"); //force logger to drain the queue and shutdown + spdlog::drop("failed_logger"); // force logger to drain the queue and shutdown spdlog::set_sync_mode(); } diff --git a/tests/file_helper.cpp b/tests/file_helper.cpp index f57397eb..931c3f3e 100644 --- a/tests/file_helper.cpp +++ b/tests/file_helper.cpp @@ -1,10 +1,10 @@ /* -* This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE -*/ + * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + */ #include "includes.h" -using spdlog::details::log_msg; using spdlog::details::file_helper; +using spdlog::details::log_msg; static const std::string target_filename = "logs/file_helper_test.txt"; @@ -70,7 +70,7 @@ TEST_CASE("file_helper_reopen2", "[file_helper::reopen(false)]]") REQUIRE(helper.size() == expected_size); } -static void test_split_ext(const char* fname, const char* expect_base, const char* expect_ext) +static void test_split_ext(const char *fname, const char *expect_base, const char *expect_ext) { spdlog::filename_t filename(fname); spdlog::filename_t expected_base(expect_base); diff --git a/tests/file_log.cpp b/tests/file_log.cpp index 086bd5ed..e20071a3 100644 --- a/tests/file_log.cpp +++ b/tests/file_log.cpp @@ -3,7 +3,6 @@ */ #include "includes.h" - TEST_CASE("simple_file_logger", "[simple_logger]]") { prepare_logdir(); @@ -24,7 +23,6 @@ TEST_CASE("simple_file_logger", "[simple_logger]]") REQUIRE(count_lines(filename) == 2); } - TEST_CASE("flush_on", "[flush_on]]") { prepare_logdir(); @@ -69,7 +67,6 @@ TEST_CASE("rotating_file_logger1", "[rotating_logger]]") REQUIRE(count_lines(filename) == 10); } - TEST_CASE("rotating_file_logger2", "[rotating_logger]]") { prepare_logdir(); @@ -96,11 +93,10 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]") REQUIRE(get_filesize(filename1) <= 1024); } - TEST_CASE("daily_logger", "[daily_logger]]") { prepare_logdir(); - //calculate filename (time based) + // calculate filename (time based) std::string basename = "logs/daily_log"; std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -121,15 +117,12 @@ TEST_CASE("daily_logger", "[daily_logger]]") REQUIRE(count_lines(filename) == 10); } - TEST_CASE("daily_logger with dateonly calculator", "[daily_logger_dateonly]]") { - using sink_type = spdlog::sinks::daily_file_sink< - std::mutex, - spdlog::sinks::dateonly_daily_file_name_calculator>; + using sink_type = spdlog::sinks::daily_file_sink; prepare_logdir(); - //calculate filename (time based) + // calculate filename (time based) std::string basename = "logs/daily_dateonly"; std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -151,7 +144,7 @@ TEST_CASE("daily_logger with dateonly calculator", "[daily_logger_dateonly]]") struct custom_daily_file_name_calculator { - static spdlog::filename_t calc_filename(const spdlog::filename_t& basename) + static spdlog::filename_t calc_filename(const spdlog::filename_t &basename) { std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -162,12 +155,10 @@ struct custom_daily_file_name_calculator TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") { - using sink_type = spdlog::sinks::daily_file_sink< - std::mutex, - custom_daily_file_name_calculator>; + using sink_type = spdlog::sinks::daily_file_sink; prepare_logdir(); - //calculate filename (time based) + // calculate filename (time based) std::string basename = "logs/daily_dateonly"; std::tm tm = spdlog::details::os::localtime(); fmt::MemoryWriter w; @@ -188,7 +179,6 @@ TEST_CASE("daily_logger with custom calculator", "[daily_logger_custom]]") REQUIRE(count_lines(filename) == 10); } - /* * File name calculations */ @@ -211,12 +201,8 @@ TEST_CASE("rotating_file_sink::calc_filename3", "[rotating_file_sink]]") REQUIRE(filename == "rotated.txt"); } - - - - // regex supported only from gcc 4.9 and above -#if defined (_MSC_VER) || !(__GNUC__ <= 4 && __GNUC_MINOR__ < 9) +#if defined(_MSC_VER) || !(__GNUC__ <= 4 && __GNUC_MINOR__ < 9) #include TEST_CASE("daily_file_sink::default_daily_file_name_calculator1", "[daily_file_sink]]") { diff --git a/tests/includes.h b/tests/includes.h index 8e70efad..ccc62d16 100644 --- a/tests/includes.h +++ b/tests/includes.h @@ -1,18 +1,17 @@ #pragma once -#include -#include -#include -#include -#include -#include #include "catch.hpp" #include "utils.h" +#include +#include +#include +#include +#include +#include #define SPDLOG_TRACE_ON #define SPDLOG_DEBUG_ON -#include "../include/spdlog/spdlog.h" #include "../include/spdlog/sinks/null_sink.h" #include "../include/spdlog/sinks/ostream_sink.h" - +#include "../include/spdlog/spdlog.h" diff --git a/tests/registry.cpp b/tests/registry.cpp index 1936932a..ff84cacf 100644 --- a/tests/registry.cpp +++ b/tests/registry.cpp @@ -7,23 +7,24 @@ TEST_CASE("register_drop", "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); - REQUIRE(spdlog::get(tested_logger_name)!=nullptr); - //Throw if registring existing name + REQUIRE(spdlog::get(tested_logger_name) != nullptr); + // Throw if registring existing name REQUIRE_THROWS_AS(spdlog::create(tested_logger_name), spdlog::spdlog_ex); } - -TEST_CASE("explicit register" "[registry]") +TEST_CASE("explicit register" + "[registry]") { spdlog::drop_all(); auto logger = std::make_shared(tested_logger_name, std::make_shared()); spdlog::register_logger(logger); REQUIRE(spdlog::get(tested_logger_name) != nullptr); - //Throw if registring existing name + // Throw if registring existing name REQUIRE_THROWS_AS(spdlog::create(tested_logger_name), spdlog::spdlog_ex); } -TEST_CASE("apply_all" "[registry]") +TEST_CASE("apply_all" + "[registry]") { spdlog::drop_all(); auto logger = std::make_shared(tested_logger_name, std::make_shared()); @@ -32,26 +33,20 @@ TEST_CASE("apply_all" "[registry]") spdlog::register_logger(logger2); int counter = 0; - spdlog::apply_all([&counter](std::shared_ptr l) - { - counter++; - }); + spdlog::apply_all([&counter](std::shared_ptr l) { counter++; }); REQUIRE(counter == 2); counter = 0; spdlog::drop(tested_logger_name2); - spdlog::apply_all([&counter](std::shared_ptr l) - { + spdlog::apply_all([&counter](std::shared_ptr l) { REQUIRE(l->name() == tested_logger_name); counter++; - } - ); + }); REQUIRE(counter == 1); } - - -TEST_CASE("drop" "[registry]") +TEST_CASE("drop" + "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); @@ -59,7 +54,8 @@ TEST_CASE("drop" "[registry]") REQUIRE_FALSE(spdlog::get(tested_logger_name)); } -TEST_CASE("drop_all" "[registry]") +TEST_CASE("drop_all" + "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); @@ -69,8 +65,8 @@ TEST_CASE("drop_all" "[registry]") REQUIRE_FALSE(spdlog::get(tested_logger_name)); } - -TEST_CASE("drop non existing" "[registry]") +TEST_CASE("drop non existing" + "[registry]") { spdlog::drop_all(); spdlog::create(tested_logger_name); @@ -79,6 +75,3 @@ TEST_CASE("drop non existing" "[registry]") REQUIRE(spdlog::get(tested_logger_name)); spdlog::drop_all(); } - - - diff --git a/tests/test_macros.cpp b/tests/test_macros.cpp index 8ad7bd41..e3e66c4a 100644 --- a/tests/test_macros.cpp +++ b/tests/test_macros.cpp @@ -1,6 +1,6 @@ /* -* This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE -*/ + * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE + */ #include "includes.h" @@ -14,7 +14,7 @@ TEST_CASE("debug and trace w/o format string", "[macros]]") logger->set_level(spdlog::level::trace); SPDLOG_TRACE(logger, "Test message 1"); - //SPDLOG_DEBUG(logger, "Test message 2"); + // SPDLOG_DEBUG(logger, "Test message 2"); SPDLOG_DEBUG(logger, "Test message 2"); logger->flush(); @@ -22,7 +22,6 @@ TEST_CASE("debug and trace w/o format string", "[macros]]") REQUIRE(count_lines(filename) == 2); } - TEST_CASE("debug and trace with format strings", "[macros]]") { prepare_logdir(); @@ -34,11 +33,11 @@ TEST_CASE("debug and trace with format strings", "[macros]]") #if !defined(SPDLOG_FMT_PRINTF) SPDLOG_TRACE(logger, "Test message {}", 1); - //SPDLOG_DEBUG(logger, "Test message 2"); + // SPDLOG_DEBUG(logger, "Test message 2"); SPDLOG_DEBUG(logger, "Test message {}", 222); #else SPDLOG_TRACE(logger, "Test message %d", 1); - //SPDLOG_DEBUG(logger, "Test message 2"); + // SPDLOG_DEBUG(logger, "Test message 2"); SPDLOG_DEBUG(logger, "Test message %d", 222); #endif @@ -47,4 +46,3 @@ TEST_CASE("debug and trace with format strings", "[macros]]") REQUIRE(ends_with(file_contents(filename), "Test message 222\n")); REQUIRE(count_lines(filename) == 2); } - diff --git a/tests/test_pattern_formatter.cpp b/tests/test_pattern_formatter.cpp index 51b0f35d..5c2be1f2 100644 --- a/tests/test_pattern_formatter.cpp +++ b/tests/test_pattern_formatter.cpp @@ -1,13 +1,14 @@ #include "includes.h" // log to str and return it -static std::string log_to_str(const std::string& msg, const std::shared_ptr& formatter = nullptr) +static std::string log_to_str(const std::string &msg, const std::shared_ptr &formatter = nullptr) { std::ostringstream oss; auto oss_sink = std::make_shared(oss); spdlog::logger oss_logger("pattern_tester", oss_sink); oss_logger.set_level(spdlog::level::info); - if (formatter) oss_logger.set_formatter(formatter); + if (formatter) + oss_logger.set_formatter(formatter); oss_logger.info(msg); return oss.str(); } @@ -56,6 +57,7 @@ TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") auto formatter = std::make_shared("%D %v", spdlog::pattern_time_type::local, "\n"); auto now_tm = spdlog::details::os::localtime(); std::stringstream oss; - oss << std::setfill('0') << std::setw(2) << now_tm.tm_mon + 1 << "/" << std::setw(2) << now_tm.tm_mday << "/" << std::setw(2) << (now_tm.tm_year + 1900) % 1000 << " Some message\n"; + oss << std::setfill('0') << std::setw(2) << now_tm.tm_mon + 1 << "/" << std::setw(2) << now_tm.tm_mday << "/" << std::setw(2) + << (now_tm.tm_year + 1900) % 1000 << " Some message\n"; REQUIRE(log_to_str("Some message", formatter) == oss.str()); } diff --git a/tests/utils.cpp b/tests/utils.cpp index e179147b..2c50ce36 100644 --- a/tests/utils.cpp +++ b/tests/utils.cpp @@ -1,6 +1,5 @@ #include "includes.h" - void prepare_logdir() { spdlog::drop_all(); @@ -14,18 +13,15 @@ void prepare_logdir() #endif } - -std::string file_contents(const std::string& filename) +std::string file_contents(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) throw std::runtime_error("Failed open file "); - return std::string((std::istreambuf_iterator(ifs)), - (std::istreambuf_iterator())); - + return std::string((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); } -std::size_t count_lines(const std::string& filename) +std::size_t count_lines(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) @@ -33,12 +29,12 @@ std::size_t count_lines(const std::string& filename) std::string line; size_t counter = 0; - while(std::getline(ifs, line)) + while (std::getline(ifs, line)) counter++; return counter; } -std::size_t get_filesize(const std::string& filename) +std::size_t get_filesize(const std::string &filename) { std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary); if (!ifs) @@ -47,10 +43,10 @@ std::size_t get_filesize(const std::string& filename) return static_cast(ifs.tellg()); } - // source: https://stackoverflow.com/a/2072890/192001 -bool ends_with(std::string const & value, std::string const & ending) +bool ends_with(std::string const &value, std::string const &ending) { - if (ending.size() > value.size()) return false; + if (ending.size() > value.size()) + return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } diff --git a/tests/utils.h b/tests/utils.h index 819bcee6..e788b507 100644 --- a/tests/utils.h +++ b/tests/utils.h @@ -1,16 +1,16 @@ #pragma once +#include #include -#include -std::size_t count_lines(const std::string& filename); +std::size_t count_lines(const std::string &filename); void prepare_logdir(); -std::string file_contents(const std::string& filename); +std::string file_contents(const std::string &filename); -std::size_t count_lines(const std::string& filename); +std::size_t count_lines(const std::string &filename); -std::size_t get_filesize(const std::string& filename); +std::size_t get_filesize(const std::string &filename); -bool ends_with(std::string const & value, std::string const & ending); \ No newline at end of file +bool ends_with(std::string const &value, std::string const &ending); \ No newline at end of file