I think these seem like valuable additions to nscore.h. It would be helpful to extend these facilities that would allow more code to use the Result-based programming model.

(I'm not too much of a fan of the NS_TRY name, but can't think of a better name myself... :/ )


On 05/07/2017 03:34 PM, Kris Maglione wrote:
I've been trying to write most of my new code to use Result.h as much as possible. When I have to mix Result-based code with nsresult-based code, though, things tend to get ugly, and I wind up writing helpers. At this point I've wound up writing the same helpers in 3 or 4 different places, so it may be time to try to standardize on something.

The helpers I've been using look something like:

 template <>
 class MOZ_MUST_USE_TYPE GenericErrorResult<nsresult>
 {
   nsresult mErrorValue;

   template<typename V, typename E2> friend class Result;

 public:
explicit GenericErrorResult(nsresult aErrorValue) : mErrorValue(aErrorValue) {}

   operator nsresult() { return mErrorValue; }
 };

 static inline Result<Ok, nsresult>
 WrapNSResult(PRStatus aRv)
 {
     if (aRv != PR_SUCCESS) {
         return Err(NS_ERROR_FAILURE);
     }
     return Ok();
 }

 static inline Result<Ok, nsresult>
 WrapNSResult(nsresult aRv)
 {
     if (NS_FAILED(aRv)) {
         return Err(aRv);
     }
     return Ok();
 }

 #define NS_TRY(expr) MOZ_TRY(WrapNSResult(expr))

And their use looks something like:

 Result<nsCOMPtr<nsIFile>, nsresult>
 GetFile(nsIFile* aBase, const char* aChild)
 {
   nsCOMPtr<nsIFile> file;
   NS_TRY(aBase->Clone(getter_AddRefs(file)));
   NS_TRY(aBase->AppendNative(aChild));

   return Move(file);
 }

 nsresult
 ReadFile(const char* aPath)
 {
   nsCOMPtr<nsIFile> file;
   MOZ_TRY_VAR(file, GetFile(mBase, aPath));

   PRFileDesc* fd;
   NS_TRY(file->OpenNSPRFileDesc(PR_RDONLY, 0, &fd));

   ...
   return NS_OK;
 }

Where NS_TRY converts a nsresult or PRStatus to an appropriate Result or GenericErrorResult, and the GenericErrorResult<nsresult> specialization automatically converts an nsresult when used in nsresult-based code.

Does this seem like the kind of thing we should implement in some standard header, or would a different approach be better?

-Kris
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to