1 /*
2  * Copyright (C) 2017 The Android Open Source Project
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 namespace slicer {
20 
21 // A simple and lightweight scope guard and macro
22 // (inspired by Andrei Alexandrescu's C++11 Scope Guard)
23 //
24 // Here is how it's used:
25 //
26 //  FILE* file = std::fopen(...);
27 //  SLICER_SCOPE_EXIT {
28 //      std::fclose(file);
29 //  };
30 //
31 // "file" will be closed at the end of the enclosing scope,
32 //  regardless of how the scope is exited
33 //
34 class ScopeGuardHelper
35 {
36     template<class T>
37     class ScopeGuard
38     {
39     public:
ScopeGuard(T closure)40         explicit ScopeGuard(T closure) :
41             closure_(std::move(closure))
42         {
43         }
44 
~ScopeGuard()45         ~ScopeGuard()
46         {
47             closure_();
48         }
49 
50         // move constructor only
51         ScopeGuard(ScopeGuard&&) = default;
52         ScopeGuard(const ScopeGuard&) = delete;
53         ScopeGuard& operator=(const ScopeGuard&) = delete;
54         ScopeGuard& operator=(ScopeGuard&&) = delete;
55 
56     private:
57         T closure_;
58     };
59 
60 public:
61     template<class T>
62     ScopeGuard<T> operator<<(T closure)
63     {
64         return ScopeGuard<T>(std::move(closure));
65     }
66 };
67 
68 #define SLICER_SG_MACRO_CONCAT2(a, b) a ## b
69 #define SLICER_SG_MACRO_CONCAT(a, b) SLICER_SG_MACRO_CONCAT2(a, b)
70 #define SLICER_SG_ANONYMOUS(prefix)  SLICER_SG_MACRO_CONCAT(prefix, __COUNTER__)
71 
72 #define SLICER_SCOPE_EXIT \
73     auto SLICER_SG_ANONYMOUS(_scope_guard_) = slicer::ScopeGuardHelper() << [&]()
74 
75 } // namespace slicer
76 
77