Get the audio sync once per update in alffplay
[openal-soft.git] / common / intrusive_ptr.h
blob595c831da7b6679423d109ab4d964f545a4766e9
1 #ifndef INTRUSIVE_PTR_H
2 #define INTRUSIVE_PTR_H
4 #include "atomic.h"
5 #include "opthelpers.h"
8 namespace al {
10 template<typename T>
11 class intrusive_ref {
12 RefCount mRef{1u};
14 public:
15 unsigned int add_ref() noexcept { return IncrementRef(mRef); }
16 unsigned int release() noexcept
18 auto ref = DecrementRef(mRef);
19 if UNLIKELY(ref == 0)
20 delete static_cast<T*>(this);
21 return ref;
24 /**
25 * Release only if doing so would not bring the object to 0 references and
26 * delete it. Returns false if the object could not be released.
28 * NOTE: The caller is responsible for handling a failed release, as it
29 * means the object has no other references and needs to be be deleted
30 * somehow.
32 bool releaseIfNoDelete() noexcept
34 auto val = mRef.load(std::memory_order_acquire);
35 while(val > 1 && !mRef.compare_exchange_strong(val, val-1, std::memory_order_acq_rel))
37 /* val was updated with the current value on failure, so just try
38 * again.
42 return val >= 2;
47 template<typename T>
48 class intrusive_ptr {
49 T *mPtr{nullptr};
51 public:
52 intrusive_ptr() noexcept = default;
53 intrusive_ptr(const intrusive_ptr &rhs) noexcept : mPtr{rhs.mPtr}
54 { if(mPtr) mPtr->add_ref(); }
55 intrusive_ptr(intrusive_ptr&& rhs) noexcept : mPtr{rhs.mPtr}
56 { rhs.mPtr = nullptr; }
57 intrusive_ptr(std::nullptr_t) noexcept { }
58 explicit intrusive_ptr(T *ptr) noexcept : mPtr{ptr} { }
59 ~intrusive_ptr() { if(mPtr) mPtr->release(); }
61 intrusive_ptr& operator=(const intrusive_ptr &rhs) noexcept
63 if(rhs.mPtr) rhs.mPtr->add_ref();
64 if(mPtr) mPtr->release();
65 mPtr = rhs.mPtr;
66 return *this;
68 intrusive_ptr& operator=(intrusive_ptr&& rhs) noexcept
70 if(mPtr)
71 mPtr->release();
72 mPtr = rhs.mPtr;
73 rhs.mPtr = nullptr;
74 return *this;
77 operator bool() const noexcept { return mPtr != nullptr; }
79 T& operator*() const noexcept { return *mPtr; }
80 T* operator->() const noexcept { return mPtr; }
81 T* get() const noexcept { return mPtr; }
83 void reset() noexcept
85 if(mPtr)
86 mPtr->release();
87 mPtr = nullptr;
90 T* release() noexcept
92 T *ret{mPtr};
93 mPtr = nullptr;
94 return ret;
97 void swap(intrusive_ptr &rhs) noexcept { std::swap(mPtr, rhs.mPtr); }
98 void swap(intrusive_ptr&& rhs) noexcept { std::swap(mPtr, rhs.mPtr); }
101 #define AL_DECL_OP(op) \
102 template<typename T> \
103 inline bool operator op(const intrusive_ptr<T> &lhs, const T *rhs) noexcept \
104 { return lhs.get() op rhs; } \
105 template<typename T> \
106 inline bool operator op(const T *lhs, const intrusive_ptr<T> &rhs) noexcept \
107 { return lhs op rhs.get(); }
109 AL_DECL_OP(==)
110 AL_DECL_OP(!=)
111 AL_DECL_OP(<=)
112 AL_DECL_OP(>=)
113 AL_DECL_OP(<)
114 AL_DECL_OP(>)
116 #undef AL_DECL_OP
118 } // namespace al
120 #endif /* INTRUSIVE_PTR_H */