blob: 015255e4dc00b5c0b7baadf0506483d0ee0c07c6 [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
Steve Anton10542f22019-01-11 09:11:00 -080011#ifndef RTC_BASE_MESSAGE_HANDLER_H_
12#define RTC_BASE_MESSAGE_HANDLER_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
Steve Anton10542f22019-01-11 09:11:00 -080016#include "rtc_base/constructor_magic.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:
Artem Titovd8bd7502019-01-09 21:10:00 +010058 explicit FunctorMessageHandler(FunctorT&& functor)
59 : functor_(std::forward<FunctorT>(functor)) {}
Yves Gerey665174f2018-06-19 15:03:05 +020060 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
Steve Anton10542f22019-01-11 09:11:00 -080070#endif // RTC_BASE_MESSAGE_HANDLER_H_