Upgrade SpdLog library to 1.11.0

* Upgrade SpdLog library to 1.11.0.
* Compile SpdLog as static library.
This commit is contained in:
Kawe Mazidjatari 2023-03-18 13:34:43 +01:00
parent f7e7858dae
commit fd7e981e8c
127 changed files with 9884 additions and 7439 deletions

View File

@ -11,6 +11,7 @@
#include <Ws2tcpip.h>
#include <bcrypt.h>
#include <comdef.h>
#include <direct.h>
#include <gdiplus.h>
#include <timeapi.h>
#include <shellapi.h>
@ -76,14 +77,14 @@
#include "thirdparty/lzham/include/lzham.h"
#endif // !SDKLAUNCHER && !NETCONSOLE && !PLUGINSDK
#include "thirdparty/spdlog/include/spdlog.h"
#include "thirdparty/spdlog/include/async.h"
#include "thirdparty/spdlog/include/sinks/ostream_sink.h"
#include "thirdparty/spdlog/include/sinks/basic_file_sink.h"
#include "thirdparty/spdlog/include/sinks/stdout_sinks.h"
#include "thirdparty/spdlog/include/sinks/stdout_color_sinks.h"
#include "thirdparty/spdlog/include/sinks/ansicolor_sink.h"
#include "thirdparty/spdlog/include/sinks/rotating_file_sink.h"
#include "thirdparty/spdlog/spdlog.h"
#include "thirdparty/spdlog/async.h"
#include "thirdparty/spdlog/sinks/ostream_sink.h"
#include "thirdparty/spdlog/sinks/basic_file_sink.h"
#include "thirdparty/spdlog/sinks/stdout_sinks.h"
#include "thirdparty/spdlog/sinks/stdout_color_sinks.h"
#include "thirdparty/spdlog/sinks/ansicolor_sink.h"
#include "thirdparty/spdlog/sinks/rotating_file_sink.h"
#include "thirdparty/curl/include/curl/curl.h"

View File

@ -14,9 +14,9 @@
// This is because each message in the queue holds a shared_ptr to the
// originating logger.
#include <thirdparty/spdlog/include/async_logger.h>
#include <thirdparty/spdlog/include/details/registry.h>
#include <thirdparty/spdlog/include/details/thread_pool.h>
#include <spdlog/async_logger.h>
#include <spdlog/details/registry.h>
#include <spdlog/details/thread_pool.h>
#include <memory>
#include <mutex>
@ -35,7 +35,7 @@ template<async_overflow_policy OverflowPolicy = async_overflow_policy::block>
struct async_factory_impl
{
template<typename Sink, typename... SinkArgs>
static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&...args)
static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&... args)
{
auto &registry_inst = details::registry::instance();
@ -61,28 +61,34 @@ using async_factory = async_factory_impl<async_overflow_policy::block>;
using async_factory_nonblock = async_factory_impl<async_overflow_policy::overrun_oldest>;
template<typename Sink, typename... SinkArgs>
inline std::shared_ptr<spdlog::logger> create_async(std::string logger_name, SinkArgs &&...sink_args)
inline std::shared_ptr<spdlog::logger> create_async(std::string logger_name, SinkArgs &&... sink_args)
{
return async_factory::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
}
template<typename Sink, typename... SinkArgs>
inline std::shared_ptr<spdlog::logger> create_async_nb(std::string logger_name, SinkArgs &&...sink_args)
inline std::shared_ptr<spdlog::logger> create_async_nb(std::string logger_name, SinkArgs &&... sink_args)
{
return async_factory_nonblock::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
}
// set global thread pool.
inline void init_thread_pool(size_t q_size, size_t thread_count, std::function<void()> on_thread_start)
inline void init_thread_pool(
size_t q_size, size_t thread_count, std::function<void()> on_thread_start, std::function<void()> on_thread_stop)
{
auto tp = std::make_shared<details::thread_pool>(q_size, thread_count, on_thread_start);
auto tp = std::make_shared<details::thread_pool>(q_size, thread_count, on_thread_start, on_thread_stop);
details::registry::instance().set_tp(std::move(tp));
}
// set global thread pool.
inline void init_thread_pool(size_t q_size, size_t thread_count, std::function<void()> on_thread_start)
{
init_thread_pool(q_size, thread_count, on_thread_start, [] {});
}
inline void init_thread_pool(size_t q_size, size_t thread_count)
{
init_thread_pool(q_size, thread_count, [] {});
init_thread_pool(
q_size, thread_count, [] {}, [] {});
}
// get the global thread pool.

View File

@ -4,11 +4,11 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/async_logger.h>
# include <spdlog/async_logger.h>
#endif
#include <thirdparty/spdlog/include/sinks/sink.h>
#include <thirdparty/spdlog/include/details/thread_pool.h>
#include <spdlog/sinks/sink.h>
#include <spdlog/details/thread_pool.h>
#include <memory>
#include <string>
@ -62,7 +62,7 @@ SPDLOG_INLINE void spdlog::async_logger::backend_sink_it_(const details::log_msg
{
sink->log(msg);
}
SPDLOG_LOGGER_CATCH()
SPDLOG_LOGGER_CATCH(msg.source)
}
}
@ -80,7 +80,7 @@ SPDLOG_INLINE void spdlog::async_logger::backend_flush_()
{
sink->flush();
}
SPDLOG_LOGGER_CATCH()
SPDLOG_LOGGER_CATCH(source_loc())
}
}

View File

@ -14,7 +14,7 @@
// Upon destruction, logs all remaining messages in the queue before
// destructing..
#include <thirdparty/spdlog/include/logger.h>
#include <spdlog/logger.h>
namespace spdlog {
@ -64,5 +64,5 @@ private:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "async_logger-inl.h"
# include "async_logger-inl.h"
#endif

View File

@ -2,8 +2,8 @@
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#include <thirdparty/spdlog/include/cfg/helpers.h>
#include <thirdparty/spdlog/include/details/registry.h>
#include <spdlog/cfg/helpers.h>
#include <spdlog/details/registry.h>
//
// Init log levels using each argv entry that starts with "SPDLOG_LEVEL="

View File

@ -2,9 +2,9 @@
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#include <thirdparty/spdlog/include/cfg/helpers.h>
#include <thirdparty/spdlog/include/details/registry.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <spdlog/cfg/helpers.h>
#include <spdlog/details/registry.h>
#include <spdlog/details/os.h>
//
// Init levels and patterns from env variables SPDLOG_LEVEL

View File

@ -4,12 +4,12 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/cfg/helpers.h>
# include <spdlog/cfg/helpers.h>
#endif
#include <thirdparty/spdlog/include/spdlog.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <thirdparty/spdlog/include/details/registry.h>
#include <spdlog/spdlog.h>
#include <spdlog/details/os.h>
#include <spdlog/details/registry.h>
#include <algorithm>
#include <string>

View File

@ -3,7 +3,7 @@
#pragma once
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <unordered_map>
namespace spdlog {
@ -25,5 +25,5 @@ SPDLOG_API void load_levels(const std::string &txt);
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "helpers-inl.h"
# include "helpers-inl.h"
#endif // SPDLOG_HEADER_ONLY

View File

@ -4,7 +4,7 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/common.h>
# include <spdlog/common.h>
#endif
#include <algorithm>
@ -16,7 +16,7 @@ namespace level {
#if __cplusplus >= 201703L
constexpr
#endif
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES;
@ -55,9 +55,13 @@ SPDLOG_INLINE spdlog_ex::spdlog_ex(std::string msg)
SPDLOG_INLINE spdlog_ex::spdlog_ex(const std::string &msg, int last_errno)
{
#ifdef SPDLOG_USE_STD_FORMAT
msg_ = std::system_error(std::error_code(last_errno, std::generic_category()), msg).what();
#else
memory_buf_t outbuf;
fmt::format_system_error(outbuf, last_errno, msg.c_str());
msg_ = fmt::to_string(outbuf);
#endif
}
SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT

View File

@ -3,8 +3,8 @@
#pragma once
#include <thirdparty/spdlog/include/tweakme.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <spdlog/tweakme.h>
#include <spdlog/details/null_mutex.h>
#include <atomic>
#include <chrono>
@ -14,16 +14,25 @@
#include <string>
#include <type_traits>
#include <functional>
#include <cstdio>
#ifdef SPDLOG_USE_STD_FORMAT
# include <string_view>
#endif
#ifdef SPDLOG_COMPILED_LIB
# undef SPDLOG_HEADER_ONLY
# if defined(_WIN32) && defined(SPDLOG_SHARED_LIB)
# ifdef spdlog_EXPORTS
# define SPDLOG_API __declspec(dllexport)
# else
# define SPDLOG_API __declspec(dllimport)
# if defined(SPDLOG_SHARED_LIB)
# if defined(_WIN32)
# ifdef spdlog_EXPORTS
# define SPDLOG_API __declspec(dllexport)
# else // !spdlog_EXPORTS
# define SPDLOG_API __declspec(dllimport)
# endif
# else // !defined(_WIN32)
# define SPDLOG_API __attribute__((visibility("default")))
# endif
# else // !defined(_WIN32) || !defined(SPDLOG_SHARED_LIB)
# else // !defined(SPDLOG_SHARED_LIB)
# define SPDLOG_API
# endif
# define SPDLOG_INLINE
@ -33,19 +42,32 @@
# define SPDLOG_INLINE inline
#endif // #ifdef SPDLOG_COMPILED_LIB
#include <thirdparty/spdlog/include/fmt/fmt.h>
#include <spdlog/fmt/fmt.h>
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
# include <fmt/xchar.h>
#if !defined(SPDLOG_USE_STD_FORMAT) && FMT_VERSION >= 80000 // backward compatibility with fmt versions older than 8
# define SPDLOG_FMT_RUNTIME(format_string) fmt::runtime(format_string)
# define SPDLOG_FMT_STRING(format_string) FMT_STRING(format_string)
# if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
# include <spdlog/fmt/xchar.h>
# endif
#else
# define SPDLOG_FMT_RUNTIME(format_string) format_string
# define SPDLOG_FMT_STRING(format_string) format_string
#endif
// visual studio upto 2013 does not support noexcept nor constexpr
// visual studio up to 2013 does not support noexcept nor constexpr
#if defined(_MSC_VER) && (_MSC_VER < 1900)
# define SPDLOG_NOEXCEPT _NOEXCEPT
# define SPDLOG_CONSTEXPR
# define SPDLOG_CONSTEXPR_FUNC
#else
# define SPDLOG_NOEXCEPT noexcept
# define SPDLOG_CONSTEXPR constexpr
# if __cplusplus >= 201402L
# define SPDLOG_CONSTEXPR_FUNC constexpr
# else
# define SPDLOG_CONSTEXPR_FUNC
# endif
#endif
#if defined(__GNUC__) || defined(__clang__)
@ -105,24 +127,67 @@ using log_clock = std::chrono::system_clock;
using sink_ptr = std::shared_ptr<sinks::sink>;
using sinks_init_list = std::initializer_list<sink_ptr>;
using err_handler = std::function<void(const std::string &err_msg)>;
#ifdef SPDLOG_USE_STD_FORMAT
namespace fmt_lib = std;
using string_view_t = std::string_view;
using memory_buf_t = std::string;
template<typename... Args>
using format_string_t = std::string_view;
template<class T, class Char = char>
struct is_convertible_to_basic_format_string : std::integral_constant<bool, std::is_convertible<T, std::basic_string_view<Char>>::value>
{};
# if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
using wstring_view_t = std::wstring_view;
using wmemory_buf_t = std::wstring;
template<typename... Args>
using wformat_string_t = std::wstring_view;
# endif
# define SPDLOG_BUF_TO_STRING(x) x
#else // use fmt lib instead of std::format
namespace fmt_lib = fmt;
using string_view_t = fmt::basic_string_view<char>;
using wstring_view_t = fmt::basic_string_view<wchar_t>;
using memory_buf_t = fmt::basic_memory_buffer<char, 250>;
template<typename... Args>
using format_string_t = fmt::format_string<Args...>;
template<class T>
using remove_cvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
// clang doesn't like SFINAE disabled constructor in std::is_convertible<> so have to repeat the condition from basic_format_string here,
// in addition, fmt::basic_runtime<Char> is only convertible to basic_format_string<Char> but not basic_string_view<Char>
template<class T, class Char = char>
struct is_convertible_to_basic_format_string
: std::integral_constant<bool,
std::is_convertible<T, fmt::basic_string_view<Char>>::value || std::is_same<remove_cvref_t<T>, fmt::basic_runtime<Char>>::value>
{};
# if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
using wstring_view_t = fmt::basic_string_view<wchar_t>;
using wmemory_buf_t = fmt::basic_memory_buffer<wchar_t, 250>;
template<typename... Args>
using wformat_string_t = fmt::wformat_string<Args...>;
# endif
# define SPDLOG_BUF_TO_STRING(x) fmt::to_string(x)
#endif
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
# ifndef _WIN32
# error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
# else
template<typename T>
struct is_convertible_to_wstring_view : std::is_convertible<T, wstring_view_t>
{};
# endif // _WIN32
#else
template<typename>
struct is_convertible_to_wstring_view : std::false_type
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
template<class T>
struct is_convertible_to_any_format_string : std::integral_constant<bool, is_convertible_to_basic_format_string<T, char>::value ||
is_convertible_to_basic_format_string<T, wchar_t>::value>
{};
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
#if defined(SPDLOG_NO_ATOMIC_LEVELS)
using level_t = details::null_atomic_int;
@ -144,7 +209,7 @@ using level_t = std::atomic<int>;
// Log level enum
namespace level {
enum level_enum
enum level_enum : int
{
trace = SPDLOG_LEVEL_TRACE,
debug = SPDLOG_LEVEL_DEBUG,
@ -156,13 +221,13 @@ enum level_enum
n_levels
};
#define SPDLOG_LEVEL_NAME_TRACE string_view_t("trace", 5)
#define SPDLOG_LEVEL_NAME_DEBUG string_view_t("debug", 5)
#define SPDLOG_LEVEL_NAME_INFO string_view_t("info", 4)
#define SPDLOG_LEVEL_NAME_WARNING string_view_t("warning", 7)
#define SPDLOG_LEVEL_NAME_ERROR string_view_t("error", 5)
#define SPDLOG_LEVEL_NAME_CRITICAL string_view_t("critical", 8)
#define SPDLOG_LEVEL_NAME_OFF string_view_t("off", 3)
#define SPDLOG_LEVEL_NAME_TRACE spdlog::string_view_t("trace", 5)
#define SPDLOG_LEVEL_NAME_DEBUG spdlog::string_view_t("debug", 5)
#define SPDLOG_LEVEL_NAME_INFO spdlog::string_view_t("info", 4)
#define SPDLOG_LEVEL_NAME_WARNING spdlog::string_view_t("warning", 7)
#define SPDLOG_LEVEL_NAME_ERROR spdlog::string_view_t("error", 5)
#define SPDLOG_LEVEL_NAME_CRITICAL spdlog::string_view_t("critical", 8)
#define SPDLOG_LEVEL_NAME_OFF spdlog::string_view_t("off", 3)
#if !defined(SPDLOG_LEVEL_NAMES)
# define SPDLOG_LEVEL_NAMES \
@ -241,19 +306,53 @@ struct source_loc
const char *funcname{nullptr};
};
struct file_event_handlers
{
file_event_handlers()
: before_open(nullptr)
, after_open(nullptr)
, before_close(nullptr)
, after_close(nullptr)
{}
std::function<void(const filename_t &filename)> before_open;
std::function<void(const filename_t &filename, std::FILE *file_stream)> after_open;
std::function<void(const filename_t &filename, std::FILE *file_stream)> before_close;
std::function<void(const filename_t &filename)> after_close;
};
namespace details {
// make_unique support for pre c++14
#if __cplusplus >= 201402L // C++14 and beyond
using std::enable_if_t;
using std::make_unique;
#else
template<bool B, class T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args &&...args)
std::unique_ptr<T> make_unique(Args &&... args)
{
static_assert(!std::is_array<T>::value, "arrays not supported");
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif
// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
template<typename T, typename U, enable_if_t<!std::is_same<T, U>::value, int> = 0>
constexpr T conditional_static_cast(U value)
{
return static_cast<T>(value);
}
template<typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
constexpr T conditional_static_cast(U value)
{
return value;
}
} // namespace details
} // namespace spdlog

View File

@ -4,7 +4,7 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/details/backtracer.h>
# include <spdlog/details/backtracer.h>
#endif
namespace spdlog {
namespace details {

View File

@ -3,8 +3,8 @@
#pragma once
#include <thirdparty/spdlog/include/details/log_msg_buffer.h>
#include <thirdparty/spdlog/include/details/circular_q.h>
#include <spdlog/details/log_msg_buffer.h>
#include <spdlog/details/circular_q.h>
#include <atomic>
#include <mutex>
@ -41,6 +41,5 @@ public:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "backtracer-inl.h"
# include "backtracer-inl.h"
#endif

View File

@ -121,6 +121,11 @@ public:
return overrun_counter_;
}
void reset_overrun_counter()
{
overrun_counter_ = 0;
}
private:
// copy from other&& and reset it to disabled state
void copy_moveable(circular_q &&other) SPDLOG_NOEXCEPT

View File

@ -3,7 +3,7 @@
#pragma once
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <spdlog/details/null_mutex.h>
#include <mutex>
namespace spdlog {

View File

@ -4,11 +4,11 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/thirdparty/spdlog/include/details/file_helper.h>
# include <spdlog/details/file_helper.h>
#endif
#include <thirdparty/spdlog/include/details/os.h>
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/details/os.h>
#include <spdlog/common.h>
#include <cerrno>
#include <chrono>
@ -20,6 +20,10 @@
namespace spdlog {
namespace details {
SPDLOG_INLINE file_helper::file_helper(const file_event_handlers &event_handlers)
: event_handlers_(event_handlers)
{}
SPDLOG_INLINE file_helper::~file_helper()
{
close();
@ -33,6 +37,10 @@ SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate)
auto *mode = SPDLOG_FILENAME_T("ab");
auto *trunc_mode = SPDLOG_FILENAME_T("wb");
if (event_handlers_.before_open)
{
event_handlers_.before_open(filename_);
}
for (int tries = 0; tries < open_tries_; ++tries)
{
// create containing folder if not exists already.
@ -52,6 +60,10 @@ SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate)
}
if (!os::fopen_s(&fd_, fname, mode))
{
if (event_handlers_.after_open)
{
event_handlers_.after_open(filename_, fd_);
}
return;
}
@ -72,15 +84,28 @@ SPDLOG_INLINE void file_helper::reopen(bool truncate)
SPDLOG_INLINE void file_helper::flush()
{
std::fflush(fd_);
if (std::fflush(fd_) != 0)
{
throw_spdlog_ex("Failed flush to file " + os::filename_to_str(filename_), errno);
}
}
SPDLOG_INLINE void file_helper::close()
{
if (fd_ != nullptr)
{
if (event_handlers_.before_close)
{
event_handlers_.before_close(filename_, fd_);
}
std::fclose(fd_);
fd_ = nullptr;
if (event_handlers_.after_close)
{
event_handlers_.after_close(filename_);
}
}
}

View File

@ -3,7 +3,7 @@
#pragma once
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <tuple>
namespace spdlog {
@ -16,7 +16,8 @@ namespace details {
class SPDLOG_API file_helper
{
public:
explicit file_helper() = default;
file_helper() = default;
explicit file_helper(const file_event_handlers &event_handlers);
file_helper(const file_helper &) = delete;
file_helper &operator=(const file_helper &) = delete;
@ -50,10 +51,11 @@ private:
const unsigned int open_interval_ = 10;
std::FILE *fd_{nullptr};
filename_t filename_;
file_event_handlers event_handlers_;
};
} // namespace details
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "file_helper-inl.h"
# include "file_helper-inl.h"
#endif

View File

@ -5,8 +5,13 @@
#include <chrono>
#include <type_traits>
#include <iterator>
#include <thirdparty/spdlog/include/fmt/fmt.h>
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/fmt/fmt.h>
#include <spdlog/common.h>
#ifdef SPDLOG_USE_STD_FORMAT
# include <charconv>
# include <limits>
#endif
// Some fmt helpers to efficiently format and pad ints and strings
namespace spdlog {
@ -24,26 +29,73 @@ inline void append_string_view(spdlog::string_view_t view, memory_buf_t &dest)
dest.append(buf_ptr, buf_ptr + view.size());
}
#ifdef SPDLOG_USE_STD_FORMAT
template<typename T>
inline void append_int(T n, memory_buf_t &dest)
{
// Buffer should be large enough to hold all digits (digits10 + 1) and a sign
SPDLOG_CONSTEXPR const auto BUF_SIZE = std::numeric_limits<T>::digits10 + 2;
char buf[BUF_SIZE];
auto [ptr, ec] = std::to_chars(buf, buf + BUF_SIZE, n, 10);
if (ec == std::errc())
{
dest.append(buf, ptr);
}
else
{
throw_spdlog_ex("Failed to format int", static_cast<int>(ec));
}
}
#else
template<typename T>
inline void append_int(T n, memory_buf_t &dest)
{
fmt::format_int i(n);
dest.append(i.data(), i.data() + i.size());
}
#endif
template<typename T>
SPDLOG_CONSTEXPR_FUNC unsigned int count_digits_fallback(T n)
{
// taken from fmt: https://github.com/fmtlib/fmt/blob/8.0.1/include/fmt/format.h#L899-L912
unsigned int count = 1;
for (;;)
{
// Integer division is slow so do it for a group of four digits instead
// of for every digit. The idea comes from the talk by Alexandrescu
// "Three Optimization Tips for C++". See speed-test for a comparison.
if (n < 10)
return count;
if (n < 100)
return count + 1;
if (n < 1000)
return count + 2;
if (n < 10000)
return count + 3;
n /= 10000u;
count += 4;
}
}
template<typename T>
inline unsigned int count_digits(T n)
{
using count_type = typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type;
#ifdef SPDLOG_USE_STD_FORMAT
return count_digits_fallback(static_cast<count_type>(n));
#else
return static_cast<unsigned int>(fmt::
// fmt 7.0.0 renamed the internal namespace to detail.
// See: https://github.com/fmtlib/fmt/issues/1538
#if FMT_VERSION < 70000
# if FMT_VERSION < 70000
internal
#else
# else
detail
#endif
# endif
::count_digits(static_cast<count_type>(n)));
#endif
}
inline void pad2(int n, memory_buf_t &dest)
@ -55,7 +107,7 @@ inline void pad2(int n, memory_buf_t &dest)
}
else // unlikely, but just in case, let fmt deal with it
{
fmt::format_to(std::back_inserter(dest), "{:02}", n);
fmt_lib::format_to(std::back_inserter(dest), SPDLOG_FMT_STRING("{:02}"), n);
}
}

View File

@ -4,10 +4,10 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/details/log_msg.h>
# include <spdlog/details/log_msg.h>
#endif
#include <thirdparty/spdlog/include/details/os.h>
#include <spdlog/details/os.h>
namespace spdlog {
namespace details {

View File

@ -3,7 +3,7 @@
#pragma once
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <string>
namespace spdlog {
@ -33,5 +33,5 @@ struct SPDLOG_API log_msg
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "log_msg-inl.h"
# include "log_msg-inl.h"
#endif

View File

@ -4,7 +4,7 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/details/log_msg_buffer.h>
# include <spdlog/details/log_msg_buffer.h>
#endif
namespace spdlog {
@ -26,9 +26,7 @@ SPDLOG_INLINE log_msg_buffer::log_msg_buffer(const log_msg_buffer &other)
update_string_views();
}
SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT
: log_msg{other}
, buffer{std::move(other.buffer)}
SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT : log_msg{other}, buffer{std::move(other.buffer)}
{
update_string_views();
}

View File

@ -3,7 +3,7 @@
#pragma once
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <spdlog/details/log_msg.h>
namespace spdlog {
namespace details {
@ -29,5 +29,5 @@ public:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "log_msg_buffer-inl.h"
# include "log_msg_buffer-inl.h"
#endif

View File

@ -10,7 +10,7 @@
// dequeue_for(..) - will block until the queue is not empty or timeout have
// passed.
#include <thirdparty/spdlog/include/details/circular_q.h>
#include <spdlog/details/circular_q.h>
#include <condition_variable>
#include <mutex>
@ -49,7 +49,7 @@ public:
push_cv_.notify_one();
}
// try to dequeue item. if no item found. wait upto timeout and try again
// try to dequeue item. if no item found. wait up to timeout and try again
// Return true, if succeeded dequeue item, false otherwise
bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration)
{
@ -87,7 +87,7 @@ public:
push_cv_.notify_one();
}
// try to dequeue item. if no item found. wait upto timeout and try again
// try to dequeue item. if no item found. wait up to timeout and try again
// Return true, if succeeded dequeue item, false otherwise
bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration)
{
@ -116,6 +116,12 @@ public:
return q_.size();
}
void reset_overrun_counter()
{
std::unique_lock<std::mutex> lock(queue_mutex_);
q_.reset_overrun_counter();
}
private:
std::mutex queue_mutex_;
std::condition_variable push_cv_;

View File

@ -13,10 +13,6 @@ struct null_mutex
{
void lock() const {}
void unlock() const {}
bool try_lock() const
{
return true;
}
};
struct null_atomic_int

View File

@ -4,10 +4,10 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/details/os.h>
# include <spdlog/details/os.h>
#endif
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <algorithm>
#include <chrono>
@ -23,45 +23,45 @@
#ifdef _WIN32
#include <io.h> // _get_osfhandle and _isatty support
#include <process.h> // _get_pid support
#include <thirdparty/spdlog/include/details/windows_include.h>
# include <io.h> // _get_osfhandle and _isatty support
# include <process.h> // _get_pid support
# include <spdlog/details/windows_include.h>
#ifdef __MINGW32__
#include <share.h>
#endif
# ifdef __MINGW32__
# include <share.h>
# endif
#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)
#include <limits>
#endif
# if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)
# include <limits>
# endif
#include <direct.h> // for _mkdir/_wmkdir
# include <direct.h> // for _mkdir/_wmkdir
#else // unix
#include <fcntl.h>
#include <unistd.h>
# include <fcntl.h>
# include <unistd.h>
#ifdef __linux__
#include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
# ifdef __linux__
# include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
#elif defined(_AIX)
#include <pthread.h> // for pthread_getthreadid_np
# elif defined(_AIX)
# include <pthread.h> // for pthread_getthrds_np
#elif defined(__DragonFly__) || defined(__FreeBSD__)
#include <pthread_np.h> // for pthread_getthreadid_np
# elif defined(__DragonFly__) || defined(__FreeBSD__)
# include <pthread_np.h> // for pthread_getthreadid_np
#elif defined(__NetBSD__)
#include <lwp.h> // for _lwp_self
# elif defined(__NetBSD__)
# include <lwp.h> // for _lwp_self
#elif defined(__sun)
#include <thread.h> // for thr_self
#endif
# elif defined(__sun)
# include <thread.h> // for thr_self
# endif
#endif // unix
#ifndef __has_feature // Clang - feature checking macros.
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#ifndef __has_feature // Clang - feature checking macros.
# define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif
namespace spdlog {
@ -123,12 +123,12 @@ SPDLOG_INLINE std::tm gmtime() SPDLOG_NOEXCEPT
SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
# ifdef SPDLOG_WCHAR_FILENAMES
*fp = ::_wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#else
# else
*fp = ::_fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
#endif
#if defined(SPDLOG_PREVENT_CHILD_FD)
# endif
# if defined(SPDLOG_PREVENT_CHILD_FD)
if (*fp != nullptr)
{
auto file_handle = reinterpret_cast<HANDLE>(_get_osfhandle(::_fileno(*fp)));
@ -138,23 +138,23 @@ SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename
*fp = nullptr;
}
}
#endif
# endif
#else // unix
#if defined(SPDLOG_PREVENT_CHILD_FD)
# if defined(SPDLOG_PREVENT_CHILD_FD)
const int mode_flag = mode == SPDLOG_FILENAME_T("ab") ? O_APPEND : O_TRUNC;
const int fd = ::open((filename.c_str()), O_CREAT | O_WRONLY | O_CLOEXEC | mode_flag, mode_t(0644));
if (fd == -1)
{
return false;
return true;
}
*fp = ::fdopen(fd, mode.c_str());
if (*fp == nullptr)
{
::close(fd);
}
#else
# else
*fp = ::fopen((filename.c_str()), mode.c_str());
#endif
# endif
#endif
return *fp == nullptr;
@ -187,11 +187,11 @@ SPDLOG_INLINE int rename(const filename_t &filename1, const filename_t &filename
SPDLOG_INLINE bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
# ifdef SPDLOG_WCHAR_FILENAMES
auto attribs = ::GetFileAttributesW(filename.c_str());
#else
# else
auto attribs = ::GetFileAttributesA(filename.c_str());
#endif
# endif
return attribs != INVALID_FILE_ATTRIBUTES;
#else // common linux/unix all have the stat system call
struct stat buffer;
@ -200,9 +200,9 @@ SPDLOG_INLINE bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT
}
#ifdef _MSC_VER
// avoid warning about unreachable statement at the end of filesize()
#pragma warning(push)
#pragma warning(disable: 4702)
// avoid warning about unreachable statement at the end of filesize()
# pragma warning(push)
# pragma warning(disable : 4702)
#endif
// Return file size according to open FILE* object
@ -214,49 +214,49 @@ SPDLOG_INLINE size_t filesize(FILE *f)
}
#if defined(_WIN32) && !defined(__CYGWIN__)
int fd = ::_fileno(f);
#if defined(_WIN64) // 64 bits
# if defined(_WIN64) // 64 bits
__int64 ret = ::_filelengthi64(fd);
if (ret >= 0)
{
return static_cast<size_t>(ret);
}
#else // windows 32 bits
# else // windows 32 bits
long ret = ::_filelength(fd);
if (ret >= 0)
{
return static_cast<size_t>(ret);
}
#endif
# endif
#else // unix
// OpenBSD doesn't compile with :: before the fileno(..)
#if defined(__OpenBSD__)
// OpenBSD and AIX doesn't compile with :: before the fileno(..)
# if defined(__OpenBSD__) || defined(_AIX)
int fd = fileno(f);
#else
# else
int fd = ::fileno(f);
#endif
# endif
// 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
#if (defined(__linux__) || defined(__sun) || defined(_AIX)) && (defined(__LP64__) || defined(_LP64))
# if (defined(__linux__) || defined(__sun) || defined(_AIX)) && (defined(__LP64__) || defined(_LP64))
struct stat64 st;
if (::fstat64(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size);
}
#else // other unix or linux 32 bits or cygwin
# else // other unix or linux 32 bits or cygwin
struct stat st;
if (::fstat(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size);
}
#endif
# endif
#endif
throw_spdlog_ex("Failed getting file size from fd", errno);
return 0; // will not be reached.
}
#ifdef _MSC_VER
#pragma warning(pop)
# pragma warning(pop)
#endif
// Return utc offset in minutes or throw spdlog_ex on failure
@ -264,13 +264,13 @@ SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
{
#ifdef _WIN32
#if _WIN32_WINNT < _WIN32_WINNT_WS08
# if _WIN32_WINNT < _WIN32_WINNT_WS08
TIME_ZONE_INFORMATION tzinfo;
auto rv = ::GetTimeZoneInformation(&tzinfo);
#else
# else
DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
auto rv = ::GetDynamicTimeZoneInformation(&tzinfo);
#endif
# endif
if (rv == TIME_ZONE_ID_INVALID)
throw_spdlog_ex("Failed getting timezone info. ", errno);
@ -286,7 +286,7 @@ SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
return offset;
#else
#if defined(sun) || defined(__sun) || defined(_AIX) || (!defined(_BSD_SOURCE) && !defined(_GNU_SOURCE))
# if defined(sun) || defined(__sun) || defined(_AIX) || (!defined(_BSD_SOURCE) && !defined(_GNU_SOURCE))
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
struct helper
{
@ -305,7 +305,7 @@ SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
// + difference in years * 365 */
+ (long int)(local_year - gmt_year) * 365);
+ static_cast<long int>(local_year - gmt_year) * 365);
long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
@ -316,9 +316,9 @@ SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
};
auto offset_seconds = helper::calculate_gmt_offset(tm);
#else
# else
auto offset_seconds = tm.tm_gmtoff;
#endif
# endif
return static_cast<int>(offset_seconds / 60);
#endif
@ -332,11 +332,18 @@ SPDLOG_INLINE size_t _thread_id() SPDLOG_NOEXCEPT
#ifdef _WIN32
return static_cast<size_t>(::GetCurrentThreadId());
#elif defined(__linux__)
#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
#define SYS_gettid __NR_gettid
#endif
# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
# define SYS_gettid __NR_gettid
# endif
return static_cast<size_t>(::syscall(SYS_gettid));
#elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD__)
#elif defined(_AIX)
struct __pthrdsinfo buf;
int reg_size = 0;
pthread_t pt = pthread_self();
int retval = pthread_getthrds_np(&pt, PTHRDSINFO_QUERY_TID, &buf, sizeof(buf), NULL, &reg_size);
int tid = (!retval) ? buf.__pi_tid : 0;
return static_cast<size_t>(tid);
#elif defined(__DragonFly__) || defined(__FreeBSD__)
return static_cast<size_t>(::pthread_getthreadid_np());
#elif defined(__NetBSD__)
return static_cast<size_t>(::_lwp_self());
@ -381,7 +388,7 @@ SPDLOG_INLINE std::string filename_to_str(const filename_t &filename)
{
memory_buf_t buf;
wstr_to_utf8buf(filename, buf);
return fmt::to_string(buf);
return SPDLOG_BUF_TO_STRING(buf);
}
#else
SPDLOG_INLINE std::string filename_to_str(const filename_t &filename)
@ -394,9 +401,9 @@ SPDLOG_INLINE int pid() SPDLOG_NOEXCEPT
{
#ifdef _WIN32
return static_cast<int>(::GetCurrentProcessId());
return conditional_static_cast<int>(::GetCurrentProcessId());
#else
return static_cast<int>(::getpid());
return conditional_static_cast<int>(::getpid());
#endif
}
@ -416,7 +423,7 @@ SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT
}
static constexpr std::array<const char *, 16> terms = {{"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux",
"msys", "putty", "rxvt", "screen", "vt100"), "xterm", "alacritty", "vt102"}};
"msys", "putty", "rxvt", "screen", "vt100", "xterm", "alacritty", "vt102"}};
const char *env_term_p = std::getenv("TERM");
if (env_term_p == nullptr)
@ -476,7 +483,7 @@ SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target)
}
}
throw_spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
throw_spdlog_ex(fmt_lib::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
}
SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target)
@ -511,7 +518,7 @@ SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target)
}
}
throw_spdlog_ex(fmt::format("MultiByteToWideChar failed. Last error: {}", ::GetLastError()));
throw_spdlog_ex(fmt_lib::format("MultiByteToWideChar failed. Last error: {}", ::GetLastError()));
}
#endif // (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
@ -519,11 +526,11 @@ SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target)
static SPDLOG_INLINE bool mkdir_(const filename_t &path)
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
# ifdef SPDLOG_WCHAR_FILENAMES
return ::_wmkdir(path.c_str()) == 0;
#else
# else
return ::_mkdir(path.c_str()) == 0;
#endif
# endif
#else
return ::mkdir(path.c_str(), mode_t(0755)) == 0;
#endif
@ -531,7 +538,7 @@ static SPDLOG_INLINE bool mkdir_(const filename_t &path)
// create the given directory - and all directories leading to it
// return true on success or if the directory already exists
SPDLOG_INLINE bool create_dir(filename_t path)
SPDLOG_INLINE bool create_dir(const filename_t &path)
{
if (path_exists(path))
{
@ -570,7 +577,7 @@ SPDLOG_INLINE bool create_dir(filename_t path)
// "abc/" => "abc"
// "abc" => ""
// "abc///" => "abc//"
SPDLOG_INLINE filename_t dir_name(filename_t path)
SPDLOG_INLINE filename_t dir_name(const filename_t &path)
{
auto pos = path.find_last_of(folder_seps_filename);
return pos != filename_t::npos ? path.substr(0, pos) : filename_t{};
@ -580,14 +587,14 @@ std::string SPDLOG_INLINE getenv(const char *field)
{
#if defined(_MSC_VER)
#if defined(__cplusplus_winrt)
# if defined(__cplusplus_winrt)
return std::string{}; // not supported under uwp
#else
# else
size_t len = 0;
char buf[128];
bool ok = ::getenv_s(&len, buf, sizeof(buf), field) == 0;
return ok ? buf : std::string{};
#endif
# endif
#else // revert to getenv
char *buf = ::getenv(field);
return buf ? buf : std::string{};

View File

@ -3,7 +3,7 @@
#pragma once
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <ctime> // std::time_t
namespace spdlog {
@ -22,22 +22,22 @@ SPDLOG_API std::tm gmtime() SPDLOG_NOEXCEPT;
// eol definition
#if !defined(SPDLOG_EOL)
#ifdef _WIN32
#define SPDLOG_EOL "\r\n"
#else
#define SPDLOG_EOL "\n"
#endif
# ifdef _WIN32
# define SPDLOG_EOL "\r\n"
# else
# define SPDLOG_EOL "\n"
# endif
#endif
SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
// folder separator
#if !defined(SPDLOG_FOLDER_SEPS)
#ifdef _WIN32
#define SPDLOG_FOLDER_SEPS "\\/"
#else
#define SPDLOG_FOLDER_SEPS "/"
#endif
# ifdef _WIN32
# define SPDLOG_FOLDER_SEPS "\\/"
# else
# define SPDLOG_FOLDER_SEPS "/"
# endif
#endif
SPDLOG_CONSTEXPR static const char folder_seps[] = SPDLOG_FOLDER_SEPS;
@ -99,11 +99,11 @@ SPDLOG_API void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target);
// "abc/" => "abc"
// "abc" => ""
// "abc///" => "abc//"
SPDLOG_API filename_t dir_name(filename_t path);
SPDLOG_API filename_t dir_name(const filename_t &path);
// Create a dir from the given path.
// Return true if succeeded or if this dir already exists.
SPDLOG_API bool create_dir(filename_t path);
SPDLOG_API bool create_dir(const filename_t &path);
// non thread safe, cross platform getenv/getenv_s
// return empty string if field not found
@ -114,5 +114,5 @@ SPDLOG_API std::string getenv(const char *field);
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "os-inl.h"
# include "os-inl.h"
#endif

View File

@ -0,0 +1,28 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
# include <spdlog/details/periodic_worker.h>
#endif
namespace spdlog {
namespace details {
// stop the worker thread and join it
SPDLOG_INLINE periodic_worker::~periodic_worker()
{
if (worker_thread_.joinable())
{
{
std::lock_guard<std::mutex> lock(mutex_);
active_ = false;
}
cv_.notify_one();
worker_thread_.join();
}
}
} // namespace details
} // namespace spdlog

View File

@ -20,7 +20,27 @@ namespace details {
class SPDLOG_API periodic_worker
{
public:
periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval);
template<typename Rep, typename Period>
periodic_worker(const std::function<void()> &callback_fun, std::chrono::duration<Rep, Period> interval)
{
active_ = (interval > std::chrono::duration<Rep, Period>::zero());
if (!active_)
{
return;
}
worker_thread_ = std::thread([this, callback_fun, interval]() {
for (;;)
{
std::unique_lock<std::mutex> lock(this->mutex_);
if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
{
return; // active_ == false, so exit this thread
}
callback_fun();
}
});
}
periodic_worker(const periodic_worker &) = delete;
periodic_worker &operator=(const periodic_worker &) = delete;
// stop the worker thread and join it
@ -36,5 +56,5 @@ private:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "periodic_worker-inl.h"
# include "periodic_worker-inl.h"
#endif

View File

@ -4,21 +4,21 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/details/registry.h>
# include <spdlog/details/registry.h>
#endif
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/periodic_worker.h>
#include <thirdparty/spdlog/include/logger.h>
#include <thirdparty/spdlog/include/pattern_formatter.h>
#include <spdlog/common.h>
#include <spdlog/details/periodic_worker.h>
#include <spdlog/logger.h>
#include <spdlog/pattern_formatter.h>
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
// support for the default stdout color logger
#ifdef _WIN32
#include <thirdparty/spdlog/include/sinks/wincolor_sink.h>
#else
#include <thirdparty/spdlog/include/sinks/ansicolor_sink.h>
#endif
# ifdef _WIN32
# include <spdlog/sinks/wincolor_sink.h>
# else
# include <spdlog/sinks/ansicolor_sink.h>
# endif
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
#include <chrono>
@ -36,11 +36,11 @@ SPDLOG_INLINE registry::registry()
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
// create default logger (ansicolor_stdout_sink_mt or wincolor_stdout_sink_mt in windows).
#ifdef _WIN32
# ifdef _WIN32
auto color_sink = std::make_shared<sinks::wincolor_stdout_sink_mt>();
#else
# else
auto color_sink = std::make_shared<sinks::ansicolor_stdout_sink_mt>();
#endif
# endif
const char *default_logger_name = "";
default_logger_ = std::make_shared<spdlog::logger>(default_logger_name, std::move(color_sink));
@ -188,13 +188,6 @@ SPDLOG_INLINE void registry::flush_on(level::level_enum log_level)
flush_level_ = log_level;
}
SPDLOG_INLINE void registry::flush_every(std::chrono::seconds interval)
{
std::lock_guard<std::mutex> lock(flusher_mutex_);
auto clbk = [this]() { this->flush_all(); };
periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
}
SPDLOG_INLINE void registry::set_error_handler(err_handler handler)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);

View File

@ -8,7 +8,8 @@
// If user requests a non existing logger, nullptr will be returned
// This class is thread safe
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <spdlog/details/periodic_worker.h>
#include <chrono>
#include <functional>
@ -22,7 +23,6 @@ class logger;
namespace details {
class thread_pool;
class periodic_worker;
class SPDLOG_API registry
{
@ -61,7 +61,13 @@ public:
void flush_on(level::level_enum log_level);
void flush_every(std::chrono::seconds interval);
template<typename Rep, typename Period>
void flush_every(std::chrono::duration<Rep, Period> interval)
{
std::lock_guard<std::mutex> lock(flusher_mutex_);
auto clbk = [this]() { this->flush_all(); };
periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
}
void set_error_handler(err_handler handler);
@ -111,5 +117,5 @@ private:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "registry-inl.h"
# include "registry-inl.h"
#endif

View File

@ -13,7 +13,7 @@ class logger;
struct synchronous_factory
{
template<typename Sink, typename... SinkArgs>
static std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs &&...args)
static std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs &&... args)
{
auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
auto new_logger = std::make_shared<spdlog::logger>(std::move(logger_name), std::move(sink));
@ -22,4 +22,3 @@ struct synchronous_factory
}
};
} // namespace spdlog

View File

@ -5,8 +5,8 @@
#define WIN32_LEAN_AND_MEAN
// tcp client helper
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <spdlog/common.h>
#include <spdlog/details/os.h>
#include <winsock2.h>
#include <windows.h>
@ -25,20 +25,6 @@ class tcp_client
{
SOCKET socket_ = INVALID_SOCKET;
static bool winsock_initialized_()
{
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
return false;
}
else
{
closesocket(s);
return true;
}
}
static void init_winsock_()
{
WSADATA wsaData;
@ -52,13 +38,24 @@ class tcp_client
static void throw_winsock_error_(const std::string &msg, int last_error)
{
char buf[512];
::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL);
throw_spdlog_ex(fmt::format("tcp_sink - {}: {}", msg, buf));
throw_spdlog_ex(fmt_lib::format("tcp_sink - {}: {}", msg, buf));
}
public:
tcp_client()
{
init_winsock_();
}
~tcp_client()
{
close();
::WSACleanup();
}
bool is_connected() const
{
return socket_ != INVALID_SOCKET;
@ -68,7 +65,6 @@ public:
{
::closesocket(socket_);
socket_ = INVALID_SOCKET;
WSACleanup();
}
SOCKET fd() const
@ -76,20 +72,9 @@ public:
return socket_;
}
~tcp_client()
{
close();
}
// try to connect or throw on failure
void connect(const std::string &host, int port)
{
// initialize winsock if needed
if (!winsock_initialized_())
{
init_winsock_();
}
if (is_connected())
{
close();

View File

@ -4,12 +4,12 @@
#pragma once
#ifdef _WIN32
#error include tcp_client-windows.h instead
# error include tcp_client-windows.h instead
#endif
// tcp client helper
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <spdlog/common.h>
#include <spdlog/details/os.h>
#include <sys/socket.h>
#include <arpa/inet.h>
@ -67,8 +67,7 @@ public:
auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
if (rv != 0)
{
auto msg = fmt::format("::getaddrinfo failed: {}", gai_strerror(rv));
throw_spdlog_ex(msg);
throw_spdlog_ex(fmt_lib::format("::getaddrinfo failed: {}", gai_strerror(rv)));
}
// Try each address until we successfully connect(2).
@ -111,7 +110,7 @@ public:
#endif
#if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
#error "tcp_sink would raise SIGPIPE since niether SO_NOSIGPIPE nor MSG_NOSIGNAL are available"
# error "tcp_sink would raise SIGPIPE since niether SO_NOSIGPIPE nor MSG_NOSIGNAL are available"
#endif
}

View File

@ -4,16 +4,17 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/details/thread_pool.h>
# include <spdlog/details/thread_pool.h>
#endif
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <cassert>
namespace spdlog {
namespace details {
SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start)
SPDLOG_INLINE thread_pool::thread_pool(
size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start, std::function<void()> on_thread_stop)
: q_(q_max_items)
{
if (threads_n == 0 || threads_n > 1000)
@ -23,15 +24,21 @@ SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n, std
}
for (size_t i = 0; i < threads_n; i++)
{
threads_.emplace_back([this, on_thread_start] {
threads_.emplace_back([this, on_thread_start, on_thread_stop] {
on_thread_start();
this->thread_pool::worker_loop_();
on_thread_stop();
});
}
}
SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start)
: thread_pool(q_max_items, threads_n, on_thread_start, [] {})
{}
SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n)
: thread_pool(q_max_items, threads_n, [] {})
: thread_pool(
q_max_items, threads_n, [] {}, [] {})
{}
// message all threads to terminate gracefully join them
@ -68,6 +75,11 @@ size_t SPDLOG_INLINE thread_pool::overrun_counter()
return q_.overrun_counter();
}
void SPDLOG_INLINE thread_pool::reset_overrun_counter()
{
q_.reset_overrun_counter();
}
size_t SPDLOG_INLINE thread_pool::queue_size()
{
return q_.size();

View File

@ -3,9 +3,9 @@
#pragma once
#include <thirdparty/spdlog/include/details/log_msg_buffer.h>
#include <thirdparty/spdlog/include/details/mpmc_blocking_q.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <spdlog/details/log_msg_buffer.h>
#include <spdlog/details/mpmc_blocking_q.h>
#include <spdlog/details/os.h>
#include <chrono>
#include <memory>
@ -27,7 +27,6 @@ enum class async_msg_type
terminate
};
#include <thirdparty/spdlog/include/details/log_msg_buffer.h>
// Async msg to move to/from the queue
// Movable only. should never be copied
struct async_msg : log_msg_buffer
@ -85,10 +84,11 @@ public:
using item_type = async_msg;
using q_type = details::mpmc_blocking_queue<item_type>;
thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start, std::function<void()> on_thread_stop);
thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start);
thread_pool(size_t q_max_items, size_t threads_n);
// message all threads to terminate gracefully join them
// message all threads to terminate gracefully and join them
~thread_pool();
thread_pool(const thread_pool &) = delete;
@ -97,6 +97,7 @@ public:
void post_log(async_logger_ptr &&worker_ptr, const details::log_msg &msg, async_overflow_policy overflow_policy);
void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy);
size_t overrun_counter();
void reset_overrun_counter();
size_t queue_size();
private:
@ -117,5 +118,5 @@ private:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "thread_pool-inl.h"
# include "thread_pool-inl.h"
#endif

