Improve "split to byte array views" function

1. Utilize string matcher
2. Remove split behavior parameter
   Previously `KeepEmptyParts` behavior doesn't match Qt's
   implementation and since our codebase doesn't really make use of it,
   we can just remove the parameter.
3. Add tests.

PR #22352.
This commit is contained in:
Chocobo1
2025-03-03 21:42:03 +08:00
committed by GitHub
parent 96295adc08
commit 62a7fd86d6
9 changed files with 67 additions and 19 deletions

View File

@@ -30,28 +30,30 @@
#include "bytearray.h"
#include <QByteArray>
#include <QByteArrayMatcher>
#include <QByteArrayView>
#include <QList>
QList<QByteArrayView> Utils::ByteArray::splitToViews(const QByteArrayView in, const QByteArrayView sep, const Qt::SplitBehavior behavior)
QList<QByteArrayView> Utils::ByteArray::splitToViews(const QByteArrayView in, const QByteArrayView sep)
{
if (in.isEmpty())
return {};
if (sep.isEmpty())
return {in};
const QByteArrayMatcher matcher {sep};
QList<QByteArrayView> ret;
ret.reserve((behavior == Qt::KeepEmptyParts)
? (1 + (in.size() / sep.size()))
: (1 + (in.size() / (sep.size() + 1))));
int head = 0;
ret.reserve(1 + (in.size() / (sep.size() + 1)));
qsizetype head = 0;
while (head < in.size())
{
int end = in.indexOf(sep, head);
qsizetype end = matcher.indexIn(in, head);
if (end < 0)
end = in.size();
// omit empty parts
const QByteArrayView part = in.mid(head, (end - head));
if (!part.isEmpty() || (behavior == Qt::KeepEmptyParts))
const QByteArrayView part = in.sliced(head, (end - head));
if (!part.isEmpty())
ret += part;
head = end + sep.size();

View File

@@ -37,8 +37,8 @@ class QByteArrayView;
namespace Utils::ByteArray
{
// Mimic QStringView(in).split(sep, behavior)
QList<QByteArrayView> splitToViews(QByteArrayView in, QByteArrayView sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts);
// Inspired by QStringView(in).split(sep, Qt::SkipEmptyParts)
QList<QByteArrayView> splitToViews(QByteArrayView in, QByteArrayView sep);
QByteArray asQByteArray(QByteArrayView view);
QByteArray toBase32(const QByteArray &in);

View File

@@ -68,7 +68,7 @@ namespace
// Software 'Anaconda' installs its own python interpreter
// and `python --version` returns a string like this:
// "Python 3.4.3 :: Anaconda 2.3.0 (64-bit)"
const QList<QByteArrayView> outputSplit = Utils::ByteArray::splitToViews(procOutput, " ", Qt::SkipEmptyParts);
const QList<QByteArrayView> outputSplit = Utils::ByteArray::splitToViews(procOutput, " ");
if (outputSplit.size() <= 1)
return false;

View File

@@ -115,7 +115,7 @@ bool Utils::Password::PBKDF2::verify(const QByteArray &secret, const QString &pa
bool Utils::Password::PBKDF2::verify(const QByteArray &secret, const QByteArray &password)
{
const QList<QByteArrayView> list = ByteArray::splitToViews(secret, ":", Qt::SkipEmptyParts);
const QList<QByteArrayView> list = ByteArray::splitToViews(secret, ":");
if (list.size() != 2)
return false;