blob: acec791996f38449f413d5b7221c13bb03ad0078 [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
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 Cherrye2ea1ef2019-06-10 12:51:32 -070031// 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 Parkab7dc5a2019-05-31 03:43:34 +090033// 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 Park4e223e62019-06-12 16:25:04 +090045// 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 Parkab7dc5a2019-05-31 03:43:34 +090054//
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 Park4e223e62019-06-12 16:25:04 +090063// return Errorf("SomeOtherCppFunction {} failed", input);
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090064// }
65// if (!c_api_function(output)) {
Jiyong Park4e223e62019-06-12 16:25:04 +090066// return ErrnoErrorf("c_api_function {} failed", output);
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090067// }
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 Cherry377d1ad2019-06-14 14:34:54 -070083#include "android-base/format.h"
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090084
85namespace android {
86namespace base {
87
88struct ResultError {
89 template <typename T>
Jooyung Han072c7142019-06-11 13:38:01 +090090 ResultError(T&& message, int code) : message_(std::forward<T>(message)), code_(code) {}
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090091
92 template <typename T>
Maciej Żenczykowskib39ecb42020-01-26 20:12:30 -080093 // NOLINTNEXTLINE(google-explicit-constructor)
Jiyong Parkab7dc5a2019-05-31 03:43:34 +090094 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 Parkbdf42dc2019-06-05 18:33:01 +0900106inline bool operator==(const ResultError& lhs, const ResultError& rhs) {
107 return lhs.message() == rhs.message() && lhs.code() == rhs.code();
108}
109
110inline bool operator!=(const ResultError& lhs, const ResultError& rhs) {
111 return !(lhs == rhs);
112}
113
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900114inline std::ostream& operator<<(std::ostream& os, const ResultError& t) {
115 os << t.message();
116 return os;
117}
118
119class Error {
120 public:
121 Error() : errno_(0), append_errno_(false) {}
Maciej Żenczykowskib39ecb42020-01-26 20:12:30 -0800122 // NOLINTNEXTLINE(google-explicit-constructor)
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900123 Error(int errno_to_append) : errno_(errno_to_append), append_errno_(true) {}
124
125 template <typename T>
Maciej Żenczykowskib39ecb42020-01-26 20:12:30 -0800126 // NOLINTNEXTLINE(google-explicit-constructor)
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900127 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 Żenczykowskice99a912020-04-24 11:21:21 -0700133 // NOLINTNEXTLINE(bugprone-suspicious-semicolon)
Jooyung Han072c7142019-06-11 13:38:01 +0900134 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 Parkab7dc5a2019-05-31 03:43:34 +0900138 int saved = errno;
139 ss_ << t;
140 errno = saved;
141 return *this;
142 }
143
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900144 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 Cherry81f5f502020-02-04 15:18:29 -0800160 template <typename T, typename... Args>
161 friend Error ErrorfImpl(const T&& fmt, const Args&... args);
Jiyong Park4e223e62019-06-12 16:25:04 +0900162
Tom Cherry81f5f502020-02-04 15:18:29 -0800163 template <typename T, typename... Args>
164 friend Error ErrnoErrorfImpl(const T&& fmt, const Args&... args);
Jiyong Park4e223e62019-06-12 16:25:04 +0900165
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900166 private:
Jiyong Park4e223e62019-06-12 16:25:04 +0900167 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 Parkab7dc5a2019-05-31 03:43:34 +0900172 std::stringstream ss_;
173 int errno_;
Jiyong Park4e223e62019-06-12 16:25:04 +0900174 const bool append_errno_;
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900175};
176
177inline Error ErrnoError() {
178 return Error(errno);
179}
180
Jiyong Park4e223e62019-06-12 16:25:04 +0900181inline 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.
187template <typename T, typename... Args>
188inline 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 Cherry81f5f502020-02-04 15:18:29 -0800195template <typename T, typename... Args>
196inline Error ErrorfImpl(const T&& fmt, const Args&... args) {
Jiyong Park4e223e62019-06-12 16:25:04 +0900197 return Error(false, ErrorCode(0, args...), fmt::format(fmt, args...));
198}
199
Tom Cherry81f5f502020-02-04 15:18:29 -0800200template <typename T, typename... Args>
201inline Error ErrnoErrorfImpl(const T&& fmt, const Args&... args) {
Jiyong Park4e223e62019-06-12 16:25:04 +0900202 return Error(true, errno, fmt::format(fmt, args...));
203}
204
Tom Cherry81f5f502020-02-04 15:18:29 -0800205#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 Parkab7dc5a2019-05-31 03:43:34 +0900208template <typename T>
209using Result = android::base::expected<T, ResultError>;
210
Bernie Innocenti9cc7edc2020-02-06 02:51:42 +0900211// Macros for testing the results of functions that return android::base::Result.
212// These also work with base::android::expected.
Yifan Hongf21c5462021-05-21 18:43:16 -0700213// For advanced matchers and customized error messages, see result-gtest.h.
Bernie Innocenti9cc7edc2020-02-06 02:51:42 +0900214
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 Parkab7dc5a2019-05-31 03:43:34 +0900235} // namespace base
236} // namespace android