From f138311d2d2e0cc9ba0496d523bb46f2c1c9fb73 Mon Sep 17 00:00:00 2001 From: rtk0c Date: Wed, 20 Sep 2023 23:58:58 -0700 Subject: Copy from the PlasticSCM repo, replace vendored glm wtih conan --- source/10-common/ScopeGuard.hpp | 60 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 source/10-common/ScopeGuard.hpp (limited to 'source/10-common/ScopeGuard.hpp') diff --git a/source/10-common/ScopeGuard.hpp b/source/10-common/ScopeGuard.hpp new file mode 100644 index 0000000..4e1a348 --- /dev/null +++ b/source/10-common/ScopeGuard.hpp @@ -0,0 +1,60 @@ +#pragma once + +#include "Macros.hpp" + +#include + +template +class ScopeGuard { +private: + TCleanupFunc mFunc; + bool mDismissed = false; + +public: + /// Specifically left this implicit so that constructs like + /// \code + /// ScopeGuard sg = [&]() { res.Cleanup(); }; + /// \endcode + /// would work. It is highly discourage and unlikely that one would want to use ScopeGuard as a function + /// parameter, so the normal argument that implicit conversion are harmful doesn't really apply here. + // Deliberately not explicit to allow usages like: ScopeGuard var = lambda; + ScopeGuard(TCleanupFunc&& function) noexcept + : mFunc{ std::move(function) } { + } + + ~ScopeGuard() noexcept { + if (!mDismissed) { + mFunc(); + } + } + + ScopeGuard(const ScopeGuard&) = delete; + ScopeGuard& operator=(const ScopeGuard&) = delete; + + ScopeGuard(ScopeGuard&& that) noexcept + : mFunc{ std::move(that.mFunc) } { + that.Cancel(); + } + + ScopeGuard& operator=(ScopeGuard&& that) noexcept { + if (!mDismissed) { + mFunc(); + } + this->mFunc = std::move(that.mFunc); + this->cancelled = std::exchange(that.cancelled, true); + } + + void Dismiss() noexcept { + mDismissed = true; + } +}; + +template +auto GuardDeletion(T* ptr) { + return ScopeGuard([ptr]() { + delete ptr; + }); +} + +#define SCOPE_GUARD(name) ScopeGuard name = [&]() +#define DEFER ScopeGuard UNIQUE_NAME(scopeGuard) = [&]() -- cgit v1.2.3-70-g09d2