60afe08744d36f7f865728cd04c9e031ea64401d
[staging/windowmanager.git] / src / result.hpp
1 /*
2  * Copyright (C) 2017 Mentor Graphics Development (Deutschland) GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 //
18 // Created by mfritzsc on 7/12/17.
19 //
20
21 #ifndef TMCAGLWM_RESULT_HPP
22 #define TMCAGLWM_RESULT_HPP
23
24 #include <experimental/optional>
25 #include <functional>
26
27 namespace wm {
28
29 using std::experimental::optional;
30 using std::experimental::nullopt;
31
32 // We only ever return a string as an error - so just parametrize
33 // this over result type T
34 template <typename T>
35 struct result {
36    char const *e;
37    optional<T> t;
38
39    bool is_ok() const { return this->t != nullopt; }
40    bool is_err() const { return this->e != nullptr; }
41
42    T unwrap() {
43       if (this->e != nullptr) {
44          throw std::logic_error(this->e);
45       }
46       return this->t.value();
47    }
48
49    operator T() { return this->unwrap(); }
50
51    char const *unwrap_err() { return this->e; }
52
53    optional<T> const &ok() const { return this->t; }
54    optional<char const *> err() const {
55       return this->e ? optional<char const *>(this->e) : nullopt;
56    }
57
58    result<T> map_err(std::function<char const *(char const *)> f);
59 };
60
61 template <typename T>
62 struct result<T> Err(char const *e) {
63    return result<T>{e, nullopt};
64 }
65
66 template <typename T>
67 struct result<T> Ok(T t) {
68    return result<T>{nullptr, t};
69 }
70
71 template <typename T>
72 result<T> result<T>::map_err(std::function<char const *(char const *)> f) {
73    if (this->is_err()) {
74       return Err<T>(f(this->e));
75    }
76    return *this;
77 }
78
79 }  // namespace wm
80
81 #endif  // TMCAGLWM_RESULT_HPP