aboutsummaryrefslogtreecommitdiff
path: root/include/Result.hpp
blob: e8f4d12d96fc2ea00c83c13d8a43ef2b0fe49f6b (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
#ifndef SIBS_RESULT_HPP
#define SIBS_RESULT_HPP

#include <cassert>
#include <string>

namespace sibs
{
	template <typename T>
	class Result
	{
	public:
		static Result Ok(const T &value)
		{
			Result result(value);
			result.errorCode = 0;
			return result;
		}

        template <typename OtherType>
        static Result Err(const Result<OtherType> &other)
        {
            Result result;
            result.errMsg = other.getErrMsg();
            result.errorCode = other.getErrorCode();
            return result;
        }

		static Result Err(const std::string &errMsg, int errorCode = 1)
		{
			Result result;
			result.errMsg = errMsg;
			result.errorCode = errorCode;
			return result;
		}

		bool isOk() const { return !errorCode; }
		bool isErr() const { return errorCode; }

		T& unwrap()
		{
			assert(isOk());
			return value;
		}

		const std::string &getErrMsg() const
		{
			assert(isErr());
			return errMsg;
		}

        int getErrorCode() const
        {
            return errorCode;
        }

		operator bool () { return isOk(); }
	private:
		Result(const T &_value = T()) : value(_value) {}
	private:
		T value;
		std::string errMsg;
		int errorCode;
	};
}

#endif //SIBS_RESULT_HPP