Files
spark/src/lib/logging/MsgPacking.h
T

66 lines
1.8 KiB
C++

#pragma once
#include <fmt/ostream.h>
#include <array>
#include <type_traits>
#include <iostream>
namespace bts {
namespace log {
template <class Tuple, std::size_t... Is>
std::string format_tuple(const char*msg_template, Tuple const &t,std::index_sequence<Is...>)
{
try {
return fmt::format(msg_template,std::get<Is>(t)...);
}
catch (fmt::FormatError const &e)
{
return fmt::format("Bad log message template: '{}' Error: '{}'",
msg_template,e.what());
}
}
template <size_t SZ, typename... Args>
std::string unpack_msg_args(std::array<uint8_t,SZ> const&buffer, const char*msg_template)
{
std::string result;
using Store = std::tuple<Args...>;
if (sizeof(Store) <= SZ) {
auto args = (Store*) &buffer[0];
result = format_tuple(msg_template,*args,std::index_sequence_for<Args...>{});
args->~Store();
}
else {
auto indirect_store = (Store**) &buffer[0];
auto args = *indirect_store;
result = format_tuple(msg_template,*args,std::index_sequence_for<Args...>{});
delete args;
}
return result;
}
template <typename... Args> struct CheckPtr {
const static auto value = true;
};
template <typename Head, typename... Tail>
struct CheckPtr<Head,Tail...> : public CheckPtr<Tail...> {
static_assert(!std::is_pointer<Head>::value,"Pointers cannot be logged");
};
template <size_t SZ, typename... Args>
void pack_msg_args(std::array<uint8_t,SZ> &buffer,Args&&...args) {
using Store = std::tuple<typename std::remove_reference<Args>::type...>;
static_assert(CheckPtr<typename std::remove_reference<Args>::type...>::value,"Illegal type logged");
if(sizeof(Store) <= SZ)
new (&buffer[0]) Store(std::forward<Args>(args)...);
else {
auto indirect_store = new Store(std::forward<Args>(args)...);
*((Store**) &buffer[0]) = indirect_store;
}
}
}}