aboutsummaryrefslogtreecommitdiff
path: root/include/Result.hpp
blob: 86ae176016fd02a7326b9043ba6b9687ee232528 (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
#pragma once

#include <string>
#include <cassert>

namespace amalgine
{
    template <typename T>
    class Result
    {
    public:
        static Result<T> Ok(T data)
        {
            Result<T> result(std::move(data));
            return result;
        }
        
        static Result<T> Err(const std::string &errorMsg, int errorCode = -1)
        {
            Result<T> result;
            result.errorMsg = errorMsg;
            result.errorCode = errorCode;
            return result;
        }
        
        template <typename OtherType>
        static Result<T> Err(const Result<OtherType> &otherResult)
        {
            Result<T> result;
            result.errorMsg = otherResult.getErrorMsg();
            result.errorCode = otherResult.getErrorCode();
            return result;
        }
        
        bool isOk() const { return errorCode == 0; }
        bool isErr() const { return !isOk(); }
        operator bool() const { return isOk(); }
        T& unwrap()
        {
            assert(isOk());
            return data;
        }

        T* operator -> () {
            assert(isOk());
            return &data;
        }
        
        const std::string& getErrorMsg() const { return errorMsg; }
        int getErrorCode() const { return errorCode; }
    private:
        Result() {}
        Result(T data) : data(std::move(data)), errorCode(0) {}
    private:
        T data;
        int errorCode;
        std::string errorMsg;
    };
}