diff --git a/accessible/generic/DocAccessible-inl.h b/accessible/generic/DocAccessible-inl.h index e7ab8491c32d..96e8e50a1e93 100644 --- a/accessible/generic/DocAccessible-inl.h +++ b/accessible/generic/DocAccessible-inl.h @@ -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(); }) + .get(); - AttrRelProviders* providers = hash->Get(aID); - if (!providers) { - providers = new AttrRelProviders(); - hash->Put(aID, providers); - } - return providers; + return hash + ->GetOrInsertWith(aID, [] { return MakeUnique(); }) + .get(); } inline void DocAccessible::RemoveRelProvidersIfEmpty(dom::Element* aElement, diff --git a/dom/base/EventSourceEventService.cpp b/dom/base/EventSourceEventService.cpp index 46aba37f8ec5..9ce0a0d4360c 100644 --- a/dom/base/EventSourceEventService.cpp +++ b/dom/base/EventSourceEventService.cpp @@ -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(); }) + .get(); listener->mListeners.AppendElement(aListener); diff --git a/dom/events/PointerEventHandler.cpp b/dom/events/PointerEventHandler.cpp index 61e678864bb0..97dfe751d527 100644 --- a/dom/events/PointerEventHandler.cpp +++ b/dom/events/PointerEventHandler.cpp @@ -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(aElement)); + } + }); } /* static */ diff --git a/dom/filehandle/ActorsParent.cpp b/dom/filehandle/ActorsParent.cpp index f104d694bbaf..302e0ec1c7d6 100644 --- a/dom/filehandle/ActorsParent.cpp +++ b/dom/filehandle/ActorsParent.cpp @@ -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(new DirectoryInfo(this)); }) + .get(); FileHandleQueue* existingFileHandleQueue = directoryInfo->GetFileHandleQueue(aFileHandle); diff --git a/dom/filesystem/FileSystemSecurity.cpp b/dom/filesystem/FileSystemSecurity.cpp index 0416278e18c2..b9468270d453 100644 --- a/dom/filesystem/FileSystemSecurity.cpp +++ b/dom/filesystem/FileSystemSecurity.cpp @@ -56,15 +56,14 @@ void FileSystemSecurity::GrantAccessToContentProcess( MOZ_ASSERT(NS_IsMainThread()); mozilla::ipc::AssertIsInMainProcess(); - nsTArray* paths; - if (!mPaths.Get(aId, &paths)) { - paths = new nsTArray(); - 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>(); }) + ->AppendElement(aDirectoryPath); + }); } void FileSystemSecurity::Forget(ContentParentId aId) { diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index 90a6966f1828..169fd6e3c917 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -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; diff --git a/dom/localstorage/ActorsParent.cpp b/dom/localstorage/ActorsParent.cpp index 401246aeb961..c0d2afac507f 100644 --- a/dom/localstorage/ActorsParent.cpp +++ b/dom/localstorage/ActorsParent.cpp @@ -3212,11 +3212,12 @@ bool RecvPBackgroundLSObserverConstructor(PBackgroundLSObserverParent* aActor, const auto notNullObserver = WrapNotNull(observer.get()); - nsTArray>* array; - if (!gObservers->Get(notNullObserver->Origin(), &array)) { - array = new nsTArray>(); - gObservers->Put(notNullObserver->Origin(), array); - } + nsTArray>* const array = + gObservers + ->GetOrInsertWith( + notNullObserver->Origin(), + [] { return MakeUnique>>(); }) + .get(); array->AppendElement(notNullObserver); if (RefPtr datastore = GetDatastore(observer->Origin())) { diff --git a/dom/media/MediaManager.cpp b/dom/media/MediaManager.cpp index 293f21ce9e59..40ba6f58904e 100644 --- a/dom/media/MediaManager.cpp +++ b/dom/media/MediaManager.cpp @@ -2763,11 +2763,12 @@ RefPtr MediaManager::GetUserMedia( // Add a WindowID cross-reference so OnNavigation can tear // things down - nsTArray* array; - if (!self->mCallIds.Get(windowID, &array)) { - array = new nsTArray(); - self->mCallIds.Put(windowID, array); - } + nsTArray* const array = + self->mCallIds + .GetOrInsertWith( + windowID, + [] { return MakeUnique>(); }) + .get(); array->AppendElement(callID); nsCOMPtr obs = services::GetObserverService(); diff --git a/dom/media/gmp/GMPDiskStorage.cpp b/dom/media/gmp/GMPDiskStorage.cpp index 2336b748c24a..fc38762ee446 100644 --- a/dom/media/gmp/GMPDiskStorage.cpp +++ b/dom/media/gmp/GMPDiskStorage.cpp @@ -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(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; } diff --git a/dom/media/gmp/GMPMemoryStorage.cpp b/dom/media/gmp/GMPMemoryStorage.cpp index a39d705c78cc..e535c6cf769f 100644 --- a/dom/media/gmp/GMPMemoryStorage.cpp +++ b/dom/media/gmp/GMPMemoryStorage.cpp @@ -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(); }) + .get(); record->mIsOpen = true; return GMPNoErr; } diff --git a/dom/media/gmp/GMPService.cpp b/dom/media/gmp/GMPService.cpp index 32c0061f2246..cf8d89ccdc2b 100644 --- a/dom/media/gmp/GMPService.cpp +++ b/dom/media/gmp/GMPService.cpp @@ -430,15 +430,16 @@ void GeckoMediaPluginService::ConnectCrashHelper(uint32_t aPluginId, if (!aHelper) { return; } + MutexAutoLock lock(mMutex); - nsTArray>* helpers; - if (!mPluginCrashHelpers.Get(aPluginId, &helpers)) { - helpers = new nsTArray>(); - mPluginCrashHelpers.Put(aPluginId, helpers); - } else if (helpers->Contains(aHelper)) { - return; - } - helpers->AppendElement(aHelper); + mPluginCrashHelpers.WithEntryHandle(aPluginId, [&](auto&& entry) { + if (!entry) { + entry.Insert(MakeUnique>>()); + } else if (entry.Data()->Contains(aHelper)) { + return; + } + entry.Data()->AppendElement(aHelper); + }); } void GeckoMediaPluginService::DisconnectCrashHelper(GMPCrashHelper* aHelper) { diff --git a/dom/media/gmp/GMPServiceParent.cpp b/dom/media/gmp/GMPServiceParent.cpp index 63eecf06e76d..4e06d07ba41f 100644 --- a/dom/media/gmp/GMPServiceParent.cpp +++ b/dom/media/gmp/GMPServiceParent.cpp @@ -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(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 diff --git a/dom/media/systemservices/MediaSystemResourceManagerParent.cpp b/dom/media/systemservices/MediaSystemResourceManagerParent.cpp index d6d0d7dce420..ec20079abc3d 100644 --- a/dom/media/systemservices/MediaSystemResourceManagerParent.cpp +++ b/dom/media/systemservices/MediaSystemResourceManagerParent.cpp @@ -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(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(); } diff --git a/dom/presentation/PresentationServiceBase.h b/dom/presentation/PresentationServiceBase.h index a997d5db89b5..eda02c52dd93 100644 --- a/dom/presentation/PresentationServiceBase.h +++ b/dom/presentation/PresentationServiceBase.h @@ -79,13 +79,10 @@ class PresentationServiceBase { return; } - nsTArray* sessionIdArray; - if (!mRespondingSessionIds.Get(aWindowId, &sessionIdArray)) { - sessionIdArray = new nsTArray(); - mRespondingSessionIds.Put(aWindowId, sessionIdArray); - } - - sessionIdArray->AppendElement(nsString(aSessionId)); + mRespondingSessionIds + .GetOrInsertWith(aWindowId, + [] { return MakeUnique>(); }) + ->AppendElement(nsString(aSessionId)); mRespondingWindowIds.Put(aSessionId, aWindowId); } @@ -151,12 +148,14 @@ class PresentationServiceBase { aAddedUrls.Clear(); nsTArray 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(); + }) + .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* urlArray; - if (!availabilityListenerTable.Get(listener, &urlArray)) { - urlArray = new nsTArray(); - availabilityListenerTable.Put(listener, urlArray); - } - urlArray->AppendElement(it.Key()); + availabilityListenerTable + .GetOrInsertWith( + listener, [] { return MakeUnique>(); }) + ->AppendElement(it.Key()); } } } diff --git a/dom/quota/ActorsParent.cpp b/dom/quota/ActorsParent.cpp index b5caceea2568..92a0146bbdc4 100644 --- a/dom/quota/ActorsParent.cpp +++ b/dom/quota/ActorsParent.cpp @@ -3278,21 +3278,20 @@ void QuotaManager::RegisterDirectoryLock(DirectoryLockImpl& aLock) { DirectoryLockTable& directoryLockTable = GetDirectoryLockTable(aLock.GetPersistenceType()); - nsTArray>* array; - if (!directoryLockTable.Get(aLock.Origin(), &array)) { - array = new nsTArray>(); - 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? - array->AppendElement(WrapNotNullUnchecked(&aLock)); + directoryLockTable + .GetOrInsertWith( + aLock.Origin(), + [this, &aLock] { + if (!IsShuttingDown()) { + UpdateOriginAccessTime(aLock.GetPersistenceType(), + aLock.OriginMetadata()); + } + return MakeUnique>>(); + }) + ->AppendElement(WrapNotNullUnchecked(&aLock)); } aLock.SetRegistered(true); @@ -6610,12 +6609,10 @@ already_AddRefed 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(); }) + .get(); RefPtr groupInfo = pair->LockedGetGroupInfo(aPersistenceType); if (!groupInfo) { diff --git a/dom/storage/StorageIPC.cpp b/dom/storage/StorageIPC.cpp index 20aeac427cd8..78d18f9fe5e2 100644 --- a/dom/storage/StorageIPC.cpp +++ b/dom/storage/StorageIPC.cpp @@ -1463,12 +1463,11 @@ mozilla::ipc::IPCResult RecvPBackgroundLocalStorageCacheConstructor( gLocalStorageCacheParents = new LocalStorageCacheParentHashtable(); } - nsTArray* array; - if (!gLocalStorageCacheParents->Get(aOriginKey, &array)) { - array = new nsTArray(); - gLocalStorageCacheParents->Put(aOriginKey, array); - } - array->AppendElement(actor); + gLocalStorageCacheParents + ->GetOrInsertWith( + aOriginKey, + [] { return MakeUnique>(); }) + ->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 diff --git a/gfx/layers/wr/AsyncImagePipelineManager.cpp b/gfx/layers/wr/AsyncImagePipelineManager.cpp index c9848e6d7c3c..8d3d80e490eb 100644 --- a/gfx/layers/wr/AsyncImagePipelineManager.cpp +++ b/gfx/layers/wr/AsyncImagePipelineManager.cpp @@ -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())->mWrBridge = + aWrBridge; + }); } void AsyncImagePipelineManager::RemovePipeline( diff --git a/gfx/thebes/gfxFcPlatformFontList.cpp b/gfx/thebes/gfxFcPlatformFontList.cpp index cdd908ff0cc5..d6b60aa210a0 100644 --- a/gfx/thebes/gfxFcPlatformFontList.cpp +++ b/gfx/thebes/gfxFcPlatformFontList.cpp @@ -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 genericPattern = dont_AddRef(FcPatternCreate()); + FcPatternAddString(genericPattern, FC_FAMILY, + ToFcChar8Ptr(aGeneric.get())); - // if not found, ask fontconfig to pick the appropriate font - RefPtr 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 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 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 faces( + FcFontSort(nullptr, genericPattern, FcFalse, nullptr, &result)); + + if (!faces) { + return nullptr; + } + + // -- select the fonts to be used for the generic + auto prefFonts = MakeUnique(); // 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 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() { diff --git a/gfx/thebes/gfxSVGGlyphs.cpp b/gfx/thebes/gfxSVGGlyphs.cpp index aa973e4782be..0e4a5c54b389 100644 --- a/gfx/thebes/gfxSVGGlyphs.cpp +++ b/gfx/thebes/gfxSVGGlyphs.cpp @@ -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( + 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() { diff --git a/hal/HalWakeLock.cpp b/hal/HalWakeLock.cpp index 063df37eb3ad..5457e90ee7cd 100644 --- a/hal/HalWakeLock.cpp +++ b/hal/HalWakeLock.cpp @@ -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()); + } 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); diff --git a/netwerk/base/SSLTokensCache.cpp b/netwerk/base/SSLTokensCache.cpp index 46d3a3bace30..983a15421793 100644 --- a/netwerk/base/SSLTokensCache.cpp +++ b/netwerk/base/SSLTokensCache.cpp @@ -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(); + 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()); diff --git a/netwerk/cache2/CacheFile.cpp b/netwerk/cache2/CacheFile.cpp index b6b052ba3a70..792696007f78 100644 --- a/netwerk/cache2/CacheFile.cpp +++ b/netwerk/cache2/CacheFile.cpp @@ -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(); }) + ->mItems.AppendElement(item); } nsresult CacheFile::NotifyChunkListeners(uint32_t aIndex, nsresult aResult, diff --git a/netwerk/cache2/CacheStorageService.cpp b/netwerk/cache2/CacheStorageService.cpp index 30df87a5cf9d..96a478fe4f4c 100644 --- a/netwerk/cache2/CacheStorageService.cpp +++ b/netwerk/cache2/CacheStorageService.cpp @@ -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::ALL_ENTRIES); + }) + .get(); bool entryExists = entries->Get(entryKey, getter_AddRefs(entry)); diff --git a/netwerk/dns/nsDNSService2.cpp b/netwerk/dns/nsDNSService2.cpp index 0150d5a383ee..a56d58c40400 100644 --- a/netwerk/dns/nsDNSService2.cpp +++ b/netwerk/dns/nsDNSService2.cpp @@ -1418,13 +1418,10 @@ nsDNSService::ReportFailedSVCDomainName(const nsACString& aOwnerName, const nsACString& aSVCDomainName) { MutexAutoLock lock(mLock); - nsTArray* failedList = mFailedSVCDomainNames.Get(aOwnerName); - if (!failedList) { - failedList = new nsTArray(1); - mFailedSVCDomainNames.Put(aOwnerName, failedList); - } - - failedList->AppendElement(aSVCDomainName); + mFailedSVCDomainNames + .GetOrInsertWith(aOwnerName, + [] { return MakeUnique>(1); }) + ->AppendElement(aSVCDomainName); return NS_OK; } diff --git a/netwerk/protocol/http/PendingTransactionQueue.cpp b/netwerk/protocol/http/PendingTransactionQueue.cpp index 6fea59be0378..9c3de78cc74d 100644 --- a/netwerk/protocol/http/PendingTransactionQueue.cpp +++ b/netwerk/protocol/http/PendingTransactionQueue.cpp @@ -56,11 +56,14 @@ void PendingTransactionQueue::InsertTransactionNormal( info->Transaction()->TopLevelOuterContentWindowId())); uint64_t windowId = TabIdForQueuing(info->Transaction()); - nsTArray>* infoArray; - if (!mPendingTransactionTable.Get(windowId, &infoArray)) { - infoArray = new nsTArray>(); - mPendingTransactionTable.Put(windowId, infoArray); - } + nsTArray>* const infoArray = + mPendingTransactionTable + .GetOrInsertWith( + windowId, + [] { + return MakeUnique>>(); + }) + .get(); InsertTransactionSorted(*infoArray, info, aInsertAsFirstForTheSamePriority); } diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.cpp b/netwerk/protocol/http/nsHttpConnectionMgr.cpp index c5d8c8f00ac0..7aa1ea91a9bc 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp +++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp @@ -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* listOfWeakConns = - mCoalescingHash.Get(ent->mCoalescingKeys[i]); - if (!listOfWeakConns) { - LOG(("UpdateCoalescingForNewConn() need new list element\n")); - listOfWeakConns = new nsTArray(1); - mCoalescingHash.Put(ent->mCoalescingKeys[i], listOfWeakConns); - } - listOfWeakConns->AppendElement( - do_GetWeakReference(static_cast(newConn))); + + mCoalescingHash + .GetOrInsertWith( + ent->mCoalescingKeys[i], + [] { + LOG(("UpdateCoalescingForNewConn() need new list element\n")); + return MakeUnique>(1); + }) + ->AppendElement(do_GetWeakReference( + static_cast(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* listOfWeakConns = mCoalescingHash.Get(newKey); - if (!listOfWeakConns) { - listOfWeakConns = new nsTArray(1); - mCoalescingHash.Put(newKey, listOfWeakConns); - } - listOfWeakConns->AppendElement( - do_GetWeakReference(static_cast(conn))); + mCoalescingHash + .GetOrInsertWith(newKey, + [] { return MakeUnique>(1); }) + ->AppendElement( + do_GetWeakReference(static_cast(conn))); LOG( ("nsHttpConnectionMgr::RegisterOriginCoalescingKey " diff --git a/netwerk/protocol/websocket/WebSocketEventService.cpp b/netwerk/protocol/websocket/WebSocketEventService.cpp index 13322bad4ec8..afa4bea68ad2 100644 --- a/netwerk/protocol/websocket/WebSocketEventService.cpp +++ b/netwerk/protocol/websocket/WebSocketEventService.cpp @@ -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(); - if (IsChildProcess()) { - PWebSocketEventListenerChild* actor = - gNeckoChild->SendPWebSocketEventListenerConstructor(aInnerWindowID); + if (IsChildProcess()) { + PWebSocketEventListenerChild* actor = + gNeckoChild->SendPWebSocketEventListenerConstructor( + aInnerWindowID); - listener->mActor = static_cast(actor); - MOZ_ASSERT(listener->mActor); - } + listener->mActor = + static_cast(actor); + MOZ_ASSERT(listener->mActor); + } - mWindows.Put(aInnerWindowID, listener); - } - - listener->mListeners.AppendElement(aListener); + return listener; + }) + ->mListeners.AppendElement(aListener); return NS_OK; } diff --git a/netwerk/streamconv/nsStreamConverterService.cpp b/netwerk/streamconv/nsStreamConverterService.cpp index 495e10a94d16..2c4a510c5582 100644 --- a/netwerk/streamconv/nsStreamConverterService.cpp +++ b/netwerk/streamconv/nsStreamConverterService.cpp @@ -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>* fromEdges = mAdjacencyList.Get(fromStr); - if (!fromEdges) { - // There is no fromStr vertex, create one. - fromEdges = new nsTArray>(); - mAdjacencyList.Put(fromStr, fromEdges); - } + nsTArray>* const fromEdges = + mAdjacencyList + .GetOrInsertWith( + fromStr, + [] { return mozilla::MakeUnique>>(); }) + .get(); - if (!mAdjacencyList.Get(toStr)) { - // There is no toStr vertex, create one. - mAdjacencyList.Put(toStr, new nsTArray>()); - } + mozilla::Unused << mAdjacencyList.GetOrInsertWith( + toStr, [] { return mozilla::MakeUnique>>(); }); // Now we know the FROM and TO types are represented as keys in the hashtable. // Let's "connect" the verticies, making an edge. diff --git a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp index f93abae14420..e744ff3985d6 100644 --- a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp +++ b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp @@ -1095,15 +1095,13 @@ void NativeFileWatcherIOTask::AppendCallbacksToHashtables( const nsMainThreadPtrHandle& aOnChangeHandle, const nsMainThreadPtrHandle& 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(); }) + .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(); }) + .get(); ErrorCallbackArray::index_type errorCallbackIndex = errorCallbacksArray->IndexOf(aOnErrorHandle); diff --git a/toolkit/components/telemetry/core/TelemetryEvent.cpp b/toolkit/components/telemetry/core/TelemetryEvent.cpp index 9904ae3c7178..bd0288a91ba2 100644 --- a/toolkit/components/telemetry/core/TelemetryEvent.cpp +++ b/toolkit/components/telemetry/core/TelemetryEvent.cpp @@ -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(); }) + .get(); } EventKey* GetEventKey(const StaticMutexAutoLock& lock, diff --git a/toolkit/components/telemetry/core/TelemetryScalar.cpp b/toolkit/components/telemetry/core/TelemetryScalar.cpp index 0f4bace0119d..787392d11958 100644 --- a/toolkit/components/telemetry/core/TelemetryScalar.cpp +++ b/toolkit/components/telemetry/core/TelemetryScalar.cpp @@ -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(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(); }) + .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(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(); }) + .get(); if (scalarStorage->Get(aId.id, &scalar)) { *aRet = scalar; diff --git a/widget/android/EventDispatcher.cpp b/widget/android/EventDispatcher.cpp index 061bd645560d..d3d0315c10fc 100644 --- a/widget/android/EventDispatcher.cpp +++ b/widget/android/EventDispatcher.cpp @@ -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(); }) + .get(); #ifdef DEBUG for (ssize_t i = 0; i < list->listeners.Count(); i++) { diff --git a/widget/gtk/WakeLockListener.cpp b/widget/gtk/WakeLockListener.cpp index 2192e3f49242..f27f21e2eaa9 100644 --- a/widget/gtk/WakeLockListener.cpp +++ b/widget/gtk/WakeLockListener.cpp @@ -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(topic, mConnection); }) + .get(); // Treat "locked-background" the same as "unlocked" on desktop linux. bool shouldLock = state.EqualsLiteral("locked-foreground"); diff --git a/widget/windows/nsWindowBase.cpp b/widget/windows/nsWindowBase.cpp index a9c9d2b53ec3..70f5c0001747 100644 --- a/widget/windows/nsWindowBase.cpp +++ b/widget/windows/nsWindowBase.cpp @@ -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(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) { diff --git a/xpcom/base/Logging.cpp b/xpcom/base/Logging.cpp index e12f83311ab5..bfcef302a669 100644 --- a/xpcom/base/Logging.cpp +++ b/xpcom/base/Logging.cpp @@ -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( + new LogModule{aName, LogLevel::Disabled}); + }) + .get(); } void Print(const char* aName, LogLevel aLevel, const char* aFmt, diff --git a/xpcom/base/nsINIParser.cpp b/xpcom/base/nsINIParser.cpp index 3f91c07f8599..20248c407d0b 100644 --- a/xpcom/base/nsINIParser.cpp +++ b/xpcom/base/nsINIParser.cpp @@ -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(aKey, aValue)); + return; } - if (!v->next) { - v->next = MakeUnique(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(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; } diff --git a/xpcom/components/nsComponentManager.cpp b/xpcom/components/nsComponentManager.cpp index 7feefae7a79f..b11a5807fbfe 100644 --- a/xpcom/components/nsComponentManager.cpp +++ b/xpcom/components/nsComponentManager.cpp @@ -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(fl); }) + .get(); void* place = mArena.Allocate(sizeof(nsCID)); nsID* permanentCID = static_cast(place);