Readd policy table generated by ZIPC for EXAMPLE
[apps/agl-service-windowmanager-2017.git] / src / result.hpp
1 /*
2  * Copyright (c) 2017 TOYOTA MOTOR CORPORATION
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
26 using std::experimental::nullopt;
27 using std::experimental::optional;
28
29 // We only ever return a string as an error - so just parametrize
30 // this over result type T
31 template <typename T>
32 struct result
33 {
34   char const *e;
35   optional<T> t;
36
37   bool is_ok() const { return this->t != nullopt; }
38   bool is_err() const { return this->e != nullptr; }
39
40   T unwrap()
41   {
42     if (this->e != nullptr)
43     {
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   {
56     return this->e ? optional<char const *>(this->e) : nullopt;
57   }
58
59   result<T> map_err(std::function<char const *(char const *)> f);
60 };
61
62 template <typename T>
63 struct result<T> Err(char const *e)
64 {
65   return result<T>{e, nullopt};
66 }
67
68 template <typename T>
69 struct result<T> Ok(T t)
70 {
71   return result<T>{nullptr, t};
72 }
73
74 template <typename T>
75 result<T> result<T>::map_err(std::function<char const *(char const *)> f)
76 {
77   if (this->is_err())
78   {
79     return Err<T>(f(this->e));
80   }
81   return *this;
82 }
83
84 } // namespace wm
85
86 #endif // TMCAGLWM_RESULT_HPP