libjxl

FORK: libjxl patches used on blog
git clone https://git.neptards.moe/blog/libjxl.git
Log | Files | Refs | Submodules | README | LICENSE

scope_guard.h (1231B)


      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.
     22   ScopeGuard(ScopeGuard &&other) : callback_(std::move(other.callback_)) {
     23     other.armed_ = false;
     24   }
     25 
     26   template <typename CallbackParam>
     27   ScopeGuard(CallbackParam &&callback, bool armed)
     28       : callback_(std::forward<CallbackParam>(callback)), armed_(armed) {}
     29 
     30   ~ScopeGuard() {
     31     if (armed_) callback_();
     32   }
     33 
     34   void Disarm() { armed_ = false; }
     35 
     36  private:
     37   Callback callback_;
     38   bool armed_;
     39 };
     40 
     41 template <typename Callback>
     42 ScopeGuard<Callback> MakeScopeGuard(Callback &&callback) {
     43   return ScopeGuard<Callback>{std::forward<Callback>(callback), true};
     44 }
     45 
     46 }  // namespace jxl
     47 
     48 #endif  // LIB_JXL_BASE_SCOPE_GUARD_H_