blob: a5016b90e96c55a68618655db1e60cb5a78aabed [file] [log] [blame]
Jiyong Parkab7dc5a2019-05-31 03:43:34 +09001/*
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
Jiyong Parkf7bb3e82021-12-10 22:46:25 +090017// Result<T, E> is the type that is used to pass a success value of type T or an error code of type
18// E, optionally together with an error message. T and E can be any type. If E is omitted it
19// defaults to int, which is useful when errno(3) is used as the error code.
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090020//
Jiyong Parkf7bb3e82021-12-10 22:46:25 +090021// Passing a success value or an error value:
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090022//
Jiyong Parkf7bb3e82021-12-10 22:46:25 +090023// Result<std::string> readFile() {
24// std::string content;
25// if (base::ReadFileToString("path", &content)) {
26// return content; // ok case
27// } else {
28// return ErrnoError() << "failed to read"; // error case
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090029// }
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090030// }
31//
Jiyong Parkf7bb3e82021-12-10 22:46:25 +090032// Checking the result and then unwrapping the value or propagating the error:
33//
34// Result<bool> hasAWord() {
35// auto content = readFile();
36// if (!content.ok()) {
37// return Error() << "failed to process: " << content.error();
38// }
39// return (*content.find("happy") != std::string::npos);
40// }
41//
42// Using custom error code type:
43//
Jiyong Park7706f492021-12-14 22:33:38 +090044// enum class MyError { A, B }; // assume that this is the error code you already have
45//
46// // To use the error code with Result, define a wrapper class that provides the following
47// operations and use the wrapper class as the second type parameter (E) when instantiating
48// Result<T, E>
49//
50// 1. default constructor
51// 2. copy constructor / and move constructor if copying is expensive
52// 3. conversion operator to the error code type
53// 4. value() function that return the error code value
54// 5. print() function that gives a string representation of the error ode value
55//
56// struct MyErrorWrapper {
57// MyError val_;
58// MyErrorWrapper() : val_(/* reasonable default value */) {}
59// MyErrorWrapper(MyError&& e) : val_(std:forward<MyError>(e)) {}
60// operator const MyError&() const { return val_; }
61// MyError value() const { return val_; }
62// std::string print() const {
63// switch(val_) {
Jiyong Parkf7bb3e82021-12-10 22:46:25 +090064// MyError::A: return "A";
65// MyError::B: return "B";
66// }
67// }
68// };
69//
Jiyong Park7706f492021-12-14 22:33:38 +090070// #define NewMyError(e) Error<MyErrorWrapper>(MyError::e)
Jiyong Parkf7bb3e82021-12-10 22:46:25 +090071//
72// Result<T, MyError> val = NewMyError(A) << "some message";
73//
74// Formatting the error message using fmtlib:
75//
76// Errorf("{} errors", num); // equivalent to Error() << num << " errors";
77// ErrnoErrorf("{} errors", num); // equivalent to ErrnoError() << num << " errors";
78//
79// Returning success or failure, but not the value:
80//
81// Result<void> doSomething() {
82// if (success) return {};
83// else return Error() << "error occurred";
84// }
85//
86// Extracting error code:
87//
88// Result<T> val = Error(3) << "some error occurred";
89// assert(3 == val.error().code());
90//
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090091
92#pragma once
93
Jiyong Parkf7bb3e82021-12-10 22:46:25 +090094#include <assert.h>
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090095#include <errno.h>
96
97#include <sstream>
98#include <string>
99
Jiyong Park7706f492021-12-14 22:33:38 +0900100#include "android-base/errors.h"
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900101#include "android-base/expected.h"
Tom Cherry377d1ad2019-06-14 14:34:54 -0700102#include "android-base/format.h"
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900103
104namespace android {
105namespace base {
106
Jiyong Park7706f492021-12-14 22:33:38 +0900107// Errno is a wrapper class for errno(3). Use this type instead of `int` when instantiating
108// `Result<T, E>` and `Error<E>` template classes. This is required to distinguish errno from other
109// integer-based error code types like `status_t`.
110struct Errno {
111 Errno() : val_(0) {}
112 Errno(int e) : val_(e) {}
113 int value() const { return val_; }
114 operator int() const { return value(); }
115 std::string print() const { return strerror(value()); }
116
117 int val_;
118
119 // TODO(b/209929099): remove this conversion operator. This currently is needed to not break
120 // existing places where error().code() is used to construct enum values.
121 template <typename E, typename = std::enable_if_t<std::is_enum_v<E>>>
122 operator E() const {
123 return E(val_);
124 }
125};
126
Jiyong Park959593a2022-01-03 17:43:12 +0900127template <typename E = Errno, bool include_message = true>
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900128struct ResultError {
Jiyong Park7706f492021-12-14 22:33:38 +0900129 template <typename T, typename P, typename = std::enable_if_t<std::is_convertible_v<P, E>>>
130 ResultError(T&& message, P&& code)
131 : message_(std::forward<T>(message)), code_(E(std::forward<P>(code))) {}
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900132
133 template <typename T>
Maciej Żenczykowskib39ecb42020-01-26 20:12:30 -0800134 // NOLINTNEXTLINE(google-explicit-constructor)
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900135 operator android::base::expected<T, ResultError<E>>() const {
136 return android::base::unexpected(ResultError<E>(message_, code_));
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900137 }
138
139 std::string message() const { return message_; }
Jiyong Park7706f492021-12-14 22:33:38 +0900140 const E& code() const { return code_; }
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900141
142 private:
143 std::string message_;
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900144 E code_;
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900145};
146
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900147template <typename E>
Jiyong Park959593a2022-01-03 17:43:12 +0900148struct ResultError<E, /* include_message */ false> {
149 template <typename P, typename = std::enable_if_t<std::is_convertible_v<P, E>>>
150 ResultError(P&& code) : code_(E(std::forward<P>(code))) {}
151
152 template <typename T>
153 operator android::base::expected<T, ResultError<E, false>>() const {
154 return android::base::unexpected(ResultError<E, false>(code_));
155 }
156
157 const E& code() const { return code_; }
158
159 private:
160 E code_;
161};
162
163template <typename E>
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900164inline bool operator==(const ResultError<E>& lhs, const ResultError<E>& rhs) {
Jiyong Parkbdf42dc2019-06-05 18:33:01 +0900165 return lhs.message() == rhs.message() && lhs.code() == rhs.code();
166}
167
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900168template <typename E>
169inline bool operator!=(const ResultError<E>& lhs, const ResultError<E>& rhs) {
Jiyong Parkbdf42dc2019-06-05 18:33:01 +0900170 return !(lhs == rhs);
171}
172
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900173template <typename E>
174inline std::ostream& operator<<(std::ostream& os, const ResultError<E>& t) {
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900175 os << t.message();
176 return os;
177}
178
Jiyong Park959593a2022-01-03 17:43:12 +0900179namespace internal {
180// Stream class that does nothing and is has zero (actually 1) size. It is used instead of
181// std::stringstream when include_message is false so that we use less on stack.
182// sizeof(std::stringstream) is 280 on arm64.
183struct DoNothingStream {
184 template <typename T>
185 DoNothingStream& operator<<(T&&) {
186 return *this;
187 }
188
189 std::string str() const { return ""; }
190};
191} // namespace internal
192
193template <typename E = Errno, bool include_message = true,
194 typename = std::enable_if_t<!std::is_same_v<E, int>>>
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900195class Error {
196 public:
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900197 Error() : code_(0), has_code_(false) {}
Jiyong Park7706f492021-12-14 22:33:38 +0900198 template <typename P, typename = std::enable_if_t<std::is_convertible_v<P, E>>>
Maciej Żenczykowskib39ecb42020-01-26 20:12:30 -0800199 // NOLINTNEXTLINE(google-explicit-constructor)
Jiyong Park7706f492021-12-14 22:33:38 +0900200 Error(P&& code) : code_(std::forward<P>(code)), has_code_(true) {}
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900201
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900202 template <typename T, typename P, typename = std::enable_if_t<std::is_convertible_v<E, P>>>
Maciej Żenczykowskib39ecb42020-01-26 20:12:30 -0800203 // NOLINTNEXTLINE(google-explicit-constructor)
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900204 operator android::base::expected<T, ResultError<P>>() const {
205 return android::base::unexpected(ResultError<P>(str(), static_cast<P>(code_)));
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900206 }
207
Jiyong Park959593a2022-01-03 17:43:12 +0900208 template <typename T, typename P, typename = std::enable_if_t<std::is_convertible_v<E, P>>>
209 // NOLINTNEXTLINE(google-explicit-constructor)
210 operator android::base::expected<T, ResultError<P, false>>() const {
211 return android::base::unexpected(ResultError<P, false>(static_cast<P>(code_)));
212 }
213
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900214 template <typename T>
215 Error& operator<<(T&& t) {
Jiyong Park959593a2022-01-03 17:43:12 +0900216 static_assert(include_message, "<< not supported when include_message = false");
Maciej Żenczykowskice99a912020-04-24 11:21:21 -0700217 // NOLINTNEXTLINE(bugprone-suspicious-semicolon)
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900218 if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError<E>>) {
219 if (!has_code_) {
220 code_ = t.code();
221 }
Jooyung Han072c7142019-06-11 13:38:01 +0900222 return (*this) << t.message();
223 }
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900224 int saved = errno;
225 ss_ << t;
226 errno = saved;
227 return *this;
228 }
229
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900230 const std::string str() const {
Jiyong Park959593a2022-01-03 17:43:12 +0900231 static_assert(include_message, "str() not supported when include_message = false");
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900232 std::string str = ss_.str();
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900233 if (has_code_) {
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900234 if (str.empty()) {
Jiyong Park7706f492021-12-14 22:33:38 +0900235 return code_.print();
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900236 }
Jiyong Park7706f492021-12-14 22:33:38 +0900237 return std::move(str) + ": " + code_.print();
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900238 }
239 return str;
240 }
241
242 Error(const Error&) = delete;
243 Error(Error&&) = delete;
244 Error& operator=(const Error&) = delete;
245 Error& operator=(Error&&) = delete;
246
Tom Cherry81f5f502020-02-04 15:18:29 -0800247 template <typename T, typename... Args>
248 friend Error ErrorfImpl(const T&& fmt, const Args&... args);
Jiyong Park4e223e62019-06-12 16:25:04 +0900249
Tom Cherry81f5f502020-02-04 15:18:29 -0800250 template <typename T, typename... Args>
251 friend Error ErrnoErrorfImpl(const T&& fmt, const Args&... args);
Jiyong Park4e223e62019-06-12 16:25:04 +0900252
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900253 private:
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900254 Error(bool has_code, E code, const std::string& message) : code_(code), has_code_(has_code) {
Jiyong Park4e223e62019-06-12 16:25:04 +0900255 (*this) << message;
256 }
257
Jiyong Park959593a2022-01-03 17:43:12 +0900258 std::conditional_t<include_message, std::stringstream, internal::DoNothingStream> ss_;
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900259 E code_;
260 const bool has_code_;
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900261};
262
Jiyong Park7706f492021-12-14 22:33:38 +0900263inline Error<Errno> ErrnoError() {
264 return Error<Errno>(Errno{errno});
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900265}
266
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900267template <typename E>
268inline E ErrorCode(E code) {
Jiyong Park4e223e62019-06-12 16:25:04 +0900269 return code;
270}
271
272// Return the error code of the last ResultError object, if any.
273// Otherwise, return `code` as it is.
Jiyong Parkf7bb3e82021-12-10 22:46:25 +0900274template <typename T, typename E, typename... Args>
275inline E ErrorCode(E code, T&& t, const Args&... args) {
276 if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError<E>>) {
Jiyong Park4e223e62019-06-12 16:25:04 +0900277 return ErrorCode(t.code(), args...);
278 }
279 return ErrorCode(code, args...);
280}
281
Tom Cherry81f5f502020-02-04 15:18:29 -0800282template <typename T, typename... Args>
Jiyong Park7706f492021-12-14 22:33:38 +0900283inline Error<Errno> ErrorfImpl(const T&& fmt, const Args&... args) {
284 return Error(false, ErrorCode(Errno{}, args...), fmt::format(fmt, args...));
Jiyong Park4e223e62019-06-12 16:25:04 +0900285}
286
Tom Cherry81f5f502020-02-04 15:18:29 -0800287template <typename T, typename... Args>
Jiyong Park7706f492021-12-14 22:33:38 +0900288inline Error<Errno> ErrnoErrorfImpl(const T&& fmt, const Args&... args) {
289 return Error<Errno>(true, Errno{errno}, fmt::format(fmt, args...));
Jiyong Park4e223e62019-06-12 16:25:04 +0900290}
291
Tom Cherry81f5f502020-02-04 15:18:29 -0800292#define Errorf(fmt, ...) android::base::ErrorfImpl(FMT_STRING(fmt), ##__VA_ARGS__)
293#define ErrnoErrorf(fmt, ...) android::base::ErrnoErrorfImpl(FMT_STRING(fmt), ##__VA_ARGS__)
294
Jiyong Park959593a2022-01-03 17:43:12 +0900295template <typename T, typename E = Errno, bool include_message = true>
296using Result = android::base::expected<T, ResultError<E, include_message>>;
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900297
Jiyong Park7706f492021-12-14 22:33:38 +0900298// Specialization of android::base::OkOrFail<V> for V = Result<T, E>. See android-base/errors.h
299// for the contract.
300template <typename T, typename E>
301struct OkOrFail<Result<T, E>> {
302 typedef Result<T, E> V;
303 // Checks if V is ok or fail
304 static bool IsOk(const V& val) { return val.ok(); }
305
306 // Turns V into a success value
307 static T Unwrap(V&& val) { return std::move(val.value()); }
308
309 // Consumes V when it's a fail value
310 static OkOrFail<V> Fail(V&& v) {
311 assert(!IsOk(v));
312 return OkOrFail<V>{std::move(v)};
313 }
314 V val_;
315
316 // Turns V into S (convertible from E) or Result<U, E>
317 template <typename S, typename = std::enable_if_t<std::is_convertible_v<E, S>>>
318 operator S() && {
319 return val_.error().code();
320 }
321 template <typename U>
322 operator Result<U, E>() && {
323 return val_.error();
324 }
325
326 static std::string ErrorMessage(const V& val) { return val.error().message(); }
327};
328
Bernie Innocenti9cc7edc2020-02-06 02:51:42 +0900329// Macros for testing the results of functions that return android::base::Result.
330// These also work with base::android::expected.
Yifan Hongf21c5462021-05-21 18:43:16 -0700331// For advanced matchers and customized error messages, see result-gtest.h.
Bernie Innocenti9cc7edc2020-02-06 02:51:42 +0900332
Jiyong Parkc6efce12021-12-20 15:17:58 +0900333#define ASSERT_RESULT_OK(stmt) \
334 if (const auto& tmp = (stmt); !tmp.ok()) \
335 FAIL() << "Value of: " << #stmt << "\n" \
336 << " Actual: " << tmp.error().message() << "\n" \
337 << "Expected: is ok\n"
Bernie Innocenti9cc7edc2020-02-06 02:51:42 +0900338
Jiyong Parkc6efce12021-12-20 15:17:58 +0900339#define EXPECT_RESULT_OK(stmt) \
340 if (const auto& tmp = (stmt); !tmp.ok()) \
341 ADD_FAILURE() << "Value of: " << #stmt << "\n" \
342 << " Actual: " << tmp.error().message() << "\n" \
343 << "Expected: is ok\n"
Bernie Innocenti9cc7edc2020-02-06 02:51:42 +0900344
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900345} // namespace base
346} // namespace android