Added the ability to add iterator ranges to packets

So, fr::Packet::add_range(std::begin(container), std::end(container));
This commit is contained in:
Fred Nicolson 2018-03-06 14:31:47 +00:00
parent 2040540e94
commit 4207468ef0
2 changed files with 55 additions and 0 deletions

View File

@ -36,6 +36,13 @@ namespace fr
add(part, std::forward<Args>(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<typename T, typename ...Args>
inline void add(T const& part, Args &&...args)
{
@ -43,12 +50,34 @@ namespace fr
add(std::forward<Args>(args)...);
}
/*!
* Part of the variadic add function.
*
* @param part The argument to add to the packet
*/
template<typename T>
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<typename Iter>
inline void add_range(Iter begin, Iter end)
{
*this << static_cast<uint64_t>(std::distance(begin, end));
for(auto iter = begin; iter != end; ++iter)
*this << *iter;
}
/*!
* Adds raw data to packet
*

View File

@ -3,6 +3,32 @@
#include <gtest/gtest.h>
#include <frnetlib/Packet.h>
TEST(PacketTest, range_add)
{
std::vector<int> var{1, 2, 3, 4, 5};
fr::Packet packet;
packet.add_range(var.begin(), var.end());
std::vector<int> out;
packet >> out;
ASSERT_EQ(var, out);
}
TEST(PacketTest, double_range_add)
{
std::vector<int> var1{1, 2, 3, 4, 5};
std::vector<int> 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<int> out1;
std::vector<int> out2;
packet >> out1 >> out2;
ASSERT_EQ(var1, out1);
ASSERT_EQ(var2, out2);
}
TEST(PacketTest, pack_and_unpack_ints)
{
fr::Packet packet;