userver: userver/concurrent/async_event_source.hpp Source File
Loading...
Searching...
No Matches
async_event_source.hpp
Go to the documentation of this file.
1#pragma once
2
5
6#include <cstddef>
7#include <functional>
8#include <string>
9#include <string_view>
10#include <typeinfo>
11#include <utility>
12
13#include <userver/utils/impl/internal_tag.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace concurrent {
19
22class FunctionId final {
23public:
24 constexpr FunctionId() = default;
25
26 template <typename Class>
27 explicit FunctionId(Class* obj)
28 : FunctionId(obj, typeid(Class))
29 {}
30
31 explicit operator bool() const;
32
33 bool operator==(const FunctionId& other) const;
34
35 struct Hash final {
36 std::size_t operator()(FunctionId id) const noexcept;
37 };
38
39private:
40 FunctionId(void* ptr, const std::type_info& type);
41
42 void* ptr_{nullptr};
43 const std::type_info* type_{nullptr};
44};
45
52template <typename... Args>
54public:
55 using Function = std::function<void(Args... args)>;
56
57 virtual ~AsyncEventSource() = default;
58
100 template <class Class>
103 Class* obj,
104 std::string_view name,
105 void (Class::*func)(Args...)
106 ) {
107 AddListener(scopes, FunctionId(obj), name, [obj, func](Args... args) { (obj->*func)(args...); });
108 }
109
116 void AddListener(utils::ResourceScopeStorage& scopes, FunctionId id, std::string_view name, Function&& func) {
117 scopes.Register([this, id, name = std::string{name}, func = std::move(func)]() mutable {
118 DoAddListener(id, name, std::move(func));
119 return AsyncEventSubscriberScope(utils::impl::InternalTag{}, *this, id);
120 });
121 }
122
123protected:
124 class [[nodiscard]] AsyncEventSubscriberScope final {
125 public:
126 AsyncEventSubscriberScope(utils::impl::InternalTag, AsyncEventSource& source, FunctionId id) noexcept
127 : source_(&source),
128 id_(id)
129 {}
130
131 AsyncEventSubscriberScope(const AsyncEventSubscriberScope&) = delete;
132 AsyncEventSubscriberScope(AsyncEventSubscriberScope&& other) noexcept
133 : source_(std::exchange(other.source_, nullptr)), id_(other.id_) {}
134 AsyncEventSubscriberScope& operator=(const AsyncEventSubscriberScope&) = delete;
135 AsyncEventSubscriberScope& operator=(AsyncEventSubscriberScope&&) = delete;
136 ~AsyncEventSubscriberScope() {
137 if (source_) {
138 source_->RemoveListener(id_);
139 }
140 }
141
142 private:
143 AsyncEventSource* source_;
144 FunctionId id_;
145 };
146
148 virtual void DoAddListener(FunctionId id, std::string_view name, Function&& func) = 0;
149
151 virtual void RemoveListener(FunctionId id) noexcept = 0;
152};
153
154} // namespace concurrent
155
156USERVER_NAMESPACE_END