From 8ed090d38ef1f28e330fa396f1d65e8d207748a1 Mon Sep 17 00:00:00 2001 From: Gordon Lam <73506701+yeelam-gordon@users.noreply.github.com> Date: Thu, 8 Jan 2026 14:02:32 +0800 Subject: [PATCH] Optimize PowerRename logic on memory allocation based on path depth. (#44603) ## Summary of the Pull Request This pull request improves the way items are grouped and processed by depth in the `s_fileOpWorkerThread` function of `PowerRenameManager.cpp`. Instead of sizing the depth matrix by the total item count, it now determines the actual maximum depth of items first, resulting in more efficient memory usage and correctness when handling items by their depth. **Improvements to depth-based processing:** * Added a first pass to determine the maximum depth among all items before allocating the depth matrix, ensuring the matrix is sized appropriately and not excessively large. * Updated the logic to iterate from the maximum depth down to zero when adding items, aligning with the new matrix sizing and ensuring correct processing order. --- .../powerrename/lib/PowerRenameManager.cpp | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/modules/powerrename/lib/PowerRenameManager.cpp b/src/modules/powerrename/lib/PowerRenameManager.cpp index 160d064e09..b650113b25 100644 --- a/src/modules/powerrename/lib/PowerRenameManager.cpp +++ b/src/modules/powerrename/lib/PowerRenameManager.cpp @@ -754,8 +754,26 @@ DWORD WINAPI CPowerRenameManager::s_fileOpWorkerThread(_In_ void* pv) // We add the items to the operation in depth-first order. This allows child items to be // renamed before parent items. + // First pass: find the maximum depth to properly size the matrix + UINT maxDepth = 0; + for (UINT u = 0; u < itemCount; u++) + { + CComPtr spItem; + if (SUCCEEDED(pwtd->spsrm->GetItemByIndex(u, &spItem))) + { + UINT depth = 0; + spItem->GetDepth(&depth); + if (depth > maxDepth) + { + maxDepth = depth; + } + } + } + // Creating a vector of vectors of items of the same depth - std::vector> matrix(itemCount); + // Size by maxDepth+1 (not itemCount) to avoid excessive memory allocation + // Cast to size_t before arithmetic to avoid overflow on 32-bit UINT + std::vector> matrix(static_cast(maxDepth) + 1); for (UINT u = 0; u < itemCount; u++) { @@ -769,7 +787,7 @@ DWORD WINAPI CPowerRenameManager::s_fileOpWorkerThread(_In_ void* pv) } // From the greatest depth first, add all items of that depth to the operation - for (LONG v = itemCount - 1; v >= 0; v--) + for (LONG v = static_cast(maxDepth); v >= 0; v--) { for (auto it : matrix[v]) {