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