async_mqtt 5.0.0
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_TOPIC_ALIAS_RECV_HPP)
8#define ASYNC_MQTT_TOPIC_ALIAS_RECV_HPP
9
10#include <string>
11#include <unordered_map>
12#include <array>
13
14#include <boost/assert.hpp>
15#include <boost/multi_index_container.hpp>
16#include <boost/multi_index/ordered_index.hpp>
17#include <boost/multi_index/key.hpp>
18
19#include <async_mqtt/constant.hpp>
20#include <async_mqtt/type.hpp>
21#include <async_mqtt/log.hpp>
22#include <async_mqtt/util/move.hpp>
23#include <async_mqtt/util/string_view.hpp>
24
25namespace async_mqtt {
26
27namespace mi = boost::multi_index;
28
29class topic_alias_recv {
30public:
31 topic_alias_recv(topic_alias_t max)
32 :max_{max} {}
33
34 void insert_or_update(string_view topic, topic_alias_t alias) {
35 ASYNC_MQTT_LOG("mqtt_impl", trace)
36 << ASYNC_MQTT_ADD_VALUE(address, this)
37 << "topic_alias_recv insert"
38 << " topic:" << topic
39 << " alias:" << alias;
40 BOOST_ASSERT(!topic.empty() && alias >= min_ && alias <= max_);
41 auto it = aliases_.lower_bound(alias);
42 if (it == aliases_.end() || it->alias != alias) {
43 aliases_.emplace_hint(it, std::string(topic), alias);
44 }
45 else {
46 aliases_.modify(
47 it,
48 [&](entry& e) {
49 e.topic = std::string{topic};
50 },
51 [](auto&) { BOOST_ASSERT(false); }
52 );
53
54 }
55 }
56
57 std::string find(topic_alias_t alias) const {
58 BOOST_ASSERT(alias >= min_ && alias <= max_);
59 std::string topic;
60 auto it = aliases_.find(alias);
61 if (it != aliases_.end()) topic = it->topic;
62
63 ASYNC_MQTT_LOG("mqtt_impl", info)
64 << ASYNC_MQTT_ADD_VALUE(address, this)
65 << "find_topic_by_alias"
66 << " alias:" << alias
67 << " topic:" << topic;
68
69 return topic;
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_t max() const { return max_; }
80
81private:
82 static constexpr topic_alias_t min_ = 1;
83 topic_alias_t max_;
84
85 struct entry {
86 entry(std::string topic, topic_alias_t alias)
87 : topic{force_move(topic)}, alias{alias} {}
88
89 std::string topic;
90 topic_alias_t 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_TOPIC_ALIAS_RECV_HPP