xref: /aosp_15_r20/external/pigweed/pw_async2/public/pw_async2/allocate_task.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 "pw_allocator/allocator.h"
17 #include "pw_async2/dispatcher.h"
18 
19 namespace pw::async2 {
20 namespace internal {
21 
22 template <typename Pendable>
23 class AllocatedTask final : public Task {
24  public:
25   template <typename... Args>
AllocatedTask(pw::allocator::Deallocator & deallocator,Args &&...args)26   AllocatedTask(pw::allocator::Deallocator& deallocator, Args&&... args)
27       : deallocator_(deallocator), pendable_(std::forward<Args>(args)...) {}
28 
29  private:
DoPend(Context & cx)30   Poll<> DoPend(Context& cx) final { return pendable_.Pend(cx); }
31 
DoDestroy()32   void DoDestroy() final { deallocator_.Delete(this); }
33 
34   pw::allocator::Deallocator& deallocator_;
35   Pendable pendable_;
36 };
37 
38 }  // namespace internal
39 
40 /// Creates a ``Task`` by dynamically allocating ``Task`` memory from
41 /// ``allocator``.
42 ///
43 /// Returns ``nullptr`` on allocation failure.
44 /// ``Pendable`` must have a ``Poll<> Pend(Context&)`` method.
45 /// ``allocator`` must outlive the resulting ``Task``.
46 template <typename Pendable>
AllocateTask(pw::allocator::Allocator & allocator,Pendable && pendable)47 Task* AllocateTask(pw::allocator::Allocator& allocator, Pendable&& pendable) {
48   return allocator.New<internal::AllocatedTask<Pendable>>(
49       allocator, std::forward<Pendable>(pendable));
50 }
51 
52 /// Creates a ``Task`` by dynamically allocating ``Task`` memory from
53 /// ``allocator``.
54 ///
55 /// Returns ``nullptr`` on allocation failure.
56 /// ``Pendable`` must have a ``Poll<> Pend(Context&)`` method.
57 /// ``allocator`` must outlive the resulting ``Task``.
58 template <typename Pendable, typename... Args>
AllocateTask(pw::allocator::Allocator & allocator,Args &&...args)59 Task* AllocateTask(pw::allocator::Allocator& allocator, Args&&... args) {
60   return allocator.New<internal::AllocatedTask<Pendable>>(
61       allocator, std::forward<Args>(args)...);
62 }
63 
64 }  // namespace pw::async2
65