#ifndef FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_
#define FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_
#include <atomic>
#include "flutter/fml/logging.h"
#include "flutter/fml/macros.h"
namespace fml {
namespace internal {
class RefCountedThreadSafeBase {
public:
void AddRef() const {
#ifndef NDEBUG
FML_DCHECK(!adoption_required_);
FML_DCHECK(!destruction_started_);
#endif
ref_count_.fetch_add(1u, std::memory_order_relaxed);
}
bool HasOneRef() const {
return ref_count_.load(std::memory_order_acquire) == 1u;
}
void AssertHasOneRef() const { FML_DCHECK(HasOneRef()); }
protected:
RefCountedThreadSafeBase();
~RefCountedThreadSafeBase();
bool Release() const {
#ifndef NDEBUG
FML_DCHECK(!adoption_required_);
FML_DCHECK(!destruction_started_);
#endif
FML_DCHECK(ref_count_.load(std::memory_order_acquire) != 0u);
if (ref_count_.fetch_sub(1u, std::memory_order_release) == 1u) {
std::atomic_thread_fence(std::memory_order_acquire);
#ifndef NDEBUG
destruction_started_ = true;
#endif
return true;
}
return false;
}
#ifndef NDEBUG
void Adopt() {
FML_DCHECK(adoption_required_);
adoption_required_ = false;
}
#endif
private:
mutable std::atomic_uint_fast32_t ref_count_;
#ifndef NDEBUG
mutable bool adoption_required_;
mutable bool destruction_started_;
#endif
FML_DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase);
};
inline RefCountedThreadSafeBase::RefCountedThreadSafeBase()
: ref_count_(1u)
#ifndef NDEBUG
,
adoption_required_(true),
destruction_started_(false)
#endif
{
}
inline RefCountedThreadSafeBase::~RefCountedThreadSafeBase() {
#ifndef NDEBUG
FML_DCHECK(!adoption_required_);
FML_DCHECK(destruction_started_);
#endif
}
}
}
#endif