1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_SRC_CORE_LIB_PROMISE_CONTEXT_H
16 #define GRPC_SRC_CORE_LIB_PROMISE_CONTEXT_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <type_traits>
21 #include <utility>
22
23 #include <grpc/support/log.h>
24
25 namespace grpc_core {
26
27 // To avoid accidentally creating context types, we require an explicit
28 // specialization of this template per context type. The specialization need
29 // not contain any members, only exist.
30 // The reason for avoiding this is that context types each use a thread local.
31 template <typename T>
32 struct ContextType; // IWYU pragma: keep
33
34 namespace promise_detail {
35
36 template <typename T>
37 class Context : public ContextType<T> {
38 public:
Context(T * p)39 explicit Context(T* p) : old_(current_) { current_ = p; }
~Context()40 ~Context() { current_ = old_; }
41 Context(const Context&) = delete;
42 Context& operator=(const Context&) = delete;
43
get()44 static T* get() { return current_; }
45
46 private:
47 T* const old_;
48 static thread_local T* current_;
49 };
50
51 template <typename T>
52 thread_local T* Context<T>::current_;
53
54 template <typename T, typename F>
55 class WithContext {
56 public:
WithContext(F f,T * context)57 WithContext(F f, T* context) : context_(context), f_(std::move(f)) {}
58
operator()59 decltype(std::declval<F>()()) operator()() {
60 Context<T> ctx(context_);
61 return f_();
62 }
63
64 private:
65 T* context_;
66 F f_;
67 };
68
69 } // namespace promise_detail
70
71 // Return true if a context of type T is currently active.
72 template <typename T>
HasContext()73 bool HasContext() {
74 return promise_detail::Context<T>::get() != nullptr;
75 }
76
77 // Retrieve the current value of a context, or abort if the value is unset.
78 template <typename T>
GetContext()79 T* GetContext() {
80 auto* p = promise_detail::Context<T>::get();
81 GPR_ASSERT(p != nullptr);
82 return p;
83 }
84
85 // Given a promise and a context, return a promise that has that context set.
86 template <typename T, typename F>
WithContext(F f,T * context)87 promise_detail::WithContext<T, F> WithContext(F f, T* context) {
88 return promise_detail::WithContext<T, F>(std::move(f), context);
89 }
90
91 } // namespace grpc_core
92
93 #endif // GRPC_SRC_CORE_LIB_PROMISE_CONTEXT_H
94