FTL: Add Optional<T>::ok_or and FTL_TRY
Optional<T>::ok_or maps to Expected<T, E> where nullopt becomes E.
FTL_TRY unwraps T for Expected<T, E> or does an early out on error.
Bug: 185536303
Test: ftl_test
Change-Id: Ia03f7e3d8773878db1c493b62772ab2c2b7a4fed
diff --git a/include/ftl/expected.h b/include/ftl/expected.h
index 12b6102..57448dc 100644
--- a/include/ftl/expected.h
+++ b/include/ftl/expected.h
@@ -18,9 +18,57 @@
#include <android-base/expected.h>
#include <ftl/optional.h>
+#include <ftl/unit.h>
#include <utility>
+// Given an expression `expr` that evaluates to an ftl::Expected<T, E> result (R for short), FTL_TRY
+// unwraps T out of R, or bails out of the enclosing function F if R has an error E. The return type
+// of F must be R, since FTL_TRY propagates R in the error case. As a special case, ftl::Unit may be
+// used as the error E to allow FTL_TRY expressions when F returns `void`.
+//
+// The non-standard syntax requires `-Wno-gnu-statement-expression-from-macro-expansion` to compile.
+// The UnitToVoid conversion allows the macro to be used for early exit from a function that returns
+// `void`.
+//
+// Example usage:
+//
+// using StringExp = ftl::Expected<std::string, std::errc>;
+//
+// StringExp repeat(StringExp exp) {
+// const std::string str = FTL_TRY(exp);
+// return StringExp(str + str);
+// }
+//
+// assert(StringExp("haha"s) == repeat(StringExp("ha"s)));
+// assert(repeat(ftl::Unexpected(std::errc::bad_message)).has_error([](std::errc e) {
+// return e == std::errc::bad_message;
+// }));
+//
+//
+// FTL_TRY may be used in void-returning functions by using ftl::Unit as the error type:
+//
+// void uppercase(char& c, ftl::Optional<char> opt) {
+// c = std::toupper(FTL_TRY(std::move(opt).ok_or(ftl::Unit())));
+// }
+//
+// char c = '?';
+// uppercase(c, std::nullopt);
+// assert(c == '?');
+//
+// uppercase(c, 'a');
+// assert(c == 'A');
+//
+#define FTL_TRY(expr) \
+ ({ \
+ auto exp_ = (expr); \
+ if (!exp_.has_value()) { \
+ using E = decltype(exp_)::error_type; \
+ return android::ftl::details::UnitToVoid<E>::from(std::move(exp_)); \
+ } \
+ exp_.value(); \
+ })
+
namespace android::ftl {
// Superset of base::expected<T, E> with monadic operations.
diff --git a/include/ftl/optional.h b/include/ftl/optional.h
index 94d8e3d..e245d88 100644
--- a/include/ftl/optional.h
+++ b/include/ftl/optional.h
@@ -20,13 +20,14 @@
#include <optional>
#include <utility>
+#include <android-base/expected.h>
#include <ftl/details/optional.h>
namespace android::ftl {
// Superset of std::optional<T> with monadic operations, as proposed in https://wg21.link/P0798R8.
//
-// TODO: Remove in C++23.
+// TODO: Remove standard APIs in C++23.
//
template <typename T>
struct Optional final : std::optional<T> {
@@ -109,6 +110,13 @@
return std::forward<F>(f)();
}
+ // Maps this Optional<T> to expected<T, E> where nullopt becomes E.
+ template <typename E>
+ constexpr auto ok_or(E&& e) && -> base::expected<T, E> {
+ if (has_value()) return std::move(value());
+ return base::unexpected(std::forward<E>(e));
+ }
+
// Delete new for this class. Its base doesn't have a virtual destructor, and
// if it got deleted via base class pointer, it would cause undefined
// behavior. There's not a good reason to allocate this object on the heap
diff --git a/include/ftl/unit.h b/include/ftl/unit.h
index e38230b..62549a3 100644
--- a/include/ftl/unit.h
+++ b/include/ftl/unit.h
@@ -58,4 +58,22 @@
return {std::forward<F>(f)};
}
+namespace details {
+
+// Identity function for all T except Unit, which maps to void.
+template <typename T>
+struct UnitToVoid {
+ template <typename U>
+ static auto from(U&& value) {
+ return value;
+ }
+};
+
+template <>
+struct UnitToVoid<Unit> {
+ template <typename U>
+ static void from(U&&) {}
+};
+
+} // namespace details
} // namespace android::ftl
diff --git a/libs/ftl/Android.bp b/libs/ftl/Android.bp
index 4b41152..368f5e0 100644
--- a/libs/ftl/Android.bp
+++ b/libs/ftl/Android.bp
@@ -41,5 +41,6 @@
"-Wextra",
"-Wpedantic",
"-Wthread-safety",
+ "-Wno-gnu-statement-expression-from-macro-expansion",
],
}
diff --git a/libs/ftl/expected_test.cpp b/libs/ftl/expected_test.cpp
index 8cb07e4..9b7f017 100644
--- a/libs/ftl/expected_test.cpp
+++ b/libs/ftl/expected_test.cpp
@@ -15,8 +15,11 @@
*/
#include <ftl/expected.h>
+#include <ftl/optional.h>
+#include <ftl/unit.h>
#include <gtest/gtest.h>
+#include <cctype>
#include <string>
#include <system_error>
@@ -74,4 +77,42 @@
}
}
+namespace {
+
+IntExp increment(IntExp exp) {
+ const int i = FTL_TRY(exp);
+ return IntExp(i + 1);
+}
+
+StringExp repeat(StringExp exp) {
+ const std::string str = FTL_TRY(exp);
+ return StringExp(str + str);
+}
+
+void uppercase(char& c, ftl::Optional<char> opt) {
+ c = std::toupper(FTL_TRY(std::move(opt).ok_or(ftl::Unit())));
+}
+
+} // namespace
+
+// Keep in sync with example usage in header file.
+TEST(Expected, Try) {
+ EXPECT_EQ(IntExp(100), increment(IntExp(99)));
+ EXPECT_TRUE(repeat(ftl::Unexpected(std::errc::value_too_large)).has_error([](std::errc e) {
+ return e == std::errc::value_too_large;
+ }));
+
+ EXPECT_EQ(StringExp("haha"s), repeat(StringExp("ha"s)));
+ EXPECT_TRUE(repeat(ftl::Unexpected(std::errc::bad_message)).has_error([](std::errc e) {
+ return e == std::errc::bad_message;
+ }));
+
+ char c = '?';
+ uppercase(c, std::nullopt);
+ EXPECT_EQ(c, '?');
+
+ uppercase(c, 'a');
+ EXPECT_EQ(c, 'A');
+}
+
} // namespace android::test
diff --git a/libs/ftl/optional_test.cpp b/libs/ftl/optional_test.cpp
index 91bf7bc..e7f1f14 100644
--- a/libs/ftl/optional_test.cpp
+++ b/libs/ftl/optional_test.cpp
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+#include <ftl/expected.h>
#include <ftl/optional.h>
#include <ftl/static_vector.h>
#include <ftl/string.h>
@@ -23,6 +24,7 @@
#include <cstdlib>
#include <functional>
#include <numeric>
+#include <system_error>
#include <utility>
using namespace std::placeholders;
@@ -204,6 +206,19 @@
.or_else([] { return Optional(-1); }));
}
+TEST(Optional, OkOr) {
+ using CharExp = ftl::Expected<char, std::errc>;
+ using StringExp = ftl::Expected<std::string, std::errc>;
+
+ EXPECT_EQ(CharExp('z'), Optional('z').ok_or(std::errc::broken_pipe));
+ EXPECT_EQ(CharExp(ftl::Unexpected(std::errc::broken_pipe)),
+ Optional<char>().ok_or(std::errc::broken_pipe));
+
+ EXPECT_EQ(StringExp("abc"s), Optional("abc"s).ok_or(std::errc::protocol_error));
+ EXPECT_EQ(StringExp(ftl::Unexpected(std::errc::protocol_error)),
+ Optional<std::string>().ok_or(std::errc::protocol_error));
+}
+
// Comparison.
namespace {