From 9daa6667ba7ca3c09d70ce6b8fc101227a0d7c6e Mon Sep 17 00:00:00 2001 From: Masha Basmanova Date: Fri, 17 May 2024 09:45:00 -0700 Subject: [PATCH] Introduce velox::Expected (#9858) Summary: `velox::Expected` can be used by no-throw APIs to return result or error. Differential Revision: D57496990 --- velox/common/base/Status.h | 5 +++++ velox/common/base/tests/StatusTest.cpp | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/velox/common/base/Status.h b/velox/common/base/Status.h index 94537b17f38c5..5e9c308b965b2 100644 --- a/velox/common/base/Status.h +++ b/velox/common/base/Status.h @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -489,6 +490,10 @@ inline Status genericToStatus(Status&& st) { } } // namespace internal + +template +using Expected = folly::Expected; + } // namespace facebook::velox template <> diff --git a/velox/common/base/tests/StatusTest.cpp b/velox/common/base/tests/StatusTest.cpp index 1b4195394083c..7ca42b3d0f3cf 100644 --- a/velox/common/base/tests/StatusTest.cpp +++ b/velox/common/base/tests/StatusTest.cpp @@ -128,5 +128,23 @@ TEST(StatusTest, macros) { ASSERT_TRUE(didThrow) << "VELOX_CHECK_OK did not throw"; } +Expected modulo(int a, int b) { + if (b == 0) { + return folly::makeUnexpected(Status::UserError("division by zero")); + } + + return a % b; +} + +TEST(StatusTest, expected) { + auto result = modulo(10, 3); + EXPECT_TRUE(result.hasValue()); + EXPECT_EQ(result.value(), 1); + + result = modulo(10, 0); + EXPECT_TRUE(result.hasError()); + EXPECT_EQ(result.error(), Status::UserError("division by zero")); +} + } // namespace } // namespace facebook::velox::test