1 /*
2  * Copyright (C) 2021 Huawei Device Co., Ltd.
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  *     http://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 
16 #ifndef SCOPE_GUARD_H
17 #define SCOPE_GUARD_H
18 
19 #include <functional>
20 
21 namespace OHOS {
22 /*
23  * The RAII feature is used to implement scope exit protection so that resources
24  * can be released and the closure action can be performed in a unified manner when
25  * the scope exits.
26  */
27 namespace Detail {
28 template<typename ExitAction>
29 class ScopeGuard {
30 public:
ScopeGuard(ExitAction && action)31     explicit ScopeGuard(ExitAction &&action) : action_(action), enable_(true) {}
~ScopeGuard()32     ~ScopeGuard()
33     {
34         if (enable_) {
35             action_();
36         }
37     }
38 
Disable()39     void Disable()
40     {
41         enable_ = false;
42     }
43 
44 private:
45     ExitAction action_;
46     bool enable_;
47 };
48 
49 struct ScopeExitGuardHelper {};
50 template<typename ExitAction>
51 static inline ScopeGuard<ExitAction> operator+(ScopeExitGuardHelper, ExitAction &&action)
52 {
53     return ScopeGuard<ExitAction>(std::forward<ExitAction>(action));
54 }
55 }
56 
57 #define ON_SCOPE_EXIT(id) \
58     auto onScopeExitGuard##id = Detail::ScopeExitGuardHelper{} + [ & ]
59 
60 #define CANCEL_SCOPE_EXIT_GUARD(id) \
61     onScopeExitGuard##id.Disable()
62 }
63 #endif
64