Part 4: Bug 1700623 - Add js value conversion for Record. r=peterv

Depends on D111430

Differential Revision: https://phabricator.services.mozilla.com/D111431
This commit is contained in:
Andreas Farre 2021-05-26 07:14:05 +00:00
parent 75578a78f7
commit 5b19cea74f

View File

@ -23,9 +23,10 @@
#include "mozilla/Unused.h" // for Unused
#include "mozilla/dom/BindingUtils.h" // for MaybeWrapValue, MaybeWrapObjectOrNullValue, XPCOMObjectToJsval, GetOrCreateDOMReflector
#include "mozilla/dom/CallbackObject.h" // for CallbackObject
#include "nsID.h" // for NS_GET_TEMPLATE_IID, nsIID
#include "nsISupports.h" // for nsISupports
#include "nsStringFwd.h" // for nsAString
#include "mozilla/dom/Record.h"
#include "nsID.h" // for NS_GET_TEMPLATE_IID, nsIID
#include "nsISupports.h" // for nsISupports
#include "nsStringFwd.h" // for nsAString
#include "nsTArrayForwardDeclare.h"
#include "xpcObjectHelper.h" // for xpcObjectHelper
@ -399,6 +400,40 @@ template <typename T>
return true;
}
// Accept records of other things we accept. N.B. This assumes that
// keys are either UTF-8 or UTF-16-ish. See Bug 1706058.
template <typename K, typename V>
[[nodiscard]] bool ToJSValue(JSContext* aCx, const Record<K, V>& aArgument,
JS::MutableHandle<JS::Value> aValue) {
JS::RootedObject recordObj(aCx, JS_NewPlainObject(aCx));
if (!recordObj) {
return false;
}
for (auto& entry : aArgument.Entries()) {
JS::Rooted<JS::Value> value(aCx);
if (!ToJSValue(aCx, entry.mValue, &value)) {
return false;
}
if constexpr (std::is_same_v<nsCString, decltype(entry.mKey)>) {
NS_ConvertUTF8toUTF16 expandedKey(entry.mKey);
if (!JS_DefineUCProperty(aCx, recordObj, expandedKey.BeginReading(),
expandedKey.Length(), value, JSPROP_ENUMERATE)) {
return false;
}
} else {
if (!JS_DefineUCProperty(aCx, recordObj, entry.mKey.BeginReading(),
entry.mKey.Length(), value, JSPROP_ENUMERATE)) {
return false;
}
}
}
aValue.setObject(*recordObj);
return true;
}
} // namespace dom
} // namespace mozilla