constexpr_pow
[folly.git] / folly / ScopeGuard.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <cstddef>
20 #include <functional>
21 #include <new>
22 #include <type_traits>
23 #include <utility>
24
25 #include <folly/Portability.h>
26 #include <folly/Preprocessor.h>
27 #include <folly/UncaughtExceptions.h>
28
29 namespace folly {
30
31 /**
32  * ScopeGuard is a general implementation of the "Initialization is
33  * Resource Acquisition" idiom.  Basically, it guarantees that a function
34  * is executed upon leaving the currrent scope unless otherwise told.
35  *
36  * The makeGuard() function is used to create a new ScopeGuard object.
37  * It can be instantiated with a lambda function, a std::function<void()>,
38  * a functor, or a void(*)() function pointer.
39  *
40  *
41  * Usage example: Add a friend to memory if and only if it is also added
42  * to the db.
43  *
44  * void User::addFriend(User& newFriend) {
45  *   // add the friend to memory
46  *   friends_.push_back(&newFriend);
47  *
48  *   // If the db insertion that follows fails, we should
49  *   // remove it from memory.
50  *   // (You could also declare this as "auto guard = makeGuard(...)")
51  *   ScopeGuard guard = makeGuard([&] { friends_.pop_back(); });
52  *
53  *   // this will throw an exception upon error, which
54  *   // makes the ScopeGuard execute UserCont::pop_back()
55  *   // once the Guard's destructor is called.
56  *   db_->addFriend(GetName(), newFriend.GetName());
57  *
58  *   // an exception was not thrown, so don't execute
59  *   // the Guard.
60  *   guard.dismiss();
61  * }
62  *
63  * Examine ScopeGuardTest.cpp for some more sample usage.
64  *
65  * Stolen from:
66  *   Andrei's and Petru Marginean's CUJ article:
67  *     http://drdobbs.com/184403758
68  *   and the loki library:
69  *     http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer
70  *   and triendl.kj article:
71  *     http://www.codeproject.com/KB/cpp/scope_guard.aspx
72  */
73 class ScopeGuardImplBase {
74  public:
75   void dismiss() noexcept {
76     dismissed_ = true;
77   }
78
79   template <typename T>
80   FOLLY_ALWAYS_INLINE static void runAndWarnAboutToCrashOnException(
81       T& function) noexcept {
82     try {
83       function();
84     } catch (...) {
85       warnAboutToCrash();
86       std::terminate();
87     }
88   }
89
90  protected:
91   ScopeGuardImplBase() noexcept : dismissed_(false) {}
92
93   static ScopeGuardImplBase makeEmptyScopeGuard() noexcept {
94     return ScopeGuardImplBase{};
95   }
96
97   template <typename T>
98   static const T& asConst(const T& t) noexcept {
99     return t;
100   }
101
102   bool dismissed_;
103
104  private:
105   static void warnAboutToCrash() noexcept;
106 };
107
108 template <typename FunctionType>
109 class ScopeGuardImpl : public ScopeGuardImplBase {
110  public:
111   explicit ScopeGuardImpl(FunctionType& fn) noexcept(
112       std::is_nothrow_copy_constructible<FunctionType>::value)
113       : ScopeGuardImpl(
114             asConst(fn),
115             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
116                          &fn)) {}
117
118   explicit ScopeGuardImpl(const FunctionType& fn) noexcept(
119       std::is_nothrow_copy_constructible<FunctionType>::value)
120       : ScopeGuardImpl(
121             fn,
122             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
123                          &fn)) {}
124
125   explicit ScopeGuardImpl(FunctionType&& fn) noexcept(
126       std::is_nothrow_move_constructible<FunctionType>::value)
127       : ScopeGuardImpl(
128             std::move_if_noexcept(fn),
129             makeFailsafe(std::is_nothrow_move_constructible<FunctionType>{},
130                          &fn)) {}
131
132   ScopeGuardImpl(ScopeGuardImpl&& other) noexcept(
133       std::is_nothrow_move_constructible<FunctionType>::value)
134       : function_(std::move_if_noexcept(other.function_)) {
135     // If the above line attempts a copy and the copy throws, other is
136     // left owning the cleanup action and will execute it (or not) depending
137     // on the value of other.dismissed_. The following lines only execute
138     // if the move/copy succeeded, in which case *this assumes ownership of
139     // the cleanup action and dismisses other.
140     dismissed_ = other.dismissed_;
141     other.dismissed_ = true;
142   }
143
144   ~ScopeGuardImpl() noexcept {
145     if (!dismissed_) {
146       execute();
147     }
148   }
149
150  private:
151   static ScopeGuardImplBase makeFailsafe(std::true_type, const void*) noexcept {
152     return makeEmptyScopeGuard();
153   }
154
155   template <typename Fn>
156   static auto makeFailsafe(std::false_type, Fn* fn) noexcept
157       -> ScopeGuardImpl<decltype(std::ref(*fn))> {
158     return ScopeGuardImpl<decltype(std::ref(*fn))>{std::ref(*fn)};
159   }
160
161   template <typename Fn>
162   explicit ScopeGuardImpl(Fn&& fn, ScopeGuardImplBase&& failsafe)
163       : ScopeGuardImplBase{}, function_(std::forward<Fn>(fn)) {
164     failsafe.dismiss();
165   }
166
167   void* operator new(std::size_t) = delete;
168
169   void execute() noexcept {
170     runAndWarnAboutToCrashOnException(function_);
171   }
172
173   FunctionType function_;
174 };
175
176 template <typename FunctionType>
177 ScopeGuardImpl<typename std::decay<FunctionType>::type>
178 makeGuard(FunctionType&& fn) noexcept(
179     std::is_nothrow_constructible<typename std::decay<FunctionType>::type,
180                                   FunctionType>::value) {
181   return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
182       std::forward<FunctionType>(fn));
183 }
184
185 /**
186  * This is largely unneeded if you just use auto for your guards.
187  */
188 typedef ScopeGuardImplBase&& ScopeGuard;
189
190 namespace detail {
191
192 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
193     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
194     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
195
196 /**
197  * ScopeGuard used for executing a function when leaving the current scope
198  * depending on the presence of a new uncaught exception.
199  *
200  * If the executeOnException template parameter is true, the function is
201  * executed if a new uncaught exception is present at the end of the scope.
202  * If the parameter is false, then the function is executed if no new uncaught
203  * exceptions are present at the end of the scope.
204  *
205  * Used to implement SCOPE_FAIL and SCOPE_SUCCESS below.
206  */
207 template <typename FunctionType, bool ExecuteOnException>
208 class ScopeGuardForNewException {
209  public:
210   explicit ScopeGuardForNewException(const FunctionType& fn) : function_(fn) {}
211
212   explicit ScopeGuardForNewException(FunctionType&& fn)
213       : function_(std::move(fn)) {}
214
215   ScopeGuardForNewException(ScopeGuardForNewException&& other) = default;
216
217   ~ScopeGuardForNewException() noexcept(ExecuteOnException) {
218     if (ExecuteOnException == (exceptionCounter_ < uncaught_exceptions())) {
219       if (ExecuteOnException) {
220         ScopeGuardImplBase::runAndWarnAboutToCrashOnException(function_);
221       } else {
222         function_();
223       }
224     }
225   }
226
227  private:
228   ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
229
230   void* operator new(std::size_t) = delete;
231
232   FunctionType function_;
233   int exceptionCounter_{uncaught_exceptions()};
234 };
235
236 /**
237  * Internal use for the macro SCOPE_FAIL below
238  */
239 enum class ScopeGuardOnFail {};
240
241 template <typename FunctionType>
242 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
243 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
244   return
245       ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
246       std::forward<FunctionType>(fn));
247 }
248
249 /**
250  * Internal use for the macro SCOPE_SUCCESS below
251  */
252 enum class ScopeGuardOnSuccess {};
253
254 template <typename FunctionType>
255 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
256 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
257   return
258       ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
259       std::forward<FunctionType>(fn));
260 }
261
262 #endif // native uncaught_exception() supported
263
264 /**
265  * Internal use for the macro SCOPE_EXIT below
266  */
267 enum class ScopeGuardOnExit {};
268
269 template <typename FunctionType>
270 ScopeGuardImpl<typename std::decay<FunctionType>::type>
271 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
272   return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
273       std::forward<FunctionType>(fn));
274 }
275 } // namespace detail
276
277 } // namespace folly
278
279 #define SCOPE_EXIT \
280   auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
281   = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
282
283 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
284     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
285     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
286 #define SCOPE_FAIL \
287   auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
288   = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
289
290 #define SCOPE_SUCCESS \
291   auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
292   = ::folly::detail::ScopeGuardOnSuccess() + [&]()
293 #endif // native uncaught_exception() supported