Change the MozMap API and data storage to more what we want record<> to look like

This commit is contained in:
JustOff 2019-03-13 18:46:01 +02:00 • committed by Roy Tam
commit 4faee1f41a
4 changed files with 55 additions and 103 deletions

View file

@ -2293,19 +2293,13 @@ public:
} }
}; };
template<typename T>
static void
TraceMozMapValue(T* aValue, void* aClosure)
{
JSTracer* trc = static_cast<JSTracer*>(aClosure);
// Act like it's a one-element sequence to leverage all that infrastructure.
SequenceTracer<T>::TraceSequence(trc, aValue, aValue + 1);
}
template<typename T> template<typename T>
void TraceMozMap(JSTracer* trc, MozMap<T>& map) void TraceMozMap(JSTracer* trc, MozMap<T>& map)
{ {
map.EnumerateValues(TraceMozMapValue<T>, trc); for (auto& entry : map.Entries()) {
// Act like it's a one-element sequence to leverage all that infrastructure.
SequenceTracer<T>::TraceSequence(trc, &entry.mValue, &entry.mValue + 1);
}
} }
// sequence<MozMap> // sequence<MozMap>
@ -2317,7 +2311,7 @@ class SequenceTracer<MozMap<T>, false, false, false>
public: public:
static void TraceSequence(JSTracer* trc, MozMap<T>* seqp, MozMap<T>* end) { static void TraceSequence(JSTracer* trc, MozMap<T>* seqp, MozMap<T>* end) {
for (; seqp != end; ++seqp) { for (; seqp != end; ++seqp) {
seqp->EnumerateValues(TraceMozMapValue<T>, trc); TraceMozMap(trc, *seqp);
} }
} }
}; };

View file

