| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 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 | // |
| Tom Cherry | e2ea1ef | 2019-06-10 12:51:32 -0700 | [diff] [blame] | 31 | // Result<void> is the correct return type for a function that either returns successfully or |
| 32 | // returns an error value. Returning {} from a function that returns Result<void> is the |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 33 | // correct way to indicate that a function without a return type has completed successfully. |
| 34 | // |
| 35 | // A successful Result<T> is constructed implicitly from any type that can be implicitly converted |
| 36 | // to T or from the constructor arguments for T. This allows you to return a type T directly from |
| 37 | // a function that returns Result<T>. |
| 38 | // |
| 39 | // Error and ErrnoError are used to construct a Result<T> that has failed. The Error class takes |
| 40 | // an ostream as an input and are implicitly cast to a Result<T> containing that failure. |
| 41 | // ErrnoError() is a helper function to create an Error class that appends ": " + strerror(errno) |
| 42 | // to the end of the failure string to aid in interacting with C APIs. Alternatively, an errno |
| 43 | // value can be directly specified via the Error() constructor. |
| 44 | // |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 45 | // Errorf and ErrnoErrorf accept the format string syntax of the fmblib (https://fmt.dev). |
| 46 | // Errorf("{} errors", num) is equivalent to Error() << num << " errors". |
| 47 | // |
| 48 | // ResultError can be used in the ostream and when using Error/Errorf to construct a Result<T>. |
| 49 | // In this case, the string that the ResultError takes is passed through the stream normally, but |
| 50 | // the errno is passed to the Result<T>. This can be used to pass errno from a failing C function up |
| 51 | // multiple callers. Note that when the outer Result<T> is created with ErrnoError/ErrnoErrorf then |
| 52 | // the errno from the inner ResultError is not passed. Also when multiple ResultError objects are |
| 53 | // used, the errno of the last one is respected. |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 54 | // |
| 55 | // ResultError can also directly construct a Result<T>. This is particularly useful if you have a |
| 56 | // function that return Result<T> but you have a Result<U> and want to return its error. In this |
| 57 | // case, you can return the .error() from the Result<U> to construct the Result<T>. |
| 58 | |
| 59 | // An example of how to use these is below: |
| 60 | // Result<U> CalculateResult(const T& input) { |
| 61 | // U output; |
| 62 | // if (!SomeOtherCppFunction(input, &output)) { |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 63 | // return Errorf("SomeOtherCppFunction {} failed", input); |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 64 | // } |
| 65 | // if (!c_api_function(output)) { |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 66 | // return ErrnoErrorf("c_api_function {} failed", output); |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 67 | // } |
| 68 | // return output; |
| 69 | // } |
| 70 | // |
| 71 | // auto output = CalculateResult(input); |
| 72 | // if (!output) return Error() << "CalculateResult failed: " << output.error(); |
| 73 | // UseOutput(*output); |
| 74 | |
| 75 | #pragma once |
| 76 | |
| 77 | #include <errno.h> |
| 78 | |
| 79 | #include <sstream> |
| 80 | #include <string> |
| 81 | |
| 82 | #include "android-base/expected.h" |
| Tom Cherry | 377d1ad | 2019-06-14 14:34:54 -0700 | [diff] [blame] | 83 | #include "android-base/format.h" |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 84 | |
| 85 | namespace android { |
| 86 | namespace base { |
| 87 | |
| 88 | struct ResultError { |
| 89 | template <typename T> |
| Jooyung Han | 072c714 | 2019-06-11 13:38:01 +0900 | [diff] [blame] | 90 | ResultError(T&& message, int code) : message_(std::forward<T>(message)), code_(code) {} |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 91 | |
| 92 | template <typename T> |
| Maciej Żenczykowski | b39ecb4 | 2020-01-26 20:12:30 -0800 | [diff] [blame] | 93 | // NOLINTNEXTLINE(google-explicit-constructor) |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 94 | operator android::base::expected<T, ResultError>() { |
| 95 | return android::base::unexpected(ResultError(message_, code_)); |
| 96 | } |
| 97 | |
| 98 | std::string message() const { return message_; } |
| 99 | int code() const { return code_; } |
| 100 | |
| 101 | private: |
| 102 | std::string message_; |
| 103 | int code_; |
| 104 | }; |
| 105 | |
| Jiyong Park | bdf42dc | 2019-06-05 18:33:01 +0900 | [diff] [blame] | 106 | inline bool operator==(const ResultError& lhs, const ResultError& rhs) { |
| 107 | return lhs.message() == rhs.message() && lhs.code() == rhs.code(); |
| 108 | } |
| 109 | |
| 110 | inline bool operator!=(const ResultError& lhs, const ResultError& rhs) { |
| 111 | return !(lhs == rhs); |
| 112 | } |
| 113 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 114 | inline std::ostream& operator<<(std::ostream& os, const ResultError& t) { |
| 115 | os << t.message(); |
| 116 | return os; |
| 117 | } |
| 118 | |
| 119 | class Error { |
| 120 | public: |
| 121 | Error() : errno_(0), append_errno_(false) {} |
| Maciej Żenczykowski | b39ecb4 | 2020-01-26 20:12:30 -0800 | [diff] [blame] | 122 | // NOLINTNEXTLINE(google-explicit-constructor) |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 123 | Error(int errno_to_append) : errno_(errno_to_append), append_errno_(true) {} |
| 124 | |
| 125 | template <typename T> |
| Maciej Żenczykowski | b39ecb4 | 2020-01-26 20:12:30 -0800 | [diff] [blame] | 126 | // NOLINTNEXTLINE(google-explicit-constructor) |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 127 | operator android::base::expected<T, ResultError>() { |
| 128 | return android::base::unexpected(ResultError(str(), errno_)); |
| 129 | } |
| 130 | |
| 131 | template <typename T> |
| 132 | Error& operator<<(T&& t) { |
| Maciej Żenczykowski | ce99a91 | 2020-04-24 11:21:21 -0700 | [diff] [blame] | 133 | // NOLINTNEXTLINE(bugprone-suspicious-semicolon) |
| Jooyung Han | 072c714 | 2019-06-11 13:38:01 +0900 | [diff] [blame] | 134 | if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError>) { |
| 135 | errno_ = t.code(); |
| 136 | return (*this) << t.message(); |
| 137 | } |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 138 | int saved = errno; |
| 139 | ss_ << t; |
| 140 | errno = saved; |
| 141 | return *this; |
| 142 | } |
| 143 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 144 | const std::string str() const { |
| 145 | std::string str = ss_.str(); |
| 146 | if (append_errno_) { |
| 147 | if (str.empty()) { |
| 148 | return strerror(errno_); |
| 149 | } |
| 150 | return std::move(str) + ": " + strerror(errno_); |
| 151 | } |
| 152 | return str; |
| 153 | } |
| 154 | |
| 155 | Error(const Error&) = delete; |
| 156 | Error(Error&&) = delete; |
| 157 | Error& operator=(const Error&) = delete; |
| 158 | Error& operator=(Error&&) = delete; |
| 159 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame] | 160 | template <typename T, typename... Args> |
| 161 | friend Error ErrorfImpl(const T&& fmt, const Args&... args); |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 162 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame] | 163 | template <typename T, typename... Args> |
| 164 | friend Error ErrnoErrorfImpl(const T&& fmt, const Args&... args); |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 165 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 166 | private: |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 167 | Error(bool append_errno, int errno_to_append, const std::string& message) |
| 168 | : errno_(errno_to_append), append_errno_(append_errno) { |
| 169 | (*this) << message; |
| 170 | } |
| 171 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 172 | std::stringstream ss_; |
| 173 | int errno_; |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 174 | const bool append_errno_; |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 175 | }; |
| 176 | |
| 177 | inline Error ErrnoError() { |
| 178 | return Error(errno); |
| 179 | } |
| 180 | |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 181 | inline int ErrorCode(int code) { |
| 182 | return code; |
| 183 | } |
| 184 | |
| 185 | // Return the error code of the last ResultError object, if any. |
| 186 | // Otherwise, return `code` as it is. |
| 187 | template <typename T, typename... Args> |
| 188 | inline int ErrorCode(int code, T&& t, const Args&... args) { |
| 189 | if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError>) { |
| 190 | return ErrorCode(t.code(), args...); |
| 191 | } |
| 192 | return ErrorCode(code, args...); |
| 193 | } |
| 194 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame] | 195 | template <typename T, typename... Args> |
| 196 | inline Error ErrorfImpl(const T&& fmt, const Args&... args) { |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 197 | return Error(false, ErrorCode(0, args...), fmt::format(fmt, args...)); |
| 198 | } |
| 199 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame] | 200 | template <typename T, typename... Args> |
| 201 | inline Error ErrnoErrorfImpl(const T&& fmt, const Args&... args) { |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 202 | return Error(true, errno, fmt::format(fmt, args...)); |
| 203 | } |
| 204 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame] | 205 | #define Errorf(fmt, ...) android::base::ErrorfImpl(FMT_STRING(fmt), ##__VA_ARGS__) |
| 206 | #define ErrnoErrorf(fmt, ...) android::base::ErrnoErrorfImpl(FMT_STRING(fmt), ##__VA_ARGS__) |
| 207 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 208 | template <typename T> |
| 209 | using Result = android::base::expected<T, ResultError>; |
| 210 | |
| Bernie Innocenti | 9cc7edc | 2020-02-06 02:51:42 +0900 | [diff] [blame] | 211 | // Macros for testing the results of functions that return android::base::Result. |
| 212 | // These also work with base::android::expected. |
| Yifan Hong | f21c546 | 2021-05-21 18:43:16 -0700 | [diff] [blame^] | 213 | // For advanced matchers and customized error messages, see result-gtest.h. |
| Bernie Innocenti | 9cc7edc | 2020-02-06 02:51:42 +0900 | [diff] [blame] | 214 | |
| 215 | #define CHECK_RESULT_OK(stmt) \ |
| 216 | do { \ |
| 217 | const auto& tmp = (stmt); \ |
| 218 | CHECK(tmp.ok()) << tmp.error(); \ |
| 219 | } while (0) |
| 220 | |
| 221 | #define ASSERT_RESULT_OK(stmt) \ |
| 222 | do { \ |
| 223 | const auto& tmp = (stmt); \ |
| 224 | ASSERT_TRUE(tmp.ok()) << tmp.error(); \ |
| 225 | } while (0) |
| 226 | |
| 227 | #define EXPECT_RESULT_OK(stmt) \ |
| 228 | do { \ |
| 229 | auto tmp = (stmt); \ |
| 230 | EXPECT_TRUE(tmp.ok()) << tmp.error(); \ |
| 231 | } while (0) |
| 232 | |
| 233 | // TODO: Maybe add RETURN_IF_ERROR() and ASSIGN_OR_RETURN() |
| 234 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 235 | } // namespace base |
| 236 | } // namespace android |