From 5b19cea74ffb2419022990adb6a18241e7f8103d Mon Sep 17 00:00:00 2001 From: Andreas Farre Date: Wed, 26 May 2021 07:14:05 +0000 Subject: [PATCH] Part 4: Bug 1700623 - Add js value conversion for Record. r=peterv Depends on D111430 Differential Revision: https://phabricator.services.mozilla.com/D111431 --- dom/bindings/ToJSValue.h | 41 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/dom/bindings/ToJSValue.h b/dom/bindings/ToJSValue.h index 22ade817453f..3a4097b19e2a 100644 --- a/dom/bindings/ToJSValue.h +++ b/dom/bindings/ToJSValue.h @@ -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 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 +[[nodiscard]] bool ToJSValue(JSContext* aCx, const Record& aArgument, + JS::MutableHandle aValue) { + JS::RootedObject recordObj(aCx, JS_NewPlainObject(aCx)); + if (!recordObj) { + return false; + } + + for (auto& entry : aArgument.Entries()) { + JS::Rooted value(aCx); + if (!ToJSValue(aCx, entry.mValue, &value)) { + return false; + } + + if constexpr (std::is_same_v) { + 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