// Copyright 2024-2025, Amlal El Mahrouss (amlal@nekernel.org) // Licensed under the Apache License, Version 2.0 (See accompanying // file LICENSE or copy at http://www.apache.org/licenses/LICENSE-2.0) // Official repository: https://github.com/ne-foss-org/nectar #ifndef NECTAR_COMPILERKIT_REF_H #define NECTAR_COMPILERKIT_REF_H #include namespace CompilerKit { /// @author Amlal El Mahrouss /// @brief Reference holder class, refers to a pointer of data in static memory. template class StrongRef { public: StrongRef() = default; virtual ~StrongRef() { if (mStrong) { MUST_PASS(mClass); if (mClass) delete mClass; mClass = nullptr; } } NECTAR_COPY_DEFAULT(StrongRef) using Type = T; protected: StrongRef(Type* cls, const bool strong) : mClass(cls), mStrong(strong) {} public: StrongRef(Type* cls) : mClass(cls), mStrong(true) {} StrongRef& operator=(Type* ref) { mClass = ref; return *this; } public: Type* operator->() const { return mClass; } Type* Leak() { return mClass; } Type* operator*() { return mClass; } bool IsStrong() const { return mStrong; } explicit operator bool() { return mClass != nullptr; } private: Type* mClass{nullptr}; bool mStrong{false}; }; template class WeakRef final : public StrongRef { public: WeakRef() = delete; ~WeakRef() = default; NECTAR_COPY_DEFAULT(WeakRef) public: using Type = T; WeakRef(Type* cls) : StrongRef(cls, false) {} }; /// @author Amlal El Mahrouss /// @brief Non null reference holder class, refers to a pointer of data in static memory. template class NonNullRef final { public: explicit NonNullRef() = delete; NonNullRef(Type* ref) : mRef(ref, true) {} StrongRef& operator->() { MUST_PASS(mRef); return mRef; } NonNullRef& operator=(const NonNullRef& ref) = delete; NonNullRef(const NonNullRef& ref) = default; private: StrongRef mRef{nullptr}; }; using StrongAny = StrongRef; using WeakAny = WeakRef; } // namespace CompilerKit #endif // NECTAR_COMPILERKIT_REF_H