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