View File

@ -0,0 +1,111 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
// Helper RAII over winsock udp client socket.
// Will throw on construction if socket creation failed.
#include <spdlog/common.h>
#include <spdlog/details/os.h>
#include <spdlog/details/windows_include.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "Mswsock.lib")
#pragma comment(lib, "AdvApi32.lib")
namespace spdlog {
namespace details {
class udp_client
{
static constexpr int TX_BUFFER_SIZE = 1024 * 10;
SOCKET socket_ = INVALID_SOCKET;
sockaddr_in addr_ = {0};
static void init_winsock_()
{
WSADATA wsaData;
auto rv = ::WSAStartup(MAKEWORD(2, 2), &wsaData);
if (rv != 0)
{
throw_winsock_error_("WSAStartup failed", ::WSAGetLastError());
}
}
static void throw_winsock_error_(const std::string &msg, int last_error)
{
char buf[512];
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL);
throw_spdlog_ex(fmt_lib::format("udp_sink - {}: {}", msg, buf));
}
void cleanup_()
{
if (socket_ != INVALID_SOCKET)
{
::closesocket(socket_);
}
socket_ = INVALID_SOCKET;
::WSACleanup();
}
public:
udp_client(const std::string &host, uint16_t port)
{
init_winsock_();
addr_.sin_family = PF_INET;
addr_.sin_port = htons(port);
addr_.sin_addr.s_addr = INADDR_ANY;
if (InetPtonA(PF_INET, host.c_str(), &addr_.sin_addr.s_addr) != 1)
{
int last_error = ::WSAGetLastError();
::WSACleanup();
throw_winsock_error_("error: Invalid address!", last_error);
}
socket_ = ::socket(PF_INET, SOCK_DGRAM, 0);
if (socket_ == INVALID_SOCKET)
{
int last_error = ::WSAGetLastError();
::WSACleanup();
throw_winsock_error_("error: Create Socket failed", last_error);
}
int option_value = TX_BUFFER_SIZE;
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0)
{
int last_error = ::WSAGetLastError();
cleanup_();
throw_winsock_error_("error: setsockopt(SO_SNDBUF) Failed!", last_error);
}
}
~udp_client()
{
cleanup_();
}
SOCKET fd() const
{
return socket_;
}
void send(const char *data, size_t n_bytes)
{
socklen_t tolen = sizeof(struct sockaddr);
if (::sendto(socket_, data, static_cast<int>(n_bytes), 0, (struct sockaddr *)&addr_, tolen) == -1)
{
throw_spdlog_ex("sendto(2) failed", errno);
}
}
};
} // namespace details
} // namespace spdlog

View File

@ -0,0 +1,94 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
// Helper RAII over unix udp client socket.
// Will throw on construction if the socket creation failed.
#ifdef _WIN32
# error "include udp_client-windows.h instead"
#endif
#include <spdlog/common.h>
#include <spdlog/details/os.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/udp.h>
#include <string>
namespace spdlog {
namespace details {
class udp_client
{
static constexpr int TX_BUFFER_SIZE = 1024 * 10;
int socket_ = -1;
struct sockaddr_in sockAddr_;
void cleanup_()
{
if (socket_ != -1)
{
::close(socket_);
socket_ = -1;
}
}
public:
udp_client(const std::string &host, uint16_t port)
{
socket_ = ::socket(PF_INET, SOCK_DGRAM, 0);
if (socket_ < 0)
{
throw_spdlog_ex("error: Create Socket Failed!");
}
int option_value = TX_BUFFER_SIZE;
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0)
{
cleanup_();
throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!");
}
sockAddr_.sin_family = AF_INET;
sockAddr_.sin_port = htons(port);
if (::inet_aton(host.c_str(), &sockAddr_.sin_addr) == 0)
{
cleanup_();
throw_spdlog_ex("error: Invalid address!");
}
::memset(sockAddr_.sin_zero, 0x00, sizeof(sockAddr_.sin_zero));
}
~udp_client()
{
cleanup_();
}
int fd() const
{
return socket_;
}
// Send exactly n_bytes of the given data.
// On error close the connection and throw.
void send(const char *data, size_t n_bytes)
{
ssize_t toslen = 0;
socklen_t tolen = sizeof(struct sockaddr);
if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) == -1)
{
throw_spdlog_ex("sendto(2) failed", errno);
}
}
};
} // namespace details
} // namespace spdlog

View File

@ -1,11 +1,11 @@
#pragma once
#ifndef NOMINMAX
#define NOMINMAX // prevent windows redefining min/max
# define NOMINMAX // prevent windows redefining min/max
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>

View File

