binlog icon indicating copy to clipboard operation
binlog copied to clipboard

Log type directly to stream

Open andrewkcorcoran opened this issue 1 year ago • 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});

andrewkcorcoran avatar Aug 02 '22 09:08 andrewkcorcoran

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 .

erenon avatar Aug 02 '22 11:08 erenon

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?

andrewkcorcoran avatar Aug 02 '22 13:08 andrewkcorcoran

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";
}

erenon avatar Aug 31 '22 12:08 erenon