blob: e5d90c8606adada4f541962e595752ba9ae1c79f [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) {
Jooyung Han072c7142019-06-11 13:38:01 +0900133 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 Parkab7dc5a2019-05-31 03:43:34 +0900137 int saved = errno;
138 ss_ << t;
139 errno = saved;
140 return *this;
141 }
142
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900143 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 Cherry81f5f502020-02-04 15:18:29 -0800159 template <typename T, typename... Args>
160 friend Error ErrorfImpl(const T&& fmt, const Args&... args);
Jiyong Park4e223e62019-06-12 16:25:04 +0900161
Tom Cherry81f5f502020-02-04 15:18:29 -0800162 template <typename T, typename... Args>
163 friend Error ErrnoErrorfImpl(const T&& fmt, const Args&... args);
Jiyong Park4e223e62019-06-12 16:25:04 +0900164
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900165 private:
Jiyong Park4e223e62019-06-12 16:25:04 +0900166 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 Parkab7dc5a2019-05-31 03:43:34 +0900171 std::stringstream ss_;
172 int errno_;
Jiyong Park4e223e62019-06-12 16:25:04 +0900173 const bool append_errno_;
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900174};
175
176inline Error ErrnoError() {
177 return Error(errno);
178}
179
Jiyong Park4e223e62019-06-12 16:25:04 +0900180inline 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.
186template <typename T, typename... Args>
187inline 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 Cherry81f5f502020-02-04 15:18:29 -0800194// TODO(tomcherry): Remove this once we've removed all `using android::base::Errorf` and `using
195// android::base::ErrnoErrorf` lines.
196enum Errorf {};
197enum ErrnoErrorf {};
198
199template <typename T, typename... Args>
200inline Error ErrorfImpl(const T&& fmt, const Args&... args) {
Jiyong Park4e223e62019-06-12 16:25:04 +0900201 return Error(false, ErrorCode(0, args...), fmt::format(fmt, args...));
202}
203
Tom Cherry81f5f502020-02-04 15:18:29 -0800204template <typename T, typename... Args>
205inline Error ErrnoErrorfImpl(const T&& fmt, const Args&... args) {
Jiyong Park4e223e62019-06-12 16:25:04 +0900206 return Error(true, errno, fmt::format(fmt, args...));
207}
208
Tom Cherry81f5f502020-02-04 15:18:29 -0800209#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 Parkab7dc5a2019-05-31 03:43:34 +0900212template <typename T>
213using Result = android::base::expected<T, ResultError>;
214
Jiyong Parkab7dc5a2019-05-31 03:43:34 +0900215} // namespace base
216} // namespace android