Skip to content

Commit e410ae6

Browse files
author
pfeatherstone
committed
Added support for std::tuple
1 parent 0707e02 commit e410ae6

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

include/msgpack.h

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <vector>
99
#include <map>
1010
#include <unordered_map>
11+
#include <tuple>
1112
#include <cstring>
1213
#if __cpp_lib_bit_cast
1314
#include <bit>
@@ -670,6 +671,32 @@ namespace msgpackcpp
670671
}
671672
}
672673

674+
/////////////////////////////////////////////////////////////////////////////////
675+
/// Tuple
676+
/////////////////////////////////////////////////////////////////////////////////
677+
678+
template<class Stream, class... Args>
679+
inline void serialize(Stream& out, const std::tuple<Args...>& tpl)
680+
{
681+
serialize_array_size(out, sizeof...(Args));
682+
std::apply([&](auto&&... args) {
683+
(serialize(out, std::forward<decltype(args)>(args)),...);
684+
}, tpl);
685+
}
686+
687+
template<class Source, class... Args>
688+
inline void deserialize(Source& in, std::tuple<Args...>& tpl)
689+
{
690+
uint32_t size{};
691+
deserialize_array_size(in, size);
692+
if (size != sizeof...(Args))
693+
throw std::system_error(BAD_SIZE);
694+
695+
std::apply([&](auto&&... args) {
696+
(deserialize(in, std::forward<decltype(args)>(args)),...);
697+
}, tpl);
698+
}
699+
673700
/////////////////////////////////////////////////////////////////////////////////
674701
/// Helpers
675702
/////////////////////////////////////////////////////////////////////////////////

test.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,40 @@ BOOST_AUTO_TEST_CASE(test_maps)
406406
}
407407
}
408408

409+
BOOST_AUTO_TEST_CASE(test_tuple)
410+
{
411+
std::mt19937 eng(std::random_device{}());
412+
std::vector<uint8_t> buf1, buf2;
413+
414+
msgpack::type::tuple<int, bool, std::string> a(1, true, "example");
415+
msgpack::type::tuple<int, bool, std::string> aa;
416+
417+
{
418+
// using msgpack-c library
419+
vector_sink sink{buf1};
420+
msgpack::pack(sink, a);
421+
}
422+
423+
{
424+
// using custom library
425+
using namespace msgpackcpp;
426+
auto out = sink(buf2);
427+
serialize(out, a);
428+
}
429+
430+
BOOST_TEST_REQUIRE(num_errors(buf1, buf2) == 0);
431+
432+
{
433+
// deserialize
434+
using namespace msgpackcpp;
435+
auto in = source(buf2);
436+
deserialize(in, aa);
437+
BOOST_TEST_REQUIRE(std::get<0>(a) == std::get<0>(aa));
438+
BOOST_TEST_REQUIRE(std::get<1>(a) == std::get<1>(aa));
439+
BOOST_TEST_REQUIRE(std::get<2>(a) == std::get<2>(aa));
440+
}
441+
}
442+
409443
BOOST_AUTO_TEST_CASE(test_custom_struct)
410444
{
411445
std::mt19937 eng(std::random_device{}());

0 commit comments

Comments
 (0)