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