1 /*
2 * Copyright (C) 2017 The Android Open Source Project
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 // This file contains classes for returning a successful result along with an optional
18 // arbitrarily typed return value or for returning a failure result along with an optional string
19 // indicating why the function failed.
20
21 // There are 3 classes that implement this functionality and one additional helper type.
22 //
23 // Result<T> either contains a member of type T that can be accessed using similar semantics as
24 // std::optional<T> or it contains a ResultError describing an error, which can be accessed via
25 // Result<T>::error().
26 //
27 // ResultError is a type that contains both a std::string describing the error and a copy of errno
28 // from when the error occurred. ResultError can be used in an ostream directly to print its
29 // string value.
30 //
31 // Success is a typedef that aids in creating Result<T> that do not contain a return value.
32 // Result<Success> is the correct return type for a function that either returns successfully or
33 // returns an error value. Returning Success() from a function that returns Result<Success> is the
34 // correct way to indicate that a function without a return type has completed successfully.
35 //
36 // A successful Result<T> is constructed implicitly from any type that can be implicitly converted
37 // to T or from the constructor arguments for T. This allows you to return a type T directly from
38 // a function that returns Result<T>.
39 //
40 // Error and ErrnoError are used to construct a Result<T> that has failed. The Error class takes
41 // an ostream as an input and are implicitly cast to a Result<T> containing that failure.
42 // ErrnoError() is a helper function to create an Error class that appends ": " + strerror(errno)
43 // to the end of the failure string to aid in interacting with C APIs. Alternatively, an errno
44 // value can be directly specified via the Error() constructor.
45 //
46 // ResultError can be used in the ostream when using Error to construct a Result<T>. In this case,
47 // the string that the ResultError takes is passed through the stream normally, but the errno is
48 // passed to the Result<T>. This can be used to pass errno from a failing C function up multiple
49 // callers.
50 //
51 // ResultError can also directly construct a Result<T>. This is particularly useful if you have a
52 // function that return Result<T> but you have a Result<U> and want to return its error. In this
53 // case, you can return the .error() from the Result<U> to construct the Result<T>.
54
55 // An example of how to use these is below:
56 // Result<U> CalculateResult(const T& input) {
57 // U output;
58 // if (!SomeOtherCppFunction(input, &output)) {
59 // return Error() << "SomeOtherCppFunction(" << input << ") failed";
60 // }
61 // if (!c_api_function(output)) {
62 // return ErrnoError() << "c_api_function(" << output << ") failed";
63 // }
64 // return output;
65 // }
66 //
67 // auto output = CalculateResult(input);
68 // if (!output) return Error() << "CalculateResult failed: " << output.error();
69 // UseOutput(*output);
70
71 #ifndef _INIT_RESULT_H
72 #define _INIT_RESULT_H
73
74 #include <errno.h>
75
76 #include <sstream>
77 #include <string>
78 #include <variant>
79
80 namespace android {
81 namespace init {
82
83 struct ResultError {
84 template <typename T>
ResultErrorResultError85 ResultError(T&& error_string, int error_errno)
86 : error_string(std::forward<T>(error_string)), error_errno(error_errno) {}
87
88 std::string error_string;
89 int error_errno;
90 };
91
92 inline std::ostream& operator<<(std::ostream& os, const ResultError& t) {
93 os << t.error_string;
94 return os;
95 }
96
97 inline std::ostream& operator<<(std::ostream& os, ResultError&& t) {
98 os << std::move(t.error_string);
99 return os;
100 }
101
102 class Error {
103 public:
Error()104 Error() : errno_(0), append_errno_(false) {}
Error(int errno_to_append)105 Error(int errno_to_append) : errno_(errno_to_append), append_errno_(true) {}
106
107 template <typename T>
108 Error&& operator<<(T&& t) {
109 ss_ << std::forward<T>(t);
110 return std::move(*this);
111 }
112
113 Error&& operator<<(const ResultError& result_error) {
114 ss_ << result_error.error_string;
115 errno_ = result_error.error_errno;
116 return std::move(*this);
117 }
118
119 Error&& operator<<(ResultError&& result_error) {
120 ss_ << std::move(result_error.error_string);
121 errno_ = result_error.error_errno;
122 return std::move(*this);
123 }
124
str()125 const std::string str() const {
126 std::string str = ss_.str();
127 if (append_errno_) {
128 if (str.empty()) {
129 return strerror(errno_);
130 }
131 return str + ": " + strerror(errno_);
132 }
133 return str;
134 }
135
get_errno()136 int get_errno() const { return errno_; }
137
138 Error(const Error&) = delete;
139 Error(Error&&) = delete;
140 Error& operator=(const Error&) = delete;
141 Error& operator=(Error&&) = delete;
142
143 private:
144 std::stringstream ss_;
145 int errno_;
146 bool append_errno_;
147 };
148
ErrnoError()149 inline Error ErrnoError() {
150 return Error(errno);
151 }
152
153 template <typename T>
154 class [[nodiscard]] Result {
155 public:
Result()156 Result() {}
157
158 template <typename U, typename... V,
159 typename = std::enable_if_t<!(std::is_same_v<std::decay_t<U>, Result<T>> &&
160 sizeof...(V) == 0)>>
Result(U && result,V &&...results)161 Result(U&& result, V&&... results)
162 : contents_(std::in_place_index_t<0>(), std::forward<U>(result),
163 std::forward<V>(results)...) {}
164
Result(Error && error)165 Result(Error&& error) : contents_(std::in_place_index_t<1>(), error.str(), error.get_errno()) {}
Result(const ResultError & result_error)166 Result(const ResultError& result_error)
167 : contents_(std::in_place_index_t<1>(), result_error.error_string,
168 result_error.error_errno) {}
Result(ResultError && result_error)169 Result(ResultError&& result_error)
170 : contents_(std::in_place_index_t<1>(), std::move(result_error.error_string),
171 result_error.error_errno) {}
172
IgnoreError()173 void IgnoreError() const {}
174
has_value()175 bool has_value() const { return contents_.index() == 0; }
176
value()177 T& value() & { return std::get<0>(contents_); }
value()178 const T& value() const & { return std::get<0>(contents_); }
value()179 T&& value() && { return std::get<0>(std::move(contents_)); }
value()180 const T&& value() const && { return std::get<0>(std::move(contents_)); }
181
error()182 const ResultError& error() const & { return std::get<1>(contents_); }
error()183 ResultError&& error() && { return std::get<1>(std::move(contents_)); }
error()184 const ResultError&& error() const && { return std::get<1>(std::move(contents_)); }
185
error_string()186 const std::string& error_string() const & { return std::get<1>(contents_).error_string; }
error_string()187 std::string&& error_string() && { return std::get<1>(std::move(contents_)).error_string; }
error_string()188 const std::string&& error_string() const && {
189 return std::get<1>(std::move(contents_)).error_string;
190 }
191
error_errno()192 int error_errno() const { return std::get<1>(contents_).error_errno; }
193
194 explicit operator bool() const { return has_value(); }
195
196 T& operator*() & { return value(); }
197 const T& operator*() const & { return value(); }
198 T&& operator*() && { return std::move(value()); }
199 const T&& operator*() const && { return std::move(value()); }
200
201 T* operator->() { return &value(); }
202 const T* operator->() const { return &value(); }
203
204 private:
205 std::variant<T, ResultError> contents_;
206 };
207
208 using Success = std::monostate;
209
210 } // namespace init
211 } // namespace android
212
213 #endif
214