5701f243a754206e0261957c4a829433aa0076b3
[staging/windowmanager.git] / src / result.hpp
1 //
2 // Created by mfritzsc on 7/12/17.
3 //
4
5 #ifndef TMCAGLWM_RESULT_HPP
6 #define TMCAGLWM_RESULT_HPP
7
8 #include <experimental/optional>
9 #include <functional>
10
11 namespace wm {
12
13 using std::experimental::optional;
14 using std::experimental::nullopt;
15
16 // We only ever return a string as an error - so just parametrize
17 // this over result type T
18 template <typename T>
19 struct result {
20    char const *e;
21    optional<T> t;
22
23    bool is_ok() const { return this->t != nullopt; }
24    bool is_err() const { return this->e != nullptr; }
25
26    T unwrap() {
27       if (this->e != nullptr) {
28          throw std::logic_error(this->e);
29       }
30       return this->t.value();
31    }
32
33    operator T() { return this->unwrap(); }
34
35    char const *unwrap_err() { return this->e; }
36
37    optional<T> const &ok() const { return this->t; }
38    optional<char const *> err() const {
39       return this->e ? optional<char const *>(this->e) : nullopt;
40    }
41
42    result<T> map_err(std::function<char const *(char const *)> f);
43 };
44
45 template <typename T>
46 struct result<T> Err(char const *e) {
47    return result<T>{e, nullopt};
48 }
49
50 template <typename T>
51 struct result<T> Ok(T t) {
52    return result<T>{nullptr, t};
53 }
54
55 template <typename T>
56 result<T> result<T>::map_err(std::function<char const *(char const *)> f) {
57    if (this->is_err()) {
58       return Err<T>(f(this->e));
59    }
60    return *this;
61 }
62
63 }  // namespace wm
64
65 #endif  // TMCAGLWM_RESULT_HPP