diff --git a/Client/core/DXHook/CProxyDirect3D9.cpp b/Client/core/DXHook/CProxyDirect3D9.cpp index d563d95a5d..84372ab1f9 100644 --- a/Client/core/DXHook/CProxyDirect3D9.cpp +++ b/Client/core/DXHook/CProxyDirect3D9.cpp @@ -26,7 +26,7 @@ CProxyDirect3D9::CProxyDirect3D9(IDirect3D9* pInterface) CProxyDirect3D9::~CProxyDirect3D9() { WriteDebugEvent(SString("CProxyDirect3D9::~CProxyDirect3D9 %08x", this)); - ListRemove(ms_CreatedDirect3D9List, m_pDevice); + ListRemoveAll(ms_CreatedDirect3D9List, m_pDevice); m_pDevice = NULL; } diff --git a/Client/core/ServerBrowser/CServerList.cpp b/Client/core/ServerBrowser/CServerList.cpp index 044f88e496..f4c8ea6a34 100644 --- a/Client/core/ServerBrowser/CServerList.cpp +++ b/Client/core/ServerBrowser/CServerList.cpp @@ -615,7 +615,7 @@ void CServerListItemList::RemoveItem(CServerListItem* pItem) dassert(MapFindRef(m_AddressMap, key) == pItem); MapRemove(m_AddressMap, key); - ListRemove(m_List, pItem); + ListRemoveAll(m_List, pItem); dassert(m_List.size() == m_AddressMap.size()); } diff --git a/Client/game_sa/CRenderWareSA.TextureReplacing.cpp b/Client/game_sa/CRenderWareSA.TextureReplacing.cpp index f8c4313079..a53cf28829 100644 --- a/Client/game_sa/CRenderWareSA.TextureReplacing.cpp +++ b/Client/game_sa/CRenderWareSA.TextureReplacing.cpp @@ -249,7 +249,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen } // Remove refs - ListRemove(pInfo->usedByReplacements, pReplacementTextures); + ListRemoveAll(pInfo->usedByReplacements, pReplacementTextures); // If no refs left, check original state and then remove info if (pInfo->usedByReplacements.empty()) @@ -263,7 +263,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen { RwTexture* pOriginalTexture = pInfo->originalTextures[i]; assert(ListContains(currentTextures, pOriginalTexture)); - ListRemove(currentTextures, pOriginalTexture); + ListRemoveAll(currentTextures, pOriginalTexture); } assert(currentTextures.empty()); #endif diff --git a/Client/game_sa/CVehicleSA.cpp b/Client/game_sa/CVehicleSA.cpp index b4e7a2c438..fec3465ab2 100644 --- a/Client/game_sa/CVehicleSA.cpp +++ b/Client/game_sa/CVehicleSA.cpp @@ -910,7 +910,7 @@ void CVehicleSA::SetColor(SharedUtil::SColor color1, SharedUtil::SColor color2, || color == 0x00FFC8 // 0, 255, 200 || color == 0xFF3C00 // 255, 60, 0 || color == 0x3CFF00) // 60, 255, 0 - m_RGBColorsFixed[i].ulARGB |= 0x010101; + m_RGBColorsFixed[i] |= 0x010101; } } diff --git a/Client/loader/CInstallManager.cpp b/Client/loader/CInstallManager.cpp index 0f1b9f9728..f9704e5d1b 100644 --- a/Client/loader/CInstallManager.cpp +++ b/Client/loader/CInstallManager.cpp @@ -1245,11 +1245,11 @@ SString CInstallManager::_ProcessAppCompatChecks() // Break into words std::vector entryList; strValue.Split(" ", entryList); - ListRemove(entryList, WString()); + ListRemoveAll(entryList, WString()); // Apply removals for (uint a = 0; a < removeList.size(); a++) - ListRemove(entryList, removeList[a]); + ListRemoveAll(entryList, removeList[a]); // Apply adds for (uint a = 0; a < addList.size(); a++) diff --git a/Client/loader/Utils.cpp b/Client/loader/Utils.cpp index 9d3ead9eba..2658b837c5 100644 --- a/Client/loader/Utils.cpp +++ b/Client/loader/Utils.cpp @@ -368,7 +368,7 @@ std::vector GetOtherMTAProcessList() ListAddUnique(result, processId); // Ignore this process - ListRemove(result, GetCurrentProcessId()); + ListRemoveAll(result, GetCurrentProcessId()); return result; } diff --git a/Client/mods/deathmatch/logic/CClientColManager.cpp b/Client/mods/deathmatch/logic/CClientColManager.cpp index 0afeb093c7..67129fa86a 100644 --- a/Client/mods/deathmatch/logic/CClientColManager.cpp +++ b/Client/mods/deathmatch/logic/CClientColManager.cpp @@ -214,5 +214,5 @@ void CClientColManager::DeleteAll() void CClientColManager::RemoveFromList(CClientColShape* pShape) { - ListRemove(m_List, pShape); + ListRemoveAll(m_List, pShape); } diff --git a/Client/mods/deathmatch/logic/CClientEntity.cpp b/Client/mods/deathmatch/logic/CClientEntity.cpp index 849f218e25..7f2a02b12a 100644 --- a/Client/mods/deathmatch/logic/CClientEntity.cpp +++ b/Client/mods/deathmatch/logic/CClientEntity.cpp @@ -649,7 +649,7 @@ void CClientEntity::AttachTo(CClientEntity* pEntity) if (m_pAttachedToEntity) { assert(ListContains(m_pAttachedToEntity->m_AttachedEntities, this)); - ListRemove(m_pAttachedToEntity->m_AttachedEntities, this); + ListRemoveAll(m_pAttachedToEntity->m_AttachedEntities, this); } m_pAttachedToEntity = pEntity; diff --git a/Client/mods/deathmatch/logic/CClientEntity.h b/Client/mods/deathmatch/logic/CClientEntity.h index 0d84526d8b..ed5a8f806b 100644 --- a/Client/mods/deathmatch/logic/CClientEntity.h +++ b/Client/mods/deathmatch/logic/CClientEntity.h @@ -296,7 +296,7 @@ class CClientEntity : public CClientEntityBase void RemoveOriginSourceUser(CClientPed* pModel) { m_OriginSourceUsers.remove(pModel); } void AddContact(CClientPed* pModel) { m_Contacts.push_back(pModel); } - void RemoveContact(CClientPed* pModel) { ListRemove(m_Contacts, pModel); } + void RemoveContact(CClientPed* pModel) { ListRemoveAll(m_Contacts, pModel); } virtual CEntity* GetGameEntity() { return NULL; } virtual const CEntity* GetGameEntity() const { return NULL; } diff --git a/Client/mods/deathmatch/logic/CClientObject.cpp b/Client/mods/deathmatch/logic/CClientObject.cpp index 7d34045f1b..3f67df46e0 100644 --- a/Client/mods/deathmatch/logic/CClientObject.cpp +++ b/Client/mods/deathmatch/logic/CClientObject.cpp @@ -302,7 +302,7 @@ bool CClientObject::SetLowLodObject(CClientObject* pNewLowLodObject) assert(ListContains(m_pLowLodObject->m_HighLodObjectList, this)); // Clear there and here - ListRemove(m_pLowLodObject->m_HighLodObjectList, this); + ListRemoveAll(m_pLowLodObject->m_HighLodObjectList, this); m_pLowLodObject = NULL; return true; } diff --git a/Client/mods/deathmatch/logic/CClientObjectManager.cpp b/Client/mods/deathmatch/logic/CClientObjectManager.cpp index 45cc2a0408..da452d81ab 100644 --- a/Client/mods/deathmatch/logic/CClientObjectManager.cpp +++ b/Client/mods/deathmatch/logic/CClientObjectManager.cpp @@ -222,7 +222,7 @@ void CClientObjectManager::OnDestruction(CClientObject* pObject) m_uiLowLodStreamedInCount--; else m_uiStreamedInCount--; - ListRemove(m_StreamedIn, pObject); + ListRemoveAll(m_StreamedIn, pObject); } UpdateLimitInfo(); } @@ -334,7 +334,7 @@ void CClientObjectManager::RemoveFromLists(CClientObject* pObject) { if (m_bCanRemoveFromList) { - ListRemove(m_Objects, pObject); + ListRemoveAll(m_Objects, pObject); } if (ListContains(m_StreamedIn, pObject)) { @@ -342,7 +342,7 @@ void CClientObjectManager::RemoveFromLists(CClientObject* pObject) m_uiLowLodStreamedInCount--; else m_uiStreamedInCount--; - ListRemove(m_StreamedIn, pObject); + ListRemoveAll(m_StreamedIn, pObject); } } diff --git a/Client/mods/deathmatch/logic/CClientPedManager.cpp b/Client/mods/deathmatch/logic/CClientPedManager.cpp index 878b002a6d..b375dbe6c2 100644 --- a/Client/mods/deathmatch/logic/CClientPedManager.cpp +++ b/Client/mods/deathmatch/logic/CClientPedManager.cpp @@ -82,7 +82,7 @@ void CClientPedManager::RemoveFromList(CClientPed* pPed) { if (m_bRemoveFromList) { - ListRemove(m_List, pPed); + ListRemoveAll(m_List, pPed); } } @@ -95,7 +95,7 @@ void CClientPedManager::OnCreation(CClientPed* pPed) void CClientPedManager::OnDestruction(CClientPed* pPed) { - ListRemove(m_StreamedIn, pPed); + ListRemoveAll(m_StreamedIn, pPed); } void CClientPedManager::RestreamPeds(unsigned short usModel) diff --git a/Client/mods/deathmatch/logic/CClientPerfStatManager.cpp b/Client/mods/deathmatch/logic/CClientPerfStatManager.cpp index c21806ec54..c2bca854a6 100644 --- a/Client/mods/deathmatch/logic/CClientPerfStatManager.cpp +++ b/Client/mods/deathmatch/logic/CClientPerfStatManager.cpp @@ -108,7 +108,7 @@ void CClientPerfStatManagerImpl::AddModule(CClientPerfStatModule* pModule) /////////////////////////////////////////////////////////////// void CClientPerfStatManagerImpl::RemoveModule(CClientPerfStatModule* pModule) { - ListRemove(m_ModuleList, pModule); + ListRemoveAll(m_ModuleList, pModule); } /////////////////////////////////////////////////////////////// diff --git a/Client/mods/deathmatch/logic/CClientVehicleManager.cpp b/Client/mods/deathmatch/logic/CClientVehicleManager.cpp index 67abb03f5e..cff93692b2 100644 --- a/Client/mods/deathmatch/logic/CClientVehicleManager.cpp +++ b/Client/mods/deathmatch/logic/CClientVehicleManager.cpp @@ -715,9 +715,9 @@ void CClientVehicleManager::RemoveFromLists(CClientVehicle* pVehicle) { if (m_bCanRemoveFromList) { - ListRemove(m_List, pVehicle); + ListRemoveAll(m_List, pVehicle); } - ListRemove(m_StreamedIn, pVehicle); + ListRemoveAll(m_StreamedIn, pVehicle); } bool CClientVehicleManager::Exists(CClientVehicle* pVehicle) @@ -739,7 +739,7 @@ void CClientVehicleManager::OnCreation(CClientVehicle* pVehicle) void CClientVehicleManager::OnDestruction(CClientVehicle* pVehicle) { - ListRemove(m_StreamedIn, pVehicle); + ListRemoveAll(m_StreamedIn, pVehicle); } void CClientVehicleManager::RestreamVehicles(unsigned short usModel) diff --git a/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp b/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp index 6109151606..206fc53fbd 100644 --- a/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp +++ b/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp @@ -79,7 +79,7 @@ void CResourceFileDownloadManager::UpdatePendingDownloads() if (pResourceFile->GetDownloadPriorityGroup() == iGroup) { // Move to active list and begin download - ListRemove(m_PendingFileDownloadList, pResourceFile); + ListRemoveAll(m_PendingFileDownloadList, pResourceFile); m_ActiveFileDownloadList.push_back(pResourceFile); BeginResourceFileDownload(pResourceFile, 0); @@ -105,8 +105,8 @@ void CResourceFileDownloadManager::UpdatePendingDownloads() /////////////////////////////////////////////////////////////// void CResourceFileDownloadManager::OnRemoveResourceFile(CDownloadableResource* pResourceFile) { - ListRemove(m_PendingFileDownloadList, pResourceFile); - ListRemove(m_ActiveFileDownloadList, pResourceFile); + ListRemoveAll(m_PendingFileDownloadList, pResourceFile); + ListRemoveAll(m_ActiveFileDownloadList, pResourceFile); } /////////////////////////////////////////////////////////////// diff --git a/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp b/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp index 4c70d03f04..1fb4b8e904 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp @@ -82,8 +82,8 @@ void CLuaTimerManager::RemoveTimer(CLuaTimer* pLuaTimer) return; // Remove all references - ListRemove(m_TimerList, pLuaTimer); - ListRemove(m_ProcessQueue, pLuaTimer); + ListRemoveAll(m_TimerList, pLuaTimer); + ListRemoveAll(m_ProcessQueue, pLuaTimer); if (m_pProcessingTimer == pLuaTimer) { diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp index 382c2c7488..239d005def 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp @@ -2029,9 +2029,9 @@ bool CLuaWorldDefs::SetColorFilter(uchar ucPass0Red, uchar ucPass0Green, uchar u CLuaMultiReturn CLuaWorldDefs::GetColorFilter(bool isOriginal) { - SColor uColor0 = 0; - SColor uColor1 = 0; - g_pMultiplayer->GetColorFilter(uColor0.ulARGB, uColor1.ulARGB, isOriginal); + SColor uColor0; + SColor uColor1; + g_pMultiplayer->GetColorFilter(uColor0.ARGB, uColor1.ARGB, isOriginal); return { uColor0.R, uColor0.G, uColor0.B, uColor0.A, uColor1.R, uColor1.G, uColor1.B, uColor1.A, diff --git a/Client/multiplayer_sa/CMultiplayerSA.cpp b/Client/multiplayer_sa/CMultiplayerSA.cpp index 1b21f79a23..e065f1d0f1 100644 --- a/Client/multiplayer_sa/CMultiplayerSA.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA.cpp @@ -1734,8 +1734,8 @@ void CMultiplayerSA::GetColorFilter(DWORD& dwPass0Color, DWORD& dwPass1Color, bo if (bUseTimeCycle || isOriginal){ //If we are using color filter from time cycle or we specified color filter from time cycle SColorRGBA pass0SColor(*(float*)0xB7C518, *(float*)0xB7C51C, *(float*)0xB7C520, *(float*)0xB7C524); SColorRGBA pass1SColor(*(float*)0xB7C528, *(float*)0xB7C52C, *(float*)0xB7C530, *(float*)0xB7C534); - dwPass0Color = pass0SColor.ulARGB; - dwPass1Color = pass1SColor.ulARGB; + dwPass0Color = pass0SColor.ARGB; + dwPass1Color = pass1SColor.ARGB; } else { diff --git a/Server/mods/deathmatch/logic/CColManager.cpp b/Server/mods/deathmatch/logic/CColManager.cpp index f560f34dc1..b75b7d185c 100644 --- a/Server/mods/deathmatch/logic/CColManager.cpp +++ b/Server/mods/deathmatch/logic/CColManager.cpp @@ -207,7 +207,7 @@ void CColManager::RemoveFromList(CColShape* pShape) } else { - ListRemove(m_List, pShape); + ListRemoveAll(m_List, pShape); } } } @@ -217,7 +217,7 @@ void CColManager::TakeOutTheTrash() std::vector::const_iterator iter = m_TrashCan.begin(); for (; iter != m_TrashCan.end(); iter++) { - ListRemove(m_List, *iter); + ListRemoveAll(m_List, *iter); } m_TrashCan.clear(); diff --git a/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp b/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp index 3a75cf8074..77a0d6876b 100644 --- a/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp +++ b/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp @@ -365,7 +365,7 @@ bool CDatabaseJobQueueImpl::PollCommand(CDbJobData* pJobData, uint uiTimeout) // See if result has come in yet if (ListContains(shared.m_ResultQueue, pJobData)) { - ListRemove(shared.m_ResultQueue, pJobData); + ListRemoveAll(shared.m_ResultQueue, pJobData); pJobData->stage = EJobStage::FINISHED; MapInsert(m_FinishedList, pJobData); diff --git a/Server/mods/deathmatch/logic/CObject.cpp b/Server/mods/deathmatch/logic/CObject.cpp index 8094f9dda9..4d44f54886 100644 --- a/Server/mods/deathmatch/logic/CObject.cpp +++ b/Server/mods/deathmatch/logic/CObject.cpp @@ -426,7 +426,7 @@ bool CObject::SetLowLodObject(CObject* pNewLowLodObject) assert(ListContains(m_pLowLodObject->m_HighLodObjectList, this)); // Clear there and here - ListRemove(m_pLowLodObject->m_HighLodObjectList, this); + ListRemoveAll(m_pLowLodObject->m_HighLodObjectList, this); m_pLowLodObject = NULL; return true; } diff --git a/Server/mods/deathmatch/logic/CPerfStatManager.cpp b/Server/mods/deathmatch/logic/CPerfStatManager.cpp index 2b5d0926dd..9c9880b593 100644 --- a/Server/mods/deathmatch/logic/CPerfStatManager.cpp +++ b/Server/mods/deathmatch/logic/CPerfStatManager.cpp @@ -136,7 +136,7 @@ void CPerfStatManagerImpl::AddModule(CPerfStatModule* pModule) /////////////////////////////////////////////////////////////// void CPerfStatManagerImpl::RemoveModule(CPerfStatModule* pModule) { - ListRemove(m_ModuleList, pModule); + ListRemoveAll(m_ModuleList, pModule); } /////////////////////////////////////////////////////////////// diff --git a/Server/mods/deathmatch/logic/CRegistryManager.cpp b/Server/mods/deathmatch/logic/CRegistryManager.cpp index 008445064f..b025198766 100644 --- a/Server/mods/deathmatch/logic/CRegistryManager.cpp +++ b/Server/mods/deathmatch/logic/CRegistryManager.cpp @@ -41,7 +41,7 @@ bool CRegistryManager::CloseRegistry(CRegistry* pRegistry) { if (ListContains(m_RegistryList, pRegistry)) { - ListRemove(m_RegistryList, pRegistry); + ListRemoveAll(m_RegistryList, pRegistry); delete pRegistry; return true; } diff --git a/Server/mods/deathmatch/logic/CResource.AclRequest.cpp b/Server/mods/deathmatch/logic/CResource.AclRequest.cpp index 27b7017141..8900fb6f77 100644 --- a/Server/mods/deathmatch/logic/CResource.AclRequest.cpp +++ b/Server/mods/deathmatch/logic/CResource.AclRequest.cpp @@ -169,7 +169,7 @@ void CResource::RefreshAutoPermissions(CXMLNode* pNodeAclRequest) } // This right is used - ListRemove(unusedRightNameMap, request.rightName); + ListRemoveAll(unusedRightNameMap, request.rightName); // Update flag bHasPending |= request.bPending; diff --git a/Server/mods/deathmatch/logic/lua/CLuaCallback.h b/Server/mods/deathmatch/logic/lua/CLuaCallback.h index 477fadb5b3..74c5c7cf9f 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaCallback.h +++ b/Server/mods/deathmatch/logic/lua/CLuaCallback.h @@ -59,7 +59,7 @@ class CLuaCallbackManager void DestroyCallback(CLuaCallback* pCallback) { - ListRemove(m_CallbackList, pCallback); + ListRemoveAll(m_CallbackList, pCallback); delete pCallback; } diff --git a/Server/mods/deathmatch/logic/lua/CLuaTimerManager.cpp b/Server/mods/deathmatch/logic/lua/CLuaTimerManager.cpp index 0af771b289..826db1342c 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaTimerManager.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaTimerManager.cpp @@ -87,8 +87,8 @@ void CLuaTimerManager::RemoveTimer(CLuaTimer* pLuaTimer) return; // Remove all references - ListRemove(m_TimerList, pLuaTimer); - ListRemove(m_ProcessQueue, pLuaTimer); + ListRemoveAll(m_TimerList, pLuaTimer); + ListRemoveAll(m_ProcessQueue, pLuaTimer); if (m_pProcessingTimer == pLuaTimer) { diff --git a/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp b/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp index 41324166d3..dbffdc90da 100644 --- a/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp +++ b/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp @@ -90,7 +90,7 @@ void CSimPlayerManager::RemoveSimPlayer(CPlayer* pPlayer) for (std::set::const_iterator iter = m_AllSimPlayerMap.begin(); iter != m_AllSimPlayerMap.end(); ++iter) { CSimPlayer* pOtherSim = *iter; - ListRemove(pOtherSim->m_PuresyncSendListFlat, pSim); + ListRemoveAll(pOtherSim->m_PuresyncSendListFlat, pSim); pOtherSim->m_bSendListChanged = true; } diff --git a/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp b/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp index 942eba525c..dd85d9727f 100644 --- a/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp +++ b/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp @@ -86,7 +86,7 @@ void CLatentTransferManager::RemoveRemote(NetPlayerID remoteId) { CLatentSendQueue* pSendQueue = FindSendQueueForRemote(remoteId); CLatentReceiver* pReceiver = FindReceiverForRemote(remoteId); - ListRemove(m_SendQueueList, pSendQueue); + ListRemoveAll(m_SendQueueList, pSendQueue); MapRemove(m_SendQueueMap, remoteId); SAFE_DELETE(pSendQueue); diff --git a/Shared/mods/deathmatch/logic/CScriptDebugging.cpp b/Shared/mods/deathmatch/logic/CScriptDebugging.cpp index 701ef435bb..593e81f585 100644 --- a/Shared/mods/deathmatch/logic/CScriptDebugging.cpp +++ b/Shared/mods/deathmatch/logic/CScriptDebugging.cpp @@ -401,7 +401,7 @@ void CScriptDebugging::PopLuaMain(CLuaMain* pLuaMain) void CScriptDebugging::OnLuaMainDestroy(CLuaMain* pLuaMain) { dassert(!ListContains(m_LuaMainStack, pLuaMain)); - ListRemove(m_LuaMainStack, pLuaMain); + ListRemoveAll(m_LuaMainStack, pLuaMain); } CLuaMain* CScriptDebugging::GetTopLuaMain() diff --git a/Shared/sdk/CFastList.h b/Shared/sdk/CFastList.h index 30f65a1eb0..6a6d899bf9 100644 --- a/Shared/sdk/CFastList.h +++ b/Shared/sdk/CFastList.h @@ -9,8 +9,10 @@ * *****************************************************************************/ #pragma once + #include #include +#include #include "SharedUtil.IntTypes.h" //////////////////////////////////////////////////////////////// @@ -33,136 +35,134 @@ // 4. ITEMS CAN ONLY APPEAR IN THE LIST ONCE // //////////////////////////////////////////////////////////////// -template +template class CFastList { public: - typedef typename std::map MapType; - typedef typename std::pair MapTypePair; - typedef typename std::map InfoType; + using value_type = Value; + + using MapType = typename std::map; + using MapTypePair = typename std::pair; + using InfoType = typename std::map; + enum class EOperation { PushBack, PushFront, Remove, }; + struct SSuspendedOperation { EOperation operation; - T item; + value_type item; }; - uint uiRevision; // Incremented every time the ordered map changes - uint uiNextFrontIndex; // Next (decrementing) index to use as a map key for items added to the front - uint uiNextBackIndex; // Next (incrementing) index to use as a map key for items added to the back - MapType orderedMap; // Ordered map of items - InfoType infoMap; // info for each item - bool m_bSuspendingModifyOperations; - std::vector m_SuspendedOperationList; + std::uint32_t m_revision; // Incremented every time the ordered map changes + std::uint32_t m_nextFrontIndex; // Next (decrementing) index to use as a map key for items added to the front + std::uint32_t m_nextBackIndex; // Next (incrementing) index to use as a map key for items added to the back + MapType m_orderedMap; // Ordered map of items + InfoType m_infoMap; // info for each item + bool m_suspendingModifyOperations; + std::vector m_suspendedOperationList; - CFastList() : uiRevision(1), uiNextFrontIndex(UINT_MAX / 2 - 1), uiNextBackIndex(UINT_MAX / 2), m_bSuspendingModifyOperations(false) - { - #ifdef MTA_DEBUG - // T must be a pointer - void* ptr = (T)NULL; - ptr = NULL; - #endif - } + CFastList() noexcept : m_revision(1), m_nextFrontIndex(UINT_MAX / 2 - 1), m_nextBackIndex(UINT_MAX / 2), m_suspendingModifyOperations(false) + {} - const T& front() const { return orderedMap.begin()->second; } + const value_type& front() const noexcept { return m_orderedMap.begin()->second; } void pop_front() { - dassert(!m_bSuspendingModifyOperations); - T item = front(); - remove(item); + dassert(!m_suspendingModifyOperations); + remove(front()); } - void push_front(const T& item) + void push_front(const value_type& item) { - if (m_bSuspendingModifyOperations) + if (m_suspendingModifyOperations) { - m_SuspendedOperationList.push_back({EOperation::PushFront, item}); + m_suspendedOperationList.push_back({EOperation::PushFront, item}); return; } // Check if indexing will wrap (and so destroy map order) - if (uiNextFrontIndex < 5000) + if (m_nextFrontIndex < 5000) Reindex(); - dassert(orderedMap.find(uiNextFrontIndex) == orderedMap.end()); + dassert(m_orderedMap.find(m_nextFrontIndex) == m_orderedMap.end()); // Optimized insert at the map beginning - orderedMap.insert(orderedMap.begin(), MapTypePair(uiNextFrontIndex, item)); - uiRevision++; - SetItemIndex(item, uiNextFrontIndex); - uiNextFrontIndex--; + m_orderedMap.insert(m_orderedMap.begin(), MapTypePair(m_nextFrontIndex, item)); + m_revision++; + SetItemIndex(item, m_nextFrontIndex); + m_nextFrontIndex--; } - void push_back(const T& item) + void push_back(const value_type& item) { - if (m_bSuspendingModifyOperations) + if (m_suspendingModifyOperations) { - m_SuspendedOperationList.push_back({EOperation::PushBack, item}); + m_suspendedOperationList.push_back({EOperation::PushBack, item}); return; } // Check if indexing will wrap (and so destroy map order) - if (uiNextBackIndex > UINT_MAX - 5000) + if (m_nextBackIndex > UINT_MAX - 5000) Reindex(); - dassert(orderedMap.find(uiNextBackIndex) == orderedMap.end()); + dassert(m_orderedMap.find(m_nextBackIndex) == m_orderedMap.end()); // Optimized insert at the map end - orderedMap.insert(orderedMap.end(), MapTypePair(uiNextBackIndex, item)); - uiRevision++; - SetItemIndex(item, uiNextBackIndex); - uiNextBackIndex++; + m_orderedMap.insert(m_orderedMap.end(), MapTypePair(m_nextBackIndex, item)); + m_revision++; + SetItemIndex(item, m_nextBackIndex); + m_nextBackIndex++; } - bool contains(const T& item) const { return (infoMap.find(item) != infoMap.end()); } - - size_t size() const { return orderedMap.size(); } - - bool empty() const { return orderedMap.empty(); } + bool contains(const value_type& item) const noexcept { + return m_infoMap.find(item) != m_infoMap.end(); + } + std::size_t size() const noexcept { return m_orderedMap.size(); } + bool empty() const noexcept { return m_orderedMap.empty(); } void clear() { - dassert(!m_bSuspendingModifyOperations); - orderedMap.clear(); - uiRevision++; - infoMap.clear(); - uiNextFrontIndex = UINT_MAX / 2 - 1; - uiNextBackIndex = UINT_MAX / 2; + dassert(!m_suspendingModifyOperations); + m_orderedMap.clear(); + m_revision++; + m_infoMap.clear(); + m_nextBackIndex = UINT_MAX / 2; + m_nextFrontIndex = m_nextFrontIndex - 1; } - void remove(const T& item) + void remove(const value_type& item) { - if (m_bSuspendingModifyOperations) + if (m_suspendingModifyOperations) { - m_SuspendedOperationList.push_back({EOperation::Remove, item}); + m_suspendedOperationList.push_back({EOperation::Remove, item}); return; } - if (uint uiIndex = GetItemIndex(item)) - { - typename MapType::iterator it = orderedMap.find(uiIndex); - dassert(it != orderedMap.end()); - dassert(it->second == item); - orderedMap.erase(it); - uiRevision++; - RemoveItemIndex(item); - } + auto i = GetItemIndex(item); + if (!i) + return; + + auto it = m_orderedMap.find(i); + dassert(it != m_orderedMap.end()); + dassert(it->second == item); + m_orderedMap.erase(it); + m_revision++; + RemoveItemIndex(item); } - uint GetRevision() const { return uiRevision; } + std::uint32_t GetRevision() const noexcept { return m_revision; } // Queue remove/push_back/push_front operations until ResumeModifyOperations is called void SuspendModifyOperations() { - dassert(!m_bSuspendingModifyOperations); - m_bSuspendingModifyOperations = true; + dassert(!m_suspendingModifyOperations); + m_suspendingModifyOperations = true; } // Replay queued operations void ResumeModifyOperations() { - dassert(m_bSuspendingModifyOperations); - m_bSuspendingModifyOperations = false; - for (const auto& suspendedOperation : m_SuspendedOperationList) + dassert(m_suspendingModifyOperations); + m_suspendingModifyOperations = false; + for (const auto& suspendedOperation : m_suspendedOperationList) { if (suspendedOperation.operation == EOperation::PushBack) push_back(suspendedOperation.item); @@ -171,50 +171,49 @@ class CFastList else if (suspendedOperation.operation == EOperation::Remove) remove(suspendedOperation.item); } - m_SuspendedOperationList.clear(); + m_suspendedOperationList.clear(); } protected: // Reset indexing void Reindex() { - uiNextFrontIndex = UINT_MAX / 2 - 1; - uiNextBackIndex = UINT_MAX / 2; + m_nextBackIndex = UINT_MAX / 2; + m_nextFrontIndex = m_nextBackIndex - 1; MapType newMap; - for (typename MapType::iterator iter = orderedMap.begin(); iter != orderedMap.end(); ++iter) + for (const auto& [__, item] : m_orderedMap) { - T item = iter->second; - newMap[uiNextBackIndex] = item; + newMap[m_nextBackIndex] = item; RemoveItemIndex(item); - SetItemIndex(item, uiNextBackIndex); - uiNextBackIndex++; + SetItemIndex(item, m_nextBackIndex); + m_nextBackIndex++; } - orderedMap = newMap; + m_orderedMap = newMap; } // Handle storage of the item index - uint GetItemIndex(const T& item) const + std::uint32_t GetItemIndex(const value_type& item) const noexcept { - typename InfoType::const_iterator it = infoMap.find(item); - if (it == infoMap.end()) + auto it = m_infoMap.find(item); + if (it == m_infoMap.end()) return 0; return it->second; } // Item must not exist in the infoMap - void SetItemIndex(const T& item, uint uiIndex) + void SetItemIndex(const value_type& item, std::uint32_t index) { - typename InfoType::const_iterator it = infoMap.find(item); - assert(it == infoMap.end() && uiIndex); - infoMap[item] = uiIndex; + auto it = m_infoMap.find(item); + assert(it == m_infoMap.end() && index); + m_infoMap[item] = index; } // Item must exist in the infoMap - void RemoveItemIndex(const T& item) + void RemoveItemIndex(const value_type& item) { - typename InfoType::iterator it = infoMap.find(item); - assert(it != infoMap.end()); - infoMap.erase(it); + auto it = m_infoMap.find(item); + assert(it != m_infoMap.end()); + m_infoMap.erase(it); } public: @@ -226,12 +225,12 @@ class CFastList public: typename MapType::const_iterator iter; - ConstIterator(typename MapType::const_iterator initer) : iter(initer) {} - bool operator==(const ConstIterator& other) const { return iter == other.iter; } - bool operator!=(const ConstIterator& other) const { return iter != other.iter; } - void operator++() { ++iter; } - void operator++(int) { iter++; } - const T& operator*() const { return iter->second; } + ConstIterator(typename MapType::const_iterator initer) noexcept : iter(initer){} + bool operator==(const ConstIterator& other) const noexcept { return iter == other.iter; } + bool operator!=(const ConstIterator& other) const noexcept { return iter != other.iter; } + void operator++() noexcept { ++iter; } + void operator++(int) noexcept { iter++; } + const value_type& operator*() const noexcept { return iter->second; } }; class Iterator @@ -239,13 +238,13 @@ class CFastList public: typename MapType::iterator iter; - Iterator(typename MapType::iterator initer) : iter(initer) {} - bool operator==(const Iterator& other) const { return iter == other.iter; } - bool operator!=(const Iterator& other) const { return iter != other.iter; } - void operator++() { ++iter; } - void operator++(int) { iter++; } - const T& operator*() const { return iter->second; } - operator ConstIterator() const { return ConstIterator(iter); } + Iterator(typename MapType::iterator initer) noexcept : iter(initer){} + bool operator==(const Iterator& other) const noexcept { return iter == other.iter; } + bool operator!=(const Iterator& other) const noexcept { return iter != other.iter; } + void operator++() noexcept { ++iter; } + void operator++(int) noexcept { iter++; } + const value_type& operator*() const noexcept { return iter->second; } + operator ConstIterator() const noexcept { return ConstIterator(iter); } }; // @@ -256,12 +255,12 @@ class CFastList public: typename MapType::const_reverse_iterator iter; - ConstReverseIterator(typename MapType::const_reverse_iterator initer) : iter(initer) {} - bool operator==(const ConstReverseIterator& other) const { return iter == other.iter; } - bool operator!=(const ConstReverseIterator& other) const { return iter != other.iter; } - void operator++() { ++iter; } - void operator++(int) { iter++; } - const T& operator*() const { return iter->second; } + ConstReverseIterator(typename MapType::const_reverse_iterator initer) noexcept : iter(initer){} + bool operator==(const ConstReverseIterator& other) const noexcept { return iter == other.iter; } + bool operator!=(const ConstReverseIterator& other) const noexcept { return iter != other.iter; } + void operator++() noexcept { ++iter; } + void operator++(int) noexcept { iter++; } + const value_type& operator*() const noexcept { return iter->second; } }; class ReverseIterator @@ -269,52 +268,60 @@ class CFastList public: typename MapType::reverse_iterator iter; - ReverseIterator(typename MapType::reverse_iterator initer) : iter(initer) {} - bool operator==(const ReverseIterator& other) const { return iter == other.iter; } - bool operator!=(const ReverseIterator& other) const { return iter != other.iter; } - void operator++() { ++iter; } - void operator++(int) { iter++; } - const T& operator*() const { return iter->second; } - operator ConstReverseIterator() const { return ConstReverseIterator(iter); } + ReverseIterator(typename MapType::reverse_iterator initer) noexcept : iter(initer){} + bool operator==(const ReverseIterator& other) const noexcept { return iter == other.iter; } + bool operator!=(const ReverseIterator& other) const noexcept { return iter != other.iter; } + void operator++() noexcept { ++iter; } + void operator++(int) noexcept { iter++; } + const value_type& operator*() const noexcept { return iter->second; } + operator ConstReverseIterator() const noexcept { return ConstReverseIterator(iter); } }; - ConstIterator begin() const { return ConstIterator(orderedMap.begin()); } - ConstIterator end() const { return ConstIterator(orderedMap.end()); } - Iterator begin() { return Iterator(orderedMap.begin()); } - Iterator end() { return Iterator(orderedMap.end()); } + ConstIterator begin() const noexcept { return ConstIterator(m_orderedMap.begin()); } + ConstIterator end() const noexcept { return ConstIterator(m_orderedMap.end()); } + Iterator begin() noexcept { return Iterator(m_orderedMap.begin()); } + Iterator end() noexcept { return Iterator(m_orderedMap.end()); } - ConstReverseIterator rbegin() const { return ConstReverseIterator(orderedMap.rbegin()); } - ConstReverseIterator rend() const { return ConstReverseIterator(orderedMap.rend()); } - ReverseIterator rbegin() { return ReverseIterator(orderedMap.rbegin()); } - ReverseIterator rend() { return ReverseIterator(orderedMap.rend()); } + ConstReverseIterator rbegin() const noexcept { return ConstReverseIterator(m_orderedMap.rbegin()); } + ConstReverseIterator rend() const noexcept { return ConstReverseIterator(m_orderedMap.rend()); } + ReverseIterator rbegin() noexcept { return ReverseIterator(m_orderedMap.rbegin()); } + ReverseIterator rend() noexcept { return ReverseIterator(m_orderedMap.rend()); } // Allow use of std iterator names - typedef Iterator iterator; - typedef ConstIterator const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ConstReverseIterator const_reverse_iterator; + using iterator = Iterator; + using const_iterator = ConstIterator; + using reverse_iterator = ReverseIterator; + using const_reverse_iterator = ConstReverseIterator; - Iterator erase(Iterator iter) + Iterator erase(Iterator pos) noexcept { - RemoveItemIndex(*iter); - orderedMap.erase(iter.iter++); - uiRevision++; - return iter; + RemoveItemIndex(*pos); + m_orderedMap.erase(pos.iter++); + m_revision++; + return pos; + } + + Iterator erase(Iterator first, Iterator last) noexcept { + Iterator outIter; + for (auto it = first; it != last; it++) + { + erase(it); + outIter = it; + } + return outIter; } }; // Returns true if the item is in the itemList template -bool ListContains(const CFastList& itemList, const U& item) +constexpr bool ListContains(const CFastList& list, const U& item) noexcept { - if (itemList.empty()) - return false; - return itemList.contains(item); + return list.contains(item); } // Remove all occurrences of item from itemList (There should never be more than one anyway) template -void ListRemove(CFastList& itemList, const U& item) +constexpr void ListRemoveAll(CFastList& list, const U& item) noexcept { - itemList.remove(item); + list.remove(item); } diff --git a/Shared/sdk/SharedUtil.Misc.h b/Shared/sdk/SharedUtil.Misc.h index d64f155a7c..703a76e175 100644 --- a/Shared/sdk/SharedUtil.Misc.h +++ b/Shared/sdk/SharedUtil.Misc.h @@ -25,12 +25,12 @@ namespace SharedUtil { class CArgMap; -#ifdef WIN32 +#ifdef _WIN32 SString GetMajorVersionString(); // Get a system registry value - SString GetSystemRegistryValue(uint hKey, const SString& strPath, const SString& strName); + SString GetSystemRegistryValue(std::uint32_t hKey, const SString& strPath, const SString& strName); // Get/set registry values for the current version void SetRegistryValue(const SString& strPath, const SString& strName, const SString& strValue, bool bFlush = false); @@ -100,8 +100,8 @@ namespace SharedUtil // // For tracking results of new features // - void AddReportLog(uint uiId, const SString& strText, uint uiAmountLimit = 0); - void AddExceptionReportLog(uint uiId, const char* szExceptionName, const char* szExceptionText); + void AddReportLog(std::uint32_t uiId, const SString& strText, std::uint32_t uiAmountLimit = 0); + void AddExceptionReportLog(std::uint32_t uiId, const char* szExceptionName, const char* szExceptionText); void SetReportLogContents(const SString& strText); SString GetReportLogContents(); SString GetReportLogProcessTag(); @@ -163,7 +163,7 @@ namespace SharedUtil bool ProcessPendingBrowseToSolution(); void ClearPendingBrowseToSolution(); - SString GetSystemErrorMessage(uint uiErrorCode, bool bRemoveNewlines = true, bool bPrependCode = true); + SString GetSystemErrorMessage(std::uint32_t uiErrorCode, bool bRemoveNewlines = true, bool bPrependCode = true); void SetClipboardText(const SString& strText); SString GetClipboardText(); @@ -191,7 +191,7 @@ namespace SharedUtil // CPU stats struct SThreadCPUTimes { - uint uiProcessorNumber = 0; + std::uint32_t uiProcessorNumber = 0; float fUserPercent = 0; float fKernelPercent = 0; float fTotalCPUPercent = 0; @@ -201,17 +201,16 @@ namespace SharedUtil }; struct SThreadCPUTimesStore : SThreadCPUTimes { - SThreadCPUTimesStore() {} uint64 ullPrevCPUMeasureTimeMs = 0; uint64 ullPrevUserTimeUs = 0; uint64 ullPrevKernelTimeUs = 0; float fAvgTimeSeconds = 5.0f; }; DWORD _GetCurrentProcessorNumber(); - void GetThreadCPUTimes(uint64& outUserTime, uint64& outKernelTime); - void UpdateThreadCPUTimes(SThreadCPUTimesStore& store, long long* pllTickCount = NULL); + void GetThreadCPUTimes(std::uint64_t& outUserTime, std::uint64_t& outKernelTime); + void UpdateThreadCPUTimes(SThreadCPUTimesStore& store, long long* pllTickCount = nullptr); - SString EscapeString(const SString& strText, const SString& strDisallowedChars, char cSpecialChar = '#', uchar ucLowerLimit = 0, uchar ucUpperLimit = 255); + SString EscapeString(const SString& strText, const SString& strDisallowedChars, char cSpecialChar = '#', std::uint8_t ucLowerLimit = 0, std::uint8_t ucUpperLimit = 255); SString UnescapeString(const SString& strText, char cSpecialChar = '#'); SString EscapeURLArgument(const SString& strText); @@ -238,13 +237,13 @@ namespace SharedUtil std::wstring ANSIToUTF16(const SString& s); - int GetUTF8Confidence(const unsigned char* input, int len); + int GetUTF8Confidence(const std::uint8_t* input, int len); - bool IsUTF8BOM(const void* pData, uint uiLength); + bool IsUTF8BOM(const void* pData, std::uint32_t uiLength); // Buffer identification - bool IsLuaCompiledScript(const void* pData, uint uiLength); - bool IsLuaObfuscatedScript(const void* pData, uint uiLength); + bool IsLuaCompiledScript(const void* pData, std::uint32_t uiLength); + bool IsLuaObfuscatedScript(const void* pData, std::uint32_t uiLength); // Return a pointer to the (shifted) trimmed string // @ref https://stackoverflow.com/a/26984026 @@ -255,27 +254,27 @@ namespace SharedUtil // // Clamps a value between two other values ( min < a < max ) template - T Clamp(const T& min, const T& a, const T& max) + constexpr T Clamp(const T& min, const T& a, const T& max) noexcept { return a < min ? min : a > max ? max : a; } // Checks whether a value is between two other values ( min <= a <= max ) template - bool Between(const T& min, const T& a, const T& max) + constexpr bool Between(const T& min, const T& a, const T& max) noexcept { return a >= min && a <= max; } // Lerps between two values depending on the weight template - T Lerp(const T& from, float fAlpha, const T& to) + constexpr T Lerp(const T& from, float fAlpha, const T& to) noexcept { - return (T)((to - from) * fAlpha + from); + return static_cast((to - from) * fAlpha + from); } // Find the relative position of Pos between From and To - inline const float Unlerp(const double dFrom, const double dPos, const double dTo) + constexpr float Unlerp(const double dFrom, const double dPos, const double dTo) noexcept { // Avoid dividing by 0 (results in INF values) if (dFrom == dTo) @@ -285,16 +284,18 @@ namespace SharedUtil } // Unlerp avoiding extrapolation - inline const float UnlerpClamped(const double dFrom, const double dPos, const double dTo) { return Clamp(0.0f, Unlerp(dFrom, dPos, dTo), 1.0f); } + constexpr float UnlerpClamped(const double dFrom, const double dPos, const double dTo) { + return Clamp(0.0f, Unlerp(dFrom, dPos, dTo), 1.0f); + } template - int Round(T value) + int Round(const T value) noexcept { return static_cast(std::floor(value + 0.5f)); } template - T WrapAround(T fLow, T fValue, T fHigh) + T WrapAround(const T fLow, const T fValue, const T fHigh) noexcept { const T fSize = fHigh - fLow; return fValue - (fSize * std::floor((fValue - fLow) / fSize)); @@ -310,22 +311,22 @@ namespace SharedUtil }; template - T EvalSamplePosition(const SSamplePoint* pPoints, uint uiNumPoints, const T& samplePosition) + constexpr T EvalSamplePosition(const SSamplePoint* pPoints, std::uint32_t uiNumPoints, const T& samplePosition) noexcept { // Before first point if (samplePosition < pPoints[0].in) return pPoints[0].out; // Between points - for (uint i = 1; i < uiNumPoints; i++) + for (std::uint32_t i = 1; i < uiNumPoints; i++) { - if (samplePosition < pPoints[i].in) - { - // Find position between input points - T pos = UnlerpClamped(pPoints[i - 1].in, samplePosition, pPoints[i].in); - // Map to output points - return Lerp(pPoints[i - 1].out, pos, pPoints[i].out); - } + if (samplePosition >= pPoints[i].in) + continue; + + // Find position between input points + T pos = UnlerpClamped(pPoints[i - 1].in, samplePosition, pPoints[i].in); + // Map to output points + return Lerp(pPoints[i - 1].out, pos, pPoints[i].out); } // After last point @@ -340,121 +341,86 @@ namespace SharedUtil // std:: container helpers // - // Returns true if the item is in the itemList - template - bool ListContains(const TL& itemList, const T& item) + template + constexpr auto ListGetIterator(const Container& list, const Value& value) noexcept { - if (itemList.empty()) - return false; - typename TL ::const_iterator it = itemList.begin(); - for (; it != itemList.end(); ++it) - if (item == *it) - return true; - return false; + return std::find(list.cbegin(), list.cend(), value); } - // Add item if it does not aleady exist in itemList - template - void ListAddUnique(TL& itemList, const T& item) + + template + constexpr bool ListContains(const Container& list, const Value& value) noexcept { - if (!ListContains(itemList, item)) - itemList.push_back(item); + return ListGetIterator(list, value) != list.end(); } - // - // std::list helpers - // - - // Remove first occurrence of item from itemList - template - void ListRemoveFirst(std::list& itemList, const T& item) + template + constexpr void ListRemoveFirst(Container& list, const Value& value) noexcept { - typename std::list::iterator it = itemList.begin(); - for (; it != itemList.end(); ++it) - if (item == *it) - { - itemList.erase(it); - break; - } + auto iter = ListGetIterator(list, value); + if (iter != list.end()) + list.erase(iter); } - // Remove all occurrences of item from itemList - template - void ListRemove(std::list& itemList, const T& item) + template + constexpr void ListRemoveAll(Container& list, const Value& value) noexcept { - itemList.remove(item); + list.erase(std::remove(list.begin(), list.end(), value), list.end()); } - // - // std::vector helpers - // + // Add item if it does not aleady exist in itemList + template + constexpr void ListAddUnique(Container& list, const Value& value) noexcept + { + if (!ListContains(list, value)) + list.push_back(value); + } - // Remove first occurrence of item from itemList - template - void ListRemoveFirst(std::vector& itemList, const T& item) + // Append one list onto another + template + constexpr void ListAppend(Container& list, const Container& other) noexcept { - typename std::vector::iterator it = itemList.begin(); - for (; it != itemList.end(); ++it) - if (item == *it) - { - itemList.erase(it); - break; - } + list.insert(list.end(), other.begin(), other.end()); } + // + // std::list helpers + // + // Remove all occurrences of item from itemList - template - void ListRemove(std::vector& itemList, const T& item) + + template + constexpr void ListRemoveAll(std::list& list, const Value& value) noexcept { - typename std::vector::iterator it = itemList.begin(); - while (it != itemList.end()) - { - if (item == *it) - it = itemList.erase(it); - else - ++it; - } + list.remove(value); } + // + // std::vector helpers + // + // Remove item at index from itemList - template - void ListRemoveIndex(std::vector& itemList, uint index) + template + constexpr void ListRemoveIndex(std::vector& list, const std::size_t& value) noexcept { - if (index < itemList.size()) - itemList.erase(itemList.begin() + index); + if (value < list.size()) + list.erase(list.begin() + value); } // Append one list onto another - template - void ListAppend(std::vector& itemList, const std::vector& other) - { - itemList.insert(itemList.end(), other.begin(), other.end()); - } - - // Clear and reserve memory for the same size - template - void ListClearAndReserve(std::vector& itemList) + template + constexpr void ListAppend(std::vector& list, const std::vector& other) noexcept { - size_t prevSize = itemList.size(); - itemList.clear(); - itemList.reserve(prevSize); + list.insert(list.end(), other.begin(), other.end()); } - // - // std::deque helpers - // - // Remove all occurrences of item from itemList - template - void ListRemove(std::deque& itemList, const T& item) + // Clear and reserve memory for the same size + template + constexpr void ListClearAndReserve(std::vector& list) noexcept { - typename std::deque::iterator it = itemList.begin(); - while (it != itemList.end()) - { - if (item == *it) - it = itemList.erase(it); - else - ++it; - } + std::size_t prevSize = list.size(); + list.clear(); + list.reserve(prevSize); } // @@ -463,23 +429,35 @@ namespace SharedUtil // Encapsulates the most common usage of 4 byte color storage. // Casts to and from a DWORD as 0xAARRGGBB // - class SColor + struct SColor { - public: union { - struct - { - unsigned char B, G, R, A; - }; - unsigned long ulARGB; + struct { std::uint8_t B, G, R, A; }; + DWORD ARGB; }; + constexpr SColor() noexcept : ARGB(0) {} + constexpr SColor(std::uint32_t value) noexcept : ARGB(value) {} + constexpr SColor(std::uint8_t a, std::uint8_t r, std::uint8_t g, std::uint8_t b) noexcept : A(a), R(r), G(g), B(b) {} - SColor() : ulARGB(0) {} + constexpr operator unsigned long() const noexcept { return ARGB; } - SColor(unsigned long ulValue) { ulARGB = ulValue; } - - operator unsigned long() const { return ulARGB; } + constexpr SColor operator|(std::uint32_t value) const noexcept { + return SColor(ARGB | value); + } + constexpr SColor operator&(std::uint32_t value) const noexcept { + return SColor(ARGB & value); + } + constexpr SColor& operator|=(std::uint32_t value) noexcept { + ARGB |= value; + return *this; + } + constexpr SColor& operator&=(std::uint32_t value) noexcept { + ARGB &= value; + return *this; + } + constexpr bool operator==(SColor other) noexcept { return ARGB == other.ARGB; } + constexpr bool operator!=(SColor other) noexcept { return !operator==(other); } }; // @@ -487,25 +465,13 @@ namespace SharedUtil // // Make an SColor from A,R,G,B // - class SColorARGB : public SColor + struct SColorARGB : public SColor { - public: - SColorARGB(unsigned char ucA, unsigned char ucR, unsigned char ucG, unsigned char ucB) - { - A = ucA; - R = ucR; - G = ucG; - B = ucB; - } - - template - SColorARGB(T a, U r, V g, W b) - { - A = Clamp(0, static_cast(a), 255); - R = Clamp(0, static_cast(r), 255); - G = Clamp(0, static_cast(g), 255); - B = Clamp(0, static_cast(b), 255); - } + template + constexpr SColorARGB(TypeA a, TypeR r, TypeG g, TypeB b) noexcept + : SColor(Clamp(0, static_cast(a), 255), Clamp(0, static_cast(r), 255), + Clamp(0, static_cast(g), 255), Clamp(0, static_cast(b), 255)) + {} }; // @@ -513,41 +479,32 @@ namespace SharedUtil // // Make an SColor from R,G,B,A // - class SColorRGBA : public SColor + struct SColorRGBA : public SColor { - public: - SColorRGBA(unsigned char ucR, unsigned char ucG, unsigned char ucB, unsigned char ucA) - { - A = ucA; - R = ucR; - G = ucG; - B = ucB; - } + constexpr SColorRGBA(std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint8_t a) noexcept : SColor(a, r, g, b) + {} template - SColorRGBA(T r, U g, V b, W a) - { - A = Clamp(0, static_cast(a), 255); - R = Clamp(0, static_cast(r), 255); - G = Clamp(0, static_cast(g), 255); - B = Clamp(0, static_cast(b), 255); - } + constexpr SColorRGBA(T r, U g, V b, W a) noexcept + : SColor(Clamp(0, static_cast(a), 255), Clamp(0, static_cast(r), 255), + Clamp(0, static_cast(g), 255), Clamp(0, static_cast(b), 255)) + {} }; // // Things to make it simpler to use SColor with the source code as it stands // - typedef SColor RGBA; + using RGBA = SColor; - inline unsigned char COLOR_RGBA_R(SColor color) { return color.R; } - inline unsigned char COLOR_RGBA_G(SColor color) { return color.G; } - inline unsigned char COLOR_RGBA_B(SColor color) { return color.B; } - inline unsigned char COLOR_RGBA_A(SColor color) { return color.A; } - inline unsigned char COLOR_ARGB_A(SColor color) { return color.A; } + constexpr std::uint8_t COLOR_RGBA_R(SColor color) noexcept { return color.R; } + constexpr std::uint8_t COLOR_RGBA_G(SColor color) noexcept { return color.G; } + constexpr std::uint8_t COLOR_RGBA_B(SColor color) noexcept { return color.B; } + constexpr std::uint8_t COLOR_RGBA_A(SColor color) noexcept { return color.A; } + constexpr std::uint8_t COLOR_ARGB_A(SColor color) noexcept { return color.A; } - inline SColor COLOR_RGBA(unsigned char R, unsigned char G, unsigned char B, unsigned char A) { return SColorRGBA(R, G, B, A); } - inline SColor COLOR_ARGB(unsigned char A, unsigned char R, unsigned char G, unsigned char B) { return SColorRGBA(R, G, B, A); } - inline SColor COLOR_ABGR(unsigned char A, unsigned char B, unsigned char G, unsigned char R) { return SColorRGBA(R, G, B, A); } + constexpr SColor COLOR_RGBA(std::uint8_t R, std::uint8_t G, std::uint8_t B, std::uint8_t A) noexcept { return SColorRGBA(R, G, B, A); } + constexpr SColor COLOR_ARGB(std::uint8_t A, std::uint8_t R, std::uint8_t G, std::uint8_t B) noexcept { return SColorRGBA(R, G, B, A); } + constexpr SColor COLOR_ABGR(std::uint8_t A, std::uint8_t B, std::uint8_t G, std::uint8_t R) noexcept { return SColorRGBA(R, G, B, A); } // // Cross platform critical section @@ -573,9 +530,10 @@ namespace SharedUtil CAutoCSLock& operator=(const CAutoCSLock&); public: - CAutoCSLock(CCriticalSection& criticalSection) : m_CS(criticalSection) { m_CS.Lock(); } + CAutoCSLock(CCriticalSection& criticalSection) noexcept + : m_CS(criticalSection) { m_CS.Lock(); } - ~CAutoCSLock() { m_CS.Unlock(); } + ~CAutoCSLock() noexcept { m_CS.Unlock(); } protected: CCriticalSection& m_CS; @@ -604,46 +562,42 @@ namespace SharedUtil // // Note: IDs run from 1 to Capacity // - template + template class CStack { public: - CStack() + CStack() noexcept { m_ulCapacity = 0; ExpandBy(INITIAL_MAX_STACK_SIZE - 1); } - unsigned long GetCapacity() const { return m_ulCapacity; } - - unsigned long GetUnusedAmount() const { return m_Queue.size(); } + std::size_t GetCapacity() const noexcept { return m_ulCapacity; } + std::size_t GetUnusedAmount() const noexcept { return m_Queue.size(); } - void ExpandBy(unsigned long ulAmount) + void ExpandBy(std::size_t amount) { - const unsigned long ulOldSize = m_ulCapacity; - const unsigned long ulNewSize = m_ulCapacity + ulAmount; + const auto oldSize = m_ulCapacity; + const auto newSize = m_ulCapacity + amount; // Add ID's for new items - for (T ID = ulOldSize + 1; ID <= ulNewSize; ++ID) + for (T ID = oldSize + 1; ID <= newSize; ++ID) { m_Queue.push_front(ID); } - m_ulCapacity = ulNewSize; + m_ulCapacity = newSize; } bool Pop(T& dest) { // Got any items? Pop from the back - if (m_Queue.size() > 0) - { - T ID = m_Queue.back(); - dest = ID; - m_Queue.pop_back(); - return true; - } + if (m_Queue.size() <= 0) + return false; - // No IDs left - return false; + T ID = m_Queue.back(); + dest = ID; + m_Queue.pop_back(); + return true; } void Push(T ID) @@ -654,35 +608,37 @@ namespace SharedUtil } private: - unsigned long m_ulCapacity; + std::uint32_t m_ulCapacity; std::deque m_Queue; }; // // Fixed sized string buffer // - template + template class SFixedString { + std::size_t m_length{ 0 }; char szData[MAX_LENGTH + 1]; public: - constexpr SFixedString() { szData[0] = 0; } + constexpr SFixedString() noexcept { szData[0] = 0; } // In - constexpr SFixedString& Assign(const char* szOther, size_t len) + constexpr SFixedString& Assign(const char* szOther, std::size_t len) noexcept { STRNCPY(szData, szOther, len + 1); + for (m_length = 0; m_length < len; m_length++); return *this; } - constexpr SFixedString& operator=(const char* szOther) + constexpr SFixedString& operator=(const char* szOther) noexcept { Assign(szOther, MAX_LENGTH + 1); return *this; } #ifdef __cpp_lib_string_view - constexpr SFixedString& operator=(std::string_view other) + constexpr SFixedString& operator=(std::string_view other) noexcept { Assign(other.data(), other.length() + 1); return *this; @@ -691,21 +647,24 @@ namespace SharedUtil #ifdef __cpp_lib_string_view // Out - constexpr operator std::string_view() const { return {szData}; } + constexpr operator std::string_view() const noexcept { return {szData}; } #endif - constexpr operator const char*() const { return szData; } - constexpr char* Data() { return &szData[0]; } + constexpr operator const char*() const noexcept { return szData; } + constexpr char* Data() noexcept { return &szData[0]; } - constexpr size_t GetMaxLength() const { return MAX_LENGTH; } - size_t GetLength() const { return strlen(szData); } + constexpr std::size_t GetMaxLength() const noexcept { return MAX_LENGTH; } + constexpr std::size_t GetLength() const noexcept { return m_length; } // Shake it all about void Encrypt(); - constexpr bool Empty() { return szData[0] == 0; } - constexpr void Clear() const { szData[0] = 0; } + constexpr bool Empty() const noexcept { return m_length <= 0; } + constexpr void Clear() noexcept { + for (auto i = 0; i < m_length; i++) + szData[i] = 0; + } // Returns a pointer to a null-terminated character array - const char* c_str() const noexcept { return &szData[0]; } + constexpr const char* c_str() const noexcept { return &szData[0]; } }; /////////////////////////////////////////////////////////////// @@ -725,8 +684,8 @@ namespace SharedUtil char m_cEscapeCharacter; public: - CArgMap(const SString& strArgSep = "=", const SString& strPartsSep = "&", const SString& strExtraDisallowedChars = ""); - void SetEscapeCharacter(char cEscapeCharacter); + CArgMap(const SString& strArgSep = "=", const SString& strPartsSep = "&", const SString& strExtraDisallowedChars = "") noexcept; + void SetEscapeCharacter(char cEscapeCharacter) noexcept; void Merge(const CArgMap& other, bool bAllowMultiValues = false); void SetFromString(const SString& strLine, bool bAllowMultiValues = false); void MergeFromString(const SString& strLine, bool bAllowMultiValues = false); @@ -803,7 +762,7 @@ namespace SharedUtil GetOption(strText, strKey, strNumbers); std::vector numberList; strNumbers.Split(szSeperator, numberList); - for (uint i = 0; i < numberList.size(); i++) + for (std::uint32_t i = 0; i < numberList.size(); i++) if (!numberList[i].empty()) MapInsert(outValues, static_cast(atoi(numberList[i]))); } @@ -815,33 +774,38 @@ namespace SharedUtil // Combination list and map - For fast list Contains() method // /////////////////////////////////////////////////////////////// - template + template class CMappedContainer { public: + using value_type = Value; + using iterator = typename ListType::iterator; + using const_iterator = typename ListType::const_iterator; + using reverse_iterator = typename ListType::reverse_iterator; + // map only - bool Contains(const T& item) const { return MapContains(m_Map, item); } + bool Contains(const value_type& item) const noexcept { return MapContains(m_Map, item); } // list only - typename LIST_TYPE ::iterator begin() { return m_List.begin(); } - typename LIST_TYPE ::iterator end() { return m_List.end(); } - typename LIST_TYPE ::const_iterator begin() const { return m_List.begin(); } - typename LIST_TYPE ::const_iterator end() const { return m_List.end(); } - typename LIST_TYPE ::reverse_iterator rbegin() { return m_List.rbegin(); } - typename LIST_TYPE ::reverse_iterator rend() { return m_List.rend(); } - uint size() const { return m_List.size(); } - bool empty() const { return m_List.empty(); } - const T& back() const { return m_List.back(); } - const T& front() const { return m_List.front(); } + iterator begin() noexcept { return m_List.begin(); } + iterator end() noexcept { return m_List.end(); } + const_iterator begin() const noexcept { return m_List.begin(); } + const_iterator end() const noexcept { return m_List.end(); } + reverse_iterator rbegin() noexcept { return m_List.rbegin(); } + reverse_iterator rend() noexcept { return m_List.rend(); } + std::size_t size() const noexcept { return m_List.size(); } + bool empty() const noexcept { return m_List.empty(); } + const value_type& back() const noexcept { return m_List.back(); } + const value_type& front() const noexcept { return m_List.front(); } // list and map - void push_back(const T& item) + void push_back(const value_type& item) { AddMapRef(item); m_List.push_back(item); } - void push_front(const T& item) + void push_front(const value_type& item) { AddMapRef(item); m_List.push_front(item); @@ -860,14 +824,14 @@ namespace SharedUtil } // Remove all occurrences of item - void remove(const T& item) + void remove(const value_type& item) { - if (Contains(item)) - { - // Remove all refs from map and list - MapRemove(m_Map, item); - ListRemove(m_List, item); - } + if (!Contains(item)) + return; + + // Remove all refs from map and list + MapRemove(m_Map, item); + ListRemoveAll(m_List, item); } void clear() @@ -876,7 +840,7 @@ namespace SharedUtil m_List.clear(); } - typename LIST_TYPE ::iterator erase(typename LIST_TYPE ::iterator iter) + iterator erase(iterator iter) { RemoveMapRef(*iter); return m_List.erase(iter); @@ -884,7 +848,7 @@ namespace SharedUtil protected: // Increment reference count for item - void AddMapRef(const T& item) + void AddMapRef(const value_type& item) { if (int* pInt = MapFind(m_Map, item)) (*pInt)++; @@ -893,9 +857,9 @@ namespace SharedUtil } // Decrement reference count for item - void RemoveMapRef(const T& item) + void RemoveMapRef(const value_type& item) { - typename std::map::iterator it = m_Map.find(item); + auto it = m_Map.find(item); if (it != m_Map.end()) if (!--(it->second)) m_Map.erase(it); @@ -905,13 +869,13 @@ namespace SharedUtil void Validate() const { int iTotalRefs = 0; - for (typename std::map::const_iterator it = m_Map.begin(); it != m_Map.end(); ++it) - iTotalRefs += it->second; + for (const auto& [first, second] : m_Map) + iTotalRefs += second; assert(iTotalRefs == m_List.size()); } - std::map m_Map; - LIST_TYPE m_List; + std::map m_Map; + ListType m_List; }; template @@ -923,8 +887,8 @@ namespace SharedUtil class CMappedArray : public CMappedContainer > { public: - const T& operator[](int idx) const { return CMappedContainer >::m_List[idx]; } - T& operator[](int idx) { return CMappedContainer >::m_List[idx]; } + const T& operator[](int idx) const noexcept { return CMappedContainer >::m_List[idx]; } + T& operator[](int idx) noexcept { return CMappedContainer >::m_List[idx]; } }; // Returns true if the item is in the itemList @@ -943,14 +907,14 @@ namespace SharedUtil // Remove all occurrences of item from itemList template - void ListRemove(CMappedList& itemList, const T& item) + void ListRemoveAll(CMappedList& itemList, const T& item) { itemList.remove(item); } // Remove all occurrences of item from itemList template - void ListRemove(CMappedArray& itemList, const T& item) + void ListRemoveAll(CMappedArray& itemList, const T& item) { itemList.remove(item); } @@ -968,7 +932,7 @@ namespace SharedUtil public: typedef CIntrusiveListNode Node; - CIntrusiveListNode(T* pOuterItem) : m_pOuterItem(pOuterItem), m_pPrev(NULL), m_pNext(NULL) {} + CIntrusiveListNode(T* pOuterItem) : m_pOuterItem(pOuterItem), m_pPrev(nullptr), m_pNext(nullptr) {} T* m_pOuterItem; // Item this node is inside Node* m_pPrev; @@ -992,11 +956,11 @@ namespace SharedUtil class IteratorBase; protected: - typedef CIntrusiveListNode Node; + using Node = CIntrusiveListNode; - size_t m_Size; - Node* m_pFirst; - Node* m_pLast; + std::size_t m_Size; + Node* m_pFirst; + Node* m_pLast; Node T::* m_pNodePtr; // Pointer to the CIntrusiveListNode member variable in T std::vector m_ActiveIterators; // Keep track of iterators @@ -1011,9 +975,9 @@ namespace SharedUtil public: Node* m_pNode; - IteratorBase(CIntrusiveList* pList, Node* pNode) : m_pList(pList), m_pNode(pNode) { m_pList->m_ActiveIterators.push_back(this); } - ~IteratorBase() { ListRemove(m_pList->m_ActiveIterators, this); } - T* operator*() { return m_pNode->m_pOuterItem; } + IteratorBase(CIntrusiveList* pList, Node* pNode) noexcept : m_pList(pList), m_pNode(pNode) { m_pList->m_ActiveIterators.push_back(this); } + ~IteratorBase() noexcept { ListRemoveAll(m_pList->m_ActiveIterators, this); } + T* operator*() noexcept { return m_pNode->m_pOuterItem; } virtual void NotifyRemovingNode(Node* pNode) = 0; }; @@ -1023,12 +987,12 @@ namespace SharedUtil class Iterator : public IteratorBase { public: - Iterator(CIntrusiveList* pList, Node* pNode) : IteratorBase(pList, pNode) {} - bool operator==(const Iterator& other) const { return IteratorBase::m_pNode == other.m_pNode; } - bool operator!=(const Iterator& other) const { return IteratorBase::m_pNode != other.m_pNode; } - void operator++() { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pNext; } - void operator++(int) { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pNext; } - virtual void NotifyRemovingNode(Node* pNode) + Iterator(CIntrusiveList* pList, Node* pNode) noexcept : IteratorBase(pList, pNode) {} + bool operator==(const Iterator& other) const noexcept { return IteratorBase::m_pNode == other.m_pNode; } + bool operator!=(const Iterator& other) const noexcept { return IteratorBase::m_pNode != other.m_pNode; } + void operator++() noexcept { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pNext; } + void operator++(int) noexcept { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pNext; } + virtual void NotifyRemovingNode(Node* pNode) noexcept { if (IteratorBase::m_pNode == pNode) IteratorBase::m_pNode = IteratorBase::m_pNode->m_pNext; @@ -1041,12 +1005,12 @@ namespace SharedUtil class ReverseIterator : public IteratorBase { public: - ReverseIterator(CIntrusiveList* pList, Node* pNode) : IteratorBase(pList, pNode) {} - bool operator==(const ReverseIterator& other) const { return IteratorBase::m_pNode == other.m_pNode; } - bool operator!=(const ReverseIterator& other) const { return IteratorBase::m_pNode != other.m_pNode; } - void operator++() { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pPrev; } - void operator++(int) { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pPrev; } - virtual void NotifyRemovingNode(Node* pNode) + ReverseIterator(CIntrusiveList* pList, Node* pNode) noexcept : IteratorBase(pList, pNode) {} + bool operator==(const ReverseIterator& other) const noexcept { return IteratorBase::m_pNode == other.m_pNode; } + bool operator!=(const ReverseIterator& other) const noexcept { return IteratorBase::m_pNode != other.m_pNode; } + void operator++() noexcept { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pPrev; } + void operator++(int) noexcept { IteratorBase::m_pNode = IteratorBase::m_pNode->m_pPrev; } + virtual void NotifyRemovingNode(Node* pNode) noexcept { if (IteratorBase::m_pNode == pNode) IteratorBase::m_pNode = IteratorBase::m_pNode->m_pPrev; @@ -1056,19 +1020,19 @@ namespace SharedUtil // // Constructor // - CIntrusiveList(Node T::*pNodePtr) : m_pNodePtr(pNodePtr) + CIntrusiveList(Node T::*pNodePtr) noexcept : m_pNodePtr(pNodePtr) { assert(m_pNodePtr); // This must be set upon construction m_Size = 0; - m_pFirst = NULL; - m_pLast = NULL; + m_pFirst = nullptr; + m_pLast = nullptr; } - ~CIntrusiveList() { assert(m_ActiveIterators.empty()); } + ~CIntrusiveList() noexcept { assert(m_ActiveIterators.empty()); } - bool empty() const { return m_Size == 0; } + bool empty() const noexcept { return m_Size == 0; } - size_t size() const { return m_Size; } + size_t size() const noexcept { return m_Size; } // // Check if list contains item @@ -1100,14 +1064,14 @@ namespace SharedUtil { // Only item in list assert(!pNode->m_pPrev && !pNode->m_pNext); - m_pFirst = NULL; - m_pLast = NULL; + m_pFirst = nullptr; + m_pLast = nullptr; } else { // First item in list assert(!pNode->m_pPrev && pNode->m_pNext && pNode->m_pNext->m_pPrev == pNode); - pNode->m_pNext->m_pPrev = NULL; + pNode->m_pNext->m_pPrev = nullptr; m_pFirst = pNode->m_pNext; } } @@ -1115,7 +1079,7 @@ namespace SharedUtil { // Last item in list assert(pNode->m_pPrev && !pNode->m_pNext && pNode->m_pPrev->m_pNext == pNode); - pNode->m_pPrev->m_pNext = NULL; + pNode->m_pPrev->m_pNext = nullptr; m_pLast = pNode->m_pPrev; } else @@ -1125,8 +1089,8 @@ namespace SharedUtil pNode->m_pPrev->m_pNext = pNode->m_pNext; pNode->m_pNext->m_pPrev = pNode->m_pPrev; } - pNode->m_pNext = NULL; - pNode->m_pPrev = NULL; + pNode->m_pNext = nullptr; + pNode->m_pPrev = nullptr; m_Size--; } @@ -1174,19 +1138,17 @@ namespace SharedUtil m_Size++; } - Iterator begin() { return Iterator(this, m_pFirst); } + Iterator begin() noexcept { return Iterator(this, m_pFirst); } + Iterator end() noexcept { return Iterator(this, nullptr); } - Iterator end() { return Iterator(this, NULL); } - - ReverseIterator rbegin() { return ReverseIterator(this, m_pLast); } - - ReverseIterator rend() { return ReverseIterator(this, NULL); } + ReverseIterator rbegin() noexcept { return ReverseIterator(this, m_pLast); } + ReverseIterator rend() noexcept { return ReverseIterator(this, nullptr); } // Allow use of std iterator names - typedef Iterator iterator; - typedef Iterator const_iterator; // TODO - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; // TODO + using iterator = Iterator; + using const_iterator = Iterator; // TODO + using reverse_iterator = ReverseIterator; + using const_reverse_iterator = ReverseIterator; // TODO }; /////////////////////////////////////////////////////////////// @@ -1200,14 +1162,14 @@ namespace SharedUtil class CIntrusiveListExt : public CIntrusiveList { public: - CIntrusiveListExt() : CIntrusiveList(member_ptr) {} + CIntrusiveListExt() noexcept : CIntrusiveList(member_ptr) {} }; // // tolower / toupper // Implemented here so it can be inlined. // - static const char ms_ucTolowerTab[256] = { + static constexpr const char ms_ucTolowerTab[256] = { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27', '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', @@ -1222,7 +1184,7 @@ namespace SharedUtil '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff'}; - static const char ms_ucToupperTab[256] = { + static constexpr const char ms_ucToupperTab[256] = { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27', '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', @@ -1237,15 +1199,16 @@ namespace SharedUtil '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff'}; + template - inline T tolower(T c) + constexpr T tolower(T c) noexcept { - return static_cast(ms_ucTolowerTab[static_cast(c)]); + return static_cast(ms_ucTolowerTab[static_cast(c)]); } template - inline T toupper(T c) + constexpr T toupper(T c) noexcept { - return static_cast(ms_ucToupperTab[static_cast(c)]); + return static_cast(ms_ucToupperTab[static_cast(c)]); } // @@ -1264,12 +1227,12 @@ namespace SharedUtil const char* szName; }; - CEnumInfo(const SString& strTypeName, const SEnumItem* pItemList, uint uiAmount, eDummy defaultValue, const SString& strDefaultName) + CEnumInfo(const SString& strTypeName, const SEnumItem* pItemList, std::uint32_t uiAmount, eDummy defaultValue, const SString& strDefaultName) { m_strTypeName = strTypeName; m_strDefaultName = strDefaultName; m_DefaultValue = defaultValue; - for (uint i = 0; i < uiAmount; i++) + for (std::uint32_t i = 0; i < uiAmount; i++) { const SEnumItem& item = pItemList[i]; m_ValueMap[item.szName] = (eDummy)item.iValue; @@ -1350,7 +1313,7 @@ namespace SharedUtil // Written by Jack Handy - jakkhandy@hotmail.com assert(wild && string); - const char *cp = NULL, *mp = NULL; + const char *cp = nullptr, *mp = nullptr; while ((*string) && (*wild != '*')) { @@ -1400,7 +1363,7 @@ namespace SharedUtil // Written by Jack Handy - jakkhandy@hotmail.com assert(wild && string); - const char *cp = NULL, *mp = NULL; + const char *cp = nullptr, *mp = nullptr; while ((*string) && (*wild != '*')) { @@ -1496,7 +1459,7 @@ namespace SharedUtil { std::vector partList; strFilterDesc.Split(",", partList); - for (uint i = 0; i < partList.size(); i++) + for (std::uint32_t i = 0; i < partList.size(); i++) { const SString& part = partList[i]; char cType = part.Left(1)[0]; @@ -1540,7 +1503,7 @@ namespace SharedUtil cDefaultType = cType; } - std::map idMap; + std::map idMap; char cDefaultType; }; @@ -1559,10 +1522,10 @@ namespace SharedUtil static CCriticalSection ms_CS; protected: - virtual ~CRefCountable() {} + virtual ~CRefCountable() noexcept {} public: - CRefCountable() : m_iRefCount(1), m_pCS(&ms_CS) {} + CRefCountable() noexcept : m_iRefCount(1), m_pCS(&ms_CS) {} void AddRef() { @@ -1590,16 +1553,16 @@ namespace SharedUtil // Replacement for e.g. int var[100] // Checks bounds // - template + template struct SFixedArray { - T& operator[](uint uiIndex) + T& operator[](std::uint32_t uiIndex) { assert(uiIndex < SIZE); return data[uiIndex]; } - const T& operator[](uint uiIndex) const + const T& operator[](std::uint32_t uiIndex) const { assert(uiIndex < SIZE); return data[uiIndex]; @@ -1612,10 +1575,10 @@ namespace SharedUtil // Fixed size array with a constructer // so it can be used with the IMPLEMENT_FIXED_ARRAY macro // - template + template struct SFixedArrayInit : SFixedArray { - SFixedArrayInit(const T* pInitData, uint uiInitCount) + SFixedArrayInit(const T* pInitData, std::uint32_t uiInitCount) { dassert(SIZE == uiInitCount); memcpy(SFixedArray::data, pInitData, sizeof(SFixedArray::data)); @@ -1632,17 +1595,17 @@ namespace SharedUtil class CRanges { public: - void SetRange(uint uiStart, uint uiLength); - void UnsetRange(uint uiStart, uint uiLength); - bool IsRangeSet(uint uiStart, uint uiLength); // Returns true if any part of the range already exists in the map + void SetRange(std::uint32_t uiStart, std::uint32_t uiLength); + void UnsetRange(std::uint32_t uiStart, std::uint32_t uiLength); + bool IsRangeSet(std::uint32_t uiStart, std::uint32_t uiLength); // Returns true if any part of the range already exists in the map protected: - typedef std::map::iterator IterType; + using IterType = std::map::iterator; - void RemoveObscuredRanges(uint uiStart, uint uiLast); - bool GetRangeOverlappingPoint(uint uiPoint, IterType& result); + void RemoveObscuredRanges(std::uint32_t uiStart, std::uint32_t uiLast); + bool GetRangeOverlappingPoint(std::uint32_t uiPoint, IterType& result); - std::map m_StartLastMap; + std::map m_StartLastMap; }; // @@ -1654,14 +1617,15 @@ namespace SharedUtil private: T* pData; // Target - virtual ~CRefedPointer() { SAFE_DELETE(pData); } + virtual ~CRefedPointer() noexcept { SAFE_DELETE(pData); } CRefedPointer(const CRefedPointer& other); CRefedPointer& operator=(const CRefedPointer& other); public: - CRefedPointer() { pData = new T(); } + CRefedPointer() noexcept { pData = new T(); } - T* GetData() { return pData; } + T* GetData() noexcept { return pData; } + const T* GetData() const noexcept { return pData; } }; // @@ -1674,37 +1638,36 @@ namespace SharedUtil CRefedPointer* pPointer; public: - CAutoRefedPointer() { pPointer = new CRefedPointer(); } + CAutoRefedPointer() noexcept { pPointer = new CRefedPointer(); } - CAutoRefedPointer(const CAutoRefedPointer& other) + CAutoRefedPointer(const CAutoRefedPointer& other) noexcept { pPointer = other.pPointer; pPointer->AddRef(); } - ~CAutoRefedPointer() { pPointer->Release(); } + ~CAutoRefedPointer() noexcept { pPointer->Release(); } CAutoRefedPointer& operator=(const CAutoRefedPointer& other) { // Assignment operator - if (this != &other) // Avoid self assignment - { - CRefedPointer* pOldPointer = pPointer; + if (this == &other) // Avoid self assignment + return *this; - // Copy the data and reference pointer - // and increment the reference count - pPointer = other.pPointer; - pPointer->AddRef(); + CRefedPointer* pOldPointer = pPointer; - // Decrement the old reference count - pOldPointer->Release(); - } + // Copy the data and reference pointer + // and increment the reference count + pPointer = other.pPointer; + pPointer->AddRef(); + + // Decrement the old reference count + pOldPointer->Release(); return *this; } - T* operator->() { return pPointer->GetData(); } - - const T* operator->() const { return pPointer->GetData(); } + T* operator->() noexcept { return pPointer->GetData(); } + const T* operator->() const noexcept { return pPointer->GetData(); } }; }; // namespace SharedUtil @@ -1713,5 +1676,5 @@ using namespace SharedUtil; // // For checking MTA library module versions // -typedef void(FUNC_GetMtaVersion)(char* pBuffer, uint uiMaxSize); -MTAEXPORT void GetLibMtaVersion(char* pBuffer, uint uiMaxSize); +using FUNC_GetMtaVersion = void(*)(char* pBuffer, std::uint32_t uiMaxSize); +MTAEXPORT void GetLibMtaVersion(char* pBuffer, std::uint32_t uiMaxSize); diff --git a/Shared/sdk/SharedUtil.Misc.hpp b/Shared/sdk/SharedUtil.Misc.hpp index 5697da49f4..131b4f3bad 100644 --- a/Shared/sdk/SharedUtil.Misc.hpp +++ b/Shared/sdk/SharedUtil.Misc.hpp @@ -16,7 +16,13 @@ #include "UTF8Detect.hpp" #include "CDuplicateLineFilter.h" #include "version.h" -#ifdef WIN32 +#ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif #include #include #include @@ -41,7 +47,7 @@ #endif CCriticalSection CRefCountable::ms_CS; -std::map ms_ReportAmountMap; +std::map ms_ReportAmountMap; SString ms_strProductRegistryPath; SString ms_strProductCommonDataDir; SString ms_strProductVersion; @@ -49,9 +55,9 @@ SString ms_strProductVersion; struct SReportLine { SString strText; - uint uiId; + std::uint32_t uiId; void operator+=(const char* szAppend) { strText += szAppend; } - bool operator==(const SReportLine& other) const { return strText == other.strText && uiId == other.uiId; } + bool operator==(const SReportLine& other) const noexcept { return strText == other.strText && uiId == other.uiId; } }; CDuplicateLineFilter ms_ReportLineFilter; @@ -87,30 +93,32 @@ SString SharedUtil::GetParentProcessPathFilename(int pid) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32W pe = {sizeof(PROCESSENTRY32W)}; - if (Process32FirstW(hSnapshot, &pe)) + if (!Process32FirstW(hSnapshot, &pe)) { - do - { - if (pe.th32ProcessID == pid) - { - HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe.th32ParentProcessID); - if (hProcess) - { - WCHAR szModuleName[MAX_PATH * 2] = {0}; - GetModuleFileNameExW(hProcess, nullptr, szModuleName, NUMELMS(szModuleName)); - CloseHandle(hProcess); - SString strModuleName = ToUTF8(szModuleName); - if (FileExists(strModuleName)) - { - CloseHandle(hSnapshot); - if (IsShortPathName(strModuleName)) - return GetSystemLongPathName(strModuleName); - return strModuleName; - } - } - } - } while (Process32NextW(hSnapshot, &pe)); + CloseHandle(hSnapshot); + return ""; } + do + { + if (pe.th32ProcessID != pid) + continue; + + HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe.th32ParentProcessID); + if (!hProcess) + continue; + + WCHAR szModuleName[MAX_PATH * 2] = {0}; + GetModuleFileNameExW(hProcess, nullptr, szModuleName, NUMELMS(szModuleName)); + CloseHandle(hProcess); + SString strModuleName = ToUTF8(szModuleName); + if (!FileExists(strModuleName)) + continue; + + CloseHandle(hSnapshot); + if (IsShortPathName(strModuleName)) + return GetSystemLongPathName(strModuleName); + return strModuleName; + } while (Process32NextW(hSnapshot, &pe)); CloseHandle(hSnapshot); return ""; } @@ -122,24 +130,24 @@ SString SharedUtil::GetParentProcessPathFilename(int pid) SString SharedUtil::GetMTASABaseDir() { static SString strInstallRoot; - if (strInstallRoot.empty()) + if (!strInstallRoot.empty()) + return strInstallRoot; + + if (IsGTAProcess()) { - if (IsGTAProcess()) - { - // Try to get base dir from parent process - strInstallRoot = ExtractPath(GetParentProcessPathFilename(GetCurrentProcessId())); - } - if (strInstallRoot.empty()) - { - strInstallRoot = GetRegistryValue("", "Last Run Location"); - if (strInstallRoot.empty()) - { - MessageBoxUTF8(0, _("Multi Theft Auto has not been installed properly, please reinstall."), _("Error") + _E("U01"), - MB_OK | MB_ICONERROR | MB_TOPMOST); - TerminateProcess(GetCurrentProcess(), 9); - } - } + // Try to get base dir from parent process + strInstallRoot = ExtractPath(GetParentProcessPathFilename(GetCurrentProcessId())); } + if (!strInstallRoot.empty()) + return strInstallRoot; + + strInstallRoot = GetRegistryValue("", "Last Run Location"); + if (!strInstallRoot.empty()) + return strInstallRoot; + + MessageBoxUTF8(0, _("Multi Theft Auto has not been installed properly, please reinstall."), _("Error") + _E("U01"), + MB_OK | MB_ICONERROR | MB_TOPMOST); + TerminateProcess(GetCurrentProcess(), 9); return strInstallRoot; } @@ -170,17 +178,17 @@ static void WriteRegistryStringValue(HKEY hkRoot, const char* szSubKey, const ch WString wstrSubKey = FromUTF8(szSubKey); WString wstrValue = FromUTF8(szValue); WString wstrBuffer = FromUTF8(strBuffer); - RegCreateKeyExW(hkRoot, wstrSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkTemp, NULL); - if (hkTemp) + RegCreateKeyExW(hkRoot, wstrSubKey, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nullptr, &hkTemp, nullptr); + if (!hkTemp) + return; + + RegSetValueExW(hkTemp, wstrValue, 0, REG_SZ, (LPBYTE)wstrBuffer.c_str(), (wstrBuffer.length() + 1) * sizeof(wchar_t)); + if (bFlush) { - RegSetValueExW(hkTemp, wstrValue, NULL, REG_SZ, (LPBYTE)wstrBuffer.c_str(), (wstrBuffer.length() + 1) * sizeof(wchar_t)); - if (bFlush) - { - // Very slow. Only needed if there is a risk of BSOD soon afterwards. - RegFlushKey(hkTemp); - } - RegCloseKey(hkTemp); + // Very slow. Only needed if there is a risk of BSOD soon afterwards. + RegFlushKey(hkTemp); } + RegCloseKey(hkTemp); } // @@ -192,24 +200,28 @@ static SString ReadRegistryStringValue(HKEY hkRoot, const char* szSubKey, const SString strOutResult = ""; bool bResult = false; - HKEY hkTemp = NULL; + HKEY hkTemp = nullptr; WString wstrSubKey = FromUTF8(szSubKey); WString wstrValue = FromUTF8(szValue); - if (RegOpenKeyExW(hkRoot, wstrSubKey, 0, KEY_READ, &hkTemp) == ERROR_SUCCESS) + if (RegOpenKeyExW(hkRoot, wstrSubKey, 0, KEY_READ, &hkTemp) != ERROR_SUCCESS) { + if (iResult) + *iResult = bResult; + return strOutResult; + } + + DWORD dwBufferSize; + if (RegQueryValueExW(hkTemp, wstrValue, nullptr, nullptr, nullptr, &dwBufferSize) == ERROR_SUCCESS) { - DWORD dwBufferSize; - if (RegQueryValueExW(hkTemp, wstrValue, NULL, NULL, NULL, &dwBufferSize) == ERROR_SUCCESS) + CScopeAlloc szBuffer(dwBufferSize + sizeof(wchar_t)); + if (RegQueryValueExW(hkTemp, wstrValue, nullptr, nullptr, (LPBYTE)(wchar_t*)szBuffer, &dwBufferSize) == ERROR_SUCCESS) { - CScopeAlloc szBuffer(dwBufferSize + sizeof(wchar_t)); - if (RegQueryValueExW(hkTemp, wstrValue, NULL, NULL, (LPBYTE)(wchar_t*)szBuffer, &dwBufferSize) == ERROR_SUCCESS) - { - szBuffer[dwBufferSize / sizeof(wchar_t)] = 0; - strOutResult = ToUTF8((wchar_t*)szBuffer); - bResult = true; - } + szBuffer[dwBufferSize / sizeof(wchar_t)] = 0; + strOutResult = ToUTF8((wchar_t*)szBuffer); + bResult = true; } - RegCloseKey(hkTemp); } + RegCloseKey(hkTemp); + if (iResult) *iResult = bResult; return strOutResult; @@ -234,9 +246,9 @@ SString SharedUtil::GetMajorVersionString() // // GetSystemRegistryValue // -SString SharedUtil::GetSystemRegistryValue(uint hKey, const SString& strPath, const SString& strName) +SString SharedUtil::GetSystemRegistryValue(std::uint32_t hKey, const SString& strPath, const SString& strName) { - return ReadRegistryStringValue((HKEY)hKey, strPath, strName, NULL); + return ReadRegistryStringValue((HKEY)hKey, strPath, strName, nullptr); } // @@ -262,7 +274,7 @@ void SharedUtil::SetRegistryValue(const SString& strPath, const SString& strName SString SharedUtil::GetRegistryValue(const SString& strPath, const SString& strName) { - return ReadRegistryStringValue(HKEY_LOCAL_MACHINE, MakeVersionRegistryPath(GetMajorVersionString(), strPath), strName, NULL); + return ReadRegistryStringValue(HKEY_LOCAL_MACHINE, MakeVersionRegistryPath(GetMajorVersionString(), strPath), strName, nullptr); } bool SharedUtil::RemoveRegistryKey(const SString& strPath) @@ -278,7 +290,7 @@ void SharedUtil::SetVersionRegistryValue(const SString& strVersion, const SStrin SString SharedUtil::GetVersionRegistryValue(const SString& strVersion, const SString& strPath, const SString& strName) { - return ReadRegistryStringValue(HKEY_LOCAL_MACHINE, MakeVersionRegistryPath(strVersion, strPath), strName, NULL); + return ReadRegistryStringValue(HKEY_LOCAL_MACHINE, MakeVersionRegistryPath(strVersion, strPath), strName, nullptr); } // Get/set registry values for all versions (common) @@ -289,7 +301,7 @@ void SharedUtil::SetCommonRegistryValue(const SString& strPath, const SString& s SString SharedUtil::GetCommonRegistryValue(const SString& strPath, const SString& strName) { - return ReadRegistryStringValue(HKEY_LOCAL_MACHINE, MakeVersionRegistryPath("Common", strPath), strName, NULL); + return ReadRegistryStringValue(HKEY_LOCAL_MACHINE, MakeVersionRegistryPath("Common", strPath), strName, nullptr); } // @@ -326,20 +338,20 @@ bool SharedUtil::GetOnRestartCommand(SString& strOperation, SString& strFile, SS std::vector vecParts; strOnRestartCommand.Split("\t", vecParts); - if (vecParts.size() > 5 && vecParts[0].length()) + if (vecParts.size() <= 5 || vecParts[0].empty()) + return false; + + SString strVersion("%d.%d.%d-%d.%05d", MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, MTASA_VERSION_BUILD); + if (vecParts[5] == strVersion) { - SString strVersion("%d.%d.%d-%d.%05d", MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, MTASA_VERSION_BUILD); - if (vecParts[5] == strVersion) - { - strOperation = vecParts[0]; - strFile = vecParts[1]; - strParameters = vecParts[2]; - strDirectory = vecParts[3]; - strShowCmd = vecParts[4]; - return true; - } - AddReportLog(4000, SString("OnRestartCommand disregarded due to version change %s -> %s", vecParts[5].c_str(), strVersion.c_str())); + strOperation = vecParts[0]; + strFile = vecParts[1]; + strParameters = vecParts[2]; + strDirectory = vecParts[3]; + strShowCmd = vecParts[4]; + return true; } + AddReportLog(4000, SString("OnRestartCommand disregarded due to version change %s -> %s", vecParts[5].c_str(), strVersion.c_str())); return false; } @@ -368,7 +380,7 @@ SString SharedUtil::GetPostUpdateConnect() time_t timeThen = (time_t)std::atoll(argMap.Get("time")); // Expire after 5 mins - double seconds = difftime(time(NULL), timeThen); + double seconds = difftime(time(nullptr), timeThen); if ((seconds < 0 || seconds > 60 * 5) && timeThen != 0) strHost = ""; @@ -497,11 +509,11 @@ static bool bWatchDogWasUncleanStopValue = false; bool SharedUtil::WatchDogWasUncleanStop() { - if (!bWatchDogWasUncleanStopCached) - { - bWatchDogWasUncleanStopValue = GetApplicationSettingInt("watchdog", "uncleanstop") != 0; - bWatchDogWasUncleanStopCached = true; - } + if (bWatchDogWasUncleanStopCached) + return bWatchDogWasUncleanStopValue; + + bWatchDogWasUncleanStopValue = GetApplicationSettingInt("watchdog", "uncleanstop") != 0; + bWatchDogWasUncleanStopCached = true; return bWatchDogWasUncleanStopValue; } @@ -520,11 +532,11 @@ static bool bWatchDogWasLastRunCrashValue = false; bool SharedUtil::WatchDogWasLastRunCrash() { - if (!bWatchDogWasLastRunCrashCached) - { - bWatchDogWasLastRunCrashValue = GetApplicationSettingInt("watchdog", "lastruncrash") != 0; - bWatchDogWasLastRunCrashCached = true; - } + if (bWatchDogWasLastRunCrashCached) + return bWatchDogWasLastRunCrashValue; + + bWatchDogWasLastRunCrashValue = GetApplicationSettingInt("watchdog", "lastruncrash") != 0; + bWatchDogWasLastRunCrashCached = true; return bWatchDogWasLastRunCrashValue; } @@ -579,52 +591,51 @@ void SharedUtil::SetProductVersion(const SString& strVersion) const SString& SharedUtil::GetProductVersion() { if (ms_strProductVersion.empty()) - ms_strProductVersion = - SString("%d.%d.%d-%d.%05d", MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, MTASA_VERSION_BUILD); + ms_strProductVersion = SString("%d.%d.%d-%d.%05d", MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, MTASA_VERSION_BUILD); return ms_strProductVersion; } void SharedUtil::SetClipboardText(const SString& strText) { // If we got something to copy - if (!strText.empty()) - { - // Convert it to Unicode - WString strUTF = MbUTF8ToUTF16(strText); + if (strText.empty()) + return; + + // Convert it to Unicode + WString strUTF = MbUTF8ToUTF16(strText); - // Open and empty the clipboard - OpenClipboard(NULL); - EmptyClipboard(); + // Open and empty the clipboard + OpenClipboard(nullptr); + EmptyClipboard(); - // Allocate the clipboard buffer and copy the data - HGLOBAL hBuf = GlobalAlloc(GMEM_DDESHARE, strUTF.length() * sizeof(wchar_t) + sizeof(wchar_t)); - wchar_t* buf = reinterpret_cast(GlobalLock(hBuf)); - wcscpy(buf, strUTF); - GlobalUnlock(hBuf); + // Allocate the clipboard buffer and copy the data + HGLOBAL hBuf = GlobalAlloc(GMEM_DDESHARE, strUTF.length() * sizeof(wchar_t) + sizeof(wchar_t)); + wchar_t* buf = reinterpret_cast(GlobalLock(hBuf)); + wcscpy(buf, strUTF); + GlobalUnlock(hBuf); - // Copy the data into the clipboard - SetClipboardData(CF_UNICODETEXT, hBuf); + // Copy the data into the clipboard + SetClipboardData(CF_UNICODETEXT, hBuf); - // Close the clipboard - CloseClipboard(); - } + // Close the clipboard + CloseClipboard(); } SString SharedUtil::GetClipboardText() { SString data; - if (OpenClipboard(NULL)) - { - // Get the clipboard's data - HANDLE clipboardData = GetClipboardData(CF_UNICODETEXT); - void* lockedData = GlobalLock(clipboardData); - if (lockedData) - data = UTF16ToMbUTF8(static_cast(lockedData)); - - GlobalUnlock(clipboardData); - CloseClipboard(); - } + if (!OpenClipboard(nullptr)) + return data; + + // Get the clipboard's data + HANDLE clipboardData = GetClipboardData(CF_UNICODETEXT); + void* lockedData = GlobalLock(clipboardData); + if (lockedData) + data = UTF16ToMbUTF8(static_cast(lockedData)); + + GlobalUnlock(clipboardData); + CloseClipboard(); return data; } @@ -686,19 +697,19 @@ bool SharedUtil::ProcessPendingBrowseToSolution() if (!strMessageBoxMessage.empty()) strMessageBoxMessage += "\n\n\n"; strMessageBoxMessage += _("Do you want to see some on-line help about this problem ?"); - if (IDYES != MessageBoxUTF8(NULL, strMessageBoxMessage, strTitle, MB_YESNO | MB_TOPMOST | (iFlags & ICON_MASK_VALUE))) + if (IDYES != MessageBoxUTF8(nullptr, strMessageBoxMessage, strTitle, MB_YESNO | MB_TOPMOST | (iFlags & ICON_MASK_VALUE))) return false; } else { if (!strMessageBoxMessage.empty()) - MessageBoxUTF8(NULL, strMessageBoxMessage, strTitle, MB_OK | MB_TOPMOST | (iFlags & ICON_MASK_VALUE)); + MessageBoxUTF8(nullptr, strMessageBoxMessage, strTitle, MB_OK | MB_TOPMOST | (iFlags & ICON_MASK_VALUE)); if (iFlags & SHOW_MESSAGE_ONLY) return true; } MessageBoxUTF8( - NULL, + nullptr, _("Your browser will now display a web page with some help infomation.\n\n(If the page fails to load, paste (CTRL-V) the URL into your web browser)"), "MTA: San Andreas", MB_OK | MB_ICONINFORMATION | MB_TOPMOST); @@ -749,11 +760,11 @@ static SString GetReportLogHeaderText() return strResult.TrimEnd(" ") + "]"; } -void SharedUtil::AddReportLog(uint uiId, const SString& strText, uint uiAmountLimit) +void SharedUtil::AddReportLog(std::uint32_t uiId, const SString& strText, std::uint32_t uiAmountLimit) { if (uiAmountLimit) { - uint& uiAmount = MapGet(ms_ReportAmountMap, uiId); + std::uint32_t& uiAmount = MapGet(ms_ReportAmountMap, uiId); if (uiAmount++ >= uiAmountLimit) return; } @@ -764,7 +775,7 @@ void SharedUtil::AddReportLog(uint uiId, const SString& strText, uint uiAmountLi while (ms_ReportLineFilter.PopOutputLine(line)) { const SString& strText = line.strText; - uint uiId = line.uiId; + std::uint32_t uiId = line.uiId; SString strPathFilename = PathJoin(GetMTADataPath(), "report.log"); MakeSureDirExists(strPathFilename); @@ -780,12 +791,12 @@ void SharedUtil::AddReportLog(uint uiId, const SString& strText, uint uiAmountLi // Track results of new features by avoiding heap memory allocations // Avoid using this function if you have plenty of memory available // -void SharedUtil::AddExceptionReportLog(uint uiId, const char* szExceptionName, const char* szExceptionText) +void SharedUtil::AddExceptionReportLog(std::uint32_t uiId, const char* szExceptionName, const char* szExceptionText) { - constexpr size_t BOILERPLATE_SIZE = 46; - constexpr size_t MAX_EXCEPTION_NAME_SIZE = 64; - constexpr size_t MAX_EXCEPTION_TEXT_SIZE = 256; - static char szOutput[BOILERPLATE_SIZE + MAX_EXCEPTION_NAME_SIZE + MAX_EXCEPTION_TEXT_SIZE] = {0}; + constexpr std::size_t BOILERPLATE_SIZE = 46; + constexpr std::size_t MAX_EXCEPTION_NAME_SIZE = 64; + constexpr std::size_t MAX_EXCEPTION_TEXT_SIZE = 256; + static char szOutput[BOILERPLATE_SIZE + MAX_EXCEPTION_NAME_SIZE + MAX_EXCEPTION_TEXT_SIZE] = {0}; SYSTEMTIME s = {0}; GetSystemTime(&s); @@ -807,6 +818,7 @@ void SharedUtil::AddExceptionReportLog(uint uiId, const char* szExceptionName, c { // At the time of writing this function, it is only called from other 'try-catch' blocks // so we can assume we literally ran out of all available memory here and ignore the exception + // 🤔 } } @@ -814,7 +826,7 @@ void SharedUtil::SetReportLogContents(const SString& strText) { SString strPathFilename = PathJoin(GetMTADataPath(), "report.log"); MakeSureDirExists(strPathFilename); - FileSave(strPathFilename, strText.length() ? &strText.at(0) : NULL, strText.length()); + FileSave(strPathFilename, strText.length() ? &strText.at(0) : nullptr, strText.length()); } SString SharedUtil::GetReportLogContents() @@ -830,36 +842,35 @@ SString SharedUtil::GetReportLogContents() SString SharedUtil::GetReportLogProcessTag() { static SString strResult; - if (strResult.empty()) + if (!strResult.empty()) + return strResult; + + int pid = GetCurrentProcessId(); + if (!IsGTAProcess()) { - int pid = GetCurrentProcessId(); - if (!IsGTAProcess()) - { - // Use pid only for launcher - strResult = SString("%05d", pid); - } - else + // Use pid only for launcher + strResult = SString("%05d", pid); + return strResult; + } + + // Use pid & parent pid for game + int parentPid = 0; + HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + PROCESSENTRY32W pe = {0}; + pe.dwSize = sizeof(PROCESSENTRY32W); + if (Process32FirstW(h, &pe)) + { + do { - // Use pid & parent pid for game - int parentPid = 0; - HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - PROCESSENTRY32W pe = {0}; - pe.dwSize = sizeof(PROCESSENTRY32W); - if (Process32FirstW(h, &pe)) + if (pe.th32ProcessID == pid) { - do - { - if (pe.th32ProcessID == pid) - { - parentPid = pe.th32ParentProcessID; - break; - } - } while (Process32NextW(h, &pe)); + parentPid = pe.th32ParentProcessID; + break; } - CloseHandle(h); - strResult = SString("%05d-%05d", parentPid, pid); - } + } while (Process32NextW(h, &pe)); } + CloseHandle(h); + strResult = SString("%05d-%05d", parentPid, pid); return strResult; } @@ -871,8 +882,8 @@ void WriteEvent(const char* szType, const SString& strText) { std::vector lineList; strText.Split("\n", lineList); - for (uint i = 0; i < lineList.size(); i++) - WriteEvent(szType, lineList[i]); + for (const auto& value : lineList) + WriteEvent(szType, value); return; } SString strPathFilename = CalcMTASAPath(PathJoin("mta", "logs", "logfile.txt")); @@ -917,19 +928,19 @@ void SharedUtil::CycleEventLog() // Get Windows error message text from a last error code. // /////////////////////////////////////////////////////////////////////////// -SString SharedUtil::GetSystemErrorMessage(uint uiError, bool bRemoveNewlines, bool bPrependCode) +SString SharedUtil::GetSystemErrorMessage(std::uint32_t uiError, bool bRemoveNewlines, bool bPrependCode) { SString strResult; - LPWSTR szErrorText = NULL; - FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, uiError, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&szErrorText, 0, NULL); + LPWSTR szErrorText = nullptr; + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, uiError, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&szErrorText, 0, nullptr); if (szErrorText) { strResult = UTF16ToMbUTF8(szErrorText); LocalFree(szErrorText); - szErrorText = NULL; + szErrorText = nullptr; } if (bRemoveNewlines) @@ -977,34 +988,31 @@ static bool MyShellExecute(bool bBlocking, const SString& strAction, const SStri strFile = "rundll32.exe"; } - if (bBlocking) + if (!bBlocking) { - WString wstrAction = FromUTF8(strAction); - WString wstrFile = FromUTF8(strFile); - WString wstrParameters = FromUTF8(strParameters); - WString wstrDirectory = FromUTF8(strDirectory); - SHELLEXECUTEINFOW info; - memset(&info, 0, sizeof(info)); - info.cbSize = sizeof(info); - info.fMask = SEE_MASK_NOCLOSEPROCESS; - info.lpVerb = wstrAction; - info.lpFile = wstrFile; - info.lpParameters = wstrParameters; - info.lpDirectory = wstrDirectory; - info.nShow = nShowCmd; - bool bResult = ShellExecuteExW(&info) != FALSE; - if (info.hProcess) - { - WaitForSingleObject(info.hProcess, INFINITE); - CloseHandle(info.hProcess); - } - return bResult; + int iResult = (int)ShellExecute(nullptr, strAction, strFile, strParameters, strDirectory, nShowCmd); + return iResult > 32; } - else + WString wstrAction = FromUTF8(strAction); + WString wstrFile = FromUTF8(strFile); + WString wstrParameters = FromUTF8(strParameters); + WString wstrDirectory = FromUTF8(strDirectory); + SHELLEXECUTEINFOW info; + memset(&info, 0, sizeof(info)); + info.cbSize = sizeof(info); + info.fMask = SEE_MASK_NOCLOSEPROCESS; + info.lpVerb = wstrAction; + info.lpFile = wstrFile; + info.lpParameters = wstrParameters; + info.lpDirectory = wstrDirectory; + info.nShow = nShowCmd; + bool bResult = ShellExecuteExW(&info) != FALSE; + if (info.hProcess) { - int iResult = (int)ShellExecute(NULL, strAction, strFile, strParameters, strDirectory, nShowCmd); - return iResult > 32; + WaitForSingleObject(info.hProcess, INFINITE); + CloseHandle(info.hProcess); } + return bResult; } /////////////////////////////////////////////////////////////// @@ -1034,7 +1042,7 @@ bool SharedUtil::ShellExecuteNonBlocking(const SString& strAction, const SString #endif // MTA_CLIENT -#ifdef WIN32 +#ifdef _WIN32 #define _WIN32_WINNT_WIN8 0x0602 /////////////////////////////////////////////////////////////////////////// // @@ -1079,23 +1087,23 @@ bool SharedUtil::IsWindows8OrGreater() } #endif // WIN32 -static uchar ToHexChar(uchar c) +static std::uint8_t ToHexChar(std::uint8_t c) noexcept { return c > 9 ? c - 10 + 'A' : c + '0'; } -static uchar FromHexChar(uchar c) +static std::uint8_t FromHexChar(std::uint8_t c) noexcept { return c > '9' ? c - 'A' + 10 : c - '0'; } -SString SharedUtil::EscapeString(const SString& strText, const SString& strDisallowedChars, char cSpecialChar, uchar ucLowerLimit, uchar ucUpperLimit) +SString SharedUtil::EscapeString(const SString& strText, const SString& strDisallowedChars, char cSpecialChar, std::uint8_t ucLowerLimit, std::uint8_t ucUpperLimit) { // Replace each disallowed char with #FF SString strResult; - for (uint i = 0; i < strText.length(); i++) + for (std::uint32_t i = 0; i < strText.length(); i++) { - uchar c = strText[i]; + std::uint8_t c = strText[i]; if (strDisallowedChars.find(c) == std::string::npos && c != cSpecialChar && c >= ucLowerLimit && c <= ucUpperLimit) strResult += c; else @@ -1112,13 +1120,13 @@ SString SharedUtil::UnescapeString(const SString& strText, char cSpecialChar) { SString strResult; // Replace #FF with char - for (uint i = 0; i < strText.length(); i++) + for (std::size_t i = 0; i < strText.length(); i++) { - uchar c = strText[i]; + std::uint8_t c = strText[i]; if (c == cSpecialChar && i < strText.length() - 2) { - uchar c0 = FromHexChar(strText[++i]); - uchar c1 = FromHexChar(strText[++i]); + std::uint8_t c0 = FromHexChar(strText[++i]); + std::uint8_t c1 = FromHexChar(strText[++i]); c = (c0 << 4) | c1; } strResult += c; @@ -1138,7 +1146,7 @@ SString SharedUtil::EscapeURLArgument(const SString& strArg) // // Cross platform critical section // -#ifdef WIN32 +#ifdef _WIN32 SharedUtil::CCriticalSection::CCriticalSection() { @@ -1170,7 +1178,7 @@ void SharedUtil::CCriticalSection::Unlock() SharedUtil::CCriticalSection::CCriticalSection() { m_pCriticalSection = new pthread_mutex_t; - pthread_mutex_init((pthread_mutex_t*)m_pCriticalSection, NULL); + pthread_mutex_init((pthread_mutex_t*)m_pCriticalSection, nullptr); } SharedUtil::CCriticalSection::~CCriticalSection() @@ -1199,7 +1207,7 @@ void SharedUtil::RandomizeRandomSeed() srand(rand() + GetTickCount32()); } -#ifdef WIN32 +#ifdef _WIN32 static LONG SafeNtQueryInformationThread(HANDLE ThreadHandle, INT ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength) { @@ -1240,78 +1248,78 @@ DWORD SharedUtil::GetMainThreadId() { static DWORD dwMainThreadID = 0; - if (dwMainThreadID == 0) + if (dwMainThreadID) + return dwMainThreadID; + + // Get the module information for the currently running process + DWORD processEntryPointAddress = 0; + MODULEINFO moduleInfo = {}; + + if (GetModuleInformation(GetCurrentProcess(), GetModuleHandle(nullptr), &moduleInfo, sizeof(MODULEINFO))) { - // Get the module information for the currently running process - DWORD processEntryPointAddress = 0; - MODULEINFO moduleInfo = {}; + processEntryPointAddress = reinterpret_cast(moduleInfo.EntryPoint); + } - if (GetModuleInformation(GetCurrentProcess(), GetModuleHandle(nullptr), &moduleInfo, sizeof(MODULEINFO)) != 0) - { - processEntryPointAddress = reinterpret_cast(moduleInfo.EntryPoint); - } + // Find oldest thread in the current process ( http://www.codeproject.com/Questions/78801/How-to-get-the-main-thread-ID-of-a-process-known-b ) + HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - // Find oldest thread in the current process ( http://www.codeproject.com/Questions/78801/How-to-get-the-main-thread-ID-of-a-process-known-b ) - HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if (hThreadSnap == INVALID_HANDLE_VALUE) + return GetCurrentThreadId(); + + ULONGLONG ullMinCreateTime = ULLONG_MAX; - if (hThreadSnap != INVALID_HANDLE_VALUE) - { - ULONGLONG ullMinCreateTime = ULLONG_MAX; + DWORD currentProcessID = GetCurrentProcessId(); - DWORD currentProcessID = GetCurrentProcessId(); + THREADENTRY32 th32 = {}; + th32.dwSize = sizeof(THREADENTRY32); - THREADENTRY32 th32 = {}; - th32.dwSize = sizeof(THREADENTRY32); + for (BOOL bOK = Thread32First(hThreadSnap, &th32); bOK; bOK = Thread32Next(hThreadSnap, &th32)) + { + if (th32.th32OwnerProcessID != currentProcessID) + continue; + + HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, TRUE, th32.th32ThreadID); + + if (!hThread) + continue; + + // Check the thread by entry point first + if (processEntryPointAddress != 0) + { + DWORD entryPointAddress = 0; - for (BOOL bOK = Thread32First(hThreadSnap, &th32); bOK; bOK = Thread32Next(hThreadSnap, &th32)) + if (QueryThreadEntryPointAddress(hThread, &entryPointAddress) && entryPointAddress == processEntryPointAddress) { - if (th32.th32OwnerProcessID == currentProcessID) - { - HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, TRUE, th32.th32ThreadID); - - if (hThread) - { - // Check the thread by entry point first - if (processEntryPointAddress != 0) - { - DWORD entryPointAddress = 0; - - if (QueryThreadEntryPointAddress(hThread, &entryPointAddress) && entryPointAddress == processEntryPointAddress) - { - dwMainThreadID = th32.th32ThreadID; - CloseHandle(hThread); - CloseHandle(hThreadSnap); - return dwMainThreadID; - } - } - - // If entry point check failed, find the oldest thread in the system - FILETIME afTimes[4] = {}; - - if (GetThreadTimes(hThread, &afTimes[0], &afTimes[1], &afTimes[2], &afTimes[3])) - { - ULONGLONG ullTest = (ULONGLONG(afTimes[0].dwHighDateTime) << 32) + afTimes[0].dwLowDateTime; - - if (ullTest && ullTest < ullMinCreateTime) - { - ullMinCreateTime = ullTest; - dwMainThreadID = th32.th32ThreadID; - } - } - - CloseHandle(hThread); - } - } + dwMainThreadID = th32.th32ThreadID; + CloseHandle(hThread); + CloseHandle(hThreadSnap); + return dwMainThreadID; } - - CloseHandle(hThreadSnap); } - // Fallback - if (dwMainThreadID == 0) + // If entry point check failed, find the oldest thread in the system + FILETIME afTimes[4] = {}; + + if (GetThreadTimes(hThread, &afTimes[0], &afTimes[1], &afTimes[2], &afTimes[3])) { - dwMainThreadID = GetCurrentThreadId(); + ULONGLONG ullTest = (ULONGLONG(afTimes[0].dwHighDateTime) << 32) + afTimes[0].dwLowDateTime; + + if (ullTest && ullTest < ullMinCreateTime) + { + ullMinCreateTime = ullTest; + dwMainThreadID = th32.th32ThreadID; + } } + + CloseHandle(hThread); + } + + CloseHandle(hThreadSnap); + + // Fallback + if (!dwMainThreadID) + { + dwMainThreadID = GetCurrentThreadId(); } return dwMainThreadID; @@ -1324,7 +1332,7 @@ DWORD SharedUtil::GetMainThreadId() // bool SharedUtil::IsMainThread() { -#ifdef WIN32 +#ifdef _WIN32 DWORD mainThreadID = GetMainThreadId(); DWORD currentThreadID = GetCurrentThreadId(); return mainThreadID == currentThreadID; @@ -1337,7 +1345,7 @@ bool SharedUtil::IsMainThread() // // Expiry stuff // -#ifdef WIN32 +#ifdef _WIN32 #include int SharedUtil::GetBuildAge() @@ -1347,7 +1355,7 @@ int SharedUtil::GetBuildAge() when.tm_year = BUILD_YEAR - 1900; when.tm_mon = BUILD_MONTH; when.tm_mday = BUILD_DAY; - return (int)(time(NULL) - mktime(&when)) / (60 * 60 * 24); + return (int)(time(nullptr) - mktime(&when)) / (60 * 60 * 24); } #if defined(MTA_DM_EXPIRE_DAYS) @@ -1358,7 +1366,7 @@ int SharedUtil::GetDaysUntilExpire() when.tm_year = BUILD_YEAR - 1900; when.tm_mon = BUILD_MONTH; when.tm_mday = BUILD_DAY + MTA_DM_EXPIRE_DAYS; - return (int)(mktime(&when) - time(NULL)) / (60 * 60 * 24); + return (int)(mktime(&when) - time(nullptr)) / (60 * 60 * 24); } #endif @@ -1400,7 +1408,7 @@ SString SharedUtil::RemoveColorCodes(const char* szString) // void SharedUtil::RemoveColorCodesInPlaceW(WString& strText) { - uint uiSearchPos = 0; + std::uint32_t uiSearchPos = 0; while (true) { std::wstring::size_type uiFoundPos = strText.find(L'#', uiSearchPos); @@ -1427,10 +1435,12 @@ bool SharedUtil::IsColorCode(const char* szColorCode) return false; bool bValid = true; - for (int i = 0; i < 6; i++) + for (auto i = 0; i < 6; i++) { - char c = szColorCode[1 + i]; - if (!isdigit((unsigned char)c) && (c < 'A' || c > 'F') && (c < 'a' || c > 'f')) + std::uint8_t c = szColorCode[1 + i]; + if (isdigit(c)) + continue; + if ((c < 'A' || c > 'F') && (c < 'a' || c > 'f')) { bValid = false; break; @@ -1447,13 +1457,13 @@ bool SharedUtil::IsColorCodeW(const wchar_t* wszColorCode) if (*wszColorCode != L'#') return false; - for (uint i = 0; i < 6; i++) + for (std::uint32_t i = 0; i < 6; i++) { wchar_t c = wszColorCode[i + 1]; - if (!iswdigit(c) && (c < 'A' || c > 'F') && (c < 'a' || c > 'f')) - { + if (iswdigit(c)) + continue; + if ((c < 'A' || c > 'F') && (c < 'a' || c > 'f')) return false; - } } return true; } @@ -1463,7 +1473,7 @@ char* SharedUtil::Trim(char* szText) char* szOriginal = szText; size_t uiLen = 0; - while (isspace((unsigned char)*szText)) + while (isspace((std::uint8_t)*szText)) szText++; if (*szText) @@ -1471,7 +1481,7 @@ char* SharedUtil::Trim(char* szText) char* p = szText; while (*p) p++; - while (isspace((unsigned char)*(--p))) + while (isspace((std::uint8_t)*(--p))) ; p[1] = '\0'; uiLen = (size_t)(p - szText + 1); @@ -1508,7 +1518,7 @@ std::string SharedUtil::UTF16ToMbUTF8(const char16_t* input) } // Get UTF8 confidence -int SharedUtil::GetUTF8Confidence(const unsigned char* input, int len) +int SharedUtil::GetUTF8Confidence(const std::uint8_t* input, int len) { return icu_getUTF8Confidence(input, len); } @@ -1516,8 +1526,8 @@ int SharedUtil::GetUTF8Confidence(const unsigned char* input, int len) // Translate a true ANSI string to the UTF-16 equivalent (reencode+convert) std::wstring SharedUtil::ANSIToUTF16(const SString& input) { - size_t len = mbstowcs(NULL, input.c_str(), input.length()); - if (len == (size_t)-1) + std::size_t len = mbstowcs(nullptr, input.c_str(), input.length()); + if (len == (std::size_t)-1) return L"?"; wchar_t* wcsOutput = new wchar_t[len + 1]; mbstowcs(wcsOutput, input.c_str(), input.length()); @@ -1528,16 +1538,16 @@ std::wstring SharedUtil::ANSIToUTF16(const SString& input) } // Check for BOM bytes -bool SharedUtil::IsUTF8BOM(const void* pData, uint uiLength) +bool SharedUtil::IsUTF8BOM(const void* pData, std::uint32_t uiLength) { - const uchar* pCharData = (const uchar*)pData; + const std::uint8_t* pCharData = static_cast(pData); return (uiLength > 2 && pCharData[0] == 0xEF && pCharData[1] == 0xBB && pCharData[2] == 0xBF); } // Check for UTF8/ANSI compiled script -bool SharedUtil::IsLuaCompiledScript(const void* pData, uint uiLength) +bool SharedUtil::IsLuaCompiledScript(const void* pData, std::uint32_t uiLength) { - const uchar* pCharData = (const uchar*)pData; + const std::uint8_t* pCharData = static_cast(pData); if (IsUTF8BOM(pCharData, uiLength)) { pCharData += 3; @@ -1547,9 +1557,9 @@ bool SharedUtil::IsLuaCompiledScript(const void* pData, uint uiLength) } // Check for obfuscated script -bool SharedUtil::IsLuaObfuscatedScript(const void* pData, uint uiLength) +bool SharedUtil::IsLuaObfuscatedScript(const void* pData, std::uint32_t uiLength) { - const uchar* pCharData = (const uchar*)pData; + const std::uint8_t* pCharData = static_cast(pData); return (uiLength > 0 && pCharData[0] == 0x1C); // Look for our special marker } @@ -1559,14 +1569,16 @@ bool SharedUtil::IsLuaObfuscatedScript(const void* pData, uint uiLength) bool SharedUtil::IsValidVersionString(const SString& strVersion) { const SString strCheck = "0.0.0-0.00000.0.000"; - uint uiLength = std::min(strCheck.length(), strVersion.length()); - for (unsigned int i = 0; i < uiLength; i++) + std::size_t uiLength = std::min(strCheck.length(), strVersion.length()); + + for (std::size_t i = 0; i < uiLength; i++) { - uchar c = strVersion[i]; - uchar d = strCheck[i]; - if (!isdigit(c) || !isdigit(d)) - if (c != d) - return false; + std::uint8_t c = strVersion[i]; + std::uint8_t d = strCheck[i]; + if (isdigit(c) && isdigit(d)) + continue; + if (c != d) + return false; } return true; } @@ -1602,7 +1614,7 @@ SString SharedUtil::ConformResourcePath(const char* szRes, bool bConvertToUnixPa if (!bConvertToUnixPathSep) { cPathSep = '\\'; - for (unsigned int i = 0; i < NUMELMS(strDelimList); i++) + for (auto i = 0; i < NUMELMS(strDelimList); i++) strDelimList[i] = strDelimList[i].Replace("/", "\\"); strText = strText.Replace("/", "\\"); } @@ -1610,12 +1622,12 @@ SString SharedUtil::ConformResourcePath(const char* szRes, bool bConvertToUnixPa #endif { cPathSep = '/'; - for (unsigned int i = 0; i < NUMELMS(strDelimList); i++) + for (auto i = 0; i < NUMELMS(strDelimList); i++) strDelimList[i] = strDelimList[i].Replace("\\", "/"); strText = strText.Replace("\\", "/"); } - for (unsigned int i = 0; i < NUMELMS(strDelimList); i++) + for (auto i = 0; i < NUMELMS(strDelimList); i++) { // Remove up to first occurrence int iPos = strText.find(strDelimList[i]); @@ -1636,14 +1648,14 @@ SString SharedUtil::ConformResourcePath(const char* szRes, bool bConvertToUnixPa namespace SharedUtil { - CArgMap::CArgMap(const SString& strArgSep, const SString& strPartsSep, const SString& strExtraDisallowedChars) + CArgMap::CArgMap(const SString& strArgSep, const SString& strPartsSep, const SString& strExtraDisallowedChars) noexcept : m_strArgSep(strArgSep), m_strPartsSep(strPartsSep) { m_strDisallowedChars = strExtraDisallowedChars + m_strArgSep + m_strPartsSep; m_cEscapeCharacter = '#'; } - void CArgMap::SetEscapeCharacter(char cEscapeCharacter) { m_cEscapeCharacter = cEscapeCharacter; } + void CArgMap::SetEscapeCharacter(char cEscapeCharacter) noexcept { m_cEscapeCharacter = cEscapeCharacter; } void CArgMap::Merge(const CArgMap& other, bool bAllowMultiValues) { MergeFromString(other.ToString(), bAllowMultiValues); } @@ -1657,10 +1669,10 @@ namespace SharedUtil { std::vector parts; strLine.Split(m_strPartsSep, parts); - for (uint i = 0; i < parts.size(); i++) + for (const auto& value : parts) { SString strCmd, strArg; - parts[i].Split(m_strArgSep, &strCmd, &strArg); + value.Split(m_strArgSep, &strCmd, &strArg); if (!bAllowMultiValues) m_Map.erase(strCmd); if (strCmd.length()) // Key can not be empty @@ -1671,21 +1683,25 @@ namespace SharedUtil SString CArgMap::ToString() const { SString strResult; - for (std::multimap::const_iterator iter = m_Map.begin(); iter != m_Map.end(); ++iter) + // cant use structurized binding because + // game_sa is C++14 (C++17 required) + for(auto it = m_Map.begin(); it != m_Map.end(); ++it) { - if (strResult.length()) + if (!strResult.empty()) strResult += m_strPartsSep; - strResult += iter->first + m_strArgSep + iter->second; + strResult += it->first + m_strArgSep + it->second; } return strResult; } bool CArgMap::HasMultiValues() const { - for (std::multimap::const_iterator iter = m_Map.begin(); iter != m_Map.end(); ++iter) + // cant use structurized binding because + // game_sa is C++14 (C++17 required) + for(auto it = m_Map.begin(); it != m_Map.end(); ++it) { std::vector newItems; - MultiFind(m_Map, iter->first, &newItems); + MultiFind(m_Map, it->first, &newItems); if (newItems.size() > 1) return true; } @@ -1727,7 +1743,7 @@ namespace SharedUtil } // Test if key exists - bool CArgMap::Contains(const SString& strCmd) const { return MapFind(m_Map, Escape(strCmd)) != NULL; } + bool CArgMap::Contains(const SString& strCmd) const { return MapFind(m_Map, Escape(strCmd)) != nullptr; } // First result as string bool CArgMap::Get(const SString& strCmd, SString& strOut, const char* szDefault) const @@ -1755,10 +1771,10 @@ namespace SharedUtil { std::vector newItems; MultiFind(m_Map, Escape(strCmd), &newItems); - for (uint i = 0; i < newItems.size(); i++) - newItems[i] = Unescape(newItems[i]); + for (auto& value : newItems) + value = Unescape(value); ListAppend(outList, newItems); - return newItems.size() > 0; + return !newItems.empty(); } // First result as int @@ -1777,11 +1793,13 @@ namespace SharedUtil // All keys void CArgMap::GetKeys(std::vector& outList) const { - for (std::multimap::const_iterator iter = m_Map.begin(); iter != m_Map.end(); ++iter) - outList.push_back(iter->first); + // cant use structurized binding because + // game_sa is C++14 (C++17 required) + for (auto it = m_Map.begin(); it != m_Map.end(); ++it) + outList.push_back(it->first); } -#ifdef WIN32 +#ifdef _WIN32 /////////////////////////////////////////////////////////////////////////// // // GetCurrentProcessorNumberXP for the current thread, especially for Windows XP @@ -1817,17 +1835,16 @@ namespace SharedUtil /////////////////////////////////////////////////////////////////////////// DWORD _GetCurrentProcessorNumber() { -#ifdef WIN32 +#ifdef _WIN32 // Dynamically load GetCurrentProcessorNumber, as it does not exist on XP using GetCurrentProcessorNumber_t = DWORD(WINAPI*)(); static auto FnGetCurrentProcessorNumber = ([]() -> GetCurrentProcessorNumber_t { HMODULE kernel32 = LoadLibraryA("kernel32"); - if (kernel32) - return static_cast(static_cast(GetProcAddress(kernel32, "GetCurrentProcessorNumber"))); - - return nullptr; + if (!kernel32) + return nullptr; + return static_cast(static_cast(GetProcAddress(kernel32, "GetCurrentProcessorNumber"))); })(); if (FnGetCurrentProcessorNumber) @@ -1866,11 +1883,11 @@ namespace SharedUtil // Returns time in microseconds used by this thread // /////////////////////////////////////////////////////////////////////////// - void GetThreadCPUTimes(uint64& outUserTime, uint64& outKernelTime) + void GetThreadCPUTimes(std::uint64_t& outUserTime, std::uint64_t& outKernelTime) { outUserTime = 0; outKernelTime = 0; -#ifdef WIN32 +#ifdef _WIN32 FILETIME CreationTime, ExitTime, KernelTime, UserTime; if (GetThreadTimes(GetCurrentThread(), &CreationTime, &ExitTime, &KernelTime, &UserTime)) { @@ -1885,8 +1902,8 @@ namespace SharedUtil rusage usage; if (getrusage(RUSAGE_THREAD, &usage) == 0) { - outUserTime = (uint64)usage.ru_utime.tv_sec * 1000000ULL + (uint64)usage.ru_utime.tv_usec; - outKernelTime = (uint64)usage.ru_stime.tv_sec * 1000000ULL + (uint64)usage.ru_stime.tv_usec; + outUserTime = (std::uint64_t)usage.ru_utime.tv_sec * 1000000ULL + (std::uint64_t)usage.ru_utime.tv_usec; + outKernelTime = (std::uint64_t)usage.ru_stime.tv_sec * 1000000ULL + (std::uint64_t)usage.ru_stime.tv_usec; } #endif } @@ -1901,44 +1918,44 @@ namespace SharedUtil void UpdateThreadCPUTimes(SThreadCPUTimesStore& store, long long* pllTickCount) { // Use supplied tick count if present - uint64 ullCPUMeasureTimeMs; + std::uint64_t ullCPUMeasureTimeMs; if (pllTickCount) ullCPUMeasureTimeMs = *pllTickCount; else ullCPUMeasureTimeMs = GetTickCount64_(); - if (ullCPUMeasureTimeMs - store.ullPrevCPUMeasureTimeMs > 1000) + if (ullCPUMeasureTimeMs - store.ullPrevCPUMeasureTimeMs <= 1000) + return; + + store.uiProcessorNumber = SharedUtil::_GetCurrentProcessorNumber(); + std::uint64_t ullUserTimeUs, ullKernelTimeUs; + GetThreadCPUTimes(ullUserTimeUs, ullKernelTimeUs); + + float fCPUMeasureTimeDeltaMs = static_cast(ullCPUMeasureTimeMs - store.ullPrevCPUMeasureTimeMs); + float fUserTimeDeltaUs = static_cast(ullUserTimeUs - store.ullPrevUserTimeUs); + float fKernelTimeDeltaUs = static_cast(ullKernelTimeUs - store.ullPrevKernelTimeUs); + if (fCPUMeasureTimeDeltaMs > 0) { - store.uiProcessorNumber = SharedUtil::_GetCurrentProcessorNumber(); - uint64 ullUserTimeUs, ullKernelTimeUs; - GetThreadCPUTimes(ullUserTimeUs, ullKernelTimeUs); - - float fCPUMeasureTimeDeltaMs = (float)(ullCPUMeasureTimeMs - store.ullPrevCPUMeasureTimeMs); - float fUserTimeDeltaUs = (float)(ullUserTimeUs - store.ullPrevUserTimeUs); - float fKernelTimeDeltaUs = (float)(ullKernelTimeUs - store.ullPrevKernelTimeUs); - if (fCPUMeasureTimeDeltaMs > 0) - { - float fPercentScaler = 0.1f / fCPUMeasureTimeDeltaMs; - store.fUserPercent = fUserTimeDeltaUs * fPercentScaler; - store.fKernelPercent = fKernelTimeDeltaUs * fPercentScaler; - store.fTotalCPUPercent = (fUserTimeDeltaUs + fKernelTimeDeltaUs) * fPercentScaler; - } - else - { - store.fUserPercent = 0; - store.fKernelPercent = 0; - store.fTotalCPUPercent = 0; - } - store.ullPrevUserTimeUs = ullUserTimeUs; - store.ullPrevKernelTimeUs = ullKernelTimeUs; - store.ullPrevCPUMeasureTimeMs = ullCPUMeasureTimeMs; - - // Updated smoothed values - float fAlpha = 1.f / store.fAvgTimeSeconds; - store.fUserPercentAvg = Lerp(store.fUserPercentAvg, fAlpha, store.fUserPercent); - store.fKernelPercentAvg = Lerp(store.fKernelPercentAvg, fAlpha, store.fKernelPercent); - store.fTotalCPUPercentAvg = Lerp(store.fTotalCPUPercentAvg, fAlpha, store.fTotalCPUPercent); + float fPercentScaler = 0.1f / fCPUMeasureTimeDeltaMs; + store.fUserPercent = fUserTimeDeltaUs * fPercentScaler; + store.fKernelPercent = fKernelTimeDeltaUs * fPercentScaler; + store.fTotalCPUPercent = (fUserTimeDeltaUs + fKernelTimeDeltaUs) * fPercentScaler; } + else + { + store.fUserPercent = 0; + store.fKernelPercent = 0; + store.fTotalCPUPercent = 0; + } + store.ullPrevUserTimeUs = ullUserTimeUs; + store.ullPrevKernelTimeUs = ullKernelTimeUs; + store.ullPrevCPUMeasureTimeMs = ullCPUMeasureTimeMs; + + // Updated smoothed values + float fAlpha = 1.0f / store.fAvgTimeSeconds; + store.fUserPercentAvg = Lerp(store.fUserPercentAvg, fAlpha, store.fUserPercent); + store.fKernelPercentAvg = Lerp(store.fKernelPercentAvg, fAlpha, store.fKernelPercent); + store.fTotalCPUPercentAvg = Lerp(store.fTotalCPUPercentAvg, fAlpha, store.fTotalCPUPercent); } // @@ -1946,11 +1963,12 @@ namespace SharedUtil // // Ranges of numbers. i.e. 100-4000, 5000-6999, 7000-7010 // - void CRanges::SetRange(uint uiStart, uint uiLength) + void CRanges::SetRange(std::uint32_t uiStart, std::uint32_t uiLength) { if (uiLength < 1) return; - uint uiLast = uiStart + uiLength - 1; + + std::uint32_t uiLast = uiStart + uiLength - 1; // Make a hole UnsetRange(uiStart, uiLength); @@ -1961,27 +1979,27 @@ namespace SharedUtil // Maybe join adjacent ranges one day } - void CRanges::UnsetRange(uint uiStart, uint uiLength) + void CRanges::UnsetRange(std::uint32_t uiStart, std::uint32_t uiLength) { if (uiLength < 1) return; - uint uiLast = uiStart + uiLength - 1; + std::uint32_t uiLast = uiStart + uiLength - 1; RemoveObscuredRanges(uiStart, uiLast); IterType iterOverlap; if (GetRangeOverlappingPoint(uiStart, iterOverlap)) { - uint uiOverlapPrevLast = iterOverlap->second; + std::uint32_t uiOverlapPrevLast = iterOverlap->second; // Modify overlapping range last point - uint uiNewLast = uiStart - 1; + std::uint32_t uiNewLast = uiStart - 1; iterOverlap->second = uiNewLast; if (uiOverlapPrevLast > uiLast) { // Need to add range after hole - uint uiNewStart = uiLast + 1; + std::uint32_t uiNewStart = uiLast + 1; m_StartLastMap[uiNewStart] = uiOverlapPrevLast; } } @@ -1989,19 +2007,19 @@ namespace SharedUtil if (GetRangeOverlappingPoint(uiLast, iterOverlap)) { // Modify overlapping range start point - uint uiNewStart = uiLast + 1; - uint uiOldLast = iterOverlap->second; + std::uint32_t uiNewStart = uiLast + 1; + std::uint32_t uiOldLast = iterOverlap->second; m_StartLastMap.erase(iterOverlap); m_StartLastMap[uiNewStart] = uiOldLast; } } // Returns true if any part of the range already exists in the map - bool CRanges::IsRangeSet(uint uiStart, uint uiLength) + bool CRanges::IsRangeSet(std::uint32_t uiStart, std::uint32_t uiLength) { if (uiLength < 1) return false; - uint uiLast = uiStart + uiLength - 1; + std::uint32_t uiLast = uiStart + uiLength - 1; IterType iter = m_StartLastMap.lower_bound(uiStart); // iter is on or after start @@ -2026,7 +2044,7 @@ namespace SharedUtil return false; } - void CRanges::RemoveObscuredRanges(uint uiStart, uint uiLast) + void CRanges::RemoveObscuredRanges(std::uint32_t uiStart, std::uint32_t uiLast) { while (true) { @@ -2045,22 +2063,22 @@ namespace SharedUtil } } - bool CRanges::GetRangeOverlappingPoint(uint uiPoint, IterType& result) + bool CRanges::GetRangeOverlappingPoint(std::uint32_t uiPoint, IterType& result) { IterType iter = m_StartLastMap.lower_bound(uiPoint); // iter is on or after point - So it can't overlap the point - if (iter != m_StartLastMap.begin()) - { - iter--; - // iter is now before point + if (iter == m_StartLastMap.begin()) + return false; + + iter--; + // iter is now before point - // If last of found range is after or at query point, then range is overlapping - if (iter->second >= uiPoint) - { - result = iter; - return true; - } + // If last of found range is after or at query point, then range is overlapping + if (iter->second >= uiPoint) + { + result = iter; + return true; } return false; } @@ -2070,18 +2088,19 @@ namespace SharedUtil // // For checking MTA library module versions // -MTAEXPORT void GetLibMtaVersion(char* pBuffer, uint uiMaxSize) +MTAEXPORT void GetLibMtaVersion(char* pBuffer, std::uint32_t uiMaxSize) { SString strVersion("%d.%d.%d-%d.%05d.%d" #ifdef MTASA_VERSION_MAJOR - , - MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, MTASA_VERSION_BUILD + , + MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, MTASA_VERSION_BUILD #else - , - 0, 0, 0, 0, 0 + , + 0, 0, 0, 0, 0 #endif - , - 0); - uint uiLengthInclTerm = strVersion.length() + 1; + , + 0 + ); + std::uint32_t uiLengthInclTerm = strVersion.length() + 1; STRNCPY(pBuffer, *strVersion, std::max(uiLengthInclTerm, uiMaxSize)); }