From 4dec5318f7674717674d5d64b56eb7f82d6cfa68 Mon Sep 17 00:00:00 2001 From: Fred Nicolson Date: Fri, 22 Jun 2018 09:22:27 +0100 Subject: [PATCH] Added support for std::map/std::unordered_map to fr::Packet --- include/frnetlib/Packet.h | 82 +++++++++++++++++++++++++++++++++++++++ tests/PacketTest.cpp | 20 ++++++++++ 2 files changed, 102 insertions(+) diff --git a/include/frnetlib/Packet.h b/include/frnetlib/Packet.h index c3edf59..8ca6601 100644 --- a/include/frnetlib/Packet.h +++ b/include/frnetlib/Packet.h @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include "NetworkEncoding.h" #include "Packetable.h" #include "Sendable.h" @@ -142,6 +144,86 @@ namespace fr return *this; } + /* + * Adds a map to a packet + */ + template + inline Packet &operator<<(const std::map &m) + { + //First store its length + *this << static_cast(m.size()); + + //Now each of the elements + for(const auto &iter : m) + { + *this << iter; + } + + return *this; + } + + /* + * Extracts a map from the packet + */ + template + inline Packet &operator>>(std::map &m) + { + uint32_t length; + + //First extract the length + *this >> length; + + //Now take each of the elements out of the packet + for(uint32_t a = 0; a < length; a++) + { + std::pair pair; + *this >> pair; + m.emplace(std::move(pair)); + } + + return *this; + } + + /* + * Adds an unordered_map to a packet + */ + template + inline Packet &operator<<(const std::unordered_map &m) + { + //First store its length + *this << static_cast(m.size()); + + //Now each of the elements + for(const auto &iter : m) + { + *this << iter; + } + + return *this; + } + + /* + * Extracts an unordered_map from the packet + */ + template + inline Packet &operator>>(std::unordered_map &m) + { + uint32_t length; + + //First extract the length + *this >> length; + + //Now take each of the elements out of the packet + for(uint32_t a = 0; a < length; a++) + { + std::pair pair; + *this >> pair; + m.emplace(std::move(pair)); + } + + return *this; + } + /* * For packing pairs */ diff --git a/tests/PacketTest.cpp b/tests/PacketTest.cpp index ddeaab6..10b70db 100644 --- a/tests/PacketTest.cpp +++ b/tests/PacketTest.cpp @@ -66,6 +66,26 @@ TEST(PacketTest, pack_and_unpack_stl) ASSERT_EQ(c1, c2); } +TEST(PacketTest, pack_and_unpack_map) +{ + std::map base = {{"a", "b"}, {"bob", "lob"}}; + std::map copy; + fr::Packet packet; + packet << base; + packet >> copy; + ASSERT_EQ(base, copy); +} + +TEST(PacketTest, pack_and_unpack_unordered_map) +{ + std::unordered_map base = {{"a", "b"}, {"bob", "lob"}}; + std::unordered_map copy; + fr::Packet packet; + packet << base; + packet >> copy; + ASSERT_EQ(base, copy); +} + TEST(PacketTest, variadic_packet_constructor) { int a1 = 10, a2;