#ifndef WeakObjCPtr_h
#define WeakObjCPtr_h
#include <objc/runtime.h>
#include <type_traits>
#include <wtf/RetainPtr.h>
#if __has_include(<objc/objc-internal.h>)
#include <objc/objc-internal.h>
#else
extern "C" {
id objc_loadWeakRetained(id*);
id objc_initWeak(id*, id);
void objc_destroyWeak(id*);
void objc_copyWeak(id*, id*);
void objc_moveWeak(id*, id*);
}
#endif
namespace WebKit {
template<typename T> class WeakObjCPtr {
public:
typedef typename std::remove_pointer<T>::type ValueType;
WeakObjCPtr()
: m_weakReference(nullptr)
{
}
WeakObjCPtr(ValueType *ptr)
{
objc_initWeak(&m_weakReference, ptr);
}
WeakObjCPtr(const WeakObjCPtr& other)
{
objc_copyWeak(&m_weakReference, const_cast<id*>(&other.m_weakReference));
}
WeakObjCPtr(WeakObjCPtr&& other)
{
objc_moveWeak(&m_weakReference, &other.m_weakReference);
}
~WeakObjCPtr()
{
objc_destroyWeak(&m_weakReference);
}
WeakObjCPtr& operator=(ValueType *ptr)
{
objc_storeWeak(&m_weakReference, ptr);
return *this;
}
bool operator!() const
{
return !get();
}
RetainPtr<ValueType> get() const
{
return adoptNS(objc_loadWeakRetained(const_cast<id*>(&m_weakReference)));
}
ValueType *getAutoreleased() const
{
return static_cast<ValueType *>(objc_loadWeak(const_cast<id*>(&m_weakReference)));
}
explicit operator ValueType *() const { return getAutoreleased(); }
private:
id m_weakReference;
};
}
#endif // WeakObjCPtr_h