1 // Copyright 2021 The Abseil 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 // 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,
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 ABSL_CLEANUP_INTERNAL_CLEANUP_H_
16 #define ABSL_CLEANUP_INTERNAL_CLEANUP_H_
17
18 #include <type_traits>
19 #include <utility>
20
21 #include "absl/base/internal/invoke.h"
22 #include "absl/base/thread_annotations.h"
23 #include "absl/utility/utility.h"
24
25 namespace absl {
26 ABSL_NAMESPACE_BEGIN
27
28 namespace cleanup_internal {
29
30 struct Tag {};
31
32 template <typename Arg, typename... Args>
WasDeduced()33 constexpr bool WasDeduced() {
34 return (std::is_same<cleanup_internal::Tag, Arg>::value) &&
35 (sizeof...(Args) == 0);
36 }
37
38 template <typename Callback>
ReturnsVoid()39 constexpr bool ReturnsVoid() {
40 return (std::is_same<base_internal::invoke_result_t<Callback>, void>::value);
41 }
42
43 template <typename Callback>
44 class Storage {
45 public:
46 Storage() = delete;
47
Storage(Callback callback,bool is_callback_engaged)48 Storage(Callback callback, bool is_callback_engaged)
49 : callback_(std::move(callback)),
50 is_callback_engaged_(is_callback_engaged) {}
51
Storage(Storage && other)52 Storage(Storage&& other)
53 : callback_(std::move(other.callback_)),
54 is_callback_engaged_(
55 absl::exchange(other.is_callback_engaged_, false)) {}
56
57 Storage(const Storage& other) = delete;
58
59 Storage& operator=(Storage&& other) = delete;
60
61 Storage& operator=(const Storage& other) = delete;
62
IsCallbackEngaged()63 bool IsCallbackEngaged() const { return is_callback_engaged_; }
64
DisengageCallback()65 void DisengageCallback() { is_callback_engaged_ = false; }
66
InvokeCallback()67 void InvokeCallback() ABSL_NO_THREAD_SAFETY_ANALYSIS {
68 std::move(callback_)();
69 }
70
71 private:
72 Callback callback_;
73 bool is_callback_engaged_;
74 };
75
76 } // namespace cleanup_internal
77
78 ABSL_NAMESPACE_END
79 } // namespace absl
80
81 #endif // ABSL_CLEANUP_INTERNAL_CLEANUP_H_
82