From d21a535bf6201163d1cd4a14ba77a07a94535fa7 Mon Sep 17 00:00:00 2001 From: Lang Hames Date: Thu, 24 Mar 2016 02:00:10 +0000 Subject: [PATCH] [Support] Add conversions between Expected and ErrorOr. More utilities to help with std::error_code -> Error transitions. llvm-svn: 264238 --- llvm/include/llvm/Support/Error.h | 16 ++++++++++++++++ llvm/unittests/Support/ErrorTest.cpp | 25 ++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/llvm/include/llvm/Support/Error.h b/llvm/include/llvm/Support/Error.h index f1eccf8..1432cb1 100644 --- a/llvm/include/llvm/Support/Error.h +++ b/llvm/include/llvm/Support/Error.h @@ -753,6 +753,22 @@ inline std::error_code errorToErrorCode(Error Err) { return EC; } +/// Convert an ErrorOr to an Expected. +template +Expected errorOrToExpected(ErrorOr &&EO) { + if (auto EC = EO.getError()) + return errorCodeToError(EC); + return std::move(*EO); +} + +/// Convert an Expected to an ErrorOr. +template +ErrorOr expectedToErrorOr(Expected &&E) { + if (auto Err = E.takeError()) + return errorToErrorCode(std::move(Err)); + return std::move(*E); +} + /// Helper for check-and-exit error handling. /// /// For tool use only. NOT FOR USE IN LIBRARY CODE. diff --git a/llvm/unittests/Support/ErrorTest.cpp b/llvm/unittests/Support/ErrorTest.cpp index 1807547..fadb00c 100644 --- a/llvm/unittests/Support/ErrorTest.cpp +++ b/llvm/unittests/Support/ErrorTest.cpp @@ -416,7 +416,7 @@ TEST(Error, ExpectedCovariance) { A2 = Expected>(nullptr); } -TEST(Error, ECError) { +TEST(Error, ErrorCodeConversions) { // Round-trip a success value to check that it converts correctly. EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())), std::error_code()) @@ -427,6 +427,29 @@ TEST(Error, ECError) { errc::invalid_argument) << "std::error_code error value should round-trip via Error " "conversions"; + + // Round-trip a success value through ErrorOr/Expected to check that it + // converts correctly. + { + auto Orig = ErrorOr(42); + auto RoundTripped = + expectedToErrorOr(errorOrToExpected(ErrorOr(42))); + EXPECT_EQ(*Orig, *RoundTripped) + << "ErrorOr success value should round-trip via Expected " + "conversions."; + } + + // Round-trip a failure value through ErrorOr/Expected to check that it + // converts correctly. + { + auto Orig = ErrorOr(errc::invalid_argument); + auto RoundTripped = + expectedToErrorOr( + errorOrToExpected(ErrorOr(errc::invalid_argument))); + EXPECT_EQ(Orig.getError(), RoundTripped.getError()) + << "ErrorOr failure value should round-trip via Expected " + "conversions."; + } } } // end anon namespace -- 2.7.4