1 // Copyright (c) the JPEG XL Project Authors. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5 
6 #ifndef LIB_JXL_BASE_SCOPE_GUARD_H_
7 #define LIB_JXL_BASE_SCOPE_GUARD_H_
8 
9 #include <utility>
10 
11 namespace jxl {
12 
13 template <typename Callback>
14 class ScopeGuard {
15  public:
16   // Discourage unnecessary moves / copies.
17   ScopeGuard(const ScopeGuard &) = delete;
18   ScopeGuard &operator=(const ScopeGuard &) = delete;
19   ScopeGuard &operator=(ScopeGuard &&) = delete;
20 
21   // Pre-C++17 does not guarantee RVO -> require move constructor.
ScopeGuard(ScopeGuard && other)22   ScopeGuard(ScopeGuard &&other) : callback_(std::move(other.callback_)) {
23     other.armed_ = false;
24   }
25 
26   template <typename CallbackParam>
ScopeGuard(CallbackParam && callback)27   ScopeGuard(CallbackParam &&callback)
28       : callback_(std::forward<CallbackParam>(callback)), armed_(true) {}
29 
~ScopeGuard()30   ~ScopeGuard() {
31     if (armed_) callback_();
32   }
33 
Disarm()34   void Disarm() { armed_ = false; }
35 
36  private:
37   Callback callback_;
38   bool armed_;
39 };
40 
41 template <typename Callback>
MakeScopeGuard(Callback && callback)42 ScopeGuard<Callback> MakeScopeGuard(Callback &&callback) {
43   return {std::forward<Callback>(callback)};
44 }
45 
46 }  // namespace jxl
47 
48 #endif  // LIB_JXL_BASE_SCOPE_GUARD_H_
49