| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- // This file is part of Desktop App Toolkit,
- // a set of libraries for developing nice desktop applications.
- //
- // For license and copyright information please follow this link:
- // https://github.com/desktop-app/legal/blob/master/LEGAL
- //
- #pragma once
- #include "base/algorithm.h"
- #include <atomic>
- namespace base {
- class binary_guard {
- public:
- binary_guard() = default;
- binary_guard(binary_guard &&other);
- binary_guard &operator=(binary_guard &&other);
- ~binary_guard();
- binary_guard &operator=(std::nullptr_t);
- bool alive() const;
- binary_guard make_guard();
- explicit operator bool() const;
- private:
- void destroy();
- std::atomic<bool> *_bothAlive = nullptr;
- };
- inline binary_guard::binary_guard(binary_guard &&other)
- : _bothAlive(base::take(other._bothAlive)) {
- }
- inline binary_guard &binary_guard::operator=(binary_guard &&other) {
- if (this != &other) {
- destroy();
- _bothAlive = base::take(other._bothAlive);
- }
- return *this;
- }
- inline binary_guard::~binary_guard() {
- destroy();
- }
- inline binary_guard &binary_guard::operator=(std::nullptr_t) {
- destroy();
- return *this;
- }
- inline binary_guard::operator bool() const {
- return alive();
- }
- inline bool binary_guard::alive() const {
- return _bothAlive && _bothAlive->load();
- }
- inline void binary_guard::destroy() {
- if (const auto both = base::take(_bothAlive)) {
- auto old = true;
- if (!both->compare_exchange_strong(old, false)) {
- delete both;
- }
- }
- }
- inline binary_guard binary_guard::make_guard() {
- destroy();
- auto result = binary_guard();
- _bothAlive = result._bothAlive = new std::atomic<bool>(true);
- return result;
- }
- } // namespace base
- namespace crl {
- template <typename T, typename Enable>
- struct guard_traits;
- template <>
- struct guard_traits<base::binary_guard, void> {
- static base::binary_guard create(base::binary_guard value) {
- return value;
- }
- static bool check(const base::binary_guard &guard) {
- return guard.alive();
- }
- };
- } // namespace crl
|