diff --git a/3d_party/spd_log/include/spdlog/async_logger.h b/3d_party/spd_log/include/spdlog/async_logger.h index e9fcd5f40f265dd6f88322cefa0bf56fc9ab997a..09e324a3b5e1acd43dc21461dd2f655e948936a4 100644 --- a/3d_party/spd_log/include/spdlog/async_logger.h +++ b/3d_party/spd_log/include/spdlog/async_logger.h @@ -23,17 +23,14 @@ #include <string> #include <memory> -namespace spdlog -{ +namespace spdlog { -namespace details -{ +namespace details { class async_log_helper; } -class async_logger SPDLOG_FINAL :public logger -{ -public: +class async_logger SPDLOG_FINAL : public logger { + public: template<class It> async_logger(const std::string& name, const It& begin, @@ -68,12 +65,12 @@ public: virtual void set_error_handler(log_err_handler) override; virtual log_err_handler error_handler() override; -protected: + protected: 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; -private: + private: std::unique_ptr<details::async_log_helper> _async_log_helper; }; } diff --git a/3d_party/spd_log/include/spdlog/common.h b/3d_party/spd_log/include/spdlog/common.h index ea0b056707d32f71b681ffa7a16314edafc483c2..72af2fbe58d616cbf46b6340d5103c93646b360f 100644 --- a/3d_party/spd_log/include/spdlog/common.h +++ b/3d_party/spd_log/include/spdlog/common.h @@ -46,13 +46,11 @@ #include "fmt/fmt.h" -namespace spdlog -{ +namespace spdlog { class formatter; -namespace sinks -{ +namespace sinks { class sink; } @@ -66,13 +64,11 @@ using level_t = details::null_atomic_int; using level_t = std::atomic<int>; #endif -using log_err_handler = std::function<void(const std::string &err_msg)>; +using log_err_handler = std::function<void(const std::string& err_msg)>; //Log level enum -namespace level -{ -typedef enum -{ +namespace level { +typedef enum { trace = 0, debug = 1, info = 2, @@ -89,13 +85,11 @@ static const char* level_names[] SPDLOG_LEVEL_NAMES; static const char* short_level_names[] { "T", "D", "I", "W", "E", "C", "O" }; -inline const char* to_str(spdlog::level::level_enum l) -{ +inline const char* to_str(spdlog::level::level_enum l) { return level_names[l]; } -inline const char* to_short_str(spdlog::level::level_enum l) -{ +inline const char* to_short_str(spdlog::level::level_enum l) { return short_level_names[l]; } } //level @@ -104,8 +98,7 @@ inline const char* to_short_str(spdlog::level::level_enum l) // // Async overflow policy - block by default. // -enum class async_overflow_policy -{ +enum class async_overflow_policy { block_retry, // Block / yield / sleep until message can be enqueued discard_log_msg // Discard the message it enqueue fails }; @@ -114,8 +107,7 @@ enum class async_overflow_policy // Pattern time - specific time getting to use for pattern_formatter. // local time by default // -enum class pattern_time_type -{ +enum class pattern_time_type { local, // log localtime utc // log utc }; @@ -123,27 +115,22 @@ enum class pattern_time_type // // Log exception // -namespace details -{ -namespace os -{ +namespace details { +namespace os { std::string errno_str(int err_num); } } -class spdlog_ex: public std::exception -{ -public: - spdlog_ex(const std::string& msg):_msg(msg) - {} - spdlog_ex(const std::string& msg, int last_errno) - { +class spdlog_ex: public std::exception { + public: + spdlog_ex(const std::string& msg): _msg(msg) { + } + spdlog_ex(const std::string& msg, int last_errno) { _msg = msg + ": " + details::os::errno_str(last_errno); } - const char* what() const SPDLOG_NOEXCEPT override - { + const char* what() const SPDLOG_NOEXCEPT override { return _msg.c_str(); } -private: + private: std::string _msg; }; diff --git a/3d_party/spd_log/include/spdlog/details/async_log_helper.h b/3d_party/spd_log/include/spdlog/details/async_log_helper.h index bba9bc0eb0d6152fc03005ab3c994f67a8e5a0f6..877262a5f360b1d97c7fa0fbb62fa5096ddb3a98 100644 --- a/3d_party/spd_log/include/spdlog/details/async_log_helper.h +++ b/3d_party/spd_log/include/spdlog/details/async_log_helper.h @@ -28,23 +28,18 @@ #include <utility> #include <vector> -namespace spdlog -{ -namespace details -{ +namespace spdlog { +namespace details { -class async_log_helper -{ +class async_log_helper { // Async msg to move to/from the queue // Movable only. should never be copied - enum class async_msg_type - { + enum class async_msg_type { log, flush, terminate }; - struct async_msg - { + struct async_msg { std::string logger_name; level::level_enum level; log_clock::time_point time; @@ -64,18 +59,17 @@ async_msg(async_msg&& other) SPDLOG_NOEXCEPT: thread_id(other.thread_id), txt(std::move(other.txt)), msg_type(std::move(other.msg_type)), - msg_id(other.msg_id) - {} + msg_id(other.msg_id) { + } async_msg(async_msg_type m_type): level(level::info), thread_id(0), msg_type(m_type), - msg_id(0) - {} + msg_id(0) { + } - 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; time = std::move(other.time); @@ -97,8 +91,7 @@ async_msg(async_msg&& other) SPDLOG_NOEXCEPT: thread_id(m.thread_id), txt(m.raw.data(), m.raw.size()), msg_type(async_msg_type::log), - msg_id(m.msg_id) - { + msg_id(m.msg_id) { #ifndef SPDLOG_NO_NAME logger_name = *m.logger_name; #endif @@ -106,8 +99,7 @@ async_msg(async_msg&& other) SPDLOG_NOEXCEPT: // copy into log_msg - void fill_log_msg(log_msg &msg) - { + void fill_log_msg(log_msg& msg) { msg.logger_name = &logger_name; msg.level = level; msg.time = time; @@ -117,7 +109,7 @@ async_msg(async_msg&& other) SPDLOG_NOEXCEPT: } }; -public: + public: using item_type = async_msg; using q_type = details::mpmc_bounded_queue<item_type>; @@ -145,7 +137,7 @@ public: void set_error_handler(spdlog::log_err_handler err_handler); -private: + private: formatter_ptr _formatter; std::vector<std::shared_ptr<sinks::sink>> _sinks; @@ -217,71 +209,54 @@ inline spdlog::details::async_log_helper::async_log_helper( _worker_warmup_cb(worker_warmup_cb), _flush_interval_ms(flush_interval_ms), _worker_teardown_cb(worker_teardown_cb), - _worker_thread(&async_log_helper::worker_loop, this) -{} + _worker_thread(&async_log_helper::worker_loop, this) { +} // Send to the worker thread termination message(level=off) // and wait for it to finish gracefully -inline spdlog::details::async_log_helper::~async_log_helper() -{ - try - { +inline spdlog::details::async_log_helper::~async_log_helper() { + try { push_msg(async_msg(async_msg_type::terminate)); _worker_thread.join(); - } - catch (...) // don't crash in destructor - { + } catch (...) { // don't crash in destructor } } //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) -{ +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) -{ - if (!_q.enqueue(std::move(new_msg)) && _overflow_policy != async_overflow_policy::discard_log_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) { auto last_op_time = details::os::now(); auto now = last_op_time; - do - { + do { 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))); } } // optionally wait for the queue be empty and request flush from the sinks -inline void spdlog::details::async_log_helper::flush(bool wait_for_q) -{ +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 } -inline void spdlog::details::async_log_helper::worker_loop() -{ +inline void spdlog::details::async_log_helper::worker_loop() { if (_worker_warmup_cb) _worker_warmup_cb(); auto last_pop = details::os::now(); auto last_flush = last_pop; auto active = true; - while (active) - { - try - { + while (active) { + try { active = process_next_msg(last_pop, last_flush); - } - catch (const std::exception &ex) - { + } catch (const std::exception& ex) { _err_handler(ex.what()); - } - catch(...) - { + } catch(...) { _err_handler("Unknown exeption in async logger worker loop."); } } @@ -292,15 +267,13 @@ inline void spdlog::details::async_log_helper::worker_loop() // 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; - if (_q.dequeue(incoming_async_msg)) - { + if (_q.dequeue(incoming_async_msg)) { last_pop = details::os::now(); - switch (incoming_async_msg.msg_type) - { + switch (incoming_async_msg.msg_type) { case async_msg_type::flush: _flush_requested = true; break; @@ -314,10 +287,8 @@ inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_ log_msg incoming_log_msg; incoming_async_msg.fill_log_msg(incoming_log_msg); _formatter->format(incoming_log_msg); - for (auto &s : _sinks) - { - if (s->should_log(incoming_log_msg.level)) - { + for (auto& s : _sinks) { + if (s->should_log(incoming_log_msg.level)) { s->log(incoming_log_msg); } } @@ -327,8 +298,7 @@ inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_ // Handle empty queue.. // This is the only place where the queue can terminate or flush to avoid losing messages already in the queue - else - { + else { auto now = details::os::now(); handle_flush_interval(now, last_flush); sleep_or_yield(now, last_pop); @@ -337,27 +307,26 @@ 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) -{ - 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) +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); + if (should_flush) { + for (auto& s : _sinks) s->flush(); now = last_flush = details::os::now(); _flush_requested = false; } } -inline void spdlog::details::async_log_helper::set_formatter(formatter_ptr msg_formatter) -{ +inline void spdlog::details::async_log_helper::set_formatter(formatter_ptr msg_formatter) { _formatter = msg_formatter; } // 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; @@ -380,17 +349,14 @@ inline void spdlog::details::async_log_helper::sleep_or_yield(const spdlog::log_ } // wait for the queue to be empty -inline void spdlog::details::async_log_helper::wait_empty_q() -{ +inline void spdlog::details::async_log_helper::wait_empty_q() { auto last_op = details::os::now(); - while (!_q.is_empty()) - { + while (!_q.is_empty()) { sleep_or_yield(details::os::now(), last_op); } } -inline void spdlog::details::async_log_helper::set_error_handler(spdlog::log_err_handler err_handler) -{ +inline void spdlog::details::async_log_helper::set_error_handler(spdlog::log_err_handler err_handler) { _err_handler = err_handler; } diff --git a/3d_party/spd_log/include/spdlog/details/async_logger_impl.h b/3d_party/spd_log/include/spdlog/details/async_logger_impl.h index 8373211767fe889befb6e60b89ece589cb200b1b..36d3eff937bb0482c31c3c191982a6fede596e16 100644 --- a/3d_party/spd_log/include/spdlog/details/async_logger_impl.h +++ b/3d_party/spd_log/include/spdlog/details/async_logger_impl.h @@ -18,88 +18,77 @@ template<class It> 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<void()>& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function<void()>& worker_teardown_cb) : + const It& begin, + const It& end, + size_t queue_size, + const async_overflow_policy overflow_policy, + const std::function<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, + const std::function<void()>& 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)) -{ + _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<void()>& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function<void()>& 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) {} + sinks_init_list sinks_list, + size_t queue_size, + const async_overflow_policy overflow_policy, + const std::function<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, + const std::function<void()>& 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<void()>& worker_warmup_cb, - const std::chrono::milliseconds& flush_interval_ms, - const std::function<void()>& worker_teardown_cb) : - async_logger(logger_name, -{ + sink_ptr single_sink, + size_t queue_size, + const async_overflow_policy overflow_policy, + const std::function<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, + const std::function<void()>& worker_teardown_cb) : + async_logger(logger_name, { single_sink }, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {} -inline void spdlog::async_logger::flush() -{ +inline void spdlog::async_logger::flush() { _async_log_helper->flush(true); } // Error handler -inline void spdlog::async_logger::set_error_handler(spdlog::log_err_handler err_handler) -{ +inline void spdlog::async_logger::set_error_handler(spdlog::log_err_handler err_handler) { _err_handler = err_handler; _async_log_helper->set_error_handler(err_handler); } -inline spdlog::log_err_handler spdlog::async_logger::error_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) -{ +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_formatter>(pattern, pattern_time); _async_log_helper->set_formatter(_formatter); } -inline void spdlog::async_logger::_sink_it(details::log_msg& msg) -{ - try - { +inline void spdlog::async_logger::_sink_it(details::log_msg& msg) { + try { #if defined(SPDLOG_ENABLE_MESSAGE_COUNTER) _incr_msg_counter(msg); #endif _async_log_helper->log(msg); if (_should_flush_on(msg)) _async_log_helper->flush(false); // do async flush - } - catch (const std::exception &ex) - { + } catch (const std::exception& ex) { _err_handler(ex.what()); - } - catch(...) - { + } catch(...) { _err_handler("Unknown exception in logger " + _name); throw; } diff --git a/3d_party/spd_log/include/spdlog/details/file_helper.h b/3d_party/spd_log/include/spdlog/details/file_helper.h index dff788ffc287677587dff93752a4ed1b4f087b8b..eaeae558eaf1ab1ef1041215253fc8ea1c8cb89b 100644 --- a/3d_party/spd_log/include/spdlog/details/file_helper.h +++ b/3d_party/spd_log/include/spdlog/details/file_helper.h @@ -19,39 +19,33 @@ #include <tuple> #include <cerrno> -namespace spdlog -{ -namespace details -{ +namespace spdlog { +namespace details { -class file_helper -{ +class file_helper { -public: + public: const int open_tries = 5; const int open_interval = 10; explicit file_helper() : - _fd(nullptr) - {} + _fd(nullptr) { + } file_helper(const file_helper&) = delete; file_helper& operator=(const file_helper&) = delete; - ~file_helper() - { + ~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"); + auto* mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab"); _filename = fname; - for (int tries = 0; tries < open_tries; ++tries) - { + for (int tries = 0; tries < open_tries; ++tries) { if (!os::fopen_s(&_fd, fname, mode)) return; @@ -61,50 +55,42 @@ public: throw spdlog_ex("Failed opening file " + os::filename_to_str(_filename) + " for writing", errno); } - void reopen(bool truncate) - { + void reopen(bool truncate) { if (_filename.empty()) throw spdlog_ex("Failed re opening file - was not opened before"); open(_filename, truncate); } - void flush() - { + void flush() { std::fflush(_fd); } - void close() - { - if (_fd) - { + void close() { + if (_fd) { std::fclose(_fd); _fd = nullptr; } } - void write(const log_msg& msg) - { + void write(const log_msg& msg) { size_t msg_size = msg.formatted.size(); auto data = msg.formatted.data(); if (std::fwrite(data, 1, msg_size, _fd) != msg_size) throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno); } - size_t size() const - { + size_t size() const { if (!_fd) throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename)); 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); } @@ -121,8 +107,7 @@ public: // ".mylog" => (".mylog". "") // "my_folder/.mylog" => ("my_folder/.mylog", "") // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt") - static std::tuple<filename_t, filename_t> split_by_extenstion(const spdlog::filename_t& fname) - { + static std::tuple<filename_t, filename_t> split_by_extenstion(const spdlog::filename_t& fname) { auto ext_index = fname.rfind('.'); // no valid extension found - return whole path and empty string as extension @@ -137,7 +122,7 @@ public: // finally - return a valid base and extension tuple return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index)); } -private: + private: FILE* _fd; filename_t _filename; }; diff --git a/3d_party/spd_log/include/spdlog/details/log_msg.h b/3d_party/spd_log/include/spdlog/details/log_msg.h index a9fe920116da05520c99f5135d3b6b9521d010cc..82dab0cae843dc61e6e85d156ca77a06d1c21981 100644 --- a/3d_party/spd_log/include/spdlog/details/log_msg.h +++ b/3d_party/spd_log/include/spdlog/details/log_msg.h @@ -12,18 +12,14 @@ #include <string> #include <utility> -namespace spdlog -{ -namespace details -{ -struct log_msg -{ +namespace spdlog { +namespace details { +struct log_msg { log_msg() = default; - log_msg(const std::string *loggers_name, level::level_enum lvl) : + log_msg(const std::string* loggers_name, level::level_enum lvl) : logger_name(loggers_name), level(lvl), - msg_id(0) - { + msg_id(0) { #ifndef SPDLOG_NO_DATETIME time = os::now(); #endif @@ -38,7 +34,7 @@ struct log_msg log_msg(log_msg&& other) = delete; - const std::string *logger_name; + const std::string* logger_name; level::level_enum level; log_clock::time_point time; size_t thread_id; diff --git a/3d_party/spd_log/include/spdlog/details/logger_impl.h b/3d_party/spd_log/include/spdlog/details/logger_impl.h index 880447471a111cbb9c0f8d895bdbebe81c6d6824..7bfe446b9001b4b443981de106f04c60224bae9d 100644 --- a/3d_party/spd_log/include/spdlog/details/logger_impl.h +++ b/3d_party/spd_log/include/spdlog/details/logger_impl.h @@ -21,49 +21,42 @@ inline spdlog::logger::logger(const std::string& logger_name, const It& begin, c _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) - { + _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); }; } // 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()) -{} + 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, -{ + logger(logger_name, { single_sink -}) -{} +}) { +} inline spdlog::logger::~logger() = default; -inline void spdlog::logger::set_formatter(spdlog::formatter_ptr msg_formatter) -{ +inline void spdlog::logger::set_formatter(spdlog::formatter_ptr msg_formatter) { _set_formatter(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 <typename... Args> -inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Args&... args) -{ +inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Args& ... args) { if (!should_log(lvl)) return; - try - { + try { details::log_msg log_msg(&_name, lvl); #if defined(SPDLOG_FMT_PRINTF) @@ -72,55 +65,39 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Ar log_msg.raw.write(fmt, args...); #endif _sink_it(log_msg); - } - catch (const std::exception &ex) - { + } catch (const std::exception& ex) { _err_handler(ex.what()); - } - catch(...) - { + } catch(...) { _err_handler("Unknown exception in logger " + _name); throw; } } template <typename... Args> -inline void spdlog::logger::log(level::level_enum lvl, const char* msg) -{ +inline void spdlog::logger::log(level::level_enum lvl, const char* msg) { if (!should_log(lvl)) return; - try - { + try { details::log_msg log_msg(&_name, lvl); log_msg.raw << msg; _sink_it(log_msg); - } - catch (const std::exception &ex) - { + } catch (const std::exception& ex) { _err_handler(ex.what()); - } - catch (...) - { + } catch (...) { _err_handler("Unknown exception in logger " + _name); throw; } } template<typename T> -inline void spdlog::logger::log(level::level_enum lvl, const T& msg) -{ +inline void spdlog::logger::log(level::level_enum lvl, const T& msg) { if (!should_log(lvl)) return; - try - { + try { details::log_msg log_msg(&_name, lvl); log_msg.raw << msg; _sink_it(log_msg); - } - catch (const std::exception &ex) - { + } catch (const std::exception& ex) { _err_handler(ex.what()); - } - catch (...) - { + } catch (...) { _err_handler("Unknown exception in logger " + _name); throw; } @@ -128,77 +105,65 @@ inline void spdlog::logger::log(level::level_enum lvl, const T& msg) template <typename Arg1, typename... Args> -inline void spdlog::logger::trace(const char* fmt, const Arg1 &arg1, const Args&... args) -{ +inline void spdlog::logger::trace(const char* fmt, const Arg1& arg1, const Args& ... args) { log(level::trace, fmt, arg1, args...); } template <typename Arg1, typename... Args> -inline void spdlog::logger::debug(const char* fmt, const Arg1 &arg1, const Args&... args) -{ +inline void spdlog::logger::debug(const char* fmt, const Arg1& arg1, const Args& ... args) { log(level::debug, fmt, arg1, args...); } template <typename Arg1, typename... Args> -inline void spdlog::logger::info(const char* fmt, const Arg1 &arg1, const Args&... args) -{ +inline void spdlog::logger::info(const char* fmt, const Arg1& arg1, const Args& ... args) { log(level::info, fmt, arg1, args...); } template <typename Arg1, typename... Args> -inline void spdlog::logger::warn(const char* fmt, const Arg1 &arg1, const Args&... args) -{ +inline void spdlog::logger::warn(const char* fmt, const Arg1& arg1, const Args& ... args) { log(level::warn, fmt, arg1, args...); } template <typename Arg1, typename... Args> -inline void spdlog::logger::error(const char* fmt, const Arg1 &arg1, const Args&... args) -{ +inline void spdlog::logger::error(const char* fmt, const Arg1& arg1, const Args& ... args) { log(level::err, fmt, arg1, args...); } template <typename Arg1, typename... Args> -inline void spdlog::logger::critical(const char* fmt, const Arg1 &arg1, const Args&... args) -{ +inline void spdlog::logger::critical(const char* fmt, const Arg1& arg1, const Args& ... args) { log(level::critical, fmt, arg1, args...); } template<typename T> -inline void spdlog::logger::trace(const T& msg) -{ +inline void spdlog::logger::trace(const T& msg) { log(level::trace, msg); } template<typename T> -inline void spdlog::logger::debug(const T& msg) -{ +inline void spdlog::logger::debug(const T& msg) { log(level::debug, msg); } template<typename T> -inline void spdlog::logger::info(const T& msg) -{ +inline void spdlog::logger::info(const T& msg) { log(level::info, msg); } template<typename T> -inline void spdlog::logger::warn(const T& msg) -{ +inline void spdlog::logger::warn(const T& msg) { log(level::warn, msg); } template<typename T> -inline void spdlog::logger::error(const T& msg) -{ +inline void spdlog::logger::error(const T& msg) { log(level::err, msg); } template<typename T> -inline void spdlog::logger::critical(const T& msg) -{ +inline void spdlog::logger::critical(const T& msg) { log(level::critical, msg); } @@ -209,16 +174,14 @@ inline void spdlog::logger::critical(const T& msg) #include <locale> template <typename... Args> -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* msg) -{ +inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* msg) { std::wstring_convert<std::codecvt_utf8<wchar_t> > conv; log(lvl, conv.to_bytes(msg)); } template <typename... Args> -inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const Args&... args) -{ +inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const Args& ... args) { fmt::WMemoryWriter wWriter; wWriter.write(fmt, args...); @@ -226,39 +189,33 @@ inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const } template <typename... Args> -inline void spdlog::logger::trace(const wchar_t* fmt, const Args&... args) -{ +inline void spdlog::logger::trace(const wchar_t* fmt, const Args& ... args) { log(level::trace, fmt, args...); } template <typename... Args> -inline void spdlog::logger::debug(const wchar_t* fmt, const Args&... args) -{ +inline void spdlog::logger::debug(const wchar_t* fmt, const Args& ... args) { log(level::debug, fmt, args...); } template <typename... Args> -inline void spdlog::logger::info(const wchar_t* fmt, const Args&... args) -{ +inline void spdlog::logger::info(const wchar_t* fmt, const Args& ... args) { log(level::info, fmt, args...); } template <typename... Args> -inline void spdlog::logger::warn(const wchar_t* fmt, const Args&... args) -{ +inline void spdlog::logger::warn(const wchar_t* fmt, const Args& ... args) { log(level::warn, fmt, args...); } template <typename... Args> -inline void spdlog::logger::error(const wchar_t* fmt, const Args&... args) -{ +inline void spdlog::logger::error(const wchar_t* fmt, const Args& ... args) { log(level::err, fmt, args...); } template <typename... Args> -inline void spdlog::logger::critical(const wchar_t* fmt, const Args&... args) -{ +inline void spdlog::logger::critical(const wchar_t* fmt, const Args& ... args) { log(level::critical, fmt, args...); } @@ -269,55 +226,45 @@ inline void spdlog::logger::critical(const wchar_t* fmt, const Args&... args) // // name and level // -inline const std::string& spdlog::logger::name() const -{ +inline const std::string& spdlog::logger::name() const { return _name; } -inline void spdlog::logger::set_level(spdlog::level::level_enum log_level) -{ +inline void spdlog::logger::set_level(spdlog::level::level_enum log_level) { _level.store(log_level); } -inline void spdlog::logger::set_error_handler(spdlog::log_err_handler err_handler) -{ +inline void spdlog::logger::set_error_handler(spdlog::log_err_handler err_handler) { _err_handler = err_handler; } -inline spdlog::log_err_handler spdlog::logger::error_handler() -{ +inline spdlog::log_err_handler spdlog::logger::error_handler() { return _err_handler; } -inline void spdlog::logger::flush_on(level::level_enum log_level) -{ +inline void spdlog::logger::flush_on(level::level_enum log_level) { _flush_level.store(log_level); } -inline spdlog::level::level_enum spdlog::logger::level() const -{ +inline spdlog::level::level_enum spdlog::logger::level() const { return static_cast<spdlog::level::level_enum>(_level.load(std::memory_order_relaxed)); } -inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) const -{ +inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) const { return msg_level >= _level.load(std::memory_order_relaxed); } // // 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); #endif _formatter->format(msg); - for (auto &sink : _sinks) - { - if( sink->should_log( msg.level)) - { + for (auto& sink : _sinks) { + if( sink->should_log( msg.level)) { sink->log(msg); } } @@ -326,23 +273,19 @@ inline void spdlog::logger::_sink_it(details::log_msg& 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_formatter>(pattern, pattern_time); } -inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter) -{ +inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter) { _formatter = msg_formatter; } -inline void spdlog::logger::flush() -{ +inline void spdlog::logger::flush() { for (auto& sink : _sinks) sink->flush(); } -inline void spdlog::logger::_default_err_handler(const std::string &msg) -{ +inline void spdlog::logger::_default_err_handler(const std::string& msg) { auto now = time(nullptr); if (now - _last_err_time < 60) return; @@ -355,19 +298,16 @@ inline void spdlog::logger::_default_err_handler(const std::string &msg) _last_err_time = now; } -inline bool spdlog::logger::_should_flush_on(const details::log_msg &msg) -{ +inline bool spdlog::logger::_should_flush_on(const details::log_msg& msg) { const auto flush_level = _flush_level.load(std::memory_order_relaxed); return (msg.level >= flush_level) && (msg.level != level::off); } -inline void spdlog::logger::_incr_msg_counter(details::log_msg &msg) -{ +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::sink_ptr>& spdlog::logger::sinks() const -{ +inline const std::vector<spdlog::sink_ptr>& spdlog::logger::sinks() const { return _sinks; } diff --git a/3d_party/spd_log/include/spdlog/details/mpmc_bounded_q.h b/3d_party/spd_log/include/spdlog/details/mpmc_bounded_q.h index 102df855545ade7820ec2b59f38533bc338a0c3e..451aada2fcd6b24119d9a73fb5b69a56ae793ecd 100644 --- a/3d_party/spd_log/include/spdlog/details/mpmc_bounded_q.h +++ b/3d_party/spd_log/include/spdlog/details/mpmc_bounded_q.h @@ -48,22 +48,18 @@ Distributed under the MIT License (http://opensource.org/licenses/MIT) #include <atomic> #include <utility> -namespace spdlog -{ -namespace details -{ +namespace spdlog { +namespace details { template<typename T> -class mpmc_bounded_queue -{ -public: +class mpmc_bounded_queue { + public: using item_type = T; 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 if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0))) throw spdlog_ex("async logger queue size must be power of two"); @@ -74,32 +70,24 @@ public: dequeue_pos_.store(0, std::memory_order_relaxed); } - ~mpmc_bounded_queue() - { + ~mpmc_bounded_queue() { delete[] buffer_; } - bool enqueue(T&& data) - { + bool enqueue(T&& data) { cell_t* cell; size_t pos = enqueue_pos_.load(std::memory_order_relaxed); - for (;;) - { + for (;;) { cell = &buffer_[pos & buffer_mask_]; size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = static_cast<intptr_t>(seq) - static_cast<intptr_t>(pos); - if (dif == 0) - { + if (dif == 0) { if (enqueue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) break; - } - else if (dif < 0) - { + } else if (dif < 0) { return false; - } - else - { + } else { pos = enqueue_pos_.load(std::memory_order_relaxed); } } @@ -108,22 +96,18 @@ public: return true; } - bool dequeue(T& data) - { + bool dequeue(T& data) { cell_t* cell; size_t pos = dequeue_pos_.load(std::memory_order_relaxed); - for (;;) - { + for (;;) { cell = &buffer_[pos & buffer_mask_]; size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = static_cast<intptr_t>(seq) - static_cast<intptr_t>(pos + 1); - if (dif == 0) - { + if (dif == 0) { if (dequeue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) break; - } - else if (dif < 0) + } else if (dif < 0) return false; else pos = dequeue_pos_.load(std::memory_order_relaxed); @@ -133,23 +117,19 @@ public: return true; } - bool is_empty() - { + bool is_empty() { size_t front, front1, back; // try to take a consistent snapshot of front/tail. - do - { + do { 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 - { + private: + struct cell_t { std::atomic<size_t> sequence_; T data_; }; diff --git a/3d_party/spd_log/include/spdlog/details/null_mutex.h b/3d_party/spd_log/include/spdlog/details/null_mutex.h index 67b0aeee004c3120d33d54e546a18854ac4d0ecc..1235ba5258395574690ad9ba3bb7dd4c6a72db20 100644 --- a/3d_party/spd_log/include/spdlog/details/null_mutex.h +++ b/3d_party/spd_log/include/spdlog/details/null_mutex.h @@ -8,35 +8,28 @@ #include <atomic> // null, no cost dummy "mutex" and dummy "atomic" int -namespace spdlog -{ -namespace details -{ -struct null_mutex -{ +namespace spdlog { +namespace details { +struct null_mutex { void lock() {} void unlock() {} - bool try_lock() - { + bool try_lock() { return true; } }; -struct null_atomic_int -{ +struct null_atomic_int { int value; null_atomic_int() = default; - null_atomic_int(int val):value(val) - {} + null_atomic_int(int val): value(val) { + } - int load(std::memory_order) const - { + int load(std::memory_order) const { return value; } - void store(int val) - { + void store(int val) { value = val; } }; diff --git a/3d_party/spd_log/include/spdlog/details/os.h b/3d_party/spd_log/include/spdlog/details/os.h index b881cae45fd113eeabcc5f31b29ae89daf827a4b..74d2aa7c9a71f26ab14e4f483857f750671baf1c 100644 --- a/3d_party/spd_log/include/spdlog/details/os.h +++ b/3d_party/spd_log/include/spdlog/details/os.h @@ -54,15 +54,11 @@ #endif -namespace spdlog -{ -namespace details -{ -namespace os -{ +namespace spdlog { +namespace details { +namespace os { -inline spdlog::log_clock::time_point now() -{ +inline spdlog::log_clock::time_point now() { #if defined __linux__ && defined SPDLOG_CLOCK_COARSE timespec ts; @@ -77,8 +73,7 @@ inline spdlog::log_clock::time_point now() #endif } -inline std::tm localtime(const std::time_t &time_tt) -{ +inline std::tm localtime(const std::time_t& time_tt) { #ifdef _WIN32 std::tm tm; @@ -90,15 +85,13 @@ inline std::tm localtime(const std::time_t &time_tt) return tm; } -inline std::tm localtime() -{ +inline std::tm localtime() { std::time_t now_t = time(nullptr); return localtime(now_t); } -inline std::tm gmtime(const std::time_t &time_tt) -{ +inline std::tm gmtime(const std::time_t& time_tt) { #ifdef _WIN32 std::tm tm; @@ -110,13 +103,11 @@ inline std::tm gmtime(const std::time_t &time_tt) return tm; } -inline std::tm gmtime() -{ +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 && @@ -126,8 +117,7 @@ inline bool operator==(const std::tm& tm1, const std::tm& tm2) 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); } @@ -153,8 +143,7 @@ SPDLOG_CONSTEXPR static const char folder_sep = '/'; #endif -inline void prevent_child_fd(FILE *f) -{ +inline void prevent_child_fd(FILE* f) { #ifdef _WIN32 auto file_handle = (HANDLE)_get_osfhandle(_fileno(f)); if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0)) @@ -168,8 +157,7 @@ inline void prevent_child_fd(FILE *f) //fopen_s on non windows for writing -inline int fopen_s(FILE** fp, const filename_t& filename, const filename_t& mode) -{ +inline int fopen_s(FILE** fp, const filename_t& filename, const filename_t& mode) { #ifdef _WIN32 #ifdef SPDLOG_WCHAR_FILENAMES *fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYWR); @@ -188,8 +176,7 @@ inline int fopen_s(FILE** fp, const filename_t& filename, const filename_t& mode } -inline int remove(const filename_t &filename) -{ +inline int remove(const filename_t& filename) { #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES) return _wremove(filename.c_str()); #else @@ -197,8 +184,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()); #else @@ -208,8 +194,7 @@ inline int rename(const filename_t& filename1, const filename_t& filename2) //Return if file exists -inline bool file_exists(const filename_t& filename) -{ +inline bool file_exists(const filename_t& filename) { #ifdef _WIN32 #ifdef SPDLOG_WCHAR_FILENAMES auto attribs = GetFileAttributesW(filename.c_str()); @@ -227,8 +212,7 @@ inline bool file_exists(const filename_t& filename) //Return file size according to open FILE* object -inline size_t filesize(FILE *f) -{ +inline size_t filesize(FILE* f) { if (f == nullptr) throw spdlog_ex("Failed getting file size. fd is null"); #if defined ( _WIN32) && !defined(__CYGWIN__) @@ -264,8 +248,7 @@ inline size_t filesize(FILE *f) //Return utc offset in minutes or throw spdlog_ex on failure -inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) -{ +inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) { #ifdef _WIN32 #if _WIN32_WINNT < _WIN32_WINNT_WS08 @@ -288,10 +271,9 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) #if defined(sun) || defined(__sun) // '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()) - { + struct helper { + 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); @@ -327,8 +309,7 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime()) //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() -{ +inline size_t _thread_id() { #ifdef _WIN32 return static_cast<size_t>(::GetCurrentThreadId()); #elif __linux__ @@ -350,8 +331,7 @@ inline size_t _thread_id() } //Return current thread id as size_t (from thread local storage) -inline size_t thread_id() -{ +inline size_t thread_id() { #if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || (defined(__clang__) && !__has_feature(cxx_thread_local)) return _thread_id(); #else // cache thread id in tls @@ -365,8 +345,7 @@ inline size_t thread_id() // 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) -{ +inline void sleep_for_millis(int milliseconds) { #if defined(_WIN32) Sleep(milliseconds); #else @@ -377,39 +356,31 @@ 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) -{ +inline std::string filename_to_str(const filename_t& filename) { std::wstring_convert<std::codecvt_utf8<wchar_t>, 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); } -inline std::string errno_to_string(char buf[256], int res) -{ - if (res == 0) - { +inline std::string errno_to_string(char buf[256], int res) { + if (res == 0) { return std::string(buf); - } - else - { + } else { return "Unknown error"; } } // Return errno string (thread safe) -inline std::string errno_str(int err_num) -{ +inline std::string errno_str(int err_num) { char buf[256]; SPDLOG_CONSTEXPR auto buf_size = sizeof(buf); @@ -433,8 +404,7 @@ inline std::string errno_str(int err_num) #endif } -inline int pid() -{ +inline int pid() { #ifdef _WIN32 return ::_getpid(); @@ -447,26 +417,22 @@ inline int pid() // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ -inline bool is_color_terminal() -{ +inline bool is_color_terminal() { #ifdef _WIN32 return true; #else - static constexpr const char* Terms[] = - { + 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) - { + const char* env_p = std::getenv("TERM"); + if (env_p == nullptr) { return false; } static const bool result = std::any_of( - std::begin(Terms), std::end(Terms), [&](const char* term) - { + std::begin(Terms), std::end(Terms), [&](const char* term) { return std::strstr(env_p, term) != nullptr; }); return result; @@ -476,8 +442,7 @@ inline bool is_color_terminal() // 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 return _isatty(_fileno(file)) ? true : false; diff --git a/3d_party/spd_log/include/spdlog/details/pattern_formatter_impl.h b/3d_party/spd_log/include/spdlog/details/pattern_formatter_impl.h index a73f5deabbbca1ccf7fe402ae04f5f3dee7628e2..d1760524c9a528ffc6a1089f699a7081464dba71 100644 --- a/3d_party/spd_log/include/spdlog/details/pattern_formatter_impl.h +++ b/3d_party/spd_log/include/spdlog/details/pattern_formatter_impl.h @@ -20,46 +20,36 @@ #include <vector> #include <array> -namespace spdlog -{ -namespace details -{ -class flag_formatter -{ -public: - virtual ~flag_formatter() - {} +namespace spdlog { +namespace details { +class flag_formatter { + public: + virtual ~flag_formatter() { + } virtual void format(details::log_msg& msg, const std::tm& tm_time) = 0; }; /////////////////////////////////////////////////////////////////////// // name & level pattern appenders /////////////////////////////////////////////////////////////////////// -namespace -{ -class name_formatter:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +namespace { +class name_formatter: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { msg.formatted << *msg.logger_name; } }; } // log level appender -class level_formatter:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class level_formatter: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { msg.formatted << level::to_str(msg.level); } }; // short log level appender -class short_level_formatter:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class short_level_formatter: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { msg.formatted << level::to_short_str(msg.level); } }; @@ -68,77 +58,63 @@ 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" }; -class a_formatter:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class a_formatter: public flag_formatter { + 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" }; -class A_formatter:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class A_formatter: public flag_formatter { + 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" }; -class b_formatter:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class b_formatter: public flag_formatter { + 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" }; -class B_formatter:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class B_formatter: public flag_formatter { + 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) -{ +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) -{ +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) -class c_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class c_formatter SPDLOG_FINAL: public flag_formatter { + 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; } @@ -146,10 +122,8 @@ 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 - { +class C_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << fmt::pad(tm_time.tm_year % 100, 2, '0'); } }; @@ -157,83 +131,65 @@ 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 - { +class D_formatter SPDLOG_FINAL: public flag_formatter { + 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, '/'); } }; // year - 4 digit -class Y_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class Y_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << tm_time.tm_year + 1900; } }; // month 1-12 -class m_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class m_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << fmt::pad(tm_time.tm_mon + 1, 2, '0'); } }; // 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 - { +class d_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << fmt::pad(tm_time.tm_mday, 2, '0'); } }; // 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 - { +class H_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << fmt::pad(tm_time.tm_hour, 2, '0'); } }; // 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 - { +class I_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << fmt::pad(to12h(tm_time), 2, '0'); } }; // minutes 0-59 -class M_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class M_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << fmt::pad(tm_time.tm_min, 2, '0'); } }; // seconds 0-59 -class S_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm& tm_time) override - { +class S_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << fmt::pad(tm_time.tm_sec, 2, '0'); } }; // milliseconds -class e_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class e_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { auto duration = msg.time.time_since_epoch(); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000; msg.formatted << fmt::pad(static_cast<int>(millis), 3, '0'); @@ -241,10 +197,8 @@ 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 - { +class f_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { auto duration = msg.time.time_since_epoch(); auto micros = std::chrono::duration_cast<std::chrono::microseconds>(duration).count() % 1000000; msg.formatted << fmt::pad(static_cast<int>(micros), 6, '0'); @@ -252,20 +206,16 @@ 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 - { +class F_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { auto duration = msg.time.time_since_epoch(); auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count() % 1000000000; msg.formatted << fmt::pad(static_cast<int>(ns), 9, '0'); } }; -class E_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class E_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { auto duration = msg.time.time_since_epoch(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); msg.formatted << seconds; @@ -273,55 +223,45 @@ 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 - { +class p_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { msg.formatted << ampm(tm_time); } }; // 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 - { +class r_formatter SPDLOG_FINAL: public flag_formatter { + 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); } }; // 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 - { +class R_formatter SPDLOG_FINAL: public flag_formatter { + 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, ':'); } }; // 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 - { +class T_formatter SPDLOG_FINAL: public flag_formatter { + 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, ':'); } }; // ISO 8601 offset from UTC in timezone (+-HH:MM) -class z_formatter SPDLOG_FINAL:public flag_formatter -{ -public: +class z_formatter SPDLOG_FINAL: public flag_formatter { + public: const std::chrono::seconds cache_refresh = std::chrono::seconds(5); - z_formatter():_last_update(std::chrono::seconds(0)), _offset_minutes(0) - {} + z_formatter(): _last_update(std::chrono::seconds(0)), _offset_minutes(0) { + } 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); #else @@ -331,13 +271,10 @@ public: #endif bool is_negative = total_minutes < 0; char sign; - if (is_negative) - { + if (is_negative) { total_minutes = -total_minutes; sign = '-'; - } - else - { + } else { sign = '+'; } @@ -346,17 +283,15 @@ public: msg.formatted << sign; pad_n_join(msg.formatted, h, m, ':'); } -private: + private: log_clock::time_point _last_update; int _offset_minutes; 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) { using namespace std::chrono; std::lock_guard<std::mutex> l(_mutex); - if (msg.time - _last_update >= cache_refresh) - { + if (msg.time - _last_update >= cache_refresh) { _offset_minutes = os::utc_minutes_offset(tm_time); _last_update = msg.time; } @@ -367,78 +302,63 @@ private: // Thread id -class t_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class t_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { msg.formatted << msg.thread_id; } }; // Current pid -class pid_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class pid_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { msg.formatted << details::os::pid(); } }; // message counter formatter -class i_formatter SPDLOG_FINAL :public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class i_formatter SPDLOG_FINAL : public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { msg.formatted << fmt::pad(msg.msg_id, 6, '0'); } }; -class v_formatter SPDLOG_FINAL:public flag_formatter -{ - void format(details::log_msg& msg, const std::tm&) override - { +class v_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm&) override { msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size()); } }; -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 - { +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 { msg.formatted << _ch; } -private: + private: char _ch; }; //aggregate user chars to display as is -class aggregate_formatter SPDLOG_FINAL:public flag_formatter -{ -public: - aggregate_formatter() - {} - void add_ch(char ch) - { +class aggregate_formatter SPDLOG_FINAL: public flag_formatter { + public: + aggregate_formatter() { + } + void add_ch(char ch) { _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: + private: std::string _str; }; // Full info formatter // 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 - { +class full_formatter SPDLOG_FINAL: public flag_formatter { + void format(details::log_msg& msg, const std::tm& tm_time) override { #ifndef SPDLOG_NO_DATETIME auto duration = msg.time.time_since_epoch(); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000; @@ -488,19 +408,15 @@ class full_formatter SPDLOG_FINAL:public flag_formatter // pattern_formatter inline impl /////////////////////////////////////////////////////////////////////////////// inline spdlog::pattern_formatter::pattern_formatter(const std::string& pattern, pattern_time_type pattern_time) - : _pattern_time(pattern_time) -{ + : _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<details::aggregate_formatter> user_chars; - for (auto it = pattern.begin(); it != end; ++it) - { - if (*it == '%') - { + for (auto it = pattern.begin(); it != end; ++it) { + if (*it == '%') { if (user_chars) //append user chars found so far _formatters.push_back(std::move(user_chars)); @@ -508,24 +424,19 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter handle_flag(*it); else break; - } - else // chars not following the % sign should be displayed as is - { + } else { // chars not following the % sign should be displayed as is if (!user_chars) user_chars = std::unique_ptr<details::aggregate_formatter>(new details::aggregate_formatter()); 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) -{ - switch (flag) - { +inline void spdlog::pattern_formatter::handle_flag(char flag) { + switch (flag) { // logger name case 'n': _formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::name_formatter())); @@ -661,24 +572,21 @@ inline void spdlog::pattern_formatter::handle_flag(char flag) } } -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) return details::os::localtime(log_clock::to_time_t(msg.time)); else 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 auto tm_time = get_time(msg); #else std::tm tm_time; #endif - for (auto &f : _formatters) - { + for (auto& f : _formatters) { f->format(msg, tm_time); } //write eol diff --git a/3d_party/spd_log/include/spdlog/details/registry.h b/3d_party/spd_log/include/spdlog/details/registry.h index b68b9f5a33c228be4a449adeebcf7818371cc1b9..1c04385e7cb4675c417ab16852cfbf7ddae69ba4 100644 --- a/3d_party/spd_log/include/spdlog/details/registry.h +++ b/3d_party/spd_log/include/spdlog/details/registry.h @@ -22,16 +22,12 @@ #include <string> #include <unordered_map> -namespace spdlog -{ -namespace details -{ -template <class Mutex> class registry_t -{ -public: - - void register_logger(std::shared_ptr<logger> logger) - { +namespace spdlog { +namespace details { +template <class Mutex> class registry_t { + public: + + void register_logger(std::shared_ptr<logger> logger) { std::lock_guard<Mutex> lock(_mutex); auto logger_name = logger->name(); throw_if_exists(logger_name); @@ -39,21 +35,20 @@ public: } - std::shared_ptr<logger> get(const std::string& logger_name) - { + std::shared_ptr<logger> get(const std::string& logger_name) { std::lock_guard<Mutex> lock(_mutex); auto found = _loggers.find(logger_name); return found == _loggers.end() ? nullptr : found->second; } template<class It> - std::shared_ptr<logger> create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end) - { + std::shared_ptr<logger> create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end) { std::lock_guard<Mutex> lock(_mutex); throw_if_exists(logger_name); std::shared_ptr<logger> new_logger; if (_async_mode) - new_logger = std::make_shared<async_logger>(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<async_logger>(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>(logger_name, sinks_begin, sinks_end); @@ -73,11 +68,14 @@ public: } template<class It> - std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb, const It& sinks_begin, const It& sinks_end) - { + std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb, + const It& sinks_begin, const It& sinks_end) { std::lock_guard<Mutex> lock(_mutex); throw_if_exists(logger_name); - auto new_logger = std::make_shared<async_logger>(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<async_logger>(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); @@ -93,85 +91,80 @@ public: return new_logger; } - void apply_all(std::function<void(std::shared_ptr<logger>)> fun) - { + void apply_all(std::function<void(std::shared_ptr<logger>)> fun) { std::lock_guard<Mutex> lock(_mutex); - for (auto &l : _loggers) + for (auto& l : _loggers) fun(l.second); } - void drop(const std::string& logger_name) - { + void drop(const std::string& logger_name) { std::lock_guard<Mutex> lock(_mutex); _loggers.erase(logger_name); } - void drop_all() - { + void drop_all() { std::lock_guard<Mutex> lock(_mutex); _loggers.clear(); } - std::shared_ptr<logger> create(const std::string& logger_name, sinks_init_list sinks) - { + std::shared_ptr<logger> create(const std::string& logger_name, sinks_init_list sinks) { return create(logger_name, sinks.begin(), sinks.end()); } - std::shared_ptr<logger> create(const std::string& logger_name, sink_ptr sink) - { + std::shared_ptr<logger> create(const std::string& logger_name, sink_ptr sink) { return create(logger_name, { sink }); } - std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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()); + std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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()); } - std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb, sink_ptr sink) - { + std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, + const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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 }); } - void formatter(formatter_ptr f) - { + void formatter(formatter_ptr f) { std::lock_guard<Mutex> lock(_mutex); _formatter = f; 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<Mutex> lock(_mutex); _formatter = std::make_shared<pattern_formatter>(pattern); for (auto& l : _loggers) l.second->set_formatter(_formatter); } - void set_level(level::level_enum log_level) - { + void set_level(level::level_enum log_level) { std::lock_guard<Mutex> lock(_mutex); for (auto& l : _loggers) l.second->set_level(log_level); _level = log_level; } - void flush_on(level::level_enum log_level) - { + void flush_on(level::level_enum log_level) { std::lock_guard<Mutex> lock(_mutex); for (auto& l : _loggers) l.second->flush_on(log_level); _flush_level = log_level; } - void set_error_handler(log_err_handler handler) - { + void set_error_handler(log_err_handler handler) { 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<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb) - { + void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, + const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, + const std::function<void()>& worker_teardown_cb) { std::lock_guard<Mutex> lock(_mutex); _async_mode = true; _async_q_size = q_size; @@ -181,25 +174,22 @@ public: _worker_teardown_cb = worker_teardown_cb; } - void set_sync_mode() - { + void set_sync_mode() { std::lock_guard<Mutex> lock(_mutex); _async_mode = false; } - static registry_t<Mutex>& instance() - { + static registry_t<Mutex>& instance() { static registry_t<Mutex> s_instance; return s_instance; } -private: + private: registry_t<Mutex>() {} registry_t<Mutex>(const registry_t<Mutex>&) = delete; registry_t<Mutex>& operator=(const registry_t<Mutex>&) = delete; - void throw_if_exists(const std::string &logger_name) - { + void throw_if_exists(const std::string& logger_name) { if (_loggers.find(logger_name) != _loggers.end()) throw spdlog_ex("logger with name '" + logger_name + "' already exists"); } diff --git a/3d_party/spd_log/include/spdlog/details/spdlog_impl.h b/3d_party/spd_log/include/spdlog/details/spdlog_impl.h index 25c7b7e9a8ecef64e378ba4ceb05032e79117069..fa6cf9f7be795c60d8cfbdb3dbac1def83273f2e 100644 --- a/3d_party/spd_log/include/spdlog/details/spdlog_impl.h +++ b/3d_party/spd_log/include/spdlog/details/spdlog_impl.h @@ -32,51 +32,48 @@ #include <memory> #include <string> -inline void spdlog::register_logger(std::shared_ptr<logger> logger) -{ +inline void spdlog::register_logger(std::shared_ptr<logger> logger) { return details::registry::instance().register_logger(logger); } -inline std::shared_ptr<spdlog::logger> spdlog::get(const std::string& name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::get(const std::string& name) { return details::registry::instance().get(name); } -inline void spdlog::drop(const std::string &name) -{ +inline void spdlog::drop(const std::string& name) { details::registry::instance().drop(name); } // Create multi/single threaded simple file logger -inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate) -{ +inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_mt(const std::string& logger_name, + const filename_t& filename, bool truncate) { return create<spdlog::sinks::simple_file_sink_mt>(logger_name, filename, truncate); } -inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate) -{ +inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_st(const std::string& logger_name, + const filename_t& filename, bool truncate) { return create<spdlog::sinks::simple_file_sink_st>(logger_name, filename, truncate); } // Create multi/single threaded rotating file logger -inline std::shared_ptr<spdlog::logger> 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::logger> spdlog::rotating_logger_mt(const std::string& logger_name, + const filename_t& filename, size_t max_file_size, size_t max_files) { return create<spdlog::sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files); } -inline std::shared_ptr<spdlog::logger> 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::logger> spdlog::rotating_logger_st(const std::string& logger_name, + const filename_t& filename, size_t max_file_size, size_t max_files) { return create<spdlog::sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files); } // Create file logger which creates new file at midnight): -inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour, int minute) -{ +inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_mt(const std::string& logger_name, + const filename_t& filename, int hour, int minute) { return create<spdlog::sinks::daily_file_sink_mt>(logger_name, filename, hour, minute); } -inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour, int minute) -{ +inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_st(const std::string& logger_name, + const filename_t& filename, int hour, int minute) { return create<spdlog::sinks::daily_file_sink_st>(logger_name, filename, hour, minute); } @@ -84,23 +81,19 @@ inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_st(const std::string // // stdout/stderr loggers // -inline std::shared_ptr<spdlog::logger> spdlog::stdout_logger_mt(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> 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::logger> spdlog::stdout_logger_st(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> 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::logger> spdlog::stderr_logger_mt(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> 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::logger> spdlog::stderr_logger_st(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_st(const std::string& logger_name) { return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stderr_sink_st::instance()); } @@ -108,53 +101,45 @@ inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_st(const std::strin // stdout/stderr color loggers // #ifdef _WIN32 -inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_st>(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::wincolor_stderr_sink_mt>(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::wincolor_stderr_sink_st>(); return spdlog::details::registry::instance().create(logger_name, sink); } #else //ansi terminal colors -inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_st>(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::ansicolor_stderr_sink_mt>(); return spdlog::details::registry::instance().create(logger_name, sink); } -inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string& logger_name) -{ +inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string& logger_name) { auto sink = std::make_shared<spdlog::sinks::ansicolor_stderr_sink_st>(); return spdlog::details::registry::instance().create(logger_name, sink); } @@ -162,107 +147,104 @@ inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string #ifdef SPDLOG_ENABLE_SYSLOG // Create syslog logger -inline std::shared_ptr<spdlog::logger> spdlog::syslog_logger(const std::string& logger_name, const std::string& syslog_ident, int syslog_option, int syslog_facility) -{ +inline std::shared_ptr<spdlog::logger> spdlog::syslog_logger(const std::string& logger_name, + const std::string& syslog_ident, int syslog_option, int syslog_facility) { return create<spdlog::sinks::syslog_sink>(logger_name, syslog_ident, syslog_option, syslog_facility); } #endif #ifdef __ANDROID__ -inline std::shared_ptr<spdlog::logger> spdlog::android_logger(const std::string& logger_name, const std::string& tag) -{ +inline std::shared_ptr<spdlog::logger> spdlog::android_logger(const std::string& logger_name, const std::string& tag) { return create<spdlog::sinks::android_sink>(logger_name, tag); } #endif // Create and register a logger a single sink -inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, const spdlog::sink_ptr& sink) -{ +inline std::shared_ptr<spdlog::logger> 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::logger> spdlog::create(const std::string& logger_name, spdlog::sinks_init_list sinks) -{ +inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, spdlog::sinks_init_list sinks) { return details::registry::instance().create(logger_name, sinks); } template <typename Sink, typename... Args> -inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, Args... args) -{ +inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, Args... args) { sink_ptr sink = std::make_shared<Sink>(args...); return details::registry::instance().create(logger_name, { sink }); } template<class It> -inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end) -{ +inline std::shared_ptr<spdlog::logger> 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::logger> 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<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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); +inline std::shared_ptr<spdlog::logger> 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<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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); } // Create and register an async logger with multiple sinks -inline std::shared_ptr<spdlog::logger> 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<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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); +inline std::shared_ptr<spdlog::logger> 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<void()>& worker_warmup_cb, + const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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); } template<class It> -inline std::shared_ptr<spdlog::logger> 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<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& 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); +inline std::shared_ptr<spdlog::logger> 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<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, + const std::function<void()>& 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); } -inline void spdlog::set_formatter(spdlog::formatter_ptr f) -{ +inline void spdlog::set_formatter(spdlog::formatter_ptr f) { details::registry::instance().formatter(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); } -inline void spdlog::set_level(level::level_enum log_level) -{ +inline void spdlog::set_level(level::level_enum log_level) { return details::registry::instance().set_level(log_level); } -inline void spdlog::flush_on(level::level_enum log_level) -{ +inline void spdlog::flush_on(level::level_enum log_level) { return details::registry::instance().flush_on(log_level); } -inline void spdlog::set_error_handler(log_err_handler handler) -{ +inline void spdlog::set_error_handler(log_err_handler handler) { return details::registry::instance().set_error_handler(handler); } -inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb) -{ - details::registry::instance().set_async_mode(queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); +inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, + const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, + const std::function<void()>& worker_teardown_cb) { + details::registry::instance().set_async_mode(queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, + worker_teardown_cb); } -inline void spdlog::set_sync_mode() -{ +inline void spdlog::set_sync_mode() { details::registry::instance().set_sync_mode(); } -inline void spdlog::apply_all(std::function<void(std::shared_ptr<logger>)> fun) -{ +inline void spdlog::apply_all(std::function<void(std::shared_ptr<logger>)> fun) { details::registry::instance().apply_all(fun); } -inline void spdlog::drop_all() -{ +inline void spdlog::drop_all() { details::registry::instance().drop_all(); } diff --git a/3d_party/spd_log/include/spdlog/fmt/bundled/format.h b/3d_party/spd_log/include/spdlog/fmt/bundled/format.h index 91f434813e9865b5a272a6f30b7caf1d41821247..1e5319fd2c741103c9d7ffa275f0a10298a7b339 100644 --- a/3d_party/spd_log/include/spdlog/fmt/bundled/format.h +++ b/3d_party/spd_log/include/spdlog/fmt/bundled/format.h @@ -303,13 +303,10 @@ typedef __int64 intmax_t; #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED) # include <intrin.h> // _BitScanReverse, _BitScanReverse64 -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { # pragma intrinsic(_BitScanReverse) -inline uint32_t clz(uint32_t x) -{ +inline uint32_t clz(uint32_t x) { unsigned long r = 0; _BitScanReverse(&r, x); @@ -326,8 +323,7 @@ inline uint32_t clz(uint32_t x) # pragma intrinsic(_BitScanReverse64) # endif -inline uint32_t clzll(uint64_t x) -{ +inline uint32_t clzll(uint64_t x) { unsigned long r = 0; # ifdef _WIN64 _BitScanReverse64(&r, x); @@ -352,15 +348,11 @@ inline uint32_t clzll(uint64_t x) } #endif -namespace fmt -{ -namespace internal -{ -struct DummyInt -{ +namespace fmt { +namespace internal { +struct DummyInt { int data[2]; - operator int() const - { + operator int() const { return 0; } }; @@ -368,62 +360,51 @@ typedef std::numeric_limits<fmt::internal::DummyInt> FPUtil; // Dummy implementations of system functions such as signbit and ecvt called // if the latter are not available. -inline DummyInt signbit(...) -{ +inline DummyInt signbit(...) { return DummyInt(); } -inline DummyInt _ecvt_s(...) -{ +inline DummyInt _ecvt_s(...) { return DummyInt(); } -inline DummyInt isinf(...) -{ +inline DummyInt isinf(...) { return DummyInt(); } -inline DummyInt _finite(...) -{ +inline DummyInt _finite(...) { return DummyInt(); } -inline DummyInt isnan(...) -{ +inline DummyInt isnan(...) { return DummyInt(); } -inline DummyInt _isnan(...) -{ +inline DummyInt _isnan(...) { return DummyInt(); } // A helper function to suppress bogus "conditional expression is constant" // warnings. template <typename T> -inline T const_check(T value) -{ +inline T const_check(T value) { return value; } } } // namespace fmt -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<fmt::internal::DummyInt> : - public std::numeric_limits<int> -{ -public: + public std::numeric_limits<int> { + public: // Portable version of isinf. template <typename T> - static bool isinfinity(T x) - { + 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))) - { + sizeof(isinf(x)) == sizeof(int))) { return isinf(x) != 0; } return !_finite(static_cast<double>(x)); @@ -431,24 +412,20 @@ public: // Portable version of isnan. template <typename T> - static bool isnotanumber(T x) - { + static bool isnotanumber(T x) { using namespace fmt::internal; if (const_check(sizeof(isnan(x)) == sizeof(bool) || - sizeof(isnan(x)) == sizeof(int))) - { + sizeof(isnan(x)) == sizeof(int))) { return isnan(x) != 0; } return _isnan(static_cast<double>(x)) != 0; } // Portable version of signbit. - static bool isnegative(double x) - { + static bool isnegative(double x) { using namespace fmt::internal; if (const_check(sizeof(signbit(x)) == sizeof(bool) || - sizeof(signbit(x)) == sizeof(int))) - { + sizeof(signbit(x)) == sizeof(int))) { return signbit(x) != 0; } if (x < 0) return true; @@ -461,8 +438,7 @@ public: }; } // namespace std -namespace fmt -{ +namespace fmt { // Fix the warning about long long on older versions of GCC // that don't support the diagnostic pragma. @@ -517,15 +493,14 @@ class BasicFormatter; \endrst */ template <typename Char> -class BasicStringRef -{ -private: - const Char *data_; +class BasicStringRef { + private: + const Char* data_; std::size_t size_; -public: + 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 @@ -533,7 +508,7 @@ public: the size with ``std::char_traits<Char>::length``. \endrst */ - BasicStringRef(const Char *s) + BasicStringRef(const Char* s) : data_(s), size_(std::char_traits<Char>::length(s)) {} /** @@ -543,7 +518,7 @@ public: */ template <typename Allocator> BasicStringRef( - const std::basic_string<Char, std::char_traits<Char>, Allocator> &s) + const std::basic_string<Char, std::char_traits<Char>, Allocator>& s) : data_(s.c_str()), size_(s.size()) {} /** @@ -551,26 +526,22 @@ public: Converts a string reference to an ``std::string`` object. \endrst */ - std::basic_string<Char> to_string() const - { + std::basic_string<Char> to_string() const { return std::basic_string<Char>(data_, size_); } /** Returns a pointer to the string data. */ - const Char *data() const - { + const Char* data() const { return data_; } /** Returns the string size. */ - std::size_t size() const - { + std::size_t size() const { return size_; } // Lexicographically compare this string reference to other. - int compare(BasicStringRef other) const - { + int compare(BasicStringRef other) const { std::size_t size = size_ < other.size_ ? size_ : other.size_; int result = std::char_traits<Char>::compare(data_, other.data_, size); if (result == 0) @@ -578,28 +549,22 @@ public: return result; } - friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) - { + friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) == 0; } - friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) - { + friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) != 0; } - friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) - { + friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) < 0; } - friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) - { + friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) <= 0; } - friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) - { + friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) > 0; } - friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) - { + friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) >= 0; } }; @@ -633,14 +598,13 @@ typedef BasicStringRef<wchar_t> WStringRef; \endrst */ template <typename Char> -class BasicCStringRef -{ -private: - const Char *data_; +class BasicCStringRef { + private: + const Char* data_; -public: + public: /** Constructs a string reference object from a C string. */ - BasicCStringRef(const Char *s) : data_(s) {} + BasicCStringRef(const Char* s) : data_(s) {} /** \rst @@ -649,12 +613,11 @@ public: */ template <typename Allocator> BasicCStringRef( - const std::basic_string<Char, std::char_traits<Char>, Allocator> &s) + const std::basic_string<Char, std::char_traits<Char>, Allocator>& s) : data_(s.c_str()) {} /** Returns the pointer to a C string. */ - const Char *c_str() const - { + const Char* c_str() const { return data_; } }; @@ -663,22 +626,19 @@ typedef BasicCStringRef<char> CStringRef; typedef BasicCStringRef<wchar_t> WCStringRef; /** A formatting error such as invalid format string. */ -class FormatError : public std::runtime_error -{ -public: +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) {} + FormatError(const FormatError& ferr) : std::runtime_error(ferr) {} FMT_API ~FormatError() FMT_DTOR_NOEXCEPT; }; -namespace internal -{ +namespace internal { // MakeUnsigned<T>::Type gives an unsigned type corresponding to integer type T. template <typename T> -struct MakeUnsigned -{ +struct MakeUnsigned { typedef T Type; }; @@ -695,8 +655,7 @@ FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); // Casts nonnegative integer to unsigned. template <typename Int> -inline typename MakeUnsigned<Int>::Type to_unsigned(Int value) -{ +inline typename MakeUnsigned<Int>::Type to_unsigned(Int value) { FMT_ASSERT(value >= 0, "negative value"); return static_cast<typename MakeUnsigned<Int>::Type>(value); } @@ -708,14 +667,12 @@ enum { INLINE_BUFFER_SIZE = 500 }; #if FMT_SECURE_SCL // Use checked iterator to avoid warnings on MSVC. template <typename T> -inline stdext::checked_array_iterator<T*> make_ptr(T *ptr, std::size_t size) -{ +inline stdext::checked_array_iterator<T*> make_ptr(T* ptr, std::size_t size) { return stdext::checked_array_iterator<T*>(ptr, size); } #else template <typename T> -inline T *make_ptr(T *ptr, std::size_t) -{ +inline T* make_ptr(T* ptr, std::size_t) { return ptr; } #endif @@ -727,17 +684,16 @@ inline T *make_ptr(T *ptr, std::size_t) \endrst */ template <typename T> -class Buffer -{ -private: +class Buffer { + private: FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); -protected: - T *ptr_; + protected: + T* ptr_; std::size_t size_; std::size_t capacity_; - Buffer(T *ptr = FMT_NULL, std::size_t capacity = 0) + Buffer(T* ptr = FMT_NULL, std::size_t capacity = 0) : ptr_(ptr), size_(0), capacity_(capacity) {} /** @@ -748,26 +704,23 @@ protected: */ virtual void grow(std::size_t size) = 0; -public: + public: virtual ~Buffer() {} /** Returns the size of this buffer. */ - std::size_t size() const - { + std::size_t size() const { return size_; } /** Returns the capacity of this buffer. */ - std::size_t capacity() const - { + std::size_t capacity() const { return capacity_; } /** Resizes the buffer. If T is a POD type new elements may not be initialized. */ - void resize(std::size_t new_size) - { + void resize(std::size_t new_size) { if (new_size > capacity_) grow(new_size); size_ = new_size; @@ -778,16 +731,14 @@ public: Reserves space to store at least *capacity* elements. \endrst */ - void reserve(std::size_t capacity) - { + void reserve(std::size_t capacity) { if (capacity > capacity_) grow(capacity); } void clear() FMT_NOEXCEPT { size_ = 0; } - void push_back(const T &value) - { + void push_back(const T& value) { if (size_ == capacity_) grow(size_ + 1); ptr_[size_++] = value; @@ -795,22 +746,19 @@ public: /** Appends data to the end of the buffer. */ template <typename U> - void append(const U *begin, const U *end); + void append(const U* begin, const U* end); - T &operator[](std::size_t index) - { + T& operator[](std::size_t index) { return ptr_[index]; } - const T &operator[](std::size_t index) const - { + const T& operator[](std::size_t index) const { return ptr_[index]; } }; template <typename T> template <typename U> -void Buffer<T>::append(const U *begin, const U *end) -{ +void Buffer<T>::append(const U* begin, const U* end) { FMT_ASSERT(end >= begin, "negative value"); std::size_t new_size = size_ + (end - begin); if (new_size > capacity_) @@ -820,51 +768,43 @@ void Buffer<T>::append(const U *begin, const U *end) 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 <typename T, std::size_t SIZE, typename Allocator = std::allocator<T> > -class MemoryBuffer : private Allocator, public Buffer<T> -{ -private: +class MemoryBuffer : private Allocator, public Buffer<T> { + private: T data_[SIZE]; // Deallocate memory allocated by the buffer. - void deallocate() - { + void deallocate() { if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_); } -protected: + protected: void grow(std::size_t size) FMT_OVERRIDE; -public: - explicit MemoryBuffer(const Allocator &alloc = Allocator()) + public: + explicit MemoryBuffer(const Allocator& alloc = Allocator()) : Allocator(alloc), Buffer<T>(data_, SIZE) {} - ~MemoryBuffer() - { + ~MemoryBuffer() { deallocate(); } #if FMT_USE_RVALUE_REFERENCES -private: + private: // Move data from other to this buffer. - void move(MemoryBuffer &other) - { - Allocator &this_alloc = *this, &other_alloc = other; + void move(MemoryBuffer& other) { + Allocator& this_alloc = *this, &other_alloc = other; this_alloc = std::move(other_alloc); this->size_ = other.size_; this->capacity_ = other.capacity_; - if (other.ptr_ == other.data_) - { + if (other.ptr_ == other.data_) { this->ptr_ = data_; std::uninitialized_copy(other.data_, other.data_ + this->size_, make_ptr(data_, this->capacity_)); - } - else - { + } else { this->ptr_ = other.ptr_; // Set pointer to the inline array so that delete is not called // when deallocating. @@ -872,14 +812,12 @@ private: } } -public: - MemoryBuffer(MemoryBuffer &&other) - { + public: + MemoryBuffer(MemoryBuffer&& other) { move(other); } - MemoryBuffer &operator=(MemoryBuffer &&other) - { + MemoryBuffer& operator=(MemoryBuffer&& other) { assert(this != &other); deallocate(); move(other); @@ -888,24 +826,22 @@ public: #endif // Returns a copy of the allocator associated with this buffer. - Allocator get_allocator() const - { + Allocator get_allocator() const { return *this; } }; template <typename T, std::size_t SIZE, typename Allocator> -void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) -{ +void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) { std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; if (size > new_capacity) new_capacity = size; - T *new_ptr = this->allocate(new_capacity, FMT_NULL); + T* new_ptr = this->allocate(new_capacity, FMT_NULL); // 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::size_t old_capacity = this->capacity_; - T *old_ptr = this->ptr_; + T* old_ptr = this->ptr_; this->capacity_ = new_capacity; this->ptr_ = new_ptr; // deallocate may throw (at least in principle), but it doesn't matter since @@ -917,26 +853,23 @@ void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) // A fixed-size buffer. template <typename Char> -class FixedBuffer : public fmt::Buffer<Char> -{ -public: - FixedBuffer(Char *array, std::size_t size) : fmt::Buffer<Char>(array, size) {} +class FixedBuffer : public fmt::Buffer<Char> { + public: + FixedBuffer(Char* array, std::size_t size) : fmt::Buffer<Char>(array, size) {} -protected: + protected: FMT_API void grow(std::size_t size) FMT_OVERRIDE; }; template <typename Char> -class BasicCharTraits -{ -public: +class BasicCharTraits { + public: #if FMT_SECURE_SCL typedef stdext::checked_array_iterator<Char*> CharPtr; #else - typedef Char *CharPtr; + typedef Char* CharPtr; #endif - static Char cast(int value) - { + static Char cast(int value) { return static_cast<Char>(value); } }; @@ -945,77 +878,68 @@ template <typename Char> class CharTraits; template <> -class CharTraits<char> : public BasicCharTraits<char> -{ -private: +class CharTraits<char> : public BasicCharTraits<char> { + private: // Conversion from wchar_t to char is not allowed. static char convert(wchar_t); -public: - static char convert(char value) - { + public: + static char convert(char value) { return value; } // Formats a floating-point number. template <typename T> - 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<char>::format_float<double> -(char *buffer, std::size_t size, +(char* buffer, std::size_t size, const char* format, unsigned width, int precision, double value); extern template int CharTraits<char>::format_float<long double> -(char *buffer, std::size_t size, +(char* buffer, std::size_t size, const char* format, unsigned width, int precision, long double value); #endif template <> -class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> -{ -public: - static wchar_t convert(char value) - { +class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> { + public: + static wchar_t convert(char value) { return value; } - static wchar_t convert(wchar_t value) - { + static wchar_t convert(wchar_t value) { return value; } template <typename T> - 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<wchar_t>::format_float<double> -(wchar_t *buffer, std::size_t size, +(wchar_t* buffer, std::size_t size, const wchar_t* format, unsigned width, int precision, double value); extern template int CharTraits<wchar_t>::format_float<long double> -(wchar_t *buffer, std::size_t size, +(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 <bool IsSigned> -struct SignChecker -{ +struct SignChecker { template <typename T> - static bool is_negative(T value) - { + static bool is_negative(T value) { return value < 0; } }; template <> -struct SignChecker<false> -{ +struct SignChecker<false> { template <typename T> - static bool is_negative(T) - { + static bool is_negative(T) { return false; } }; @@ -1023,40 +947,35 @@ struct SignChecker<false> // Returns true if value is negative, false otherwise. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. template <typename T> -inline bool is_negative(T value) -{ +inline bool is_negative(T value) { return SignChecker<std::numeric_limits<T>::is_signed>::is_negative(value); } // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. template <bool FitsIn32Bits> -struct TypeSelector -{ +struct TypeSelector { typedef uint32_t Type; }; template <> -struct TypeSelector<false> -{ +struct TypeSelector<false> { typedef uint64_t Type; }; template <typename T> -struct IntTraits -{ +struct IntTraits { // Smallest of uint32_t and uint64_t that is large enough to represent // all values of T. typedef typename - TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType; + TypeSelector < std::numeric_limits<T>::digits <= 32 >::Type MainType; }; -FMT_API void report_unknown_type(char code, const char *type); +FMT_API void report_unknown_type(char code, const char* type); // Static data is placed in this class template to allow header-only // configuration. template <typename T = void> -struct FMT_API BasicData -{ +struct FMT_API BasicData { static const uint32_t POWERS_OF_10_32[]; static const uint64_t POWERS_OF_10_64[]; static const char DIGITS[]; @@ -1071,8 +990,7 @@ typedef BasicData<> Data; #ifdef FMT_BUILTIN_CLZLL // Returns the number of decimal digits in n. Leading zeros are not counted // except for n == 0 in which case count_digits returns 1. -inline unsigned count_digits(uint64_t n) -{ +inline unsigned count_digits(uint64_t n) { // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; @@ -1080,11 +998,9 @@ inline unsigned count_digits(uint64_t n) } #else // Fallback version of count_digits used when __builtin_clz is not available. -inline unsigned count_digits(uint64_t n) -{ +inline unsigned count_digits(uint64_t n) { unsigned count = 1; - for (;;) - { + for (;;) { // Integer division is slow so do it for a group of four digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. @@ -1100,35 +1016,31 @@ inline unsigned count_digits(uint64_t n) #ifdef FMT_BUILTIN_CLZ // Optional version of count_digits for better performance on 32-bit platforms. -inline unsigned count_digits(uint32_t n) -{ +inline unsigned count_digits(uint32_t n) { int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; return to_unsigned(t) - (n < Data::POWERS_OF_10_32[t]) + 1; } #endif // A functor that doesn't add a thousands separator. -struct NoThousandsSep -{ +struct NoThousandsSep { template <typename Char> - void operator()(Char *) {} + void operator()(Char*) {} }; // A functor that adds a thousands separator. -class ThousandsSep -{ -private: +class ThousandsSep { + private: fmt::StringRef sep_; // Index of a decimal digit with the least significant digit having index 0. unsigned digit_index_; -public: + public: explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {} template <typename Char> - void operator()(Char *&buffer) - { + void operator()(Char*& buffer) { if (++digit_index_ % 3 != 0) return; buffer -= sep_.size(); @@ -1141,12 +1053,10 @@ public: // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. template <typename UInt, typename Char, typename ThousandsSep> -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) - { + while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. @@ -1157,8 +1067,7 @@ inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, *--buffer = Data::DIGITS[index]; thousands_sep(buffer); } - if (value < 10) - { + if (value < 10) { *--buffer = static_cast<char>('0' + value); return; } @@ -1169,8 +1078,7 @@ inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, } template <typename UInt, typename Char> -inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) -{ +inline void format_decimal(Char* buffer, UInt value, unsigned num_digits) { format_decimal(buffer, value, num_digits, NoThousandsSep()); return; } @@ -1186,55 +1094,45 @@ inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) #if FMT_USE_WINDOWS_H // A converter from UTF-8 to UTF-16. // It is only provided for Windows since other systems support UTF-8 natively. -class UTF8ToUTF16 -{ -private: +class UTF8ToUTF16 { + private: MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer_; -public: + public: FMT_API explicit UTF8ToUTF16(StringRef s); - operator WStringRef() const - { + operator WStringRef() const { return WStringRef(&buffer_[0], size()); } - size_t size() const - { + size_t size() const { return buffer_.size() - 1; } - const wchar_t *c_str() const - { + const wchar_t* c_str() const { return &buffer_[0]; } - std::wstring str() const - { + std::wstring str() const { return std::wstring(&buffer_[0], size()); } }; // A converter from UTF-16 to UTF-8. // It is only provided for Windows since other systems support UTF-8 natively. -class UTF16ToUTF8 -{ -private: +class UTF16ToUTF8 { + private: MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer_; -public: + public: UTF16ToUTF8() {} FMT_API explicit UTF16ToUTF8(WStringRef s); - operator StringRef() const - { + operator StringRef() const { return StringRef(&buffer_[0], size()); } - size_t size() const - { + size_t size() const { return buffer_.size() - 1; } - const char *c_str() const - { + const char* c_str() const { return &buffer_[0]; } - std::string str() const - { + std::string str() const { return std::string(&buffer_[0], size()); } @@ -1244,38 +1142,34 @@ public: FMT_API int convert(WStringRef s); }; -FMT_API void format_windows_error(fmt::Writer &out, int error_code, +FMT_API void format_windows_error(fmt::Writer& out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; #endif // A formatting argument value. -struct Value -{ +struct Value { template <typename Char> - struct StringValue - { - const Char *value; + struct StringValue { + const Char* value; std::size_t size; }; typedef void (*FormatFunc)( - void *formatter, const void *arg, void *format_str_ptr); + void* formatter, const void* arg, void* format_str_ptr); - struct CustomValue - { - const void *value; + struct CustomValue { + const void* value; FormatFunc format; }; - union - { + union { int int_value; unsigned uint_value; LongLong long_long_value; ULongLong ulong_long_value; double double_value; long double long_double_value; - const void *pointer; + const void* pointer; StringValue<char> string; StringValue<signed char> sstring; StringValue<unsigned char> ustring; @@ -1283,8 +1177,7 @@ struct Value CustomValue custom; }; - enum Type - { + enum Type { NONE, NAMED_ARG, // Integer types should go first, INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR, @@ -1296,8 +1189,7 @@ struct Value // A formatting argument. It is a trivially copyable/constructible type to // allow storage in internal::MemoryBuffer. -struct Arg : Value -{ +struct Arg : Value { Type type; }; @@ -1312,15 +1204,13 @@ struct Null {}; // A helper class template to enable or disable overloads taking wide // characters and strings in MakeValue. template <typename T, typename Char> -struct WCharHelper -{ +struct WCharHelper { typedef Null<T> Supported; typedef T Unsupported; }; template <typename T> -struct WCharHelper<T, wchar_t> -{ +struct WCharHelper<T, wchar_t> { typedef T Supported; typedef Null<T> Unsupported; }; @@ -1329,39 +1219,33 @@ typedef char Yes[1]; typedef char No[2]; template <typename T> -T &get(); +T& get(); // These are non-members to workaround an overload resolution bug in bcc32. -Yes &convert(fmt::ULongLong); -No &convert(...); +Yes& convert(fmt::ULongLong); +No& convert(...); template<typename T, bool ENABLE_CONVERSION> -struct ConvertToIntImpl -{ +struct ConvertToIntImpl { enum { value = ENABLE_CONVERSION }; }; template<typename T, bool ENABLE_CONVERSION> -struct ConvertToIntImpl2 -{ +struct ConvertToIntImpl2 { enum { value = false }; }; template<typename T> -struct ConvertToIntImpl2<T, true> -{ - enum - { +struct ConvertToIntImpl2<T, true> { + enum { // Don't convert numeric types. - value = ConvertToIntImpl<T, !std::numeric_limits<T>::is_specialized>::value + value = ConvertToIntImpl < T, !std::numeric_limits<T>::is_specialized >::value }; }; template<typename T> -struct ConvertToInt -{ - enum - { +struct ConvertToInt { + enum { enable_conversion = sizeof(fmt::internal::convert(get<T>())) == sizeof(Yes) }; enum { value = ConvertToIntImpl2<T, enable_conversion>::value }; @@ -1380,44 +1264,37 @@ template<bool B, class T = void> struct EnableIf {}; template<class T> -struct EnableIf<true, T> -{ +struct EnableIf<true, T> { typedef T type; }; template<bool B, class T, class F> -struct Conditional -{ +struct Conditional { typedef T type; }; template<class T, class F> -struct Conditional<false, T, F> -{ +struct Conditional<false, T, F> { typedef F type; }; // For bcc32 which doesn't understand ! in template arguments. template <bool> -struct Not -{ +struct Not { enum { value = 0 }; }; template <> -struct Not<false> -{ +struct Not<false> { enum { value = 1 }; }; template <typename T> -struct FalseType -{ +struct FalseType { enum { value = 0 }; }; -template <typename T, T> struct LConvCheck -{ +template <typename T, T> struct LConvCheck { LConvCheck(int) {} }; @@ -1426,13 +1303,11 @@ template <typename T, T> struct LConvCheck // ``lconv`` is stubbed as an empty struct. template <typename LConv> inline StringRef thousands_sep( - LConv *lc, LConvCheck<char *LConv::*, &LConv::thousands_sep> = 0) -{ + LConv* lc, LConvCheck<char* LConv::*, &LConv::thousands_sep> = 0) { return lc->thousands_sep; } -inline fmt::StringRef thousands_sep(...) -{ +inline fmt::StringRef thousands_sep(...) { return ""; } @@ -1458,8 +1333,7 @@ inline fmt::StringRef thousands_sep(...) #endif template <typename Formatter, typename Char, typename T> -void format_arg(Formatter &, const Char *, const T &) -{ +void format_arg(Formatter&, const Char*, const T&) { FMT_STATIC_ASSERT(FalseType<T>::value, "Cannot format argument. To enable the use of ostream " "operator<< include fmt/ostream.h. Otherwise provide " @@ -1468,21 +1342,20 @@ void format_arg(Formatter &, const Char *, const T &) // Makes an Arg object from any type. template <typename Formatter> -class MakeValue : public Arg -{ -public: +class MakeValue : public Arg { + public: typedef typename Formatter::Char Char; -private: + private: // The following two methods are private to disallow formatting of // arbitrary pointers. If you want to output a pointer cast it to // "void *" or "const void *". In particular, this forbids formatting // of "[const] volatile char *" which is printed as bool by iostreams. // Do not implement! template <typename T> - MakeValue(const T *value); + MakeValue(const T* value); template <typename T> - MakeValue(T *value); + MakeValue(T* value); // The following methods are private to disallow formatting of wide // characters and strings into narrow strings as in @@ -1491,19 +1364,17 @@ private: #if !FMT_MSC_VER || defined(_NATIVE_WCHAR_T_DEFINED) MakeValue(typename WCharHelper<wchar_t, Char>::Unsupported); #endif - MakeValue(typename WCharHelper<wchar_t *, Char>::Unsupported); - MakeValue(typename WCharHelper<const wchar_t *, Char>::Unsupported); - MakeValue(typename WCharHelper<const std::wstring &, Char>::Unsupported); + MakeValue(typename WCharHelper<wchar_t*, Char>::Unsupported); + MakeValue(typename WCharHelper<const wchar_t*, Char>::Unsupported); + MakeValue(typename WCharHelper<const std::wstring&, Char>::Unsupported); MakeValue(typename WCharHelper<WStringRef, Char>::Unsupported); - void set_string(StringRef str) - { + void set_string(StringRef str) { string.value = str.data(); string.size = str.size(); } - void set_string(WStringRef str) - { + void set_string(WStringRef str) { wstring.value = str.data(); wstring.size = str.size(); } @@ -1511,14 +1382,13 @@ private: // Formats an argument of a custom type, such as a user-defined class. template <typename T> static void format_custom_arg( - void *formatter, const void *arg, void *format_str_ptr) - { + void* formatter, const void* arg, void* format_str_ptr) { format_arg(*static_cast<Formatter*>(formatter), *static_cast<const Char**>(format_str_ptr), *static_cast<const T*>(arg)); } -public: + public: MakeValue() {} #define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ @@ -1534,8 +1404,7 @@ public: FMT_MAKE_VALUE(int, int_value, INT) FMT_MAKE_VALUE(unsigned, uint_value, UINT) - MakeValue(long value) - { + MakeValue(long value) { // To minimize the number of types we need to deal with, long is // translated either to int or to long long depending on its size. if (const_check(sizeof(long) == sizeof(int))) @@ -1543,20 +1412,17 @@ public: else long_long_value = value; } - static uint64_t type(long) - { + static uint64_t type(long) { return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG; } - MakeValue(unsigned long value) - { + MakeValue(unsigned long value) { if (const_check(sizeof(unsigned long) == sizeof(unsigned))) uint_value = static_cast<unsigned>(value); else ulong_long_value = value; } - static uint64_t type(unsigned long) - { + static uint64_t type(unsigned long) { return sizeof(unsigned long) == sizeof(unsigned) ? Arg::UINT : Arg::ULONG_LONG; } @@ -1571,12 +1437,10 @@ public: FMT_MAKE_VALUE(char, int_value, CHAR) #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) - MakeValue(typename WCharHelper<wchar_t, Char>::Supported value) - { + MakeValue(typename WCharHelper<wchar_t, Char>::Supported value) { int_value = value; } - static uint64_t type(wchar_t) - { + static uint64_t type(wchar_t) { return Arg::CHAR; } #endif @@ -1585,13 +1449,13 @@ public: MakeValue(Type value) { set_string(value); } \ static uint64_t type(Type) { return Arg::TYPE; } - FMT_MAKE_VALUE(char *, string.value, CSTRING) - FMT_MAKE_VALUE(const char *, string.value, CSTRING) - FMT_MAKE_VALUE(signed char *, sstring.value, CSTRING) - FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING) - FMT_MAKE_VALUE(unsigned char *, ustring.value, CSTRING) - FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING) - FMT_MAKE_STR_VALUE(const std::string &, STRING) + FMT_MAKE_VALUE(char*, string.value, CSTRING) + FMT_MAKE_VALUE(const char*, string.value, CSTRING) + FMT_MAKE_VALUE(signed char*, sstring.value, CSTRING) + FMT_MAKE_VALUE(const signed char*, sstring.value, CSTRING) + FMT_MAKE_VALUE(unsigned char*, ustring.value, CSTRING) + FMT_MAKE_VALUE(const unsigned char*, ustring.value, CSTRING) + FMT_MAKE_STR_VALUE(const std::string&, STRING) FMT_MAKE_STR_VALUE(StringRef, STRING) FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str()) @@ -1601,94 +1465,82 @@ public: } \ static uint64_t type(Type) { return Arg::TYPE; } - FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) - FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) - FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING) + FMT_MAKE_WSTR_VALUE(wchar_t*, WSTRING) + FMT_MAKE_WSTR_VALUE(const wchar_t*, WSTRING) + FMT_MAKE_WSTR_VALUE(const std::wstring&, WSTRING) FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING) - FMT_MAKE_VALUE(void *, pointer, POINTER) - FMT_MAKE_VALUE(const void *, pointer, POINTER) + FMT_MAKE_VALUE(void*, pointer, POINTER) + FMT_MAKE_VALUE(const void*, pointer, POINTER) template <typename T> - MakeValue(const T &value, + MakeValue(const T& value, typename EnableIf<Not< - ConvertToInt<T>::value>::value, int>::type = 0) - { + ConvertToInt<T>::value>::value, int>::type = 0) { custom.value = &value; custom.format = &format_custom_arg<T>; } template <typename T> static typename EnableIf<Not<ConvertToInt<T>::value>::value, uint64_t>::type - type(const T &) - { + type(const T&) { return Arg::CUSTOM; } // Additional template param `Char_` is needed here because make_type always // uses char. template <typename Char_> - MakeValue(const NamedArg<Char_> &value) - { + MakeValue(const NamedArg<Char_>& value) { pointer = &value; } template <typename Char_, typename T> - MakeValue(const NamedArgWithType<Char_, T> &value) - { + MakeValue(const NamedArgWithType<Char_, T>& value) { pointer = &value; } template <typename Char_> - static uint64_t type(const NamedArg<Char_> &) - { + static uint64_t type(const NamedArg<Char_>&) { return Arg::NAMED_ARG; } template <typename Char_, typename T> - static uint64_t type(const NamedArgWithType<Char_, T> &) - { + static uint64_t type(const NamedArgWithType<Char_, T>&) { return Arg::NAMED_ARG; } }; template <typename Formatter> -class MakeArg : public Arg -{ -public: - MakeArg() - { +class MakeArg : public Arg { + public: + MakeArg() { type = Arg::NONE; } template <typename T> - MakeArg(const T &value) - : Arg(MakeValue<Formatter>(value)) - { + MakeArg(const T& value) + : Arg(MakeValue<Formatter>(value)) { type = static_cast<Arg::Type>(MakeValue<Formatter>::type(value)); } }; template <typename Char> -struct NamedArg : Arg -{ +struct NamedArg : Arg { BasicStringRef<Char> name; template <typename T> - NamedArg(BasicStringRef<Char> argname, const T &value) + NamedArg(BasicStringRef<Char> argname, const T& value) : Arg(MakeArg< BasicFormatter<Char> >(value)), name(argname) {} }; template <typename Char, typename T> -struct NamedArgWithType : NamedArg<Char> -{ - NamedArgWithType(BasicStringRef<Char> argname, const T &value) +struct NamedArgWithType : NamedArg<Char> { + NamedArgWithType(BasicStringRef<Char> argname, const T& value) : NamedArg<Char>(argname, value) {} }; -class RuntimeError : public std::runtime_error -{ -protected: +class RuntimeError : public std::runtime_error { + protected: RuntimeError() : std::runtime_error("") {} - RuntimeError(const RuntimeError &rerr) : std::runtime_error(rerr) {} + RuntimeError(const RuntimeError& rerr) : std::runtime_error(rerr) {} FMT_API ~RuntimeError() FMT_DTOR_NOEXCEPT; }; @@ -1697,79 +1549,70 @@ class ArgMap; } // namespace internal /** An argument list. */ -class ArgList -{ -private: +class ArgList { + private: // To reduce compiled code size per formatting function call, types of first // MAX_PACKED_ARGS arguments are passed in the types_ field. uint64_t types_; - union - { + union { // If the number of arguments is less than MAX_PACKED_ARGS, the argument // values are stored in values_, otherwise they are stored in args_. // This is done to reduce compiled code size as storing larger objects // may require more code (at least on x86-64) even if the same amount of // data is actually copied to stack. It saves ~10% on the bloat test. - const internal::Value *values_; - const internal::Arg *args_; + const internal::Value* values_; + const internal::Arg* args_; }; - internal::Arg::Type type(unsigned index) const - { + internal::Arg::Type type(unsigned index) const { return type(types_, index); } template <typename Char> friend class internal::ArgMap; -public: + public: // Maximum number of arguments with packed types. enum { MAX_PACKED_ARGS = 16 }; ArgList() : types_(0) {} - ArgList(ULongLong types, const internal::Value *values) + ArgList(ULongLong types, const internal::Value* values) : types_(types), values_(values) {} - ArgList(ULongLong types, const internal::Arg *args) + ArgList(ULongLong types, const internal::Arg* args) : types_(types), args_(args) {} - uint64_t types() const - { + uint64_t types() const { return types_; } /** Returns the argument at specified index. */ - internal::Arg operator[](unsigned index) const - { + internal::Arg operator[](unsigned index) const { using internal::Arg; Arg arg; bool use_values = type(MAX_PACKED_ARGS - 1) == Arg::NONE; - if (index < MAX_PACKED_ARGS) - { + if (index < MAX_PACKED_ARGS) { Arg::Type arg_type = type(index); - internal::Value &val = arg; + internal::Value& val = arg; if (arg_type != Arg::NONE) val = use_values ? values_[index] : args_[index]; arg.type = arg_type; return arg; } - if (use_values) - { + if (use_values) { // The index is greater than the number of arguments that can be stored // in values, so return a "none" argument. arg.type = Arg::NONE; return arg; } - for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) - { + for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) { if (args_[i].type == Arg::NONE) return args_[i]; } return args_[index]; } - static internal::Arg::Type type(uint64_t types, unsigned index) - { + static internal::Arg::Type type(uint64_t types, unsigned index) { unsigned shift = index * 4; uint64_t mask = 0xf; return static_cast<internal::Arg::Type>( @@ -1804,109 +1647,92 @@ public: \endrst */ template <typename Impl, typename Result> -class ArgVisitor -{ -private: +class ArgVisitor { + private: typedef internal::Arg Arg; -public: + public: void report_unhandled_arg() {} - Result visit_unhandled_arg() - { + Result visit_unhandled_arg() { FMT_DISPATCH(report_unhandled_arg()); return Result(); } /** Visits an ``int`` argument. **/ - Result visit_int(int value) - { + Result visit_int(int value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits a ``long long`` argument. **/ - Result visit_long_long(LongLong value) - { + Result visit_long_long(LongLong value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits an ``unsigned`` argument. **/ - Result visit_uint(unsigned value) - { + Result visit_uint(unsigned value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits an ``unsigned long long`` argument. **/ - Result visit_ulong_long(ULongLong value) - { + Result visit_ulong_long(ULongLong value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits a ``bool`` argument. **/ - Result visit_bool(bool value) - { + Result visit_bool(bool value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits a ``char`` or ``wchar_t`` argument. **/ - Result visit_char(int value) - { + Result visit_char(int value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits an argument of any integral type. **/ template <typename T> - Result visit_any_int(T) - { + Result visit_any_int(T) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a ``double`` argument. **/ - Result visit_double(double value) - { + Result visit_double(double value) { return FMT_DISPATCH(visit_any_double(value)); } /** Visits a ``long double`` argument. **/ - Result visit_long_double(long double value) - { + Result visit_long_double(long double value) { return FMT_DISPATCH(visit_any_double(value)); } /** Visits a ``double`` or ``long double`` argument. **/ template <typename T> - Result visit_any_double(T) - { + Result visit_any_double(T) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a null-terminated C string (``const char *``) argument. **/ - Result visit_cstring(const char *) - { + Result visit_cstring(const char*) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a string argument. **/ - Result visit_string(Arg::StringValue<char>) - { + Result visit_string(Arg::StringValue<char>) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a wide string argument. **/ - Result visit_wstring(Arg::StringValue<wchar_t>) - { + Result visit_wstring(Arg::StringValue<wchar_t>) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a pointer argument. **/ - Result visit_pointer(const void *) - { + Result visit_pointer(const void*) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits an argument of a custom (user-defined) type. **/ - Result visit_custom(Arg::CustomValue) - { + Result visit_custom(Arg::CustomValue) { return FMT_DISPATCH(visit_unhandled_arg()); } @@ -1918,10 +1744,8 @@ public: called. \endrst */ - Result visit(const Arg &arg) - { - switch (arg.type) - { + Result visit(const Arg& arg) { + switch (arg.type) { case Arg::NONE: case Arg::NAMED_ARG: FMT_ASSERT(false, "invalid argument type"); @@ -1957,14 +1781,12 @@ public: } }; -enum Alignment -{ +enum Alignment { ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC }; // Flags. -enum -{ +enum { SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. }; @@ -1974,41 +1796,32 @@ struct EmptySpec {}; // A type specifier. template <char TYPE> -struct TypeSpec : EmptySpec -{ - Alignment align() const - { +struct TypeSpec : EmptySpec { + Alignment align() const { return ALIGN_DEFAULT; } - unsigned width() const - { + unsigned width() const { return 0; } - int precision() const - { + int precision() const { return -1; } - bool flag(unsigned) const - { + bool flag(unsigned) const { return false; } - char type() const - { + char type() const { return TYPE; } - char type_prefix() const - { + char type_prefix() const { return TYPE; } - char fill() const - { + char fill() const { return ' '; } }; // A width specifier. -struct WidthSpec -{ +struct WidthSpec { unsigned width_; // Fill is always wchar_t and cast to char if necessary to avoid having // two specialization of WidthSpec and its subclasses. @@ -2016,58 +1829,48 @@ struct WidthSpec WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} - unsigned width() const - { + unsigned width() const { return width_; } - wchar_t fill() const - { + wchar_t fill() const { return fill_; } }; // An alignment specifier. -struct AlignSpec : WidthSpec -{ +struct AlignSpec : WidthSpec { Alignment align_; AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) : WidthSpec(width, fill), align_(align) {} - Alignment align() const - { + Alignment align() const { return align_; } - int precision() const - { + int precision() const { return -1; } }; // An alignment and type specifier. template <char TYPE> -struct AlignTypeSpec : AlignSpec -{ +struct AlignTypeSpec : AlignSpec { AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} - bool flag(unsigned) const - { + bool flag(unsigned) const { return false; } - char type() const - { + char type() const { return TYPE; } - char type_prefix() const - { + char type_prefix() const { return TYPE; } }; // A full format specifier. -struct FormatSpec : AlignSpec -{ +struct FormatSpec : AlignSpec { unsigned flags_; int precision_; char type_; @@ -2076,58 +1879,49 @@ struct FormatSpec : AlignSpec unsigned width = 0, char type = 0, wchar_t fill = ' ') : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} - bool flag(unsigned f) const - { + bool flag(unsigned f) const { return (flags_ & f) != 0; } - int precision() const - { + int precision() const { return precision_; } - char type() const - { + char type() const { return type_; } - char type_prefix() const - { + char type_prefix() const { return type_; } }; // An integer format specifier. template <typename T, typename SpecT = TypeSpec<0>, typename Char = char> -class IntFormatSpec : public SpecT -{ -private: +class IntFormatSpec : public SpecT { + private: T value_; -public: - IntFormatSpec(T val, const SpecT &spec = SpecT()) + public: + IntFormatSpec(T val, const SpecT& spec = SpecT()) : SpecT(spec), value_(val) {} - T value() const - { + T value() const { return value_; } }; // A string format specifier. template <typename Char> -class StrFormatSpec : public AlignSpec -{ -private: - const Char *str_; +class StrFormatSpec : public AlignSpec { + private: + const Char* str_; -public: + public: template <typename FillChar> - StrFormatSpec(const Char *str, unsigned width, FillChar fill) - : AlignSpec(width, fill), str_(str) - { + StrFormatSpec(const Char* str, unsigned width, FillChar fill) + : AlignSpec(width, fill), str_(str) { internal::CharTraits<Char>::convert(FillChar()); } - const Char *str() const - { + const Char* str() const { return str_; } }; @@ -2242,39 +2036,33 @@ FMT_DEFINE_INT_FORMATTERS(ULongLong) */ template <typename Char> inline StrFormatSpec<Char> pad( - const Char *str, unsigned width, Char fill = ' ') -{ + const Char* str, unsigned width, Char fill = ' ') { return StrFormatSpec<Char>(str, width, fill); } inline StrFormatSpec<wchar_t> pad( - const wchar_t *str, unsigned width, char fill = ' ') -{ + const wchar_t* str, unsigned width, char fill = ' ') { return StrFormatSpec<wchar_t>(str, width, fill); } -namespace internal -{ +namespace internal { template <typename Char> -class ArgMap -{ -private: - typedef std::vector< +class ArgMap { + private: + typedef std::vector < std::pair<fmt::BasicStringRef<Char>, internal::Arg> > MapType; typedef typename MapType::value_type Pair; MapType map_; -public: - FMT_API void init(const ArgList &args); + public: + FMT_API void init(const ArgList& args); - const internal::Arg *find(const fmt::BasicStringRef<Char> &name) const - { + const internal::Arg* find(const fmt::BasicStringRef<Char>& 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) - { + it != end; ++it) { if (it->first == name) return &it->second; } @@ -2283,16 +2071,14 @@ public: }; template <typename Impl, typename Char, typename Spec = fmt::FormatSpec> -class ArgFormatterBase : public ArgVisitor<Impl, void> -{ -private: - BasicWriter<Char> &writer_; - Spec &spec_; +class ArgFormatterBase : public ArgVisitor<Impl, void> { + private: + BasicWriter<Char>& writer_; + Spec& spec_; FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatterBase); - void write_pointer(const void *p) - { + void write_pointer(const void* p) { spec_.flags_ = HASH_FLAG; spec_.type_ = 'x'; writer_.write_int(reinterpret_cast<uintptr_t>(p), spec_); @@ -2301,61 +2087,51 @@ private: // workaround MSVC two-phase lookup issue typedef internal::Arg Arg; -protected: - BasicWriter<Char> &writer() - { + protected: + BasicWriter<Char>& writer() { return writer_; } - Spec &spec() - { + Spec& spec() { return spec_; } - void write(bool value) - { - const char *str_value = value ? "true" : "false"; + void write(bool value) { + const char* str_value = value ? "true" : "false"; Arg::StringValue<char> str = { str_value, std::strlen(str_value) }; writer_.write_str(str, spec_); } - void write(const char *value) - { + void write(const char* value) { Arg::StringValue<char> str = {value, value ? std::strlen(value) : 0}; writer_.write_str(str, spec_); } -public: + public: typedef Spec SpecType; - ArgFormatterBase(BasicWriter<Char> &w, Spec &s) + ArgFormatterBase(BasicWriter<Char>& w, Spec& s) : writer_(w), spec_(s) {} template <typename T> - void visit_any_int(T value) - { + void visit_any_int(T value) { writer_.write_int(value, spec_); } template <typename T> - void visit_any_double(T value) - { + void visit_any_double(T value) { writer_.write_double(value, spec_); } - void visit_bool(bool value) - { - if (spec_.type_) - { + void visit_bool(bool value) { + if (spec_.type_) { visit_any_int(value); return; } write(value); } - void visit_char(int value) - { - if (spec_.type_ && spec_.type_ != 'c') - { + void visit_char(int value) { + if (spec_.type_ && spec_.type_ != 'c') { spec_.flags_ |= CHAR_FLAG; writer_.write_int(value, spec_); return; @@ -2366,84 +2142,68 @@ public: Char fill = internal::CharTraits<Char>::cast(spec_.fill()); CharPtr out = CharPtr(); const unsigned CHAR_SIZE = 1; - if (spec_.width_ > CHAR_SIZE) - { + if (spec_.width_ > CHAR_SIZE) { out = writer_.grow_buffer(spec_.width_); - if (spec_.align_ == ALIGN_RIGHT) - { + if (spec_.align_ == ALIGN_RIGHT) { std::uninitialized_fill_n(out, spec_.width_ - CHAR_SIZE, fill); out += spec_.width_ - CHAR_SIZE; - } - else if (spec_.align_ == ALIGN_CENTER) - { + } else if (spec_.align_ == ALIGN_CENTER) { out = writer_.fill_padding(out, spec_.width_, internal::const_check(CHAR_SIZE), fill); - } - else - { + } else { std::uninitialized_fill_n(out + CHAR_SIZE, spec_.width_ - CHAR_SIZE, fill); } - } - else - { + } else { out = writer_.grow_buffer(CHAR_SIZE); } *out = internal::CharTraits<Char>::cast(value); } - void visit_cstring(const char *value) - { + void visit_cstring(const char* value) { if (spec_.type_ == 'p') return write_pointer(value); write(value); } // Qualification with "internal" here and below is a workaround for nvcc. - void visit_string(internal::Arg::StringValue<char> value) - { + void visit_string(internal::Arg::StringValue<char> value) { writer_.write_str(value, spec_); } using ArgVisitor<Impl, void>::visit_wstring; - void visit_wstring(internal::Arg::StringValue<Char> value) - { + void visit_wstring(internal::Arg::StringValue<Char> value) { writer_.write_str(value, spec_); } - void visit_pointer(const void *value) - { + void visit_pointer(const void* value) { if (spec_.type_ && spec_.type_ != 'p') report_unknown_type(spec_.type_, "pointer"); write_pointer(value); } }; -class FormatterBase -{ -private: +class FormatterBase { + private: ArgList args_; int next_arg_index_; // Returns the argument with specified index. - FMT_API Arg do_get_arg(unsigned arg_index, const char *&error); + FMT_API Arg do_get_arg(unsigned arg_index, const char*& error); -protected: - const ArgList &args() const - { + protected: + const ArgList& args() const { return args_; } - explicit FormatterBase(const ArgList &args) - { + explicit FormatterBase(const ArgList& args) { args_ = args; next_arg_index_ = 0; } // Returns the next argument. - Arg next_arg(const char *&error) - { + Arg next_arg(const char*& error) { if (next_arg_index_ >= 0) return do_get_arg(internal::to_unsigned(next_arg_index_++), error); error = "cannot switch from manual to automatic argument indexing"; @@ -2452,15 +2212,12 @@ protected: // Checks if manual indexing is used and returns the argument with // specified index. - Arg get_arg(unsigned arg_index, const char *&error) - { + Arg get_arg(unsigned arg_index, const char*& error) { return check_no_auto_index(error) ? do_get_arg(arg_index, error) : Arg(); } - bool check_no_auto_index(const char *&error) - { - if (next_arg_index_ > 0) - { + bool check_no_auto_index(const char*& error) { + if (next_arg_index_ > 0) { error = "cannot switch from automatic to manual argument indexing"; return false; } @@ -2469,8 +2226,7 @@ protected: } template <typename Char> - void write(BasicWriter<Char> &w, const Char *start, const Char *end) - { + void write(BasicWriter<Char>& w, const Char* start, const Char* end) { if (start != end) w << BasicStringRef<Char>(start, internal::to_unsigned(end - start)); } @@ -2495,13 +2251,12 @@ protected: \endrst */ template <typename Impl, typename Char, typename Spec = fmt::FormatSpec> -class BasicArgFormatter : public internal::ArgFormatterBase<Impl, Char, Spec> -{ -private: - BasicFormatter<Char, Impl> &formatter_; - const Char *format_; +class BasicArgFormatter : public internal::ArgFormatterBase<Impl, Char, Spec> { + private: + BasicFormatter<Char, Impl>& formatter_; + const Char* format_; -public: + public: /** \rst Constructs an argument formatter object. @@ -2510,14 +2265,13 @@ public: to the part of the format string being parsed for custom argument types. \endrst */ - BasicArgFormatter(BasicFormatter<Char, Impl> &formatter, - Spec &spec, const Char *fmt) + BasicArgFormatter(BasicFormatter<Char, Impl>& formatter, + Spec& spec, const Char* fmt) : internal::ArgFormatterBase<Impl, Char, Spec>(formatter.writer(), spec), formatter_(formatter), format_(fmt) {} /** Formats an argument of a custom (user-defined) type. */ - void visit_custom(internal::Arg::CustomValue c) - { + void visit_custom(internal::Arg::CustomValue c) { c.format(&formatter_, c.value, &format_); } }; @@ -2525,26 +2279,24 @@ public: /** The default argument formatter. */ template <typename Char> class ArgFormatter : - public BasicArgFormatter<ArgFormatter<Char>, Char, FormatSpec> -{ -public: + public BasicArgFormatter<ArgFormatter<Char>, Char, FormatSpec> { + public: /** Constructs an argument formatter object. */ - ArgFormatter(BasicFormatter<Char> &formatter, - FormatSpec &spec, const Char *fmt) + ArgFormatter(BasicFormatter<Char>& formatter, + FormatSpec& spec, const Char* fmt) : BasicArgFormatter<ArgFormatter<Char>, Char, FormatSpec>(formatter, spec, fmt) {} }; /** This template formats data and writes the output to a writer. */ template <typename CharType, typename ArgFormatter> -class BasicFormatter : private internal::FormatterBase -{ -public: +class BasicFormatter : private internal::FormatterBase { + public: /** The character type for the output. */ typedef CharType Char; -private: - BasicWriter<Char> &writer_; + private: + BasicWriter<Char>& writer_; internal::ArgMap<Char> map_; FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter); @@ -2553,15 +2305,15 @@ private: // Checks if manual indexing is used and returns the argument with // specified name. - internal::Arg get_arg(BasicStringRef<Char> arg_name, const char *&error); + internal::Arg get_arg(BasicStringRef<Char> arg_name, const char*& error); // Parses argument index and returns corresponding argument. - internal::Arg parse_arg_index(const Char *&s); + internal::Arg parse_arg_index(const Char*& s); // Parses argument name and returns corresponding argument. - internal::Arg parse_arg_name(const Char *&s); + internal::Arg parse_arg_name(const Char*& s); -public: + public: /** \rst Constructs a ``BasicFormatter`` object. References to the arguments and @@ -2569,12 +2321,11 @@ public: appropriate lifetimes. \endrst */ - BasicFormatter(const ArgList &args, BasicWriter<Char> &w) + BasicFormatter(const ArgList& args, BasicWriter<Char>& w) : internal::FormatterBase(args), writer_(w) {} /** Returns a reference to the writer associated with this formatter. */ - BasicWriter<Char> &writer() - { + BasicWriter<Char>& writer() { return writer_; } @@ -2582,7 +2333,7 @@ public: void format(BasicCStringRef<Char> format_str); // Formats a single argument and advances format_str, a format string pointer. - const Char *format(const Char *&format_str, const internal::Arg &arg); + const Char* format(const Char*& format_str, const internal::Arg& arg); }; // Generates a comma-separated list with results of applying f to @@ -2604,30 +2355,25 @@ public: # define FMT_GEN14(f) FMT_GEN13(f), f(13) # define FMT_GEN15(f) FMT_GEN14(f), f(14) -namespace internal -{ -inline uint64_t make_type() -{ +namespace internal { +inline uint64_t make_type() { return 0; } template <typename T> -inline uint64_t make_type(const T &arg) -{ +inline uint64_t make_type(const T& arg) { return MakeValue< BasicFormatter<char> >::type(arg); } -template <std::size_t N, bool/*IsPacked*/= (N < ArgList::MAX_PACKED_ARGS)> - struct ArgArray; +template < std::size_t N, bool/*IsPacked*/ = (N < ArgList::MAX_PACKED_ARGS) > + struct ArgArray; template <std::size_t N> -struct ArgArray<N, true/*IsPacked*/> -{ +struct ArgArray<N, true/*IsPacked*/> { typedef Value Type[N > 0 ? N : 1]; template <typename Formatter, typename T> -static Value make(const T &value) -{ +static Value make(const T& value) { #ifdef __clang__ Value result = MakeValue<Formatter>(value); // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: @@ -2641,40 +2387,35 @@ static Value make(const T &value) }; template <std::size_t N> -struct ArgArray<N, false/*IsPacked*/> -{ +struct ArgArray<N, false/*IsPacked*/> { typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE template <typename Formatter, typename T> - static Arg make(const T &value) - { + static Arg make(const T& value) { return MakeArg<Formatter>(value); } }; #if FMT_USE_VARIADIC_TEMPLATES template <typename Arg, typename... Args> -inline uint64_t make_type(const Arg &first, const Args & ... tail) -{ +inline uint64_t make_type(const Arg& first, const Args& ... tail) { return make_type(first) | (make_type(tail...) << 4); } #else -struct ArgType -{ +struct ArgType { uint64_t type; ArgType() : type(0) {} template <typename T> - 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() -inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) -{ +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) | @@ -2785,19 +2526,18 @@ inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) An error returned by an operating system or a language runtime, for example a file opening error. */ -class SystemError : public internal::RuntimeError -{ -private: +class SystemError : public internal::RuntimeError { + private: FMT_API void init(int err_code, CStringRef format_str, ArgList args); -protected: + protected: int error_code_; typedef char Char; // For FMT_VARIADIC_CTOR. SystemError() {} -public: + public: /** \rst Constructs a :class:`fmt::SystemError` object with a description @@ -2816,8 +2556,7 @@ public: throw fmt::SystemError(errno, "cannot open file '{}'", filename); \endrst */ - SystemError(int error_code, CStringRef message) - { + SystemError(int error_code, CStringRef message) { init(error_code, message, ArgList()); } FMT_DEFAULTED_COPY_CTOR(SystemError) @@ -2825,8 +2564,7 @@ public: FMT_API ~SystemError() FMT_DTOR_NOEXCEPT; - int error_code() const - { + int error_code() const { return error_code_; } }; @@ -2847,7 +2585,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_API void format_system_error(fmt::Writer& out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; /** @@ -2869,11 +2607,10 @@ FMT_API void format_system_error(fmt::Writer &out, int error_code, \endrst */ template <typename Char> -class BasicWriter -{ -private: +class BasicWriter { + private: // Output buffer. - Buffer<Char> &buffer_; + Buffer<Char>& buffer_; FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter); @@ -2881,13 +2618,11 @@ private: #if FMT_SECURE_SCL // Returns pointer value. - static Char *get(CharPtr p) - { + static Char* get(CharPtr p) { return p.base(); } #else - static Char *get(Char *p) - { + static Char* get(Char* p) { return p; } #endif @@ -2899,8 +2634,7 @@ private: // Grows the buffer by n characters and returns a pointer to the newly // allocated area. - CharPtr grow_buffer(std::size_t n) - { + CharPtr grow_buffer(std::size_t n) { std::size_t size = buffer_.size(); buffer_.resize(size + n); return internal::make_ptr(&buffer_[size], n); @@ -2908,35 +2642,29 @@ private: // Writes an unsigned decimal integer. template <typename UInt> - Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) - { + 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)); + Char* ptr = get(grow_buffer(prefix_size + num_digits)); internal::format_decimal(ptr + prefix_size, value, num_digits); return ptr; } // Writes a decimal integer. template <typename Int> - void write_decimal(Int value) - { + void write_decimal(Int value) { typedef typename internal::IntTraits<Int>::MainType MainType; MainType abs_value = static_cast<MainType>(value); - if (internal::is_negative(value)) - { + if (internal::is_negative(value)) { abs_value = 0 - abs_value; *write_unsigned_decimal(abs_value, 1) = '-'; - } - else - { + } else { write_unsigned_decimal(abs_value, 0); } } // Prepare a buffer for integer formatting. CharPtr prepare_int_buffer(unsigned num_digits, - const EmptySpec &, const char *prefix, unsigned prefix_size) - { + const EmptySpec&, const char* prefix, unsigned prefix_size) { unsigned size = prefix_size + num_digits; CharPtr p = grow_buffer(size); std::uninitialized_copy(prefix, prefix + prefix_size, p); @@ -2945,7 +2673,7 @@ private: template <typename Spec> CharPtr prepare_int_buffer(unsigned num_digits, - const Spec &spec, const char *prefix, unsigned prefix_size); + const Spec& spec, const char* prefix, unsigned prefix_size); // Formats an integer. template <typename T, typename Spec> @@ -2953,15 +2681,15 @@ private: // Formats a floating-point number (double or long double). template <typename T, typename Spec> - void write_double(T value, const Spec &spec); + void write_double(T value, const Spec& spec); // Writes a formatted string. template <typename StrChar> - CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); + CharPtr write_str(const StrChar* s, std::size_t size, const AlignSpec& spec); template <typename StrChar, typename Spec> - void write_str(const internal::Arg::StringValue<StrChar> &str, - const Spec &spec); + void write_str(const internal::Arg::StringValue<StrChar>& 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 @@ -2969,17 +2697,16 @@ private: // Do not implement! void operator<<(typename internal::WCharHelper<wchar_t, Char>::Unsupported); void operator<<( - typename internal::WCharHelper<const wchar_t *, Char>::Unsupported); + typename internal::WCharHelper<const wchar_t*, Char>::Unsupported); // Appends floating-point length specifier to the format string. // The second argument is only used for overload resolution. - void append_float_length(Char *&format_ptr, long double) - { + void append_float_length(Char*& format_ptr, long double) { *format_ptr++ = 'L'; } template<typename T> - void append_float_length(Char *&, T) {} + void append_float_length(Char*&, T) {} template <typename Impl, typename Char_, typename Spec_> friend class internal::ArgFormatterBase; @@ -2987,13 +2714,13 @@ private: template <typename Impl, typename Char_, typename Spec_> friend class BasicPrintfArgFormatter; -protected: + protected: /** Constructs a ``BasicWriter`` object. */ - explicit BasicWriter(Buffer<Char> &b) : buffer_(b) {} + explicit BasicWriter(Buffer<Char>& b) : buffer_(b) {} -public: + public: /** \rst Destroys a ``BasicWriter`` object. @@ -3004,8 +2731,7 @@ public: /** Returns the total number of characters written. */ - std::size_t size() const - { + std::size_t size() const { return buffer_.size(); } @@ -3013,8 +2739,7 @@ public: Returns a pointer to the output buffer content. No terminating null character is appended. */ - const Char *data() const FMT_NOEXCEPT - { + const Char* data() const FMT_NOEXCEPT { return &buffer_[0]; } @@ -3022,8 +2747,7 @@ public: Returns a pointer to the output buffer content with terminating null character appended. */ - const Char *c_str() const - { + const Char* c_str() const { std::size_t size = buffer_.size(); buffer_.reserve(size + 1); buffer_[size] = '\0'; @@ -3035,8 +2759,7 @@ public: Returns the content of the output buffer as an `std::string`. \endrst */ - std::basic_string<Char> str() const - { + std::basic_string<Char> str() const { return std::basic_string<Char>(&buffer_[0], buffer_.size()); } @@ -3065,32 +2788,26 @@ public: See also :ref:`syntax`. \endrst */ - void write(BasicCStringRef<Char> format, ArgList args) - { + void write(BasicCStringRef<Char> format, ArgList args) { BasicFormatter<Char>(args, *this).format(format); } FMT_VARIADIC_VOID(write, BasicCStringRef<Char>) - BasicWriter &operator<<(int value) - { + BasicWriter& operator<<(int value) { write_decimal(value); return *this; } - BasicWriter &operator<<(unsigned value) - { + BasicWriter& operator<<(unsigned value) { return *this << IntFormatSpec<unsigned>(value); } - BasicWriter &operator<<(long value) - { + BasicWriter& operator<<(long value) { write_decimal(value); return *this; } - BasicWriter &operator<<(unsigned long value) - { + BasicWriter& operator<<(unsigned long value) { return *this << IntFormatSpec<unsigned long>(value); } - BasicWriter &operator<<(LongLong value) - { + BasicWriter& operator<<(LongLong value) { write_decimal(value); return *this; } @@ -3100,13 +2817,11 @@ public: Formats *value* and writes it to the stream. \endrst */ - BasicWriter &operator<<(ULongLong value) - { + BasicWriter& operator<<(ULongLong value) { return *this << IntFormatSpec<ULongLong>(value); } - BasicWriter &operator<<(double value) - { + BasicWriter& operator<<(double value) { write_double(value, FormatSpec()); return *this; } @@ -3117,8 +2832,7 @@ public: (``'g'``) and writes it to the stream. \endrst */ - BasicWriter &operator<<(long double value) - { + BasicWriter& operator<<(long double value) { write_double(value, FormatSpec()); return *this; } @@ -3126,15 +2840,13 @@ public: /** Writes a character to the stream. */ - BasicWriter &operator<<(char value) - { + BasicWriter& operator<<(char value) { buffer_.push_back(value); return *this; } - BasicWriter &operator<<( - typename internal::WCharHelper<wchar_t, Char>::Supported value) - { + BasicWriter& operator<<( + typename internal::WCharHelper<wchar_t, Char>::Supported value) { buffer_.push_back(value); return *this; } @@ -3144,68 +2856,55 @@ public: Writes *value* to the stream. \endrst */ - BasicWriter &operator<<(fmt::BasicStringRef<Char> value) - { - const Char *str = value.data(); + BasicWriter& operator<<(fmt::BasicStringRef<Char> value) { + const Char* str = value.data(); buffer_.append(str, str + value.size()); return *this; } - BasicWriter &operator<<( - typename internal::WCharHelper<StringRef, Char>::Supported value) - { - const char *str = value.data(); + BasicWriter& operator<<( + typename internal::WCharHelper<StringRef, Char>::Supported value) { + const char* str = value.data(); buffer_.append(str, str + value.size()); return *this; } template <typename T, typename Spec, typename FillChar> - BasicWriter &operator<<(IntFormatSpec<T, Spec, FillChar> spec) - { + BasicWriter& operator<<(IntFormatSpec<T, Spec, FillChar> spec) { internal::CharTraits<Char>::convert(FillChar()); write_int(spec.value(), spec); return *this; } template <typename StrChar> - BasicWriter &operator<<(const StrFormatSpec<StrChar> &spec) - { - const StrChar *s = spec.str(); + BasicWriter& operator<<(const StrFormatSpec<StrChar>& spec) { + const StrChar* s = spec.str(); write_str(s, std::char_traits<Char>::length(s), spec); return *this; } void clear() FMT_NOEXCEPT { buffer_.clear(); } - Buffer<Char> &buffer() FMT_NOEXCEPT { return buffer_; } + Buffer<Char>& buffer() FMT_NOEXCEPT { return buffer_; } }; template <typename Char> template <typename StrChar> typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str( - const StrChar *s, std::size_t size, const AlignSpec &spec) -{ + const StrChar* s, std::size_t size, const AlignSpec& spec) { CharPtr out = CharPtr(); - if (spec.width() > size) - { + if (spec.width() > size) { out = grow_buffer(spec.width()); Char fill = internal::CharTraits<Char>::cast(spec.fill()); - if (spec.align() == ALIGN_RIGHT) - { + if (spec.align() == ALIGN_RIGHT) { std::uninitialized_fill_n(out, spec.width() - size, fill); out += spec.width() - size; - } - else if (spec.align() == ALIGN_CENTER) - { + } else if (spec.align() == ALIGN_CENTER) { out = fill_padding(out, spec.width(), size, fill); - } - else - { + } else { std::uninitialized_fill_n(out + size, spec.width() - size, fill); } - } - else - { + } else { out = grow_buffer(size); } std::uninitialized_copy(s, s + size, out); @@ -3215,18 +2914,15 @@ typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str( template <typename Char> template <typename StrChar, typename Spec> void BasicWriter<Char>::write_str( - const internal::Arg::StringValue<StrChar> &s, const Spec &spec) -{ + const internal::Arg::StringValue<StrChar>& s, const Spec& spec) { // Check if StrChar is convertible to Char. internal::CharTraits<Char>::convert(StrChar()); if (spec.type_ && spec.type_ != 's') internal::report_unknown_type(spec.type_, "string"); - const StrChar *str_value = s.value; + const StrChar* str_value = s.value; std::size_t str_size = s.size; - if (str_size == 0) - { - if (!str_value) - { + if (str_size == 0) { + if (!str_value) { FMT_THROW(FormatError("string pointer is null")); } } @@ -3240,8 +2936,7 @@ template <typename Char> typename BasicWriter<Char>::CharPtr BasicWriter<Char>::fill_padding( CharPtr buffer, unsigned total_size, - std::size_t content_size, wchar_t fill) -{ + std::size_t content_size, wchar_t fill) { std::size_t padding = total_size - content_size; std::size_t left_padding = padding / 2; Char fill_char = internal::CharTraits<Char>::cast(fill); @@ -3257,14 +2952,12 @@ template <typename Char> template <typename Spec> typename BasicWriter<Char>::CharPtr BasicWriter<Char>::prepare_int_buffer( - unsigned num_digits, const Spec &spec, - const char *prefix, unsigned prefix_size) -{ + unsigned num_digits, const Spec& spec, + const char* prefix, unsigned prefix_size) { unsigned width = spec.width(); Alignment align = spec.align(); Char fill = internal::CharTraits<Char>::cast(spec.fill()); - if (spec.precision() > static_cast<int>(num_digits)) - { + if (spec.precision() > static_cast<int>(num_digits)) { // Octal prefix '0' is counted as a digit, so ignore it if precision // is specified. if (prefix_size > 0 && prefix[prefix_size - 1] == '0') @@ -3276,53 +2969,41 @@ BasicWriter<Char>::prepare_int_buffer( return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); buffer_.reserve(width); unsigned fill_size = width - number_size; - if (align != ALIGN_LEFT) - { + if (align != ALIGN_LEFT) { 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); - if (align == ALIGN_LEFT) - { + if (align == ALIGN_LEFT) { CharPtr p = grow_buffer(fill_size); std::uninitialized_fill(p, p + fill_size, fill); } return result; } unsigned size = prefix_size + num_digits; - if (width <= size) - { + if (width <= size) { CharPtr p = grow_buffer(size); std::uninitialized_copy(prefix, prefix + prefix_size, p); return p + size - 1; } CharPtr p = grow_buffer(width); CharPtr end = p + width; - if (align == ALIGN_LEFT) - { + if (align == ALIGN_LEFT) { std::uninitialized_copy(prefix, prefix + prefix_size, p); p += size; std::uninitialized_fill(p, end, fill); - } - else if (align == ALIGN_CENTER) - { + } else if (align == ALIGN_CENTER) { p = fill_padding(p, width, size, fill); std::uninitialized_copy(prefix, prefix + prefix_size, p); p += size; - } - else - { - if (align == ALIGN_NUMERIC) - { - if (prefix_size != 0) - { + } else { + if (align == ALIGN_NUMERIC) { + if (prefix_size != 0) { p = std::uninitialized_copy(prefix, prefix + prefix_size, p); size -= prefix_size; } - } - else - { + } else { std::uninitialized_copy(prefix, prefix + prefix_size, end - size); } std::uninitialized_fill(p, end - size, fill); @@ -3333,106 +3014,82 @@ BasicWriter<Char>::prepare_int_buffer( template <typename Char> template <typename T, typename Spec> -void BasicWriter<Char>::write_int(T value, Spec spec) -{ +void BasicWriter<Char>::write_int(T value, Spec spec) { unsigned prefix_size = 0; typedef typename internal::IntTraits<T>::MainType UnsignedType; UnsignedType abs_value = static_cast<UnsignedType>(value); char prefix[4] = ""; - if (internal::is_negative(value)) - { + if (internal::is_negative(value)) { prefix[0] = '-'; ++prefix_size; abs_value = 0 - abs_value; - } - else if (spec.flag(SIGN_FLAG)) - { + } else if (spec.flag(SIGN_FLAG)) { prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' '; ++prefix_size; } - switch (spec.type()) - { + switch (spec.type()) { case 0: - case 'd': - { + case 'd': { unsigned num_digits = internal::count_digits(abs_value); CharPtr p = prepare_int_buffer(num_digits, spec, prefix, prefix_size) + 1; internal::format_decimal(get(p), abs_value, 0); break; } case 'x': - case 'X': - { + case 'X': { UnsignedType n = abs_value; - if (spec.flag(HASH_FLAG)) - { + if (spec.flag(HASH_FLAG)) { prefix[prefix_size++] = '0'; prefix[prefix_size++] = spec.type_prefix(); } unsigned num_digits = 0; - do - { + do { ++num_digits; - } - while ((n >>= 4) != 0); - Char *p = get(prepare_int_buffer( + } 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' ? + const char* digits = spec.type() == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; - do - { + do { *p-- = digits[n & 0xf]; - } - while ((n >>= 4) != 0); + } while ((n >>= 4) != 0); break; } case 'b': - case 'B': - { + case 'B': { UnsignedType n = abs_value; - if (spec.flag(HASH_FLAG)) - { + if (spec.flag(HASH_FLAG)) { prefix[prefix_size++] = '0'; prefix[prefix_size++] = spec.type_prefix(); } unsigned num_digits = 0; - do - { + do { ++num_digits; - } - while ((n >>= 1) != 0); - Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); + } while ((n >>= 1) != 0); + Char* p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; - do - { + do { *p-- = static_cast<Char>('0' + (n & 1)); - } - while ((n >>= 1) != 0); + } while ((n >>= 1) != 0); break; } - case 'o': - { + case 'o': { UnsignedType n = abs_value; if (spec.flag(HASH_FLAG)) prefix[prefix_size++] = '0'; unsigned num_digits = 0; - do - { + do { ++num_digits; - } - while ((n >>= 3) != 0); - Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); + } while ((n >>= 3) != 0); + Char* p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; - do - { + do { *p-- = static_cast<Char>('0' + (n & 7)); - } - while ((n >>= 3) != 0); + } while ((n >>= 3) != 0); break; } - case 'n': - { + case 'n': { unsigned num_digits = internal::count_digits(abs_value); fmt::StringRef sep = ""; #if !(defined(ANDROID) || defined(__ANDROID__)) @@ -3453,13 +3110,11 @@ void BasicWriter<Char>::write_int(T value, Spec spec) template <typename Char> template <typename T, typename Spec> -void BasicWriter<Char>::write_double(T value, const Spec &spec) -{ +void BasicWriter<Char>::write_double(T value, const Spec& spec) { // Check type. char type = spec.type(); bool upper = false; - switch (type) - { + switch (type) { case 0: type = 'g'; break; @@ -3487,24 +3142,19 @@ void BasicWriter<Char>::write_double(T value, const Spec &spec) char sign = 0; // Use isnegative instead of value < 0 because the latter is always // false for NaN. - if (internal::FPUtil::isnegative(static_cast<double>(value))) - { + if (internal::FPUtil::isnegative(static_cast<double>(value))) { sign = '-'; value = -value; - } - else if (spec.flag(SIGN_FLAG)) - { + } else if (spec.flag(SIGN_FLAG)) { sign = spec.flag(PLUS_FLAG) ? '+' : ' '; } - if (internal::FPUtil::isnotanumber(value)) - { + if (internal::FPUtil::isnotanumber(value)) { // Format NaN ourselves because sprintf's output is not consistent // across platforms. std::size_t nan_size = 4; - const char *nan = upper ? " NAN" : " nan"; - if (!sign) - { + const char* nan = upper ? " NAN" : " nan"; + if (!sign) { --nan_size; ++nan; } @@ -3514,14 +3164,12 @@ void BasicWriter<Char>::write_double(T value, const Spec &spec) return; } - if (internal::FPUtil::isinfinity(value)) - { + if (internal::FPUtil::isinfinity(value)) { // Format infinity ourselves because sprintf's output is not consistent // across platforms. std::size_t inf_size = 4; - const char *inf = upper ? " INF" : " inf"; - if (!sign) - { + const char* inf = upper ? " INF" : " inf"; + if (!sign) { --inf_size; ++inf; } @@ -3533,8 +3181,7 @@ void BasicWriter<Char>::write_double(T value, const Spec &spec) std::size_t offset = buffer_.size(); unsigned width = spec.width(); - if (sign) - { + if (sign) { buffer_.reserve(buffer_.size() + (width > 1u ? width : 1u)); if (width > 0) --width; @@ -3544,24 +3191,20 @@ void BasicWriter<Char>::write_double(T value, const Spec &spec) // Build format string. enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg Char format[MAX_FORMAT_SIZE]; - Char *format_ptr = format; + Char* format_ptr = format; *format_ptr++ = '%'; unsigned width_for_sprintf = width; if (spec.flag(HASH_FLAG)) *format_ptr++ = '#'; - if (spec.align() == ALIGN_CENTER) - { + if (spec.align() == ALIGN_CENTER) { width_for_sprintf = 0; - } - else - { + } else { if (spec.align() == ALIGN_LEFT) *format_ptr++ = '-'; if (width != 0) *format_ptr++ = '*'; } - if (spec.precision() >= 0) - { + if (spec.precision() >= 0) { *format_ptr++ = '.'; *format_ptr++ = '*'; } @@ -3573,16 +3216,14 @@ void BasicWriter<Char>::write_double(T value, const Spec &spec) // Format using snprintf. Char fill = internal::CharTraits<Char>::cast(spec.fill()); unsigned n = 0; - Char *start = FMT_NULL; - for (;;) - { + Char* start = FMT_NULL; + for (;;) { std::size_t buffer_size = buffer_.capacity() - offset; #if FMT_MSC_VER // MSVC's vsnprintf_s doesn't work with zero size, so reserve // space for at least one extra character to make the size non-zero. // Note that the buffer's capacity will increase by more than 1. - if (buffer_size == 0) - { + if (buffer_size == 0) { buffer_.reserve(offset + 1); buffer_size = buffer_.capacity() - offset; } @@ -3590,44 +3231,35 @@ void BasicWriter<Char>::write_double(T value, const Spec &spec) start = &buffer_[offset]; int result = internal::CharTraits<Char>::format_float( start, buffer_size, format, width_for_sprintf, spec.precision(), value); - if (result >= 0) - { + if (result >= 0) { n = internal::to_unsigned(result); if (offset + n < buffer_.capacity()) break; // The buffer is large enough - continue with formatting. buffer_.reserve(offset + n + 1); - } - else - { + } else { // If result is negative we ask to increase the capacity by at least 1, // but as std::vector, the buffer grows exponentially. buffer_.reserve(buffer_.capacity() + 1); } } - if (sign) - { + if (sign) { if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || - *start != ' ') - { + *start != ' ') { *(start - 1) = sign; sign = 0; - } - else - { + } else { *(start - 1) = fill; } ++n; } - if (spec.align() == ALIGN_CENTER && spec.width() > n) - { + if (spec.align() == ALIGN_CENTER && spec.width() > n) { width = spec.width(); CharPtr p = grow_buffer(width); std::memmove(get(p) + (width - n) / 2, get(p), n * sizeof(Char)); fill_padding(p, spec.width(), n, fill); return; } - if (spec.fill() != ' ' || sign) - { + if (spec.fill() != ' ' || sign) { while (*start == ' ') *start++ = fill; if (sign) @@ -3671,12 +3303,11 @@ void BasicWriter<Char>::write_double(T value, const Spec &spec) \endrst */ template <typename Char, typename Allocator = std::allocator<Char> > -class BasicMemoryWriter : public BasicWriter<Char> -{ -private: +class BasicMemoryWriter : public BasicWriter<Char> { + private: internal::MemoryBuffer<Char, internal::INLINE_BUFFER_SIZE, Allocator> buffer_; -public: + public: explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) : BasicWriter<Char>(buffer_), buffer_(alloc) {} @@ -3687,9 +3318,8 @@ public: of the other object to it. \endrst */ - BasicMemoryWriter(BasicMemoryWriter &&other) - : BasicWriter<Char>(buffer_), buffer_(std::move(other.buffer_)) - { + BasicMemoryWriter(BasicMemoryWriter&& other) + : BasicWriter<Char>(buffer_), buffer_(std::move(other.buffer_)) { } /** @@ -3697,8 +3327,7 @@ public: Moves the content of the other ``BasicMemoryWriter`` object to this one. \endrst */ - BasicMemoryWriter &operator=(BasicMemoryWriter &&other) - { + BasicMemoryWriter& operator=(BasicMemoryWriter&& other) { buffer_ = std::move(other.buffer_); return *this; } @@ -3729,19 +3358,18 @@ typedef BasicMemoryWriter<wchar_t> WMemoryWriter; \endrst */ template <typename Char> -class BasicArrayWriter : public BasicWriter<Char> -{ -private: +class BasicArrayWriter : public BasicWriter<Char> { + private: internal::FixedBuffer<Char> buffer_; -public: + public: /** \rst Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the given size. \endrst */ - BasicArrayWriter(Char *array, std::size_t size) + BasicArrayWriter(Char* array, std::size_t size) : BasicWriter<Char>(buffer_), buffer_(array, size) {} /** @@ -3766,12 +3394,11 @@ FMT_API void report_system_error(int error_code, #if FMT_USE_WINDOWS_H /** A Windows error. */ -class WindowsError : public SystemError -{ -private: +class WindowsError : public SystemError { + private: FMT_API void init(int error_code, CStringRef format_str, ArgList args); -public: + public: /** \rst Constructs a :class:`fmt::WindowsError` object with the description @@ -3800,8 +3427,7 @@ public: } \endrst */ - WindowsError(int error_code, CStringRef message) - { + WindowsError(int error_code, CStringRef message) { init(error_code, message, ArgList()); } FMT_VARIADIC_CTOR(WindowsError, init, int, CStringRef) @@ -3833,15 +3459,13 @@ FMT_API void print_colored(Color c, CStringRef format, ArgList args); std::string message = format("The answer is {}", 42); \endrst */ -inline std::string format(CStringRef format_str, ArgList args) -{ +inline std::string format(CStringRef format_str, ArgList args) { MemoryWriter w; w.write(format_str, args); return w.str(); } -inline std::wstring format(WCStringRef format_str, ArgList args) -{ +inline std::wstring format(WCStringRef format_str, ArgList args) { WMemoryWriter w; w.write(format_str, args); return w.str(); @@ -3856,7 +3480,7 @@ inline std::wstring format(WCStringRef format_str, ArgList args) print(stderr, "Don't {}!", "panic"); \endrst */ -FMT_API void print(std::FILE *f, CStringRef format_str, ArgList args); +FMT_API void print(std::FILE* f, CStringRef format_str, ArgList args); /** \rst @@ -3872,21 +3496,18 @@ FMT_API void print(CStringRef format_str, ArgList args); /** Fast integer formatter. */ -class FormatInt -{ -private: +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<ULongLong>::digits10 + 3}; mutable char buffer_[BUFFER_SIZE]; - char *str_; + char* str_; // Formats value in reverse and returns the number of digits. - char *format_decimal(ULongLong value) - { - char *buffer_end = buffer_ + BUFFER_SIZE - 1; - while (value >= 100) - { + char* format_decimal(ULongLong value) { + char* buffer_end = buffer_ + BUFFER_SIZE - 1; + while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. @@ -3895,8 +3516,7 @@ private: *--buffer_end = internal::Data::DIGITS[index + 1]; *--buffer_end = internal::Data::DIGITS[index]; } - if (value < 10) - { + if (value < 10) { *--buffer_end = static_cast<char>('0' + value); return buffer_end; } @@ -3906,8 +3526,7 @@ private: return buffer_end; } - void FormatSigned(LongLong value) - { + void FormatSigned(LongLong value) { ULongLong abs_value = static_cast<ULongLong>(value); bool negative = value < 0; if (negative) @@ -3917,17 +3536,14 @@ private: *--str_ = '-'; } -public: - explicit FormatInt(int value) - { + public: + explicit FormatInt(int value) { FormatSigned(value); } - explicit FormatInt(long value) - { + explicit FormatInt(long value) { FormatSigned(value); } - explicit FormatInt(LongLong value) - { + explicit FormatInt(LongLong value) { FormatSigned(value); } explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} @@ -3935,8 +3551,7 @@ public: explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} /** Returns the number of characters written to the output buffer. */ - std::size_t size() const - { + std::size_t size() const { return internal::to_unsigned(buffer_ - str_ + BUFFER_SIZE - 1); } @@ -3944,8 +3559,7 @@ public: Returns a pointer to the output buffer content. No terminating null character is appended. */ - const char *data() const - { + const char* data() const { return str_; } @@ -3953,8 +3567,7 @@ public: Returns a pointer to the output buffer content with terminating null character appended. */ - const char *c_str() const - { + const char* c_str() const { buffer_[BUFFER_SIZE - 1] = '\0'; return str_; } @@ -3964,8 +3577,7 @@ public: Returns the content of the output buffer as an ``std::string``. \endrst */ - std::string str() const - { + std::string str() const { return std::string(str_, size()); } }; @@ -3974,19 +3586,15 @@ public: // a pointer to the end of the formatted string. This function doesn't // write a terminating null character. template <typename T> -inline void format_decimal(char *&buffer, T value) -{ +inline void format_decimal(char*& buffer, T value) { typedef typename internal::IntTraits<T>::MainType MainType; MainType abs_value = static_cast<MainType>(value); - if (internal::is_negative(value)) - { + if (internal::is_negative(value)) { *buffer++ = '-'; abs_value = 0 - abs_value; } - if (abs_value < 100) - { - if (abs_value < 10) - { + if (abs_value < 100) { + if (abs_value < 10) { *buffer++ = static_cast<char>('0' + abs_value); return; } @@ -4011,14 +3619,12 @@ inline void format_decimal(char *&buffer, T value) \endrst */ template <typename T> -inline internal::NamedArgWithType<char, T> arg(StringRef name, const T &arg) -{ +inline internal::NamedArgWithType<char, T> arg(StringRef name, const T& arg) { return internal::NamedArgWithType<char, T>(name, arg); } template <typename T> -inline internal::NamedArgWithType<wchar_t, T> arg(WStringRef name, const T &arg) -{ +inline internal::NamedArgWithType<wchar_t, T> arg(WStringRef name, const T& arg) { return internal::NamedArgWithType<wchar_t, T>(name, arg); } @@ -4156,41 +3762,34 @@ void arg(WStringRef, const internal::NamedArg<Char>&) 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, std::FILE*, CStringRef) FMT_VARIADIC(void, print_colored, Color, CStringRef) -namespace internal -{ +namespace internal { template <typename Char> -inline bool is_name_start(Char c) -{ +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 <typename Char> -unsigned parse_nonnegative_int(const Char *&s) -{ +unsigned parse_nonnegative_int(const Char*& s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; - do - { + do { unsigned new_value = value * 10 + (*s++ - '0'); // Check if value wrapped around. - if (new_value < value) - { + if (new_value < value) { value = (std::numeric_limits<unsigned>::max)(); break; } value = new_value; - } - while ('0' <= *s && *s <= '9'); + } while ('0' <= *s && *s <= '9'); // Convert to unsigned to prevent a warning. unsigned max_int = (std::numeric_limits<int>::max)(); if (value > max_int) @@ -4198,10 +3797,8 @@ unsigned parse_nonnegative_int(const Char *&s) return value; } -inline void require_numeric_argument(const Arg &arg, char spec) -{ - if (arg.type > Arg::LAST_NUMERIC_TYPE) - { +inline void require_numeric_argument(const Arg& arg, char spec) { + if (arg.type > Arg::LAST_NUMERIC_TYPE) { std::string message = fmt::format("format specifier '{}' requires numeric argument", spec); FMT_THROW(fmt::FormatError(message)); @@ -4209,12 +3806,10 @@ inline void require_numeric_argument(const Arg &arg, char spec) } template <typename Char> -void check_sign(const Char *&s, const Arg &arg) -{ +void check_sign(const Char*& s, const Arg& arg) { char sign = static_cast<char>(*s); require_numeric_argument(arg, sign); - if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) - { + if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { FMT_THROW(FormatError(fmt::format( "format specifier '{}' requires signed argument", sign))); } @@ -4224,12 +3819,10 @@ void check_sign(const Char *&s, const Arg &arg) template <typename Char, typename AF> inline internal::Arg BasicFormatter<Char, AF>::get_arg( - BasicStringRef<Char> arg_name, const char *&error) -{ - if (check_no_auto_index(error)) - { + BasicStringRef<Char> arg_name, const char*& error) { + if (check_no_auto_index(error)) { map_.init(args()); - const internal::Arg *arg = map_.find(arg_name); + const internal::Arg* arg = map_.find(arg_name); if (arg) return *arg; error = "argument not found"; @@ -4238,13 +3831,11 @@ inline internal::Arg BasicFormatter<Char, AF>::get_arg( } template <typename Char, typename AF> -inline internal::Arg BasicFormatter<Char, AF>::parse_arg_index(const Char *&s) -{ - const char *error = FMT_NULL; +inline internal::Arg BasicFormatter<Char, AF>::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); - if (error) - { + if (error) { FMT_THROW(FormatError( *s != '}' && *s != ':' ? "invalid format string" : error)); } @@ -4252,17 +3843,14 @@ inline internal::Arg BasicFormatter<Char, AF>::parse_arg_index(const Char *&s) } template <typename Char, typename AF> -inline internal::Arg BasicFormatter<Char, AF>::parse_arg_name(const Char *&s) -{ +inline internal::Arg BasicFormatter<Char, AF>::parse_arg_name(const Char*& s) { assert(internal::is_name_start(*s)); - const Char *start = s; + const Char* start = s; Char c; - do - { + do { c = *++s; - } - while (internal::is_name_start(c) || ('0' <= c && c <= '9')); - const char *error = FMT_NULL; + } while (internal::is_name_start(c) || ('0' <= c && c <= '9')); + const char* error = FMT_NULL; internal::Arg arg = get_arg(BasicStringRef<Char>(start, s - start), error); if (error) FMT_THROW(FormatError(error)); @@ -4270,29 +3858,23 @@ inline internal::Arg BasicFormatter<Char, AF>::parse_arg_name(const Char *&s) } template <typename Char, typename ArgFormatter> -const Char *BasicFormatter<Char, ArgFormatter>::format( - const Char *&format_str, const internal::Arg &arg) -{ +const Char* BasicFormatter<Char, ArgFormatter>::format( + const Char*& format_str, const internal::Arg& arg) { using internal::Arg; - const Char *s = format_str; + const Char* s = format_str; typename ArgFormatter::SpecType spec; - if (*s == ':') - { - if (arg.type == Arg::CUSTOM) - { + if (*s == ':') { + if (arg.type == Arg::CUSTOM) { arg.custom.format(this, arg.custom.value, &s); return s; } ++s; // Parse fill and alignment. - if (Char c = *s) - { - const Char *p = s + 1; + if (Char c = *s) { + const Char* p = s + 1; spec.align_ = ALIGN_DEFAULT; - do - { - switch (*p) - { + do { + switch (*p) { case '<': spec.align_ = ALIGN_LEFT; break; @@ -4306,28 +3888,23 @@ const Char *BasicFormatter<Char, ArgFormatter>::format( spec.align_ = ALIGN_CENTER; break; } - if (spec.align_ != ALIGN_DEFAULT) - { - if (p != s) - { + if (spec.align_ != ALIGN_DEFAULT) { + if (p != s) { if (c == '}') break; if (c == '{') FMT_THROW(FormatError("invalid fill character '{'")); s += 2; spec.fill_ = c; - } - else ++s; + } else ++s; if (spec.align_ == ALIGN_NUMERIC) require_numeric_argument(arg, '='); break; } - } - while (--p >= s); + } while (--p >= s); } // Parse sign. - switch (*s) - { + switch (*s) { case '+': check_sign(s, arg); spec.flags_ |= SIGN_FLAG | PLUS_FLAG; @@ -4342,16 +3919,14 @@ const Char *BasicFormatter<Char, ArgFormatter>::format( break; } - if (*s == '#') - { + if (*s == '#') { require_numeric_argument(arg, '#'); spec.flags_ |= HASH_FLAG; ++s; } // Parse zero flag. - if (*s == '0') - { + if (*s == '0') { require_numeric_argument(arg, '0'); spec.align_ = ALIGN_NUMERIC; spec.fill_ = '0'; @@ -4359,20 +3934,16 @@ const Char *BasicFormatter<Char, ArgFormatter>::format( } // Parse width. - if ('0' <= *s && *s <= '9') - { + if ('0' <= *s && *s <= '9') { spec.width_ = internal::parse_nonnegative_int(s); - } - else if (*s == '{') - { + } else if (*s == '{') { ++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; - switch (width_arg.type) - { + switch (width_arg.type) { case Arg::INT: if (width_arg.int_value < 0) FMT_THROW(FormatError("negative width")); @@ -4398,24 +3969,19 @@ const Char *BasicFormatter<Char, ArgFormatter>::format( } // Parse precision. - if (*s == '.') - { + if (*s == '.') { ++s; spec.precision_ = 0; - if ('0' <= *s && *s <= '9') - { + if ('0' <= *s && *s <= '9') { spec.precision_ = internal::parse_nonnegative_int(s); - } - else if (*s == '{') - { + } else if (*s == '{') { ++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; - switch (precision_arg.type) - { + switch (precision_arg.type) { case Arg::INT: if (precision_arg.int_value < 0) FMT_THROW(FormatError("negative precision")); @@ -4438,13 +4004,10 @@ const Char *BasicFormatter<Char, ArgFormatter>::format( if (value > (std::numeric_limits<int>::max)()) FMT_THROW(FormatError("number is too big")); spec.precision_ = static_cast<int>(value); - } - else - { + } else { FMT_THROW(FormatError("missing precision specifier")); } - if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) - { + 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"))); @@ -4465,16 +4028,13 @@ const Char *BasicFormatter<Char, ArgFormatter>::format( } template <typename Char, typename AF> -void BasicFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) -{ - const Char *s = format_str.c_str(); - const Char *start = s; - while (*s) - { +void BasicFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) { + const Char* s = format_str.c_str(); + const Char* start = s; + while (*s) { Char c = *s++; if (c != '{' && c != '}') continue; - if (*s == c) - { + if (*s == c) { write(writer_, start, s); start = ++s; continue; @@ -4490,8 +4050,7 @@ void BasicFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) } template <typename Char, typename It> -struct ArgJoin -{ +struct ArgJoin { It first; It last; BasicCStringRef<Char> sep; @@ -4503,37 +4062,32 @@ struct ArgJoin }; template <typename It> -ArgJoin<char, It> join(It first, It last, const BasicCStringRef<char>& sep) -{ +ArgJoin<char, It> join(It first, It last, const BasicCStringRef<char>& sep) { return ArgJoin<char, It>(first, last, sep); } template <typename It> -ArgJoin<wchar_t, It> join(It first, It last, const BasicCStringRef<wchar_t>& sep) -{ +ArgJoin<wchar_t, It> join(It first, It last, const BasicCStringRef<wchar_t>& sep) { return ArgJoin<wchar_t, It>(first, last, sep); } #if FMT_HAS_GXX_CXX11 template <typename Range> auto join(const Range& range, const BasicCStringRef<char>& sep) --> ArgJoin<char, decltype(std::begin(range))> -{ +-> ArgJoin<char, decltype(std::begin(range))> { return join(std::begin(range), std::end(range), sep); } template <typename Range> auto join(const Range& range, const BasicCStringRef<wchar_t>& sep) --> ArgJoin<wchar_t, decltype(std::begin(range))> -{ +-> ArgJoin<wchar_t, decltype(std::begin(range))> { return join(std::begin(range), std::end(range), sep); } #endif template <typename ArgFormatter, typename Char, typename It> -void format_arg(fmt::BasicFormatter<Char, ArgFormatter> &f, - const Char *&format_str, const ArgJoin<Char, It>& e) -{ +void format_arg(fmt::BasicFormatter<Char, ArgFormatter>& f, + const Char*& format_str, const ArgJoin<Char, It>& e) { const Char* end = format_str; if (*end == ':') ++end; @@ -4543,12 +4097,10 @@ void format_arg(fmt::BasicFormatter<Char, ArgFormatter> &f, FMT_THROW(FormatError("missing '}' in format string")); It it = e.first; - if (it != e.last) - { + if (it != e.last) { const Char* save = format_str; f.format(format_str, internal::MakeArg<fmt::BasicFormatter<Char, ArgFormatter> >(*it++)); - while (it != e.last) - { + while (it != e.last) { f.writer().write(e.sep); format_str = save; f.format(format_str, internal::MakeArg<fmt::BasicFormatter<Char, ArgFormatter> >(*it++)); @@ -4559,40 +4111,33 @@ void format_arg(fmt::BasicFormatter<Char, ArgFormatter> &f, } // namespace fmt #if FMT_USE_USER_DEFINED_LITERALS -namespace fmt -{ -namespace internal -{ +namespace fmt { +namespace internal { template <typename Char> -struct UdlFormat -{ - const Char *str; +struct UdlFormat { + const Char* str; template <typename... Args> - auto operator()(Args && ... args) const - -> decltype(format(str, std::forward<Args>(args)...)) - { + auto operator()(Args&& ... args) const + -> decltype(format(str, std::forward<Args>(args)...)) { return format(str, std::forward<Args>(args)...); } }; template <typename Char> -struct UdlArg -{ - const Char *str; +struct UdlArg { + const Char* str; template <typename T> - NamedArgWithType<Char, T> operator=(T &&value) const - { + NamedArgWithType<Char, T> operator=(T&& value) const { return {str, std::forward<T>(value)}; } }; } // namespace internal -inline namespace literals -{ +inline namespace literals { /** \rst @@ -4605,13 +4150,11 @@ inline namespace literals \endrst */ inline internal::UdlFormat<char> -operator"" _format(const char *s, std::size_t) -{ +operator"" _format(const char* s, std::size_t) { return {s}; } inline internal::UdlFormat<wchar_t> -operator"" _format(const wchar_t *s, std::size_t) -{ +operator"" _format(const wchar_t* s, std::size_t) { return {s}; } @@ -4626,13 +4169,11 @@ operator"" _format(const wchar_t *s, std::size_t) \endrst */ inline internal::UdlArg<char> -operator"" _a(const char *s, std::size_t) -{ +operator"" _a(const char* s, std::size_t) { return {s}; } inline internal::UdlArg<wchar_t> -operator"" _a(const wchar_t *s, std::size_t) -{ +operator"" _a(const wchar_t* s, std::size_t) { return {s}; } diff --git a/3d_party/spd_log/include/spdlog/fmt/bundled/ostream.h b/3d_party/spd_log/include/spdlog/fmt/bundled/ostream.h index cfb8e035561733597f3f31aa2bffe7c4273f4389..896ae50f0c63d25230b6e10f574bf1702f4a68a9 100644 --- a/3d_party/spd_log/include/spdlog/fmt/bundled/ostream.h +++ b/3d_party/spd_log/include/spdlog/fmt/bundled/ostream.h @@ -13,25 +13,22 @@ #include "format.h" #include <ostream> -namespace fmt -{ +namespace fmt { -namespace internal -{ +namespace internal { template <class Char> -class FormatBuf : public std::basic_streambuf<Char> -{ -private: +class FormatBuf : public std::basic_streambuf<Char> { + private: typedef typename std::basic_streambuf<Char>::int_type int_type; typedef typename std::basic_streambuf<Char>::traits_type traits_type; - Buffer<Char> &buffer_; + Buffer<Char>& buffer_; -public: - FormatBuf(Buffer<Char> &buffer) : buffer_(buffer) {} + public: + FormatBuf(Buffer<Char>& buffer) : buffer_(buffer) {} -protected: + protected: // The put-area is actually always empty. This makes the implementation // simpler and has the advantage that the streambuf and the buffer are always // in sync and sputc never writes into uninitialized memory. The obvious @@ -39,50 +36,44 @@ protected: // to overflow. There is no disadvantage here for sputn since this always // results in a call to xsputn. - int_type overflow(int_type ch = traits_type::eof()) FMT_OVERRIDE - { + int_type overflow(int_type ch = traits_type::eof()) FMT_OVERRIDE { if (!traits_type::eq_int_type(ch, traits_type::eof())) buffer_.push_back(static_cast<Char>(ch)); return ch; } - std::streamsize xsputn(const Char *s, std::streamsize count) FMT_OVERRIDE - { + std::streamsize xsputn(const Char* s, std::streamsize count) FMT_OVERRIDE { buffer_.append(s, s + count); return count; } }; -Yes &convert(std::ostream &); +Yes& convert(std::ostream&); -struct DummyStream : std::ostream -{ +struct DummyStream : std::ostream { DummyStream(); // Suppress a bogus warning in MSVC. // Hide all operator<< overloads from std::ostream. void operator<<(Null<>); }; -No &operator<<(std::ostream &, int); +No& operator<<(std::ostream&, int); template<typename T> -struct ConvertToIntImpl<T, true> -{ +struct ConvertToIntImpl<T, true> { // Convert to int only if T doesn't have an overloaded operator<<. - enum - { + enum { value = sizeof(convert(get<DummyStream>() << get<T>())) == sizeof(No) }; }; // Write the content of w to os. -FMT_API void write(std::ostream &os, Writer &w); +FMT_API void write(std::ostream& os, Writer& w); } // namespace internal // Formats a value. template <typename Char, typename ArgFormatter_, typename T> -void format_arg(BasicFormatter<Char, ArgFormatter_> &f, - const Char *&format_str, const T &value) -{ +void format_arg(BasicFormatter<Char, ArgFormatter_>& f, + const Char*& format_str, const T& value) { internal::MemoryBuffer<Char, internal::INLINE_BUFFER_SIZE> buffer; internal::FormatBuf<Char> format_buf(buffer); @@ -103,8 +94,8 @@ void format_arg(BasicFormatter<Char, ArgFormatter_> &f, print(cerr, "Don't {}!", "panic"); \endrst */ -FMT_API void print(std::ostream &os, CStringRef format_str, ArgList args); -FMT_VARIADIC(void, print, std::ostream &, CStringRef) +FMT_API void print(std::ostream& os, CStringRef format_str, ArgList args); +FMT_VARIADIC(void, print, std::ostream&, CStringRef) } // namespace fmt #ifdef FMT_HEADER_ONLY diff --git a/3d_party/spd_log/include/spdlog/fmt/bundled/posix.h b/3d_party/spd_log/include/spdlog/fmt/bundled/posix.h index 693272500341d681e570108fbd3fa37092e52cf2..34b1fc5913df5ee2d320c94bcdb0abf53de6f9bf 100644 --- a/3d_party/spd_log/include/spdlog/fmt/bundled/posix.h +++ b/3d_party/spd_log/include/spdlog/fmt/bundled/posix.h @@ -64,38 +64,34 @@ #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) -namespace fmt -{ +namespace fmt { // An error code. -class ErrorCode -{ -private: +class ErrorCode { + private: int value_; -public: -explicit ErrorCode(int value = 0) FMT_NOEXCEPT : + public: + explicit ErrorCode(int value = 0) FMT_NOEXCEPT : value_(value) {} - int get() const FMT_NOEXCEPT - { + int get() const FMT_NOEXCEPT { return value_; } }; // A buffered file. -class BufferedFile -{ -private: - FILE *file_; +class BufferedFile { + private: + FILE* file_; friend class File; - explicit BufferedFile(FILE *f) : file_(f) {} + explicit BufferedFile(FILE* f) : file_(f) {} -public: + public: // Constructs a BufferedFile object which doesn't represent any file. -BufferedFile() FMT_NOEXCEPT : + BufferedFile() FMT_NOEXCEPT : file_(FMT_NULL) {} // Destroys the object closing the file it represents if any. @@ -105,37 +101,33 @@ BufferedFile() FMT_NOEXCEPT : // Emulate a move constructor and a move assignment operator if rvalue // references are not supported. -private: + private: // A proxy object to emulate a move constructor. // It is private to make it impossible call operator Proxy directly. - struct Proxy - { - FILE *file; + struct Proxy { + FILE* file; }; -public: + public: // A "move constructor" for moving from a temporary. -BufferedFile(Proxy p) FMT_NOEXCEPT : + 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; } // A "move assignment operator" for moving from a temporary. - BufferedFile &operator=(Proxy p) - { + BufferedFile& operator=(Proxy p) { close(); file_ = p.file; return *this; } // A "move assignment operator" for moving from an lvalue. - BufferedFile &operator=(BufferedFile &other) - { + BufferedFile& operator=(BufferedFile& other) { close(); file_ = other.file_; other.file_ = FMT_NULL; @@ -144,26 +136,23 @@ BufferedFile(BufferedFile &f) FMT_NOEXCEPT : // Returns a proxy object for moving from a temporary: // BufferedFile file = BufferedFile(...); - operator Proxy() FMT_NOEXCEPT - { + operator Proxy() FMT_NOEXCEPT { Proxy p = {file_}; file_ = FMT_NULL; return p; } #else -private: + private: FMT_DISALLOW_COPY_AND_ASSIGN(BufferedFile); -public: -BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : - file_(other.file_) - { + public: + BufferedFile(BufferedFile&& other) FMT_NOEXCEPT : + file_(other.file_) { other.file_ = FMT_NULL; } - BufferedFile& operator=(BufferedFile &&other) - { + BufferedFile& operator=(BufferedFile&& other) { close(); file_ = other.file_; other.file_ = FMT_NULL; @@ -178,8 +167,7 @@ BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : FMT_API void close(); // Returns the pointer to a FILE object representing this file. - FILE *get() const FMT_NOEXCEPT - { + FILE* get() const FMT_NOEXCEPT { return file_; } @@ -187,8 +175,7 @@ BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : // of MinGW that define fileno as a macro. FMT_API int (fileno)() const; - void print(CStringRef format_str, const ArgList &args) - { + void print(CStringRef format_str, const ArgList& args) { fmt::print(file_, format_str, args); } FMT_VARIADIC(void, print, CStringRef) @@ -200,25 +187,23 @@ BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : // closing the file multiple times will cause a crash on Windows rather // than an exception. You can get standard behavior by overriding the // invalid parameter handler with _set_invalid_parameter_handler. -class File -{ -private: +class File { + private: int fd_; // File descriptor. // Constructs a File object with a given descriptor. explicit File(int fd) : fd_(fd) {} -public: + public: // Possible values for the oflag argument to the constructor. - enum - { + enum { RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. }; // Constructs a File object which doesn't represent any file. -File() FMT_NOEXCEPT : + File() FMT_NOEXCEPT : fd_(-1) {} // Opens a file and constructs a File object representing this file. @@ -228,37 +213,33 @@ File() FMT_NOEXCEPT : // Emulate a move constructor and a move assignment operator if rvalue // references are not supported. -private: + private: // A proxy object to emulate a move constructor. // It is private to make it impossible call operator Proxy directly. - struct Proxy - { + struct Proxy { int fd; }; -public: + public: // A "move constructor" for moving from a temporary. -File(Proxy p) FMT_NOEXCEPT : + 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; } // A "move assignment operator" for moving from a temporary. - File &operator=(Proxy p) - { + File& operator=(Proxy p) { close(); fd_ = p.fd; return *this; } // A "move assignment operator" for moving from an lvalue. - File &operator=(File &other) - { + File& operator=(File& other) { close(); fd_ = other.fd_; other.fd_ = -1; @@ -267,26 +248,23 @@ File(File &other) FMT_NOEXCEPT : // Returns a proxy object for moving from a temporary: // File file = File(...); - operator Proxy() FMT_NOEXCEPT - { + operator Proxy() FMT_NOEXCEPT { Proxy p = {fd_}; fd_ = -1; return p; } #else -private: + private: FMT_DISALLOW_COPY_AND_ASSIGN(File); -public: -File(File &&other) FMT_NOEXCEPT : - fd_(other.fd_) - { + public: + File(File&& other) FMT_NOEXCEPT : + fd_(other.fd_) { other.fd_ = -1; } - File& operator=(File &&other) - { + File& operator=(File&& other) { close(); fd_ = other.fd_; other.fd_ = -1; @@ -298,8 +276,7 @@ File(File &&other) FMT_NOEXCEPT : FMT_API ~File() FMT_NOEXCEPT; // Returns the file descriptor. - int descriptor() const FMT_NOEXCEPT - { + int descriptor() const FMT_NOEXCEPT { return fd_; } @@ -311,10 +288,10 @@ File(File &&other) FMT_NOEXCEPT : FMT_API LongLong size() const; // Attempts to read count bytes from the file into the specified buffer. - FMT_API std::size_t read(void *buffer, std::size_t count); + FMT_API std::size_t read(void* buffer, std::size_t count); // Attempts to write count bytes from the specified buffer to the file. - FMT_API std::size_t write(const void *buffer, std::size_t count); + FMT_API std::size_t write(const void* buffer, std::size_t count); // Duplicates a file descriptor with the dup function and returns // the duplicate as a file object. @@ -326,15 +303,15 @@ File(File &&other) FMT_NOEXCEPT : // Makes fd be the copy of this file descriptor, closing fd first if // necessary. - FMT_API void dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT; + FMT_API void dup2(int fd, ErrorCode& ec) FMT_NOEXCEPT; // Creates a pipe setting up read_end and write_end file objects for reading // and writing respectively. - FMT_API static void pipe(File &read_end, File &write_end); + FMT_API static void pipe(File& read_end, File& write_end); // Creates a BufferedFile object associated with this file and detaches // this File object from the file. - FMT_API BufferedFile fdopen(const char *mode); + FMT_API BufferedFile fdopen(const char* mode); }; // Returns the memory page size. @@ -347,26 +324,22 @@ long getpagesize(); #ifdef FMT_LOCALE // A "C" numeric locale. -class Locale -{ -private: +class Locale { + private: # ifdef _MSC_VER typedef _locale_t locale_t; enum { LC_NUMERIC_MASK = LC_NUMERIC }; - static locale_t newlocale(int category_mask, const char *locale, locale_t) - { + static locale_t newlocale(int category_mask, const char* locale, locale_t) { return _create_locale(category_mask, locale); } - static void freelocale(locale_t locale) - { + static void freelocale(locale_t locale) { _free_locale(locale); } - static double strtod_l(const char *nptr, char **endptr, _locale_t locale) - { + static double strtod_l(const char* nptr, char** endptr, _locale_t locale) { return _strtod_l(nptr, endptr, locale); } # endif @@ -375,29 +348,25 @@ private: FMT_DISALLOW_COPY_AND_ASSIGN(Locale); -public: + 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")); } - ~Locale() - { + ~Locale() { freelocale(locale_); } - Type get() const - { + Type get() const { return locale_; } // Converts string to floating-point number and advances str past the end // of the parsed input. - double strtod(const char *&str) const - { - char *end = FMT_NULL; + double strtod(const char*& str) const { + char* end = FMT_NULL; double result = strtod_l(str, &end, locale_); str = end; return result; @@ -407,15 +376,12 @@ public: } // namespace fmt #if !FMT_USE_RVALUE_REFERENCES -namespace std -{ +namespace std { // For compatibility with C++98. -inline fmt::BufferedFile &move(fmt::BufferedFile &f) -{ +inline fmt::BufferedFile& move(fmt::BufferedFile& f) { return f; } -inline fmt::File &move(fmt::File &f) -{ +inline fmt::File& move(fmt::File& f) { return f; } } diff --git a/3d_party/spd_log/include/spdlog/fmt/bundled/printf.h b/3d_party/spd_log/include/spdlog/fmt/bundled/printf.h index 7861b460e4bcf5bcd6827a6c9510478d4a57bee4..c3a7346c06e5ceb6ab80fd5924c4675e5d63ba1d 100644 --- a/3d_party/spd_log/include/spdlog/fmt/bundled/printf.h +++ b/3d_party/spd_log/include/spdlog/fmt/bundled/printf.h @@ -15,54 +15,43 @@ #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 <bool IsSigned> -struct IntChecker -{ +struct IntChecker { template <typename T> - static bool fits_in_int(T value) - { + static bool fits_in_int(T value) { unsigned max = std::numeric_limits<int>::max(); return value <= max; } - static bool fits_in_int(bool) - { + static bool fits_in_int(bool) { return true; } }; template <> -struct IntChecker<true> -{ +struct IntChecker<true> { template <typename T> - static bool fits_in_int(T value) - { + static bool fits_in_int(T value) { return value >= std::numeric_limits<int>::min() && value <= std::numeric_limits<int>::max(); } - static bool fits_in_int(int) - { + static bool fits_in_int(int) { return true; } }; -class PrecisionHandler : public ArgVisitor<PrecisionHandler, int> -{ -public: - void report_unhandled_arg() - { +class PrecisionHandler : public ArgVisitor<PrecisionHandler, int> { + public: + void report_unhandled_arg() { FMT_THROW(FormatError("precision is not integer")); } template <typename T> - int visit_any_int(T value) - { + int visit_any_int(T value) { if (!IntChecker<std::numeric_limits<T>::is_signed>::fits_in_int(value)) FMT_THROW(FormatError("number is too big")); return static_cast<int>(value); @@ -70,62 +59,51 @@ public: }; // IsZeroInt::visit(arg) returns true iff arg is a zero integer. -class IsZeroInt : public ArgVisitor<IsZeroInt, bool> -{ -public: +class IsZeroInt : public ArgVisitor<IsZeroInt, bool> { + public: template <typename T> - bool visit_any_int(T value) - { + bool visit_any_int(T value) { return value == 0; } }; // returns the default type for format specific "%s" -class DefaultType : public ArgVisitor<DefaultType, char> -{ -public: - char visit_char(int) - { +class DefaultType : public ArgVisitor<DefaultType, char> { + public: + char visit_char(int) { return 'c'; } - char visit_bool(bool) - { + char visit_bool(bool) { return 's'; } - char visit_pointer(const void *) - { + char visit_pointer(const void*) { return 'p'; } template <typename T> - char visit_any_int(T) - { + char visit_any_int(T) { return 'd'; } template <typename T> - char visit_any_double(T) - { + char visit_any_double(T) { return 'g'; } - char visit_unhandled_arg() - { + char visit_unhandled_arg() { return 's'; } }; template <typename T, typename U> -struct is_same -{ +struct is_same { enum { value = 0 }; }; template <typename T> -struct is_same<T, T> -{ +struct is_same<T, T> { enum { value = 1 }; }; @@ -134,69 +112,55 @@ struct is_same<T, T> // corresponding signed or unsigned type depending on the type specifier: // 'd' and 'i' - signed, other - unsigned) template <typename T = void> -class ArgConverter : public ArgVisitor<ArgConverter<T>, void> -{ -private: - internal::Arg &arg_; +class ArgConverter : public ArgVisitor<ArgConverter<T>, void> { + private: + internal::Arg& arg_; wchar_t type_; FMT_DISALLOW_COPY_AND_ASSIGN(ArgConverter); -public: - ArgConverter(internal::Arg &arg, wchar_t type) + public: + ArgConverter(internal::Arg& arg, wchar_t type) : arg_(arg), type_(type) {} - void visit_bool(bool value) - { + void visit_bool(bool value) { if (type_ != 's') visit_any_int(value); } - void visit_char(char value) - { + void visit_char(char value) { if (type_ != 's') visit_any_int(value); } template <typename U> - void visit_any_int(U value) - { + void visit_any_int(U value) { bool is_signed = type_ == 'd' || type_ == 'i'; - if (type_ == 's') - { + if (type_ == 's') { is_signed = std::numeric_limits<U>::is_signed; } using internal::Arg; - typedef typename internal::Conditional< - is_same<T, void>::value, U, T>::type TargetType; - if (sizeof(TargetType) <= sizeof(int)) - { + typedef typename internal::Conditional < + is_same<T, void>::value, U, T >::type TargetType; + if (sizeof(TargetType) <= sizeof(int)) { // Extra casts are used to silence warnings. - if (is_signed) - { + if (is_signed) { arg_.type = Arg::INT; arg_.int_value = static_cast<int>(static_cast<TargetType>(value)); - } - else - { + } else { arg_.type = Arg::UINT; typedef typename internal::MakeUnsigned<TargetType>::Type Unsigned; arg_.uint_value = static_cast<unsigned>(static_cast<Unsigned>(value)); } - } - else - { - if (is_signed) - { + } else { + if (is_signed) { arg_.type = Arg::LONG_LONG; // glibc's printf doesn't sign extend arguments of smaller types: // std::printf("%lld", -42); // prints "4294967254" // but we don't have to do the same because it's a UB. arg_.long_long_value = static_cast<LongLong>(value); - } - else - { + } else { arg_.type = Arg::ULONG_LONG; arg_.ulong_long_value = static_cast<typename internal::MakeUnsigned<U>::Type>(value); @@ -206,19 +170,17 @@ public: }; // Converts an integer argument to char for printf. -class CharConverter : public ArgVisitor<CharConverter, void> -{ -private: - internal::Arg &arg_; +class CharConverter : public ArgVisitor<CharConverter, void> { + private: + internal::Arg& arg_; FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter); -public: - explicit CharConverter(internal::Arg &arg) : arg_(arg) {} + public: + explicit CharConverter(internal::Arg& arg) : arg_(arg) {} template <typename T> - void visit_any_int(T value) - { + void visit_any_int(T value) { arg_.type = internal::Arg::CHAR; arg_.int_value = static_cast<char>(value); } @@ -226,28 +188,24 @@ public: // Checks if an argument is a valid printf width specifier and sets // left alignment if it is negative. -class WidthHandler : public ArgVisitor<WidthHandler, unsigned> -{ -private: - FormatSpec &spec_; +class WidthHandler : public ArgVisitor<WidthHandler, unsigned> { + private: + FormatSpec& spec_; FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler); -public: - explicit WidthHandler(FormatSpec &spec) : spec_(spec) {} + public: + explicit WidthHandler(FormatSpec& spec) : spec_(spec) {} - void report_unhandled_arg() - { + void report_unhandled_arg() { FMT_THROW(FormatError("width is not integer")); } template <typename T> - unsigned visit_any_int(T value) - { + unsigned visit_any_int(T value) { typedef typename internal::IntTraits<T>::MainType UnsignedType; UnsignedType width = static_cast<UnsignedType>(value); - if (internal::is_negative(value)) - { + if (internal::is_negative(value)) { spec_.align_ = ALIGN_LEFT; width = 0 - width; } @@ -278,18 +236,16 @@ public: */ template <typename Impl, typename Char, typename Spec> class BasicPrintfArgFormatter : - public internal::ArgFormatterBase<Impl, Char, Spec> -{ -private: - void write_null_pointer() - { + public internal::ArgFormatterBase<Impl, Char, Spec> { + private: + void write_null_pointer() { this->spec().type_ = 0; this->write("(nil)"); } typedef internal::ArgFormatterBase<Impl, Char, Spec> Base; -public: + public: /** \rst Constructs an argument formatter object. @@ -297,13 +253,12 @@ public: specifier information for standard argument types. \endrst */ - BasicPrintfArgFormatter(BasicWriter<Char> &w, Spec &s) + BasicPrintfArgFormatter(BasicWriter<Char>& w, Spec& s) : internal::ArgFormatterBase<Impl, Char, Spec>(w, s) {} /** Formats an argument of type ``bool``. */ - void visit_bool(bool value) - { - Spec &fmt_spec = this->spec(); + void visit_bool(bool value) { + Spec& fmt_spec = this->spec(); if (fmt_spec.type_ != 's') return this->visit_any_int(value); fmt_spec.type_ = 0; @@ -311,38 +266,30 @@ public: } /** Formats a character. */ - void visit_char(int value) - { - const Spec &fmt_spec = this->spec(); - BasicWriter<Char> &w = this->writer(); + void visit_char(int value) { + const Spec& fmt_spec = this->spec(); + BasicWriter<Char>& w = this->writer(); if (fmt_spec.type_ && fmt_spec.type_ != 'c') w.write_int(value, fmt_spec); typedef typename BasicWriter<Char>::CharPtr CharPtr; CharPtr out = CharPtr(); - if (fmt_spec.width_ > 1) - { + if (fmt_spec.width_ > 1) { Char fill = ' '; out = w.grow_buffer(fmt_spec.width_); - if (fmt_spec.align_ != ALIGN_LEFT) - { + if (fmt_spec.align_ != ALIGN_LEFT) { std::fill_n(out, fmt_spec.width_ - 1, fill); out += fmt_spec.width_ - 1; - } - else - { + } else { std::fill_n(out + 1, fmt_spec.width_ - 1, fill); } - } - else - { + } else { out = w.grow_buffer(1); } *out = static_cast<Char>(value); } /** Formats a null-terminated C string. */ - void visit_cstring(const char *value) - { + void visit_cstring(const char* value) { if (value) Base::visit_cstring(value); else if (this->spec().type_ == 'p') @@ -352,8 +299,7 @@ public: } /** Formats a pointer. */ - void visit_pointer(const void *value) - { + void visit_pointer(const void* value) { if (value) return Base::visit_pointer(value); this->spec().type_ = 0; @@ -361,11 +307,10 @@ public: } /** Formats an argument of a custom (user-defined) type. */ - void visit_custom(internal::Arg::CustomValue c) - { + void visit_custom(internal::Arg::CustomValue c) { BasicFormatter<Char> formatter(ArgList(), this->writer()); const Char format_str[] = {'}', 0}; - const Char *format = format_str; + const Char* format = format_str; c.format(&formatter, c.value, &format); } }; @@ -373,33 +318,31 @@ public: /** The default printf argument formatter. */ template <typename Char> class PrintfArgFormatter : - public BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char, FormatSpec> -{ -public: + public BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char, FormatSpec> { + public: /** Constructs an argument formatter object. */ - PrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s) + PrintfArgFormatter(BasicWriter<Char>& w, FormatSpec& s) : BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char, FormatSpec>(w, s) {} }; /** This template formats data and writes the output to a writer. */ template <typename Char, typename ArgFormatter = PrintfArgFormatter<Char> > -class PrintfFormatter : private internal::FormatterBase -{ -private: - BasicWriter<Char> &writer_; +class PrintfFormatter : private internal::FormatterBase { + private: + BasicWriter<Char>& writer_; - void parse_flags(FormatSpec &spec, const Char *&s); + void parse_flags(FormatSpec& spec, const Char*& s); // Returns the argument with specified index or, if arg_index is equal // to the maximum unsigned value, the next argument. internal::Arg get_arg( - const Char *s, + const Char* s, unsigned arg_index = (std::numeric_limits<unsigned>::max)()); // Parses argument index, flags and width and returns the argument index. - unsigned parse_header(const Char *&s, FormatSpec &spec); + unsigned parse_header(const Char*& s, FormatSpec& spec); -public: + public: /** \rst Constructs a ``PrintfFormatter`` object. References to the arguments and @@ -407,7 +350,7 @@ public: appropriate lifetimes. \endrst */ - explicit PrintfFormatter(const ArgList &al, BasicWriter<Char> &w) + explicit PrintfFormatter(const ArgList& al, BasicWriter<Char>& w) : FormatterBase(al), writer_(w) {} /** Formats stored arguments and writes the output to the writer. */ @@ -415,12 +358,9 @@ public: }; template <typename Char, typename AF> -void PrintfFormatter<Char, AF>::parse_flags(FormatSpec &spec, const Char *&s) -{ - for (;;) - { - switch (*s++) - { +void PrintfFormatter<Char, AF>::parse_flags(FormatSpec& spec, const Char*& s) { + for (;;) { + switch (*s++) { case '-': spec.align_ = ALIGN_LEFT; break; @@ -444,11 +384,10 @@ void PrintfFormatter<Char, AF>::parse_flags(FormatSpec &spec, const Char *&s) } template <typename Char, typename AF> -internal::Arg PrintfFormatter<Char, AF>::get_arg(const Char *s, - unsigned arg_index) -{ +internal::Arg PrintfFormatter<Char, AF>::get_arg(const Char* s, + unsigned arg_index) { (void)s; - const char *error = FMT_NULL; + const char* error = FMT_NULL; internal::Arg arg = arg_index == std::numeric_limits<unsigned>::max() ? next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); if (error) @@ -458,26 +397,20 @@ internal::Arg PrintfFormatter<Char, AF>::get_arg(const Char *s, template <typename Char, typename AF> unsigned PrintfFormatter<Char, AF>::parse_header( - const Char *&s, FormatSpec &spec) -{ + const Char*& s, FormatSpec& spec) { unsigned arg_index = std::numeric_limits<unsigned>::max(); Char c = *s; - if (c >= '0' && c <= '9') - { + if (c >= '0' && c <= '9') { // 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; - } - else - { + } else { if (c == '0') spec.fill_ = '0'; - if (value != 0) - { + if (value != 0) { // Nonzero value means that we parsed width and don't need to // parse it or flags again, so return now. spec.width_ = value; @@ -487,12 +420,9 @@ unsigned PrintfFormatter<Char, AF>::parse_header( } parse_flags(spec, s); // Parse width. - if (*s >= '0' && *s <= '9') - { + if (*s >= '0' && *s <= '9') { spec.width_ = internal::parse_nonnegative_int(s); - } - else if (*s == '*') - { + } else if (*s == '*') { ++s; spec.width_ = internal::WidthHandler(spec).visit(get_arg(s)); } @@ -500,16 +430,13 @@ unsigned PrintfFormatter<Char, AF>::parse_header( } template <typename Char, typename AF> -void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) -{ - const Char *start = format_str.c_str(); - const Char *s = start; - while (*s) - { +void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) { + const Char* start = format_str.c_str(); + const Char* s = start; + while (*s) { Char c = *s++; if (c != '%') continue; - if (*s == c) - { + if (*s == c) { write(writer_, start, s); start = ++s; continue; @@ -523,20 +450,14 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) unsigned arg_index = parse_header(s, spec); // Parse precision. - if (*s == '.') - { + if (*s == '.') { ++s; - if ('0' <= *s && *s <= '9') - { + if ('0' <= *s && *s <= '9') { spec.precision_ = static_cast<int>(internal::parse_nonnegative_int(s)); - } - else if (*s == '*') - { + } else if (*s == '*') { ++s; spec.precision_ = internal::PrecisionHandler().visit(get_arg(s)); - } - else - { + } else { spec.precision_ = 0; } } @@ -545,8 +466,7 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) Arg arg = get_arg(s, arg_index); if (spec.flag(HASH_FLAG) && internal::IsZeroInt().visit(arg)) spec.flags_ &= ~internal::to_unsigned<int>(HASH_FLAG); - if (spec.fill_ == '0') - { + if (spec.fill_ == '0') { if (arg.type <= Arg::LAST_NUMERIC_TYPE) spec.align_ = ALIGN_NUMERIC; else @@ -555,8 +475,7 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) // Parse length and convert the argument to the required type. using internal::ArgConverter; - switch (*s++) - { + switch (*s++) { case 'h': if (*s == 'h') ArgConverter<signed char>(arg, *++s).visit(arg); @@ -592,17 +511,14 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) FMT_THROW(FormatError("invalid format string")); spec.type_ = static_cast<char>(*s++); - if (spec.type_ == 's') - { + if (spec.type_ == 's') { // set the format type to the default if 's' is specified spec.type_ = internal::DefaultType().visit(arg); } - if (arg.type <= Arg::LAST_INTEGER_TYPE) - { + if (arg.type <= Arg::LAST_INTEGER_TYPE) { // Normalize type. - switch (spec.type_) - { + switch (spec.type_) { case 'i': case 'u': spec.type_ = 'd'; @@ -622,17 +538,15 @@ void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) write(writer_, start, s); } -inline void printf(Writer &w, CStringRef format, ArgList args) -{ +inline void printf(Writer& w, CStringRef format, ArgList args) { PrintfFormatter<char>(args, w).format(format); } -FMT_VARIADIC(void, printf, Writer &, CStringRef) +FMT_VARIADIC(void, printf, Writer&, CStringRef) -inline void printf(WWriter &w, WCStringRef format, ArgList args) -{ +inline void printf(WWriter& w, WCStringRef format, ArgList args) { PrintfFormatter<wchar_t>(args, w).format(format); } -FMT_VARIADIC(void, printf, WWriter &, WCStringRef) +FMT_VARIADIC(void, printf, WWriter&, WCStringRef) /** \rst @@ -643,16 +557,14 @@ FMT_VARIADIC(void, printf, WWriter &, WCStringRef) std::string message = fmt::sprintf("The answer is %d", 42); \endrst */ -inline std::string sprintf(CStringRef format, ArgList args) -{ +inline std::string sprintf(CStringRef format, ArgList args) { MemoryWriter w; printf(w, format, args); return w.str(); } FMT_VARIADIC(std::string, sprintf, CStringRef) -inline std::wstring sprintf(WCStringRef format, ArgList args) -{ +inline std::wstring sprintf(WCStringRef format, ArgList args) { WMemoryWriter w; printf(w, format, args); return w.str(); @@ -668,8 +580,8 @@ FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef) fmt::fprintf(stderr, "Don't %s!", "panic"); \endrst */ -FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args); -FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef) +FMT_API int fprintf(std::FILE* f, CStringRef format, ArgList args); +FMT_VARIADIC(int, fprintf, std::FILE*, CStringRef) /** \rst @@ -680,8 +592,7 @@ FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef) fmt::printf("Elapsed time: %.2f seconds", 1.23); \endrst */ -inline int printf(CStringRef format, ArgList args) -{ +inline int printf(CStringRef format, ArgList args) { return fprintf(stdout, format, args); } FMT_VARIADIC(int, printf, CStringRef) @@ -695,14 +606,13 @@ FMT_VARIADIC(int, printf, CStringRef) fprintf(cerr, "Don't %s!", "panic"); \endrst */ -inline int fprintf(std::ostream &os, CStringRef format_str, ArgList args) -{ +inline int fprintf(std::ostream& os, CStringRef format_str, ArgList args) { MemoryWriter w; printf(w, format_str, args); internal::write(os, w); return static_cast<int>(w.size()); } -FMT_VARIADIC(int, fprintf, std::ostream &, CStringRef) +FMT_VARIADIC(int, fprintf, std::ostream&, CStringRef) } // namespace fmt #ifdef FMT_HEADER_ONLY diff --git a/3d_party/spd_log/include/spdlog/fmt/bundled/time.h b/3d_party/spd_log/include/spdlog/fmt/bundled/time.h index 206d092094c1cd2b63243eaff3160990eab1315f..4bf58c38e80117e19ac8aeec716ef29d3ae05ee8 100644 --- a/3d_party/spd_log/include/spdlog/fmt/bundled/time.h +++ b/3d_party/spd_log/include/spdlog/fmt/bundled/time.h @@ -19,15 +19,13 @@ # pragma warning(disable: 4996) // "deprecated" functions #endif -namespace fmt -{ +namespace fmt { template <typename ArgFormatter> -void format_arg(BasicFormatter<char, ArgFormatter> &f, - const char *&format_str, const std::tm &tm) -{ +void format_arg(BasicFormatter<char, ArgFormatter>& f, + const char*& format_str, const std::tm& tm) { if (*format_str == ':') ++format_str; - const char *end = format_str; + const char* end = format_str; while (*end && *end != '}') ++end; if (*end != '}') @@ -35,19 +33,16 @@ void format_arg(BasicFormatter<char, ArgFormatter> &f, internal::MemoryBuffer<char, internal::INLINE_BUFFER_SIZE> format; format.append(format_str, end + 1); format[format.size() - 1] = '\0'; - Buffer<char> &buffer = f.writer().buffer(); + Buffer<char>& buffer = f.writer().buffer(); std::size_t start = buffer.size(); - for (;;) - { + for (;;) { std::size_t size = buffer.capacity() - start; std::size_t count = std::strftime(&buffer[start], size, &format[0], &tm); - if (count != 0) - { + if (count != 0) { buffer.resize(start + count); break; } - if (size >= format.size() * 256) - { + if (size >= format.size() * 256) { // If the buffer is 256 times larger than the format string, assume // that `strftime` gives an empty result. There doesn't seem to be a // better way to distinguish the two cases: @@ -60,62 +55,50 @@ void format_arg(BasicFormatter<char, ArgFormatter> &f, format_str = end + 1; } -namespace internal -{ -inline Null<> localtime_r(...) -{ +namespace internal { +inline Null<> localtime_r(...) { return Null<>(); } -inline Null<> localtime_s(...) -{ +inline Null<> localtime_s(...) { return Null<>(); } -inline Null<> gmtime_r(...) -{ +inline Null<> gmtime_r(...) { return Null<>(); } -inline Null<> gmtime_s(...) -{ +inline Null<> gmtime_s(...) { return Null<>(); } } // Thread-safe replacement for std::localtime -inline std::tm localtime(std::time_t time) -{ - struct LocalTime - { +inline std::tm localtime(std::time_t time) { + struct LocalTime { std::time_t time_; std::tm tm_; LocalTime(std::time_t t): time_(t) {} - bool run() - { + bool run() { using namespace fmt::internal; return handle(localtime_r(&time_, &tm_)); } - bool handle(std::tm *tm) - { + bool handle(std::tm* tm) { return tm != FMT_NULL; } - bool handle(internal::Null<>) - { + bool handle(internal::Null<>) { using namespace fmt::internal; return fallback(localtime_s(&tm_, &time_)); } - bool fallback(int res) - { + bool fallback(int res) { return res == 0; } - bool fallback(internal::Null<>) - { + bool fallback(internal::Null<>) { using namespace fmt::internal; - std::tm *tm = std::localtime(&time_); + std::tm* tm = std::localtime(&time_); if (tm) tm_ = *tm; return tm != FMT_NULL; } @@ -129,40 +112,33 @@ inline std::tm localtime(std::time_t time) } // Thread-safe replacement for std::gmtime -inline std::tm gmtime(std::time_t time) -{ - struct GMTime - { +inline std::tm gmtime(std::time_t time) { + struct GMTime { std::time_t time_; std::tm tm_; GMTime(std::time_t t): time_(t) {} - bool run() - { + bool run() { using namespace fmt::internal; return handle(gmtime_r(&time_, &tm_)); } - bool handle(std::tm *tm) - { + bool handle(std::tm* tm) { return tm != FMT_NULL; } - bool handle(internal::Null<>) - { + bool handle(internal::Null<>) { using namespace fmt::internal; return fallback(gmtime_s(&tm_, &time_)); } - bool fallback(int res) - { + bool fallback(int res) { return res == 0; } - bool fallback(internal::Null<>) - { - std::tm *tm = std::gmtime(&time_); + bool fallback(internal::Null<>) { + std::tm* tm = std::gmtime(&time_); if (tm != FMT_NULL) tm_ = *tm; return tm != FMT_NULL; } diff --git a/3d_party/spd_log/include/spdlog/formatter.h b/3d_party/spd_log/include/spdlog/formatter.h index 8bf0f43f8354901c555ad6423ee5e5f75752615b..2e40fc50551bca039d31b077f2041792a6edf84b 100644 --- a/3d_party/spd_log/include/spdlog/formatter.h +++ b/3d_party/spd_log/include/spdlog/formatter.h @@ -11,29 +11,25 @@ #include <string> #include <memory> -namespace spdlog -{ -namespace details -{ +namespace spdlog { +namespace details { class flag_formatter; } -class formatter -{ -public: +class formatter { + public: virtual ~formatter() {} virtual void format(details::log_msg& msg) = 0; }; -class pattern_formatter SPDLOG_FINAL : public formatter -{ +class pattern_formatter SPDLOG_FINAL : public formatter { -public: + public: explicit pattern_formatter(const std::string& pattern, pattern_time_type pattern_time = pattern_time_type::local); pattern_formatter(const pattern_formatter&) = delete; pattern_formatter& operator=(const pattern_formatter&) = delete; void format(details::log_msg& msg) override; -private: + private: const std::string _pattern; const pattern_time_type _pattern_time; std::vector<std::unique_ptr<details::flag_formatter>> _formatters; diff --git a/3d_party/spd_log/include/spdlog/logger.h b/3d_party/spd_log/include/spdlog/logger.h index 742f667f1947dc018dd595490cc785e681f58356..ca1aa0d2e7cebb1d6abe3618eedb8f2c970d8457 100644 --- a/3d_party/spd_log/include/spdlog/logger.h +++ b/3d_party/spd_log/include/spdlog/logger.h @@ -19,12 +19,10 @@ #include <memory> #include <string> -namespace spdlog -{ +namespace spdlog { -class logger -{ -public: +class logger { + public: logger(const std::string& logger_name, sink_ptr single_sink); logger(const std::string& name, sinks_init_list); template<class It> @@ -35,25 +33,25 @@ public: logger& operator=(const logger&) = delete; - template <typename... Args> void log(level::level_enum lvl, const char* fmt, const Args&... args); + template <typename... Args> void log(level::level_enum lvl, const char* fmt, const Args& ... args); template <typename... Args> void log(level::level_enum lvl, const char* msg); - template <typename Arg1, typename... Args> void trace(const char* fmt, const Arg1&, const Args&... args); - template <typename Arg1, typename... Args> void debug(const char* fmt, const Arg1&, const Args&... args); - template <typename Arg1, typename... Args> void info(const char* fmt, const Arg1&, const Args&... args); - template <typename Arg1, typename... Args> void warn(const char* fmt, const Arg1&, const Args&... args); - template <typename Arg1, typename... Args> void error(const char* fmt, const Arg1&, const Args&... args); - template <typename Arg1, typename... Args> void critical(const char* fmt, const Arg1&, const Args&... args); + template <typename Arg1, typename... Args> void trace(const char* fmt, const Arg1&, const Args& ... args); + template <typename Arg1, typename... Args> void debug(const char* fmt, const Arg1&, const Args& ... args); + template <typename Arg1, typename... Args> void info(const char* fmt, const Arg1&, const Args& ... args); + template <typename Arg1, typename... Args> void warn(const char* fmt, const Arg1&, const Args& ... args); + template <typename Arg1, typename... Args> void error(const char* fmt, const Arg1&, const Args& ... args); + template <typename Arg1, typename... Args> void critical(const char* fmt, const Arg1&, const Args& ... args); #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT template <typename... Args> void log(level::level_enum lvl, const wchar_t* msg); - template <typename... Args> void log(level::level_enum lvl, const wchar_t* fmt, const Args&... args); - template <typename... Args> void trace(const wchar_t* fmt, const Args&... args); - template <typename... Args> void debug(const wchar_t* fmt, const Args&... args); - template <typename... Args> void info(const wchar_t* fmt, const Args&... args); - template <typename... Args> void warn(const wchar_t* fmt, const Args&... args); - template <typename... Args> void error(const wchar_t* fmt, const Args&... args); - template <typename... Args> void critical(const wchar_t* fmt, const Args&... args); + template <typename... Args> void log(level::level_enum lvl, const wchar_t* fmt, const Args& ... args); + template <typename... Args> void trace(const wchar_t* fmt, const Args& ... args); + template <typename... Args> void debug(const wchar_t* fmt, const Args& ... args); + template <typename... Args> void info(const wchar_t* fmt, const Args& ... args); + template <typename... Args> void warn(const wchar_t* fmt, const Args& ... args); + template <typename... Args> void error(const wchar_t* fmt, const Args& ... args); + template <typename... Args> void critical(const wchar_t* fmt, const Args& ... args); #endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT template <typename T> void log(level::level_enum lvl, const T&); @@ -82,19 +80,19 @@ public: virtual void set_error_handler(log_err_handler); virtual log_err_handler error_handler(); -protected: + protected: virtual void _sink_it(details::log_msg&); virtual void _set_pattern(const std::string&, pattern_time_type); virtual void _set_formatter(formatter_ptr); // 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); + 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&); // 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<sink_ptr> _sinks; diff --git a/3d_party/spd_log/include/spdlog/sinks/android_sink.h b/3d_party/spd_log/include/spdlog/sinks/android_sink.h index e376675583375bdf4ba9739847f36ad8a84d629b..94f0f59c6bbd3321ac7caa6ece25860f4a77058d 100644 --- a/3d_party/spd_log/include/spdlog/sinks/android_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/android_sink.h @@ -20,50 +20,42 @@ #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. */ -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) {} +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) {} - 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()); + const char* msg_output = (_use_raw_msg ? msg.raw.c_str() : msg.formatted.c_str()); // 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); retry_count++; } - if (ret < 0) - { + if (ret < 0) { throw spdlog_ex("__android_log_write() failed", ret); } } - void flush() override - { + void flush() override { } -private: - static android_LogPriority convert_to_android(spdlog::level::level_enum level) - { - switch(level) - { + private: + static android_LogPriority convert_to_android(spdlog::level::level_enum level) { + switch(level) { case spdlog::level::trace: return ANDROID_LOG_VERBOSE; case spdlog::level::debug: diff --git a/3d_party/spd_log/include/spdlog/sinks/ansicolor_sink.h b/3d_party/spd_log/include/spdlog/sinks/ansicolor_sink.h index 290973133d29a4802852b327da8b9aa0263c29c1..733b870f42298ec986948e48e8ef0acdf04d4be1 100644 --- a/3d_party/spd_log/include/spdlog/sinks/ansicolor_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/ansicolor_sink.h @@ -12,10 +12,8 @@ #include <string> #include <map> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { /** * This sink prefixes the output with an ANSI escape sequence color code depending on the severity @@ -23,11 +21,9 @@ namespace sinks * If no color terminal detected, omit the escape codes. */ template <class Mutex> -class ansicolor_sink: public base_sink<Mutex> -{ -public: - ansicolor_sink(FILE* file): target_file_(file) - { +class ansicolor_sink: public base_sink<Mutex> { + public: + ansicolor_sink(FILE* file): target_file_(file) { should_do_colors_ = details::os::in_terminal(file) && details::os::is_color_terminal(); colors_[level::trace] = cyan; colors_[level::debug] = cyan; @@ -37,13 +33,11 @@ public: colors_[level::critical] = bold + on_red; colors_[level::off] = reset; } - virtual ~ansicolor_sink() - { + virtual ~ansicolor_sink() { _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<Mutex> lock(base_sink<Mutex>::_mutex); colors_[color_level] = color; } @@ -77,27 +71,22 @@ public: const std::string on_cyan = "\033[46m"; const std::string on_white = "\033[47m"; -protected: - virtual void _sink_it(const details::log_msg& msg) override - { + protected: + virtual 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_) - { + if (should_do_colors_) { 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_); - } - else - { + } else { fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), target_file_); } _flush(); } - void _flush() override - { + void _flush() override { fflush(target_file_); } FILE* target_file_; @@ -107,19 +96,17 @@ protected: template<class Mutex> -class ansicolor_stdout_sink: public ansicolor_sink<Mutex> -{ -public: - ansicolor_stdout_sink(): ansicolor_sink<Mutex>(stdout) - {} +class ansicolor_stdout_sink: public ansicolor_sink<Mutex> { + public: + ansicolor_stdout_sink(): ansicolor_sink<Mutex>(stdout) { + } }; template<class Mutex> -class ansicolor_stderr_sink: public ansicolor_sink<Mutex> -{ -public: - ansicolor_stderr_sink(): ansicolor_sink<Mutex>(stderr) - {} +class ansicolor_stderr_sink: public ansicolor_sink<Mutex> { + public: + ansicolor_stderr_sink(): ansicolor_sink<Mutex>(stderr) { + } }; typedef ansicolor_stdout_sink<std::mutex> ansicolor_stdout_sink_mt; diff --git a/3d_party/spd_log/include/spdlog/sinks/base_sink.h b/3d_party/spd_log/include/spdlog/sinks/base_sink.h index 23c856530b94959ae1fbd5051d86557fd8ae95de..919350c8572f4cfe59c1748c0eb3b981e09d6f2b 100644 --- a/3d_party/spd_log/include/spdlog/sinks/base_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/base_sink.h @@ -17,32 +17,27 @@ #include <mutex> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { template<class Mutex> -class base_sink:public sink -{ -public: - base_sink():_mutex() {} +class base_sink: public sink { + public: + base_sink(): _mutex() {} virtual ~base_sink() = default; 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<Mutex> lock(_mutex); _sink_it(msg); } - void flush() SPDLOG_FINAL override - { + void flush() SPDLOG_FINAL override { std::lock_guard<Mutex> lock(_mutex); _flush(); } -protected: + protected: virtual void _sink_it(const details::log_msg& msg) = 0; virtual void _flush() = 0; Mutex _mutex; diff --git a/3d_party/spd_log/include/spdlog/sinks/dist_sink.h b/3d_party/spd_log/include/spdlog/sinks/dist_sink.h index 537efe1d1fa8ab8b8696f7d24ba0f06b0e5a9012..ca22710d2c51dfd612888df82a44a8c86b21a075 100644 --- a/3d_party/spd_log/include/spdlog/sinks/dist_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/dist_sink.h @@ -17,50 +17,41 @@ // Distribution sink (mux). Stores a vector of sinks which get called when log is called -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { template<class Mutex> -class dist_sink: public base_sink<Mutex> -{ -public: - explicit dist_sink() :_sinks() {} +class dist_sink: public base_sink<Mutex> { + public: + explicit dist_sink() : _sinks() {} dist_sink(const dist_sink&) = delete; dist_sink& operator=(const dist_sink&) = delete; virtual ~dist_sink() = default; -protected: + protected: std::vector<std::shared_ptr<sink>> _sinks; - void _sink_it(const details::log_msg& msg) override - { - for (auto &sink : _sinks) - { - if( sink->should_log( msg.level)) - { + void _sink_it(const details::log_msg& msg) override { + for (auto& sink : _sinks) { + if( sink->should_log( msg.level)) { sink->log(msg); } } } - void _flush() override - { - for (auto &sink : _sinks) + void _flush() override { + for (auto& sink : _sinks) sink->flush(); } -public: + public: - void add_sink(std::shared_ptr<sink> sink) - { + void add_sink(std::shared_ptr<sink> sink) { std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex); _sinks.push_back(sink); } - void remove_sink(std::shared_ptr<sink> sink) - { + void remove_sink(std::shared_ptr<sink> sink) { std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex); _sinks.erase(std::remove(_sinks.begin(), _sinks.end(), sink), _sinks.end()); } diff --git a/3d_party/spd_log/include/spdlog/sinks/file_sinks.h b/3d_party/spd_log/include/spdlog/sinks/file_sinks.h index e78561722bae98f8e3d541f4060bfd7ce834e823..5d4535741207c55107d20659784fd2d31145710f 100644 --- a/3d_party/spd_log/include/spdlog/sinks/file_sinks.h +++ b/3d_party/spd_log/include/spdlog/sinks/file_sinks.h @@ -18,39 +18,32 @@ #include <string> #include <cerrno> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { /* * Trivial file sink with single file as target */ template<class Mutex> -class simple_file_sink SPDLOG_FINAL : public base_sink < Mutex > -{ -public: - explicit simple_file_sink(const filename_t &filename, bool truncate = false):_force_flush(false) - { +class simple_file_sink SPDLOG_FINAL : public base_sink < Mutex > { + public: + explicit simple_file_sink(const filename_t& filename, bool truncate = false): _force_flush(false) { _file_helper.open(filename, truncate); } - void set_force_flush(bool force_flush) - { + void set_force_flush(bool force_flush) { _force_flush = force_flush; } -protected: - void _sink_it(const details::log_msg& msg) override - { + protected: + void _sink_it(const details::log_msg& msg) override { _file_helper.write(msg); if(_force_flush) _file_helper.flush(); } - void _flush() override - { + void _flush() override { _file_helper.flush(); } -private: + private: details::file_helper _file_helper; bool _force_flush; }; @@ -62,82 +55,69 @@ typedef simple_file_sink<details::null_mutex> simple_file_sink_st; * Rotating file sink based on size */ template<class Mutex> -class rotating_file_sink SPDLOG_FINAL : public base_sink < Mutex > -{ -public: - rotating_file_sink(const filename_t &base_filename, +class rotating_file_sink SPDLOG_FINAL : public base_sink < Mutex > { + public: + rotating_file_sink(const filename_t& base_filename, std::size_t max_size, std::size_t max_files) : _base_filename(base_filename), _max_size(max_size), _max_files(max_files), _current_size(0), - _file_helper() - { + _file_helper() { _file_helper.open(calc_filename(_base_filename, 0)); _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) { std::conditional<std::is_same<filename_t::value_type, char>::value, fmt::MemoryWriter, fmt::WMemoryWriter>::type w; - if (index) - { + if (index) { filename_t basename, ext; std::tie(basename, ext) = details::file_helper::split_by_extenstion(filename); w.write(SPDLOG_FILENAME_T("{}.{}{}"), basename, index, ext); - } - else - { + } else { w.write(SPDLOG_FILENAME_T("{}"), filename); } return w.str(); } -protected: - void _sink_it(const details::log_msg& msg) override - { + protected: + void _sink_it(const details::log_msg& msg) override { _current_size += msg.formatted.size(); - if (_current_size > _max_size) - { + if (_current_size > _max_size) { _rotate(); _current_size = msg.formatted.size(); } _file_helper.write(msg); } - void _flush() override - { + void _flush() override { _file_helper.flush(); } -private: + private: // Rotate files: // log.txt -> log.1.txt // log.1.txt -> log.2.txt // log.2.txt -> log.3.txt // log.3.txt -> delete - void _rotate() - { + void _rotate() { using details::os::filename_to_str; _file_helper.close(); - for (auto i = _max_files; i > 0; --i) - { + for (auto i = _max_files; i > 0; --i) { filename_t src = calc_filename(_base_filename, i - 1); filename_t target = calc_filename(_base_filename, i); - if (details::file_helper::file_exists(target)) - { - if (details::os::remove(target) != 0) - { + if (details::file_helper::file_exists(target)) { + if (details::os::remove(target) != 0) { throw spdlog_ex("rotating_file_sink: failed removing " + filename_to_str(target), errno); } } - if (details::file_helper::file_exists(src) && details::os::rename(src, target)) - { - throw spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno); + if (details::file_helper::file_exists(src) && details::os::rename(src, target)) { + throw spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), + errno); } } _file_helper.reopen(true); @@ -155,16 +135,15 @@ typedef rotating_file_sink<details::null_mutex>rotating_file_sink_st; /* * Default generator of daily log file names. */ -struct default_daily_file_name_calculator -{ +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<std::is_same<filename_t::value_type, char>::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(); } }; @@ -172,11 +151,9 @@ struct default_daily_file_name_calculator /* * Generator of daily log file names in format basename.YYYY-MM-DD.ext */ -struct dateonly_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; std::tie(basename, ext) = details::file_helper::split_by_extenstion(filename); @@ -190,17 +167,15 @@ struct dateonly_daily_file_name_calculator * Rotating file sink based on date. rotates at midnight */ template<class Mutex, class FileNameCalc = default_daily_file_name_calculator> -class daily_file_sink SPDLOG_FINAL :public base_sink < Mutex > -{ -public: +class daily_file_sink SPDLOG_FINAL : public base_sink < Mutex > { + public: //create daily file sink which rotates on given time daily_file_sink( const filename_t& base_filename, int rotation_hour, int rotation_minute) : _base_filename(base_filename), _rotation_h(rotation_hour), - _rotation_m(rotation_minute) - { + _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"); _rotation_tp = _next_rotation_tp(); @@ -208,25 +183,21 @@ public: } -protected: - void _sink_it(const details::log_msg& msg) override - { - if (std::chrono::system_clock::now() >= _rotation_tp) - { + protected: + void _sink_it(const details::log_msg& msg) override { + if (std::chrono::system_clock::now() >= _rotation_tp) { _file_helper.open(FileNameCalc::calc_filename(_base_filename)); _rotation_tp = _next_rotation_tp(); } _file_helper.write(msg); } - void _flush() override - { + void _flush() override { _file_helper.flush(); } -private: - std::chrono::system_clock::time_point _next_rotation_tp() - { + private: + std::chrono::system_clock::time_point _next_rotation_tp() { auto now = std::chrono::system_clock::now(); time_t tnow = std::chrono::system_clock::to_time_t(now); tm date = spdlog::details::os::localtime(tnow); diff --git a/3d_party/spd_log/include/spdlog/sinks/msvc_sink.h b/3d_party/spd_log/include/spdlog/sinks/msvc_sink.h index 22b52c8fe9f70ae896e60ff553a781629ecad9c6..de67bf4fe9b6671ebeb36a699e5a7137acf17a6e 100644 --- a/3d_party/spd_log/include/spdlog/sinks/msvc_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/msvc_sink.h @@ -15,31 +15,26 @@ #include <mutex> #include <string> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { /* * MSVC sink (logging using OutputDebugStringA) */ template<class Mutex> -class msvc_sink : public base_sink < Mutex > -{ -public: - explicit msvc_sink() - { +class msvc_sink : public base_sink < Mutex > { + public: + explicit msvc_sink() { } -protected: - void _sink_it(const details::log_msg& msg) override - { + protected: + void _sink_it(const details::log_msg& msg) override { OutputDebugStringA(msg.formatted.c_str()); } - void _flush() override - {} + void _flush() override { + } }; typedef msvc_sink<std::mutex> msvc_sink_mt; diff --git a/3d_party/spd_log/include/spdlog/sinks/null_sink.h b/3d_party/spd_log/include/spdlog/sinks/null_sink.h index 7605ac68c27be8af987cf02b1d0af89538336017..e6fe64f7259c029a1520fcd0fbe0992a3e226971 100644 --- a/3d_party/spd_log/include/spdlog/sinks/null_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/null_sink.h @@ -10,20 +10,17 @@ #include <mutex> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { template <class Mutex> -class null_sink : public base_sink < Mutex > -{ -protected: - void _sink_it(const details::log_msg&) override - {} - - void _flush() override - {} +class null_sink : public base_sink < Mutex > { + protected: + void _sink_it(const details::log_msg&) override { + } + + void _flush() override { + } }; typedef null_sink<details::null_mutex> null_sink_st; diff --git a/3d_party/spd_log/include/spdlog/sinks/ostream_sink.h b/3d_party/spd_log/include/spdlog/sinks/ostream_sink.h index 1e5b261c08843f9aaa093daa1ba644155d0fe718..4a10f8976a42fee3b1591fbf02caefd0c5d0eba7 100644 --- a/3d_party/spd_log/include/spdlog/sinks/ostream_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/ostream_sink.h @@ -11,29 +11,24 @@ #include <ostream> #include <mutex> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { template<class Mutex> -class ostream_sink: public base_sink<Mutex> -{ -public: - explicit ostream_sink(std::ostream& os, bool force_flush=false) :_ostream(os), _force_flush(force_flush) {} +class ostream_sink: public base_sink<Mutex> { + 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; virtual ~ostream_sink() = default; -protected: - void _sink_it(const details::log_msg& msg) override - { + protected: + void _sink_it(const details::log_msg& msg) override { _ostream.write(msg.formatted.data(), msg.formatted.size()); if (_force_flush) _ostream.flush(); } - void _flush() override - { + void _flush() override { _ostream.flush(); } diff --git a/3d_party/spd_log/include/spdlog/sinks/sink.h b/3d_party/spd_log/include/spdlog/sinks/sink.h index af61b54c613a328b9e1a6c6a7983e104487cb543..7a7f767e88bb95ffbf657f344b8bda3d2c5f55d4 100644 --- a/3d_party/spd_log/include/spdlog/sinks/sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/sink.h @@ -8,15 +8,11 @@ #include "../details/log_msg.h" -namespace spdlog -{ -namespace sinks -{ -class sink -{ -public: - sink() - { +namespace spdlog { +namespace sinks { +class sink { + public: + sink() { _level = level::trace; } @@ -28,23 +24,20 @@ public: void set_level(level::level_enum log_level); level::level_enum level() const; -private: + private: level_t _level; }; -inline bool sink::should_log(level::level_enum msg_level) const -{ +inline bool sink::should_log(level::level_enum msg_level) const { return msg_level >= _level.load(std::memory_order_relaxed); } -inline void sink::set_level(level::level_enum log_level) -{ +inline void sink::set_level(level::level_enum log_level) { _level.store(log_level); } -inline level::level_enum sink::level() const -{ +inline level::level_enum sink::level() const { return static_cast<spdlog::level::level_enum>(_level.load(std::memory_order_relaxed)); } diff --git a/3d_party/spd_log/include/spdlog/sinks/stdout_sinks.h b/3d_party/spd_log/include/spdlog/sinks/stdout_sinks.h index dfbfccd51690ef77d5aef5bd673a394e63b4d22e..7825025c65c8e1810017840d62f4bb052d8e7331 100644 --- a/3d_party/spd_log/include/spdlog/sinks/stdout_sinks.h +++ b/3d_party/spd_log/include/spdlog/sinks/stdout_sinks.h @@ -12,32 +12,26 @@ #include <memory> #include <mutex> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { template <class Mutex> -class stdout_sink SPDLOG_FINAL : public base_sink<Mutex> -{ +class stdout_sink SPDLOG_FINAL : public base_sink<Mutex> { using MyType = stdout_sink<Mutex>; -public: - stdout_sink() - {} - static std::shared_ptr<MyType> instance() - { + public: + stdout_sink() { + } + static std::shared_ptr<MyType> instance() { static std::shared_ptr<MyType> instance = std::make_shared<MyType>(); return instance; } -protected: - void _sink_it(const details::log_msg& msg) override - { + protected: + void _sink_it(const details::log_msg& msg) override { fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), stdout); _flush(); } - void _flush() override - { + void _flush() override { fflush(stdout); } }; @@ -47,26 +41,22 @@ typedef stdout_sink<std::mutex> stdout_sink_mt; template <class Mutex> -class stderr_sink SPDLOG_FINAL : public base_sink<Mutex> -{ +class stderr_sink SPDLOG_FINAL : public base_sink<Mutex> { using MyType = stderr_sink<Mutex>; -public: - stderr_sink() - {} - static std::shared_ptr<MyType> instance() - { + public: + stderr_sink() { + } + static std::shared_ptr<MyType> instance() { static std::shared_ptr<MyType> instance = std::make_shared<MyType>(); return instance; } -protected: - void _sink_it(const details::log_msg& msg) override - { + protected: + void _sink_it(const details::log_msg& msg) override { fwrite(msg.formatted.data(), sizeof(char), msg.formatted.size(), stderr); _flush(); } - void _flush() override - { + void _flush() override { fflush(stderr); } }; diff --git a/3d_party/spd_log/include/spdlog/sinks/syslog_sink.h b/3d_party/spd_log/include/spdlog/sinks/syslog_sink.h index c4a726a8f86003ebab4dfe8d9d8f6c05f9dab2e2..23dc612d0c0822e2022f2882188a91d126cc3e3c 100644 --- a/3d_party/spd_log/include/spdlog/sinks/syslog_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/syslog_sink.h @@ -17,22 +17,18 @@ #include <syslog.h> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { /** * Sink that write to syslog using the `syscall()` library call. * * Locking is not needed, as `syslog()` itself is thread-safe. */ -class syslog_sink : public sink -{ -public: +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<int>(level::trace)] = LOG_DEBUG; _priorities[static_cast<int>(level::debug)] = LOG_DEBUG; _priorities[static_cast<int>(level::info)] = LOG_INFO; @@ -42,27 +38,24 @@ public: _priorities[static_cast<int>(level::off)] = LOG_INFO; //set ident to be program name if empty - ::openlog(_ident.empty()? nullptr:_ident.c_str(), syslog_option, syslog_facility); + ::openlog(_ident.empty() ? nullptr : _ident.c_str(), syslog_option, syslog_facility); } - ~syslog_sink() - { + ~syslog_sink() { ::closelog(); } syslog_sink(const syslog_sink&) = delete; syslog_sink& operator=(const syslog_sink&) = delete; - void log(const details::log_msg &msg) override - { + 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: + private: std::array<int, 7> _priorities; //must store the ident because the man says openlog might use the pointer as is and not a string copy const std::string _ident; @@ -70,8 +63,7 @@ private: // // Simply maps spdlog's log level to syslog priority level. // - int syslog_prio_from_level(const details::log_msg &msg) const - { + int syslog_prio_from_level(const details::log_msg& msg) const { return _priorities[static_cast<int>(msg.level)]; } }; diff --git a/3d_party/spd_log/include/spdlog/sinks/wincolor_sink.h b/3d_party/spd_log/include/spdlog/sinks/wincolor_sink.h index 8ee3d894c84caec4fdf8e9ac9b4cb8e59023c463..9b6ec1614efd3f4163a47292517ebf7b718e8d7d 100644 --- a/3d_party/spd_log/include/spdlog/sinks/wincolor_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/wincolor_sink.h @@ -14,25 +14,21 @@ #include <map> #include <wincon.h> -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { /* * Windows color console sink. Uses WriteConsoleA to write to the console with colors */ template<class Mutex> -class wincolor_sink: public base_sink<Mutex> -{ -public: +class wincolor_sink: public base_sink<Mutex> { + public: const WORD BOLD = FOREGROUND_INTENSITY; const WORD RED = FOREGROUND_RED; const WORD CYAN = FOREGROUND_GREEN | FOREGROUND_BLUE; 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; @@ -42,42 +38,37 @@ public: colors_[level::off] = 0; } - virtual ~wincolor_sink() - { + virtual ~wincolor_sink() { this->flush(); } wincolor_sink(const wincolor_sink& other) = delete; wincolor_sink& operator=(const wincolor_sink& other) = delete; -protected: - virtual void _sink_it(const details::log_msg& msg) override - { + protected: + virtual 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<DWORD>(msg.formatted.size()), nullptr, nullptr); SetConsoleTextAttribute(out_handle_, orig_attribs); //reset to orig colors } - virtual void _flush() override - { + virtual void _flush() override { // windows console always flushed? } // change the color for the given level - void set_color(level::level_enum level, WORD color) - { + void set_color(level::level_enum level, WORD color) { std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex); colors_[level] = color; } -private: + private: HANDLE out_handle_; std::map<level::level_enum, WORD> colors_; // set color and return the orig console attributes (for resetting later) - WORD set_console_attribs(WORD attribs) - { + WORD set_console_attribs(WORD attribs) { CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info; GetConsoleScreenBufferInfo(out_handle_, &orig_buffer_info); WORD back_color = orig_buffer_info.wAttributes; @@ -93,11 +84,10 @@ private: // windows color console to stdout // template<class Mutex> -class wincolor_stdout_sink: public wincolor_sink<Mutex> -{ -public: - wincolor_stdout_sink() : wincolor_sink<Mutex>(GetStdHandle(STD_OUTPUT_HANDLE)) - {} +class wincolor_stdout_sink: public wincolor_sink<Mutex> { + public: + wincolor_stdout_sink() : wincolor_sink<Mutex>(GetStdHandle(STD_OUTPUT_HANDLE)) { + } }; typedef wincolor_stdout_sink<std::mutex> wincolor_stdout_sink_mt; @@ -107,11 +97,10 @@ typedef wincolor_stdout_sink<details::null_mutex> wincolor_stdout_sink_st; // windows color console to stderr // template<class Mutex> -class wincolor_stderr_sink: public wincolor_sink<Mutex> -{ -public: - wincolor_stderr_sink() : wincolor_sink<Mutex>(GetStdHandle(STD_ERROR_HANDLE)) - {} +class wincolor_stderr_sink: public wincolor_sink<Mutex> { + public: + wincolor_stderr_sink() : wincolor_sink<Mutex>(GetStdHandle(STD_ERROR_HANDLE)) { + } }; typedef wincolor_stderr_sink<std::mutex> wincolor_stderr_sink_mt; diff --git a/3d_party/spd_log/include/spdlog/sinks/windebug_sink.h b/3d_party/spd_log/include/spdlog/sinks/windebug_sink.h index c22e9522e800c704c8b129b5bf219cd8c545bae2..fa561608212f0e5ec2febb23b79dd22b4a057768 100644 --- a/3d_party/spd_log/include/spdlog/sinks/windebug_sink.h +++ b/3d_party/spd_log/include/spdlog/sinks/windebug_sink.h @@ -9,10 +9,8 @@ #include "msvc_sink.h" -namespace spdlog -{ -namespace sinks -{ +namespace spdlog { +namespace sinks { /* * Windows debug sink (logging using OutputDebugStringA, synonym for msvc_sink) diff --git a/3d_party/spd_log/include/spdlog/spdlog.h b/3d_party/spd_log/include/spdlog/spdlog.h index ff79ef6e237df901c4f2816b76482048e75e4a87..f07a0a25b41e1b6fc57b89fa22fc713f4619dc11 100644 --- a/3d_party/spd_log/include/spdlog/spdlog.h +++ b/3d_party/spd_log/include/spdlog/spdlog.h @@ -18,8 +18,7 @@ #include <chrono> #include <string> -namespace spdlog -{ +namespace spdlog { // // Return an existing logger or nullptr if a logger with such name doesn't exist. @@ -66,7 +65,10 @@ void set_error_handler(log_err_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<void()>& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function<void()>& 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<void()>& worker_warmup_cb = nullptr, + const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function<void()>& worker_teardown_cb = nullptr); // Turn off async mode void set_sync_mode(); @@ -76,20 +78,26 @@ 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<logger> basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate = false); -std::shared_ptr<logger> basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate = false); +std::shared_ptr<logger> basic_logger_mt(const std::string& logger_name, const filename_t& filename, + bool truncate = false); +std::shared_ptr<logger> 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<logger> rotating_logger_mt(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files); -std::shared_ptr<logger> rotating_logger_st(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files); +std::shared_ptr<logger> rotating_logger_mt(const std::string& logger_name, const filename_t& filename, + size_t max_file_size, size_t max_files); +std::shared_ptr<logger> 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<logger> daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour=0, int minute=0); -std::shared_ptr<logger> daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour=0, int minute=0); +std::shared_ptr<logger> daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour = 0, + int minute = 0); +std::shared_ptr<logger> daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour = 0, + int minute = 0); // // Create and register stdout/stderr loggers @@ -111,7 +119,8 @@ std::shared_ptr<logger> stderr_color_st(const std::string& logger_name); // Create and register a syslog logger // #ifdef SPDLOG_ENABLE_SYSLOG -std::shared_ptr<logger> syslog_logger(const std::string& logger_name, const std::string& ident = "", int syslog_option = 0, int syslog_facilty = (1<<3)); +std::shared_ptr<logger> syslog_logger(const std::string& logger_name, const std::string& ident = "", + int syslog_option = 0, int syslog_facilty = (1 << 3)); #endif #if defined(__ANDROID__) @@ -134,12 +143,24 @@ template <typename Sink, typename... Args> std::shared_ptr<spdlog::logger> create(const std::string& logger_name, Args...); // Create and register an async logger with a single sink -std::shared_ptr<logger> 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<void()>& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function<void()>& worker_teardown_cb = nullptr); +std::shared_ptr<logger> 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<void()>& worker_warmup_cb = nullptr, + const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function<void()>& worker_teardown_cb = nullptr); // Create and register an async logger with multiple sinks -std::shared_ptr<logger> 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<void()>& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function<void()>& worker_teardown_cb = nullptr); +std::shared_ptr<logger> 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<void()>& worker_warmup_cb = nullptr, + const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function<void()>& worker_teardown_cb = nullptr); template<class It> -std::shared_ptr<logger> 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<void()>& worker_warmup_cb = nullptr, const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), const std::function<void()>& worker_teardown_cb = nullptr); +std::shared_ptr<logger> 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<void()>& worker_warmup_cb = nullptr, + const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(), + const std::function<void()>& worker_teardown_cb = nullptr); // Register the given logger with the given name void register_logger(std::shared_ptr<logger> logger); @@ -150,7 +171,7 @@ void register_logger(std::shared_ptr<logger> logger); void apply_all(std::function<void(std::shared_ptr<logger>)> fun); // Drop the reference to the given logger -void drop(const std::string &name); +void drop(const std::string& name); // Drop all references from the registry void drop_all(); diff --git a/common/cpp/include/logger/logger.h b/common/cpp/include/logger/logger.h index 7e2bd50e4d59e9a112b4d9fa1f91011373d9b63b..a8ac22b56d33521bd7cfbfe4f92fdcd5ee78c031 100644 --- a/common/cpp/include/logger/logger.h +++ b/common/cpp/include/logger/logger.h @@ -15,19 +15,20 @@ enum class LogLevel { }; class AbstractLogger { - public: + public: virtual void SetLogLevel(LogLevel level) = 0; virtual void Info(const std::string& text) = 0; virtual void Error(const std::string& text) = 0; virtual void Debug(const std::string& text) = 0; virtual void Warning(const std::string& text) = 0; + virtual ~AbstractLogger() = default; }; using Logger = std::unique_ptr<AbstractLogger>; Logger CreateDefaultLoggerBin(const std::string& name); -Logger CreateDefaultLoggerApi(const std::string& name,const std::string& endpoint_uri); +Logger CreateDefaultLoggerApi(const std::string& name, const std::string& endpoint_uri); } diff --git a/common/cpp/src/http_client/http_client_factory.cpp b/common/cpp/src/http_client/http_client_factory.cpp index dabaea7e8b44da1de89511c6a354b4fb6426318a..ca47048078026360c960b8b365238e84f7b1298a 100644 --- a/common/cpp/src/http_client/http_client_factory.cpp +++ b/common/cpp/src/http_client/http_client_factory.cpp @@ -3,7 +3,7 @@ namespace hidra2 { std::unique_ptr<HttpClient> DefaultHttpClient() { - return std::unique_ptr<HttpClient>{new CurlHttpClient}; + return std::unique_ptr<HttpClient> {new CurlHttpClient}; } diff --git a/common/cpp/src/logger/CMakeLists.txt b/common/cpp/src/logger/CMakeLists.txt index 17873877d2fb110b998f75585aac919eb829db7c..65ed7c9c5355f2a281cd36081dd72ae96a5f72e3 100644 --- a/common/cpp/src/logger/CMakeLists.txt +++ b/common/cpp/src/logger/CMakeLists.txt @@ -16,8 +16,11 @@ target_include_directories(${TARGET_NAME} PUBLIC ${HIDRA2_CXX_COMMON_INCLUDE_DIR ################################ -set(TEST_SOURCE_FILES ../../unittests/logger/test_logger.cpp) +set(TEST_SOURCE_FILES ../../unittests/logger/test_logger.cpp + ../../unittests/logger/test_fluentd_sink.cpp) -set(TEST_LIBRARIES "${TARGET_NAME};curl_http_client;${CURL_LIBRARIES}") +link_libraries(${CURL_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) + +set(TEST_LIBRARIES "${TARGET_NAME};curl_http_client") include_directories(${HIDRA2_CXX_COMMON_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3d_party/spd_log/include) gtest(${TARGET_NAME} "${TEST_SOURCE_FILES}" "${TEST_LIBRARIES}") diff --git a/common/cpp/src/logger/fluentd_sink.cpp b/common/cpp/src/logger/fluentd_sink.cpp index 62012a82d29a5dff4b2b652a3a91908d10f54f44..231ae641bc405666112cb074c63b86924cab8cbe 100644 --- a/common/cpp/src/logger/fluentd_sink.cpp +++ b/common/cpp/src/logger/fluentd_sink.cpp @@ -4,19 +4,19 @@ namespace hidra2 { -void FluentdSink::_sink_it(const spdlog::details::log_msg &msg) { +void FluentdSink::_sink_it(const spdlog::details::log_msg& msg) { std::string log_str = msg.formatted.str(); HttpCode code; Error err; - log_str.erase(log_str.find_last_not_of("\n\r\t")+1); - std::string string_to_send = "json={\"message\":\""+log_str+"\"}"; - httpclient__->Post(endpoint_uri_,string_to_send,&code,&err); - if (err){ - std::cerr<<err->Explain(); + log_str.erase(log_str.find_last_not_of("\n\r\t") + 1); + std::string string_to_send = "json={\"message\":\"" + log_str + "\"}"; + httpclient__->Post(endpoint_uri_, string_to_send, &code, &err); + if (err) { + std::cerr << err->Explain(); } } -FluentdSink::FluentdSink(const std::string& endpoint_uri):httpclient__{DefaultHttpClient()},endpoint_uri_{endpoint_uri} { +FluentdSink::FluentdSink(const std::string& endpoint_uri): httpclient__{DefaultHttpClient()}, endpoint_uri_{endpoint_uri} { }; diff --git a/common/cpp/src/logger/fluentd_sink.h b/common/cpp/src/logger/fluentd_sink.h index cf59c4a0297d6634ad0b829f0468148678bec172..2f11aa4aad88ad1df8292809a5f7c5e557b8ddfc 100644 --- a/common/cpp/src/logger/fluentd_sink.h +++ b/common/cpp/src/logger/fluentd_sink.h @@ -8,15 +8,14 @@ namespace hidra2 { -class FluentdSink : public spdlog::sinks::base_sink<std::mutex> -{ - public: +class FluentdSink : public spdlog::sinks::base_sink<std::mutex> { + public: FluentdSink(const std::string& endpoint_uri); std::unique_ptr<HttpClient> httpclient__; - protected: + protected: void _sink_it(const spdlog::details::log_msg& msg) override; - void _flush() override{}; - private: + void _flush() override {}; + private: std::string endpoint_uri_; }; diff --git a/common/cpp/src/logger/logger_factory.cpp b/common/cpp/src/logger/logger_factory.cpp index be50587497b6d06f82c288c96bd5fe65bb8fe523..e13b425ec1306610dc1ad229c52dfac55db1ac1d 100644 --- a/common/cpp/src/logger/logger_factory.cpp +++ b/common/cpp/src/logger/logger_factory.cpp @@ -2,8 +2,8 @@ namespace hidra2 { -Logger CreateLogger(std::string name,bool console,bool centralized_log,const std::string& endpoint_uri) { - auto logger = new SpdLogger{name,endpoint_uri}; +Logger CreateLogger(std::string name, bool console, bool centralized_log, const std::string& endpoint_uri) { + auto logger = new SpdLogger{name, endpoint_uri}; logger->SetLogLevel(LogLevel::Error); if (console) { logger->EnableConsoleLog(true); @@ -17,11 +17,11 @@ Logger CreateLogger(std::string name,bool console,bool centralized_log,const std Logger CreateDefaultLoggerBin(const std::string& name) { - return CreateLogger(name,true,false,""); + return CreateLogger(name, true, false, ""); } -Logger CreateDefaultLoggerApi(const std::string& name,const std::string& endpoint_uri) { - return CreateLogger(name,false,true,endpoint_uri); +Logger CreateDefaultLoggerApi(const std::string& name, const std::string& endpoint_uri) { + return CreateLogger(name, false, true, endpoint_uri); } diff --git a/common/cpp/src/logger/spd_logger.cpp b/common/cpp/src/logger/spd_logger.cpp index e857bcf08be48fdfea37a37523678aa9c3f92112..be06859e074bada704d8a1715375ca6517cf7e5c 100644 --- a/common/cpp/src/logger/spd_logger.cpp +++ b/common/cpp/src/logger/spd_logger.cpp @@ -5,32 +5,30 @@ namespace hidra2 { void SpdLogger::SetLogLevel(LogLevel level) { - if (log_) { - switch (level){ - case LogLevel::None: - log_->set_level(spdlog::level::off); - break; - case LogLevel::Debug: - log_->set_level(spdlog::level::debug); - break; - case LogLevel::Error: - log_->set_level(spdlog::level::err); - break; - case LogLevel::Warning: - log_->set_level(spdlog::level::warn); - break; - case LogLevel::Info: - log_->set_level(spdlog::level::info); - break; - default: - log_->set_level(spdlog::level::err); + if (log__) { + switch (level) { + case LogLevel::None: + log__->set_level(spdlog::level::off); + break; + case LogLevel::Debug: + log__->set_level(spdlog::level::debug); + break; + case LogLevel::Error: + log__->set_level(spdlog::level::err); + break; + case LogLevel::Warning: + log__->set_level(spdlog::level::warn); + break; + case LogLevel::Info: + log__->set_level(spdlog::level::info); + break; } } } -void SpdLogger::Info(const std::string &text) { - if (log_) { - log_->info(text); +void SpdLogger::Info(const std::string& text) { + if (log__) { + log__->info(text); } } @@ -42,36 +40,35 @@ void SpdLogger::EnableConsoleLog(bool enable) { void SpdLogger::UpdateLoggerSinks() { sinks_.clear(); if (console_log_) { - sinks_.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>()); + sinks_.push_back(std::shared_ptr<spdlog::sinks::stdout_sink_mt> {new spdlog::sinks::stdout_sink_mt()}); } if (centralized_log_) { - sinks_.push_back(std::make_shared<FluentdSink>(endpoint_uri_)); + sinks_.push_back(std::shared_ptr<FluentdSink> {new FluentdSink(endpoint_uri_)}); } - log_ = std::make_shared<spdlog::logger>(name_, std::begin(sinks_), std::end(sinks_)); + log__ = std::unique_ptr<spdlog::logger> {new spdlog::logger(name_, std::begin(sinks_), std::end(sinks_))}; } -SpdLogger::SpdLogger(const std::string& name,const std::string& endpoint_uri): name_{name},endpoint_uri_{endpoint_uri} -{ +SpdLogger::SpdLogger(const std::string& name, const std::string& endpoint_uri): name_{name}, endpoint_uri_{endpoint_uri} { } -void SpdLogger::Error(const std::string &text) { - if (log_) { - log_->error(text); +void SpdLogger::Error(const std::string& text) { + if (log__) { + log__->error(text); } } -void SpdLogger::Debug(const std::string &text) { - if (log_) { - log_->debug(text); +void SpdLogger::Debug(const std::string& text) { + if (log__) { + log__->debug(text); } } -void SpdLogger::Warning(const std::string &text) { - if (log_) { - log_->warn(text); +void SpdLogger::Warning(const std::string& text) { + if (log__) { + log__->warn(text); } } diff --git a/common/cpp/src/logger/spd_logger.h b/common/cpp/src/logger/spd_logger.h index c37fe52f63963ac6d00b2f2ec097fe82549b4fe1..4d84934e70381057e22525ca24b9108630e8ddb5 100644 --- a/common/cpp/src/logger/spd_logger.h +++ b/common/cpp/src/logger/spd_logger.h @@ -7,24 +7,24 @@ namespace hidra2 { class SpdLogger : public AbstractLogger { - public: - explicit SpdLogger(const std::string& name,const std::string& endpoint_uri); + public: + explicit SpdLogger(const std::string& name, const std::string& endpoint_uri); void SetLogLevel(LogLevel level) override; - void Info(const std::string &text) override; - void Error(const std::string &text) override; - void Debug(const std::string &text) override; - void Warning(const std::string &text) override; + void Info(const std::string& text) override; + void Error(const std::string& text) override; + void Debug(const std::string& text) override; + void Warning(const std::string& text) override; void EnableConsoleLog(bool enable); void EnableCentralizedLog(bool enable); - private: + ~SpdLogger() = default; + std::unique_ptr<spdlog::logger> log__; + private: std::string name_; std::string endpoint_uri_; std::vector<spdlog::sink_ptr> sinks_; bool console_log_ = false; bool centralized_log_ = false; void UpdateLoggerSinks(); - std::shared_ptr<spdlog::logger> log_; - }; } diff --git a/common/cpp/unittests/logger/test_fluentd_sink.cpp b/common/cpp/unittests/logger/test_fluentd_sink.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c305dc6d3df96bccafbf490081352e236dffd33 --- /dev/null +++ b/common/cpp/unittests/logger/test_fluentd_sink.cpp @@ -0,0 +1,50 @@ +#include <gmock/gmock.h> +#include "gtest/gtest.h" + +#include "../../src/logger/spd_logger.h" +#include "../../src/logger/fluentd_sink.h" + +#include "unittests/MockHttpClient.h" +#include "http_client/http_error.h" + +using ::testing::AtLeast; +using ::testing::Eq; +using ::testing::Ne; +using ::testing::Test; +using ::testing::_; +using ::testing::Mock; +using ::testing::NiceMock; +using ::testing::Return; +using ::testing::SetArgPointee; +using ::testing::HasSubstr; +using ::testing::ElementsAre; +using ::testing::ElementsAre; +using hidra2::MockHttpClient; +using hidra2::FluentdSink; + + +namespace { + +class FluentdSinkTests : public Test { + public: + std::shared_ptr<FluentdSink>sink{new FluentdSink{"test_url"}}; + NiceMock<MockHttpClient> mock_http_client; + spdlog::details::log_msg msg; + std::unique_ptr<spdlog::logger> logger; + void SetUp() override { + sink->httpclient__ = std::unique_ptr<hidra2::HttpClient> {&mock_http_client}; + logger.reset(new spdlog::logger("mylogger", sink)); + } + void TearDown() override { + sink->httpclient__.release(); + } +}; + +TEST_F(FluentdSinkTests, SendPost) { + EXPECT_CALL(mock_http_client, Post_t("test_url", HasSubstr("hello"), _, _)); + logger->info("hello"); +} + + + +} diff --git a/common/cpp/unittests/logger/test_logger.cpp b/common/cpp/unittests/logger/test_logger.cpp index 8134e61f544bffd0a408f2c9d6b10de94e706a86..9fd923ce69529684b1813134cf0cad3f09642ed1 100644 --- a/common/cpp/unittests/logger/test_logger.cpp +++ b/common/cpp/unittests/logger/test_logger.cpp @@ -1,8 +1,6 @@ #include <gmock/gmock.h> #include "gtest/gtest.h" -//#include "json_parser/json_parser.h" - #include "../../src/logger/spd_logger.h" using ::testing::AtLeast; @@ -17,6 +15,7 @@ using ::testing::SetArgPointee; using ::testing::HasSubstr; using ::testing::ElementsAre; +using hidra2::LogLevel; namespace { @@ -26,8 +25,108 @@ TEST(DefaultLogger, BinLogger) { } TEST(DefaultLogger, ApiLogger) { - auto logger = hidra2::CreateDefaultLoggerApi("test","endpoint"); + auto logger = hidra2::CreateDefaultLoggerApi("test", "endpoint"); ASSERT_THAT(dynamic_cast<hidra2::SpdLogger*>(logger.get()), Ne(nullptr)); } + +class MockSink : public spdlog::sinks::base_sink<std::mutex> { + public: + MockSink(const std::string& endpoint_uri) {}; + public: + MOCK_METHOD1(_sink_it, void (const spdlog::details::log_msg& msg)); + MOCK_METHOD0(_flush, void ()); +}; + + +class LoggerTests : public Test { + public: + std::shared_ptr<MockSink>mock_sink{new MockSink{"test_url"}}; + std::unique_ptr<spdlog::logger> log; + hidra2::SpdLogger logger{"test", "test_uri"}; + spdlog::details::log_msg msg; + std::string test_string{"Hello"}; + void SetUp() override { + msg.raw << test_string; + log.reset(new spdlog::logger("mylogger", mock_sink)); + logger.log__ = std::move(log); + } + void TearDown() override { + } +}; + + +MATCHER_P(CompareMsg, msg, "") { + if (arg.level != (*msg).level) return false; + if (arg.raw.str() != (*msg).raw.c_str()) return false; + + return true; +} + + +TEST_F(LoggerTests, Info) { + msg.level = spdlog::level::info; + logger.SetLogLevel(LogLevel::Info); + + EXPECT_CALL(*mock_sink, _sink_it(CompareMsg(&msg))); + + logger.Info(test_string); +} + +TEST_F(LoggerTests, Debug) { + msg.level = spdlog::level::debug; + logger.SetLogLevel(LogLevel::Debug); + + EXPECT_CALL(*mock_sink, _sink_it(CompareMsg(&msg))); + + logger.Debug(test_string); +} + +TEST_F(LoggerTests, Error) { + msg.level = spdlog::level::err; + + EXPECT_CALL(*mock_sink, _sink_it(CompareMsg(&msg))); + + logger.Error(test_string); +} + + +TEST_F(LoggerTests, Warning) { + msg.level = spdlog::level::warn; + + EXPECT_CALL(*mock_sink, _sink_it(CompareMsg(&msg))); + + logger.Warning(test_string); +} + +TEST_F(LoggerTests, NoWarningOnErrorLevel) { + msg.level = spdlog::level::warn; + logger.SetLogLevel(LogLevel::Error); + + EXPECT_CALL(*mock_sink, _sink_it(CompareMsg(&msg))).Times(0); + + logger.Warning(test_string); +} + + +TEST_F(LoggerTests, NoInfoOnWarningLevel) { + msg.level = spdlog::level::info; + logger.SetLogLevel(LogLevel::Warning); + + EXPECT_CALL(*mock_sink, _sink_it(CompareMsg(&msg))).Times(0); + + logger.Info(test_string); +} + + +TEST_F(LoggerTests, NoDebugOnNoneLevel) { + msg.level = spdlog::level::debug; + logger.SetLogLevel(LogLevel::None); + + EXPECT_CALL(*mock_sink, _sink_it(CompareMsg(&msg))).Times(0); + + logger.Info(test_string); +} + + } diff --git a/config/fluentd/fluentd.conf b/config/fluentd/fluentd.conf index 9c361d4a1ce1e673d73b91e79bb8dfa55cb7f8d7..c41b6147cb73acaf8368c719bf5df40bd4a20e45 100644 --- a/config/fluentd/fluentd.conf +++ b/config/fluentd/fluentd.conf @@ -36,7 +36,8 @@ reserve_data true <store> @type file flush_interval 1s - path /fluentd/etc/asapo + buffer_type memory + path /tmp/fluentd/asapo </store> </match> diff --git a/config/fluentd/start b/config/fluentd/start index ab20e1f3e5330ed8aa0be4c5f4c713c773b8431b..46c78dda3529b41e742a836ff1abe5bc559e7d4e 100644 --- a/config/fluentd/start +++ b/config/fluentd/start @@ -1,2 +1,3 @@ fluent-gem install fluent-plugin-elasticsearch +or td-agent-gem install fluent-plugin-elasticsearch docker run -p 9880:9880 -v `pwd`:/fluentd/etc -e FLUENTD_CONF=fluentd.conf --name fluentd --net elk fluent/fluentd \ No newline at end of file diff --git a/receiver/CMakeLists.txt b/receiver/CMakeLists.txt index 3b188cff526c584db0d94e1d0e2d90290eb004c7..a5d795a7ccf763b0735c11fc5c603bc6df582889 100644 --- a/receiver/CMakeLists.txt +++ b/receiver/CMakeLists.txt @@ -19,7 +19,7 @@ set(SOURCE_FILES add_library(${TARGET_NAME} STATIC ${SOURCE_FILES} $<TARGET_OBJECTS:system_io> $<TARGET_OBJECTS:curl_http_client> $<TARGET_OBJECTS:json_parser>) set_target_properties(${TARGET_NAME} PROPERTIES LINKER_LANGUAGE CXX) -target_include_directories(${TARGET_NAME} PUBLIC ${HIDRA2_CXX_COMMON_INCLUDE_DIR}) +target_include_directories(${TARGET_NAME} PUBLIC ${HIDRA2_CXX_COMMON_INCLUDE_DIR} ${CURL_INCLUDE_DIRS}) target_link_libraries(${TARGET_NAME} ${CURL_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} database) diff --git a/tests/automatic/spd_logger/console/check_linux.sh b/tests/automatic/spd_logger/console/check_linux.sh index c7943910731817b7e894abf28c8f4d33d2c0e86d..9aba0eea3852db2066957ffde9e0842f6b39a323 100644 --- a/tests/automatic/spd_logger/console/check_linux.sh +++ b/tests/automatic/spd_logger/console/check_linux.sh @@ -2,7 +2,7 @@ set -e -res=`$1` +res=`$@` echo $res | grep "\[info\] test_info" echo $res | grep "\[error\] test_error" diff --git a/tests/automatic/spd_logger/console/check_windows.bat b/tests/automatic/spd_logger/console/check_windows.bat index 8a470b403ca5365ccd54e6fd4be67f649e15a922..8ed466f7e91f94297b19accdc58643b74e7899ad 100644 --- a/tests/automatic/spd_logger/console/check_windows.bat +++ b/tests/automatic/spd_logger/console/check_windows.bat @@ -1,19 +1,35 @@ -set full_recv_name="%2" -set short_recv_name="%~nx2" - -start /B "" "%full_recv_name%" receiver.json - -ping 1.0.0.0 -n 1 -w 100 > nul - -mkdir files - -%1 localhost:4200 100 1 - -ping 1.0.0.0 -n 1 -w 100 > nul - -FOR /F "usebackq" %%A IN ('files\1.bin') DO set size=%%~zA - -if %size% NEQ 102400 goto :error +"%1" > output + +findstr /I /L /C:"[info] test_info" output || goto :error +findstr /I /L /C:"[error] test_error" output || goto :error +findstr /I /L /C:"[debug] test_debug" output|| goto :error +findstr /I /L /C:"[warning] test_warning" output || goto :error +findstr /I /L /C:"test_info_mt_0" output || goto :error +findstr /I /L /C:"test_info_mt_1" output || goto :error +findstr /I /L /C:"test_info_mt_2" output || goto :error +findstr /I /L /C:"test_info_mt_3" output || goto :error +findstr /I /L /C:"test_logger" output || goto :error + +REM error_lev +findstr /I /L /C:"test_error_errorlev" output || goto :error +findstr /I /L /C:"test_debug_errorlev" output && goto :error +findstr /I /L /C:"test_info_errorlev" output && goto :error +findstr /I /L /C:"test_warning_errorlev" output && goto :error + +REM warning_lev +findstr /I /L /C:"test_error_warninglev" output || goto :error +findstr /I /L /C:"test_debug_warninglev" output && goto :error +findstr /I /L /C:"test_info_warninglev" output && goto :error +findstr /I /L /C:"test_warning_warninglev" output || goto :error + +REM info_lev +findstr /I /L /C:"test_error_infolev" output || goto :error +findstr /I /L /C:"test_debug_infolev" output && goto :error +findstr /I /L /C:"test_info_infolev" output || goto :error +findstr /I /L /C:"test_warning_infolev" output || goto :error + +REM none_lev +findstr /I /L /C:"nonelev" output && goto :error goto :clean @@ -22,10 +38,5 @@ call :clean exit /b 1 :clean -Taskkill /IM "%short_recv_name%" /F -rmdir /S /Q files -SET database_name=test_run -SET mongo_exe="c:\Program Files\MongoDB\Server\3.6\bin\mongo.exe" -echo db.dropDatabase() | %mongo_exe% %database_name% - +del output diff --git a/tests/automatic/spd_logger/console/spd_logger_console.cpp b/tests/automatic/spd_logger/console/spd_logger_console.cpp index 9a04abfa645b92cdd581e38616535ac32ffb1319..2659b7f0096dc110ffd4f7681c00ef5246a261b5 100644 --- a/tests/automatic/spd_logger/console/spd_logger_console.cpp +++ b/tests/automatic/spd_logger/console/spd_logger_console.cpp @@ -11,7 +11,7 @@ int main(int argc, char* argv[]) { logger->SetLogLevel(LogLevel::Debug); - auto exec = [&](const std::string& i) { + auto exec = [&](const std::string & i) { logger->Info("test_info_mt_" + i); }; diff --git a/tests/automatic/spd_logger/fluentd/check_linux.sh b/tests/automatic/spd_logger/fluentd/check_linux.sh index 03ebe0750ce2298ff274f427aa0e033fd32ab78a..50942dfa45c623ea8c17d147ede7feb0d511c659 100644 --- a/tests/automatic/spd_logger/fluentd/check_linux.sh +++ b/tests/automatic/spd_logger/fluentd/check_linux.sh @@ -2,16 +2,15 @@ set -e +rm -f /tmp/fluentd/asapo.*.log -rm -f $HOME/fluentd/asapo.*.log +$@ -$1 +sleep 5 -sleep 2 +cat /tmp/fluentd/asapo.*.log -cat $HOME/fluentd/asapo.*.log - -res=`cat $HOME/fluentd/asapo.*.log` +res=`cat /tmp/fluentd/asapo.*.log` echo $res | grep "test_info" echo $res | grep "test_error" diff --git a/tests/automatic/spd_logger/fluentd/check_windows.bat b/tests/automatic/spd_logger/fluentd/check_windows.bat index 8a470b403ca5365ccd54e6fd4be67f649e15a922..2edd95733218b775520cccb13e474553a67456e0 100644 --- a/tests/automatic/spd_logger/fluentd/check_windows.bat +++ b/tests/automatic/spd_logger/fluentd/check_windows.bat @@ -1,19 +1,15 @@ -set full_recv_name="%2" -set short_recv_name="%~nx2" +set folder=c:\opt\td-agent\logs +del %folder%\asapo.*.log -start /B "" "%full_recv_name%" receiver.json +"%1" -ping 1.0.0.0 -n 1 -w 100 > nul +ping 1.0.0.0 -n 5 > nul -mkdir files +findstr /I /L /C:"test_info" %folder%\asapo.*.log || goto :error +findstr /I /L /C:"test_error" %folder%\asapo.*.log || goto :error +findstr /I /L /C:"test_debug" %folder%\asapo.*.log || goto :error +findstr /I /L /C:"test_warning" %folder%\asapo.*.log || goto :error -%1 localhost:4200 100 1 - -ping 1.0.0.0 -n 1 -w 100 > nul - -FOR /F "usebackq" %%A IN ('files\1.bin') DO set size=%%~zA - -if %size% NEQ 102400 goto :error goto :clean @@ -22,10 +18,4 @@ call :clean exit /b 1 :clean -Taskkill /IM "%short_recv_name%" /F -rmdir /S /Q files -SET database_name=test_run -SET mongo_exe="c:\Program Files\MongoDB\Server\3.6\bin\mongo.exe" -echo db.dropDatabase() | %mongo_exe% %database_name% - - +del output diff --git a/tests/automatic/spd_logger/fluentd/spd_logger_fluentd.cpp b/tests/automatic/spd_logger/fluentd/spd_logger_fluentd.cpp index 82a893aef0acb30809996bad50252b459c25fc8f..4a3aa1d575397d09bbebff9580b9b0927f9083f6 100644 --- a/tests/automatic/spd_logger/fluentd/spd_logger_fluentd.cpp +++ b/tests/automatic/spd_logger/fluentd/spd_logger_fluentd.cpp @@ -7,7 +7,7 @@ using namespace hidra2; int main(int argc, char* argv[]) { - auto logger = CreateDefaultLoggerApi("test_central","http://localhost:9880/asapo"); + auto logger = CreateDefaultLoggerApi("test_central", "http://localhost:9880/asapo"); logger->SetLogLevel(LogLevel::Debug); diff --git a/tests/manual/performance_full_chain_simple/test.sh b/tests/manual/performance_full_chain_simple/test.sh index 77c63a85c1bb178b0ac11fb9c0779c7020c8b603..b393711a2f9aa0976aa6c11e89fbe16feee68385 100755 --- a/tests/manual/performance_full_chain_simple/test.sh +++ b/tests/manual/performance_full_chain_simple/test.sh @@ -21,8 +21,8 @@ monitor_port=8086 # starts receiver on $receiver_node # runs producer with various file sizes from $producer_node and measures performance -file_size=10000 -file_num=$((10000000 / $file_size)) +file_size=100 +file_num=$((100000000 / $file_size)) echo filesize: ${file_size}K, filenum: $file_num # receiver_setup diff --git a/tests/manual/performance_producer_receiver/settings_tmp.json b/tests/manual/performance_producer_receiver/settings_tmp.json new file mode 100644 index 0000000000000000000000000000000000000000..7b5460157dced99ec9b24104f48b482173cc6d47 --- /dev/null +++ b/tests/manual/performance_producer_receiver/settings_tmp.json @@ -0,0 +1,9 @@ +{ + "MonitorDbAddress": "zitpcx27016:8086", + "MonitorDbName": "db_test", + "BrokerDbAddress": "localhost:27017", + "BrokerDbName": "test_run", + "ListenPort": 4201, + "WriteToDisk": true, + "WriteToDb": true +} diff --git a/worker/api/cpp/CMakeLists.txt b/worker/api/cpp/CMakeLists.txt index f1e94bf530865f3ad717158722fead7f3a6ee8e7..8d67c6fe9dee2b05fac32cabe28c445856fef25b 100644 --- a/worker/api/cpp/CMakeLists.txt +++ b/worker/api/cpp/CMakeLists.txt @@ -13,7 +13,7 @@ set(SOURCE_FILES add_library(${TARGET_NAME} STATIC ${SOURCE_FILES} $<TARGET_OBJECTS:system_io> $<TARGET_OBJECTS:json_parser> $<TARGET_OBJECTS:data_structs> $<TARGET_OBJECTS:curl_http_client> ) -target_include_directories(${TARGET_NAME} PUBLIC include ${HIDRA2_CXX_COMMON_INCLUDE_DIR}) +target_include_directories(${TARGET_NAME} PUBLIC include ${HIDRA2_CXX_COMMON_INCLUDE_DIR} ${CURL_INCLUDE_DIRS}) IF(CMAKE_C_COMPILER_ID STREQUAL "GNU") SET( CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++") diff --git a/worker/api/cpp/src/server_data_broker.cpp b/worker/api/cpp/src/server_data_broker.cpp index 37ef745d68ab88ebaef51c11c0c5aa66271e1721..2ef08a29e64c6c619531c328979dbd1657cdde2c 100644 --- a/worker/api/cpp/src/server_data_broker.cpp +++ b/worker/api/cpp/src/server_data_broker.cpp @@ -40,7 +40,7 @@ Error HttpCodeToWorkerError(const HttpCode& code) { ServerDataBroker::ServerDataBroker(const std::string& server_uri, const std::string& source_name): io__{GenerateDefaultIO()}, httpclient__{DefaultHttpClient()}, -server_uri_{server_uri}, source_name_{source_name} { + server_uri_{server_uri}, source_name_{source_name} { } Error ServerDataBroker::Connect() {