Bug 1419682 - add unwrap_or() for Result. r=Waldo
authorAlfredo.Yang <ayang@mozilla.com>
Wed, 22 Nov 2017 17:14:28 +0800
changeset 445799 1dc61d2e904d5b2c1299436b52ebda7f43942859
parent 445798 8b00dd26d6b586ac52cec8d7e636c049afaaae28
child 445800 8c17fff098eae31fb9f424f49ad648d4d8a2446e
push id8527
push userCallek@gmail.com
push dateThu, 11 Jan 2018 21:05:50 +0000
treeherdermozilla-beta@95342d212a7a [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersWaldo
bugs1419682
milestone59.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1419682 - add unwrap_or() for Result. r=Waldo MozReview-Commit-ID: FmPvPzUmN9j
mfbt/Result.h
mfbt/tests/TestResult.cpp
--- a/mfbt/Result.h
+++ b/mfbt/Result.h
@@ -335,16 +335,24 @@ public:
   bool isErr() const { return !mImpl.isOk(); }
 
   /** Get the success value from this Result, which must be a success result. */
   V unwrap() const {
     MOZ_ASSERT(isOk());
     return mImpl.unwrap();
   }
 
+  /**
+   *  Get the success value from this Result, which must be a success result.
+   *  If it is an error result, then return the aValue.
+   */
+  V unwrapOr(V aValue) const {
+    return isOk() ? mImpl.unwrap() : aValue;
+  }
+
   /** Get the error value from this Result, which must be an error result. */
   E unwrapErr() const {
     MOZ_ASSERT(isErr());
     return mImpl.unwrapErr();
   }
 
   /**
    * Map a function V -> W over this result's success variant. If this result is
--- a/mfbt/tests/TestResult.cpp
+++ b/mfbt/tests/TestResult.cpp
@@ -86,23 +86,26 @@ BasicTests()
   MOZ_RELEASE_ASSERT(Task1(true).isOk());
   MOZ_RELEASE_ASSERT(!Task1(true).isErr());
   MOZ_RELEASE_ASSERT(!Task1(false).isOk());
   MOZ_RELEASE_ASSERT(Task1(false).isErr());
 
   // MOZ_TRY works.
   MOZ_RELEASE_ASSERT(Task2(true, 3).isOk());
   MOZ_RELEASE_ASSERT(Task2(true, 3).unwrap() == 3);
+  MOZ_RELEASE_ASSERT(Task2(true, 3).unwrapOr(6) == 3);
   MOZ_RELEASE_ASSERT(Task2(false, 3).isErr());
+  MOZ_RELEASE_ASSERT(Task2(false, 3).unwrapOr(6) == 6);
 
   // MOZ_TRY_VAR works.
   MOZ_RELEASE_ASSERT(Task3(true, true, 3).isOk());
   MOZ_RELEASE_ASSERT(Task3(true, true, 3).unwrap() == 6);
   MOZ_RELEASE_ASSERT(Task3(true, false, 3).isErr());
   MOZ_RELEASE_ASSERT(Task3(false, true, 3).isErr());
+  MOZ_RELEASE_ASSERT(Task3(false, true, 3).unwrapOr(6) == 6);
 
   // Lvalues should work too.
   {
     Result<Ok, Failed&> res = Task1(true);
     MOZ_RELEASE_ASSERT(res.isOk());
     MOZ_RELEASE_ASSERT(!res.isErr());
 
     res = Task1(false);