Skip to content

Commit 2533a7e

Browse files
committed
socket ref or native file descriptor for poller without use of std::variant_t
1 parent dd67d56 commit 2533a7e

File tree

1 file changed

+62
-6
lines changed

1 file changed

+62
-6
lines changed

zmq_addon.hpp

Lines changed: 62 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,65 @@
3434
#include <limits>
3535
#include <functional>
3636
#include <unordered_map>
37-
#include <variant>
38-
#endif
37+
38+
namespace zmq
39+
{
40+
// socket ref or native file descriptor for poller
41+
class poller_ref_t
42+
{
43+
public:
44+
enum RefType
45+
{
46+
RT_SOCKET,
47+
RT_FD
48+
};
49+
50+
poller_ref_t() : poller_ref_t(socket_ref{})
51+
{}
52+
53+
poller_ref_t(const zmq::socket_ref& socket) : data{RT_SOCKET, socket, {}}
54+
{}
55+
56+
poller_ref_t(zmq::fd_t fd) : data{RT_FD, {}, fd}
57+
{}
58+
59+
size_t hash() const ZMQ_NOTHROW
60+
{
61+
std::size_t h = 0;
62+
hash_combine(h, std::get<0>(data));
63+
hash_combine(h, std::get<1>(data));
64+
hash_combine(h, std::get<2>(data));
65+
return h;
66+
}
67+
68+
bool operator == (const poller_ref_t& o) const ZMQ_NOTHROW
69+
{
70+
return data == o.data;
71+
}
72+
73+
private:
74+
template <class T>
75+
static void hash_combine(std::size_t& seed, const T& v) ZMQ_NOTHROW
76+
{
77+
std::hash<T> hasher;
78+
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
79+
}
80+
81+
std::tuple<int, zmq::socket_ref, zmq::fd_t> data;
82+
83+
}; // class poller_ref_t
84+
85+
} // namespace zmq
86+
87+
// std::hash<> specialization for std::unordered_map
88+
template <> struct std::hash<zmq::poller_ref_t>
89+
{
90+
size_t operator()(const zmq::poller_ref_t& ref) const ZMQ_NOTHROW
91+
{
92+
return ref.hash();
93+
}
94+
};
95+
#endif // ZMQ_CPP11
3996

4097
namespace zmq
4198
{
@@ -684,7 +741,7 @@ class active_poller_t
684741

685742
void add(zmq::socket_ref socket, event_flags events, handler_type handler)
686743
{
687-
const Ref ref{socket};
744+
const poller_ref_t ref{socket};
688745

689746
if (!handler)
690747
throw std::invalid_argument("null handler in active_poller_t::add (socket)");
@@ -705,7 +762,7 @@ class active_poller_t
705762

706763
void add(fd_t fd, event_flags events, handler_type handler)
707764
{
708-
const Ref ref{fd};
765+
const poller_ref_t ref{fd};
709766

710767
if (!handler)
711768
throw std::invalid_argument("null handler in active_poller_t::add (fd)");
@@ -778,8 +835,7 @@ class active_poller_t
778835

779836
poller_t<handler_type> base_poller{};
780837

781-
using Ref = std::variant<socket_ref, fd_t>;
782-
std::unordered_map<Ref, std::shared_ptr<handler_type>> handlers{};
838+
std::unordered_map<zmq::poller_ref_t, std::shared_ptr<handler_type>> handlers{};
783839

784840
std::vector<decltype(base_poller)::event_type> poller_events{};
785841
std::vector<std::shared_ptr<handler_type>> poller_handlers{};

0 commit comments

Comments
 (0)