blob: 9e6f6f6ed0135e37d0019915b162f57e9ace7201 (
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
#pragma once
#include <AK/Assertions.h>
#include <LibC/errno_numbers.h>
enum KSuccessTag {
KSuccess
};
class KResult {
public:
explicit KResult(int negative_e)
: m_error(negative_e)
{
ASSERT(negative_e <= 0);
}
KResult(KSuccessTag)
: m_error(0)
{
}
operator int() const { return m_error; }
bool is_success() const { return m_error == ESUCCESS; }
bool is_error() const { return !is_success(); }
private:
template<typename T>
friend class KResultOr;
KResult() {}
int m_error { 0 };
};
template<typename T>
class alignas(T) KResultOr {
public:
KResultOr(KResult error)
: m_error(error)
, m_is_error(true)
{
}
KResultOr(T&& value)
{
new (&m_storage) T(move(value));
}
template<typename U>
KResultOr(U&& value)
{
new (&m_storage) T(move(value));
}
KResultOr(KResultOr&& other)
{
m_is_error = other.m_is_error;
if (m_is_error)
m_error = other.m_error;
else {
new (&m_storage) T(move(other.value()));
other.value().~T();
}
other.m_is_error = true;
other.m_error = KSuccess;
}
KResultOr& operator=(KResultOr&& other)
{
if (!m_is_error)
value().~T();
m_is_error = other.m_is_error;
if (m_is_error)
m_error = other.m_error;
else {
new (&m_storage) T(move(other.value()));
other.value().~T();
}
other.m_is_error = true;
other.m_error = KSuccess;
return *this;
}
~KResultOr()
{
if (!m_is_error)
value().~T();
}
bool is_error() const { return m_is_error; }
KResult error() const
{
ASSERT(m_is_error);
return m_error;
}
T& value()
{
ASSERT(!m_is_error);
return *reinterpret_cast<T*>(&m_storage);
}
const T& value() const
{
ASSERT(!m_is_error);
return *reinterpret_cast<T*>(&m_storage);
}
T release_value()
{
ASSERT(!m_is_error);
T released_value = *reinterpret_cast<T*>(&m_storage);
value().~T();
return released_value;
}
private:
alignas (T) char m_storage[sizeof(T)];
KResult m_error;
bool m_is_error { false };
};
|