doc: shuffled around some sections, fixes.
[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 #ifndef TMCAGLWM_RESULT_HPP
18 #define TMCAGLWM_RESULT_HPP
19
20 #include <experimental/optional>
21 #include <functional>
22
23 namespace wm {
24
25 using std::experimental::optional;
26 using std::experimental::nullopt;
27
28 // We only ever return a string as an error - so just parametrize
29 // this over result type T
30 template <typename T>
31 struct result {
32    char const *e;
33    optional<T> t;
34
35    bool is_ok() const { return this->t != nullopt; }
36    bool is_err() const { return this->e != nullptr; }
37
38    T unwrap() {
39       if (this->e != nullptr) {
40          throw std::logic_error(this->e);
41       }
42       return this->t.value();
43    }
44
45    operator T() { return this->unwrap(); }
46
47    char const *unwrap_err() { return this->e; }
48
49    optional<T> const &ok() const { return this->t; }
50    optional<char const *> err() const {
51       return this->e ? optional<char const *>(this->e) : nullopt;
52    }
53
54    result<T> map_err(std::function<char const *(char const *)> f);
55 };
56
57 template <typename T>
58 struct result<T> Err(char const *e) {
59    return result<T>{e, nullopt};
60 }
61
62 template <typename T>
63 struct result<T> Ok(T t) {
64    return result<T>{nullptr, t};
65 }
66
67 template <typename T>
68 result<T> result<T>::map_err(std::function<char const *(char const *)> f) {
69    if (this->is_err()) {
70       return Err<T>(f(this->e));
71    }
72    return *this;
73 }
74
75 }  // namespace wm
76
77 #endif  // TMCAGLWM_RESULT_HPP