git subrepo pull (merge) --force deps/libchdr
[pcsx_rearmed.git] / deps / libchdr / deps / zstd-1.5.5 / contrib / pzstd / utils / ScopeGuard.h
CommitLineData
648db22b 1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 */
9#pragma once
10
11#include <utility>
12
13namespace pzstd {
14
15/**
16 * Dismissable scope guard.
17 * `Function` must be callable and take no parameters.
18 * Unless `dismiss()` is called, the callable is executed upon destruction of
19 * `ScopeGuard`.
20 *
21 * Example:
22 *
23 * auto guard = makeScopeGuard([&] { cleanup(); });
24 */
25template <typename Function>
26class ScopeGuard {
27 Function function;
28 bool dismissed;
29
30 public:
31 explicit ScopeGuard(Function&& function)
32 : function(std::move(function)), dismissed(false) {}
33
34 void dismiss() {
35 dismissed = true;
36 }
37
38 ~ScopeGuard() noexcept {
39 if (!dismissed) {
40 function();
41 }
42 }
43};
44
45/// Creates a scope guard from `function`.
46template <typename Function>
47ScopeGuard<Function> makeScopeGuard(Function&& function) {
48 return ScopeGuard<Function>(std::forward<Function>(function));
49}
50}