| 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) { |
| Jooyung Han | 072c714 | 2019-06-11 13:38:01 +0900 | [diff] [blame] | 133 | if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError>) { |
| 134 | errno_ = t.code(); |
| 135 | return (*this) << t.message(); |
| 136 | } |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 137 | int saved = errno; |
| 138 | ss_ << t; |
| 139 | errno = saved; |
| 140 | return *this; |
| 141 | } |
| 142 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 143 | const std::string str() const { |
| 144 | std::string str = ss_.str(); |
| 145 | if (append_errno_) { |
| 146 | if (str.empty()) { |
| 147 | return strerror(errno_); |
| 148 | } |
| 149 | return std::move(str) + ": " + strerror(errno_); |
| 150 | } |
| 151 | return str; |
| 152 | } |
| 153 | |
| 154 | Error(const Error&) = delete; |
| 155 | Error(Error&&) = delete; |
| 156 | Error& operator=(const Error&) = delete; |
| 157 | Error& operator=(Error&&) = delete; |
| 158 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame^] | 159 | template <typename T, typename... Args> |
| 160 | friend Error ErrorfImpl(const T&& fmt, const Args&... args); |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 161 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame^] | 162 | template <typename T, typename... Args> |
| 163 | friend Error ErrnoErrorfImpl(const T&& fmt, const Args&... args); |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 164 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 165 | private: |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 166 | Error(bool append_errno, int errno_to_append, const std::string& message) |
| 167 | : errno_(errno_to_append), append_errno_(append_errno) { |
| 168 | (*this) << message; |
| 169 | } |
| 170 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 171 | std::stringstream ss_; |
| 172 | int errno_; |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 173 | const bool append_errno_; |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 174 | }; |
| 175 | |
| 176 | inline Error ErrnoError() { |
| 177 | return Error(errno); |
| 178 | } |
| 179 | |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 180 | inline int ErrorCode(int code) { |
| 181 | return code; |
| 182 | } |
| 183 | |
| 184 | // Return the error code of the last ResultError object, if any. |
| 185 | // Otherwise, return `code` as it is. |
| 186 | template <typename T, typename... Args> |
| 187 | inline int ErrorCode(int code, T&& t, const Args&... args) { |
| 188 | if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError>) { |
| 189 | return ErrorCode(t.code(), args...); |
| 190 | } |
| 191 | return ErrorCode(code, args...); |
| 192 | } |
| 193 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame^] | 194 | // TODO(tomcherry): Remove this once we've removed all `using android::base::Errorf` and `using |
| 195 | // android::base::ErrnoErrorf` lines. |
| 196 | enum Errorf {}; |
| 197 | enum ErrnoErrorf {}; |
| 198 | |
| 199 | template <typename T, typename... Args> |
| 200 | inline Error ErrorfImpl(const T&& fmt, const Args&... args) { |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 201 | return Error(false, ErrorCode(0, args...), fmt::format(fmt, args...)); |
| 202 | } |
| 203 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame^] | 204 | template <typename T, typename... Args> |
| 205 | inline Error ErrnoErrorfImpl(const T&& fmt, const Args&... args) { |
| Jiyong Park | 4e223e6 | 2019-06-12 16:25:04 +0900 | [diff] [blame] | 206 | return Error(true, errno, fmt::format(fmt, args...)); |
| 207 | } |
| 208 | |
| Tom Cherry | 81f5f50 | 2020-02-04 15:18:29 -0800 | [diff] [blame^] | 209 | #define Errorf(fmt, ...) android::base::ErrorfImpl(FMT_STRING(fmt), ##__VA_ARGS__) |
| 210 | #define ErrnoErrorf(fmt, ...) android::base::ErrnoErrorfImpl(FMT_STRING(fmt), ##__VA_ARGS__) |
| 211 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 212 | template <typename T> |
| 213 | using Result = android::base::expected<T, ResultError>; |
| 214 | |
| Jiyong Park | ab7dc5a | 2019-05-31 03:43:34 +0900 | [diff] [blame] | 215 | } // namespace base |
| 216 | } // namespace android |