async_mqtt 9.0.1
Loading...
Searching...
No Matches
topic_alias_recv.hpp
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
7#if !defined(ASYNC_MQTT_UTIL_TOPIC_ALIAS_RECV_HPP)
8#define ASYNC_MQTT_UTIL_TOPIC_ALIAS_RECV_HPP
9
10#include <string>
11#include <string_view>
12#include <unordered_map>
13#include <array>
14
15#include <boost/assert.hpp>
16#include <boost/multi_index_container.hpp>
17#include <boost/multi_index/ordered_index.hpp>
18#include <boost/multi_index/key.hpp>
19
20#include <async_mqtt/util/log.hpp>
21#include <async_mqtt/util/move.hpp>
22#include <async_mqtt/packet/property.hpp>
23
24namespace async_mqtt {
25
26namespace mi = boost::multi_index;
27
28class topic_alias_recv {
29public:
30 explicit topic_alias_recv(topic_alias_type max)
31 :max_{max} {}
32
33 void insert_or_update(std::string_view topic, topic_alias_type alias) {
34 ASYNC_MQTT_LOG("mqtt_impl", trace)
35 << ASYNC_MQTT_ADD_VALUE(address, this)
36 << "topic_alias_recv insert"
37 << " topic:" << topic
38 << " alias:" << alias;
39 BOOST_ASSERT(!topic.empty() && alias >= min_ && alias <= max_);
40 auto it = aliases_.lower_bound(alias);
41 if (it == aliases_.end() || it->alias != alias) {
42 aliases_.emplace_hint(it, std::string(topic), alias);
43 }
44 else {
45 aliases_.modify(
46 it,
47 [&](entry& e) {
48 e.topic = std::string{topic};
49 },
50 [](auto&) { BOOST_ASSERT(false); }
51 );
52 }
53 }
54
55 std::string find(topic_alias_type alias) const {
56 if (alias >= min_ && alias <= max_) {
57 std::string topic;
58 auto it = aliases_.find(alias);
59 if (it != aliases_.end()) topic = it->topic;
60
61 ASYNC_MQTT_LOG("mqtt_impl", info)
62 << ASYNC_MQTT_ADD_VALUE(address, this)
63 << "find_topic_by_alias"
64 << " alias:" << alias
65 << " topic:" << topic;
66
67 return topic;
68 }
69 return std::string{};
70 }
71
72 void clear() {
73 ASYNC_MQTT_LOG("mqtt_impl", info)
74 << ASYNC_MQTT_ADD_VALUE(address, this)
75 << "clear_topic_alias";
76 aliases_.clear();
77 }
78
79 topic_alias_type max() const { return max_; }
80
81private:
82 static constexpr topic_alias_type min_ = 1;
84
85 struct entry {
86 entry(std::string topic, topic_alias_type alias)
87 : topic{force_move(topic)}, alias{alias} {}
88
89 std::string topic;
90 topic_alias_type alias;
91 };
92 using mi_topic_alias = mi::multi_index_container<
93 entry,
94 mi::indexed_by<
95 mi::ordered_unique<
96 mi::key<&entry::alias>
97 >
98 >
99 >;
100
101 mi_topic_alias aliases_;
102};
103
104} // namespace async_mqtt
105
106#endif // ASYNC_MQTT_UTIL_TOPIC_ALIAS_RECV_HPP
@ trace
trace level for detaied behavior and reporting issue
@ info
info level api call is output
std::uint16_t topic_alias_type
type of the topic alias value
Definition property.hpp:81