I am experimenting with asio web sockets and tried to write a simple serializer / deserializer.
I am also thinking about an approach on how to serialize some type information alongside the actual data. This way a dont have to worry about that i might choose the wrong type when deserializing.
// serialize.hpp
template<typename T>
struct serialize {
static_assert(std::is_fundamental_v<T> || std::is_standard_layout_v<T>, "Only primitives and PODs can be serialized");
std::array<std::byte, sizeof(T)> operator()(const T& object) {
auto buffer = std::array<std::byte, sizeof(T)>{};
const auto begin = static_cast<const std::byte*>(static_cast<const void*>(std::addressof(object)));
std::copy_n(begin, sizeof(T), buffer.begin());
return buffer;
}
};
// deserialize.hpp
template<typename T>
struct deserialize {
static_assert(std::is_fundamental_v<T> || std::is_standard_layout_v<T>, "Only primitives and PODs can be serialized");
T operator()(const std::array<std::byte, sizeof(T)>& buffer) {
T object;
const auto begin = static_cast<std::byte*>(static_cast<void*>(std::addressof(object)));
std::copy_n(buffer.begin(), sizeof(T), begin);
return object;
}
};