From d1592b1d4f6f0ea0d180e6848af42b3692e7490a Mon Sep 17 00:00:00 2001 From: Zeno Albisser Date: Mon, 22 Feb 2010 14:14:22 +0100 Subject: Added function overload for QByteArray &QByteArray::replace() This overloaded function can be used to replace a specific portion of a QByteArray with an arbitary amount of characters from a char[]. Reviewed-by: Markus Goetz --- src/corelib/tools/qbytearray.cpp | 15 ++++++++++++++- src/corelib/tools/qbytearray.h | 1 + tests/auto/qbytearray/tst_qbytearray.cpp | 13 +++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp index a27e488..3324796 100644 --- a/src/corelib/tools/qbytearray.cpp +++ b/src/corelib/tools/qbytearray.cpp @@ -1804,7 +1804,20 @@ QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after) */ QByteArray &QByteArray::replace(int pos, int len, const char *after) { - int alen = qstrlen(after); + return replace(pos,len,after,qstrlen(after)); +} + +/*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen) + + \overload + + Replaces \a len bytes from index position \a pos with \a alen bytes + from the string \a after. \a after is allowed to have '\0' characters. + + \since 4.7 +*/ +QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen) +{ if (len == alen && (pos + len <= d->size)) { detach(); memcpy(d->data + pos, after, len*sizeof(char)); diff --git a/src/corelib/tools/qbytearray.h b/src/corelib/tools/qbytearray.h index ec592f5f..0b77512 100644 --- a/src/corelib/tools/qbytearray.h +++ b/src/corelib/tools/qbytearray.h @@ -237,6 +237,7 @@ public: QByteArray &insert(int i, const QByteArray &a); QByteArray &remove(int index, int len); QByteArray &replace(int index, int len, const char *s); + QByteArray &replace(int index, int len, const char *s, int alen); QByteArray &replace(int index, int len, const QByteArray &s); QByteArray &replace(char before, const char *after); QByteArray &replace(char before, const QByteArray &after); diff --git a/tests/auto/qbytearray/tst_qbytearray.cpp b/tests/auto/qbytearray/tst_qbytearray.cpp index 5c72c7a..07fdbc3 100644 --- a/tests/auto/qbytearray/tst_qbytearray.cpp +++ b/tests/auto/qbytearray/tst_qbytearray.cpp @@ -111,6 +111,7 @@ private slots: void remove(); void replace_data(); void replace(); + void replaceWithSpecifiedLength(); void indexOf_data(); void indexOf(); void lastIndexOf_data(); @@ -840,6 +841,18 @@ void tst_QByteArray::replace() QCOMPARE(str2.replace(pos, len, after.data()), expected); } +void tst_QByteArray::replaceWithSpecifiedLength() +{ + const char after[] = "zxc\0vbnmqwert"; + int lenAfter = 6; + QByteArray ba("abcdefghjk"); + ba.replace(0,2,after,lenAfter); + + const char _expected[] = "zxc\0vbcdefghjk"; + QByteArray expected(_expected,sizeof(_expected)-1); + QCOMPARE(ba,expected); +} + void tst_QByteArray::indexOf_data() { QTest::addColumn("haystack"); -- cgit v0.12