blob: 0c40853e214855c46478c5f7a90eff142264c70a [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_MESSAGEHANDLER_H_
12#define RTC_BASE_MESSAGEHANDLER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <utility>
kwiberg0eb15ed2015-12-17 03:04:15 -080015
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "rtc_base/constructormagic.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020017
18namespace rtc {
19
20struct Message;
21
22// Messages get dispatched to a MessageHandler
23
24class MessageHandler {
25 public:
26 virtual ~MessageHandler();
27 virtual void OnMessage(Message* msg) = 0;
28
29 protected:
30 MessageHandler() {}
31
32 private:
33 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandler);
34};
35
36// Helper class to facilitate executing a functor on a thread.
37template <class ReturnT, class FunctorT>
38class FunctorMessageHandler : public MessageHandler {
39 public:
Karl Wibergd6b48192017-10-16 23:01:06 +020040 explicit FunctorMessageHandler(FunctorT&& functor)
41 : functor_(std::forward<FunctorT>(functor)) {}
Yves Gerey665174f2018-06-19 15:03:05 +020042 virtual void OnMessage(Message* msg) { result_ = functor_(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020043 const ReturnT& result() const { return result_; }
44
45 // Returns moved result. Should not call result() or MoveResult() again
46 // after this.
47 ReturnT MoveResult() { return std::move(result_); }
48
49 private:
50 FunctorT functor_;
51 ReturnT result_;
52};
53
54// Specialization for ReturnT of void.
55template <class FunctorT>
56class FunctorMessageHandler<void, FunctorT> : public MessageHandler {
57 public:
Yves Gerey665174f2018-06-19 15:03:05 +020058 explicit FunctorMessageHandler(const FunctorT& functor) : functor_(functor) {}
59 virtual void OnMessage(Message* msg) { functor_(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020060 void result() const {}
61 void MoveResult() {}
62
63 private:
64 FunctorT functor_;
65};
66
Yves Gerey665174f2018-06-19 15:03:05 +020067} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000068
Yves Gerey665174f2018-06-19 15:03:05 +020069#endif // RTC_BASE_MESSAGEHANDLER_H_