xref: /aosp_15_r20/external/pigweed/pw_async_fuchsia/public/pw_async_fuchsia/dispatcher.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include <lib/async/dispatcher.h>
17 #include <zircon/assert.h>
18 
19 #include "pw_async/dispatcher.h"
20 #include "pw_async/task.h"
21 
22 namespace pw::async_fuchsia {
23 
24 struct AllocatedTaskAndFunction {
25   pw::async::Task task;
26   pw::async::TaskFunction func;
27 };
28 
29 // TODO: https://fxbug.dev/42075970 - Replace these temporary allocating
30 // utilities.
PostAt(pw::async::Dispatcher * dispatcher,pw::async::TaskFunction && task,pw::chrono::SystemClock::time_point time)31 inline void PostAt(pw::async::Dispatcher* dispatcher,
32                    pw::async::TaskFunction&& task,
33                    pw::chrono::SystemClock::time_point time) {
34   AllocatedTaskAndFunction* t = new AllocatedTaskAndFunction();
35   t->func = std::move(task);
36   t->task.set_function([t](pw::async::Context& ctx, pw::Status status) {
37     t->func(ctx, status);
38     delete t;
39   });
40   dispatcher->PostAt(t->task, time);
41 }
42 
PostAfter(pw::async::Dispatcher * dispatcher,pw::async::TaskFunction && task,pw::chrono::SystemClock::duration delay)43 inline void PostAfter(pw::async::Dispatcher* dispatcher,
44                       pw::async::TaskFunction&& task,
45                       pw::chrono::SystemClock::duration delay) {
46   PostAt(dispatcher, std::move(task), dispatcher->now() + delay);
47 }
48 
Post(pw::async::Dispatcher * dispatcher,pw::async::TaskFunction && task)49 inline void Post(pw::async::Dispatcher* dispatcher,
50                  pw::async::TaskFunction&& task) {
51   PostAt(dispatcher, std::move(task), dispatcher->now());
52 }
53 
54 class FuchsiaDispatcher final : public async::Dispatcher {
55  public:
FuchsiaDispatcher(async_dispatcher_t * dispatcher)56   explicit FuchsiaDispatcher(async_dispatcher_t* dispatcher)
57       : dispatcher_(dispatcher) {}
58   ~FuchsiaDispatcher() override = default;
59 
60   chrono::SystemClock::time_point now() override;
61 
62   void PostAt(async::Task& task, chrono::SystemClock::time_point time) override;
63 
64   bool Cancel(async::Task& task) override;
65 
66  private:
67   async_dispatcher_t* dispatcher_;
68 };
69 
70 }  // namespace pw::async_fuchsia
71