Skip to content

Commit

Permalink
serialization: serialize tools::variant (monero-project#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffro256 committed May 20, 2024
1 parent 60c5d7e commit 38b0fc2
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/common/variant.h
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ class variant
//member variables
/// variant of all value types
VType m_value;

//friend functions
template <class Archive, typename... Ts>
friend bool do_serialize(Archive &ar, variant<Ts...> &v);
};

template <typename... Types>
Expand Down
11 changes: 11 additions & 0 deletions src/serialization/variant.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
#include <boost/mpl/if.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>
#include "common/variant.h"
#include "serialization.h"

/*! \struct variant_serialization_triats
Expand Down Expand Up @@ -144,3 +145,13 @@ static bool do_serialize(Archive<true> &ar, boost::variant<T...> &v)
{
return boost::apply_visitor(variant_write_visitor<Archive>(ar), v);
}

// implementation for tools::variant delegates to internal boost::variant member field
namespace tools
{
template <class Archive, typename... Ts>
bool do_serialize(Archive &ar, variant<Ts...> &v)
{
return do_serialize(ar, v.m_value);
}
}
27 changes: 27 additions & 0 deletions tests/unit_tests/seraphis_serialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,30 @@ TEST(seraphis_serialization, jamtis_payment_proposal_self_send_v1)
EXPECT_EQ(payprop, recovered_payprop);
}
//-------------------------------------------------------------------------------------------------------------------
template <typename... Ts> void match_tools_variant(const tools::variant<Ts...>&) {}
VARIANT_TAG(binary_archive, sp::SpEnoteCore, 0x37);
VARIANT_TAG(binary_archive, sp::SpCoinbaseEnoteCore, 0x88);
//-------------------------------------------------------------------------------------------------------------------
TEST(seraphis_serialization, tools_variant)
{
sp::SpEnoteCoreVariant enote_core{
sp::SpEnoteCore{
.onetime_address = rct::pkGen(),
.amount_commitment = rct::zeroCommit(420)
}
};

match_tools_variant(enote_core); // throws compile error if enote_core stops being of tools::variant type

// serialize
std::string serialized;
EXPECT_TRUE(::serialization::dump_binary(enote_core, serialized));

// deserialize
sp::SpEnoteCoreVariant enote_core_recovered;
EXPECT_TRUE(::serialization::parse_binary(serialized, enote_core_recovered));

// test equal
EXPECT_EQ(enote_core, enote_core_recovered);
}
//-------------------------------------------------------------------------------------------------------------------

0 comments on commit 38b0fc2

Please sign in to comment.