@ -6,10 +6,21 @@
#pragma once
#include <cctype>
#include <spdlog/common.h>
#if defined(__has_include)
# if __has_include(<version>)
# include <version>
# endif
#endif
#if __cpp_lib_span >= 202002L
# include <span>
#endif
//
// Support for logging binary data as hex
// format flags, any combination of the followng:
// format flags, any combination of the following:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
@ -38,11 +49,12 @@ public:
, size_per_line_(size_per_line)
{}
It begin() const
// do not use begin() and end() to avoid collision with fmt/ranges
It get_begin() const
{
return begin_;
}
It end() const
It get_end() const
{
return end_;
}
@ -66,6 +78,20 @@ inline details::dump_info<typename Container::const_iterator> to_hex(const Conta
return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
}
#if __cpp_lib_span >= 202002L
template<typename Value, size_t Extent>
inline details::dump_info<typename std::span<Value, Extent>::iterator> to_hex(
const std::span<Value, Extent> &container, size_t size_per_line = 32)
{
using Container = std::span<Value, Extent>;
static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1");
using Iter = typename Container::iterator;
return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
}
#endif
// create dump_info from ranges
template<typename It>
inline details::dump_info<It> to_hex(const It range_begin, const It range_end, size_t size_per_line = 32)
@ -75,10 +101,16 @@ inline details::dump_info<It> to_hex(const It range_begin, const It range_end, s
} // namespace spdlog
namespace fmt {
namespace
#ifdef SPDLOG_USE_STD_FORMAT
std
#else
fmt
#endif
{
template<typename T>
struct formatter<spdlog::details::dump_info<T>>
struct formatter<spdlog::details::dump_info<T>, char>
{
const char delimiter = ' ';
bool put_newlines = true;
@ -89,7 +121,7 @@ struct formatter<spdlog::details::dump_info<T>>
// parse the format string flags
template<typename ParseContext>
auto parse(ParseContext &ctx) -> decltype(ctx.begin())
SPDLOG_CONSTEXPR_FUNC auto parse(ParseContext &ctx) -> decltype(ctx.begin())
{
auto it = ctx.begin();
while (it != ctx.end() && *it != '}')
@ -130,21 +162,21 @@ struct formatter<spdlog::details::dump_info<T>>
SPDLOG_CONSTEXPR const char *hex_lower = "0123456789abcdef";
const char *hex_chars = use_uppercase ? hex_upper : hex_lower;
#if FMT_VERSION < 60000
#if !defined(SPDLOG_USE_STD_FORMAT) && FMT_VERSION < 60000
auto inserter = ctx.begin();
#else
auto inserter = ctx.out();
#endif
int size_per_line = static_cast<int>(the_range.size_per_line());
auto start_of_line = the_range.begin();
for (auto i = the_range.begin(); i != the_range.end(); i++)
auto start_of_line = the_range.get_begin();
for (auto i = the_range.get_begin(); i != the_range.get_end(); i++)
{
auto ch = static_cast<unsigned char>(*i);
if (put_newlines && (i == the_range.begin() || i - start_of_line >= size_per_line))
if (put_newlines && (i == the_range.get_begin() || i - start_of_line >= size_per_line))
{
if (show_ascii && i != the_range.begin())
if (show_ascii && i != the_range.get_begin())
{
*inserter++ = delimiter;
*inserter++ = delimiter;
@ -155,7 +187,7 @@ struct formatter<spdlog::details::dump_info<T>>
}
}
put_newline(inserter, static_cast<size_t>(i - the_range.begin()));
put_newline(inserter, static_cast<size_t>(i - the_range.get_begin()));
// put first byte without delimiter in front of it
*inserter++ = hex_chars[(ch >> 4) & 0x0f];
@ -174,9 +206,9 @@ struct formatter<spdlog::details::dump_info<T>>
}
if (show_ascii) // add ascii to last line
{
if (the_range.end() - the_range.begin() > size_per_line)
if (the_range.get_end() - the_range.get_begin() > size_per_line)
{
auto blank_num = size_per_line - (the_range.end() - start_of_line);
auto blank_num = size_per_line - (the_range.get_end() - start_of_line);
while (blank_num-- > 0)
{
*inserter++ = delimiter;
@ -189,7 +221,7 @@ struct formatter<spdlog::details::dump_info<T>>
}
*inserter++ = delimiter;
*inserter++ = delimiter;
for (auto j = start_of_line; j != the_range.end(); j++)
for (auto j = start_of_line; j != the_range.get_end(); j++)
{
auto pc = static_cast<unsigned char>(*j);
*inserter++ = std::isprint(pc) ? static_cast<char>(*j) : '.';
@ -209,8 +241,8 @@ struct formatter<spdlog::details::dump_info<T>>
if (put_positions)
{
fmt::format_to(inserter, "{:04X}: ", pos);
spdlog::fmt_lib::format_to(inserter, SPDLOG_FMT_STRING("{:04X}: "), pos);
}
}
};
} // namespace fmt
} // namespace std

View File

@ -95,10 +95,10 @@ class dynamic_format_arg_store
};
template <typename T>
using stored_type = conditional_t<detail::is_string<T>::value &&
!has_formatter<T, Context>::value &&
!detail::is_reference_wrapper<T>::value,
std::basic_string<char_type>, T>;
using stored_type = conditional_t<
std::is_convertible<T, std::basic_string<char_type>>::value &&
!detail::is_reference_wrapper<T>::value,
std::basic_string<char_type>, T>;
// Storage of basic_format_arg must be contiguous.
std::vector<basic_format_arg<Context>> data_;
@ -143,6 +143,8 @@ class dynamic_format_arg_store
}
public:
constexpr dynamic_format_arg_store() = default;
/**
\rst
Adds an argument into the dynamic store for later passing to a formatting

View File

@ -10,13 +10,6 @@
#include "format.h"
// __declspec(deprecated) is broken in some MSVC versions.
#if FMT_MSC_VER
# define FMT_DEPRECATED_NONMSVC
#else
# define FMT_DEPRECATED_NONMSVC FMT_DEPRECATED
#endif
FMT_BEGIN_NAMESPACE
FMT_MODULE_EXPORT_BEGIN
@ -185,9 +178,13 @@ enum class terminal_color : uint8_t {
enum class emphasis : uint8_t {
bold = 1,
italic = 1 << 1,
underline = 1 << 2,
strikethrough = 1 << 3
faint = 1 << 1,
italic = 1 << 2,
underline = 1 << 3,
blink = 1 << 4,
reverse = 1 << 5,
conceal = 1 << 6,
strikethrough = 1 << 7,
};
// rgb is a struct for red, green and blue colors.
@ -210,17 +207,16 @@ FMT_BEGIN_DETAIL_NAMESPACE
// color is a struct of either a rgb color or a terminal color.
struct color_type {
FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {}
FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true),
value{} {
FMT_CONSTEXPR color_type() noexcept : is_rgb(), value{} {}
FMT_CONSTEXPR color_type(color rgb_color) noexcept : is_rgb(true), value{} {
value.rgb_color = static_cast<uint32_t>(rgb_color);
}
FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} {
FMT_CONSTEXPR color_type(rgb rgb_color) noexcept : is_rgb(true), value{} {
value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) |
(static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
}
FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(),
value{} {
FMT_CONSTEXPR color_type(terminal_color term_color) noexcept
: is_rgb(), value{} {
value.term_color = static_cast<uint8_t>(term_color);
}
bool is_rgb;
@ -235,10 +231,8 @@ FMT_END_DETAIL_NAMESPACE
/** A text style consisting of foreground and background colors and emphasis. */
class text_style {
public:
FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT
: set_foreground_color(),
set_background_color(),
ems(em) {}
FMT_CONSTEXPR text_style(emphasis em = emphasis()) noexcept
: set_foreground_color(), set_background_color(), ems(em) {}
FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) {
if (!set_foreground_color) {
@ -269,44 +263,32 @@ class text_style {
return lhs |= rhs;
}
FMT_DEPRECATED_NONMSVC FMT_CONSTEXPR text_style& operator&=(
const text_style& rhs) {
return and_assign(rhs);
}
FMT_DEPRECATED_NONMSVC friend FMT_CONSTEXPR text_style
operator&(text_style lhs, const text_style& rhs) {
return lhs.and_assign(rhs);
}
FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT {
FMT_CONSTEXPR bool has_foreground() const noexcept {
return set_foreground_color;
}
FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT {
FMT_CONSTEXPR bool has_background() const noexcept {
return set_background_color;
}
FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT {
FMT_CONSTEXPR bool has_emphasis() const noexcept {
return static_cast<uint8_t>(ems) != 0;
}
FMT_CONSTEXPR detail::color_type get_foreground() const FMT_NOEXCEPT {
FMT_CONSTEXPR detail::color_type get_foreground() const noexcept {
FMT_ASSERT(has_foreground(), "no foreground specified for this style");
return foreground_color;
}
FMT_CONSTEXPR detail::color_type get_background() const FMT_NOEXCEPT {
FMT_CONSTEXPR detail::color_type get_background() const noexcept {
FMT_ASSERT(has_background(), "no background specified for this style");
return background_color;
}
FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT {
FMT_CONSTEXPR emphasis get_emphasis() const noexcept {
FMT_ASSERT(has_emphasis(), "no emphasis specified for this style");
return ems;
}
private:
FMT_CONSTEXPR text_style(bool is_foreground,
detail::color_type text_color) FMT_NOEXCEPT
: set_foreground_color(),
set_background_color(),
ems() {
detail::color_type text_color) noexcept
: set_foreground_color(), set_background_color(), ems() {
if (is_foreground) {
foreground_color = text_color;
set_foreground_color = true;
@ -316,36 +298,9 @@ class text_style {
}
}
// DEPRECATED!
FMT_CONSTEXPR text_style& and_assign(const text_style& rhs) {
if (!set_foreground_color) {
set_foreground_color = rhs.set_foreground_color;
foreground_color = rhs.foreground_color;
} else if (rhs.set_foreground_color) {
if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb)
FMT_THROW(format_error("can't AND a terminal color"));
foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color;
}
friend FMT_CONSTEXPR text_style fg(detail::color_type foreground) noexcept;
if (!set_background_color) {
set_background_color = rhs.set_background_color;
background_color = rhs.background_color;
} else if (rhs.set_background_color) {
if (!background_color.is_rgb || !rhs.background_color.is_rgb)
FMT_THROW(format_error("can't AND a terminal color"));
background_color.value.rgb_color &= rhs.background_color.value.rgb_color;
}
ems = static_cast<emphasis>(static_cast<uint8_t>(ems) &
static_cast<uint8_t>(rhs.ems));
return *this;
}
friend FMT_CONSTEXPR_DECL text_style fg(detail::color_type foreground)
FMT_NOEXCEPT;
friend FMT_CONSTEXPR_DECL text_style bg(detail::color_type background)
FMT_NOEXCEPT;
friend FMT_CONSTEXPR text_style bg(detail::color_type background) noexcept;
detail::color_type foreground_color;
detail::color_type background_color;
@ -355,17 +310,16 @@ class text_style {
};
/** Creates a text style from the foreground (text) color. */
FMT_CONSTEXPR inline text_style fg(detail::color_type foreground) FMT_NOEXCEPT {
FMT_CONSTEXPR inline text_style fg(detail::color_type foreground) noexcept {
return text_style(true, foreground);
}
/** Creates a text style from the background color. */
FMT_CONSTEXPR inline text_style bg(detail::color_type background) FMT_NOEXCEPT {
FMT_CONSTEXPR inline text_style bg(detail::color_type background) noexcept {
return text_style(false, background);
}
FMT_CONSTEXPR inline text_style operator|(emphasis lhs,
emphasis rhs) FMT_NOEXCEPT {
FMT_CONSTEXPR inline text_style operator|(emphasis lhs, emphasis rhs) noexcept {
return text_style(lhs) | rhs;
}
@ -373,7 +327,7 @@ FMT_BEGIN_DETAIL_NAMESPACE
template <typename Char> struct ansi_color_escape {
FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color,
const char* esc) FMT_NOEXCEPT {
const char* esc) noexcept {
// If we have a terminal color, we need to output another escape code
// sequence.
if (!text_color.is_rgb) {
@ -408,17 +362,19 @@ template <typename Char> struct ansi_color_escape {
to_esc(color.b, buffer + 15, 'm');
buffer[19] = static_cast<Char>(0);
}
FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT {
uint8_t em_codes[4] = {};
uint8_t em_bits = static_cast<uint8_t>(em);
if (em_bits & static_cast<uint8_t>(emphasis::bold)) em_codes[0] = 1;
if (em_bits & static_cast<uint8_t>(emphasis::italic)) em_codes[1] = 3;
if (em_bits & static_cast<uint8_t>(emphasis::underline)) em_codes[2] = 4;
if (em_bits & static_cast<uint8_t>(emphasis::strikethrough))
em_codes[3] = 9;
FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept {
uint8_t em_codes[num_emphases] = {};
if (has_emphasis(em, emphasis::bold)) em_codes[0] = 1;
if (has_emphasis(em, emphasis::faint)) em_codes[1] = 2;
if (has_emphasis(em, emphasis::italic)) em_codes[2] = 3;
if (has_emphasis(em, emphasis::underline)) em_codes[3] = 4;
if (has_emphasis(em, emphasis::blink)) em_codes[4] = 5;
if (has_emphasis(em, emphasis::reverse)) em_codes[5] = 7;
if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8;
if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9;
size_t index = 0;
for (int i = 0; i < 4; ++i) {
for (size_t i = 0; i < num_emphases; ++i) {
if (!em_codes[i]) continue;
buffer[index++] = static_cast<Char>('\x1b');
buffer[index++] = static_cast<Char>('[');
@ -427,66 +383,76 @@ template <typename Char> struct ansi_color_escape {
}
buffer[index++] = static_cast<Char>(0);
}
FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; }
FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; }
FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; }
FMT_CONSTEXPR_CHAR_TRAITS const Char* end() const FMT_NOEXCEPT {
FMT_CONSTEXPR const Char* begin() const noexcept { return buffer; }
FMT_CONSTEXPR_CHAR_TRAITS const Char* end() const noexcept {
return buffer + std::char_traits<Char>::length(buffer);
}
private:
Char buffer[7u + 3u * 4u + 1u];
static constexpr size_t num_emphases = 8;
Char buffer[7u + 3u * num_emphases + 1u];
static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
char delimiter) FMT_NOEXCEPT {
char delimiter) noexcept {
out[0] = static_cast<Char>('0' + c / 100);
out[1] = static_cast<Char>('0' + c / 10 % 10);
out[2] = static_cast<Char>('0' + c % 10);
out[3] = static_cast<Char>(delimiter);
}
static FMT_CONSTEXPR bool has_emphasis(emphasis em, emphasis mask) noexcept {
return static_cast<uint8_t>(em) & static_cast<uint8_t>(mask);
}
};
template <typename Char>
FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color(
detail::color_type foreground) FMT_NOEXCEPT {
detail::color_type foreground) noexcept {
return ansi_color_escape<Char>(foreground, "\x1b[38;2;");
}
template <typename Char>
FMT_CONSTEXPR ansi_color_escape<Char> make_background_color(
detail::color_type background) FMT_NOEXCEPT {
detail::color_type background) noexcept {
return ansi_color_escape<Char>(background, "\x1b[48;2;");
}
template <typename Char>
FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT {
FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) noexcept {
return ansi_color_escape<Char>(em);
}
template <typename Char>
inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT {
std::fputs(chars, stream);
template <typename Char> inline void fputs(const Char* chars, FILE* stream) {
int result = std::fputs(chars, stream);
if (result < 0)
FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
}
template <>
inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT {
std::fputws(chars, stream);
template <> inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) {
int result = std::fputws(chars, stream);
if (result < 0)
FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
}
template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT {
template <typename Char> inline void reset_color(FILE* stream) {
fputs("\x1b[0m", stream);
}
template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT {
template <> inline void reset_color<wchar_t>(FILE* stream) {
fputs(L"\x1b[0m", stream);
}
template <typename Char>
inline void reset_color(buffer<Char>& buffer) FMT_NOEXCEPT {
template <typename Char> inline void reset_color(buffer<Char>& buffer) {
auto reset_color = string_view("\x1b[0m");
buffer.append(reset_color.begin(), reset_color.end());
}
template <typename T> struct styled_arg {
const T& value;
text_style style;
};
template <typename Char>
void vformat_to(buffer<Char>& buf, const text_style& ts,
basic_string_view<Char> format_str,
@ -517,9 +483,13 @@ template <typename S, typename Char = char_t<S>>
void vprint(std::FILE* f, const text_style& ts, const S& format,
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
basic_memory_buffer<Char> buf;
detail::vformat_to(buf, ts, to_string_view(format), args);
buf.push_back(Char(0));
detail::fputs(buf.data(), f);
detail::vformat_to(buf, ts, detail::to_string_view(format), args);
if (detail::is_utf8()) {
detail::print(f, basic_string_view<Char>(buf.begin(), buf.size()));
} else {
buf.push_back(Char(0));
detail::fputs(buf.data(), f);
}
}
/**
@ -538,7 +508,7 @@ template <typename S, typename... Args,
void print(std::FILE* f, const text_style& ts, const S& format_str,
const Args&... args) {
vprint(f, ts, format_str,
fmt::make_args_checked<Args...>(format_str, args...));
fmt::make_format_args<buffer_context<char_t<S>>>(args...));
}
/**
@ -563,7 +533,7 @@ inline std::basic_string<Char> vformat(
const text_style& ts, const S& format_str,
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
basic_memory_buffer<Char> buf;
detail::vformat_to(buf, ts, to_string_view(format_str), args);
detail::vformat_to(buf, ts, detail::to_string_view(format_str), args);
return fmt::to_string(buf);
}
@ -582,8 +552,8 @@ inline std::basic_string<Char> vformat(
template <typename S, typename... Args, typename Char = char_t<S>>
inline std::basic_string<Char> format(const text_style& ts, const S& format_str,
const Args&... args) {
return fmt::vformat(ts, to_string_view(format_str),
fmt::make_args_checked<Args...>(format_str, args...));
return fmt::vformat(ts, detail::to_string_view(format_str),
fmt::make_format_args<buffer_context<Char>>(args...));
}
/**
@ -617,8 +587,62 @@ template <typename OutputIt, typename S, typename... Args,
inline auto format_to(OutputIt out, const text_style& ts, const S& format_str,
Args&&... args) ->
typename std::enable_if<enable, OutputIt>::type {
return vformat_to(out, ts, to_string_view(format_str),
fmt::make_args_checked<Args...>(format_str, args...));
return vformat_to(out, ts, detail::to_string_view(format_str),
fmt::make_format_args<buffer_context<char_t<S>>>(args...));
}
template <typename T, typename Char>
struct formatter<detail::styled_arg<T>, Char> : formatter<T, Char> {
template <typename FormatContext>
auto format(const detail::styled_arg<T>& arg, FormatContext& ctx) const
-> decltype(ctx.out()) {
const auto& ts = arg.style;
const auto& value = arg.value;
auto out = ctx.out();
bool has_style = false;
if (ts.has_emphasis()) {
has_style = true;
auto emphasis = detail::make_emphasis<Char>(ts.get_emphasis());
out = std::copy(emphasis.begin(), emphasis.end(), out);
}
if (ts.has_foreground()) {
has_style = true;
auto foreground =
detail::make_foreground_color<Char>(ts.get_foreground());
out = std::copy(foreground.begin(), foreground.end(), out);
}
if (ts.has_background()) {
has_style = true;
auto background =
detail::make_background_color<Char>(ts.get_background());
out = std::copy(background.begin(), background.end(), out);
}
out = formatter<T, Char>::format(value, ctx);
if (has_style) {
auto reset_color = string_view("\x1b[0m");
out = std::copy(reset_color.begin(), reset_color.end(), out);
}
return out;
}
};
/**
\rst
Returns an argument that will be formatted using ANSI escape sequences,
to be used in a formatting function.
**Example**::
fmt::print("Elapsed time: {0:.2f} seconds",
fmt::styled(1.23, fmt::fg(fmt::color::green) |
fmt::bg(fmt::color::blue)));
\endrst
*/
template <typename T>
FMT_CONSTEXPR auto styled(const T& value, text_style ts)
-> detail::styled_arg<remove_cvref_t<T>> {
return detail::styled_arg<remove_cvref_t<T>>{value, ts};
}
FMT_MODULE_EXPORT_END

View File

@ -13,48 +13,9 @@
FMT_BEGIN_NAMESPACE
namespace detail {
// An output iterator that counts the number of objects written to it and
// discards them.
class counting_iterator {
private:
size_t count_;
public:
using iterator_category = std::output_iterator_tag;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = void;
using _Unchecked_type = counting_iterator; // Mark iterator as checked.
struct value_type {
template <typename T> void operator=(const T&) {}
};
counting_iterator() : count_(0) {}
size_t count() const { return count_; }
counting_iterator& operator++() {
++count_;
return *this;
}
counting_iterator operator++(int) {
auto it = *this;
++*this;
return it;
}
friend counting_iterator operator+(counting_iterator it, difference_type n) {
it.count_ += static_cast<size_t>(n);
return it;
}
value_type operator*() const { return {}; }
};
template <typename Char, typename InputIt>
inline counting_iterator copy_str(InputIt begin, InputIt end,
counting_iterator it) {
FMT_CONSTEXPR inline counting_iterator copy_str(InputIt begin, InputIt end,
counting_iterator it) {
return it + (end - begin);
}
@ -75,8 +36,7 @@ template <typename OutputIt> class truncating_iterator_base {
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = void;
using _Unchecked_type =
truncating_iterator_base; // Mark iterator as checked.
FMT_UNCHECKED_ITERATOR(truncating_iterator_base);
OutputIt base() const { return out_; }
size_t count() const { return count_; }
@ -156,19 +116,19 @@ struct is_compiled_string : std::is_base_of<compiled_string, S> {};
std::string s = fmt::format(FMT_COMPILE("{}"), 42);
\endrst
*/
#ifdef __cpp_if_constexpr
#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
# define FMT_COMPILE(s) \
FMT_STRING_IMPL(s, fmt::detail::compiled_string, explicit)
#else
# define FMT_COMPILE(s) FMT_STRING(s)
#endif
#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
#if FMT_USE_NONTYPE_TEMPLATE_ARGS
template <typename Char, size_t N,
fmt::detail_exported::fixed_string<Char, N> Str>
struct udl_compiled_string : compiled_string {
using char_type = Char;
constexpr operator basic_string_view<char_type>() const {
explicit constexpr operator basic_string_view<char_type>() const {
return {Str.data, N - 1};
}
};
@ -179,7 +139,7 @@ const T& first(const T& value, const Tail&...) {
return value;
}
#ifdef __cpp_if_constexpr
#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
template <typename... Args> struct type_list {};
// Returns a reference to the argument at index N from [first, rest...].
@ -190,7 +150,7 @@ constexpr const auto& get([[maybe_unused]] const T& first,
if constexpr (N == 0)
return first;
else
return get<N - 1>(rest...);
return detail::get<N - 1>(rest...);
}
template <typename Char, typename... Args>
@ -202,7 +162,8 @@ constexpr int get_arg_index_by_name(basic_string_view<Char> name,
template <int N, typename> struct get_type_impl;
template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {
using type = remove_cvref_t<decltype(get<N>(std::declval<Args>()...))>;
using type =
remove_cvref_t<decltype(detail::get<N>(std::declval<Args>()...))>;
};
template <int N, typename T>
@ -242,7 +203,7 @@ template <typename Char> struct code_unit {
// This ensures that the argument type is convertible to `const T&`.
template <typename T, int N, typename... Args>
constexpr const T& get_arg_checked(const Args&... args) {
const auto& arg = get<N>(args...);
const auto& arg = detail::get<N>(args...);
if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) {
return arg.value;
} else {
@ -289,7 +250,7 @@ template <typename Char> struct runtime_named_field {
constexpr OutputIt format(OutputIt out, const Args&... args) const {
bool found = (try_format_argument(out, name, args) || ...);
if (!found) {
throw format_error("argument with specified name is not found");
FMT_THROW(format_error("argument with specified name is not found"));
}
return out;
}
@ -376,10 +337,11 @@ template <typename T, typename Char>
constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str,
size_t pos, int next_arg_id) {
str.remove_prefix(pos);
auto ctx = basic_format_parse_context<Char>(str, {}, next_arg_id);
auto ctx = compile_parse_context<Char>(str, max_value<int>(), nullptr, {},
next_arg_id);
auto f = formatter<T, Char>();
auto end = f.parse(ctx);
return {f, pos + fmt::detail::to_unsigned(end - str.data()) + 1,
return {f, pos + fmt::detail::to_unsigned(end - str.data()),
next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()};
}
@ -399,7 +361,9 @@ template <typename Char> struct arg_id_handler {
return 0;
}
constexpr void on_error(const char* message) { throw format_error(message); }
constexpr void on_error(const char* message) {
FMT_THROW(format_error(message));
}
};
template <typename Char> struct parse_arg_id_result {
@ -433,13 +397,20 @@ constexpr auto parse_replacement_field_then_tail(S format_str) {
return parse_tail<Args, END_POS + 1, NEXT_ID>(
field<char_type, typename field_type<T>::type, ARG_INDEX>(),
format_str);
} else if constexpr (c == ':') {
} else if constexpr (c != ':') {
FMT_THROW(format_error("expected ':'"));
} else {
constexpr auto result = parse_specs<typename field_type<T>::type>(
str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID);
return parse_tail<Args, result.end, result.next_arg_id>(
spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
result.fmt},
format_str);
if constexpr (result.end >= str.size() || str[result.end] != '}') {
FMT_THROW(format_error("expected '}'"));
return 0;
} else {
return parse_tail<Args, result.end + 1, result.next_arg_id>(
spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
result.fmt},
format_str);
}
}
}
@ -451,7 +422,7 @@ constexpr auto compile_format_string(S format_str) {
constexpr auto str = basic_string_view<char_type>(format_str);
if constexpr (str[POS] == '{') {
if constexpr (POS + 1 == str.size())
throw format_error("unmatched '{' in format string");
FMT_THROW(format_error("unmatched '{' in format string"));
if constexpr (str[POS + 1] == '{') {
return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
} else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') {
@ -500,7 +471,7 @@ constexpr auto compile_format_string(S format_str) {
}
} else if constexpr (str[POS] == '}') {
if constexpr (POS + 1 == str.size())
throw format_error("unmatched '}' in format string");
FMT_THROW(format_error("unmatched '}' in format string"));
return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
} else {
constexpr auto end = parse_text(str, POS + 1);
@ -527,12 +498,12 @@ constexpr auto compile(S format_str) {
return result;
}
}
#endif // __cpp_if_constexpr
#endif // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
} // namespace detail
FMT_MODULE_EXPORT_BEGIN
#ifdef __cpp_if_constexpr
#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
template <typename CompiledFormat, typename... Args,
typename Char = typename CompiledFormat::char_type,
@ -570,10 +541,11 @@ FMT_INLINE std::basic_string<typename S::char_type> format(const S&,
constexpr auto compiled = detail::compile<Args...>(S());
if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
detail::unknown_format>()) {
return format(static_cast<basic_string_view<typename S::char_type>>(S()),
std::forward<Args>(args)...);
return fmt::format(
static_cast<basic_string_view<typename S::char_type>>(S()),
std::forward<Args>(args)...);
} else {
return format(compiled, std::forward<Args>(args)...);
return fmt::format(compiled, std::forward<Args>(args)...);
}
}
@ -583,11 +555,11 @@ FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) {
constexpr auto compiled = detail::compile<Args...>(S());
if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
detail::unknown_format>()) {
return format_to(out,
static_cast<basic_string_view<typename S::char_type>>(S()),
std::forward<Args>(args)...);
return fmt::format_to(
out, static_cast<basic_string_view<typename S::char_type>>(S()),
std::forward<Args>(args)...);
} else {
return format_to(out, compiled, std::forward<Args>(args)...);
return fmt::format_to(out, compiled, std::forward<Args>(args)...);
}
}
#endif
@ -596,22 +568,24 @@ template <typename OutputIt, typename S, typename... Args,
FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n,
const S& format_str, Args&&... args) {
auto it = format_to(detail::truncating_iterator<OutputIt>(out, n), format_str,
std::forward<Args>(args)...);
auto it = fmt::format_to(detail::truncating_iterator<OutputIt>(out, n),
format_str, std::forward<Args>(args)...);
return {it.base(), it.count()};
}
template <typename S, typename... Args,
FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
size_t formatted_size(const S& format_str, const Args&... args) {
return format_to(detail::counting_iterator(), format_str, args...).count();
FMT_CONSTEXPR20 size_t formatted_size(const S& format_str,
const Args&... args) {
return fmt::format_to(detail::counting_iterator(), format_str, args...)
.count();
}
template <typename S, typename... Args,
FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
void print(std::FILE* f, const S& format_str, const Args&... args) {
memory_buffer buffer;
format_to(std::back_inserter(buffer), format_str, args...);
fmt::format_to(std::back_inserter(buffer), format_str, args...);
detail::print(f, {buffer.data(), buffer.size()});
}
@ -621,14 +595,12 @@ void print(const S& format_str, const Args&... args) {
print(stdout, format_str, args...);
}
#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
#if FMT_USE_NONTYPE_TEMPLATE_ARGS
inline namespace literals {
template <detail_exported::fixed_string Str>
constexpr detail::udl_compiled_string<
remove_cvref_t<decltype(Str.data[0])>,
sizeof(Str.data) / sizeof(decltype(Str.data[0])), Str>
operator""_cf() {
return {};
template <detail_exported::fixed_string Str> constexpr auto operator""_cf() {
using char_t = remove_cvref_t<decltype(Str.data[0])>;
return detail::udl_compiled_string<char_t, sizeof(Str.data) / sizeof(char_t),
Str>();
}
} // namespace literals
#endif

View File

@ -0,0 +1,27 @@
Copyright (c) 2012 - present, Victor Zverovich
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--- Optional exception to the license ---
As an exception, if, as a result of your compiling your source code, portions
of this Software are embedded into a machine-executable object form of such
source code, you may redistribute such embedded portions in such object form
without including the above copyright and permission notices.

File diff suppressed because it is too large Load Diff

View File

@ -9,10 +9,8 @@
#define FMT_OS_H_
#include <cerrno>
#include <clocale> // locale_t
#include <cstddef>
#include <cstdio>
#include <cstdlib> // strtod_l
#include <system_error> // std::system_error
#if defined __APPLE__ || defined(__FreeBSD__)
@ -21,17 +19,20 @@
#include "format.h"
#ifndef FMT_USE_FCNTL
// UWP doesn't provide _pipe.
#if FMT_HAS_INCLUDE("winapifamily.h")
# include <winapifamily.h>
#endif
#if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
defined(__linux__)) && \
(!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
# include <fcntl.h> // for O_RDONLY
# define FMT_USE_FCNTL 1
#else
# define FMT_USE_FCNTL 0
# if FMT_HAS_INCLUDE("winapifamily.h")
# include <winapifamily.h>
# endif
# if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
defined(__linux__)) && \
(!defined(WINAPI_FAMILY) || \
(WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
# include <fcntl.h> // for O_RDONLY
# define FMT_USE_FCNTL 1
# else
# define FMT_USE_FCNTL 0
# endif
#endif
#ifndef FMT_POSIX
@ -138,7 +139,7 @@ template <typename Char> struct formatter<std::error_code, Char> {
};
#ifdef _WIN32
FMT_API const std::error_category& system_category() FMT_NOEXCEPT;
FMT_API const std::error_category& system_category() noexcept;
FMT_BEGIN_DETAIL_NAMESPACE
// A converter from UTF-16 to UTF-8.
@ -162,7 +163,7 @@ class utf16_to_utf8 {
};
FMT_API void format_windows_error(buffer<char>& out, int error_code,
const char* message) FMT_NOEXCEPT;
const char* message) noexcept;
FMT_END_DETAIL_NAMESPACE
FMT_API std::system_error vwindows_error(int error_code, string_view format_str,
@ -204,10 +205,9 @@ std::system_error windows_error(int error_code, string_view message,
// Reports a Windows error without throwing an exception.
// Can be used to report errors from destructors.
FMT_API void report_windows_error(int error_code,
const char* message) FMT_NOEXCEPT;
FMT_API void report_windows_error(int error_code, const char* message) noexcept;
#else
inline const std::error_category& system_category() FMT_NOEXCEPT {
inline const std::error_category& system_category() noexcept {
return std::system_category();
}
#endif // _WIN32
@ -234,13 +234,13 @@ class buffered_file {
void operator=(const buffered_file&) = delete;
// Constructs a buffered_file object which doesn't represent any file.
buffered_file() FMT_NOEXCEPT : file_(nullptr) {}
buffered_file() noexcept : file_(nullptr) {}
// Destroys the object closing the file it represents if any.
FMT_API ~buffered_file() FMT_NOEXCEPT;
FMT_API ~buffered_file() noexcept;
public:
buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) {
buffered_file(buffered_file&& other) noexcept : file_(other.file_) {
other.file_ = nullptr;
}
@ -258,11 +258,9 @@ class buffered_file {
FMT_API void close();
// Returns the pointer to a FILE object representing this file.
FILE* get() const FMT_NOEXCEPT { return file_; }
FILE* get() const noexcept { return file_; }
// We place parentheses around fileno to workaround a bug in some versions
// of MinGW that define fileno as a macro.
FMT_API int(fileno)() const;
FMT_API int descriptor() const;
void vprint(string_view format_str, format_args args) {
fmt::vprint(file_, format_str, args);
@ -276,12 +274,12 @@ class buffered_file {
#if FMT_USE_FCNTL
// A file. Closed file is represented by a file object with descriptor -1.
// Methods that are not declared with FMT_NOEXCEPT may throw
// Methods that are not declared with noexcept may throw
// fmt::system_error in case of failure. Note that some errors such as
// closing the file multiple times will cause a crash on Windows rather
// than an exception. You can get standard behavior by overriding the
// invalid parameter handler with _set_invalid_parameter_handler.
class file {
class FMT_API file {
private:
int fd_; // File descriptor.
@ -300,16 +298,16 @@ class file {
};
// Constructs a file object which doesn't represent any file.
file() FMT_NOEXCEPT : fd_(-1) {}
file() noexcept : fd_(-1) {}
// Opens a file and constructs a file object representing this file.
FMT_API file(cstring_view path, int oflag);
file(cstring_view path, int oflag);
public:
file(const file&) = delete;
void operator=(const file&) = delete;
file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; }
// Move assignment is not noexcept because close may throw.
file& operator=(file&& other) {
@ -320,43 +318,43 @@ class file {
}
// Destroys the object closing the file it represents if any.
FMT_API ~file() FMT_NOEXCEPT;
~file() noexcept;
// Returns the file descriptor.
int descriptor() const FMT_NOEXCEPT { return fd_; }
int descriptor() const noexcept { return fd_; }
// Closes the file.
FMT_API void close();
void close();
// Returns the file size. The size has signed type for consistency with
// stat::st_size.
FMT_API long long size() const;
long long size() const;
// Attempts to read count bytes from the file into the specified buffer.
FMT_API size_t read(void* buffer, size_t count);
size_t read(void* buffer, size_t count);
// Attempts to write count bytes from the specified buffer to the file.
FMT_API size_t write(const void* buffer, size_t count);
size_t write(const void* buffer, size_t count);
// Duplicates a file descriptor with the dup function and returns
// the duplicate as a file object.
FMT_API static file dup(int fd);
static file dup(int fd);
// Makes fd be the copy of this file descriptor, closing fd first if
// necessary.
FMT_API void dup2(int fd);
void dup2(int fd);
// Makes fd be the copy of this file descriptor, closing fd first if
// necessary.
FMT_API void dup2(int fd, std::error_code& ec) FMT_NOEXCEPT;
void dup2(int fd, std::error_code& ec) 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);
static void pipe(file& read_end, file& write_end);
// Creates a buffered_file object associated with this file and detaches
// this file object from the file.
FMT_API buffered_file fdopen(const char* mode);
buffered_file fdopen(const char* mode);
};
// Returns the memory page size.
@ -390,23 +388,26 @@ struct ostream_params {
: ostream_params(params...) {
this->buffer_size = bs.value;
}
// Intel has a bug that results in failure to deduce a constructor
// for empty parameter packs.
# if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000
ostream_params(int new_oflag) : oflag(new_oflag) {}
ostream_params(detail::buffer_size bs) : buffer_size(bs.value) {}
# endif
};
FMT_END_DETAIL_NAMESPACE
constexpr detail::buffer_size buffer_size;
// Added {} below to work around default constructor error known to
// occur in Xcode versions 7.2.1 and 8.2.1.
constexpr detail::buffer_size buffer_size{};
/** A fast output stream which is not thread-safe. */
class FMT_API ostream final : private detail::buffer<char> {
private:
file file_;
void flush() {
if (size() == 0) return;
file_.write(data(), size());
clear();
}
void grow(size_t) override;
ostream(cstring_view path, const detail::ostream_params& params)
@ -426,6 +427,12 @@ class FMT_API ostream final : private detail::buffer<char> {
delete[] data();
}
void flush() {
if (size() == 0) return;
file_.write(data(), size());
clear();
}
template <typename... T>
friend ostream output_file(cstring_view path, T... params);
@ -450,7 +457,7 @@ class FMT_API ostream final : private detail::buffer<char> {
* ``<integer>``: Flags passed to `open
<https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html>`_
(``file::WRONLY | file::CREATE`` by default)
(``file::WRONLY | file::CREATE | file::TRUNC`` by default)
* ``buffer_size=<integer>``: Output buffer size
**Example**::
@ -465,50 +472,6 @@ inline ostream output_file(cstring_view path, T... params) {
}
#endif // FMT_USE_FCNTL
#ifdef FMT_LOCALE
// A "C" numeric locale.
class locale {
private:
# ifdef _WIN32
using locale_t = _locale_t;
static void freelocale(locale_t loc) { _free_locale(loc); }
static double strtod_l(const char* nptr, char** endptr, _locale_t loc) {
return _strtod_l(nptr, endptr, loc);
}
# endif
locale_t locale_;
public:
using type = locale_t;
locale(const locale&) = delete;
void operator=(const locale&) = delete;
locale() {
# ifndef _WIN32
locale_ = FMT_SYSTEM(newlocale(LC_NUMERIC_MASK, "C", nullptr));
# else
locale_ = _create_locale(LC_NUMERIC, "C");
# endif
if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
}
~locale() { freelocale(locale_); }
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 = nullptr;
double result = strtod_l(str, &end, locale_);
str = end;
return result;
}
};
using Locale FMT_DEPRECATED_ALIAS = locale;
#endif // FMT_LOCALE
FMT_MODULE_EXPORT_END
FMT_END_NAMESPACE

View File

@ -0,0 +1,237 @@
// Formatting library for C++ - std::ostream support
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#ifndef FMT_OSTREAM_H_
#define FMT_OSTREAM_H_
#include <fstream>
#include <ostream>
#if defined(_WIN32) && defined(__GLIBCXX__)
# include <ext/stdio_filebuf.h>
# include <ext/stdio_sync_filebuf.h>
#elif defined(_WIN32) && defined(_LIBCPP_VERSION)
# include <__std_stream>
#endif
#include "format.h"
FMT_BEGIN_NAMESPACE
template <typename OutputIt, typename Char> class basic_printf_context;
namespace detail {
// Checks if T has a user-defined operator<<.
template <typename T, typename Char, typename Enable = void>
class is_streamable {
private:
template <typename U>
static auto test(int)
-> bool_constant<sizeof(std::declval<std::basic_ostream<Char>&>()
<< std::declval<U>()) != 0>;
template <typename> static auto test(...) -> std::false_type;
using result = decltype(test<T>(0));
public:
is_streamable() = default;
static const bool value = result::value;
};
// Formatting of built-in types and arrays is intentionally disabled because
// it's handled by standard (non-ostream) formatters.
template <typename T, typename Char>
struct is_streamable<
T, Char,
enable_if_t<
std::is_arithmetic<T>::value || std::is_array<T>::value ||
std::is_pointer<T>::value || std::is_same<T, char8_type>::value ||
std::is_convertible<T, fmt::basic_string_view<Char>>::value ||
std::is_same<T, std_string_view<Char>>::value ||
(std::is_convertible<T, int>::value && !std::is_enum<T>::value)>>
: std::false_type {};
// Generate a unique explicit instantion in every translation unit using a tag
// type in an anonymous namespace.
namespace {
struct file_access_tag {};
} // namespace
template <class Tag, class BufType, FILE* BufType::*FileMemberPtr>
class file_access {
friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; }
};
#if FMT_MSC_VERSION
template class file_access<file_access_tag, std::filebuf,
&std::filebuf::_Myfile>;
auto get_file(std::filebuf&) -> FILE*;
#elif defined(_WIN32) && defined(_LIBCPP_VERSION)
template class file_access<file_access_tag, std::__stdoutbuf<char>,
&std::__stdoutbuf<char>::__file_>;
auto get_file(std::__stdoutbuf<char>&) -> FILE*;
#endif
inline bool write_ostream_unicode(std::ostream& os, fmt::string_view data) {
#if FMT_MSC_VERSION
if (auto* buf = dynamic_cast<std::filebuf*>(os.rdbuf()))
if (FILE* f = get_file(*buf)) return write_console(f, data);
#elif defined(_WIN32) && defined(__GLIBCXX__)
auto* rdbuf = os.rdbuf();
FILE* c_file;
if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf<char>*>(rdbuf))
c_file = fbuf->file();
else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf<char>*>(rdbuf))
c_file = fbuf->file();
else
return false;
if (c_file) return write_console(c_file, data);
#elif defined(_WIN32) && defined(_LIBCPP_VERSION)
if (auto* buf = dynamic_cast<std::__stdoutbuf<char>*>(os.rdbuf()))
if (FILE* f = get_file(*buf)) return write_console(f, data);
#else
ignore_unused(os, data);
#endif
return false;
}
inline bool write_ostream_unicode(std::wostream&,
fmt::basic_string_view<wchar_t>) {
return false;
}
// Write the content of buf to os.
// It is a separate function rather than a part of vprint to simplify testing.
template <typename Char>
void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) {
const Char* buf_data = buf.data();
using unsigned_streamsize = std::make_unsigned<std::streamsize>::type;
unsigned_streamsize size = buf.size();
unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());
do {
unsigned_streamsize n = size <= max_size ? size : max_size;
os.write(buf_data, static_cast<std::streamsize>(n));
buf_data += n;
size -= n;
} while (size != 0);
}
template <typename Char, typename T>
void format_value(buffer<Char>& buf, const T& value,
locale_ref loc = locale_ref()) {
auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);
auto&& output = std::basic_ostream<Char>(&format_buf);
#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
if (loc) output.imbue(loc.get<std::locale>());
#endif
output << value;
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
}
template <typename T> struct streamed_view { const T& value; };
} // namespace detail
// Formats an object of type T that has an overloaded ostream operator<<.
template <typename Char>
struct basic_ostream_formatter : formatter<basic_string_view<Char>, Char> {
void set_debug_format() = delete;
template <typename T, typename OutputIt>
auto format(const T& value, basic_format_context<OutputIt, Char>& ctx) const
-> OutputIt {
auto buffer = basic_memory_buffer<Char>();
format_value(buffer, value, ctx.locale());
return formatter<basic_string_view<Char>, Char>::format(
{buffer.data(), buffer.size()}, ctx);
}
};
using ostream_formatter = basic_ostream_formatter<char>;
template <typename T, typename Char>
struct formatter<detail::streamed_view<T>, Char>
: basic_ostream_formatter<Char> {
template <typename OutputIt>
auto format(detail::streamed_view<T> view,
basic_format_context<OutputIt, Char>& ctx) const -> OutputIt {
return basic_ostream_formatter<Char>::format(view.value, ctx);
}
};
/**
\rst
Returns a view that formats `value` via an ostream ``operator<<``.
**Example**::
fmt::print("Current thread id: {}\n",
fmt::streamed(std::this_thread::get_id()));
\endrst
*/
template <typename T>
auto streamed(const T& value) -> detail::streamed_view<T> {
return {value};
}
namespace detail {
// Formats an object of type T that has an overloaded ostream operator<<.
template <typename T, typename Char>
struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
: basic_ostream_formatter<Char> {
using basic_ostream_formatter<Char>::format;
};
inline void vprint_directly(std::ostream& os, string_view format_str,
format_args args) {
auto buffer = memory_buffer();
detail::vformat_to(buffer, format_str, args);
detail::write_buffer(os, buffer);
}
} // namespace detail
FMT_MODULE_EXPORT template <typename Char>
void vprint(std::basic_ostream<Char>& os,
basic_string_view<type_identity_t<Char>> format_str,
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
auto buffer = basic_memory_buffer<Char>();
detail::vformat_to(buffer, format_str, args);
if (detail::write_ostream_unicode(os, {buffer.data(), buffer.size()})) return;
detail::write_buffer(os, buffer);
}
/**
\rst
Prints formatted data to the stream *os*.
**Example**::
fmt::print(cerr, "Don't {}!", "panic");
\endrst
*/
FMT_MODULE_EXPORT template <typename... T>
void print(std::ostream& os, format_string<T...> fmt, T&&... args) {
const auto& vargs = fmt::make_format_args(args...);
if (detail::is_utf8())
vprint(os, fmt, vargs);
else
detail::vprint_directly(os, fmt, vargs);
}
FMT_MODULE_EXPORT
template <typename... Args>
void print(std::wostream& os,
basic_format_string<wchar_t, type_identity_t<Args>...> fmt,
Args&&... args) {
vprint(os, fmt, fmt::make_format_args<buffer_context<wchar_t>>(args...));
}
FMT_END_NAMESPACE
#endif // FMT_OSTREAM_H_

View File

@ -10,7 +10,6 @@
#include <algorithm> // std::max
#include <limits> // std::numeric_limits
#include <ostream>
#include "format.h"
@ -233,7 +232,7 @@ class printf_arg_formatter : public arg_formatter<Char> {
OutputIt write_null_pointer(bool is_string = false) {
auto s = this->specs;
s.type = 0;
s.type = presentation_type::none;
return write_bytes(this->out, is_string ? "(null)" : "(nil)", s);
}
@ -249,8 +248,10 @@ class printf_arg_formatter : public arg_formatter<Char> {
// std::is_same instead.
if (std::is_same<T, Char>::value) {
format_specs fmt_specs = this->specs;
if (fmt_specs.type && fmt_specs.type != 'c')
if (fmt_specs.type != presentation_type::none &&
fmt_specs.type != presentation_type::chr) {
return (*this)(static_cast<int>(value));
}
fmt_specs.sign = sign::none;
fmt_specs.alt = false;
fmt_specs.fill[0] = ' '; // Ignore '0' flag for char types.
@ -271,13 +272,13 @@ class printf_arg_formatter : public arg_formatter<Char> {
/** Formats a null-terminated C string. */
OutputIt operator()(const char* value) {
if (value) return base::operator()(value);
return write_null_pointer(this->specs.type != 'p');
return write_null_pointer(this->specs.type != presentation_type::pointer);
}
/** Formats a null-terminated wide C string. */
OutputIt operator()(const wchar_t* value) {
if (value) return base::operator()(value);
return write_null_pointer(this->specs.type != 'p');
return write_null_pointer(this->specs.type != presentation_type::pointer);
}
OutputIt operator()(basic_string_view<Char> value) {
@ -490,13 +491,13 @@ void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
// Parse type.
if (it == end) FMT_THROW(format_error("invalid format string"));
specs.type = static_cast<char>(*it++);
char type = static_cast<char>(*it++);
if (arg.is_integral()) {
// Normalize type.
switch (specs.type) {
switch (type) {
case 'i':
case 'u':
specs.type = 'd';
type = 'd';
break;
case 'c':
visit_format_arg(
@ -505,6 +506,9 @@ void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
break;
}
}
specs.type = parse_presentation_type(type);
if (specs.type == presentation_type::none)
parse_ctx.on_error("invalid type specifier");
start = it;
@ -556,7 +560,7 @@ inline auto vsprintf(
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
-> std::basic_string<Char> {
basic_memory_buffer<Char> buffer;
vprintf(buffer, to_string_view(fmt), args);
vprintf(buffer, detail::to_string_view(fmt), args);
return to_string(buffer);
}
@ -573,7 +577,8 @@ template <typename S, typename... T,
typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
inline auto sprintf(const S& fmt, const T&... args) -> std::basic_string<Char> {
using context = basic_printf_context_t<Char>;
return vsprintf(to_string_view(fmt), fmt::make_format_args<context>(args...));
return vsprintf(detail::to_string_view(fmt),
fmt::make_format_args<context>(args...));
}
template <typename S, typename Char = char_t<S>>
@ -582,7 +587,7 @@ inline auto vfprintf(
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
-> int {
basic_memory_buffer<Char> buffer;
vprintf(buffer, to_string_view(fmt), args);
vprintf(buffer, detail::to_string_view(fmt), args);
size_t size = buffer.size();
return std::fwrite(buffer.data(), sizeof(Char), size, f) < size
? -1
@ -601,7 +606,7 @@ inline auto vfprintf(
template <typename S, typename... T, typename Char = char_t<S>>
inline auto fprintf(std::FILE* f, const S& fmt, const T&... args) -> int {
using context = basic_printf_context_t<Char>;
return vfprintf(f, to_string_view(fmt),
return vfprintf(f, detail::to_string_view(fmt),
fmt::make_format_args<context>(args...));
}
@ -610,7 +615,7 @@ inline auto vprintf(
const S& fmt,
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
-> int {
return vfprintf(stdout, to_string_view(fmt), args);
return vfprintf(stdout, detail::to_string_view(fmt), args);
}
/**
@ -625,27 +630,10 @@ inline auto vprintf(
template <typename S, typename... T, FMT_ENABLE_IF(detail::is_string<S>::value)>
inline auto printf(const S& fmt, const T&... args) -> int {
return vprintf(
to_string_view(fmt),
detail::to_string_view(fmt),
fmt::make_format_args<basic_printf_context_t<char_t<S>>>(args...));
}
template <typename S, typename Char = char_t<S>>
FMT_DEPRECATED auto vfprintf(
std::basic_ostream<Char>& os, const S& fmt,
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
-> int {
basic_memory_buffer<Char> buffer;
vprintf(buffer, to_string_view(fmt), args);
os.write(buffer.data(), static_cast<std::streamsize>(buffer.size()));
return static_cast<int>(buffer.size());
}
template <typename S, typename... T, typename Char = char_t<S>>
FMT_DEPRECATED auto fprintf(std::basic_ostream<Char>& os, const S& fmt,
const T&... args) -> int {
return vfprintf(os, to_string_view(fmt),
fmt::make_format_args<basic_printf_context_t<Char>>(args...));
}
FMT_MODULE_EXPORT_END
FMT_END_NAMESPACE

View File

@ -0,0 +1,722 @@
// Formatting library for C++ - experimental range support
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
//
// Copyright (c) 2018 - present, Remotion (Igor Schulz)
// All Rights Reserved
// {fmt} support for ranges, containers and types tuple interface.
#ifndef FMT_RANGES_H_
#define FMT_RANGES_H_
#include <initializer_list>
#include <tuple>
#include <type_traits>
#include "format.h"
FMT_BEGIN_NAMESPACE
namespace detail {
template <typename RangeT, typename OutputIterator>
OutputIterator copy(const RangeT& range, OutputIterator out) {
for (auto it = range.begin(), end = range.end(); it != end; ++it)
*out++ = *it;
return out;
}
template <typename OutputIterator>
OutputIterator copy(const char* str, OutputIterator out) {
while (*str) *out++ = *str++;
return out;
}
template <typename OutputIterator>
OutputIterator copy(char ch, OutputIterator out) {
*out++ = ch;
return out;
}
template <typename OutputIterator>
OutputIterator copy(wchar_t ch, OutputIterator out) {
*out++ = ch;
return out;
}
// Returns true if T has a std::string-like interface, like std::string_view.
template <typename T> class is_std_string_like {
template <typename U>
static auto check(U* p)
-> decltype((void)p->find('a'), p->length(), (void)p->data(), int());
template <typename> static void check(...);
public:
static constexpr const bool value =
is_string<T>::value ||
std::is_convertible<T, std_string_view<char>>::value ||
!std::is_void<decltype(check<T>(nullptr))>::value;
};
template <typename Char>
struct is_std_string_like<fmt::basic_string_view<Char>> : std::true_type {};
template <typename T> class is_map {
template <typename U> static auto check(U*) -> typename U::mapped_type;
template <typename> static void check(...);
public:
#ifdef FMT_FORMAT_MAP_AS_LIST
static constexpr const bool value = false;
#else
static constexpr const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value;
#endif
};
template <typename T> class is_set {
template <typename U> static auto check(U*) -> typename U::key_type;
template <typename> static void check(...);
public:
#ifdef FMT_FORMAT_SET_AS_LIST
static constexpr const bool value = false;
#else
static constexpr const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value && !is_map<T>::value;
#endif
};
template <typename... Ts> struct conditional_helper {};
template <typename T, typename _ = void> struct is_range_ : std::false_type {};
#if !FMT_MSC_VERSION || FMT_MSC_VERSION > 1800
# define FMT_DECLTYPE_RETURN(val) \
->decltype(val) { return val; } \
static_assert( \
true, "") // This makes it so that a semicolon is required after the
// macro, which helps clang-format handle the formatting.
// C array overload
template <typename T, std::size_t N>
auto range_begin(const T (&arr)[N]) -> const T* {
return arr;
}
template <typename T, std::size_t N>
auto range_end(const T (&arr)[N]) -> const T* {
return arr + N;
}
template <typename T, typename Enable = void>
struct has_member_fn_begin_end_t : std::false_type {};
template <typename T>
struct has_member_fn_begin_end_t<T, void_t<decltype(std::declval<T>().begin()),
decltype(std::declval<T>().end())>>
: std::true_type {};
// Member function overload
template <typename T>
auto range_begin(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).begin());
template <typename T>
auto range_end(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).end());
// ADL overload. Only participates in overload resolution if member functions
// are not found.
template <typename T>
auto range_begin(T&& rng)
-> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
decltype(begin(static_cast<T&&>(rng)))> {
return begin(static_cast<T&&>(rng));
}
template <typename T>
auto range_end(T&& rng) -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
decltype(end(static_cast<T&&>(rng)))> {
return end(static_cast<T&&>(rng));
}
template <typename T, typename Enable = void>
struct has_const_begin_end : std::false_type {};
template <typename T, typename Enable = void>
struct has_mutable_begin_end : std::false_type {};
template <typename T>
struct has_const_begin_end<
T,
void_t<
decltype(detail::range_begin(std::declval<const remove_cvref_t<T>&>())),
decltype(detail::range_end(std::declval<const remove_cvref_t<T>&>()))>>
: std::true_type {};
template <typename T>
struct has_mutable_begin_end<
T, void_t<decltype(detail::range_begin(std::declval<T>())),
decltype(detail::range_end(std::declval<T>())),
enable_if_t<std::is_copy_constructible<T>::value>>>
: std::true_type {};
template <typename T>
struct is_range_<T, void>
: std::integral_constant<bool, (has_const_begin_end<T>::value ||
has_mutable_begin_end<T>::value)> {};
# undef FMT_DECLTYPE_RETURN
#endif
// tuple_size and tuple_element check.
template <typename T> class is_tuple_like_ {
template <typename U>
static auto check(U* p) -> decltype(std::tuple_size<U>::value, int());
template <typename> static void check(...);
public:
static constexpr const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value;
};
// Check for integer_sequence
#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VERSION >= 1900
template <typename T, T... N>
using integer_sequence = std::integer_sequence<T, N...>;
template <size_t... N> using index_sequence = std::index_sequence<N...>;
template <size_t N> using make_index_sequence = std::make_index_sequence<N>;
#else
template <typename T, T... N> struct integer_sequence {
using value_type = T;
static FMT_CONSTEXPR size_t size() { return sizeof...(N); }
};
template <size_t... N> using index_sequence = integer_sequence<size_t, N...>;
template <typename T, size_t N, T... Ns>
struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
template <typename T, T... Ns>
struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
template <size_t N>
using make_index_sequence = make_integer_sequence<size_t, N>;
#endif
template <typename T>
using tuple_index_sequence = make_index_sequence<std::tuple_size<T>::value>;
template <typename T, typename C, bool = is_tuple_like_<T>::value>
class is_tuple_formattable_ {
public:
static constexpr const bool value = false;
};
template <typename T, typename C> class is_tuple_formattable_<T, C, true> {
template <std::size_t... I>
static std::true_type check2(index_sequence<I...>,
integer_sequence<bool, (I == I)...>);
static std::false_type check2(...);
template <std::size_t... I>
static decltype(check2(
index_sequence<I...>{},
integer_sequence<
bool, (is_formattable<typename std::tuple_element<I, T>::type,
C>::value)...>{})) check(index_sequence<I...>);
public:
static constexpr const bool value =
decltype(check(tuple_index_sequence<T>{}))::value;
};
template <class Tuple, class F, size_t... Is>
void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) noexcept {
using std::get;
// using free function get<I>(T) now.
const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
(void)_; // blocks warnings
}
template <class T>
FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
T const&) {
return {};
}
template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
const auto indexes = get_indexes(tup);
for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
}
#if FMT_MSC_VERSION && FMT_MSC_VERSION < 1920
// Older MSVC doesn't get the reference type correctly for arrays.
template <typename R> struct range_reference_type_impl {
using type = decltype(*detail::range_begin(std::declval<R&>()));
};
template <typename T, std::size_t N> struct range_reference_type_impl<T[N]> {
using type = T&;
};
template <typename T>
using range_reference_type = typename range_reference_type_impl<T>::type;
#else
template <typename Range>
using range_reference_type =
decltype(*detail::range_begin(std::declval<Range&>()));
#endif
// We don't use the Range's value_type for anything, but we do need the Range's
// reference type, with cv-ref stripped.
template <typename Range>
using uncvref_type = remove_cvref_t<range_reference_type<Range>>;
template <typename Range>
using uncvref_first_type =
remove_cvref_t<decltype(std::declval<range_reference_type<Range>>().first)>;
template <typename Range>
using uncvref_second_type = remove_cvref_t<
decltype(std::declval<range_reference_type<Range>>().second)>;
template <typename OutputIt> OutputIt write_delimiter(OutputIt out) {
*out++ = ',';
*out++ = ' ';
return out;
}
template <typename Char, typename OutputIt>
auto write_range_entry(OutputIt out, basic_string_view<Char> str) -> OutputIt {
return write_escaped_string(out, str);
}
template <typename Char, typename OutputIt, typename T,
FMT_ENABLE_IF(std::is_convertible<T, std_string_view<char>>::value)>
inline auto write_range_entry(OutputIt out, const T& str) -> OutputIt {
auto sv = std_string_view<Char>(str);
return write_range_entry<Char>(out, basic_string_view<Char>(sv));
}
template <typename Char, typename OutputIt, typename Arg,
FMT_ENABLE_IF(std::is_same<Arg, Char>::value)>
OutputIt write_range_entry(OutputIt out, const Arg v) {
return write_escaped_char(out, v);
}
template <
typename Char, typename OutputIt, typename Arg,
FMT_ENABLE_IF(!is_std_string_like<typename std::decay<Arg>::type>::value &&
!std::is_same<Arg, Char>::value)>
OutputIt write_range_entry(OutputIt out, const Arg& v) {
return write<Char>(out, v);
}
} // namespace detail
template <typename T> struct is_tuple_like {
static constexpr const bool value =
detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
};
template <typename T, typename C> struct is_tuple_formattable {
static constexpr const bool value =
detail::is_tuple_formattable_<T, C>::value;
};
template <typename TupleT, typename Char>
struct formatter<TupleT, Char,
enable_if_t<fmt::is_tuple_like<TupleT>::value &&
fmt::is_tuple_formattable<TupleT, Char>::value>> {
private:
basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};
basic_string_view<Char> opening_bracket_ =
detail::string_literal<Char, '('>{};
basic_string_view<Char> closing_bracket_ =
detail::string_literal<Char, ')'>{};
// C++11 generic lambda for format().
template <typename FormatContext> struct format_each {
template <typename T> void operator()(const T& v) {
if (i > 0) out = detail::copy_str<Char>(separator, out);
out = detail::write_range_entry<Char>(out, v);
++i;
}
int i;
typename FormatContext::iterator& out;
basic_string_view<Char> separator;
};
public:
FMT_CONSTEXPR formatter() {}
FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {
separator_ = sep;
}
FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,
basic_string_view<Char> close) {
opening_bracket_ = open;
closing_bracket_ = close;
}
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
template <typename FormatContext = format_context>
auto format(const TupleT& values, FormatContext& ctx) const
-> decltype(ctx.out()) {
auto out = ctx.out();
out = detail::copy_str<Char>(opening_bracket_, out);
detail::for_each(values, format_each<FormatContext>{0, out, separator_});
out = detail::copy_str<Char>(closing_bracket_, out);
return out;
}
};
template <typename T, typename Char> struct is_range {
static constexpr const bool value =
detail::is_range_<T>::value && !detail::is_std_string_like<T>::value &&
!std::is_convertible<T, std::basic_string<Char>>::value &&
!std::is_convertible<T, detail::std_string_view<Char>>::value;
};
namespace detail {
template <typename Context> struct range_mapper {
using mapper = arg_mapper<Context>;
template <typename T,
FMT_ENABLE_IF(has_formatter<remove_cvref_t<T>, Context>::value)>
static auto map(T&& value) -> T&& {
return static_cast<T&&>(value);
}
template <typename T,
FMT_ENABLE_IF(!has_formatter<remove_cvref_t<T>, Context>::value)>
static auto map(T&& value)
-> decltype(mapper().map(static_cast<T&&>(value))) {
return mapper().map(static_cast<T&&>(value));
}
};
template <typename Char, typename Element>
using range_formatter_type = conditional_t<
is_formattable<Element, Char>::value,
formatter<remove_cvref_t<decltype(range_mapper<buffer_context<Char>>{}.map(
std::declval<Element>()))>,
Char>,
fallback_formatter<Element, Char>>;
template <typename R>
using maybe_const_range =
conditional_t<has_const_begin_end<R>::value, const R, R>;
// Workaround a bug in MSVC 2015 and earlier.
#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910
template <typename R, typename Char>
struct is_formattable_delayed
: disjunction<
is_formattable<uncvref_type<maybe_const_range<R>>, Char>,
has_fallback_formatter<uncvref_type<maybe_const_range<R>>, Char>> {};
#endif
} // namespace detail
template <typename T, typename Char, typename Enable = void>
struct range_formatter;
template <typename T, typename Char>
struct range_formatter<
T, Char,
enable_if_t<conjunction<
std::is_same<T, remove_cvref_t<T>>,
disjunction<is_formattable<T, Char>,
detail::has_fallback_formatter<T, Char>>>::value>> {
private:
detail::range_formatter_type<Char, T> underlying_;
bool custom_specs_ = false;
basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};
basic_string_view<Char> opening_bracket_ =
detail::string_literal<Char, '['>{};
basic_string_view<Char> closing_bracket_ =
detail::string_literal<Char, ']'>{};
template <class U>
FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, int)
-> decltype(u.set_debug_format()) {
u.set_debug_format();
}
template <class U>
FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {}
FMT_CONSTEXPR void maybe_set_debug_format() {
maybe_set_debug_format(underlying_, 0);
}
public:
FMT_CONSTEXPR range_formatter() {}
FMT_CONSTEXPR auto underlying() -> detail::range_formatter_type<Char, T>& {
return underlying_;
}
FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {
separator_ = sep;
}
FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,
basic_string_view<Char> close) {
opening_bracket_ = open;
closing_bracket_ = close;
}
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
auto it = ctx.begin();
auto end = ctx.end();
if (it == end || *it == '}') {
maybe_set_debug_format();
return it;
}
if (*it == 'n') {
set_brackets({}, {});
++it;
}
if (*it == '}') {
maybe_set_debug_format();
return it;
}
if (*it != ':')
FMT_THROW(format_error("no other top-level range formatters supported"));
custom_specs_ = true;
++it;
ctx.advance_to(it);
return underlying_.parse(ctx);
}
template <typename R, class FormatContext>
auto format(R&& range, FormatContext& ctx) const -> decltype(ctx.out()) {
detail::range_mapper<buffer_context<Char>> mapper;
auto out = ctx.out();
out = detail::copy_str<Char>(opening_bracket_, out);
int i = 0;
auto it = detail::range_begin(range);
auto end = detail::range_end(range);
for (; it != end; ++it) {
if (i > 0) out = detail::copy_str<Char>(separator_, out);
;
ctx.advance_to(out);
out = underlying_.format(mapper.map(*it), ctx);
++i;
}
out = detail::copy_str<Char>(closing_bracket_, out);
return out;
}
};
enum class range_format { disabled, map, set, sequence, string, debug_string };
namespace detail {
template <typename T> struct range_format_kind_ {
static constexpr auto value = std::is_same<range_reference_type<T>, T>::value
? range_format::disabled
: is_map<T>::value ? range_format::map
: is_set<T>::value ? range_format::set
: range_format::sequence;
};
template <range_format K, typename R, typename Char, typename Enable = void>
struct range_default_formatter;
template <range_format K>
using range_format_constant = std::integral_constant<range_format, K>;
template <range_format K, typename R, typename Char>
struct range_default_formatter<
K, R, Char,
enable_if_t<(K == range_format::sequence || K == range_format::map ||
K == range_format::set)>> {
using range_type = detail::maybe_const_range<R>;
range_formatter<detail::uncvref_type<range_type>, Char> underlying_;
FMT_CONSTEXPR range_default_formatter() { init(range_format_constant<K>()); }
FMT_CONSTEXPR void init(range_format_constant<range_format::set>) {
underlying_.set_brackets(detail::string_literal<Char, '{'>{},
detail::string_literal<Char, '}'>{});
}
FMT_CONSTEXPR void init(range_format_constant<range_format::map>) {
underlying_.set_brackets(detail::string_literal<Char, '{'>{},
detail::string_literal<Char, '}'>{});
underlying_.underlying().set_brackets({}, {});
underlying_.underlying().set_separator(
detail::string_literal<Char, ':', ' '>{});
}
FMT_CONSTEXPR void init(range_format_constant<range_format::sequence>) {}
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return underlying_.parse(ctx);
}
template <typename FormatContext>
auto format(range_type& range, FormatContext& ctx) const
-> decltype(ctx.out()) {
return underlying_.format(range, ctx);
}
};
} // namespace detail
template <typename T, typename Char, typename Enable = void>
struct range_format_kind
: conditional_t<
is_range<T, Char>::value, detail::range_format_kind_<T>,
std::integral_constant<range_format, range_format::disabled>> {};
template <typename R, typename Char>
struct formatter<
R, Char,
enable_if_t<conjunction<bool_constant<range_format_kind<R, Char>::value !=
range_format::disabled>
// Workaround a bug in MSVC 2015 and earlier.
#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910
,
detail::is_formattable_delayed<R, Char>
#endif
>::value>>
: detail::range_default_formatter<range_format_kind<R, Char>::value, R,
Char> {
};
template <typename Char, typename... T> struct tuple_join_view : detail::view {
const std::tuple<T...>& tuple;
basic_string_view<Char> sep;
tuple_join_view(const std::tuple<T...>& t, basic_string_view<Char> s)
: tuple(t), sep{s} {}
};
template <typename Char, typename... T>
using tuple_arg_join = tuple_join_view<Char, T...>;
// Define FMT_TUPLE_JOIN_SPECIFIERS to enable experimental format specifiers
// support in tuple_join. It is disabled by default because of issues with
// the dynamic width and precision.
#ifndef FMT_TUPLE_JOIN_SPECIFIERS
# define FMT_TUPLE_JOIN_SPECIFIERS 0
#endif
template <typename Char, typename... T>
struct formatter<tuple_join_view<Char, T...>, Char> {
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return do_parse(ctx, std::integral_constant<size_t, sizeof...(T)>());
}
template <typename FormatContext>
auto format(const tuple_join_view<Char, T...>& value,
FormatContext& ctx) const -> typename FormatContext::iterator {
return do_format(value, ctx,
std::integral_constant<size_t, sizeof...(T)>());
}
private:
std::tuple<formatter<typename std::decay<T>::type, Char>...> formatters_;
template <typename ParseContext>
FMT_CONSTEXPR auto do_parse(ParseContext& ctx,
std::integral_constant<size_t, 0>)
-> decltype(ctx.begin()) {
return ctx.begin();
}
template <typename ParseContext, size_t N>
FMT_CONSTEXPR auto do_parse(ParseContext& ctx,
std::integral_constant<size_t, N>)
-> decltype(ctx.begin()) {
auto end = ctx.begin();
#if FMT_TUPLE_JOIN_SPECIFIERS
end = std::get<sizeof...(T) - N>(formatters_).parse(ctx);
if (N > 1) {
auto end1 = do_parse(ctx, std::integral_constant<size_t, N - 1>());
if (end != end1)
FMT_THROW(format_error("incompatible format specs for tuple elements"));
}
#endif
return end;
}
template <typename FormatContext>
auto do_format(const tuple_join_view<Char, T...>&, FormatContext& ctx,
std::integral_constant<size_t, 0>) const ->
typename FormatContext::iterator {
return ctx.out();
}
template <typename FormatContext, size_t N>
auto do_format(const tuple_join_view<Char, T...>& value, FormatContext& ctx,
std::integral_constant<size_t, N>) const ->
typename FormatContext::iterator {
auto out = std::get<sizeof...(T) - N>(formatters_)
.format(std::get<sizeof...(T) - N>(value.tuple), ctx);
if (N > 1) {
out = std::copy(value.sep.begin(), value.sep.end(), out);
ctx.advance_to(out);
return do_format(value, ctx, std::integral_constant<size_t, N - 1>());
}
return out;
}
};
FMT_MODULE_EXPORT_BEGIN
/**
\rst
Returns an object that formats `tuple` with elements separated by `sep`.
**Example**::
std::tuple<int, char> t = {1, 'a'};
fmt::print("{}", fmt::join(t, ", "));
// Output: "1, a"
\endrst
*/
template <typename... T>
FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple, string_view sep)
-> tuple_join_view<char, T...> {
return {tuple, sep};
}
template <typename... T>
FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple,
basic_string_view<wchar_t> sep)
-> tuple_join_view<wchar_t, T...> {
return {tuple, sep};
}
/**
\rst
Returns an object that formats `initializer_list` with elements separated by
`sep`.
**Example**::
fmt::print("{}", fmt::join({1, 2, 3}, ", "));
// Output: "1, 2, 3"
\endrst
*/
template <typename T>
auto join(std::initializer_list<T> list, string_view sep)
-> join_view<const T*, const T*> {
return join(std::begin(list), std::end(list), sep);
}
FMT_MODULE_EXPORT_END
FMT_END_NAMESPACE
#endif // FMT_RANGES_H_

View File

@ -5,11 +5,10 @@
//
// For the license information refer to format.h.
#ifndef FMT_WCHAR_H_
#define FMT_WCHAR_H_
#ifndef FMT_XCHAR_H_
#define FMT_XCHAR_H_
#include <cwchar>
#include <tuple>
#include "format.h"
@ -30,9 +29,11 @@ using wmemory_buffer = basic_memory_buffer<wchar_t>;
#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
// Workaround broken conversion on older gcc.
template <typename... Args> using wformat_string = wstring_view;
inline auto runtime(wstring_view s) -> wstring_view { return s; }
#else
template <typename... Args>
using wformat_string = basic_format_string<wchar_t, type_identity_t<Args>...>;
inline auto runtime(wstring_view s) -> basic_runtime<wchar_t> { return {{s}}; }
#endif
template <> struct is_char<wchar_t> : std::true_type {};
@ -47,12 +48,7 @@ constexpr format_arg_store<wformat_context, Args...> make_wformat_args(
}
inline namespace literals {
constexpr auto operator"" _format(const wchar_t* s, size_t n)
-> detail::udl_formatter<wchar_t> {
return {{s, n}};
}
#if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
#if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_ARGS
constexpr detail::udl_arg<wchar_t> operator"" _a(const wchar_t* s, size_t) {
return {s};
}
@ -87,13 +83,19 @@ auto vformat(basic_string_view<Char> format_str,
return to_string(buffer);
}
template <typename... T>
auto format(wformat_string<T...> fmt, T&&... args) -> std::wstring {
return vformat(fmt::wstring_view(fmt), fmt::make_wformat_args(args...));
}
// Pass char_t as a default template parameter instead of using
// std::basic_string<char_t<S>> to reduce the symbol size.
template <typename S, typename... Args, typename Char = char_t<S>,
FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
FMT_ENABLE_IF(!std::is_same<Char, char>::value &&
!std::is_same<Char, wchar_t>::value)>
auto format(const S& format_str, Args&&... args) -> std::basic_string<Char> {
const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
return vformat(to_string_view(format_str), vargs);
return vformat(detail::to_string_view(format_str),
fmt::make_format_args<buffer_context<Char>>(args...));
}
template <typename Locale, typename S, typename Char = char_t<S>,
@ -103,7 +105,7 @@ inline auto vformat(
const Locale& loc, const S& format_str,
basic_format_args<buffer_context<type_identity_t<Char>>> args)
-> std::basic_string<Char> {
return detail::vformat(loc, to_string_view(format_str), args);
return detail::vformat(loc, detail::to_string_view(format_str), args);
}
template <typename Locale, typename S, typename... Args,
@ -112,8 +114,8 @@ template <typename Locale, typename S, typename... Args,
detail::is_exotic_char<Char>::value)>
inline auto format(const Locale& loc, const S& format_str, Args&&... args)
-> std::basic_string<Char> {
return detail::vformat(loc, to_string_view(format_str),
fmt::make_args_checked<Args...>(format_str, args...));
return detail::vformat(loc, detail::to_string_view(format_str),
fmt::make_format_args<buffer_context<Char>>(args...));
}
template <typename OutputIt, typename S, typename Char = char_t<S>,
@ -123,7 +125,7 @@ auto vformat_to(OutputIt out, const S& format_str,
basic_format_args<buffer_context<type_identity_t<Char>>> args)
-> OutputIt {
auto&& buf = detail::get_buffer<Char>(out);
detail::vformat_to(buf, to_string_view(format_str), args);
detail::vformat_to(buf, detail::to_string_view(format_str), args);
return detail::get_iterator(buf);
}
@ -132,18 +134,8 @@ template <typename OutputIt, typename S, typename... Args,
FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
detail::is_exotic_char<Char>::value)>
inline auto format_to(OutputIt out, const S& fmt, Args&&... args) -> OutputIt {
const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
return vformat_to(out, to_string_view(fmt), vargs);
}
template <typename S, typename... Args, typename Char, size_t SIZE,
typename Allocator, FMT_ENABLE_IF(detail::is_string<S>::value)>
FMT_DEPRECATED auto format_to(basic_memory_buffer<Char, SIZE, Allocator>& buf,
const S& format_str, Args&&... args) ->
typename buffer_context<Char>::iterator {
const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
detail::vformat_to(buf, to_string_view(format_str), vargs, {});
return detail::buffer_appender<Char>(buf);
return vformat_to(out, detail::to_string_view(fmt),
fmt::make_format_args<buffer_context<Char>>(args...));
}
template <typename Locale, typename S, typename OutputIt, typename... Args,
@ -155,7 +147,8 @@ inline auto vformat_to(
OutputIt out, const Locale& loc, const S& format_str,
basic_format_args<buffer_context<type_identity_t<Char>>> args) -> OutputIt {
auto&& buf = detail::get_buffer<Char>(out);
vformat_to(buf, to_string_view(format_str), args, detail::locale_ref(loc));
vformat_to(buf, detail::to_string_view(format_str), args,
detail::locale_ref(loc));
return detail::get_iterator(buf);
}
@ -167,8 +160,8 @@ template <
inline auto format_to(OutputIt out, const Locale& loc, const S& format_str,
Args&&... args) ->
typename std::enable_if<enable, OutputIt>::type {
const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
return vformat_to(out, loc, to_string_view(format_str), vargs);
return vformat_to(out, loc, to_string_view(format_str),
fmt::make_format_args<buffer_context<Char>>(args...));
}
template <typename OutputIt, typename Char, typename... Args,
@ -190,16 +183,16 @@ template <typename OutputIt, typename S, typename... Args,
detail::is_exotic_char<Char>::value)>
inline auto format_to_n(OutputIt out, size_t n, const S& fmt,
const Args&... args) -> format_to_n_result<OutputIt> {
const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
return vformat_to_n(out, n, to_string_view(fmt), vargs);
return vformat_to_n(out, n, detail::to_string_view(fmt),
fmt::make_format_args<buffer_context<Char>>(args...));
}
template <typename S, typename... Args, typename Char = char_t<S>,
FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
inline auto formatted_size(const S& fmt, Args&&... args) -> size_t {
detail::counting_buffer<Char> buf;
const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
detail::vformat_to(buf, to_string_view(fmt), vargs);
detail::vformat_to(buf, detail::to_string_view(fmt),
fmt::make_format_args<buffer_context<Char>>(args...));
return buf.count();
}
@ -217,11 +210,11 @@ inline void vprint(wstring_view fmt, wformat_args args) {
template <typename... T>
void print(std::FILE* f, wformat_string<T...> fmt, T&&... args) {
return vprint(f, wstring_view(fmt), make_wformat_args(args...));
return vprint(f, wstring_view(fmt), fmt::make_wformat_args(args...));
}
template <typename... T> void print(wformat_string<T...> fmt, T&&... args) {
return vprint(wstring_view(fmt), make_wformat_args(args...));
return vprint(wstring_view(fmt), fmt::make_wformat_args(args...));
}
/**
@ -233,4 +226,4 @@ template <typename T> inline auto to_wstring(const T& value) -> std::wstring {
FMT_MODULE_EXPORT_END
FMT_END_NAMESPACE
#endif // FMT_WCHAR_H_
#endif // FMT_XCHAR_H_

22
r5dev/thirdparty/spdlog/fmt/chrono.h vendored Normal file
View File

@ -0,0 +1,22 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's chrono support
//
#if !defined(SPDLOG_USE_STD_FORMAT)
# if !defined(SPDLOG_FMT_EXTERNAL)
# ifdef SPDLOG_HEADER_ONLY
# ifndef FMT_HEADER_ONLY
# define FMT_HEADER_ONLY
# endif
# endif
# include <spdlog/fmt/bundled/chrono.h>
# else
# include <fmt/chrono.h>
# endif
#endif

22
r5dev/thirdparty/spdlog/fmt/compile.h vendored Normal file
View File

@ -0,0 +1,22 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's compile-time support
//
#if !defined(SPDLOG_USE_STD_FORMAT)
# if !defined(SPDLOG_FMT_EXTERNAL)
# ifdef SPDLOG_HEADER_ONLY
# ifndef FMT_HEADER_ONLY
# define FMT_HEADER_ONLY
# endif
# endif
# include <spdlog/fmt/bundled/compile.h>
# else
# include <fmt/compile.h>
# endif
#endif

33
r5dev/thirdparty/spdlog/fmt/fmt.h vendored Normal file
View File

@ -0,0 +1,33 @@
//
// Copyright(c) 2016-2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// Include a bundled header-only copy of fmtlib or an external one.
// By default spdlog include its own copy.
//
#if defined(SPDLOG_USE_STD_FORMAT) // SPDLOG_USE_STD_FORMAT is defined - use std::format
# include <format>
#elif !defined(SPDLOG_FMT_EXTERNAL)
# if !defined(SPDLOG_COMPILED_LIB) && !defined(FMT_HEADER_ONLY)
# define FMT_HEADER_ONLY
# endif
# ifndef FMT_USE_WINDOWS_H
# define FMT_USE_WINDOWS_H 0
# endif
// enable the 'n' flag in for backward compatibility with fmt 6.x
# define FMT_DEPRECATED_N_SPECIFIER
// enable ostream formatting for backward compatibility with fmt 8.x
# define FMT_DEPRECATED_OSTREAM
# include <spdlog/fmt/bundled/core.h>
# include <spdlog/fmt/bundled/format.h>
#else // SPDLOG_FMT_EXTERNAL is defined - use external fmtlib
# include <fmt/core.h>
# include <fmt/format.h>
#endif

22
r5dev/thirdparty/spdlog/fmt/ostr.h vendored Normal file
View File

@ -0,0 +1,22 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's ostream support
//
#if !defined(SPDLOG_USE_STD_FORMAT)
# if !defined(SPDLOG_FMT_EXTERNAL)
# ifdef SPDLOG_HEADER_ONLY
# ifndef FMT_HEADER_ONLY
# define FMT_HEADER_ONLY
# endif
# endif
# include <spdlog/fmt/bundled/ostream.h>
# else
# include <fmt/ostream.h>
# endif
#endif

22
r5dev/thirdparty/spdlog/fmt/ranges.h vendored Normal file
View File

@ -0,0 +1,22 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's ranges support
//
#if !defined(SPDLOG_USE_STD_FORMAT)
# if !defined(SPDLOG_FMT_EXTERNAL)
# ifdef SPDLOG_HEADER_ONLY
# ifndef FMT_HEADER_ONLY
# define FMT_HEADER_ONLY
# endif
# endif
# include <spdlog/fmt/bundled/ranges.h>
# else
# include <fmt/ranges.h>
# endif
#endif

22
r5dev/thirdparty/spdlog/fmt/xchar.h vendored Normal file
View File

@ -0,0 +1,22 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's xchar support
//
#if !defined(SPDLOG_USE_STD_FORMAT)
# if !defined(SPDLOG_FMT_EXTERNAL)
# ifdef SPDLOG_HEADER_ONLY
# ifndef FMT_HEADER_ONLY
# define FMT_HEADER_ONLY
# endif
# endif
# include <spdlog/fmt/bundled/xchar.h>
# else
# include <fmt/xchar.h>
# endif
#endif

View File

@ -3,8 +3,8 @@
#pragma once
#include <thirdparty/spdlog/include/fmt/fmt.h>
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <spdlog/fmt/fmt.h>
#include <spdlog/details/log_msg.h>
namespace spdlog {

View File

@ -11,4 +11,8 @@ namespace sinks {
class sink;
}
namespace level {
enum level_enum : int;
}
} // namespace spdlog

View File

@ -1,49 +0,0 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/details/periodic_worker.h>
#endif
namespace spdlog {
namespace details {
SPDLOG_INLINE periodic_worker::periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval)
{
active_ = (interval > std::chrono::seconds::zero());
if (!active_)
{
return;
}
worker_thread_ = std::thread([this, callback_fun, interval]() {
for (;;)
{
std::unique_lock<std::mutex> lock(this->mutex_);
if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
{
return; // active_ == false, so exit this thread
}
callback_fun();
}
});
}
// stop the worker thread and join it
SPDLOG_INLINE periodic_worker::~periodic_worker()
{
if (worker_thread_.joinable())
{
{
std::lock_guard<std::mutex> lock(mutex_);
active_ = false;
}
cv_.notify_one();
worker_thread_.join();
}
}
} // namespace details
} // namespace spdlog

File diff suppressed because it is too large Load Diff

View File

@ -1,181 +0,0 @@
// Formatting library for C++ - std::ostream support
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#ifndef FMT_OSTREAM_H_
#define FMT_OSTREAM_H_
#include <ostream>
#include "format.h"
FMT_BEGIN_NAMESPACE
template <typename Char> class basic_printf_parse_context;
template <typename OutputIt, typename Char> class basic_printf_context;
namespace detail {
template <class Char> class formatbuf : public std::basic_streambuf<Char> {
private:
using int_type = typename std::basic_streambuf<Char>::int_type;
using traits_type = typename std::basic_streambuf<Char>::traits_type;
buffer<Char>& buffer_;
public:
formatbuf(buffer<Char>& buf) : buffer_(buf) {}
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
// disadvantage is that each call to sputc always results in a (virtual) call
// 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 {
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 {
buffer_.append(s, s + count);
return count;
}
};
struct converter {
template <typename T, FMT_ENABLE_IF(is_integral<T>::value)> converter(T);
};
template <typename Char> struct test_stream : std::basic_ostream<Char> {
private:
void_t<> operator<<(converter);
};
// Hide insertion operators for built-in types.
template <typename Char, typename Traits>
void_t<> operator<<(std::basic_ostream<Char, Traits>&, Char);
template <typename Char, typename Traits>
void_t<> operator<<(std::basic_ostream<Char, Traits>&, char);
template <typename Traits>
void_t<> operator<<(std::basic_ostream<char, Traits>&, char);
template <typename Traits>
void_t<> operator<<(std::basic_ostream<char, Traits>&, signed char);
template <typename Traits>
void_t<> operator<<(std::basic_ostream<char, Traits>&, unsigned char);
// Checks if T has a user-defined operator<< (e.g. not a member of
// std::ostream).
template <typename T, typename Char> class is_streamable {
private:
template <typename U>
static bool_constant<!std::is_same<decltype(std::declval<test_stream<Char>&>()
<< std::declval<U>()),
void_t<>>::value>
test(int);
template <typename> static std::false_type test(...);
using result = decltype(test<T>(0));
public:
is_streamable() = default;
static const bool value = result::value;
};
// Write the content of buf to os.
template <typename Char>
void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) {
const Char* buf_data = buf.data();
using unsigned_streamsize = std::make_unsigned<std::streamsize>::type;
unsigned_streamsize size = buf.size();
unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());
do {
unsigned_streamsize n = size <= max_size ? size : max_size;
os.write(buf_data, static_cast<std::streamsize>(n));
buf_data += n;
size -= n;
} while (size != 0);
}
template <typename Char, typename T>
void format_value(buffer<Char>& buf, const T& value,
locale_ref loc = locale_ref()) {
formatbuf<Char> format_buf(buf);
std::basic_ostream<Char> output(&format_buf);
#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
if (loc) output.imbue(loc.get<std::locale>());
#endif
output << value;
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
buf.try_resize(buf.size());
}
// Formats an object of type T that has an overloaded ostream operator<<.
template <typename T, typename Char>
struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
: private formatter<basic_string_view<Char>, Char> {
FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
-> decltype(ctx.begin()) {
return formatter<basic_string_view<Char>, Char>::parse(ctx);
}
template <typename ParseCtx,
FMT_ENABLE_IF(std::is_same<
ParseCtx, basic_printf_parse_context<Char>>::value)>
auto parse(ParseCtx& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
template <typename OutputIt>
auto format(const T& value, basic_format_context<OutputIt, Char>& ctx)
-> OutputIt {
basic_memory_buffer<Char> buffer;
format_value(buffer, value, ctx.locale());
basic_string_view<Char> str(buffer.data(), buffer.size());
return formatter<basic_string_view<Char>, Char>::format(str, ctx);
}
template <typename OutputIt>
auto format(const T& value, basic_printf_context<OutputIt, Char>& ctx)
-> OutputIt {
basic_memory_buffer<Char> buffer;
format_value(buffer, value, ctx.locale());
return std::copy(buffer.begin(), buffer.end(), ctx.out());
}
};
} // namespace detail
FMT_MODULE_EXPORT
template <typename Char>
void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
basic_memory_buffer<Char> buffer;
detail::vformat_to(buffer, format_str, args);
detail::write_buffer(os, buffer);
}
/**
\rst
Prints formatted data to the stream *os*.
**Example**::
fmt::print(cerr, "Don't {}!", "panic");
\endrst
*/
FMT_MODULE_EXPORT
template <typename S, typename... Args,
typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) {
vprint(os, to_string_view(format_str),
fmt::make_args_checked<Args...>(format_str, args...));
}
FMT_END_NAMESPACE
#endif // FMT_OSTREAM_H_

View File

@ -1,468 +0,0 @@
// Formatting library for C++ - experimental range support
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
//
// Copyright (c) 2018 - present, Remotion (Igor Schulz)
// All Rights Reserved
// {fmt} support for ranges, containers and types tuple interface.
#ifndef FMT_RANGES_H_
#define FMT_RANGES_H_
#include <initializer_list>
#include <type_traits>
#include "format.h"
FMT_BEGIN_NAMESPACE
template <typename Char, typename Enable = void> struct formatting_range {
#ifdef FMT_DEPRECATED_BRACED_RANGES
Char prefix = '{';
Char postfix = '}';
#else
Char prefix = '[';
Char postfix = ']';
#endif
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
};
template <typename Char, typename Enable = void> struct formatting_tuple {
Char prefix = '(';
Char postfix = ')';
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
};
namespace detail {
template <typename RangeT, typename OutputIterator>
OutputIterator copy(const RangeT& range, OutputIterator out) {
for (auto it = range.begin(), end = range.end(); it != end; ++it)
*out++ = *it;
return out;
}
template <typename OutputIterator>
OutputIterator copy(const char* str, OutputIterator out) {
while (*str) *out++ = *str++;
return out;
}
template <typename OutputIterator>
OutputIterator copy(char ch, OutputIterator out) {
*out++ = ch;
return out;
}
template <typename OutputIterator>
OutputIterator copy(wchar_t ch, OutputIterator out) {
*out++ = ch;
return out;
}
/// Return true value if T has std::string interface, like std::string_view.
template <typename T> class is_std_string_like {
template <typename U>
static auto check(U* p)
-> decltype((void)p->find('a'), p->length(), (void)p->data(), int());
template <typename> static void check(...);
public:
static FMT_CONSTEXPR_DECL const bool value =
is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value;
};
template <typename Char>
struct is_std_string_like<fmt::basic_string_view<Char>> : std::true_type {};
template <typename... Ts> struct conditional_helper {};
template <typename T, typename _ = void> struct is_range_ : std::false_type {};
#if !FMT_MSC_VER || FMT_MSC_VER > 1800
# define FMT_DECLTYPE_RETURN(val) \
->decltype(val) { return val; } \
static_assert( \
true, "") // This makes it so that a semicolon is required after the
// macro, which helps clang-format handle the formatting.
// C array overload
template <typename T, std::size_t N>
auto range_begin(const T (&arr)[N]) -> const T* {
return arr;
}
template <typename T, std::size_t N>
auto range_end(const T (&arr)[N]) -> const T* {
return arr + N;
}
template <typename T, typename Enable = void>
struct has_member_fn_begin_end_t : std::false_type {};
template <typename T>
struct has_member_fn_begin_end_t<T, void_t<decltype(std::declval<T>().begin()),
decltype(std::declval<T>().end())>>
: std::true_type {};
// Member function overload
template <typename T>
auto range_begin(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).begin());
template <typename T>
auto range_end(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).end());
// ADL overload. Only participates in overload resolution if member functions
// are not found.
template <typename T>
auto range_begin(T&& rng)
-> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
decltype(begin(static_cast<T&&>(rng)))> {
return begin(static_cast<T&&>(rng));
}
template <typename T>
auto range_end(T&& rng) -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
decltype(end(static_cast<T&&>(rng)))> {
return end(static_cast<T&&>(rng));
}
template <typename T, typename Enable = void>
struct has_const_begin_end : std::false_type {};
template <typename T, typename Enable = void>
struct has_mutable_begin_end : std::false_type {};
template <typename T>
struct has_const_begin_end<
T, void_t<decltype(detail::range_begin(
std::declval<const remove_cvref_t<T>&>())),
decltype(detail::range_begin(
std::declval<const remove_cvref_t<T>&>()))>>
: std::true_type {};
template <typename T>
struct has_mutable_begin_end<
T, void_t<decltype(detail::range_begin(std::declval<T>())),
decltype(detail::range_begin(std::declval<T>())),
enable_if_t<std::is_copy_constructible<T>::value>>>
: std::true_type {};
template <typename T>
struct is_range_<T, void>
: std::integral_constant<bool, (has_const_begin_end<T>::value ||
has_mutable_begin_end<T>::value)> {};
template <typename T, typename Enable = void> struct range_to_view;
template <typename T>
struct range_to_view<T, enable_if_t<has_const_begin_end<T>::value>> {
struct view_t {
const T* m_range_ptr;
auto begin() const FMT_DECLTYPE_RETURN(detail::range_begin(*m_range_ptr));
auto end() const FMT_DECLTYPE_RETURN(detail::range_end(*m_range_ptr));
};
static auto view(const T& range) -> view_t { return {&range}; }
};
template <typename T>
struct range_to_view<T, enable_if_t<!has_const_begin_end<T>::value &&
has_mutable_begin_end<T>::value>> {
struct view_t {
T m_range_copy;
auto begin() FMT_DECLTYPE_RETURN(detail::range_begin(m_range_copy));
auto end() FMT_DECLTYPE_RETURN(detail::range_end(m_range_copy));
};
static auto view(const T& range) -> view_t { return {range}; }
};
# undef FMT_DECLTYPE_RETURN
#endif
/// tuple_size and tuple_element check.
template <typename T> class is_tuple_like_ {
template <typename U>
static auto check(U* p) -> decltype(std::tuple_size<U>::value, int());
template <typename> static void check(...);
public:
static FMT_CONSTEXPR_DECL const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value;
};
// Check for integer_sequence
#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
template <typename T, T... N>
using integer_sequence = std::integer_sequence<T, N...>;
template <size_t... N> using index_sequence = std::index_sequence<N...>;
template <size_t N> using make_index_sequence = std::make_index_sequence<N>;
#else
template <typename T, T... N> struct integer_sequence {
using value_type = T;
static FMT_CONSTEXPR size_t size() { return sizeof...(N); }
};
template <size_t... N> using index_sequence = integer_sequence<size_t, N...>;
template <typename T, size_t N, T... Ns>
struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
template <typename T, T... Ns>
struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
template <size_t N>
using make_index_sequence = make_integer_sequence<size_t, N>;
#endif
template <class Tuple, class F, size_t... Is>
void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
using std::get;
// using free function get<I>(T) now.
const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
(void)_; // blocks warnings
}
template <class T>
FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
T const&) {
return {};
}
template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
const auto indexes = get_indexes(tup);
for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
}
template <typename Range>
using value_type =
remove_cvref_t<decltype(*detail::range_begin(std::declval<Range>()))>;
template <typename OutputIt> OutputIt write_delimiter(OutputIt out) {
*out++ = ',';
*out++ = ' ';
return out;
}
template <
typename Char, typename OutputIt, typename Arg,
FMT_ENABLE_IF(is_std_string_like<typename std::decay<Arg>::type>::value)>
OutputIt write_range_entry(OutputIt out, const Arg& v) {
*out++ = '"';
out = write<Char>(out, v);
*out++ = '"';
return out;
}
template <typename Char, typename OutputIt, typename Arg,
FMT_ENABLE_IF(std::is_same<Arg, Char>::value)>
OutputIt write_range_entry(OutputIt out, const Arg v) {
*out++ = '\'';
*out++ = v;
*out++ = '\'';
return out;
}
template <
typename Char, typename OutputIt, typename Arg,
FMT_ENABLE_IF(!is_std_string_like<typename std::decay<Arg>::type>::value &&
!std::is_same<Arg, Char>::value)>
OutputIt write_range_entry(OutputIt out, const Arg& v) {
return write<Char>(out, v);
}
} // namespace detail
template <typename T> struct is_tuple_like {
static FMT_CONSTEXPR_DECL const bool value =
detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
};
template <typename TupleT, typename Char>
struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> {
private:
// C++11 generic lambda for format()
template <typename FormatContext> struct format_each {
template <typename T> void operator()(const T& v) {
if (i > 0) out = detail::write_delimiter(out);
out = detail::write_range_entry<Char>(out, v);
++i;
}
formatting_tuple<Char>& formatting;
size_t& i;
typename std::add_lvalue_reference<
decltype(std::declval<FormatContext>().out())>::type out;
};
public:
formatting_tuple<Char> formatting;
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return formatting.parse(ctx);
}
template <typename FormatContext = format_context>
auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
auto out = ctx.out();
size_t i = 0;
detail::copy(formatting.prefix, out);
detail::for_each(values, format_each<FormatContext>{formatting, i, out});
detail::copy(formatting.postfix, out);
return ctx.out();
}
};
template <typename T, typename Char> struct is_range {
static FMT_CONSTEXPR_DECL const bool value =
detail::is_range_<T>::value && !detail::is_std_string_like<T>::value &&
!std::is_convertible<T, std::basic_string<Char>>::value &&
!std::is_constructible<detail::std_string_view<Char>, T>::value;
};
template <typename T, typename Char>
struct formatter<
T, Char,
enable_if_t<
fmt::is_range<T, Char>::value
// Workaround a bug in MSVC 2017 and earlier.
#if !FMT_MSC_VER || FMT_MSC_VER >= 1927
&& (has_formatter<detail::value_type<T>, format_context>::value ||
detail::has_fallback_formatter<detail::value_type<T>, Char>::value)
#endif
>> {
formatting_range<Char> formatting;
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return formatting.parse(ctx);
}
template <typename FormatContext>
typename FormatContext::iterator format(const T& values, FormatContext& ctx) {
auto out = detail::copy(formatting.prefix, ctx.out());
size_t i = 0;
auto view = detail::range_to_view<T>::view(values);
auto it = view.begin();
auto end = view.end();
for (; it != end; ++it) {
if (i > 0) out = detail::write_delimiter(out);
out = detail::write_range_entry<Char>(out, *it);
++i;
}
return detail::copy(formatting.postfix, out);
}
};
template <typename Char, typename... T> struct tuple_join_view : detail::view {
const std::tuple<T...>& tuple;
basic_string_view<Char> sep;
tuple_join_view(const std::tuple<T...>& t, basic_string_view<Char> s)
: tuple(t), sep{s} {}
};
template <typename Char, typename... T>
using tuple_arg_join = tuple_join_view<Char, T...>;
template <typename Char, typename... T>
struct formatter<tuple_join_view<Char, T...>, Char> {
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const tuple_join_view<Char, T...>& value, FormatContext& ctx) ->
typename FormatContext::iterator {
return format(value, ctx, detail::make_index_sequence<sizeof...(T)>{});
}
private:
template <typename FormatContext, size_t... N>
auto format(const tuple_join_view<Char, T...>& value, FormatContext& ctx,
detail::index_sequence<N...>) ->
typename FormatContext::iterator {
using std::get;
return format_args(value, ctx, get<N>(value.tuple)...);
}
template <typename FormatContext>
auto format_args(const tuple_join_view<Char, T...>&, FormatContext& ctx) ->
typename FormatContext::iterator {
// NOTE: for compilers that support C++17, this empty function instantiation
// can be replaced with a constexpr branch in the variadic overload.
return ctx.out();
}
template <typename FormatContext, typename Arg, typename... Args>
auto format_args(const tuple_join_view<Char, T...>& value, FormatContext& ctx,
const Arg& arg, const Args&... args) ->
typename FormatContext::iterator {
using base = formatter<typename std::decay<Arg>::type, Char>;
auto out = base().format(arg, ctx);
if (sizeof...(Args) > 0) {
out = std::copy(value.sep.begin(), value.sep.end(), out);
ctx.advance_to(out);
return format_args(value, ctx, args...);
}
return out;
}
};
FMT_MODULE_EXPORT_BEGIN
/**
\rst
Returns an object that formats `tuple` with elements separated by `sep`.
**Example**::
std::tuple<int, char> t = {1, 'a'};
fmt::print("{}", fmt::join(t, ", "));
// Output: "1, a"
\endrst
*/
template <typename... T>
FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple, string_view sep)
-> tuple_join_view<char, T...> {
return {tuple, sep};
}
template <typename... T>
FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple,
basic_string_view<wchar_t> sep)
-> tuple_join_view<wchar_t, T...> {
return {tuple, sep};
}
/**
\rst
Returns an object that formats `initializer_list` with elements separated by
`sep`.
**Example**::
fmt::print("{}", fmt::join({1, 2, 3}, ", "));
// Output: "1, 2, 3"
\endrst
*/
template <typename T>
auto join(std::initializer_list<T> list, string_view sep)
-> join_view<const T*, const T*> {
return join(std::begin(list), std::end(list), sep);
}
FMT_MODULE_EXPORT_END
FMT_END_NAMESPACE
#endif // FMT_RANGES_H_

View File

@ -1,20 +0,0 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's chrono support
//
#if !defined(SPDLOG_FMT_EXTERNAL)
#ifdef SPDLOG_HEADER_ONLY
#ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY
#endif
#endif
#include <fmt/bundled/chrono.h>
#else
#include <fmt/chrono.h>
#endif

View File

@ -1,28 +0,0 @@
//
// Copyright(c) 2016-2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// Include a bundled header-only copy of fmtlib or an external one.
// By default spdlog include its own copy.
//
#if !defined(SPDLOG_FMT_EXTERNAL)
#if !defined(SPDLOG_COMPILED_LIB) && !defined(FMT_HEADER_ONLY)
#define FMT_HEADER_ONLY
#endif
#ifndef FMT_USE_WINDOWS_H
#define FMT_USE_WINDOWS_H 0
#endif
// enable the 'n' flag in for backward compatibility with fmt 6.x
#define FMT_DEPRECATED_N_SPECIFIER
#include <thirdparty/spdlog/include/fmt/bundled/core.h>
#include <thirdparty/spdlog/include/fmt/bundled/format.h>
#else // SPDLOG_FMT_EXTERNAL is defined - use external fmtlib
#include <thirdparty/spdlog/include/fmt/core.h>
#include <thirdparty/spdlog/include/fmt/format.h>
#endif

View File

@ -1,20 +0,0 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's ostream support
//
#if !defined(SPDLOG_FMT_EXTERNAL)
#ifdef SPDLOG_HEADER_ONLY
#ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY
#endif
#endif
#include <fmt/bundled/ostream.h>
#else
#include <fmt/ostream.h>
#endif

View File

@ -1,20 +0,0 @@
//
// Copyright(c) 2016 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
//
// include bundled or external copy of fmtlib's ostream support
//
#if !defined(SPDLOG_FMT_EXTERNAL)
#ifdef SPDLOG_HEADER_ONLY
#ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY
#endif
#endif
#include <fmt/bundled/xchar.h>
#else
#include <fmt/xchar.h>
#endif

View File

@ -1,96 +0,0 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
//
// Custom sink for mongodb
// Building and using requires mongocxx library.
// For building mongocxx library check the url below
// http://mongocxx.org/mongocxx-v3/installation/
//
#include "thirdparty/spdlog/include/spdlog/common.h"
#include "thirdparty/spdlog/include/spdlog/details/log_msg.h"
#include "thirdparty/spdlog/include/spdlog/sinks/base_sink.h"
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/view_or_value.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
namespace spdlog {
namespace sinks {
template <typename Mutex> class mongo_sink : public base_sink<Mutex> {
public:
mongo_sink(const std::string &db_name, const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017") {
try {
client_ = std::make_unique<mongocxx::client>(mongocxx::uri{uri});
db_name_ = db_name;
coll_name_ = collection_name;
} catch (const std::exception) {
throw spdlog_ex("Error opening database");
}
}
~mongo_sink() { flush_(); }
protected:
void sink_it_(const details::log_msg &msg) override {
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
if (client_ != nullptr) {
auto doc = document{}
<< "timestamp" << bsoncxx::types::b_date(msg.time) << "level"
<< level::to_string_view(msg.level).data() << "message"
<< std::string(msg.payload.begin(), msg.payload.end())
<< "logger_name"
<< std::string(msg.logger_name.begin(), msg.logger_name.end())
<< "thread_id" << static_cast<int>(msg.thread_id) << finalize;
client_->database(db_name_).collection(coll_name_).insert_one(doc.view());
}
}
void flush_() override {}
private:
static mongocxx::instance instance_;
std::string db_name_;
std::string coll_name_;
std::unique_ptr<mongocxx::client> client_ = nullptr;
};
mongocxx::instance mongo_sink<std::mutex>::instance_{};
#include "spdlog/details/null_mutex.h"
#include <mutex>
using mongo_sink_mt = mongo_sink<std::mutex>;
using mongo_sink_st = mongo_sink<spdlog::details::null_mutex>;
} // namespace sinks
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
mongo_logger_mt(const std::string &logger_name, const std::string &db_name,
const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017") {
return Factory::template create<sinks::mongo_sink_mt>(logger_name, db_name,
collection_name, uri);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
mongo_logger_st(const std::string &logger_name, const std::string &db_name,
const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017") {
return Factory::template create<sinks::mongo_sink_st>(logger_name, db_name,
collection_name, uri);
}
} // namespace spdlog

View File

@ -1,187 +0,0 @@
// Copyright(c) 2015-present, Gabi Melman, mguludag and spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
//
// Custom sink for QPlainTextEdit or QTextEdit and its children(QTextBrowser...
// etc) Building and using requires Qt library.
//
#include "thirdparty/spdlog/include/spdlog/common.h"
#include "thirdparty/spdlog/include/spdlog/details/log_msg.h"
#include "thirdparty/spdlog/include/spdlog/details/synchronous_factory.h"
#include "thirdparty/spdlog/include/spdlog/sinks/base_sink.h"
#include <QObject>
#include <QPlainTextEdit>
#include <QTextEdit>
namespace _spdlog_p {
namespace _sinks_p {
//
// Private class for QTextEdit and its derivatives
//
class qtextedit_sink_p : public QObject {
Q_OBJECT
public:
qtextedit_sink_p(QTextEdit *textedit = nullptr) {
if (textedit != nullptr) {
textedit_ = textedit;
connect(this, &qtextedit_sink_p::append_text, textedit_,
&QTextEdit::append);
}
}
~qtextedit_sink_p() {}
void append(const spdlog::string_view_t &str) {
emit append_text(
QString::fromUtf8(str.data(), static_cast<int>(str.size() - 2)));
}
signals:
void append_text(const QString &);
private:
QTextEdit *textedit_ = nullptr;
};
//
// Private class for QPlainTextEdit
//
class qplaintextedit_sink_p : public QObject {
Q_OBJECT
public:
qplaintextedit_sink_p(QPlainTextEdit *textedit = nullptr) {
if (textedit != nullptr) {
textedit_ = textedit;
connect(this, &qplaintextedit_sink_p::append_text, textedit_,
&QPlainTextEdit::appendPlainText);
}
}
~qplaintextedit_sink_p() {}
void append(const spdlog::string_view_t &str) {
emit append_text(
QString::fromUtf8(str.data(), static_cast<int>(str.size() - 2)));
}
signals:
void append_text(const QString &);
private:
QPlainTextEdit *textedit_ = nullptr;
};
} // namespace _sinks_p
} // namespace _spdlog_p
//
// qtextedit_sink class
//
namespace spdlog {
namespace sinks {
template <typename Mutex> class qtextedit_sink : public base_sink<Mutex> {
public:
qtextedit_sink(QTextEdit *textedit = nullptr) {
if (textedit != nullptr) {
textedit_p =
std::make_shared<_spdlog_p::_sinks_p::qtextedit_sink_p>(textedit);
} else {
throw spdlog_ex("Error opening QTextEdit");
}
}
~qtextedit_sink() { flush_(); }
protected:
void sink_it_(const details::log_msg &msg) override {
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
string_view_t str_v = string_view_t(formatted.data(), formatted.size());
textedit_p->append(str_v);
}
void flush_() override {}
private:
std::shared_ptr<_spdlog_p::_sinks_p::qtextedit_sink_p> textedit_p = nullptr;
};
//
// qplaintextedit_sink class
//
template <typename Mutex> class qplaintextedit_sink : public base_sink<Mutex> {
public:
qplaintextedit_sink(QPlainTextEdit *textedit = nullptr) {
if (textedit != nullptr) {
textedit_p = std::make_shared<_spdlog_p::_sinks_p::qplaintextedit_sink_p>(
textedit);
} else {
throw spdlog_ex("Error opening QPlainTextEdit");
}
}
~qplaintextedit_sink() { flush_(); }
protected:
void sink_it_(const details::log_msg &msg) override {
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
string_view_t str_v = string_view_t(formatted.data(), formatted.size());
textedit_p->append(str_v);
}
void flush_() override {}
private:
std::shared_ptr<_spdlog_p::_sinks_p::qplaintextedit_sink_p> textedit_p =
nullptr;
};
#include "spdlog/details/null_mutex.h"
#include <mutex>
using qtextedit_sink_mt = qtextedit_sink<std::mutex>;
using qtextedit_sink_st = qtextedit_sink<spdlog::details::null_mutex>;
using qplaintextedit_sink_mt = qplaintextedit_sink<std::mutex>;
using qplaintextedit_sink_st = qplaintextedit_sink<spdlog::details::null_mutex>;
} // namespace sinks
//
// Factory functions
//
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qtextedit_logger_mt(const std::string &logger_name,
QTextEdit *qtextedit = nullptr) {
return Factory::template create<sinks::qtextedit_sink_mt>(logger_name,
qtextedit);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qtextedit_logger_st(const std::string &logger_name,
QTextEdit *qtextedit = nullptr) {
return Factory::template create<sinks::qtextedit_sink_st>(logger_name,
qtextedit);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qplaintextedit_logger_mt(const std::string &logger_name,
QPlainTextEdit *qplaintextedit = nullptr) {
return Factory::template create<sinks::qplaintextedit_sink_mt>(
logger_name, qplaintextedit);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qplaintextedit_logger_st(const std::string &logger_name,
QPlainTextEdit *qplaintextedit = nullptr) {
return Factory::template create<sinks::qplaintextedit_sink_st>(
logger_name, qplaintextedit);
}
} // namespace spdlog

View File

@ -4,12 +4,12 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <logger.h>
# include <spdlog/logger.h>
#endif
#include <thirdparty/spdlog/include/sinks/sink.h>
#include <thirdparty/spdlog/include/details/backtracer.h>
#include <thirdparty/spdlog/include/pattern_formatter.h>
#include <spdlog/sinks/sink.h>
#include <spdlog/details/backtracer.h>
#include <spdlog/pattern_formatter.h>
#include <cstdio>
@ -185,7 +185,7 @@ SPDLOG_INLINE void logger::sink_it_(const details::log_msg &msg)
{
sink->log(msg);
}
SPDLOG_LOGGER_CATCH()
SPDLOG_LOGGER_CATCH(msg.source)
}
}
@ -203,7 +203,7 @@ SPDLOG_INLINE void logger::flush_()
{
sink->flush();
}
SPDLOG_LOGGER_CATCH()
SPDLOG_LOGGER_CATCH(source_loc())
}
}

View File

@ -14,22 +14,31 @@
// The use of private formatter per sink provides the opportunity to cache some
// formatted data, and support for different format per sink.
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <thirdparty/spdlog/include/details/backtracer.h>
#include <spdlog/common.h>
#include <spdlog/details/log_msg.h>
#include <spdlog/details/backtracer.h>
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
# include <details/os.h>
# ifndef _WIN32
# error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
# endif
# include <spdlog/details/os.h>
#endif
#include <vector>
#include <iterator>
#ifndef SPDLOG_NO_EXCEPTIONS
# define SPDLOG_LOGGER_CATCH() \
# define SPDLOG_LOGGER_CATCH(location) \
catch (const std::exception &ex) \
{ \
err_handler_(ex.what()); \
if (location.filename) \
{ \
err_handler_(fmt_lib::format(SPDLOG_FMT_STRING("{} [{}({})]"), ex.what(), location.filename, location.line)); \
} \
else \
{ \
err_handler_(ex.what()); \
} \
} \
catch (...) \
{ \
@ -37,7 +46,7 @@
throw; \
}
#else
# define SPDLOG_LOGGER_CATCH()
# define SPDLOG_LOGGER_CATCH(location)
#endif
namespace spdlog {
@ -73,77 +82,31 @@ public:
logger(const logger &other);
logger(logger &&other) SPDLOG_NOEXCEPT;
logger &operator=(logger other) SPDLOG_NOEXCEPT;
void swap(spdlog::logger &other) SPDLOG_NOEXCEPT;
// FormatString is a type derived from fmt::compile_string
template<typename FormatString, typename std::enable_if<fmt::is_compile_string<FormatString>::value, int>::type = 0, typename... Args>
void log(source_loc loc, level::level_enum lvl, const FormatString &fmt, Args &&...args)
{
log_(loc, lvl, fmt, std::forward<Args>(args)...);
}
// FormatString is NOT a type derived from fmt::compile_string but is a string_view_t or can be implicitly converted to one
template<typename... Args>
void log(source_loc loc, level::level_enum lvl, string_view_t fmt, Args &&...args)
void log(source_loc loc, level::level_enum lvl, format_string_t<Args...> fmt, Args &&... args)
{
log_(loc, lvl, fmt, std::forward<Args>(args)...);
}
template<typename FormatString, typename... Args>
void log(level::level_enum lvl, const FormatString &fmt, Args &&...args)
template<typename... Args>
void log(level::level_enum lvl, format_string_t<Args...> fmt, Args &&... args)
{
log(source_loc{}, lvl, fmt, std::forward<Args>(args)...);
}
template<typename FormatString, typename... Args>
void trace(const FormatString &fmt, Args &&...args)
{
log(level::trace, fmt, std::forward<Args>(args)...);
}
template<typename FormatString, typename... Args>
void debug(const FormatString &fmt, Args &&...args)
{
log(level::debug, fmt, std::forward<Args>(args)...);
}
template<typename FormatString, typename... Args>
void info(const FormatString &fmt, Args &&...args)
{
log(level::info, fmt, std::forward<Args>(args)...);
}
template<typename FormatString, typename... Args>
void warn(const FormatString &fmt, Args &&...args)
{
log(level::warn, fmt, std::forward<Args>(args)...);
}
template<typename FormatString, typename... Args>
void error(const FormatString &fmt, Args &&...args)
{
log(level::err, fmt, std::forward<Args>(args)...);
}
template<typename FormatString, typename... Args>
void critical(const FormatString &fmt, Args &&...args)
{
log(level::critical, fmt, std::forward<Args>(args)...);
}
template<typename T>
void log(level::level_enum lvl, const T &msg)
{
log(source_loc{}, lvl, msg);
}
// T can be statically converted to string_view and isn't a fmt::compile_string
template<class T, typename std::enable_if<
std::is_convertible<const T &, spdlog::string_view_t>::value && !fmt::is_compile_string<T>::value, int>::type = 0>
// T cannot be statically converted to format string (including string_view/wstring_view)
template<class T, typename std::enable_if<!is_convertible_to_any_format_string<const T &>::value, int>::type = 0>
void log(source_loc loc, level::level_enum lvl, const T &msg)
{
log(loc, lvl, string_view_t{msg});
log(loc, lvl, "{}", msg);
}
void log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, string_view_t msg)
@ -177,15 +140,127 @@ public:
log(source_loc{}, lvl, msg);
}
// T cannot be statically converted to string_view or wstring_view
template<class T, typename std::enable_if<!std::is_convertible<const T &, spdlog::string_view_t>::value &&
!is_convertible_to_wstring_view<const T &>::value,
int>::type = 0>
void log(source_loc loc, level::level_enum lvl, const T &msg)
template<typename... Args>
void trace(format_string_t<Args...> fmt, Args &&... args)
{
log(loc, lvl, "{}", msg);
log(level::trace, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void debug(format_string_t<Args...> fmt, Args &&... args)
{
log(level::debug, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void info(format_string_t<Args...> fmt, Args &&... args)
{
log(level::info, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void warn(format_string_t<Args...> fmt, Args &&... args)
{
log(level::warn, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void error(format_string_t<Args...> fmt, Args &&... args)
{
log(level::err, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void critical(format_string_t<Args...> fmt, Args &&... args)
{
log(level::critical, fmt, std::forward<Args>(args)...);
}
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
template<typename... Args>
void log(source_loc loc, level::level_enum lvl, wformat_string_t<Args...> fmt, Args &&... args)
{
log_(loc, lvl, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void log(level::level_enum lvl, wformat_string_t<Args...> fmt, Args &&... args)
{
log(source_loc{}, lvl, fmt, std::forward<Args>(args)...);
}
void log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, wstring_view_t msg)
{
bool log_enabled = should_log(lvl);
bool traceback_enabled = tracer_.enabled();
if (!log_enabled && !traceback_enabled)
{
return;
}
memory_buf_t buf;
details::os::wstr_to_utf8buf(wstring_view_t(msg.data(), msg.size()), buf);
details::log_msg log_msg(log_time, loc, name_, lvl, string_view_t(buf.data(), buf.size()));
log_it_(log_msg, log_enabled, traceback_enabled);
}
void log(source_loc loc, level::level_enum lvl, wstring_view_t msg)
{
bool log_enabled = should_log(lvl);
bool traceback_enabled = tracer_.enabled();
if (!log_enabled && !traceback_enabled)
{
return;
}
memory_buf_t buf;
details::os::wstr_to_utf8buf(wstring_view_t(msg.data(), msg.size()), buf);
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
log_it_(log_msg, log_enabled, traceback_enabled);
}
void log(level::level_enum lvl, wstring_view_t msg)
{
log(source_loc{}, lvl, msg);
}
template<typename... Args>
void trace(wformat_string_t<Args...> fmt, Args &&... args)
{
log(level::trace, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void debug(wformat_string_t<Args...> fmt, Args &&... args)
{
log(level::debug, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void info(wformat_string_t<Args...> fmt, Args &&... args)
{
log(level::info, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void warn(wformat_string_t<Args...> fmt, Args &&... args)
{
log(level::warn, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void error(wformat_string_t<Args...> fmt, Args &&... args)
{
log(level::err, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void critical(wformat_string_t<Args...> fmt, Args &&... args)
{
log(level::critical, fmt, std::forward<Args>(args)...);
}
#endif
template<typename T>
void trace(const T &msg)
{
@ -222,58 +297,6 @@ public:
log(level::critical, msg);
}
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
# ifndef _WIN32
# error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
# else
template<typename... Args>
void log(source_loc loc, level::level_enum lvl, wstring_view_t fmt, Args &&...args)
{
bool log_enabled = should_log(lvl);
bool traceback_enabled = tracer_.enabled();
if (!log_enabled && !traceback_enabled)
{
return;
}
SPDLOG_TRY
{
// format to wmemory_buffer and convert to utf8
fmt::wmemory_buffer wbuf;
fmt::format_to(std::back_inserter(wbuf), fmt, std::forward<Args>(args)...);
memory_buf_t buf;
details::os::wstr_to_utf8buf(wstring_view_t(wbuf.data(), wbuf.size()), buf);
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
log_it_(log_msg, log_enabled, traceback_enabled);
}
SPDLOG_LOGGER_CATCH()
}
// T can be statically converted to wstring_view
template<class T, typename std::enable_if<is_convertible_to_wstring_view<const T &>::value, int>::type = 0>
void log(source_loc loc, level::level_enum lvl, const T &msg)
{
bool log_enabled = should_log(lvl);
bool traceback_enabled = tracer_.enabled();
if (!log_enabled && !traceback_enabled)
{
return;
}
SPDLOG_TRY
{
memory_buf_t buf;
details::os::wstr_to_utf8buf(msg, buf);
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
log_it_(log_msg, log_enabled, traceback_enabled);
}
SPDLOG_LOGGER_CATCH()
}
# endif // _WIN32
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
// return true logging is enabled for the given level.
bool should_log(level::level_enum msg_level) const
{
@ -296,6 +319,10 @@ public:
// each sink will get a separate instance of the formatter object.
void set_formatter(std::unique_ptr<formatter> f);
// set formatting for the sinks in this logger.
// equivalent to
// set_formatter(make_unique<pattern_formatter>(pattern, time_type))
// Note: each sink will get a new instance of a formatter object, replacing the old one.
void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);
// backtrace support.
@ -329,8 +356,8 @@ protected:
details::backtracer tracer_;
// common implementation for after templated public api has been resolved
template<typename FormatString, typename... Args>
void log_(source_loc loc, level::level_enum lvl, const FormatString &fmt, Args &&...args)
template<typename... Args>
void log_(source_loc loc, level::level_enum lvl, string_view_t fmt, Args &&... args)
{
bool log_enabled = should_log(lvl);
bool traceback_enabled = tracer_.enabled();
@ -341,13 +368,69 @@ protected:
SPDLOG_TRY
{
memory_buf_t buf;
fmt::format_to(std::back_inserter(buf), fmt::runtime(fmt), std::forward<Args>(args)...);
#ifdef SPDLOG_USE_STD_FORMAT
fmt_lib::vformat_to(std::back_inserter(buf), fmt, fmt_lib::make_format_args(std::forward<Args>(args)...));
#else
fmt::vformat_to(fmt::appender(buf), fmt, fmt::make_format_args(std::forward<Args>(args)...));
#endif
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
log_it_(log_msg, log_enabled, traceback_enabled);
}
SPDLOG_LOGGER_CATCH()
SPDLOG_LOGGER_CATCH(loc)
}
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
template<typename... Args>
void log_(source_loc loc, level::level_enum lvl, wstring_view_t fmt, Args &&... args)
{
bool log_enabled = should_log(lvl);
bool traceback_enabled = tracer_.enabled();
if (!log_enabled && !traceback_enabled)
{
return;
}
SPDLOG_TRY
{
// format to wmemory_buffer and convert to utf8
wmemory_buf_t wbuf;
# ifdef SPDLOG_USE_STD_FORMAT
fmt_lib::vformat_to(
std::back_inserter(wbuf), fmt, fmt_lib::make_format_args<fmt_lib::wformat_context>(std::forward<Args>(args)...));
# else
fmt::vformat_to(std::back_inserter(wbuf), fmt, fmt::make_format_args<fmt::wformat_context>(std::forward<Args>(args)...));
# endif
memory_buf_t buf;
details::os::wstr_to_utf8buf(wstring_view_t(wbuf.data(), wbuf.size()), buf);
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
log_it_(log_msg, log_enabled, traceback_enabled);
}
SPDLOG_LOGGER_CATCH(loc)
}
// T can be statically converted to wstring_view, and no formatting needed.
template<class T, typename std::enable_if<std::is_convertible<const T &, spdlog::wstring_view_t>::value, int>::type = 0>
void log_(source_loc loc, level::level_enum lvl, const T &msg)
{
bool log_enabled = should_log(lvl);
bool traceback_enabled = tracer_.enabled();
if (!log_enabled && !traceback_enabled)
{
return;
}
SPDLOG_TRY
{
memory_buf_t buf;
details::os::wstr_to_utf8buf(msg, buf);
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
log_it_(log_msg, log_enabled, traceback_enabled);
}
SPDLOG_LOGGER_CATCH(loc)
}
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
// log the given message (if the given log level is high enough),
// and save backtrace (if backtrace is enabled).
void log_it_(const details::log_msg &log_msg, bool log_enabled, bool traceback_enabled);

View File

@ -4,14 +4,14 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <pattern_formatter.h>
# include <spdlog/pattern_formatter.h>
#endif
#include <thirdparty/spdlog/include/details/fmt_helper.h>
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <thirdparty/spdlog/include/fmt/fmt.h>
#include <thirdparty/spdlog/include/formatter.h>
#include <spdlog/details/fmt_helper.h>
#include <spdlog/details/log_msg.h>
#include <spdlog/details/os.h>
#include <spdlog/fmt/fmt.h>
#include <spdlog/formatter.h>
#include <algorithm>
#include <array>
@ -766,6 +766,7 @@ public:
{
if (msg.source.empty())
{
ScopedPadder p(0, padinfo_, dest);
return;
}
@ -800,6 +801,7 @@ public:
{
if (msg.source.empty())
{
ScopedPadder p(0, padinfo_, dest);
return;
}
size_t text_size = padinfo_.enabled() ? std::char_traits<char>::length(msg.source.filename) : 0;
@ -817,9 +819,9 @@ public:
{}
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4127) // consider using 'if constexpr' instead
#endif // _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4127) // consider using 'if constexpr' instead
#endif // _MSC_VER
static const char *basename(const char *filename)
{
// if the size is 2 (1 character + null terminator) we can use the more efficient strrchr
@ -831,21 +833,22 @@ public:
}
else
{
const std::reverse_iterator<const char*> begin(filename + std::strlen(filename));
const std::reverse_iterator<const char*> end(filename);
const std::reverse_iterator<const char *> begin(filename + std::strlen(filename));
const std::reverse_iterator<const char *> end(filename);
const auto it = std::find_first_of(begin, end, std::begin(os::folder_seps), std::end(os::folder_seps) - 1);
return it != end ? it.base() : filename;
}
}
#ifdef _MSC_VER
#pragma warning(pop)
# pragma warning(pop)
#endif // _MSC_VER
void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
{
if (msg.source.empty())
{
ScopedPadder p(0, padinfo_, dest);
return;
}
auto filename = basename(msg.source.filename);
@ -867,6 +870,7 @@ public:
{
if (msg.source.empty())
{
ScopedPadder p(0, padinfo_, dest);
return;
}
@ -889,6 +893,7 @@ public:
{
if (msg.source.empty())
{
ScopedPadder p(0, padinfo_, dest);
return;
}
size_t text_size = padinfo_.enabled() ? std::char_traits<char>::length(msg.source.funcname) : 0;
@ -1019,6 +1024,7 @@ SPDLOG_INLINE pattern_formatter::pattern_formatter(
: pattern_(std::move(pattern))
, eol_(std::move(eol))
, pattern_time_type_(time_type)
, need_localtime_(false)
, last_log_secs_(0)
, custom_handlers_(std::move(custom_user_flags))
{
@ -1031,6 +1037,7 @@ SPDLOG_INLINE pattern_formatter::pattern_formatter(pattern_time_type time_type,
: pattern_("%+")
, eol_(std::move(eol))
, pattern_time_type_(time_type)
, need_localtime_(true)
, last_log_secs_(0)
{
std::memset(&cached_tm_, 0, sizeof(cached_tm_));
@ -1044,16 +1051,25 @@ SPDLOG_INLINE std::unique_ptr<formatter> pattern_formatter::clone() const
{
cloned_custom_formatters[it.first] = it.second->clone();
}
return details::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_, std::move(cloned_custom_formatters));
auto cloned = details::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_, std::move(cloned_custom_formatters));
cloned->need_localtime(need_localtime_);
#if defined(__GNUC__) && __GNUC__ < 5
return std::move(cloned);
#else
return cloned;
#endif
}
SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, memory_buf_t &dest)
{
auto secs = std::chrono::duration_cast<std::chrono::seconds>(msg.time.time_since_epoch());
if (secs != last_log_secs_)
if (need_localtime_)
{
cached_tm_ = get_time_(msg);
last_log_secs_ = secs;
const auto secs = std::chrono::duration_cast<std::chrono::seconds>(msg.time.time_since_epoch());
if (secs != last_log_secs_)
{
cached_tm_ = get_time_(msg);
last_log_secs_ = secs;
}
}
for (auto &f : formatters_)
@ -1067,9 +1083,15 @@ SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, memory
SPDLOG_INLINE void pattern_formatter::set_pattern(std::string pattern)
{
pattern_ = std::move(pattern);
need_localtime_ = false;
compile_pattern_(pattern_);
}
SPDLOG_INLINE void pattern_formatter::need_localtime(bool need)
{
need_localtime_ = need;
}
SPDLOG_INLINE std::tm pattern_formatter::get_time_(const details::log_msg &msg)
{
if (pattern_time_type_ == pattern_time_type::local)
@ -1097,6 +1119,7 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i
{
case ('+'): // default formatter
formatters_.push_back(details::make_unique<details::full_formatter>(padding));
need_localtime_ = true;
break;
case 'n': // logger name
@ -1121,60 +1144,74 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i
case ('a'): // weekday
formatters_.push_back(details::make_unique<details::a_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('A'): // short weekday
formatters_.push_back(details::make_unique<details::A_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('b'):
case ('h'): // month
formatters_.push_back(details::make_unique<details::b_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('B'): // short month
formatters_.push_back(details::make_unique<details::B_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('c'): // datetime
formatters_.push_back(details::make_unique<details::c_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('C'): // year 2 digits
formatters_.push_back(details::make_unique<details::C_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('Y'): // year 4 digits
formatters_.push_back(details::make_unique<details::Y_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('D'):
case ('x'): // datetime MM/DD/YY
formatters_.push_back(details::make_unique<details::D_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('m'): // month 1-12
formatters_.push_back(details::make_unique<details::m_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('d'): // day of month 1-31
formatters_.push_back(details::make_unique<details::d_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('H'): // hours 24
formatters_.push_back(details::make_unique<details::H_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('I'): // hours 12
formatters_.push_back(details::make_unique<details::I_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('M'): // minutes
formatters_.push_back(details::make_unique<details::M_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('S'): // seconds
formatters_.push_back(details::make_unique<details::S_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('e'): // milliseconds
@ -1195,23 +1232,28 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i
case ('p'): // am/pm
formatters_.push_back(details::make_unique<details::p_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('r'): // 12 hour clock 02:55:02 pm
formatters_.push_back(details::make_unique<details::r_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('R'): // 24-hour HH:MM time
formatters_.push_back(details::make_unique<details::R_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('T'):
case ('X'): // ISO 8601 time format (HH:MM:SS)
formatters_.push_back(details::make_unique<details::T_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('z'): // timezone
formatters_.push_back(details::make_unique<details::z_formatter<Padder>>(padding));
need_localtime_ = true;
break;
case ('P'): // pid
@ -1342,7 +1384,6 @@ SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::stri
{
truncate = false;
}
return details::padding_info{std::min<size_t>(width, max_width), side, truncate};
}

View File

@ -3,10 +3,10 @@
#pragma once
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <thirdparty/spdlog/include/formatter.h>
#include <spdlog/common.h>
#include <spdlog/details/log_msg.h>
#include <spdlog/details/os.h>
#include <spdlog/formatter.h>
#include <chrono>
#include <ctime>
@ -68,7 +68,7 @@ class SPDLOG_API custom_flag_formatter : public details::flag_formatter
public:
virtual std::unique_ptr<custom_flag_formatter> clone() const = 0;
void set_padding_info(details::padding_info padding)
void set_padding_info(const details::padding_info &padding)
{
flag_formatter::padinfo_ = padding;
}
@ -92,17 +92,19 @@ public:
void format(const details::log_msg &msg, memory_buf_t &dest) override;
template<typename T, typename... Args>
pattern_formatter &add_flag(char flag, Args&&...args)
pattern_formatter &add_flag(char flag, Args &&... args)
{
custom_handlers_[flag] = details::make_unique<T>(std::forward<Args>(args)...);
return *this;
}
void set_pattern(std::string pattern);
void need_localtime(bool need = true);
private:
std::string pattern_;
std::string eol_;
pattern_time_type pattern_time_type_;
bool need_localtime_;
std::tm cached_tm_;
std::chrono::seconds last_log_secs_;
std::vector<std::unique_ptr<details::flag_formatter>> formatters_;
@ -122,5 +124,5 @@ private:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "pattern_formatter-inl.h"
# include "pattern_formatter-inl.h"
#endif

View File

@ -5,29 +5,31 @@
#ifdef __ANDROID__
#include <thirdparty/spdlog/include/details/fmt_helper.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
# include <spdlog/details/fmt_helper.h>
# include <spdlog/details/null_mutex.h>
# include <spdlog/details/os.h>
# include <spdlog/sinks/base_sink.h>
# include <spdlog/details/synchronous_factory.h>
#include <android/log.h>
#include <chrono>
#include <mutex>
#include <string>
#include <thread>
# include <android/log.h>
# include <chrono>
# include <mutex>
# include <string>
# include <thread>
# include <type_traits>
#if !defined(SPDLOG_ANDROID_RETRIES)
#define SPDLOG_ANDROID_RETRIES 2
#endif
# if !defined(SPDLOG_ANDROID_RETRIES)
# define SPDLOG_ANDROID_RETRIES 2
# endif
namespace spdlog {
namespace sinks {
/*
* Android sink (logging using __android_log_write)
* Android sink
* (logging using __android_log_write or __android_log_buf_write depending on the specified BufferID)
*/
template<typename Mutex>
template<typename Mutex, int BufferID = log_id::LOG_ID_MAIN>
class android_sink final : public base_sink<Mutex>
{
public:
@ -53,24 +55,39 @@ protected:
const char *msg_output = formatted.data();
// See system/core/liblog/logger_write.c for explanation of return value
int ret = __android_log_write(priority, tag_.c_str(), msg_output);
int ret = android_log(priority, tag_.c_str(), msg_output);
int retry_count = 0;
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);
ret = android_log(priority, tag_.c_str(), msg_output);
retry_count++;
}
if (ret < 0)
{
throw_spdlog_ex("__android_log_write() failed", ret);
throw_spdlog_ex("logging to Android failed", ret);
}
}
void flush_() override {}
private:
// There might be liblog versions used, that do not support __android_log_buf_write. So we only compile and link against
// __android_log_buf_write, if user explicitely provides a non-default log buffer. Otherwise, when using the default log buffer, always
// log via __android_log_write.
template<int ID = BufferID>
typename std::enable_if<ID == static_cast<int>(log_id::LOG_ID_MAIN), int>::type android_log(int prio, const char *tag, const char *text)
{
return __android_log_write(prio, tag, text);
}
template<int ID = BufferID>
typename std::enable_if<ID != static_cast<int>(log_id::LOG_ID_MAIN), int>::type android_log(int prio, const char *tag, const char *text)
{
return __android_log_buf_write(ID, prio, tag, text);
}
static android_LogPriority convert_to_android_(spdlog::level::level_enum level)
{
switch (level)
@ -98,6 +115,12 @@ private:
using android_sink_mt = android_sink<std::mutex>;
using android_sink_st = android_sink<details::null_mutex>;
template<int BufferId = log_id::LOG_ID_MAIN>
using android_sink_buf_mt = android_sink<std::mutex, BufferId>;
template<int BufferId = log_id::LOG_ID_MAIN>
using android_sink_buf_st = android_sink<details::null_mutex, BufferId>;
} // namespace sinks
// Create and register android syslog logger

View File

@ -4,11 +4,11 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/sinks/ansicolor_sink.h>
# include <spdlog/sinks/ansicolor_sink.h>
#endif
#include <thirdparty/spdlog/include/pattern_formatter.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <spdlog/pattern_formatter.h>
#include <spdlog/details/os.h>
namespace spdlog {
namespace sinks {
@ -34,7 +34,7 @@ template<typename ConsoleMutex>
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color(level::level_enum color_level, string_view_t color)
{
std::lock_guard<mutex_t> lock(mutex_);
colors_[color_level] = to_string_(color);
colors_[static_cast<size_t>(color_level)] = to_string_(color);
}
template<typename ConsoleMutex>
@ -52,7 +52,7 @@ SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::log(const details::log_msg &msg
// before color range
print_range_(formatted, 0, msg.color_range_start);
// in color range
print_ccode_(colors_[msg.level]);
print_ccode_(colors_[static_cast<size_t>(msg.level)]);
print_range_(formatted, msg.color_range_start, msg.color_range_end);
print_ccode_(reset);
// after color range

View File

@ -3,10 +3,9 @@
#pragma once
#include <thirdparty/spdlog/include/details/console_globals.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/sinks/sink.h>
#include <spdlog/details/console_globals.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/sinks/sink.h>
#include <memory>
#include <mutex>
#include <string>
@ -115,5 +114,5 @@ using ansicolor_stderr_sink_st = ansicolor_stderr_sink<details::console_nullmute
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "ansicolor_sink-inl.h"
# include "ansicolor_sink-inl.h"
#endif

View File

@ -4,11 +4,11 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/sinks/base_sink.h>
# include <spdlog/sinks/base_sink.h>
#endif
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/pattern_formatter.h>
#include <spdlog/common.h>
#include <spdlog/pattern_formatter.h>
#include <memory>

View File

@ -9,14 +9,14 @@
// implementers..
//
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <thirdparty/spdlog/include/sinks/sink.h>
#include <spdlog/common.h>
#include <spdlog/details/log_msg.h>
#include <spdlog/sinks/sink.h>
namespace spdlog {
namespace sinks {
template<typename Mutex>
class base_sink : public sink
class SPDLOG_API base_sink : public sink
{
public:
base_sink();
@ -37,7 +37,7 @@ public:
protected:
// sink formatter
std::unique_ptr<spdlog::formatter> formatter_;
mutable Mutex mutex_;
Mutex mutex_;
virtual void sink_it_(const details::log_msg &msg) = 0;
virtual void flush_() = 0;
@ -48,5 +48,5 @@ protected:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "base_sink-inl.h"
# include "base_sink-inl.h"
#endif

View File

@ -4,17 +4,18 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/sinks/basic_file_sink.h>
# include <spdlog/sinks/basic_file_sink.h>
#endif
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <spdlog/common.h>
#include <spdlog/details/os.h>
namespace spdlog {
namespace sinks {
template<typename Mutex>
SPDLOG_INLINE basic_file_sink<Mutex>::basic_file_sink(const filename_t &filename, bool truncate)
SPDLOG_INLINE basic_file_sink<Mutex>::basic_file_sink(const filename_t &filename, bool truncate, const file_event_handlers &event_handlers)
: file_helper_{event_handlers}
{
file_helper_.open(filename, truncate);
}

View File

@ -3,10 +3,10 @@
#pragma once
#include <thirdparty/spdlog/include/details/file_helper.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <spdlog/details/file_helper.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/details/synchronous_factory.h>
#include <mutex>
#include <string>
@ -20,7 +20,7 @@ template<typename Mutex>
class basic_file_sink final : public base_sink<Mutex>
{
public:
explicit basic_file_sink(const filename_t &filename, bool truncate = false);
explicit basic_file_sink(const filename_t &filename, bool truncate = false, const file_event_handlers &event_handlers = {});
const filename_t &filename() const;
protected:
@ -40,20 +40,21 @@ using basic_file_sink_st = basic_file_sink<details::null_mutex>;
// factory functions
//
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false)
inline std::shared_ptr<logger> basic_logger_mt(
const std::string &logger_name, const filename_t &filename, bool truncate = false, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::basic_file_sink_mt>(logger_name, filename, truncate);
return Factory::template create<sinks::basic_file_sink_mt>(logger_name, filename, truncate, event_handlers);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false)
inline std::shared_ptr<logger> basic_logger_st(
const std::string &logger_name, const filename_t &filename, bool truncate = false, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::basic_file_sink_st>(logger_name, filename, truncate);
return Factory::template create<sinks::basic_file_sink_st>(logger_name, filename, truncate, event_handlers);
}
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "basic_file_sink-inl.h"
# include "basic_file_sink-inl.h"
#endif

View File

@ -3,15 +3,15 @@
#pragma once
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/file_helper.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/fmt/fmt.h>
#include <thirdparty/spdlog/include/fmt/chrono.h>
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <thirdparty/spdlog/include/details/circular_q.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <spdlog/common.h>
#include <spdlog/details/file_helper.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/fmt/fmt.h>
#include <spdlog/fmt/chrono.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/details/os.h>
#include <spdlog/details/circular_q.h>
#include <spdlog/details/synchronous_factory.h>
#include <chrono>
#include <cstdio>
@ -32,8 +32,8 @@ struct daily_filename_calculator
{
filename_t basename, ext;
std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
return fmt::format(
SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, ext);
return fmt_lib::format(SPDLOG_FMT_STRING(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}")), basename, now_tm.tm_year + 1900,
now_tm.tm_mon + 1, now_tm.tm_mday, ext);
}
};
@ -48,14 +48,65 @@ struct daily_filename_format_calculator
{
static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
{
// generate fmt datetime format string, e.g. {:%Y-%m-%d}.
filename_t fmt_filename = fmt::format(SPDLOG_FILENAME_T("{{:{}}}"), filename);
#if defined(_MSC_VER) && defined(SPDLOG_WCHAR_FILENAMES) // for some reason msvc doesnt allow fmt::runtime(..) with wchar here
return fmt::format(fmt_filename, now_tm);
#ifdef SPDLOG_USE_STD_FORMAT
// adapted from fmtlib: https://github.com/fmtlib/fmt/blob/8.0.1/include/fmt/chrono.h#L522-L546
filename_t tm_format;
tm_format.append(filename);
// By appending an extra space we can distinguish an empty result that
// indicates insufficient buffer size from a guaranteed non-empty result
// https://github.com/fmtlib/fmt/issues/2238
tm_format.push_back(' ');
const size_t MIN_SIZE = 10;
filename_t buf;
buf.resize(MIN_SIZE);
for (;;)
{
size_t count = strftime(buf.data(), buf.size(), tm_format.c_str(), &now_tm);
if (count != 0)
{
// Remove the extra space.
buf.resize(count - 1);
break;
}
buf.resize(buf.size() * 2);
}
return buf;
#else
return fmt::format(fmt::runtime(fmt_filename), now_tm);
// generate fmt datetime format string, e.g. {:%Y-%m-%d}.
filename_t fmt_filename = fmt::format(SPDLOG_FMT_STRING(SPDLOG_FILENAME_T("{{:{}}}")), filename);
// MSVC doesn't allow fmt::runtime(..) with wchar, with fmtlib versions < 9.1.x
# if defined(_MSC_VER) && defined(SPDLOG_WCHAR_FILENAMES) && FMT_VERSION < 90101
return fmt::format(fmt_filename, now_tm);
# else
return fmt::format(SPDLOG_FMT_RUNTIME(fmt_filename), now_tm);
# endif
#endif
}
private:
#if defined __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wformat-nonliteral"
#endif
static size_t strftime(char *str, size_t count, const char *format, const std::tm *time)
{
return std::strftime(str, count, format, time);
}
static size_t strftime(wchar_t *str, size_t count, const wchar_t *format, const std::tm *time)
{
return std::wcsftime(str, count, format, time);
}
#if defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
};
/*
@ -68,10 +119,12 @@ class daily_file_sink final : public base_sink<Mutex>
{
public:
// create daily file sink which rotates on given time
daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute, bool truncate = false, uint16_t max_files = 0)
daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute, bool truncate = false, uint16_t max_files = 0,
const file_event_handlers &event_handlers = {})
: base_filename_(std::move(base_filename))
, rotation_h_(rotation_hour)
, rotation_m_(rotation_minute)
, file_helper_{event_handlers}
, truncate_(truncate)
, max_files_(max_files)
, filenames_q_()
@ -213,30 +266,32 @@ using daily_file_format_sink_st = daily_file_sink<details::null_mutex, daily_fil
// factory functions
//
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_logger_mt(
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
inline std::shared_ptr<logger> daily_logger_mt(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0,
bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate, max_files);
return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate, max_files, event_handlers);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_logger_format_mt(
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
inline std::shared_ptr<logger> daily_logger_format_mt(const std::string &logger_name, const filename_t &filename, int hour = 0,
int minute = 0, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::daily_file_format_sink_mt>(logger_name, filename, hour, minute, truncate, max_files);
return Factory::template create<sinks::daily_file_format_sink_mt>(
logger_name, filename, hour, minute, truncate, max_files, event_handlers);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_logger_st(
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
inline std::shared_ptr<logger> daily_logger_st(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0,
bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate, max_files);
return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate, max_files, event_handlers);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_logger_format_st(
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
inline std::shared_ptr<logger> daily_logger_format_st(const std::string &logger_name, const filename_t &filename, int hour = 0,
int minute = 0, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::daily_file_format_sink_st>(logger_name, filename, hour, minute, truncate, max_files);
return Factory::template create<sinks::daily_file_format_sink_st>(
logger_name, filename, hour, minute, truncate, max_files, event_handlers);
}
} // namespace spdlog

View File

@ -3,10 +3,10 @@
#pragma once
#include "thirdparty/spdlog/include/base_sink.h"
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/pattern_formatter.h>
#include "base_sink.h"
#include <spdlog/details/log_msg.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/pattern_formatter.h>
#include <algorithm>
#include <memory>
@ -57,20 +57,20 @@ public:
protected:
void sink_it_(const details::log_msg &msg) override
{
for (auto &sink : sinks_)
for (auto &sub_sink : sinks_)
{
if (sink->should_log(msg.level))
if (sub_sink->should_log(msg.level))
{
sink->log(msg);
sub_sink->log(msg);
}
}
}
void flush_() override
{
for (auto &sink : sinks_)
for (auto &sub_sink : sinks_)
{
sink->flush();
sub_sink->flush();
}
}
@ -82,9 +82,9 @@ protected:
void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter) override
{
base_sink<Mutex>::formatter_ = std::move(sink_formatter);
for (auto &sink : sinks_)
for (auto &sub_sink : sinks_)
{
sink->set_formatter(base_sink<Mutex>::formatter_->clone());
sub_sink->set_formatter(base_sink<Mutex>::formatter_->clone());
}
}
std::vector<std::shared_ptr<sink>> sinks_;

View File

@ -3,9 +3,9 @@
#pragma once
#include "thirdparty/spdlog/include/dist_sink.h"
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/details/log_msg.h>
#include "dist_sink.h"
#include <spdlog/details/null_mutex.h>
#include <spdlog/details/log_msg.h>
#include <cstdio>
#include <mutex>
@ -17,7 +17,7 @@
//
// Example:
//
// #include <sinks/dup_filter_sink.h>
// #include <spdlog/sinks/dup_filter_sink.h>
//
// int main() {
// auto dup_filter = std::make_shared<dup_filter_sink_st>(std::chrono::seconds(5));
@ -62,10 +62,10 @@ protected:
// log the "skipped.." message
if (skip_counter_ > 0)
{
{
char buf[64];
auto msg_size = ::snprintf(buf, sizeof(buf), "Skipped %u duplicate messages..", static_cast<unsigned>(skip_counter_));
if (msg_size > 0 && msg_size < sizeof(buf))
if (msg_size > 0 && static_cast<size_t>(msg_size) < sizeof(buf))
{
details::log_msg skipped_msg{msg.logger_name, level::info, string_view_t{buf, static_cast<size_t>(msg_size)}};
dist_sink<Mutex>::sink_it_(skipped_msg);

View File

@ -3,14 +3,14 @@
#pragma once
#include <thirdparty/spdlog/include/common.h>
#include <thirdparty/spdlog/include/details/file_helper.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/fmt/fmt.h>
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <thirdparty/spdlog/include/details/os.h>
#include <thirdparty/spdlog/include/details/circular_q.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <spdlog/common.h>
#include <spdlog/details/file_helper.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/fmt/fmt.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/details/os.h>
#include <spdlog/details/circular_q.h>
#include <spdlog/details/synchronous_factory.h>
#include <chrono>
#include <cstdio>
@ -31,8 +31,8 @@ struct hourly_filename_calculator
{
filename_t basename, ext;
std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
return fmt::format(
SPDLOG_FILENAME_T("{}_{:04d}{:02d}{:02d}_{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, now_tm.tm_hour, ext);
return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1,
now_tm.tm_mday, now_tm.tm_hour, ext);
}
};
@ -46,8 +46,10 @@ class hourly_file_sink final : public base_sink<Mutex>
{
public:
// create hourly file sink which rotates on given time
hourly_file_sink(filename_t base_filename, bool truncate = false, uint16_t max_files = 0)
hourly_file_sink(
filename_t base_filename, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
: base_filename_(std::move(base_filename))
, file_helper_{event_handlers}
, truncate_(truncate)
, max_files_(max_files)
, filenames_q_()
@ -55,6 +57,7 @@ public:
auto now = log_clock::now();
auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
file_helper_.open(filename, truncate_);
remove_init_file_ = file_helper_.size() == 0;
rotation_tp_ = next_rotation_tp_();
if (max_files_ > 0)
@ -76,10 +79,16 @@ protected:
bool should_rotate = time >= rotation_tp_;
if (should_rotate)
{
if (remove_init_file_)
{
file_helper_.close();
details::os::remove(file_helper_.filename());
}
auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
file_helper_.open(filename, truncate_);
rotation_tp_ = next_rotation_tp_();
}
remove_init_file_ = false;
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
file_helper_.write(formatted);
@ -168,6 +177,7 @@ private:
bool truncate_;
uint16_t max_files_;
details::circular_q<filename_t> filenames_q_;
bool remove_init_file_;
};
using hourly_file_sink_mt = hourly_file_sink<std::mutex>;
@ -179,16 +189,16 @@ using hourly_file_sink_st = hourly_file_sink<details::null_mutex>;
// factory functions
//
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> hourly_logger_mt(
const std::string &logger_name, const filename_t &filename, bool truncate = false, uint16_t max_files = 0)
inline std::shared_ptr<logger> hourly_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false,
uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate, max_files);
return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate, max_files, event_handlers);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> hourly_logger_st(
const std::string &logger_name, const filename_t &filename, bool truncate = false, uint16_t max_files = 0)
inline std::shared_ptr<logger> hourly_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false,
uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate, max_files);
return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate, max_files, event_handlers);
}
} // namespace spdlog

View File

@ -0,0 +1,107 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
//
// Custom sink for mongodb
// Building and using requires mongocxx library.
// For building mongocxx library check the url below
// http://mongocxx.org/mongocxx-v3/installation/
//
#include "spdlog/common.h"
#include "spdlog/details/log_msg.h"
#include "spdlog/sinks/base_sink.h"
#include <spdlog/details/synchronous_factory.h>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/view_or_value.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
namespace spdlog {
namespace sinks {
template<typename Mutex>
class mongo_sink : public base_sink<Mutex>
{
public:
mongo_sink(const std::string &db_name, const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017")
try : mongo_sink(std::make_shared<mongocxx::instance>(), db_name, collection_name, uri)
{}
catch (const std::exception &e)
{
throw_spdlog_ex(fmt_lib::format("Error opening database: {}", e.what()));
}
mongo_sink(std::shared_ptr<mongocxx::instance> instance, const std::string &db_name, const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017")
: instance_(std::move(instance))
, db_name_(db_name)
, coll_name_(collection_name)
{
try
{
client_ = spdlog::details::make_unique<mongocxx::client>(mongocxx::uri{uri});
}
catch (const std::exception &e)
{
throw_spdlog_ex(fmt_lib::format("Error opening database: {}", e.what()));
}
}
~mongo_sink()
{
flush_();
}
protected:
void sink_it_(const details::log_msg &msg) override
{
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
if (client_ != nullptr)
{
auto doc = document{} << "timestamp" << bsoncxx::types::b_date(msg.time) << "level" << level::to_string_view(msg.level).data()
<< "level_num" << msg.level << "message" << std::string(msg.payload.begin(), msg.payload.end())
<< "logger_name" << std::string(msg.logger_name.begin(), msg.logger_name.end()) << "thread_id"
<< static_cast<int>(msg.thread_id) << finalize;
client_->database(db_name_).collection(coll_name_).insert_one(doc.view());
}
}
void flush_() override {}
private:
std::shared_ptr<mongocxx::instance> instance_;
std::string db_name_;
std::string coll_name_;
std::unique_ptr<mongocxx::client> client_ = nullptr;
};
#include "spdlog/details/null_mutex.h"
#include <mutex>
using mongo_sink_mt = mongo_sink<std::mutex>;
using mongo_sink_st = mongo_sink<spdlog::details::null_mutex>;
} // namespace sinks
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> mongo_logger_mt(const std::string &logger_name, const std::string &db_name,
const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017")
{
return Factory::template create<sinks::mongo_sink_mt>(logger_name, db_name, collection_name, uri);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> mongo_logger_st(const std::string &logger_name, const std::string &db_name,
const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017")
{
return Factory::template create<sinks::mongo_sink_st>(logger_name, db_name, collection_name, uri);
}
} // namespace spdlog

View File

@ -1,19 +1,20 @@
// Copyright(c) 2016 Alexander Dalshov.
// Copyright(c) 2016 Alexander Dalshov & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#if defined(_WIN32)
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <mutex>
#include <string>
# include <spdlog/details/null_mutex.h>
# include <spdlog/sinks/base_sink.h>
# include <mutex>
# include <string>
// Avoid including windows.h (https://stackoverflow.com/a/30741042)
extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char *lpOutputString);
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
namespace spdlog {
namespace sinks {
@ -25,16 +26,25 @@ class msvc_sink : public base_sink<Mutex>
{
public:
msvc_sink() = default;
msvc_sink(bool check_ebugger_present)
: check_debbugger_present_{check_ebugger_present} {};
protected:
void sink_it_(const details::log_msg &msg) override
{
if (check_debbugger_present_ && !IsDebuggerPresent())
{
return;
}
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
OutputDebugStringA(fmt::to_string(formatted).c_str());
formatted.push_back('\0'); // add a null terminator for OutputDebugStringA
OutputDebugStringA(formatted.data());
}
void flush_() override {}
bool check_debbugger_present_ = true;
};
using msvc_sink_mt = msvc_sink<std::mutex>;

View File

@ -3,9 +3,9 @@
#pragma once
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/details/synchronous_factory.h>
#include <mutex>

View File

@ -3,8 +3,8 @@
#pragma once
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/sinks/base_sink.h>
#include <mutex>
#include <ostream>

102
r5dev/thirdparty/spdlog/sinks/qt_sinks.h vendored Normal file
View File

@ -0,0 +1,102 @@
// Copyright(c) 2015-present, Gabi Melman, mguludag and spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
//
// Custom sink for QPlainTextEdit or QTextEdit and its childs(QTextBrowser...
// etc) Building and using requires Qt library.
//
#include "spdlog/common.h"
#include "spdlog/details/log_msg.h"
#include "spdlog/details/synchronous_factory.h"
#include "spdlog/sinks/base_sink.h"
#include <QTextEdit>
#include <QPlainTextEdit>
//
// qt_sink class
//
namespace spdlog {
namespace sinks {
template<typename Mutex>
class qt_sink : public base_sink<Mutex>
{
public:
qt_sink(QObject *qt_object, const std::string &meta_method)
{
qt_object_ = qt_object;
meta_method_ = meta_method;
}
~qt_sink()
{
flush_();
}
protected:
void sink_it_(const details::log_msg &msg) override
{
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
string_view_t str = string_view_t(formatted.data(), formatted.size());
QMetaObject::invokeMethod(qt_object_, meta_method_.c_str(), Qt::AutoConnection,
Q_ARG(QString, QString::fromUtf8(str.data(), static_cast<int>(str.size())).trimmed()));
}
void flush_() override {}
private:
QObject *qt_object_ = nullptr;
std::string meta_method_;
};
#include "spdlog/details/null_mutex.h"
#include <mutex>
using qt_sink_mt = qt_sink<std::mutex>;
using qt_sink_st = qt_sink<spdlog::details::null_mutex>;
} // namespace sinks
//
// Factory functions
//
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_mt(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append")
{
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append")
{
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_mt(
const std::string &logger_name, QPlainTextEdit *qt_object, const std::string &meta_method = "appendPlainText")
{
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_st(
const std::string &logger_name, QPlainTextEdit *qt_object, const std::string &meta_method = "appendPlainText")
{
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_mt(const std::string &logger_name, QObject *qt_object, const std::string &meta_method)
{
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name, QObject *qt_object, const std::string &meta_method)
{
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
}
} // namespace spdlog

View File

@ -3,10 +3,10 @@
#pragma once
#include "thirdparty/spdlog/include/spdlog/sinks/base_sink.h"
#include "thirdparty/spdlog/include/spdlog/details/circular_q.h"
#include "thirdparty/spdlog/include/spdlog/details/log_msg_buffer.h"
#include "thirdparty/spdlog/include/spdlog/details/null_mutex.h"
#include "spdlog/sinks/base_sink.h"
#include "spdlog/details/circular_q.h"
#include "spdlog/details/log_msg_buffer.h"
#include "spdlog/details/null_mutex.h"
#include <mutex>
#include <string>
@ -50,7 +50,7 @@ public:
{
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(q_.at(i), formatted);
ret.push_back(fmt::to_string(formatted));
ret.push_back(std::move(SPDLOG_BUF_TO_STRING(formatted)));
}
return ret;
}

View File

@ -4,14 +4,14 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/sinks/rotating_file_sink.h>
# include <spdlog/sinks/rotating_file_sink.h>
#endif
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
#include <thirdparty/spdlog/include/details/file_helper.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/fmt/fmt.h>
#include <spdlog/details/file_helper.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/fmt/fmt.h>
#include <cerrno>
#include <chrono>
@ -25,16 +25,27 @@ namespace sinks {
template<typename Mutex>
SPDLOG_INLINE rotating_file_sink<Mutex>::rotating_file_sink(
filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open)
filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open, const file_event_handlers &event_handlers)
: base_filename_(std::move(base_filename))
, max_size_(max_size)
, max_files_(max_files)
, file_helper_{event_handlers}
{
if (max_size == 0)
{
throw_spdlog_ex("rotating sink constructor: max_size arg cannot be zero");
}
if (max_files > 200000)
{
throw_spdlog_ex("rotating sink constructor: max_files arg cannot exceed 200000");
}
file_helper_.open(calc_filename(base_filename_, 0));
current_size_ = file_helper_.size(); // expensive. called only once
if (rotate_on_open && current_size_ > 0)
{
rotate_();
current_size_ = 0;
}
}
@ -50,7 +61,7 @@ SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::calc_filename(const filename
filename_t basename, ext;
std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
return fmt::format(SPDLOG_FILENAME_T("{}.{}{}"), basename, index, ext);
return fmt_lib::format(SPDLOG_FILENAME_T("{}.{}{}"), basename, index, ext);
}
template<typename Mutex>
@ -65,13 +76,22 @@ SPDLOG_INLINE void rotating_file_sink<Mutex>::sink_it_(const details::log_msg &m
{
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
current_size_ += formatted.size();
if (current_size_ > max_size_)
auto new_size = current_size_ + formatted.size();
// rotate if the new estimated file size exceeds max size.
// rotate only if the real size > 0 to better deal with full disk (see issue #2261).
// we only check the real size when new_size > max_size_ because it is relatively expensive.
if (new_size > max_size_)
{
rotate_();
current_size_ = formatted.size();
file_helper_.flush();
if (file_helper_.size() > 0)
{
rotate_();
new_size = formatted.size();
}
}
file_helper_.write(formatted);
current_size_ = new_size;
}
template<typename Mutex>
@ -90,6 +110,7 @@ SPDLOG_INLINE void rotating_file_sink<Mutex>::rotate_()
{
using details::os::filename_to_str;
using details::os::path_exists;
file_helper_.close();
for (auto i = max_files_; i > 0; --i)
{

View File

@ -3,10 +3,10 @@
#pragma once
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <thirdparty/spdlog/include/details/file_helper.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/details/file_helper.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/details/synchronous_factory.h>
#include <chrono>
#include <mutex>
@ -22,7 +22,8 @@ template<typename Mutex>
class rotating_file_sink final : public base_sink<Mutex>
{
public:
rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open = false);
rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open = false,
const file_event_handlers &event_handlers = {});
static filename_t calc_filename(const filename_t &filename, std::size_t index);
filename_t filename();
@ -59,20 +60,22 @@ using rotating_file_sink_st = rotating_file_sink<details::null_mutex>;
//
template<typename Factory = spdlog::synchronous_factory>
inline 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, bool rotate_on_open = false)
inline 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, bool rotate_on_open = false, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files, rotate_on_open);
return Factory::template create<sinks::rotating_file_sink_mt>(
logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers);
}
template<typename Factory = spdlog::synchronous_factory>
inline 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, bool rotate_on_open = false)
inline 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, bool rotate_on_open = false, const file_event_handlers &event_handlers = {})
{
return Factory::template create<sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files, rotate_on_open);
return Factory::template create<sinks::rotating_file_sink_st>(
logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers);
}
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "rotating_file_sink-inl.h"
# include "rotating_file_sink-inl.h"
#endif

View File

@ -4,10 +4,10 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/sinks/sink.h>
# include <spdlog/sinks/sink.h>
#endif
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/common.h>
SPDLOG_INLINE bool spdlog::sinks::sink::should_log(spdlog::level::level_enum msg_level) const
{

View File

@ -3,8 +3,8 @@
#pragma once
#include <thirdparty/spdlog/include/details/log_msg.h>
#include <thirdparty/spdlog/include/formatter.h>
#include <spdlog/details/log_msg.h>
#include <spdlog/formatter.h>
namespace spdlog {
@ -31,5 +31,5 @@ protected:
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "sink-inl.h"
# include "sink-inl.h"
#endif

View File

@ -4,11 +4,11 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/sinks/stdout_color_sinks.h>
# include <spdlog/sinks/stdout_color_sinks.h>
#endif
#include <thirdparty/spdlog/include/logger.h>
#include <thirdparty/spdlog/include/common.h>
#include <spdlog/logger.h>
#include <spdlog/common.h>
namespace spdlog {
@ -36,4 +36,3 @@ SPDLOG_INLINE std::shared_ptr<logger> stderr_color_st(const std::string &logger_
return Factory::template create<sinks::stderr_color_sink_st>(logger_name, mode);
}
} // namespace spdlog

View File

@ -4,12 +4,12 @@
#pragma once
#ifdef _WIN32
#include <thirdparty/spdlog/include/sinks/wincolor_sink.h>
# include <spdlog/sinks/wincolor_sink.h>
#else
#include <thirdparty/spdlog/include/sinks/ansicolor_sink.h>
# include <spdlog/sinks/ansicolor_sink.h>
#endif
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <spdlog/details/synchronous_factory.h>
namespace spdlog {
namespace sinks {
@ -41,5 +41,5 @@ std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mo
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "thirdparty/spdlog/include/sinks/stdout_color_sinks-inl.h"
# include "stdout_color_sinks-inl.h"
#endif

View File

@ -4,25 +4,25 @@
#pragma once
#ifndef SPDLOG_HEADER_ONLY
#include <thirdparty/spdlog/include/sinks/stdout_sinks.h>
# include <spdlog/sinks/stdout_sinks.h>
#endif
#include <thirdparty/spdlog/include/details/console_globals.h>
#include <thirdparty/spdlog/include/pattern_formatter.h>
#include <spdlog/details/console_globals.h>
#include <spdlog/pattern_formatter.h>
#include <memory>
#ifdef _WIN32
// under windows using fwrite to non-binary stream results in \r\r\n (see issue #1675)
// so instead we use ::FileWrite
#include <thirdparty/spdlog/include/details/windows_include.h>
# include <spdlog/details/windows_include.h>
#ifndef _USING_V110_SDK71_ // fileapi.h doesnt exist in winxp
#include <fileapi.h> // WriteFile (..)
#endif
# ifndef _USING_V110_SDK71_ // fileapi.h doesn't exist in winxp
# include <fileapi.h> // WriteFile (..)
# endif
#include <io.h> // _get_osfhandle(..)
#include <stdio.h> // _fileno(..)
#endif // WIN32
# include <io.h> // _get_osfhandle(..)
# include <stdio.h> // _fileno(..)
#endif // WIN32
namespace spdlog {
@ -36,9 +36,9 @@ SPDLOG_INLINE stdout_sink_base<ConsoleMutex>::stdout_sink_base(FILE *file)
{
#ifdef _WIN32
// get windows handle from the FILE* object
handle_ = (HANDLE)::_get_osfhandle(::_fileno(file_));
handle_ = reinterpret_cast<HANDLE>(::_get_osfhandle(::_fileno(file_)));
// don't throw to support cases where no console is attached,
// and let the log method to do nothing if (handle_ == INVALID_HANDLE_VALUE).
// throw only if non stdout/stderr target is requested (probably regular file and not console).
@ -54,13 +54,13 @@ SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::log(const details::log_msg &m
{
#ifdef _WIN32
if (handle_ == INVALID_HANDLE_VALUE)
{
{
return;
}
std::lock_guard<mutex_t> lock(mutex_);
memory_buf_t formatted;
formatter_->format(msg, formatted);
::fflush(file_); // flush in case there is somthing in this file_ already
::fflush(file_); // flush in case there is something in this file_ already
auto size = static_cast<DWORD>(formatted.size());
DWORD bytes_written = 0;
bool ok = ::WriteFile(handle_, formatted.data(), size, &bytes_written, nullptr) != 0;
@ -74,7 +74,7 @@ SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::log(const details::log_msg &m
formatter_->format(msg, formatted);
::fwrite(formatted.data(), sizeof(char), formatted.size(), file_);
::fflush(file_); // flush every line to terminal
#endif // WIN32
#endif // WIN32
}
template<typename ConsoleMutex>

View File

@ -3,13 +3,13 @@
#pragma once
#include <thirdparty/spdlog/include/details/console_globals.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <thirdparty/spdlog/include/sinks/sink.h>
#include <spdlog/details/console_globals.h>
#include <spdlog/details/synchronous_factory.h>
#include <spdlog/sinks/sink.h>
#include <cstdio>
#ifdef _WIN32
#include <thirdparty/spdlog/include/details/windows_include.h>
# include <spdlog/details/windows_include.h>
#endif
namespace spdlog {
@ -41,7 +41,7 @@ protected:
FILE *file_;
std::unique_ptr<spdlog::formatter> formatter_;
#ifdef _WIN32
HANDLE handle_;
HANDLE handle_;
#endif // WIN32
};
@ -83,5 +83,5 @@ std::shared_ptr<logger> stderr_logger_st(const std::string &logger_name);
} // namespace spdlog
#ifdef SPDLOG_HEADER_ONLY
#include "stdout_sinks-inl.h"
# include "stdout_sinks-inl.h"
#endif

View File

@ -3,9 +3,9 @@
#pragma once
#include <thirdparty/spdlog/include/sinks/base_sink.h>
#include <thirdparty/spdlog/include/details/null_mutex.h>
#include <thirdparty/spdlog/include/details/synchronous_factory.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/details/synchronous_factory.h>
#include <array>
#include <string>

Some files were not shown because too many files have changed in this diff Show More