From 3cea1dc6758709e9fd1d87e03e7baee023a1dc72 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Fri, 3 Nov 2023 08:13:19 +0000 Subject: [PATCH] Bug 1850723 - Make mozilla::Result constructor take another result with convertible value. r=emilio,glandium Differential Revision: https://phabricator.services.mozilla.com/D191538 --- mfbt/Result.h | 12 +++++----- mfbt/tests/TestResult.cpp | 47 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/mfbt/Result.h b/mfbt/Result.h index c3c96d1fbfb3..052920fdbf17 100644 --- a/mfbt/Result.h +++ b/mfbt/Result.h @@ -561,11 +561,13 @@ class [[nodiscard]] Result final { } /** - * Create a (success/error) result from another (success/error) result with a - * different but convertible error type. */ - template >> - MOZ_IMPLICIT constexpr Result(Result&& aOther) + * Create a (success/error) result from another (success/error) result with + * different but convertible value and error types. + */ + template && + std::is_convertible_v>> + MOZ_IMPLICIT constexpr Result(Result&& aOther) : mImpl(aOther.isOk() ? Impl{aOther.unwrap()} : Impl{aOther.unwrapErr()}) {} diff --git a/mfbt/tests/TestResult.cpp b/mfbt/tests/TestResult.cpp index dd9c5f695e75..a2e10640c5d9 100644 --- a/mfbt/tests/TestResult.cpp +++ b/mfbt/tests/TestResult.cpp @@ -806,6 +806,52 @@ static void ZeroIsEmptyErrorTest() { } } +class Foo {}; + +class C1 {}; +class C2 : public C1 {}; + +class E1 {}; +class E2 : public E1 {}; + +void UpcastTest() { + { + C2 c2; + + mozilla::Result result(&c2); + mozilla::Result copied(std::move(result)); + + MOZ_RELEASE_ASSERT(copied.inspect() == &c2); + } + + { + E2 e2; + + mozilla::Result result(Err(&e2)); + mozilla::Result copied(std::move(result)); + + MOZ_RELEASE_ASSERT(copied.inspectErr() == &e2); + } + + { + C2 c2; + + mozilla::Result result(&c2); + mozilla::Result copied(std::move(result)); + + MOZ_RELEASE_ASSERT(copied.inspect() == &c2); + } + + { + E2 e2; + + mozilla::Result result(Err(&e2)); + mozilla::Result copied(std::move(result)); + + MOZ_RELEASE_ASSERT(copied.inspectErr() == &e2); + } +} + /* * */ int main() { @@ -819,5 +865,6 @@ int main() { AndThenTest(); UniquePtrTest(); ZeroIsEmptyErrorTest(); + UpcastTest(); return 0; }