summaryrefslogtreecommitdiffhomepage
path: root/src/kernel/NeKit/Ref.h
blob: 25706437eb6554e2eb963fd04615b4632aa2d04c (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

/* ========================================

  Copyright (C) 2024-2025, Amlal El Mahrouss, licensed under the Apache 2.0 license.

======================================== */

#ifndef _NEKIT_REF_H_
#define _NEKIT_REF_H_

#include <CompilerKit/CompilerKit.h>
#include <KernelKit/HeapMgr.h>
#include <NeKit/Config.h>
#include <NeKit/KernelPanic.h>
#include <NeKit/Vettable.h>

namespace Kernel {
/// =========================================================== ///
/// @brief Reference wrapper class.                          ///
/// =========================================================== ///
template <typename T>
class Ref final {
 public:
  explicit Ref() = default;
  ~Ref()         = default;

 public:
  using Type = T;

  Ref(Type* cls) : fClass(*cls) {}
  Ref(Type cls) : fClass(cls) {}

  Ref& operator=(Type ref) {
    fClass = ref;
    return *this;
  }

  NE_COPY_DEFAULT(Ref)

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

  Type& Leak() { return fClass; }

  Type& TryLeak() { return fClass; }

  Type operator*() { return fClass; }

  explicit operator bool() { return Vettable<Type>::kValue; }
  bool     operator!() { return !Vettable<Type>::kValue; }

 private:
  Type fClass;
};

template <typename T>
class NonNullRef final {
 public:
  using RefType = Ref<T>;
  using Type    = T;

  NonNullRef()        = delete;
  NonNullRef(nullPtr) = delete;

  NonNullRef(Type* ref) : fRef(ref) { MUST_PASS(ref); }
  NonNullRef(RefType ref) : fRef(ref) { MUST_PASS(ref); }

  Ref<T>& operator->() {
    MUST_PASS(fRef);
    return fRef;
  }

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

 private:
  Ref<T> fRef{};
};

using RefAny        = Ref<Any>;
using NonNullRefAny = NonNullRef<Any>;
}  // namespace Kernel

#endif  // ifndef _NEKIT_REF_H_