From 4207468ef03ed1f87446f303962bbc0b06cbb2a7 Mon Sep 17 00:00:00 2001 From: Fred Nicolson Date: Tue, 6 Mar 2018 14:31:47 +0000 Subject: [PATCH] Added the ability to add iterator ranges to packets So, fr::Packet::add_range(std::begin(container), std::end(container)); --- include/frnetlib/Packet.h | 29 +++++++++++++++++++++++++++++ tests/PacketTest.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/include/frnetlib/Packet.h b/include/frnetlib/Packet.h index ddb8cf2..c7f8249 100644 --- a/include/frnetlib/Packet.h +++ b/include/frnetlib/Packet.h @@ -36,6 +36,13 @@ namespace fr add(part, std::forward(args)...); } + /*! + * Variadic add function for adding multiple values at once to the packet, + * used by packet constructor. + * + * @param part The first argument to add + * @param args The remaining arguments to add + */ template inline void add(T const& part, Args &&...args) { @@ -43,12 +50,34 @@ namespace fr add(std::forward(args)...); } + /*! + * Part of the variadic add function. + * + * @param part The argument to add to the packet + */ template inline void add(T const &part) { *this << part; } + /*! + * Add function to allow adding iterator ranges to the packet. + * + * @note std::distance() is used, and so this function should ideally be used with random access + * iterators to achieve constant time complexity. + * @tparam Iter The iterator type + * @param begin An iterator to the first element to add from + * @param end A past-the-end iterator to stop adding at + */ + template + inline void add_range(Iter begin, Iter end) + { + *this << static_cast(std::distance(begin, end)); + for(auto iter = begin; iter != end; ++iter) + *this << *iter; + } + /*! * Adds raw data to packet * diff --git a/tests/PacketTest.cpp b/tests/PacketTest.cpp index c8345c9..c0499ab 100644 --- a/tests/PacketTest.cpp +++ b/tests/PacketTest.cpp @@ -3,6 +3,32 @@ #include #include +TEST(PacketTest, range_add) +{ + std::vector var{1, 2, 3, 4, 5}; + fr::Packet packet; + packet.add_range(var.begin(), var.end()); + + std::vector out; + packet >> out; + ASSERT_EQ(var, out); +} + +TEST(PacketTest, double_range_add) +{ + std::vector var1{1, 2, 3, 4, 5}; + std::vector var2{6, 7, 8, 9, 10}; + fr::Packet packet; + packet.add_range(var1.begin(), var1.end()); + packet.add_range(var2.begin(), var2.end()); + + std::vector out1; + std::vector out2; + packet >> out1 >> out2; + ASSERT_EQ(var1, out1); + ASSERT_EQ(var2, out2); +} + TEST(PacketTest, pack_and_unpack_ints) { fr::Packet packet;