blob: a0bdff9175887292402e350dd808bc3300e474ce [file] [log] [blame]
Karl Wiberg3d452cf2020-09-11 14:09:461/*
2 * Copyright 2020 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef RTC_BASE_CANCER_STICK_CASTLE_H_
12#define RTC_BASE_CANCER_STICK_CASTLE_H_
13
14#include <utility>
15#include <vector>
16
17#include "api/function_view.h"
18#include "rtc_base/function.h"
19#include "rtc_base/system/assume.h"
20
21namespace webrtc {
22namespace cancer_stick_castle_impl {
23
24class CancerStickCastleReceivers {
25 public:
26 CancerStickCastleReceivers();
27 ~CancerStickCastleReceivers();
28 void AddReceiver(UntypedFunction&& f) {
29 AddReceiverImpl(&f);
30 // Assume that f was moved from and is now trivially destructible.
31 // This helps the compiler optimize away the destructor call.
32 RTC_ASSUME(f.IsTriviallyDestructible());
33 }
34 void Foreach(rtc::FunctionView<void(UntypedFunction&)> fv);
35
36 private:
37 void AddReceiverImpl(UntypedFunction* f);
38 std::vector<UntypedFunction> receivers_;
39};
40
41} // namespace cancer_stick_castle_impl
42
43// A collection of receivers (callable objects) that can be called all at once.
44// Optimized for minimal binary size.
45//
46// TODO(kwiberg): Add support for removing receivers, if necessary. AddReceiver
47// would have to return some sort of ID that the caller could save and then pass
48// to RemoveReceiver. Alternatively, the callable objects could return one value
49// if they wish to stay in the CSC and another value if they wish to be removed.
50// It depends on what's convenient for the callers...
51template <typename... ArgT>
52class CancerStickCastle {
53 public:
54 template <typename F>
55 void AddReceiver(F&& f) {
56 receivers_.AddReceiver(
57 UntypedFunction::Create<void(ArgT...)>(std::forward<F>(f)));
58 }
59 void Send(ArgT... args) {
60 receivers_.Foreach([&](UntypedFunction& f) {
61 f.Call<void(ArgT...)>(std::forward<ArgT>(args)...);
62 });
63 }
64
65 private:
66 cancer_stick_castle_impl::CancerStickCastleReceivers receivers_;
67};
68
69} // namespace webrtc
70
71#endif // RTC_BASE_CANCER_STICK_CASTLE_H_