Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 1 | #ifndef AOS_EVENTS_EVENT_LOOP_EVENT_H |
| 2 | #define AOS_EVENTS_EVENT_LOOP_EVENT_H |
| 3 | |
| 4 | #include "aos/time/time.h" |
| 5 | #include "glog/logging.h" |
| 6 | |
| 7 | namespace aos { |
| 8 | |
| 9 | // Common interface to track when callbacks and timers should have happened. |
| 10 | class EventLoopEvent { |
| 11 | public: |
| 12 | virtual ~EventLoopEvent() {} |
| 13 | |
| 14 | bool valid() const { return event_time_ != monotonic_clock::max_time; } |
Brian Silverman | bd405c0 | 2020-06-23 16:25:23 -0700 | [diff] [blame] | 15 | void Invalidate() { |
| 16 | event_time_ = monotonic_clock::max_time; |
| 17 | generation_ = 0; |
| 18 | } |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 19 | |
| 20 | monotonic_clock::time_point event_time() const { |
| 21 | DCHECK(valid()); |
| 22 | return event_time_; |
| 23 | } |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 24 | void set_event_time(monotonic_clock::time_point event_time) { |
| 25 | event_time_ = event_time; |
| 26 | } |
| 27 | |
Brian Silverman | bd405c0 | 2020-06-23 16:25:23 -0700 | [diff] [blame] | 28 | // Internal book-keeping for EventLoop. |
| 29 | size_t generation() const { |
| 30 | DCHECK(valid()); |
| 31 | return generation_; |
| 32 | } |
| 33 | void set_generation(size_t generation) { generation_ = generation; } |
| 34 | |
Austin Schuh | f4b09c7 | 2021-12-08 12:04:37 -0800 | [diff] [blame^] | 35 | virtual void HandleEvent() noexcept = 0; |
Brian Silverman | bd405c0 | 2020-06-23 16:25:23 -0700 | [diff] [blame] | 36 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 37 | private: |
| 38 | monotonic_clock::time_point event_time_ = monotonic_clock::max_time; |
Brian Silverman | bd405c0 | 2020-06-23 16:25:23 -0700 | [diff] [blame] | 39 | size_t generation_ = 0; |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 40 | }; |
| 41 | |
| 42 | // Adapter class to implement EventLoopEvent by calling HandleEvent on T. |
| 43 | template <typename T> |
| 44 | class EventHandler final : public EventLoopEvent { |
| 45 | public: |
| 46 | EventHandler(T *t) : t_(t) {} |
Brian Silverman | bd405c0 | 2020-06-23 16:25:23 -0700 | [diff] [blame] | 47 | ~EventHandler() override = default; |
Austin Schuh | f4b09c7 | 2021-12-08 12:04:37 -0800 | [diff] [blame^] | 48 | void HandleEvent() noexcept override { t_->HandleEvent(); } |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 49 | |
| 50 | private: |
| 51 | T *const t_; |
| 52 | }; |
| 53 | |
| 54 | } // namespace aos |
| 55 | |
| 56 | #endif // AOS_EVENTS_EVENT_LOOP_EVENT_H |