• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 // -----------------------------------------------------------------------------
18 // TODO: figure out a way to use libbase_ndk. This is currently not working
19 // because of missing apex availability. For now, we can use a copy of
20 // ScopeGuard which is very lean compared to unique_fd. This code has been
21 // copied verbatim from:
22 // https://cs.android.com/android/platform/superproject/+/master:system/libbase/include/android-base/scopeguard.h
23 
24 #pragma once
25 
26 #include <utility> // for std::move, std::forward
27 
28 namespace android {
29 namespace base {
30 
31 // ScopeGuard ensures that the specified functor is executed no matter how the
32 // current scope exits.
33 template <typename F> class ScopeGuard {
34 public:
ScopeGuard(F && f)35   ScopeGuard(F &&f) : f_(std::forward<F>(f)), active_(true) {}
36 
ScopeGuard(ScopeGuard && that)37   ScopeGuard(ScopeGuard &&that) noexcept
38       : f_(std::move(that.f_)), active_(that.active_) {
39     that.active_ = false;
40   }
41 
42   template <typename Functor>
ScopeGuard(ScopeGuard<Functor> && that)43   ScopeGuard(ScopeGuard<Functor> &&that)
44       : f_(std::move(that.f_)), active_(that.active_) {
45     that.active_ = false;
46   }
47 
~ScopeGuard()48   ~ScopeGuard() {
49     if (active_)
50       f_();
51   }
52 
53   ScopeGuard() = delete;
54   ScopeGuard(const ScopeGuard &) = delete;
55   void operator=(const ScopeGuard &) = delete;
56   void operator=(ScopeGuard &&that) = delete;
57 
Disable()58   void Disable() { active_ = false; }
59 
active()60   bool active() const { return active_; }
61 
62 private:
63   template <typename Functor> friend class ScopeGuard;
64 
65   F f_;
66   bool active_;
67 };
68 
make_scope_guard(F && f)69 template <typename F> ScopeGuard<F> make_scope_guard(F &&f) {
70   return ScopeGuard<F>(std::forward<F>(f));
71 }
72 
73 } // namespace base
74 } // namespace android
75