Log type directly to stream
Closed this issue · 3 comments
Is it possible to pretty print a type directly to a stream using mserialize and not have to use any of binlog mechanisms? e.g.
struct S{int i, double d};
auto s = S{1,2};
mserialize::serialize(s, SomePrettyPrinterMechansim{std::cout});
It is not possible to directly serialize to human readable string, but it is possible to serialize into the normal binary format, then visit it, turning it into a string.
See: https://github.com/morganstanley/binlog/blob/main/test/unit/mserialize/visit.cpp#L116 (serialize_and_visit) combined with https://github.com/morganstanley/binlog/blob/main/include/binlog/ToStringVisitor.cpp .
I'm probably missing something obvious here but I'm getting compilation errors because the ToStringVisitor::XXXBegin()
methods expect a Range
as their second parameter but the methods in mserialize/visit.cpp are calling those methods and passing InputStream
as the second parameter?
What about this?
#include <binlog/binlog.hpp>
#include <binlog/ToStringVisitor.hpp> // requires binlog library to be linked
#include <mserialize/serialize.hpp>
#include <mserialize/tag.hpp>
#include <mserialize/visit.hpp>
#include <iostream>
#include <sstream>
template <typename T>
void pretty_print(const T& in, std::ostream& out)
{
// serialize
std::stringstream stream; // for the serialized bytes in the binlog format
stream.exceptions(std::ios_base::failbit);
mserialize::serialize(in, stream);
const std::string binary = stream.str();
binlog::Range binary_range(binary.data(), binary.size());
// visit
binlog::detail::OstreamBuffer obuf(out);
binlog::ToStringVisitor visitor(obuf);
const auto tag = mserialize::tag<T>();
mserialize::visit(tag, visitor, binary_range);
}
struct Foo { int bar; };
BINLOG_ADAPT_STRUCT(Foo, bar);
int main()
{
pretty_print(123, std::cout); std::cout << "\n";
pretty_print(Foo{42}, std::cout); std::cout << "\n";
}