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 //
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
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 //
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.
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)) {
63 //     return Errorf("SomeOtherCppFunction {} failed", input);
64 //   }
65 //   if (!c_api_function(output)) {
66 //     return ErrnoErrorf("c_api_function {} failed", output);
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"
83 #include "android-base/format.h"
84 
85 namespace android {
86 namespace base {
87 
88 struct ResultError {
89   template <typename T>
ResultErrorResultError90   ResultError(T&& message, int code) : message_(std::forward<T>(message)), code_(code) {}
91 
92   template <typename T>
93   // NOLINTNEXTLINE(google-explicit-constructor)
94   operator android::base::expected<T, ResultError>() {
95     return android::base::unexpected(ResultError(message_, code_));
96   }
97 
messageResultError98   std::string message() const { return message_; }
codeResultError99   int code() const { return code_; }
100 
101  private:
102   std::string message_;
103   int code_;
104 };
105 
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 
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:
Error()121   Error() : errno_(0), append_errno_(false) {}
122   // NOLINTNEXTLINE(google-explicit-constructor)
Error(int errno_to_append)123   Error(int errno_to_append) : errno_(errno_to_append), append_errno_(true) {}
124 
125   template <typename T>
126   // NOLINTNEXTLINE(google-explicit-constructor)
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) {
133     // NOLINTNEXTLINE(bugprone-suspicious-semicolon)
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     }
138     int saved = errno;
139     ss_ << t;
140     errno = saved;
141     return *this;
142   }
143 
str()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 
160   template <typename T, typename... Args>
161   friend Error ErrorfImpl(const T&& fmt, const Args&... args);
162 
163   template <typename T, typename... Args>
164   friend Error ErrnoErrorfImpl(const T&& fmt, const Args&... args);
165 
166  private:
Error(bool append_errno,int errno_to_append,const std::string & message)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 
172   std::stringstream ss_;
173   int errno_;
174   const bool append_errno_;
175 };
176 
ErrnoError()177 inline Error ErrnoError() {
178   return Error(errno);
179 }
180 
ErrorCode(int code)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>
ErrorCode(int code,T && t,const Args &...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 
195 template <typename T, typename... Args>
ErrorfImpl(const T && fmt,const Args &...args)196 inline Error ErrorfImpl(const T&& fmt, const Args&... args) {
197   return Error(false, ErrorCode(0, args...), fmt::format(fmt, args...));
198 }
199 
200 template <typename T, typename... Args>
ErrnoErrorfImpl(const T && fmt,const Args &...args)201 inline Error ErrnoErrorfImpl(const T&& fmt, const Args&... args) {
202   return Error(true, errno, fmt::format(fmt, args...));
203 }
204 
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 
208 template <typename T>
209 using Result = android::base::expected<T, ResultError>;
210 
211 // Macros for testing the results of functions that return android::base::Result.
212 // These also work with base::android::expected.
213 
214 #define CHECK_RESULT_OK(stmt)       \
215   do {                              \
216     const auto& tmp = (stmt);       \
217     CHECK(tmp.ok()) << tmp.error(); \
218   } while (0)
219 
220 #define ASSERT_RESULT_OK(stmt)            \
221   do {                                    \
222     const auto& tmp = (stmt);             \
223     ASSERT_TRUE(tmp.ok()) << tmp.error(); \
224   } while (0)
225 
226 #define EXPECT_RESULT_OK(stmt)            \
227   do {                                    \
228     auto tmp = (stmt);                    \
229     EXPECT_TRUE(tmp.ok()) << tmp.error(); \
230   } while (0)
231 
232 // TODO: Maybe add RETURN_IF_ERROR() and ASSIGN_OR_RETURN()
233 
234 }  // namespace base
235 }  // namespace android
236