summaryrefslogtreecommitdiffhomepage
path: root/include/CompilerKit/Ref.h
blob: 8690ad10b723fe26fd57b77d2edadf116fec6f9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// 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/nekernel-org/nectar

#ifndef NECTAR_COMPILERKIT_REF_H
#define NECTAR_COMPILERKIT_REF_H

#include <CompilerKit/Detail/Config.h>

namespace CompilerKit {
/// @author Amlal El Mahrouss
/// @brief Reference holder class, refers to a pointer of data in static memory.
template <typename T>
class StrongRef {
 public:
  StrongRef() = default;

  virtual ~StrongRef() {
    if (m_Strong) {
      MUST_PASS(m_Class);
      if (m_Class) delete m_Class;
      m_Class = nullptr;
    }
  }

  NECTAR_COPY_DEFAULT(StrongRef)

  using Type = T;

 protected:
  StrongRef(Type* cls, const bool strong) : m_Class(cls), m_Strong(strong) {}

 public:
  StrongRef(Type* cls) : m_Class(cls), m_Strong(true) {}

  StrongRef& operator=(Type* ref) {
    m_Class = ref;
    return *this;
  }

 public:
  Type* operator->() const { return m_Class; }

  Type* Leak() { return m_Class; }

  Type* operator*() { return m_Class; }

  bool IsStrong() const { return m_Strong; }

  explicit operator bool() { return m_Class != nullptr; }

 private:
  Type* m_Class{nullptr};
  bool  m_Strong{false};
};

template <typename T>
class WeakRef final : public StrongRef<T> {
 public:
  WeakRef()  = delete;
  ~WeakRef() = default;

  NECTAR_COPY_DEFAULT(WeakRef)

 public:
  using Type = T;

  WeakRef(Type* cls) : StrongRef<Type>(cls, false) {}
};

/// @author Amlal El Mahrouss
/// @brief Non null reference holder class, refers to a pointer of data in static memory.
template <typename Type>
class NonNullRef final {
 public:
  explicit NonNullRef() = delete;
  NonNullRef(Type* ref) : m_Ref(ref, true) {}

  StrongRef<Type>& operator->() {
    MUST_PASS(m_Ref);
    return m_Ref;
  }

  NonNullRef& operator=(const NonNullRef<Type>& ref) = delete;
  NonNullRef(const NonNullRef<Type>& ref)            = default;

 private:
  StrongRef<Type> m_Ref{nullptr};
};

using StrongAny = StrongRef<VoidPtr>;
using WeakAny   = WeakRef<VoidPtr>;
}  // namespace CompilerKit

#endif  // NECTAR_COMPILERKIT_REF_H