summaryrefslogtreecommitdiffhomepage
path: root/dev/kernel/NeKit/Ref.h
blob: 9c244be5dba3b40c0e3b2eb3daf6262f2247d6dd (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

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

  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/Defines.h>
#include <NeKit/KernelPanic.h>

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

 public:
  Ref(T* cls) : fClass(*cls) {}
  Ref(T cls) : fClass(cls) {}

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

  NE_COPY_DEFAULT(Ref)

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

  T& Leak() noexcept { return fClass; }

  T& TryLeak() noexcept { return fClass; }

  T operator*() { return fClass; }

  operator bool() noexcept { return true; }

 private:
  T fClass;
};

template <typename T>
class NonNullRef final {
 public:
  NonNullRef()        = delete;
  NonNullRef(nullPtr) = delete;

  NonNullRef(T* 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)            = default;

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

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

#endif  // ifndef _NEKIT_REF_H_