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