summaryrefslogtreecommitdiffhomepage
path: root/src/kernel/NeKit/Ref.h
blob: 2c6696113447fa231e37cc640a208f59d0341e21 (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
97
98
// Copyright 2024-2025, Amlal El Mahrouss (amlal@nekernel.org)
// Licensed under the Apache License, Version 2.0 (see LICENSE file)
// Official repository: https://github.com/nekernel-org/nekernel

#ifndef _NEKIT_REF_H_
#define _NEKIT_REF_H_

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

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

 public:
  using Type      = T;
  using ConstType = const T&;
  using RefType   = T&;

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

  Ref& operator=(nullPtr) { return *this; }

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

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

  NE_COPY_DEFAULT(Ref)

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

  Type& Leak() { return fClass; }

  Type& TryLeak() {
    MUST_PASS(fClass);
    return fClass;
  }

  Type operator*() { return fClass; }

  explicit operator bool() {
    if constexpr (IsVettable<Type>) {
      return Type::kVettable;
    } else {
      return false;
    }
  }

 private:
  Type fClass;
};

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

  NonNullRef() = delete;

  NonNullRef(Type* ref) : fRef(ref) {}
  NonNullRef(nullPtr ref) = delete;
  NonNullRef(RefType ref) : fRef(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_