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