qstrnlen: micro-optimize further

This is the kind of loop that the autovectorizer is pretty good
at, but this is really just a type of memchr, so help dumber
compilers and build modes without vectorization.

Drive-up fix the style of the test code.

Change-Id: Ie72b0dd0fbe84d2caae0fffd16a022a35fa24c17
Reviewed-by: Ievgenii Meshcheriakov <ievgenii.meshcheriakov@qt.io>
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>
This commit is contained in:
Thiago Macieira 2021-08-30 09:32:30 -07:00
parent 9258c50936
commit f3743073a7
2 changed files with 11 additions and 13 deletions

View File

@ -96,12 +96,10 @@ inline size_t qstrlen(const char *str)
inline size_t qstrnlen(const char *str, size_t maxlen)
{
size_t length = 0;
if (str) {
while (length < maxlen && *str++)
length++;
}
return length;
if (!str)
return 0;
auto end = static_cast<const char *>(memchr(str, '\0', maxlen));
return end ? end - str : maxlen;
}
// implemented in qbytearray.cpp

View File

@ -803,18 +803,18 @@ void tst_QByteArray::qvsnprintf()
void tst_QByteArray::qstrlen()
{
const char *src = "Something about ... \0 a string.";
QCOMPARE(::qstrlen((char*)0), (uint)0);
QCOMPARE(::qstrlen(src), (uint)20);
QCOMPARE(::qstrlen(nullptr), size_t(0));
QCOMPARE(::qstrlen(src), size_t(20));
}
void tst_QByteArray::qstrnlen()
{
const char *src = "Something about ... \0 a string.";
QCOMPARE(::qstrnlen((char*)0, 1), (uint)0);
QCOMPARE(::qstrnlen(src, 31), (uint)20);
QCOMPARE(::qstrnlen(src, 19), (uint)19);
QCOMPARE(::qstrnlen(src, 21), (uint)20);
QCOMPARE(::qstrnlen(src, 20), (uint)20);
QCOMPARE(::qstrnlen(nullptr, 1), size_t(0));
QCOMPARE(::qstrnlen(src, 31), size_t(20));
QCOMPARE(::qstrnlen(src, 19), size_t(19));
QCOMPARE(::qstrnlen(src, 21), size_t(20));
QCOMPARE(::qstrnlen(src, 20), size_t(20));
}
void tst_QByteArray::qstrcpy()