-
Notifications
You must be signed in to change notification settings - Fork 7
/
sigs.h
394 lines (321 loc) · 9.27 KB
/
sigs.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/***************************************************************************************************
sigs
Simple thread-safe signal/slot C++17 library.
The MIT License (MIT)
Copyright (c) 2015-2019 Morten Kristensen, me AT mortens DOT dev
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************************************/
#ifndef SIGS_SIGNAL_SLOT_H
#define SIGS_SIGNAL_SLOT_H
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// The following is used for making variadic type lists for binding member functions and their
// parameters.
namespace sigs {
template <std::size_t... Ns>
class Seq {
};
template <std::size_t N, std::size_t... Ns>
class MakeSeq : public MakeSeq<N - 1, N - 1, Ns...> {
};
template <std::size_t... Ns>
class MakeSeq<0, Ns...> : public Seq<Ns...> {
};
template <std::size_t>
class Placeholder {
};
} // namespace sigs
// std::bind uses std::is_placeholder to detect placeholders for unbounded arguments, so it must be
// overridden to accept the custom sigs::Placeholder type.
namespace std {
template <size_t N>
class is_placeholder<sigs::Placeholder<N>> : public integral_constant<std::size_t, N + 1> {
};
} // namespace std
namespace sigs {
/// When a member function has muliple overloads and you need to use just one of them.
/** Example:
signal.connect(&instance, sigs::Use<int, float>::overloadOf(&ThClass::func));
*/
template <typename... Args>
struct Use final {
template <typename Cls, typename Ret>
[[nodiscard]] static inline auto overloadOf(Ret (Cls::*MembFunc)(Args...))
{
return MembFunc;
}
};
class ConnectionBase final {
template <typename>
friend class Signal;
public:
void disconnect()
{
if (deleter) deleter();
}
private:
std::function<void()> deleter;
};
using Connection = std::shared_ptr<ConnectionBase>;
namespace detail {
/// VoidableFunction is used internally to generate a function type depending on whether the return
/// type of the signal is non-void.
template <typename T>
class VoidableFunction final {
public:
using func = std::function<void(T)>;
};
/// Specialization for void return types.
template <>
class VoidableFunction<void> final {
public:
using func = std::function<void()>;
};
} // namespace detail
template <typename>
class Signal;
template <typename Ret, typename... Args>
class Signal<Ret(Args...)> final {
using Slot = std::function<Ret(Args...)>;
using SignalType = Signal<Ret(Args...)>;
class Entry final {
public:
Entry(const Slot &slot, Connection conn) : slot_(slot), conn_(conn), signal_(nullptr)
{
}
Entry(Slot &&slot, Connection conn) : slot_(std::move(slot)), conn_(conn), signal_(nullptr)
{
}
Entry(Signal *signal, Connection conn) : conn_(conn), signal_(signal)
{
}
const Slot &slot() const
{
return slot_;
}
Signal *signal() const
{
return signal_;
}
Connection conn() const
{
return conn_;
}
private:
Slot slot_;
Connection conn_;
Signal *signal_;
};
using Cont = std::vector<Entry>;
using Lock = std::lock_guard<std::mutex>;
public:
using ReturnType = Ret;
using SlotType = Slot;
/// Interface that only exposes connect and disconnect methods.
class Interface final {
public:
Interface(SignalType *sig) : sig(sig)
{
}
inline Connection connect(const Slot &slot)
{
return sig->connect(slot);
}
inline Connection connect(Slot &&slot)
{
return sig->connect(slot);
}
template <typename Instance, typename MembFunc>
inline Connection connect(Instance *instance, MembFunc Instance::*mf)
{
return sig->connect(instance, mf);
}
inline Connection connect(Signal &signal)
{
return sig->connect(signal);
}
inline void disconnect(std::optional<Connection> conn)
{
sig->disconnect(conn);
}
inline void disconnect(Signal &signal)
{
sig->disconnect(signal);
}
private:
SignalType *sig = nullptr;
};
Signal() = default;
virtual ~Signal()
{
Lock lock(entriesMutex);
for (auto &entry : entries) {
auto conn = entry.conn();
if (conn) {
conn->deleter = nullptr;
}
}
}
Signal(const Signal &rhs)
{
Lock lock1(entriesMutex);
Lock lock2(const_cast<Signal &>(rhs).entriesMutex);
entries = rhs.entries;
}
Signal &operator=(const Signal &rhs)
{
Lock lock1(entriesMutex);
Lock lock2(const_cast<Signal &>(rhs).entriesMutex);
entries = rhs.entries;
return *this;
}
Signal(Signal &&rhs) = default;
Signal &operator=(Signal &&rhs) = default;
Connection connect(const Slot &slot)
{
Lock lock(entriesMutex);
auto conn = makeConnection();
entries.emplace_back(Entry(slot, conn));
return conn;
}
Connection connect(Slot &&slot)
{
Lock lock(entriesMutex);
auto conn = makeConnection();
entries.emplace_back(Entry(std::move(slot), conn));
return conn;
}
template <typename Instance, typename MembFunc>
Connection connect(Instance *instance, MembFunc Instance::*mf)
{
Lock lock(entriesMutex);
auto slot = bindMf(instance, mf);
auto conn = makeConnection();
entries.emplace_back(Entry(slot, conn));
return conn;
}
/// Connecting a signal will trigger all of its slots when this signal is triggered.
Connection connect(Signal &signal)
{
Lock lock(entriesMutex);
auto conn = makeConnection();
entries.emplace_back(Entry(&signal, conn));
return conn;
}
void clear()
{
Lock lock(entriesMutex);
eraseEntries();
}
void disconnect(std::optional<Connection> conn)
{
if (!conn) {
clear();
return;
}
Lock lock(entriesMutex);
eraseEntries([conn](auto it) { return it->conn() == conn; });
}
void disconnect(Signal &signal)
{
Lock lock(entriesMutex);
eraseEntries([sig = &signal](auto it) { return it->signal() == sig; });
}
void operator()(Args &&... args)
{
Lock lock(entriesMutex);
for (auto &entry : entries) {
auto *sig = entry.signal();
if (sig) {
(*sig)(std::forward<Args>(args)...);
}
else {
entry.slot()(std::forward<Args>(args)...);
}
}
}
template <typename RetFunc = typename detail::VoidableFunction<ReturnType>::func>
void operator()(const RetFunc &retFunc, Args &&... args)
{
static_assert(!isVoidReturn(), "Must have non-void return type!");
Lock lock(entriesMutex);
for (auto &entry : entries) {
auto *sig = entry.signal();
if (sig) {
(*sig)(retFunc, std::forward<Args>(args)...);
}
else {
retFunc(entry.slot()(std::forward<Args>(args)...));
}
}
}
[[nodiscard]] inline std::unique_ptr<Interface> interface()
{
return std::make_unique<Interface>(this);
}
private:
[[nodiscard]] inline Connection makeConnection()
{
auto conn = std::make_shared<ConnectionBase>();
conn->deleter = [this, conn] { this->disconnect(conn); };
return conn;
}
/// Expects entries container to be locked beforehand.
[[nodiscard]] typename Cont::iterator eraseEntry(typename Cont::iterator it)
{
auto conn = it->conn();
if (conn) {
conn->deleter = nullptr;
}
return entries.erase(it);
}
void eraseEntries(std::function<bool(typename Cont::iterator)> pred = [](auto) { return true; })
{
for (auto it = entries.begin(); it != entries.end(); ++it) {
if (pred(it)) {
it = eraseEntry(it);
}
// Avoid iterator-advance-past-end runtime errors.
if (it == entries.end()) {
break;
}
}
}
template <typename Instance, typename MembFunc, std::size_t... Ns>
[[nodiscard]] inline Slot bindMf(Instance *instance, MembFunc Instance::*mf, Seq<Ns...>)
{
return std::bind(mf, instance, Placeholder<Ns>()...);
}
template <typename Instance, typename MembFunc>
[[nodiscard]] inline Slot bindMf(Instance *instance, MembFunc Instance::*mf)
{
return bindMf(instance, mf, MakeSeq<sizeof...(Args)>());
}
[[nodiscard]] static inline constexpr bool isVoidReturn()
{
return std::is_void<ReturnType>::value;
}
Cont entries;
std::mutex entriesMutex;
};
} // namespace sigs
#endif // SIGS_SIGNAL_SLOT_H