-
Notifications
You must be signed in to change notification settings - Fork 0
/
status.h
92 lines (72 loc) · 1.88 KB
/
status.h
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
#ifndef __STATUS_H__
#define __STATUS_H__
#include <optional>
#include <stdexcept>
#include <string>
#include <variant>
namespace ette {
enum class StatusCode {
kOk,
kHeaderNoMagicNumber,
kHeaderInvalidAlgorithm,
kHeaderInvalidPlaintextSize,
kHeaderInvalidIvSize,
kInvalidKeySize,
kInvalidKey,
kInvalidDataSize,
kInvalidIvSize,
kUnknownError,
};
class Error {
public:
Error(StatusCode code, const std::string& message)
: code_(code), message_(message) {}
StatusCode code() const { return code_; }
const std::string& message() const { return message_; }
private:
StatusCode code_;
std::string message_;
};
template <typename T>
class Status {
public:
Status(T value) : status_(std::move(value)) {}
Status(StatusCode code, const std::string& message)
: status_(Error(code, message)) {}
bool ok() const { return std::holds_alternative<T>(status_); }
const T& value() const {
if (!ok()) {
throw std::runtime_error("Bad access to value");
}
return std::get<T>(status_);
}
const Error& error() const {
if (ok()) {
throw std::runtime_error("Bad access to error");
}
return std::get<Error>(status_);
}
const T& operator*() const { return value(); }
private:
std::variant<T, Error> status_;
};
template <>
class Status<void> {
public:
Status() {}
Status(StatusCode code, const std::string& message)
: status_(Error(code, message)) {}
bool ok() const {
return status_.has_value() && status_.value().code() == StatusCode::kOk;
}
const Error& error() const {
if (ok()) {
throw std::runtime_error("Bad access to error");
}
return status_.value();
}
private:
std::optional<Error> status_;
};
} // namespace ette
#endif // __STATUS_H__