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/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