summaryrefslogtreecommitdiffhomepage
path: root/src/kernel/NeKit/ErrorOr.h
blob: 4289a890eabd0da46bd6fb353952b7a240b0a1b4 (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
// 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_ERROROR_H
#define NEKIT_ERROROR_H

#include <NeKit/Config.h>
#include <NeKit/Ref.h>

namespace Kernel {
/// ================================================================================
/// @brief ErrorOr class for error handling.
/// ================================================================================
template <class T>
class ErrorOr final {
 public:
  ErrorOr()  = default;
  ~ErrorOr() = default;

 public:
  using RefType = Ref<T>;
  using Type    = T;
  using TypePtr = T*;

  explicit ErrorOr(ErrorT err) : mRef(Type()), mId(err) {
    // TODO: Invalidate the value of mRef to make computational evaluations false.
    mRef = nullptr;
  }

  explicit ErrorOr(nullPtr) {}
  explicit ErrorOr(TypePtr klass) : mRef(klass) {}
  explicit ErrorOr(Type klass) : mRef(klass) {}

  ErrorOr& operator=(const ErrorOr&) = default;
  ErrorOr(const ErrorOr&)            = default;

  ErrorOr& operator=(const RefType& ref) {
    mRef = ref;
    return *this;
  }

  const Type& Value() { return mRef.TryLeak(); }

  RefType& Leak() { return mRef; }

  ErrorT Error() { return mId; }

  /// @note DO NOT MAKE THIS EXPLICIT! IT WILL BREAK THE COMPILATION.
  explicit operator bool() { return mRef.Leak(); }

  BOOL HasError() { return this->mId < kErrorSuccess; }

 private:
  RefType mRef;
  ErrorT  mId{0};
};

using ErrorOrAny = ErrorOr<voidPtr>;

}  // namespace Kernel

#endif