From 821a4234d04043417d0880f23479c170b062ea58 Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Mon, 29 May 2023 17:16:53 +0300 Subject: QFileDialog: refactor a static helper - Fix narrowing conversion warnings - Don't use an out of bounds index with QStringView::mid(), which happened when view.size() was used as an index - Use sliced() Change-Id: Ia9bf62887ffb6ddd2458c9e46d33e8cfe0ee2b66 Reviewed-by: Richard Moe Gustavsen Reviewed-by: Thiago Macieira --- src/widgets/dialogs/qfiledialog.cpp | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) (limited to 'src/widgets/dialogs') diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp index 6b146bbaa5..caf2918d92 100644 --- a/src/widgets/dialogs/qfiledialog.cpp +++ b/src/widgets/dialogs/qfiledialog.cpp @@ -1134,20 +1134,28 @@ Q_AUTOTEST_EXPORT QString qt_tildeExpansion(const QString &path) { if (!path.startsWith(u'~')) return path; - int separatorPosition = path.indexOf(QDir::separator()); - if (separatorPosition < 0) - separatorPosition = path.size(); - if (separatorPosition == 1) { - return QDir::homePath() + QStringView{path}.mid(1); - } else { + + if (path.size() == 1) // '~' + return QDir::homePath(); + + QStringView sv(path); + const qsizetype sepIndex = sv.indexOf(QDir::separator()); + if (sepIndex == 1) // '~/' or '~/a/b/c' + return QDir::homePath() + sv.sliced(1); + #if defined(Q_OS_VXWORKS) || defined(Q_OS_INTEGRITY) - const QString homePath = QDir::homePath(); + if (sepIndex == -1) + return QDir::homePath(); + return QDir::homePath() + sv.sliced(sepIndex); #else - const QByteArray userName = QStringView{path}.mid(1, separatorPosition - 1).toLocal8Bit(); - QString homePath = homeDirFromPasswdEntry(path, userName); -#endif - return homePath + QStringView{path}.mid(separatorPosition); - } + const qsizetype userNameLen = sepIndex != -1 ? sepIndex - strlen("~") // '~user/a/b' + : path.size() - strlen("~"); // '~user' + const QByteArray userName = sv.sliced(1, userNameLen).toLocal8Bit(); + QString homePath = homeDirFromPasswdEntry(path, userName); + if (sepIndex == -1) + return homePath; + return homePath + sv.sliced(sepIndex); +#endif // defined(Q_OS_VXWORKS) || defined(Q_OS_INTEGRITY) } #endif -- cgit v1.2.3