Added more type support to fr::Packet

Added std::pair<> support.

Added enum/enum class support
This commit is contained in:
Cloaked9000 2017-01-27 15:36:36 +00:00
parent 24195e402f
commit 15d20388c1
2 changed files with 67 additions and 45 deletions

View File

@ -83,6 +83,29 @@ namespace fr
return *this;
}
/*
* For packing pairs
*/
template<typename A, typename B>
inline Packet &operator<<(const std::pair<A, B> &var)
{
*this << var.first;
*this << var.second;
return *this;
}
/*
* For extracting pairs
*/
template<typename A, typename B>
inline Packet &operator>>(std::pair<A, B> &var)
{
*this >> var.first;
*this >> var.second;
return *this;
}
/*
* Adds a boolean variable to the packet
*/
@ -271,6 +294,39 @@ namespace fr
return *this;
}
/*
* Adds an enum, or enum class to the packet.
*
* Underlying type must not be larger than 32bits.
* The enum's underlying type should be specified like so:
*
* enum Enum : type{};
*/
template<typename T, typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>
inline Packet &operator<<(T var)
{
*this << (uint32_t)static_cast<typename std::underlying_type<T>::type>(var);
return *this;
}
/*
* Extracts en enum, or enum class from the packet.
*
* Underlying type must not be larger than 32bits.
* The enum's underlying type should be specified like so:
*
* enum Enum : type{};
*/
template<typename T, typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>
inline Packet &operator>>(T &var)
{
uint32_t val;
*this >> val;
var = static_cast<T>(val);
return *this;
}
/*
* Adds a float variable to the packet
*/

View File

@ -15,53 +15,19 @@
#include "frnetlib/SSLContext.h"
#include "frnetlib/SSLListener.h"
void server()
enum Enum : uint32_t
{
fr::TcpListener listener;
listener.listen("9092");
fr::TcpSocket socket;
listener.accept(socket);
uint64_t packet_count = 0;
auto last_print_time = std::chrono::system_clock::now();
while(true)
{
fr::Packet packet;
if(socket.receive(packet) != fr::Socket::Success)
break;
std::string s1;
packet >> s1;
packet_count++;
if(last_print_time + std::chrono::seconds(1) < std::chrono::system_clock::now())
{
std::cout << "Packets per second: " << packet_count << std::endl;
packet_count = 0;
last_print_time = std::chrono::system_clock::now();
}
}
}
E1 = 0,
E2 = 1,
E3 = 2,
};
int main()
{
std::thread server_thread(server);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
fr::TcpSocket socket;
socket.connect("127.0.0.1", "9092");
std::string a(32384, 'c');
fr::Packet packet;
while(true)
{
packet << a;
if(socket.send(packet) != fr::Socket::Success)
break;
packet.clear();
}
server_thread.join();
std::vector<std::pair<int, int>> bob = {{1, 2}, {3, 4}};
packet << bob;
bob.clear();
packet >> bob;
std::cout << bob[0].first << ", " << bob[0].second << ", " << bob[1].first << ", " << bob[1].second << std::endl;
}