packet_id_manager.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright Takatoshi Kondo 2020
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #if !defined(MQTT_PACKET_ID_MANAGER_HPP)
  7. #define MQTT_PACKET_ID_MANAGER_HPP
  8. #include <mqtt/config.hpp> // should be top to configure variant limit
  9. #include <mqtt/optional.hpp>
  10. #include <mqtt/value_allocator.hpp>
  11. namespace MQTT_NS {
  12. template <typename PacketId>
  13. class packet_id_manager {
  14. using packet_id_t = PacketId;
  15. public:
  16. /**
  17. * @brief Acquire the new unique packet id.
  18. * If all packet ids are already in use, then returns nullopt
  19. * After acquiring the packet id, you can call acquired_* functions.
  20. * The ownership of packet id is moved to the library.
  21. * Or you can call release_packet_id to release it.
  22. * @return packet id
  23. */
  24. optional<packet_id_t> acquire_unique_id() {
  25. return va_.allocate();
  26. }
  27. /**
  28. * @brief Register packet_id to the library.
  29. * After registering the packet_id, you can call acquired_* functions.
  30. * The ownership of packet id is moved to the library.
  31. * Or you can call release_packet_id to release it.
  32. * @return If packet_id is successfully registerd then return true, otherwise return false.
  33. */
  34. bool register_id(packet_id_t packet_id) {
  35. return va_.use(packet_id);
  36. }
  37. /**
  38. * @brief Release packet_id.
  39. * @param packet_id packet id to release.
  40. * only the packet_id gotten by acquire_unique_packet_id, or
  41. * register_packet_id is permitted.
  42. */
  43. void release_id(packet_id_t packet_id) {
  44. va_.deallocate(packet_id);
  45. }
  46. /**
  47. * @brief Clear all packet ids.
  48. */
  49. void clear() {
  50. va_.clear();
  51. }
  52. private:
  53. value_allocator<packet_id_t> va_ {1, std::numeric_limits<packet_id_t>::max()};
  54. };
  55. } // namespace MQTT_NS
  56. #endif // MQTT_PACKET_ID_MANAGER_HPP