libcruft-util/test/serialise.cpp

76 lines
2.3 KiB
C++
Raw Normal View History

#include <cruft/util/tap.hpp>
#include <cruft/util/serialise/ops.hpp>
#include <cruft/util/serialise/std.hpp>
///////////////////////////////////////////////////////////////////////////////
static void
test_scalars (cruft::TAP::logger &tap)
{
std::vector<std::byte> store (sizeof (f32) + sizeof (i16) + sizeof (char));
{
auto remain = cruft::serialise::to_bytes (store, 2.f, i16 (3), char (4));
tap.expect (remain.empty (), "scalar serialise: no remainder");
}
{
cruft::view remain (store);
tap.expect_eq (cruft::serialise::from_bytes<f32> (remain), 2.f, "scalar extract: f32");
tap.expect_eq (cruft::serialise::from_bytes<i16> (remain), 3, "scalar extract: i16");
tap.expect_eq (cruft::serialise::from_bytes<char> (remain), 4, "scalar extract: char");
tap.expect (remain.empty (), "scalar extract: empty");
}
}
///////////////////////////////////////////////////////////////////////////////
template <typename ValueT>
static void
test_roundtrip (cruft::TAP::logger &tap, char const *label, ValueT const &val)
{
std::vector<std::byte> raw (cruft::serialise::size (val));
{
cruft::view remain (raw);
remain = cruft::serialise::to_bytes (remain, val);
tap.expect (remain.empty (), "round_trip {}: serialise", label);
}
{
cruft::view remain (raw);
auto const extracted = cruft::serialise::from_bytes<ValueT> (remain);
tap.expect_eq (extracted, val, "round_trip {}: extract", label);
}
}
///////////////////////////////////////////////////////////////////////////////
static void
test_stdlib (cruft::TAP::logger &tap)
{
test_roundtrip (tap, "string", std::string ("this is a string"));
test_roundtrip (tap, "pair", std::pair<int, bool> (1, false));
test_roundtrip (tap, "vector", std::vector<i16> { 1, 2, 3 });
test_roundtrip (
tap,
"tuple",
std::tuple (
std::string ("this is a string"),
std::pair<int, bool> { 1, false },
std::vector<i16> { 1, 2, 3 }
)
);
}
///////////////////////////////////////////////////////////////////////////////
int main ()
{
cruft::TAP::logger tap;
test_scalars (tap);
test_stdlib (tap);
return tap.status ();
}