As of the landing of bug 1366511, it's now possible to use MOZ_TRY with and from functions that return nsresult values. This means that, among other things, it's now easy to use mozilla::Result from XPCOM methods, and vice versa, as long as the Result error type is nsresult:

   #include "mozilla/ResultExtensions.h"

   Result<nsCOMPtr<nsIFile>, nsresult>
   OpenFile(const nsACtring& aPath)
   {
     nsCOMPtr<nsIFile> file;
     MOZ_TRY(NS_NewLocalFile(aPath, false, getter_AddRefs(file)));
     return Move(file);
   }

   nsresult
   Thing::DoStuff()
   {
     nsCOMPtr<nsIFile> file;
     MOZ_TRY_VAR(file, OpenFile(mPath));

     MOZ_TRY(file->GetNSPRFileDescriptor(...));
     ...

     return NS_OK;
   }

This works thanks to a mozilla::ToResult() helper, which MOZ_TRY calls to convert arbitrary types to Result<T, E> (which incidentally also supports PRStatus by default), and GenericErrorResult<nsresult> type that auto-converts to nsresult.


As a side note, there's a particular optimization for the type Result<Ok, nsresult> so that it occupies the same amount of space as a bare nsresult, and code like this:

   Result<Ok, nsresult> MaybeThing();

   Result<Ok, nsresult>
   Thing()
   {
     MOZ_TRY(MaybeThing());
     return Ok();
   }

compiles to essentially the same machine code as:

   nsresult MaybeThing();

   nsresult
   Thing()
   {
     nsresult rv = MaybeThing();
     if (rv != NS_OK) {
         return rv;
     }
     return NS_OK;
   }

With the difference that the only success value MaybeThing() is allowed to return is NS_OK.
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to