Bug 1691894 - Replace several suboptimal uses of Put after Get by GetOrInsertWith or WithEntryHandle. r=xpcom-reviewers,necko-reviewers,kmag,valentin,geckoview-reviewers,agi

Differential Revision: https://phabricator.services.mozilla.com/D104849
This commit is contained in:
Simon Giesecke 2021-02-15 15:12:17 +00:00
parent f42597369a
commit 780a1636a9
37 changed files with 437 additions and 421 deletions

View File

@ -160,18 +160,15 @@ inline DocAccessible::AttrRelProviders* DocAccessible::GetOrCreateRelProviders(
dom::Element* aElement, const nsAString& aID) {
dom::DocumentOrShadowRoot* docOrShadowRoot =
aElement->GetUncomposedDocOrConnectedShadowRoot();
DependentIDsHashtable* hash = mDependentIDsHashes.Get(docOrShadowRoot);
if (!hash) {
hash = new DependentIDsHashtable();
mDependentIDsHashes.Put(docOrShadowRoot, hash);
}
DependentIDsHashtable* hash =
mDependentIDsHashes
.GetOrInsertWith(docOrShadowRoot,
[] { return MakeUnique<DependentIDsHashtable>(); })
.get();
AttrRelProviders* providers = hash->Get(aID);
if (!providers) {
providers = new AttrRelProviders();
hash->Put(aID, providers);
}
return providers;
return hash
->GetOrInsertWith(aID, [] { return MakeUnique<AttrRelProviders>(); })
.get();
}
inline void DocAccessible::RemoveRelProvidersIfEmpty(dom::Element* aElement,

View File

@ -201,11 +201,11 @@ EventSourceEventService::AddListener(uint64_t aInnerWindowID,
}
++mCountListeners;
WindowListener* listener = mWindows.Get(aInnerWindowID);
if (!listener) {
listener = new WindowListener();
mWindows.Put(aInnerWindowID, listener);
}
WindowListener* listener =
mWindows
.GetOrInsertWith(aInnerWindowID,
[] { return MakeUnique<WindowListener>(); })
.get();
listener->mListeners.AppendElement(aListener);

View File

@ -149,12 +149,13 @@ void PointerEventHandler::RequestPointerCaptureById(uint32_t aPointerId,
void PointerEventHandler::SetPointerCaptureById(uint32_t aPointerId,
Element* aElement) {
MOZ_ASSERT(aElement);
PointerCaptureInfo* pointerCaptureInfo = GetPointerCaptureInfo(aPointerId);
if (pointerCaptureInfo) {
pointerCaptureInfo->mPendingElement = aElement;
} else {
sPointerCaptureList->Put(aPointerId, new PointerCaptureInfo(aElement));
}
sPointerCaptureList->WithEntryHandle(aPointerId, [&](auto&& entry) {
if (entry) {
entry.Data()->mPendingElement = aElement;
} else {
entry.Insert(MakeUnique<PointerCaptureInfo>(aElement));
}
});
}
/* static */

View File

@ -672,11 +672,12 @@ void FileHandleThreadPool::Enqueue(FileHandle* aFileHandle,
const nsAString& fileName = mutableFile->FileName();
bool modeIsWrite = aFileHandle->Mode() == FileMode::Readwrite;
DirectoryInfo* directoryInfo;
if (!mDirectoryInfos.Get(directoryId, &directoryInfo)) {
directoryInfo = new DirectoryInfo(this);
mDirectoryInfos.Put(directoryId, directoryInfo);
}
DirectoryInfo* directoryInfo =
mDirectoryInfos
.GetOrInsertWith(
directoryId,
[&] { return UniquePtr<DirectoryInfo>(new DirectoryInfo(this)); })
.get();
FileHandleQueue* existingFileHandleQueue =
directoryInfo->GetFileHandleQueue(aFileHandle);

View File

@ -56,15 +56,14 @@ void FileSystemSecurity::GrantAccessToContentProcess(
MOZ_ASSERT(NS_IsMainThread());
mozilla::ipc::AssertIsInMainProcess();
nsTArray<nsString>* paths;
if (!mPaths.Get(aId, &paths)) {
paths = new nsTArray<nsString>();
mPaths.Put(aId, paths);
} else if (paths->Contains(aDirectoryPath)) {
return;
}
mPaths.WithEntryHandle(aId, [&](auto&& entry) {
if (entry && entry.Data()->Contains(aDirectoryPath)) {
return;
}
paths->AppendElement(aDirectoryPath);
entry.OrInsertWith([] { return MakeUnique<nsTArray<nsString>>(); })
->AppendElement(aDirectoryPath);
});
}
void FileSystemSecurity::Forget(ContentParentId aId) {

View File

@ -7879,6 +7879,8 @@ uint64_t ConnectionPool::Start(
const uint64_t transactionId = ++mNextTransactionId;
// To avoid always acquiring a lock, we don't use WithEntryHandle here, which
// would require a lock in any case.
DatabaseInfo* dbInfo = mDatabases.Get(aDatabaseId);
const bool databaseInfoIsNew = !dbInfo;

View File

@ -3212,11 +3212,12 @@ bool RecvPBackgroundLSObserverConstructor(PBackgroundLSObserverParent* aActor,
const auto notNullObserver = WrapNotNull(observer.get());
nsTArray<NotNull<Observer*>>* array;
if (!gObservers->Get(notNullObserver->Origin(), &array)) {
array = new nsTArray<NotNull<Observer*>>();
gObservers->Put(notNullObserver->Origin(), array);
}
nsTArray<NotNull<Observer*>>* const array =
gObservers
->GetOrInsertWith(
notNullObserver->Origin(),
[] { return MakeUnique<nsTArray<NotNull<Observer*>>>(); })
.get();
array->AppendElement(notNullObserver);
if (RefPtr<Datastore> datastore = GetDatastore(observer->Origin())) {

View File

@ -2763,11 +2763,12 @@ RefPtr<MediaManager::StreamPromise> MediaManager::GetUserMedia(
// Add a WindowID cross-reference so OnNavigation can tear
// things down
nsTArray<nsString>* array;
if (!self->mCallIds.Get(windowID, &array)) {
array = new nsTArray<nsString>();
self->mCallIds.Put(windowID, array);
}
nsTArray<nsString>* const array =
self->mCallIds
.GetOrInsertWith(
windowID,
[] { return MakeUnique<nsTArray<nsString>>(); })
.get();
array->AppendElement(callID);
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();

View File

@ -127,17 +127,24 @@ class GMPDiskStorage : public GMPStorage {
GMPErr Open(const nsCString& aRecordName) override {
MOZ_ASSERT(!IsOpen(aRecordName));
nsresult rv;
Record* record = nullptr;
if (!mRecords.Get(aRecordName, &record)) {
// New file.
nsAutoString filename;
rv = GetUnusedFilename(aRecordName, filename);
if (NS_WARN_IF(NS_FAILED(rv))) {
return GMPGenericErr;
}
record = new Record(filename, aRecordName);
mRecords.Put(aRecordName, record);
Record* const record =
mRecords.WithEntryHandle(aRecordName, [&](auto&& entry) -> Record* {
if (!entry) {
// New file.
nsAutoString filename;
nsresult rv = GetUnusedFilename(aRecordName, filename);
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
return entry.Insert(MakeUnique<Record>(filename, aRecordName))
.get();
}
return entry.Data().get();
});
if (!record) {
return GMPGenericErr;
}
MOZ_ASSERT(record);
@ -146,7 +153,8 @@ class GMPDiskStorage : public GMPStorage {
return GMPRecordInUse;
}
rv = OpenStorageFile(record->mFilename, ReadWrite, &record->mFileDesc);
nsresult rv =
OpenStorageFile(record->mFilename, ReadWrite, &record->mFileDesc);
if (NS_WARN_IF(NS_FAILED(rv))) {
return GMPGenericErr;
}

View File

@ -13,11 +13,10 @@ class GMPMemoryStorage : public GMPStorage {
GMPErr Open(const nsCString& aRecordName) override {
MOZ_ASSERT(!IsOpen(aRecordName));
Record* record = nullptr;
if (!mRecords.Get(aRecordName, &record)) {
record = new Record();
mRecords.Put(aRecordName, record);
}
Record* record =
mRecords
.GetOrInsertWith(aRecordName, [] { return MakeUnique<Record>(); })
.get();
record->mIsOpen = true;
return GMPNoErr;
}

View File

@ -430,15 +430,16 @@ void GeckoMediaPluginService::ConnectCrashHelper(uint32_t aPluginId,
if (!aHelper) {
return;
}
MutexAutoLock lock(mMutex);
nsTArray<RefPtr<GMPCrashHelper>>* helpers;
if (!mPluginCrashHelpers.Get(aPluginId, &helpers)) {
helpers = new nsTArray<RefPtr<GMPCrashHelper>>();
mPluginCrashHelpers.Put(aPluginId, helpers);
} else if (helpers->Contains(aHelper)) {
return;
}
helpers->AppendElement(aHelper);
mPluginCrashHelpers.WithEntryHandle(aPluginId, [&](auto&& entry) {
if (!entry) {
entry.Insert(MakeUnique<nsTArray<RefPtr<GMPCrashHelper>>>());
} else if (entry.Data()->Contains(aHelper)) {
return;
}
entry.Data()->AppendElement(aHelper);
});
}
void GeckoMediaPluginService::DisconnectCrashHelper(GMPCrashHelper* aHelper) {

View File

@ -1093,20 +1093,24 @@ nsresult GeckoMediaPluginServiceParent::GetNodeId(
// name, so that if the same origin pair is opened for the same GMP in this
// session, it gets the same node id.
const uint32_t pbHash = AddToHash(HashString(aGMPName), hash);
nsCString* salt = nullptr;
if (!(salt = mTempNodeIds.Get(pbHash))) {
// No salt stored, generate and temporarily store some for this id.
nsAutoCString newSalt;
rv = GenerateRandomPathName(newSalt, NodeIdSaltLength);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
return mTempNodeIds.WithEntryHandle(pbHash, [&](auto&& entry) {
if (!entry) {
// No salt stored, generate and temporarily store some for this id.
nsAutoCString newSalt;
rv = GenerateRandomPathName(newSalt, NodeIdSaltLength);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
auto salt = MakeUnique<nsCString>(newSalt);
mPersistentStorageAllowed.Put(*salt, false);
entry.Insert(std::move(salt));
}
salt = new nsCString(newSalt);
mTempNodeIds.Put(pbHash, salt);
mPersistentStorageAllowed.Put(*salt, false);
}
aOutId = *salt;
return NS_OK;
aOutId = *entry.Data();
return NS_OK;
});
}
// Otherwise, try to see if we've previously generated and stored salt

View File

@ -24,17 +24,18 @@ MediaSystemResourceManagerParent::~MediaSystemResourceManagerParent() {
mozilla::ipc::IPCResult MediaSystemResourceManagerParent::RecvAcquire(
const uint32_t& aId, const MediaSystemResourceType& aResourceType,
const bool& aWillWait) {
MediaSystemResourceRequest* request = mResourceRequests.Get(aId);
MOZ_ASSERT(!request);
if (request) {
// Send fail response
mozilla::Unused << SendResponse(aId, false /* fail */);
return IPC_OK();
}
mResourceRequests.WithEntryHandle(aId, [&](auto&& request) {
MOZ_ASSERT(!request);
if (request) {
// Send fail response
mozilla::Unused << SendResponse(aId, false /* fail */);
return;
}
request.Insert(MakeUnique<MediaSystemResourceRequest>(aId, aResourceType));
mMediaSystemResourceService->Acquire(this, aId, aResourceType, aWillWait);
});
request = new MediaSystemResourceRequest(aId, aResourceType);
mResourceRequests.Put(aId, request);
mMediaSystemResourceService->Acquire(this, aId, aResourceType, aWillWait);
return IPC_OK();
}

View File

@ -79,13 +79,10 @@ class PresentationServiceBase {
return;
}
nsTArray<nsString>* sessionIdArray;
if (!mRespondingSessionIds.Get(aWindowId, &sessionIdArray)) {
sessionIdArray = new nsTArray<nsString>();
mRespondingSessionIds.Put(aWindowId, sessionIdArray);
}
sessionIdArray->AppendElement(nsString(aSessionId));
mRespondingSessionIds
.GetOrInsertWith(aWindowId,
[] { return MakeUnique<nsTArray<nsString>>(); })
->AppendElement(nsString(aSessionId));
mRespondingWindowIds.Put(aSessionId, aWindowId);
}
@ -151,12 +148,14 @@ class PresentationServiceBase {
aAddedUrls.Clear();
nsTArray<nsString> knownAvailableUrls;
for (const auto& url : aAvailabilityUrls) {
AvailabilityEntry* entry;
if (!mAvailabilityUrlTable.Get(url, &entry)) {
entry = new AvailabilityEntry();
mAvailabilityUrlTable.Put(url, entry);
aAddedUrls.AppendElement(url);
}
AvailabilityEntry* const entry =
mAvailabilityUrlTable
.GetOrInsertWith(url,
[&] {
aAddedUrls.AppendElement(url);
return MakeUnique<AvailabilityEntry>();
})
.get();
if (!entry->mListeners.Contains(aListener)) {
entry->mListeners.AppendElement(aListener);
}
@ -228,12 +227,10 @@ class PresentationServiceBase {
for (uint32_t i = 0; i < entry->mListeners.Length(); ++i) {
nsIPresentationAvailabilityListener* listener =
entry->mListeners.ObjectAt(i);
nsTArray<nsString>* urlArray;
if (!availabilityListenerTable.Get(listener, &urlArray)) {
urlArray = new nsTArray<nsString>();
availabilityListenerTable.Put(listener, urlArray);
}
urlArray->AppendElement(it.Key());
availabilityListenerTable
.GetOrInsertWith(
listener, [] { return MakeUnique<nsTArray<nsString>>(); })
->AppendElement(it.Key());
}
}
}

View File

@ -3278,21 +3278,20 @@ void QuotaManager::RegisterDirectoryLock(DirectoryLockImpl& aLock) {
DirectoryLockTable& directoryLockTable =
GetDirectoryLockTable(aLock.GetPersistenceType());
nsTArray<NotNull<DirectoryLockImpl*>>* array;
if (!directoryLockTable.Get(aLock.Origin(), &array)) {
array = new nsTArray<NotNull<DirectoryLockImpl*>>();
directoryLockTable.Put(aLock.Origin(), array);
if (!IsShuttingDown()) {
UpdateOriginAccessTime(aLock.GetPersistenceType(),
aLock.OriginMetadata());
}
}
// XXX It seems that the contents of the array are never actually used, we
// just use that like an inefficient use counter. Can't we just change
// DirectoryLockTable to a nsDataHashtable<nsCStringHashKey, uint32_t>?
array->AppendElement(WrapNotNullUnchecked(&aLock));
directoryLockTable
.GetOrInsertWith(
aLock.Origin(),
[this, &aLock] {
if (!IsShuttingDown()) {
UpdateOriginAccessTime(aLock.GetPersistenceType(),
aLock.OriginMetadata());
}
return MakeUnique<nsTArray<NotNull<DirectoryLockImpl*>>>();
})
->AppendElement(WrapNotNullUnchecked(&aLock));
}
aLock.SetRegistered(true);
@ -6610,12 +6609,10 @@ already_AddRefed<GroupInfo> QuotaManager::LockedGetOrCreateGroupInfo(
mQuotaMutex.AssertCurrentThreadOwns();
MOZ_ASSERT(aPersistenceType != PERSISTENCE_TYPE_PERSISTENT);
GroupInfoPair* pair;
if (!mGroupInfoPairs.Get(aGroup, &pair)) {
pair = new GroupInfoPair();
mGroupInfoPairs.Put(aGroup, pair);
// The hashtable is now responsible to delete the GroupInfoPair.
}
GroupInfoPair* const pair =
mGroupInfoPairs
.GetOrInsertWith(aGroup, [] { return MakeUnique<GroupInfoPair>(); })
.get();
RefPtr<GroupInfo> groupInfo = pair->LockedGetGroupInfo(aPersistenceType);
if (!groupInfo) {

View File

@ -1463,12 +1463,11 @@ mozilla::ipc::IPCResult RecvPBackgroundLocalStorageCacheConstructor(
gLocalStorageCacheParents = new LocalStorageCacheParentHashtable();
}
nsTArray<LocalStorageCacheParent*>* array;
if (!gLocalStorageCacheParents->Get(aOriginKey, &array)) {
array = new nsTArray<LocalStorageCacheParent*>();
gLocalStorageCacheParents->Put(aOriginKey, array);
}
array->AppendElement(actor);
gLocalStorageCacheParents
->GetOrInsertWith(
aOriginKey,
[] { return MakeUnique<nsTArray<LocalStorageCacheParent*>>(); })
->AppendElement(actor);
// We are currently trusting the content process not to lie to us. It is
// future work to consult the ClientManager to determine whether this is a

View File

@ -101,21 +101,22 @@ void AsyncImagePipelineManager::AddPipeline(const wr::PipelineId& aPipelineId,
if (mDestroyed) {
return;
}
uint64_t id = wr::AsUint64(aPipelineId);
PipelineTexturesHolder* holder =
mPipelineTexturesHolders.Get(wr::AsUint64(aPipelineId));
if (holder) {
// This could happen during tab move between different windows.
// Previously removed holder could be still alive for waiting destroyed.
MOZ_ASSERT(holder->mDestroyedEpoch.isSome());
holder->mDestroyedEpoch = Nothing(); // Revive holder
holder->mWrBridge = aWrBridge;
return;
}
holder = new PipelineTexturesHolder();
holder->mWrBridge = aWrBridge;
mPipelineTexturesHolders.Put(id, holder);
mPipelineTexturesHolders.WithEntryHandle(
wr::AsUint64(aPipelineId), [&](auto&& holder) {
if (holder) {
// This could happen during tab move between different windows.
// Previously removed holder could be still alive for waiting
// destroyed.
MOZ_ASSERT(holder.Data()->mDestroyedEpoch.isSome());
holder.Data()->mDestroyedEpoch = Nothing(); // Revive holder
holder.Data()->mWrBridge = aWrBridge;
return;
}
holder.Insert(MakeUnique<PipelineTexturesHolder>())->mWrBridge =
aWrBridge;
});
}
void AsyncImagePipelineManager::RemovePipeline(

View File

@ -2178,73 +2178,79 @@ gfxPlatformFontList::PrefFontList* gfxFcPlatformFontList::FindGenericFamilies(
genericLang.Append(fcLang);
// try to get the family from the cache
PrefFontList* prefFonts = mGenericMappings.Get(genericLang);
if (prefFonts) {
return prefFonts;
}
return mGenericMappings.WithEntryHandle(
genericLang, [&](auto&& entry) -> PrefFontList* {
if (!entry) {
// if not found, ask fontconfig to pick the appropriate font
RefPtr<FcPattern> genericPattern = dont_AddRef(FcPatternCreate());
FcPatternAddString(genericPattern, FC_FAMILY,
ToFcChar8Ptr(aGeneric.get()));
// if not found, ask fontconfig to pick the appropriate font
RefPtr<FcPattern> genericPattern = dont_AddRef(FcPatternCreate());
FcPatternAddString(genericPattern, FC_FAMILY, ToFcChar8Ptr(aGeneric.get()));
// -- prefer scalable fonts
FcPatternAddBool(genericPattern, FC_SCALABLE, FcTrue);
// -- prefer scalable fonts
FcPatternAddBool(genericPattern, FC_SCALABLE, FcTrue);
// -- add the lang to the pattern
if (!fcLang.IsEmpty()) {
FcPatternAddString(genericPattern, FC_LANG, ToFcChar8Ptr(fcLang.get()));
}
// -- perform substitutions
FcConfigSubstitute(nullptr, genericPattern, FcMatchPattern);
FcDefaultSubstitute(genericPattern);
// -- sort to get the closest matches
FcResult result;
UniquePtr<FcFontSet> faces(
FcFontSort(nullptr, genericPattern, FcFalse, nullptr, &result));
if (!faces) {
return nullptr;
}
// -- select the fonts to be used for the generic
prefFonts = new PrefFontList; // can be empty but in practice won't happen
uint32_t limit = gfxPlatformGtk::GetPlatform()->MaxGenericSubstitions();
bool foundFontWithLang = false;
for (int i = 0; i < faces->nfont; i++) {
FcPattern* font = faces->fonts[i];
FcChar8* mappedGeneric = nullptr;
FcPatternGetString(font, FC_FAMILY, 0, &mappedGeneric);
if (mappedGeneric) {
nsAutoCString mappedGenericName(ToCharPtr(mappedGeneric));
AutoTArray<FamilyAndGeneric, 1> genericFamilies;
if (gfxPlatformFontList::FindAndAddFamilies(
StyleGenericFontFamily::None, mappedGenericName, &genericFamilies,
FindFamiliesFlags(0))) {
MOZ_ASSERT(genericFamilies.Length() == 1, "expected a single family");
if (!prefFonts->Contains(genericFamilies[0].mFamily)) {
prefFonts->AppendElement(genericFamilies[0].mFamily);
bool foundLang = !fcLang.IsEmpty() &&
PatternHasLang(font, ToFcChar8Ptr(fcLang.get()));
foundFontWithLang = foundFontWithLang || foundLang;
// check to see if the list is full
if (prefFonts->Length() >= limit) {
break;
// -- add the lang to the pattern
if (!fcLang.IsEmpty()) {
FcPatternAddString(genericPattern, FC_LANG,
ToFcChar8Ptr(fcLang.get()));
}
// -- perform substitutions
FcConfigSubstitute(nullptr, genericPattern, FcMatchPattern);
FcDefaultSubstitute(genericPattern);
// -- sort to get the closest matches
FcResult result;
UniquePtr<FcFontSet> faces(
FcFontSort(nullptr, genericPattern, FcFalse, nullptr, &result));
if (!faces) {
return nullptr;
}
// -- select the fonts to be used for the generic
auto prefFonts = MakeUnique<PrefFontList>(); // can be empty but in
// practice won't happen
uint32_t limit =
gfxPlatformGtk::GetPlatform()->MaxGenericSubstitions();
bool foundFontWithLang = false;
for (int i = 0; i < faces->nfont; i++) {
FcPattern* font = faces->fonts[i];
FcChar8* mappedGeneric = nullptr;
FcPatternGetString(font, FC_FAMILY, 0, &mappedGeneric);
if (mappedGeneric) {
nsAutoCString mappedGenericName(ToCharPtr(mappedGeneric));
AutoTArray<FamilyAndGeneric, 1> genericFamilies;
if (gfxPlatformFontList::FindAndAddFamilies(
StyleGenericFontFamily::None, mappedGenericName,
&genericFamilies, FindFamiliesFlags(0))) {
MOZ_ASSERT(genericFamilies.Length() == 1,
"expected a single family");
if (!prefFonts->Contains(genericFamilies[0].mFamily)) {
prefFonts->AppendElement(genericFamilies[0].mFamily);
bool foundLang =
!fcLang.IsEmpty() &&
PatternHasLang(font, ToFcChar8Ptr(fcLang.get()));
foundFontWithLang = foundFontWithLang || foundLang;
// check to see if the list is full
if (prefFonts->Length() >= limit) {
break;
}
}
}
}
}
// if no font in the list matches the lang, trim all but the first one
if (!prefFonts->IsEmpty() && !foundFontWithLang) {
prefFonts->TruncateLength(1);
}
entry.Insert(std::move(prefFonts));
}
}
}
}
// if no font in the list matches the lang, trim all but the first one
if (!prefFonts->IsEmpty() && !foundFontWithLang) {
prefFonts->TruncateLength(1);
}
mGenericMappings.Put(genericLang, prefFonts);
return prefFonts;
return entry.Data().get();
});
}
bool gfxFcPlatformFontList::PrefFontListsUseOnlyGenerics() {

View File

@ -107,23 +107,28 @@ gfxSVGGlyphsDocument* gfxSVGGlyphs::FindOrCreateGlyphsDocument(
return nullptr;
}
gfxSVGGlyphsDocument* result = mGlyphDocs.Get(entry->mDocOffset);
return mGlyphDocs.WithEntryHandle(
entry->mDocOffset, [&](auto&& glyphDocsEntry) -> gfxSVGGlyphsDocument* {
if (!glyphDocsEntry) {
unsigned int length;
const uint8_t* data =
(const uint8_t*)hb_blob_get_data(mSVGData, &length);
if (entry->mDocOffset > 0 && uint64_t(mHeader->mDocIndexOffset) +
entry->mDocOffset +
entry->mDocLength <=
length) {
return glyphDocsEntry
.Insert(MakeUnique<gfxSVGGlyphsDocument>(
data + mHeader->mDocIndexOffset + entry->mDocOffset,
entry->mDocLength, this))
.get();
}
if (!result) {
unsigned int length;
const uint8_t* data = (const uint8_t*)hb_blob_get_data(mSVGData, &length);
if (entry->mDocOffset > 0 && uint64_t(mHeader->mDocIndexOffset) +
entry->mDocOffset +
entry->mDocLength <=
length) {
result = new gfxSVGGlyphsDocument(
data + mHeader->mDocIndexOffset + entry->mDocOffset,
entry->mDocLength, this);
mGlyphDocs.Put(entry->mDocOffset, result);
}
}
return nullptr;
}
return result;
return glyphDocsEntry.Data().get();
});
}
nsresult gfxSVGGlyphsDocument::SetupPresentation() {

View File

@ -177,16 +177,18 @@ void ModifyWakeLock(const nsAString& aTopic, hal::WakeLockControl aLockAdjust,
return;
}
ProcessLockTable* table = sLockTable->Get(aTopic);
LockCount processCount;
LockCount totalCount;
if (!table) {
table = new ProcessLockTable();
sLockTable->Put(aTopic, table);
} else {
table->Get(aProcessID, &processCount);
CountWakeLocks(table, &totalCount);
}
ProcessLockTable* const table =
sLockTable->WithEntryHandle(aTopic, [&](auto&& entry) {
if (!entry) {
entry.Insert(MakeUnique<ProcessLockTable>());
} else {
entry.Data()->Get(aProcessID, &processCount);
CountWakeLocks(entry.Data().get(), &totalCount);
}
return entry.Data().get();
});
MOZ_ASSERT(processCount.numLocks >= processCount.numHidden);
MOZ_ASSERT(aLockAdjust >= 0 || processCount.numLocks > 0);

View File

@ -205,17 +205,20 @@ nsresult SSLTokensCache::Put(const nsACString& aKey, const uint8_t* aToken,
return rv;
}
TokenCacheRecord* rec = nullptr;
TokenCacheRecord* const rec =
gInstance->mTokenCacheRecords.WithEntryHandle(aKey, [&](auto&& entry) {
if (!entry) {
auto rec = MakeUnique<TokenCacheRecord>();
rec->mKey = aKey;
gInstance->mExpirationArray.AppendElement(rec.get());
entry.Insert(std::move(rec));
} else {
gInstance->mCacheSize -= entry.Data()->Size();
entry.Data()->Reset();
}
if (!gInstance->mTokenCacheRecords.Get(aKey, &rec)) {
rec = new TokenCacheRecord();
rec->mKey = aKey;
gInstance->mTokenCacheRecords.Put(aKey, rec);
gInstance->mExpirationArray.AppendElement(rec);
} else {
gInstance->mCacheSize -= rec->Size();
rec->Reset();
}
return entry.Data().get();
});
rec->mExpirationTime = aExpirationTime;
MOZ_ASSERT(rec->mToken.IsEmpty());

View File

@ -2195,13 +2195,9 @@ void CacheFile::QueueChunkListener(uint32_t aIndex,
}
item->mCallback = aCallback;
ChunkListeners* listeners;
if (!mChunkListeners.Get(aIndex, &listeners)) {
listeners = new ChunkListeners();
mChunkListeners.Put(aIndex, listeners);
}
listeners->mItems.AppendElement(item);
mChunkListeners
.GetOrInsertWith(aIndex, [] { return MakeUnique<ChunkListeners>(); })
->mItems.AppendElement(item);
}
nsresult CacheFile::NotifyChunkListeners(uint32_t aIndex, nsresult aResult,

View File

@ -1560,13 +1560,17 @@ nsresult CacheStorageService::AddStorageEntry(
NS_ENSURE_FALSE(mShutdown, NS_ERROR_NOT_INITIALIZED);
// Ensure storage table
CacheEntryTable* entries;
if (!sGlobalEntryTables->Get(aContextKey, &entries)) {
entries = new CacheEntryTable(CacheEntryTable::ALL_ENTRIES);
sGlobalEntryTables->Put(aContextKey, entries);
LOG((" new storage entries table for context '%s'",
aContextKey.BeginReading()));
}
CacheEntryTable* const entries =
sGlobalEntryTables
->GetOrInsertWith(
aContextKey,
[&aContextKey] {
LOG((" new storage entries table for context '%s'",
aContextKey.BeginReading()));
return MakeUnique<CacheEntryTable>(
CacheEntryTable::ALL_ENTRIES);
})
.get();
bool entryExists = entries->Get(entryKey, getter_AddRefs(entry));

View File

@ -1418,13 +1418,10 @@ nsDNSService::ReportFailedSVCDomainName(const nsACString& aOwnerName,
const nsACString& aSVCDomainName) {
MutexAutoLock lock(mLock);
nsTArray<nsCString>* failedList = mFailedSVCDomainNames.Get(aOwnerName);
if (!failedList) {
failedList = new nsTArray<nsCString>(1);
mFailedSVCDomainNames.Put(aOwnerName, failedList);
}
failedList->AppendElement(aSVCDomainName);
mFailedSVCDomainNames
.GetOrInsertWith(aOwnerName,
[] { return MakeUnique<nsTArray<nsCString>>(1); })
->AppendElement(aSVCDomainName);
return NS_OK;
}

View File

@ -56,11 +56,14 @@ void PendingTransactionQueue::InsertTransactionNormal(
info->Transaction()->TopLevelOuterContentWindowId()));
uint64_t windowId = TabIdForQueuing(info->Transaction());
nsTArray<RefPtr<PendingTransactionInfo>>* infoArray;
if (!mPendingTransactionTable.Get(windowId, &infoArray)) {
infoArray = new nsTArray<RefPtr<PendingTransactionInfo>>();
mPendingTransactionTable.Put(windowId, infoArray);
}
nsTArray<RefPtr<PendingTransactionInfo>>* const infoArray =
mPendingTransactionTable
.GetOrInsertWith(
windowId,
[] {
return MakeUnique<nsTArray<RefPtr<PendingTransactionInfo>>>();
})
.get();
InsertTransactionSorted(*infoArray, info, aInsertAsFirstForTheSamePriority);
}

View File

@ -803,15 +803,16 @@ void nsHttpConnectionMgr::UpdateCoalescingForNewConn(
"UpdateCoalescingForNewConn() registering newConn %p %s under key %s\n",
newConn, newConn->ConnectionInfo()->HashKey().get(),
ent->mCoalescingKeys[i].get()));
nsTArray<nsWeakPtr>* listOfWeakConns =
mCoalescingHash.Get(ent->mCoalescingKeys[i]);
if (!listOfWeakConns) {
LOG(("UpdateCoalescingForNewConn() need new list element\n"));
listOfWeakConns = new nsTArray<nsWeakPtr>(1);
mCoalescingHash.Put(ent->mCoalescingKeys[i], listOfWeakConns);
}
listOfWeakConns->AppendElement(
do_GetWeakReference(static_cast<nsISupportsWeakReference*>(newConn)));
mCoalescingHash
.GetOrInsertWith(
ent->mCoalescingKeys[i],
[] {
LOG(("UpdateCoalescingForNewConn() need new list element\n"));
return MakeUnique<nsTArray<nsWeakPtr>>(1);
})
->AppendElement(do_GetWeakReference(
static_cast<nsISupportsWeakReference*>(newConn)));
}
// this is a new connection that can be coalesced onto. hooray!
@ -3343,13 +3344,11 @@ void nsHttpConnectionMgr::RegisterOriginCoalescingKey(HttpConnectionBase* conn,
nsCString newKey;
BuildOriginFrameHashKey(newKey, ci, host, port);
nsTArray<nsWeakPtr>* listOfWeakConns = mCoalescingHash.Get(newKey);
if (!listOfWeakConns) {
listOfWeakConns = new nsTArray<nsWeakPtr>(1);
mCoalescingHash.Put(newKey, listOfWeakConns);
}
listOfWeakConns->AppendElement(
do_GetWeakReference(static_cast<nsISupportsWeakReference*>(conn)));
mCoalescingHash
.GetOrInsertWith(newKey,
[] { return MakeUnique<nsTArray<nsWeakPtr>>(1); })
->AppendElement(
do_GetWeakReference(static_cast<nsISupportsWeakReference*>(conn)));
LOG(
("nsHttpConnectionMgr::RegisterOriginCoalescingKey "

View File

@ -369,22 +369,25 @@ WebSocketEventService::AddListener(uint64_t aInnerWindowID,
++mCountListeners;
WindowListener* listener = mWindows.Get(aInnerWindowID);
if (!listener) {
listener = new WindowListener();
mWindows
.GetOrInsertWith(
aInnerWindowID,
[&] {
auto listener = MakeUnique<WindowListener>();
if (IsChildProcess()) {
PWebSocketEventListenerChild* actor =
gNeckoChild->SendPWebSocketEventListenerConstructor(aInnerWindowID);
if (IsChildProcess()) {
PWebSocketEventListenerChild* actor =
gNeckoChild->SendPWebSocketEventListenerConstructor(
aInnerWindowID);
listener->mActor = static_cast<WebSocketEventListenerChild*>(actor);
MOZ_ASSERT(listener->mActor);
}
listener->mActor =
static_cast<WebSocketEventListenerChild*>(actor);
MOZ_ASSERT(listener->mActor);
}
mWindows.Put(aInnerWindowID, listener);
}
listener->mListeners.AppendElement(aListener);
return listener;
})
->mListeners.AppendElement(aListener);
return NS_OK;
}

View File

@ -118,17 +118,15 @@ nsresult nsStreamConverterService::AddAdjacency(const char* aContractID) {
// Each MIME-type is a vertex in the graph, so first lets make sure
// each MIME-type is represented as a key in our hashtable.
nsTArray<RefPtr<nsAtom>>* fromEdges = mAdjacencyList.Get(fromStr);
if (!fromEdges) {
// There is no fromStr vertex, create one.
fromEdges = new nsTArray<RefPtr<nsAtom>>();
mAdjacencyList.Put(fromStr, fromEdges);
}
nsTArray<RefPtr<nsAtom>>* const fromEdges =
mAdjacencyList
.GetOrInsertWith(
fromStr,
[] { return mozilla::MakeUnique<nsTArray<RefPtr<nsAtom>>>(); })
.get();
if (!mAdjacencyList.Get(toStr)) {
// There is no toStr vertex, create one.
mAdjacencyList.Put(toStr, new nsTArray<RefPtr<nsAtom>>());
}
mozilla::Unused << mAdjacencyList.GetOrInsertWith(
toStr, [] { return mozilla::MakeUnique<nsTArray<RefPtr<nsAtom>>>(); });
// Now we know the FROM and TO types are represented as keys in the hashtable.
// Let's "connect" the verticies, making an edge.

View File

@ -1095,15 +1095,13 @@ void NativeFileWatcherIOTask::AppendCallbacksToHashtables(
const nsMainThreadPtrHandle<nsINativeFileWatcherCallback>& aOnChangeHandle,
const nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>&
aOnErrorHandle) {
// First check to see if we've got an entry already.
ChangeCallbackArray* callbacksArray = mChangeCallbacksTable.Get(aPath);
if (!callbacksArray) {
// We don't have an entry. Create an array and put it into the hash table.
callbacksArray = new ChangeCallbackArray();
mChangeCallbacksTable.Put(aPath, callbacksArray);
}
ChangeCallbackArray* const callbacksArray =
mChangeCallbacksTable
.GetOrInsertWith(aPath,
[] { return MakeUnique<ChangeCallbackArray>(); })
.get();
// We do have an entry for that path. Check to see if the callback is
// Now we do have an entry for that path. Check to see if the callback is
// already there.
ChangeCallbackArray::index_type changeCallbackIndex =
callbacksArray->IndexOf(aOnChangeHandle);
@ -1114,12 +1112,11 @@ void NativeFileWatcherIOTask::AppendCallbacksToHashtables(
}
// Same thing for the error callback.
ErrorCallbackArray* errorCallbacksArray = mErrorCallbacksTable.Get(aPath);
if (!errorCallbacksArray) {
// We don't have an entry. Create an array and put it into the hash table.
errorCallbacksArray = new ErrorCallbackArray();
mErrorCallbacksTable.Put(aPath, errorCallbacksArray);
}
ErrorCallbackArray* const errorCallbacksArray =
mErrorCallbacksTable
.GetOrInsertWith(aPath,
[] { return MakeUnique<ErrorCallbackArray>(); })
.get();
ErrorCallbackArray::index_type errorCallbackIndex =
errorCallbacksArray->IndexOf(aOnErrorHandle);

View File

@ -30,6 +30,7 @@
#include "TelemetryEventData.h"
#include "TelemetryScalar.h"
using mozilla::MakeUnique;
using mozilla::Maybe;
using mozilla::StaticAutoPtr;
using mozilla::StaticMutex;
@ -373,12 +374,10 @@ bool IsExpired(const EventKey& key) { return key.id == kExpiredEventId; }
EventRecordArray* GetEventRecordsForProcess(const StaticMutexAutoLock& lock,
ProcessID processType) {
EventRecordArray* eventRecords = nullptr;
if (!gEventRecords.Get(uint32_t(processType), &eventRecords)) {
eventRecords = new EventRecordArray();
gEventRecords.Put(uint32_t(processType), eventRecords);
}
return eventRecords;
return gEventRecords
.GetOrInsertWith(uint32_t(processType),
[] { return MakeUnique<EventRecordArray>(); })
.get();
}
EventKey* GetEventKey(const StaticMutexAutoLock& lock,

View File

@ -31,6 +31,7 @@
#include "nsVariant.h"
#include "TelemetryScalarData.h"
using mozilla::MakeUnique;
using mozilla::Nothing;
using mozilla::Preferences;
using mozilla::Some;
@ -1499,7 +1500,6 @@ nsresult internal_GetScalarByEnum(const StaticMutexAutoLock& lock,
}
ScalarBase* scalar = nullptr;
ScalarStorageMapType* scalarStorage = nullptr;
// Initialize the scalar storage to the parent storage. This will get
// set to the child storage if needed.
uint32_t storageId = static_cast<uint32_t>(aProcessStorage);
@ -1512,10 +1512,11 @@ nsresult internal_GetScalarByEnum(const StaticMutexAutoLock& lock,
// Get the process-specific storage or create one if it's not
// available.
if (!processStorage.Get(storageId, &scalarStorage)) {
scalarStorage = new ScalarStorageMapType();
processStorage.Put(storageId, scalarStorage);
}
ScalarStorageMapType* const scalarStorage =
processStorage
.GetOrInsertWith(storageId,
[] { return MakeUnique<ScalarStorageMapType>(); })
.get();
// Check if the scalar is already allocated in the parent or in the child
// storage.
@ -1783,7 +1784,6 @@ nsresult internal_GetKeyedScalarByEnum(const StaticMutexAutoLock& lock,
}
KeyedScalar* scalar = nullptr;
KeyedScalarStorageMapType* scalarStorage = nullptr;
// Initialize the scalar storage to the parent storage. This will get
// set to the child storage if needed.
uint32_t storageId = static_cast<uint32_t>(aProcessStorage);
@ -1796,10 +1796,11 @@ nsresult internal_GetKeyedScalarByEnum(const StaticMutexAutoLock& lock,
// Get the process-specific storage or create one if it's not
// available.
if (!processStorage.Get(storageId, &scalarStorage)) {
scalarStorage = new KeyedScalarStorageMapType();
processStorage.Put(storageId, scalarStorage);
}
KeyedScalarStorageMapType* const scalarStorage =
processStorage
.GetOrInsertWith(
storageId, [] { return MakeUnique<KeyedScalarStorageMapType>(); })
.get();
if (scalarStorage->Get(aId.id, &scalar)) {
*aRet = scalar;

View File

@ -868,11 +868,10 @@ nsresult EventDispatcher::IterateEvents(JSContext* aCx, JS::HandleValue aEvents,
nsresult EventDispatcher::RegisterEventLocked(
const nsAString& aEvent, nsIAndroidEventListener* aListener) {
ListenersList* list = mListenersMap.Get(aEvent);
if (!list) {
list = new ListenersList();
mListenersMap.Put(aEvent, list);
}
ListenersList* list =
mListenersMap
.GetOrInsertWith(aEvent, [] { return MakeUnique<ListenersList>(); })
.get();
#ifdef DEBUG
for (ssize_t i = 0; i < list->listeners.Count(); i++) {

View File

@ -482,11 +482,12 @@ nsresult WakeLockListener::Callback(const nsAString& topic,
!topic.Equals(u"video-playing"_ns))
return NS_OK;
WakeLockTopic* topicLock = mTopics.Get(topic);
if (!topicLock) {
topicLock = new WakeLockTopic(topic, mConnection);
mTopics.Put(topic, topicLock);
}
WakeLockTopic* const topicLock =
mTopics
.GetOrInsertWith(
topic,
[&] { return MakeUnique<WakeLockTopic>(topic, mConnection); })
.get();
// Treat "locked-background" the same as "unlocked" on desktop linux.
bool shouldLock = state.EqualsLiteral("locked-foreground");

View File

@ -150,50 +150,46 @@ nsresult nsWindowBase::SynthesizeNativeTouchPoint(
uint32_t pressure = (uint32_t)ceil(aPointerPressure * 1024);
// If we already know about this pointer id get it's record
PointerInfo* info = mActivePointers.Get(aPointerId);
return mActivePointers.WithEntryHandle(aPointerId, [&](auto&& entry) {
POINTER_FLAGS flags;
// We know about this pointer, send an update
if (info) {
POINTER_FLAGS flags = POINTER_FLAG_UPDATE;
if (hover) {
flags |= POINTER_FLAG_INRANGE;
} else if (contact) {
flags |= POINTER_FLAG_INCONTACT | POINTER_FLAG_INRANGE;
} else if (remove) {
flags = POINTER_FLAG_UP;
// Remove the pointer from our tracking list. This is nsAutPtr wrapped,
// so shouldn't leak.
mActivePointers.Remove(aPointerId);
}
// We know about this pointer, send an update
if (entry) {
flags = POINTER_FLAG_UPDATE;
if (hover) {
flags |= POINTER_FLAG_INRANGE;
} else if (contact) {
flags |= POINTER_FLAG_INCONTACT | POINTER_FLAG_INRANGE;
} else if (remove) {
flags = POINTER_FLAG_UP;
// Remove the pointer from our tracking list. This is UniquePtr wrapped,
// so shouldn't leak.
entry.Remove();
}
if (cancel) {
flags |= POINTER_FLAG_CANCELED;
if (cancel) {
flags |= POINTER_FLAG_CANCELED;
}
} else {
// Missing init state, error out
if (remove || cancel) {
return NS_ERROR_INVALID_ARG;
}
// Create a new pointer
flags = POINTER_FLAG_INRANGE;
if (contact) {
flags |= POINTER_FLAG_INCONTACT | POINTER_FLAG_DOWN;
}
entry.Insert(MakeUnique<PointerInfo>(aPointerId, aPoint));
}
return !InjectTouchPoint(aPointerId, aPoint, flags, pressure,
aPointerOrientation)
? NS_ERROR_UNEXPECTED
: NS_OK;
}
// Missing init state, error out
if (remove || cancel) {
return NS_ERROR_INVALID_ARG;
}
// Create a new pointer
info = new PointerInfo(aPointerId, aPoint);
POINTER_FLAGS flags = POINTER_FLAG_INRANGE;
if (contact) {
flags |= POINTER_FLAG_INCONTACT | POINTER_FLAG_DOWN;
}
mActivePointers.Put(aPointerId, info);
return !InjectTouchPoint(aPointerId, aPoint, flags, pressure,
aPointerOrientation)
? NS_ERROR_UNEXPECTED
: NS_OK;
});
}
nsresult nsWindowBase::ClearNativeTouchSequence(nsIObserver* aObserver) {

View File

@ -533,13 +533,13 @@ class LogModuleManager {
LogModule* CreateOrGetModule(const char* aName) {
OffTheBooksMutexAutoLock guard(mModulesLock);
LogModule* module = nullptr;
if (!mModules.Get(aName, &module)) {
module = new LogModule(aName, LogLevel::Disabled);
mModules.Put(aName, module);
}
return module;
return mModules
.GetOrInsertWith(aName,
[&] {
return UniquePtr<LogModule>(
new LogModule{aName, LogLevel::Disabled});
})
.get();
}
void Print(const char* aName, LogLevel aLevel, const char* aFmt,

View File

@ -199,28 +199,29 @@ nsresult nsINIParser::SetString(const char* aSection, const char* aKey,
return NS_ERROR_INVALID_ARG;
}
INIValue* v;
if (!mSections.Get(aSection, &v)) {
v = new INIValue(aKey, aValue);
mSections.Put(aSection, v);
return NS_OK;
}
// Check whether this key has already been specified; overwrite
// if so, or append if not.
while (v) {
if (!strcmp(aKey, v->key)) {
v->SetValue(aValue);
break;
mSections.WithEntryHandle(aSection, [&](auto&& entry) {
if (!entry) {
entry.Insert(MakeUnique<INIValue>(aKey, aValue));
return;
}
if (!v->next) {
v->next = MakeUnique<INIValue>(aKey, aValue);
break;
INIValue* v = entry.Data().get();
// Check whether this key has already been specified; overwrite
// if so, or append if not.
while (v) {
if (!strcmp(aKey, v->key)) {
v->SetValue(aValue);
break;
}
if (!v->next) {
v->next = MakeUnique<INIValue>(aKey, aValue);
break;
}
v = v->next.get();
}
v = v->next.get();
}
NS_ASSERTION(v, "v should never be null coming out of this loop");
NS_ASSERTION(v, "v should never be null coming out of this loop");
});
return NS_OK;
}

View File

@ -724,13 +724,10 @@ void nsComponentManagerImpl::ManifestComponent(ManifestProcessingContext& aCx,
return;
}
KnownModule* km;
km = mKnownModules.Get(hash);
if (!km) {
km = new KnownModule(fl);
mKnownModules.Put(hash, km);
}
KnownModule* const km =
mKnownModules
.GetOrInsertWith(hash, [&] { return MakeUnique<KnownModule>(fl); })
.get();
void* place = mArena.Allocate(sizeof(nsCID));
nsID* permanentCID = static_cast<nsID*>(place);