@ -4774,20 +4774,21 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None,
templateBody = fill( templateBody = fill(
""" """
${mozMapType} &mozMap = ${mozMapRef}; auto& mozMapEntries = ${mozMapRef}.Entries();
JS::Rooted<JSObject*> mozMapObj(cx, &$${val}.toObject()); JS::Rooted<JSObject*> mozMapObj(cx, &$${val}.toObject());
JS::Rooted<JS::IdVector> ids(cx, JS::IdVector(cx)); JS::Rooted<JS::IdVector> ids(cx, JS::IdVector(cx));
if (!JS_Enumerate(cx, mozMapObj, &ids)) { if (!JS_Enumerate(cx, mozMapObj, &ids)) {
$*{exceptionCode} $*{exceptionCode}
} }
if (!mozMapEntries.SetCapacity(ids.length(), mozilla::fallible)) {
JS_ReportOutOfMemory(cx);
$*{exceptionCode}
}
JS::Rooted<JS::Value> propNameValue(cx); JS::Rooted<JS::Value> propNameValue(cx);
JS::Rooted<JS::Value> temp(cx); JS::Rooted<JS::Value> temp(cx);
JS::Rooted<jsid> curId(cx); JS::Rooted<jsid> curId(cx);
for (size_t i = 0; i < ids.length(); ++i) { for (size_t i = 0; i < ids.length(); ++i) {
// Make sure we get the value before converting the name, since
// getting the value can trigger GC but our name is a dependent
// string.
curId = ids[i]; curId = ids[i];
binding_detail::FakeString propName; binding_detail::FakeString propName;
bool isSymbol; bool isSymbol;
@ -4799,18 +4800,17 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None,
continue; continue;
} }
${valueType}* slotPtr = mozMap.AddEntry(propName); // Safe to do an infallible append here, because we did a
if (!slotPtr) { // SetCapacity above to the right capacity.
JS_ReportOutOfMemory(cx); ${mozMapType}::EntryType* entry = mozMapEntries.AppendElement();
$*{exceptionCode} entry->mKey = propName;
} ${valueType}& slot = entry->mValue;
${valueType}& slot = *slotPtr;
$*{valueConversion} $*{valueConversion}
} }
""", """,
exceptionCode=exceptionCode, exceptionCode=exceptionCode,
mozMapType=mozMapType,
mozMapRef=mozMapRef, mozMapRef=mozMapRef,
mozMapType=mozMapType,
valueType=valueInfo.declType.define(), valueType=valueInfo.declType.define(),
valueConversion=valueConversion) valueConversion=valueConversion)
@ -6460,8 +6460,6 @@ def getWrapTemplateForType(type, descriptorProvider, result, successCode,
code = fill( code = fill(
""" """
nsTArray<nsString> keys;
${result}.GetKeys(keys);
JS::Rooted<JSObject*> returnObj(cx, JS_NewPlainObject(cx)); JS::Rooted<JSObject*> returnObj(cx, JS_NewPlainObject(cx));
if (!returnObj) { if (!returnObj) {
$*{exceptionCode} $*{exceptionCode}
@ -6469,15 +6467,16 @@ def getWrapTemplateForType(type, descriptorProvider, result, successCode,
// Scope for 'tmp' // Scope for 'tmp'
{ {
JS::Rooted<JS::Value> tmp(cx); JS::Rooted<JS::Value> tmp(cx);
for (size_t idx = 0; idx < keys.Length(); ++idx) { for (auto& entry : ${result}.Entries()) {
auto& ${valueName} = ${result}.Get(keys[idx]); auto& ${valueName} = entry.mValue;
// Control block to let us common up the JS_DefineUCProperty calls when there // Control block to let us common up the JS_DefineUCProperty calls when there
// are different ways to succeed at wrapping the value. // are different ways to succeed at wrapping the value.
do { do {
$*{innerTemplate} $*{innerTemplate}
} while (0); } while (0);
if (!JS_DefineUCProperty(cx, returnObj, keys[idx].get(), if (!JS_DefineUCProperty(cx, returnObj,
keys[idx].Length(), tmp, entry.mKey.BeginReading(),
entry.mKey.Length(), tmp,
JSPROP_ENUMERATE)) { JSPROP_ENUMERATE)) {
$*{exceptionCode} $*{exceptionCode}
} }
@ -7202,28 +7201,26 @@ def wrapTypeIntoCurrentCompartment(type, value, isMember=True):
return wrapCode return wrapCode
if type.isMozMap(): if type.isMozMap():
origValue = value
origType = type origType = type
if type.nullable(): if type.nullable():
type = type.inner type = type.inner
value = "%s.Value()" % value mozMapRef = "%s.Value()" % value
else:
mozMapRef = value
global mapWrapLevel global mapWrapLevel
key = "mapName%d" % mapWrapLevel entryRef = "mapEntry%d" % mapWrapLevel
mapWrapLevel += 1 mapWrapLevel += 1
wrapElement = wrapTypeIntoCurrentCompartment(type.inner, wrapElement = wrapTypeIntoCurrentCompartment(type.inner,
"%s.Get(%sKeys[%sIndex])" % (value, key, key)) "%s.mValue" % entryRef)
mapWrapLevel -= 1 mapWrapLevel -= 1
if not wrapElement: if not wrapElement:
return None return None
wrapCode = CGWrapper(CGIndenter(wrapElement), wrapCode = CGWrapper(CGIndenter(wrapElement),
pre=(""" pre=("for (auto& %s : %s.Entries()) {\n" %
nsTArray<nsString> %sKeys; (entryRef, mozMapRef)),
%s.GetKeys(%sKeys);
for (uint32_t %sIndex = 0; %sIndex < %sKeys.Length(); ++%sIndex) {
""" % (key, value, key, key, key, key, key)),
post="}\n") post="}\n")
if origType.nullable(): if origType.nullable():
wrapCode = CGIfWrapper(wrapCode, "!%s.IsNull()" % origValue) wrapCode = CGIfWrapper(wrapCode, "!%s.IsNull()" % value)
return wrapCode return wrapCode
if type.isDictionary(): if type.isDictionary():

View file

@ -5,9 +5,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** /**
* Class for representing MozMap arguments. This is an nsTHashtable * Class for representing MozMap arguments. Basically an array under the hood.
* under the hood, but we don't want to leak that implementation
* detail.
*/ */
#ifndef mozilla_dom_MozMap_h #ifndef mozilla_dom_MozMap_h
@ -24,34 +22,34 @@ namespace mozilla {
namespace dom { namespace dom {
namespace binding_detail { namespace binding_detail {
template<typename DataType> template<typename KeyType, typename ValueType>
class MozMapEntry : public nsStringHashKey class MozMapEntry
{ {
public: public:
explicit MozMapEntry(const nsAString* aKeyTypePointer) MozMapEntry()
: nsStringHashKey(aKeyTypePointer)
{ {
} }
// Move constructor so we can do MozMaps of MozMaps. // Move constructor so we can do MozMaps of MozMaps.
MozMapEntry(MozMapEntry<DataType>&& aOther) MozMapEntry(MozMapEntry<KeyType, ValueType>&& aOther)
: nsStringHashKey(aOther), : mKey(Move(aOther.mKey)),
mData(Move(aOther.mData)) mValue(Move(aOther.mValue))
{ {
} }
DataType mData; KeyType mKey;
ValueType mValue;
}; };
} // namespace binding_detail } // namespace binding_detail
template<typename DataType> template<typename ValueType>
class MozMap : protected nsTHashtable<binding_detail::MozMapEntry<DataType>> class MozMap
{ {
public: public:
typedef typename binding_detail::MozMapEntry<DataType> EntryType; typedef nsString KeyType;
typedef nsTHashtable<EntryType> Base; typedef typename binding_detail::MozMapEntry<KeyType, ValueType> EntryType;
typedef MozMap<DataType> SelfType; typedef MozMap<ValueType> SelfType;
MozMap() MozMap()
{ {
@ -59,60 +57,22 @@ public:
// Move constructor so we can do MozMap of MozMap. // Move constructor so we can do MozMap of MozMap.
MozMap(SelfType&& aOther) : MozMap(SelfType&& aOther) :
Base(Move(aOther)) mEntries(Move(aOther.mEntries))
{ {
} }
// The return value is only safe to use until an AddEntry call. const nsTArray<EntryType>& Entries() const
const DataType& Get(const nsAString& aKey) const
{ {
const EntryType* ent = this->GetEntry(aKey); return mEntries;
MOZ_ASSERT(ent, "Why are you using a key we didn't claim to have?");
return ent->mData;
} }
DataType& Get(const nsAString& aKey) nsTArray<EntryType>& Entries()
{ {
EntryType* ent = this->GetEntry(aKey); return mEntries;
MOZ_ASSERT(ent, "Why are you using a key we didn't claim to have?");
return ent->mData;
} }
// The return value is only safe to use until an AddEntry call. private:
const DataType* GetIfExists(const nsAString& aKey) const nsTArray<EntryType> mEntries;
{
const EntryType* ent = this->GetEntry(aKey);
if (!ent) {
return nullptr;
}
return &ent->mData;
}
void GetKeys(nsTArray<nsString>& aKeys) const {
for (auto iter = this->ConstIter(); !iter.Done(); iter.Next()) {
aKeys.AppendElement(iter.Get()->GetKey());
}
}
// XXXbz we expose this generic enumerator for tracing. Otherwise we'd end up
// with a dependency on BindingUtils.h here for the SequenceTracer bits.
typedef void (* Enumerator)(DataType* aValue, void* aClosure);
void EnumerateValues(Enumerator aEnumerator, void *aClosure)
{
for (auto iter = this->Iter(); !iter.Done(); iter.Next()) {
aEnumerator(&iter.Get()->mData, aClosure);
}
}
MOZ_MUST_USE
DataType* AddEntry(const nsAString& aKey)
{
EntryType* ent = this->PutEntry(aKey, fallible);
if (!ent) {
return nullptr;
}
return &ent->mData;
}
}; };
} // namespace dom } // namespace dom

View file

@ -316,10 +316,11 @@ InternalHeaders::Fill(const Sequence<Sequence<nsCString>>& aInit, ErrorResult& a
void void
InternalHeaders::Fill(const MozMap<nsCString>& aInit, ErrorResult& aRv) InternalHeaders::Fill(const MozMap<nsCString>& aInit, ErrorResult& aRv)
{ {
nsTArray<nsString> keys; for (auto& entry : aInit.Entries()) {
aInit.GetKeys(keys); Append(NS_ConvertUTF16toUTF8(entry.mKey), entry.mValue, aRv);
for (uint32_t i = 0; i < keys.Length() && !aRv.Failed(); ++i) { if (aRv.Failed()) {
Append(NS_ConvertUTF16toUTF8(keys[i]), aInit.Get(keys[i]), aRv); return;
}
} }
} }