zmq_addon.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. /*
  2. Copyright (c) 2016-2017 ZeroMQ community
  3. Copyright (c) 2016 VOCA AS / Harald Nøkland
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to
  6. deal in the Software without restriction, including without limitation the
  7. rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. sell copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  17. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  18. IN THE SOFTWARE.
  19. */
  20. #ifndef __ZMQ_ADDON_HPP_INCLUDED__
  21. #define __ZMQ_ADDON_HPP_INCLUDED__
  22. #include "zmq.hpp"
  23. #include <deque>
  24. #include <iomanip>
  25. #include <sstream>
  26. #include <stdexcept>
  27. #ifdef ZMQ_CPP11
  28. #include <limits>
  29. #include <functional>
  30. #include <unordered_map>
  31. #endif
  32. namespace zmq
  33. {
  34. #ifdef ZMQ_CPP11
  35. namespace detail
  36. {
  37. template<bool CheckN, class OutputIt>
  38. recv_result_t
  39. recv_multipart_n(socket_ref s, OutputIt out, size_t n, recv_flags flags)
  40. {
  41. size_t msg_count = 0;
  42. message_t msg;
  43. while (true) {
  44. if (CheckN) {
  45. if (msg_count >= n)
  46. throw std::runtime_error(
  47. "Too many message parts in recv_multipart_n");
  48. }
  49. if (!s.recv(msg, flags)) {
  50. // zmq ensures atomic delivery of messages
  51. assert(msg_count == 0);
  52. return {};
  53. }
  54. ++msg_count;
  55. const bool more = msg.more();
  56. *out++ = std::move(msg);
  57. if (!more)
  58. break;
  59. }
  60. return msg_count;
  61. }
  62. inline bool is_little_endian()
  63. {
  64. const uint16_t i = 0x01;
  65. return *reinterpret_cast<const uint8_t *>(&i) == 0x01;
  66. }
  67. inline void write_network_order(unsigned char *buf, const uint32_t value)
  68. {
  69. if (is_little_endian()) {
  70. ZMQ_CONSTEXPR_VAR uint32_t mask = std::numeric_limits<std::uint8_t>::max();
  71. *buf++ = (value >> 24) & mask;
  72. *buf++ = (value >> 16) & mask;
  73. *buf++ = (value >> 8) & mask;
  74. *buf++ = value & mask;
  75. } else {
  76. std::memcpy(buf, &value, sizeof(value));
  77. }
  78. }
  79. inline uint32_t read_u32_network_order(const unsigned char *buf)
  80. {
  81. if (is_little_endian()) {
  82. return (static_cast<uint32_t>(buf[0]) << 24)
  83. + (static_cast<uint32_t>(buf[1]) << 16)
  84. + (static_cast<uint32_t>(buf[2]) << 8)
  85. + static_cast<uint32_t>(buf[3]);
  86. } else {
  87. uint32_t value;
  88. std::memcpy(&value, buf, sizeof(value));
  89. return value;
  90. }
  91. }
  92. } // namespace detail
  93. /* Receive a multipart message.
  94. Writes the zmq::message_t objects to OutputIterator out.
  95. The out iterator must handle an unspecified number of writes,
  96. e.g. by using std::back_inserter.
  97. Returns: the number of messages received or nullopt (on EAGAIN).
  98. Throws: if recv throws. Any exceptions thrown
  99. by the out iterator will be propagated and the message
  100. may have been only partially received with pending
  101. message parts. It is adviced to close this socket in that event.
  102. */
  103. template<class OutputIt>
  104. ZMQ_NODISCARD recv_result_t recv_multipart(socket_ref s,
  105. OutputIt out,
  106. recv_flags flags = recv_flags::none)
  107. {
  108. return detail::recv_multipart_n<false>(s, std::move(out), 0, flags);
  109. }
  110. /* Receive a multipart message.
  111. Writes at most n zmq::message_t objects to OutputIterator out.
  112. If the number of message parts of the incoming message exceeds n
  113. then an exception will be thrown.
  114. Returns: the number of messages received or nullopt (on EAGAIN).
  115. Throws: if recv throws. Throws std::runtime_error if the number
  116. of message parts exceeds n (exactly n messages will have been written
  117. to out). Any exceptions thrown
  118. by the out iterator will be propagated and the message
  119. may have been only partially received with pending
  120. message parts. It is adviced to close this socket in that event.
  121. */
  122. template<class OutputIt>
  123. ZMQ_NODISCARD recv_result_t recv_multipart_n(socket_ref s,
  124. OutputIt out,
  125. size_t n,
  126. recv_flags flags = recv_flags::none)
  127. {
  128. return detail::recv_multipart_n<true>(s, std::move(out), n, flags);
  129. }
  130. /* Send a multipart message.
  131. The range must be a ForwardRange of zmq::message_t,
  132. zmq::const_buffer or zmq::mutable_buffer.
  133. The flags may be zmq::send_flags::sndmore if there are
  134. more message parts to be sent after the call to this function.
  135. Returns: the number of messages sent (exactly msgs.size()) or nullopt (on EAGAIN).
  136. Throws: if send throws. Any exceptions thrown
  137. by the msgs range will be propagated and the message
  138. may have been only partially sent. It is adviced to close this socket in that event.
  139. */
  140. template<class Range
  141. #ifndef ZMQ_CPP11_PARTIAL
  142. ,
  143. typename = typename std::enable_if<
  144. detail::is_range<Range>::value
  145. && (std::is_same<detail::range_value_t<Range>, message_t>::value
  146. || detail::is_buffer<detail::range_value_t<Range>>::value)>::type
  147. #endif
  148. >
  149. send_result_t
  150. send_multipart(socket_ref s, Range &&msgs, send_flags flags = send_flags::none)
  151. {
  152. using std::begin;
  153. using std::end;
  154. auto it = begin(msgs);
  155. const auto end_it = end(msgs);
  156. size_t msg_count = 0;
  157. while (it != end_it) {
  158. const auto next = std::next(it);
  159. const auto msg_flags =
  160. flags | (next == end_it ? send_flags::none : send_flags::sndmore);
  161. if (!s.send(*it, msg_flags)) {
  162. // zmq ensures atomic delivery of messages
  163. assert(it == begin(msgs));
  164. return {};
  165. }
  166. ++msg_count;
  167. it = next;
  168. }
  169. return msg_count;
  170. }
  171. /* Encode a multipart message.
  172. The range must be a ForwardRange of zmq::message_t. A
  173. zmq::multipart_t or STL container may be passed for encoding.
  174. Returns: a zmq::message_t holding the encoded multipart data.
  175. Throws: std::range_error is thrown if the size of any single part
  176. can not fit in an unsigned 32 bit integer.
  177. The encoding is compatible with that used by the CZMQ function
  178. zmsg_encode(), see https://rfc.zeromq.org/spec/50/.
  179. Each part consists of a size followed by the data.
  180. These are placed contiguously into the output message. A part of
  181. size less than 255 bytes will have a single byte size value.
  182. Larger parts will have a five byte size value with the first byte
  183. set to 0xFF and the remaining four bytes holding the size of the
  184. part's data.
  185. */
  186. template<class Range
  187. #ifndef ZMQ_CPP11_PARTIAL
  188. ,
  189. typename = typename std::enable_if<
  190. detail::is_range<Range>::value
  191. && (std::is_same<detail::range_value_t<Range>, message_t>::value
  192. || detail::is_buffer<detail::range_value_t<Range>>::value)>::type
  193. #endif
  194. >
  195. message_t encode(const Range &parts)
  196. {
  197. size_t mmsg_size = 0;
  198. // First pass check sizes
  199. for (const auto &part : parts) {
  200. const size_t part_size = part.size();
  201. if (part_size > std::numeric_limits<std::uint32_t>::max()) {
  202. // Size value must fit into uint32_t.
  203. throw std::range_error("Invalid size, message part too large");
  204. }
  205. const size_t count_size =
  206. part_size < std::numeric_limits<std::uint8_t>::max() ? 1 : 5;
  207. mmsg_size += part_size + count_size;
  208. }
  209. message_t encoded(mmsg_size);
  210. unsigned char *buf = encoded.data<unsigned char>();
  211. for (const auto &part : parts) {
  212. const uint32_t part_size = part.size();
  213. const unsigned char *part_data =
  214. static_cast<const unsigned char *>(part.data());
  215. if (part_size < std::numeric_limits<std::uint8_t>::max()) {
  216. // small part
  217. *buf++ = (unsigned char) part_size;
  218. } else {
  219. // big part
  220. *buf++ = std::numeric_limits<uint8_t>::max();
  221. detail::write_network_order(buf, part_size);
  222. buf += sizeof(part_size);
  223. }
  224. std::memcpy(buf, part_data, part_size);
  225. buf += part_size;
  226. }
  227. assert(static_cast<size_t>(buf - encoded.data<unsigned char>()) == mmsg_size);
  228. return encoded;
  229. }
  230. /* Decode an encoded message to multiple parts.
  231. The given output iterator must be a ForwardIterator to a container
  232. holding zmq::message_t such as a zmq::multipart_t or various STL
  233. containers.
  234. Returns the ForwardIterator advanced once past the last decoded
  235. part.
  236. Throws: a std::out_of_range is thrown if the encoded part sizes
  237. lead to exceeding the message data bounds.
  238. The decoding assumes the message is encoded in the manner
  239. performed by zmq::encode(), see https://rfc.zeromq.org/spec/50/.
  240. */
  241. template<class OutputIt> OutputIt decode(const message_t &encoded, OutputIt out)
  242. {
  243. const unsigned char *source = encoded.data<unsigned char>();
  244. const unsigned char *const limit = source + encoded.size();
  245. while (source < limit) {
  246. size_t part_size = *source++;
  247. if (part_size == std::numeric_limits<std::uint8_t>::max()) {
  248. if (static_cast<size_t>(limit - source) < sizeof(uint32_t)) {
  249. throw std::out_of_range(
  250. "Malformed encoding, overflow in reading size");
  251. }
  252. part_size = detail::read_u32_network_order(source);
  253. // the part size is allowed to be less than 0xFF
  254. source += sizeof(uint32_t);
  255. }
  256. if (static_cast<size_t>(limit - source) < part_size) {
  257. throw std::out_of_range("Malformed encoding, overflow in reading part");
  258. }
  259. *out = message_t(source, part_size);
  260. ++out;
  261. source += part_size;
  262. }
  263. assert(source == limit);
  264. return out;
  265. }
  266. #endif
  267. #ifdef ZMQ_HAS_RVALUE_REFS
  268. /*
  269. This class handles multipart messaging. It is the C++ equivalent of zmsg.h,
  270. which is part of CZMQ (the high-level C binding). Furthermore, it is a major
  271. improvement compared to zmsg.hpp, which is part of the examples in the ØMQ
  272. Guide. Unnecessary copying is avoided by using move semantics to efficiently
  273. add/remove parts.
  274. */
  275. class multipart_t
  276. {
  277. private:
  278. std::deque<message_t> m_parts;
  279. public:
  280. typedef std::deque<message_t>::value_type value_type;
  281. typedef std::deque<message_t>::iterator iterator;
  282. typedef std::deque<message_t>::const_iterator const_iterator;
  283. typedef std::deque<message_t>::reverse_iterator reverse_iterator;
  284. typedef std::deque<message_t>::const_reverse_iterator const_reverse_iterator;
  285. // Default constructor
  286. multipart_t() {}
  287. // Construct from socket receive
  288. multipart_t(socket_t &socket) { recv(socket); }
  289. // Construct from memory block
  290. multipart_t(const void *src, size_t size) { addmem(src, size); }
  291. // Construct from string
  292. multipart_t(const std::string &string) { addstr(string); }
  293. // Construct from message part
  294. multipart_t(message_t &&message) { add(std::move(message)); }
  295. // Move constructor
  296. multipart_t(multipart_t &&other) { m_parts = std::move(other.m_parts); }
  297. // Move assignment operator
  298. multipart_t &operator=(multipart_t &&other)
  299. {
  300. m_parts = std::move(other.m_parts);
  301. return *this;
  302. }
  303. // Destructor
  304. virtual ~multipart_t() { clear(); }
  305. message_t &operator[](size_t n) { return m_parts[n]; }
  306. const message_t &operator[](size_t n) const { return m_parts[n]; }
  307. message_t &at(size_t n) { return m_parts.at(n); }
  308. const message_t &at(size_t n) const { return m_parts.at(n); }
  309. iterator begin() { return m_parts.begin(); }
  310. const_iterator begin() const { return m_parts.begin(); }
  311. const_iterator cbegin() const { return m_parts.cbegin(); }
  312. reverse_iterator rbegin() { return m_parts.rbegin(); }
  313. const_reverse_iterator rbegin() const { return m_parts.rbegin(); }
  314. iterator end() { return m_parts.end(); }
  315. const_iterator end() const { return m_parts.end(); }
  316. const_iterator cend() const { return m_parts.cend(); }
  317. reverse_iterator rend() { return m_parts.rend(); }
  318. const_reverse_iterator rend() const { return m_parts.rend(); }
  319. // Delete all parts
  320. void clear() { m_parts.clear(); }
  321. // Get number of parts
  322. size_t size() const { return m_parts.size(); }
  323. // Check if number of parts is zero
  324. bool empty() const { return m_parts.empty(); }
  325. // Receive multipart message from socket
  326. bool recv(socket_t &socket, int flags = 0)
  327. {
  328. clear();
  329. bool more = true;
  330. while (more) {
  331. message_t message;
  332. #ifdef ZMQ_CPP11
  333. if (!socket.recv(message, static_cast<recv_flags>(flags)))
  334. return false;
  335. #else
  336. if (!socket.recv(&message, flags))
  337. return false;
  338. #endif
  339. more = message.more();
  340. add(std::move(message));
  341. }
  342. return true;
  343. }
  344. // Send multipart message to socket
  345. bool send(socket_t &socket, int flags = 0)
  346. {
  347. flags &= ~(ZMQ_SNDMORE);
  348. bool more = size() > 0;
  349. while (more) {
  350. message_t message = pop();
  351. more = size() > 0;
  352. #ifdef ZMQ_CPP11
  353. if (!socket.send(message, static_cast<send_flags>(
  354. (more ? ZMQ_SNDMORE : 0) | flags)))
  355. return false;
  356. #else
  357. if (!socket.send(message, (more ? ZMQ_SNDMORE : 0) | flags))
  358. return false;
  359. #endif
  360. }
  361. clear();
  362. return true;
  363. }
  364. // Concatenate other multipart to front
  365. void prepend(multipart_t &&other)
  366. {
  367. while (!other.empty())
  368. push(other.remove());
  369. }
  370. // Concatenate other multipart to back
  371. void append(multipart_t &&other)
  372. {
  373. while (!other.empty())
  374. add(other.pop());
  375. }
  376. // Push memory block to front
  377. void pushmem(const void *src, size_t size)
  378. {
  379. m_parts.push_front(message_t(src, size));
  380. }
  381. // Push memory block to back
  382. void addmem(const void *src, size_t size)
  383. {
  384. m_parts.push_back(message_t(src, size));
  385. }
  386. // Push string to front
  387. void pushstr(const std::string &string)
  388. {
  389. m_parts.push_front(message_t(string.data(), string.size()));
  390. }
  391. // Push string to back
  392. void addstr(const std::string &string)
  393. {
  394. m_parts.push_back(message_t(string.data(), string.size()));
  395. }
  396. // Push type (fixed-size) to front
  397. template<typename T> void pushtyp(const T &type)
  398. {
  399. static_assert(!std::is_same<T, std::string>::value,
  400. "Use pushstr() instead of pushtyp<std::string>()");
  401. m_parts.push_front(message_t(&type, sizeof(type)));
  402. }
  403. // Push type (fixed-size) to back
  404. template<typename T> void addtyp(const T &type)
  405. {
  406. static_assert(!std::is_same<T, std::string>::value,
  407. "Use addstr() instead of addtyp<std::string>()");
  408. m_parts.push_back(message_t(&type, sizeof(type)));
  409. }
  410. // Push message part to front
  411. void push(message_t &&message) { m_parts.push_front(std::move(message)); }
  412. // Push message part to back
  413. void add(message_t &&message) { m_parts.push_back(std::move(message)); }
  414. // Alias to allow std::back_inserter()
  415. void push_back(message_t &&message) { m_parts.push_back(std::move(message)); }
  416. // Pop string from front
  417. std::string popstr()
  418. {
  419. std::string string(m_parts.front().data<char>(), m_parts.front().size());
  420. m_parts.pop_front();
  421. return string;
  422. }
  423. // Pop type (fixed-size) from front
  424. template<typename T> T poptyp()
  425. {
  426. static_assert(!std::is_same<T, std::string>::value,
  427. "Use popstr() instead of poptyp<std::string>()");
  428. if (sizeof(T) != m_parts.front().size())
  429. throw std::runtime_error(
  430. "Invalid type, size does not match the message size");
  431. T type = *m_parts.front().data<T>();
  432. m_parts.pop_front();
  433. return type;
  434. }
  435. // Pop message part from front
  436. message_t pop()
  437. {
  438. message_t message = std::move(m_parts.front());
  439. m_parts.pop_front();
  440. return message;
  441. }
  442. // Pop message part from back
  443. message_t remove()
  444. {
  445. message_t message = std::move(m_parts.back());
  446. m_parts.pop_back();
  447. return message;
  448. }
  449. // get message part from front
  450. const message_t &front() { return m_parts.front(); }
  451. // get message part from back
  452. const message_t &back() { return m_parts.back(); }
  453. // Get pointer to a specific message part
  454. const message_t *peek(size_t index) const { return &m_parts[index]; }
  455. // Get a string copy of a specific message part
  456. std::string peekstr(size_t index) const
  457. {
  458. std::string string(m_parts[index].data<char>(), m_parts[index].size());
  459. return string;
  460. }
  461. // Peek type (fixed-size) from front
  462. template<typename T> T peektyp(size_t index) const
  463. {
  464. static_assert(!std::is_same<T, std::string>::value,
  465. "Use peekstr() instead of peektyp<std::string>()");
  466. if (sizeof(T) != m_parts[index].size())
  467. throw std::runtime_error(
  468. "Invalid type, size does not match the message size");
  469. T type = *m_parts[index].data<T>();
  470. return type;
  471. }
  472. // Create multipart from type (fixed-size)
  473. template<typename T> static multipart_t create(const T &type)
  474. {
  475. multipart_t multipart;
  476. multipart.addtyp(type);
  477. return multipart;
  478. }
  479. // Copy multipart
  480. multipart_t clone() const
  481. {
  482. multipart_t multipart;
  483. for (size_t i = 0; i < size(); i++)
  484. multipart.addmem(m_parts[i].data(), m_parts[i].size());
  485. return multipart;
  486. }
  487. // Dump content to string
  488. std::string str() const
  489. {
  490. std::stringstream ss;
  491. for (size_t i = 0; i < m_parts.size(); i++) {
  492. const unsigned char *data = m_parts[i].data<unsigned char>();
  493. size_t size = m_parts[i].size();
  494. // Dump the message as text or binary
  495. bool isText = true;
  496. for (size_t j = 0; j < size; j++) {
  497. if (data[j] < 32 || data[j] > 127) {
  498. isText = false;
  499. break;
  500. }
  501. }
  502. ss << "\n[" << std::dec << std::setw(3) << std::setfill('0') << size
  503. << "] ";
  504. if (size >= 1000) {
  505. ss << "... (too big to print)";
  506. continue;
  507. }
  508. for (size_t j = 0; j < size; j++) {
  509. if (isText)
  510. ss << static_cast<char>(data[j]);
  511. else
  512. ss << std::hex << std::setw(2) << std::setfill('0')
  513. << static_cast<short>(data[j]);
  514. }
  515. }
  516. return ss.str();
  517. }
  518. // Check if equal to other multipart
  519. bool equal(const multipart_t *other) const
  520. {
  521. if (size() != other->size())
  522. return false;
  523. for (size_t i = 0; i < size(); i++)
  524. if (*peek(i) != *other->peek(i))
  525. return false;
  526. return true;
  527. }
  528. #ifdef ZMQ_CPP11
  529. // Return single part message_t encoded from this multipart_t.
  530. message_t encode() const { return zmq::encode(*this); }
  531. // Decode encoded message into multiple parts and append to self.
  532. void decode_append(const message_t &encoded)
  533. {
  534. zmq::decode(encoded, std::back_inserter(*this));
  535. }
  536. // Return a new multipart_t containing the decoded message_t.
  537. static multipart_t decode(const message_t &encoded)
  538. {
  539. multipart_t tmp;
  540. zmq::decode(encoded, std::back_inserter(tmp));
  541. return tmp;
  542. }
  543. #endif
  544. private:
  545. // Disable implicit copying (moving is more efficient)
  546. multipart_t(const multipart_t &other) ZMQ_DELETED_FUNCTION;
  547. void operator=(const multipart_t &other) ZMQ_DELETED_FUNCTION;
  548. }; // class multipart_t
  549. inline std::ostream &operator<<(std::ostream &os, const multipart_t &msg)
  550. {
  551. return os << msg.str();
  552. }
  553. #endif // ZMQ_HAS_RVALUE_REFS
  554. #if defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)
  555. class active_poller_t
  556. {
  557. public:
  558. active_poller_t() = default;
  559. ~active_poller_t() = default;
  560. active_poller_t(const active_poller_t &) = delete;
  561. active_poller_t &operator=(const active_poller_t &) = delete;
  562. active_poller_t(active_poller_t &&src) = default;
  563. active_poller_t &operator=(active_poller_t &&src) = default;
  564. using handler_type = std::function<void(event_flags)>;
  565. void add(zmq::socket_ref socket, event_flags events, handler_type handler)
  566. {
  567. if (!handler)
  568. throw std::invalid_argument("null handler in active_poller_t::add");
  569. auto ret = handlers.emplace(
  570. socket, std::make_shared<handler_type>(std::move(handler)));
  571. if (!ret.second)
  572. throw error_t(EINVAL); // already added
  573. try {
  574. base_poller.add(socket, events, ret.first->second.get());
  575. need_rebuild = true;
  576. }
  577. catch (...) {
  578. // rollback
  579. handlers.erase(socket);
  580. throw;
  581. }
  582. }
  583. void remove(zmq::socket_ref socket)
  584. {
  585. base_poller.remove(socket);
  586. handlers.erase(socket);
  587. need_rebuild = true;
  588. }
  589. void modify(zmq::socket_ref socket, event_flags events)
  590. {
  591. base_poller.modify(socket, events);
  592. }
  593. size_t wait(std::chrono::milliseconds timeout)
  594. {
  595. if (need_rebuild) {
  596. poller_events.resize(handlers.size());
  597. poller_handlers.clear();
  598. poller_handlers.reserve(handlers.size());
  599. for (const auto &handler : handlers) {
  600. poller_handlers.push_back(handler.second);
  601. }
  602. need_rebuild = false;
  603. }
  604. const auto count = base_poller.wait_all(poller_events, timeout);
  605. std::for_each(poller_events.begin(),
  606. poller_events.begin() + static_cast<ptrdiff_t>(count),
  607. [](decltype(base_poller)::event_type &event) {
  608. assert(event.user_data != nullptr);
  609. (*event.user_data)(event.events);
  610. });
  611. return count;
  612. }
  613. ZMQ_NODISCARD bool empty() const noexcept { return handlers.empty(); }
  614. size_t size() const noexcept { return handlers.size(); }
  615. private:
  616. bool need_rebuild{false};
  617. poller_t<handler_type> base_poller{};
  618. std::unordered_map<socket_ref, std::shared_ptr<handler_type>> handlers{};
  619. std::vector<decltype(base_poller)::event_type> poller_events{};
  620. std::vector<std::shared_ptr<handler_type>> poller_handlers{};
  621. }; // class active_poller_t
  622. #endif // defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)
  623. } // namespace zmq
  624. #endif // __ZMQ_ADDON_HPP_INCLUDED__