summaryrefslogtreecommitdiff
path: root/deimos/core/status.h
blob: bf34833990b87e9db84d27b2252daa765b9fdb1d (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
#pragma once

#include "deimos/core/base.h"

namespace deimos
{

// NOLINTNEXTLINE(performance-enum-size)
enum class StatusCode : uint32_t
{
    kOk = 0,
    kUnknown,
    kInvalidArgument,
    kUnimplemented,
    kInternal,
};

class Status
{
    uintptr_t m_rep;

    constexpr bool IsInline() const
    {
        return (m_rep & 1U) == 1U;
    }

    static constexpr uintptr_t CodeToRep(StatusCode code)
    {
        return ((uint32_t)code << 1U) | 1U;
    }

    void Ref() const;
    void Unref() const;
    StatusCode RepCode() const;

public:
    constexpr Status() : Status(StatusCode::kOk) {}
    constexpr explicit Status(StatusCode code) : m_rep{CodeToRep(code)} {}
    Status(StatusCode code, StringView message);

    Status(const Status& other) : m_rep{other.m_rep}
    {
        Ref();
    }

    Status(Status&& other) : m_rep{std::exchange(other.m_rep, 0U)} {}

    Status& operator=(const Status& other)
    {
        if (this != &other)
        {
            Unref();
            this->m_rep = other.m_rep;
            Ref();
        }
        return *this;
    }

    Status& operator=(Status&& other)
    {
        if (this != &other)
        {
            Unref();
            this->m_rep = std::exchange(other.m_rep, 0U);

        }
        return *this;
    }

    ~Status()
    {
        Unref();
    }

    constexpr bool ok() const { return m_rep == CodeToRep(StatusCode::kOk); }

    StatusCode code() const
    {
        if (IsInline()) { return (StatusCode)(m_rep >> 1U); }
        return RepCode();
    }
};

inline Status UnknownError(StringView message = {})
{
    return Status(StatusCode::kUnknown, message);
}

inline Status InvalidArgumentError(StringView message = {})
{
    return Status(StatusCode::kInvalidArgument, message);
}

inline Status UnimplementedError(StringView message = {})
{
    return Status(StatusCode::kUnimplemented, message);
}

inline Status InternalError(StringView message = {})
{
    return Status(StatusCode::kInternal, message);
}

} // namespace deimos