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