Hi,

as part of https://bugzil.la/1637605 I recently made some additions to
the mozilla::Result<V, nsresult> integration available from
mozilla/ResultExtensions.h.

It adds several overloads of a ToResultInvoke function template, which
kind of combines ToResult and std::invoke. It allows to call a XPCOM
style function with a nsresult return value and an output parameter of
type V as the last parameter, and adapts that to returning a
mozilla::Result<V, nsresult> instead. (Note that not all functions
with nsresult return type adhere to this convention, and those cannot
be used with ToResultInvoke. Also, functions with multiple output
parameters are not yet supported.)

The examples below make use of auto, but of course you can also
explicitly specify the resulting type explicitly.

The general version requires specifying the return type explicitly, e.g.

auto res = ToResultInvoke<bool>(&HasIndexes, objectStoreName);

The result type is mozilla::Result<bool, nsresult> then.
Functions without an output parameter will adapt to
mozilla::Result<Ok, nsresult>.

For member functions, a simplified syntax is available that also
allows deduction of the success type V:

auto res = ToResultInvoke(file, &nsIFile::Exists);

which yields a res of type mozilla::Result<bool, nsresult>.

This also works for polymorphic output parameters and returning a nsCOMPtr, e.g.

auto res = ToResultInvoke<nsCOMPtr<nsIFile>>(NS_NewLocalFile, name, true);

However, this doesn't work (yet) with the simplified syntax for member
functions but requires using std::mem_fn in that case:

auto res =
  ToResultInvoke<nsCOMPtr<nsIInputStream>>(
    std::mem_fn(&nsIChannel::Open), channel);

E.g. this can be used in connection with mozilla::Result::andThen to
compose a sequence of calls.

You can find more example uses in mfbt/tests/gtest/TestResultExtensions.cpp

If you have any questions or suggestions about this, please let me know.

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

Reply via email to