blob: 69217ed2f68094a2eb886cd5ae315aa3ea5e5560 [file]
// Copyright 2017 The PDFium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CORE_FXCRT_AUTORESTORER_H_
#define CORE_FXCRT_AUTORESTORER_H_
#include <type_traits>
#include <utility>
#include "core/fxcrt/fx_memory.h"
#include "core/fxcrt/unowned_ptr.h"
namespace fxcrt {
template <typename T>
class [[maybe_unused, nodiscard]] AutoRestorer {
public:
FX_STACK_ALLOCATED();
explicit AutoRestorer(T* location)
: location_(location), old_value_(*location) {}
template <typename U>
requires std::is_assignable_v<T&, U>
AutoRestorer(T* location, U&& new_value)
: location_(location),
old_value_(std::exchange(*location, std::forward<U>(new_value))) {}
~AutoRestorer() {
if (location_) {
*location_ = std::move(old_value_);
}
}
void AbandonRestoration() { location_ = nullptr; }
private:
UnownedPtr<T> location_;
T old_value_;
};
} // namespace fxcrt
using fxcrt::AutoRestorer;
#endif // CORE_FXCRT_AUTORESTORER_H_