• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 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 <optional>
17 
18 #include "pw_async/internal/types.h"
19 #include "pw_async_backend/task.h"
20 
21 namespace pw::async {
22 
23 namespace test {
24 class FakeDispatcher;
25 }
26 
27 /// A Task represents a unit of work (TaskFunction) that can be executed on a
28 /// Dispatcher. To support various Dispatcher backends, it wraps a
29 /// `backend::NativeTask`, which contains backend-specific state and methods.
30 class Task final {
31  public:
32   /// The default constructor creates a Task without a function.
33   /// `set_function()` must be called before posting the Task.
Task()34   Task() : native_type_(*this) {}
35 
36   /// Constructs a Task that calls `f` when executed on a Dispatcher.
Task(TaskFunction && f)37   explicit Task(TaskFunction&& f) : native_type_(*this, std::move(f)) {}
38 
39   Task(const Task&) = delete;
40   Task& operator=(const Task&) = delete;
41   Task(Task&&) = delete;
42   Task& operator=(Task&&) = delete;
43 
44   /// Configure the TaskFunction after construction. This MUST NOT be called
45   /// while this Task is pending in a Dispatcher.
set_function(TaskFunction && f)46   void set_function(TaskFunction&& f) {
47     native_type_.set_function(std::move(f));
48   }
49 
50   /// Executes this task.
operator()51   void operator()(Context& ctx, Status status) { native_type_(ctx, status); }
52 
53   /// Returns the inner NativeTask containing backend-specific state. Only
54   /// Dispatcher backends or non-portable code should call these methods!
native_type()55   backend::NativeTask& native_type() { return native_type_; }
native_type()56   const backend::NativeTask& native_type() const { return native_type_; }
57 
58  private:
59   backend::NativeTask native_type_;
60 };
61 
62 }  // namespace pw::async
63