Bug 1581859: Part 3a - Add do_GetProperty helper for nsIPropertyBag2. r=mccr8

There currently isn't a typesafe way to get a property with a given interface
from a property bag from C++. This patch adds one, following the pattern of
similar helpers, like `do_GetInterface`.

Differential Revision: https://phabricator.services.mozilla.com/D103210
This commit is contained in:
Kris Maglione 2021-03-25 19:47:01 +00:00
parent 301532bc94
commit 35305e871d
2 changed files with 55 additions and 0 deletions

View File

@ -265,6 +265,23 @@ void nsHashPropertyBagBase::CopyFrom(nsIPropertyBag* aOther) {
}
}
nsresult nsGetProperty::operator()(const nsIID& aIID,
void** aInstancePtr) const {
nsresult rv;
if (mPropBag) {
rv = mPropBag->GetPropertyAsInterface(mPropName, aIID, aInstancePtr);
} else {
rv = NS_ERROR_NULL_POINTER;
*aInstancePtr = 0;
}
if (mErrorPtr) {
*mErrorPtr = rv;
}
return rv;
}
/*
* nsHashPropertyBag implementation.
*/

View File

@ -24,6 +24,9 @@ interface nsIPropertyBag2 : nsIPropertyBag
/**
* This method returns null if the value exists, but is null.
*
* Note: C++ callers should not use this method. They should use the
* typesafe `do_GetProperty` wrapper instead.
*/
void getPropertyAsInterface (in AString prop,
in nsIIDRef iid,
@ -40,3 +43,38 @@ interface nsIPropertyBag2 : nsIPropertyBag
*/
boolean hasKey (in AString prop);
};
%{C++
#include "nsCOMPtr.h"
#include "nsAString.h"
class MOZ_STACK_CLASS nsGetProperty final : public nsCOMPtr_helper {
public:
nsGetProperty(nsIPropertyBag2* aPropBag, const nsAString& aPropName, nsresult* aError)
: mPropBag(aPropBag), mPropName(aPropName), mErrorPtr(aError) {}
virtual nsresult NS_FASTCALL operator()(const nsIID&, void**) const override;
private:
nsIPropertyBag2* MOZ_NON_OWNING_REF mPropBag;
const nsAString& mPropName;
nsresult* mErrorPtr;
};
/**
* A typesafe wrapper around nsIPropertyBag2::GetPropertyAsInterface. Similar
* to the `do_QueryInterface` family of functions, when assigned to a
* `nsCOMPtr` of a given type, attempts to query the given property to that
* type.
*
* If `aError` is passed, the return value of `GetPropertyAsInterface` is
* stored in it.
*/
inline const nsGetProperty do_GetProperty(nsIPropertyBag2* aPropBag,
const nsAString& aPropName,
nsresult* aError = 0) {
return nsGetProperty(aPropBag, aPropName, aError);
}
%}