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