blob: df2d1ada8ddcecc4493e5ba245a874270eb03af9 [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 <memory>
15#include <utility>
kwiberg0eb15ed2015-12-17 03:04:15 -080016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "rtc_base/constructormagic.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018
19namespace rtc {
20
21struct Message;
22
23// Messages get dispatched to a MessageHandler
24
25class MessageHandler {
26 public:
27 virtual ~MessageHandler();
28 virtual void OnMessage(Message* msg) = 0;
29
30 protected:
31 MessageHandler() {}
32
33 private:
34 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandler);
35};
36
37// Helper class to facilitate executing a functor on a thread.
38template <class ReturnT, class FunctorT>
39class FunctorMessageHandler : public MessageHandler {
40 public:
Karl Wibergd6b48192017-10-16 23:01:06 +020041 explicit FunctorMessageHandler(FunctorT&& functor)
42 : functor_(std::forward<FunctorT>(functor)) {}
Yves Gerey665174f2018-06-19 15:03:05 +020043 virtual void OnMessage(Message* msg) { result_ = functor_(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020044 const ReturnT& result() const { return result_; }
45
46 // Returns moved result. Should not call result() or MoveResult() again
47 // after this.
48 ReturnT MoveResult() { return std::move(result_); }
49
50 private:
51 FunctorT functor_;
52 ReturnT result_;
53};
54
55// Specialization for ReturnT of void.
56template <class FunctorT>
57class FunctorMessageHandler<void, FunctorT> : public MessageHandler {
58 public:
Yves Gerey665174f2018-06-19 15:03:05 +020059 explicit FunctorMessageHandler(const FunctorT& functor) : functor_(functor) {}
60 virtual void OnMessage(Message* msg) { functor_(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020061 void result() const {}
62 void MoveResult() {}
63
64 private:
65 FunctorT functor_;
66};
67
Yves Gerey665174f2018-06-19 15:03:05 +020068} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069
Yves Gerey665174f2018-06-19 15:03:05 +020070#endif // RTC_BASE_MESSAGEHANDLER_H_