uvw 3.1.0
Loading...
Searching...
No Matches
emitter.h
1#ifndef UVW_EMITTER_INCLUDE_H
2#define UVW_EMITTER_INCLUDE_H
3
4#include <cstddef>
5#include <cstdint>
6#include <functional>
7#include <list>
8#include <memory>
9#include <type_traits>
10#include <unordered_map>
11#include <utility>
12#include <uv.h>
13#include "config.h"
14#include "type_info.hpp"
15
16namespace uvw {
17
24 template<typename U, typename = std::enable_if_t<std::is_integral_v<U>>>
25 explicit error_event(U val) noexcept
26 : ec{static_cast<int>(val)} {}
27
40 static int translate(int sys) noexcept;
41
49 const char *what() const noexcept;
50
58 const char *name() const noexcept;
59
64 int code() const noexcept;
65
70 explicit operator bool() const noexcept;
71
72private:
73 const int ec;
74};
75
82template<typename T, typename... E>
83class emitter {
84public:
85 template<typename U>
86 using listener_t = std::function<void(U &, T &)>;
87
88private:
89 template<typename U>
90 const auto &handler() const noexcept {
91 return std::get<listener_t<U>>(handlers);
92 }
93
94 template<typename U>
95 auto &handler() noexcept {
96 return std::get<listener_t<U>>(handlers);
97 }
98
99protected:
100 template<typename U>
101 void publish(U event) {
102 if(auto &listener = handler<U>(); listener) {
103 listener(event, *static_cast<T *>(this));
104 }
105 }
106
107public:
108 virtual ~emitter() noexcept {
109 static_assert(std::is_base_of_v<emitter<T, E...>, T>);
110 }
111
122 template<typename U>
123 void on(listener_t<U> f) {
124 handler<U>() = std::move(f);
125 }
126
128 template<typename U>
129 void reset() noexcept {
130 handler<U>() = nullptr;
131 }
132
134 void reset() noexcept {
135 reset<error_event>();
136 (reset<E>(), ...);
137 }
138
144 template<typename U>
145 bool has() const noexcept {
146 return static_cast<bool>(handler<U>());
147 }
148
149private:
150 std::tuple<listener_t<error_event>, listener_t<E>...> handlers{};
151};
152
153} // namespace uvw
154
155#ifndef UVW_AS_LIB
156# include "emitter.cpp"
157#endif
158
159#endif // UVW_EMITTER_INCLUDE_H
Event emitter base class.
Definition: emitter.h:83
void reset() noexcept
Disconnects all listeners.
Definition: emitter.h:134
void on(listener_t< U > f)
Registers a long-lived listener with the event emitter.
Definition: emitter.h:123
bool has() const noexcept
Checks if there is a listener registered for the specific event.
Definition: emitter.h:145
void reset() noexcept
Disconnects the listener for the given event type.
Definition: emitter.h:129
uvw default namespace.
Definition: async.h:8
Error event.
Definition: emitter.h:23
static int translate(int sys) noexcept
Returns the libuv error code equivalent to the given platform dependent error code.
int code() const noexcept
Gets the underlying error code, that is an error constant of libuv.
const char * what() const noexcept
Returns the error message for the given error code.
const char * name() const noexcept
Returns the error name for the given error code.