• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 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_EVENT_ENGINE_COMMON_CLOSURES_H
16 #define GRPC_SRC_CORE_LIB_EVENT_ENGINE_COMMON_CLOSURES_H
17 
18 #include <grpc/event_engine/event_engine.h>
19 #include <grpc/support/port_platform.h>
20 
21 #include <utility>
22 
23 #include "absl/functional/any_invocable.h"
24 
25 namespace grpc_event_engine {
26 namespace experimental {
27 
28 class AnyInvocableClosure : public EventEngine::Closure {
29  public:
AnyInvocableClosure(absl::AnyInvocable<void ()> cb)30   explicit AnyInvocableClosure(absl::AnyInvocable<void()> cb)
31       : cb_(std::move(cb)) {}
Run()32   void Run() override { cb_(); }
33 
34  private:
35   absl::AnyInvocable<void()> cb_;
36 };
37 
38 class SelfDeletingClosure : public EventEngine::Closure {
39  public:
40   // Creates a SelfDeletingClosure.
41   // The closure will be deleted after Run is called.
Create(absl::AnyInvocable<void ()> cb)42   static Closure* Create(absl::AnyInvocable<void()> cb) {
43     return new SelfDeletingClosure(std::move(cb), nullptr);
44   }
45   // Creates a SelfDeletingClosure with a custom destructor.
Create(absl::AnyInvocable<void ()> cb,absl::AnyInvocable<void ()> dest_cb)46   static Closure* Create(absl::AnyInvocable<void()> cb,
47                          absl::AnyInvocable<void()> dest_cb) {
48     return new SelfDeletingClosure(std::move(cb), std::move(dest_cb));
49   }
~SelfDeletingClosure()50   ~SelfDeletingClosure() override {
51     if (dest_cb_) dest_cb_();
52   };
53 
Run()54   void Run() override {
55     cb_();
56     delete this;
57   }
58 
59  private:
SelfDeletingClosure(absl::AnyInvocable<void ()> cb,absl::AnyInvocable<void ()> dest_cb)60   explicit SelfDeletingClosure(absl::AnyInvocable<void()> cb,
61                                absl::AnyInvocable<void()> dest_cb)
62       : cb_(std::move(cb)), dest_cb_(std::move(dest_cb)) {}
63   absl::AnyInvocable<void()> cb_;
64   absl::AnyInvocable<void()> dest_cb_;
65 };
66 
67 }  // namespace experimental
68 }  // namespace grpc_event_engine
69 
70 #endif  // GRPC_SRC_CORE_LIB_EVENT_ENGINE_COMMON_CLOSURES_H
71