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

#include <string>
#include <cassert>

namespace amalgine
{
    template <typename T>
    class Result
    {
    public:
        static Result<T> Ok(const T &data)
        {
            Result<T> result;
            result.data = data;
            result.errorCode = 0;
            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;
        }
        
        const std::string& getErrorMsg() const { return errorMsg; }
        int getErrorCode() const { return errorCode; }
    private:
        Result(){}
    private:
        T data;
        int errorCode;
        std::string errorMsg;
    };
}