From e390ff050a8fef871adc13c5e6e8acb16c71617d Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 26 May 2022 11:30:03 -0700 Subject: [PATCH] QFileSystemEngine/Win: simplify code We don't need two or even three buffers for the current directory. In the worst case, we had a 260-byte buffer on the stack, a larger one on the heap (new[]/delete[]) and then a copy of it in QString. Now, we shall have only one and it could be "gifted" to QFileSystemEntry via std::move() (requires separate patch to take the QString by rvalue- ref). Pick-to: 6.3 Change-Id: Ibcde9b9795ad42ac9978fffd16f2bb2a443697d6 Reviewed-by: Friedemann Kleint Reviewed-by: Volker Hilsheimer Reviewed-by: Kai Koehne --- src/corelib/io/qfilesystemengine_win.cpp | 27 +++++++++++------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/corelib/io/qfilesystemengine_win.cpp b/src/corelib/io/qfilesystemengine_win.cpp index a6c5d3e6ca9..91d672b52d1 100644 --- a/src/corelib/io/qfilesystemengine_win.cpp +++ b/src/corelib/io/qfilesystemengine_win.cpp @@ -1640,23 +1640,20 @@ bool QFileSystemEngine::setCurrentPath(const QFileSystemEntry &entry) QFileSystemEntry QFileSystemEngine::currentPath() { - QString ret; - DWORD size = 0; - wchar_t currentName[PATH_MAX]; - size = ::GetCurrentDirectory(PATH_MAX, currentName); - if (size != 0) { - if (size > PATH_MAX) { - wchar_t *newCurrentName = new wchar_t[size]; - if (::GetCurrentDirectory(size, newCurrentName) != 0) - ret = QString::fromWCharArray(newCurrentName, size); - delete [] newCurrentName; - } else { - ret = QString::fromWCharArray(currentName, size); - } + QString ret(PATH_MAX, Qt::Uninitialized); + DWORD size = GetCurrentDirectoryW(PATH_MAX, reinterpret_cast(ret.data())); + if (size > PATH_MAX) { + // try again after enlarging the buffer + ret.resize(size); + size = GetCurrentDirectoryW(size, reinterpret_cast(ret.data())); + + // note: the current directory may have changed underneath us; if the + // new one is even bigger, we may return a truncated string! } - if (ret.length() >= 2 && ret[1] == u':') + if (size >= 2 && ret.at(1) == u':') ret[0] = ret.at(0).toUpper(); // Force uppercase drive letters. - return QFileSystemEntry(ret, QFileSystemEntry::FromNativePath()); + ret.resize(size); + return QFileSystemEntry(std::move(ret), QFileSystemEntry::FromNativePath()); } //static