C/C++ API Reference
Loading...
Searching...
No Matches
callback_task.h
1// Copyright 2025 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 <functional>
17#include <type_traits>
18
19#include "pw_async2/future.h"
20#include "pw_async2/poll.h"
21#include "pw_async2/task.h"
22#include "pw_function/function.h"
23
24namespace pw::async2 {
25namespace internal {
26
27template <typename FutureType>
28using CallbackType = std::conditional_t<
29 std::is_same_v<typename FutureType::value_type, ReadyType>,
30 Function<void()>,
31 Function<void(typename FutureType::value_type)>>;
32
33} // namespace internal
34
36
42template <typename FutureType,
43 typename Func = internal::CallbackType<FutureType>>
44class FutureCallbackTask : public Task {
45 public:
46 using value_type = typename FutureType::value_type;
47
48 static_assert(is_future_v<FutureType>,
49 "FutureCallbackTask can only be used with Future types");
50
51 FutureCallbackTask(FutureType&& future, Func&& callback)
52 : future_(std::move(future)), callback_(std::move(callback)) {}
53
54 private:
55 Poll<> DoPend(Context& cx) final {
56 Poll<value_type> poll = future_.Pend(cx);
57 if (poll.IsPending()) {
58 return Pending();
59 }
60
61 if constexpr (std::is_same_v<value_type, ReadyType>) {
62 callback_();
63 } else {
64 callback_(std::move(*poll));
65 }
66
67 return Ready();
68 }
69
70 FutureType future_;
71 Func callback_;
72};
73
74template <typename FutureType, typename Func>
75FutureCallbackTask(FutureType&&, Func&&)
76 -> FutureCallbackTask<FutureType, Func>;
77
78// TODO: b/458069794 - Add StreamCallbackTask.
79
81
82} // namespace pw::async2
Definition: context.h:54
Definition: callback_task.h:44
Poll DoPend(Context &cx) final
Definition: callback_task.h:55
Definition: poll.h:60
Definition: task.h:62
constexpr bool IsPending() const noexcept
Returns whether or not this value is Pending.
Definition: poll.h:136
constexpr PendingType Pending()
Returns a value indicating that an operation was not yet able to complete.
Definition: poll.h:271
constexpr Poll Ready()
Returns a value indicating completion.
Definition: poll.h:255
fit::function_impl< function_internal::config::kInlineCallableSize, !function_internal::config::kEnableDynamicAllocation, FunctionType, PW_FUNCTION_DEFAULT_ALLOCATOR_TYPE > Function
Definition: function.h:73