Handle errors when streaming QJsonDocument through QDataStream

Change-Id: I96df896d446e89dc4f9733a6cc6cec61a6826a1f
Reviewed-by: Luca Beldi <v.ronin@yahoo.it>
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Jędrzej Nowacki 2018-09-03 10:30:10 +02:00
parent 811c2567b6
commit 1d0b5d26ec
2 changed files with 31 additions and 1 deletions

View File

@ -47,6 +47,7 @@
#include "qjsonwriter_p.h"
#include "qjsonparser_p.h"
#include "qjson_p.h"
#include "qdatastream.h"
QT_BEGIN_NAMESPACE
@ -680,7 +681,10 @@ QDataStream &operator>>(QDataStream &stream, QJsonDocument &doc)
{
QByteArray buffer;
stream >> buffer;
doc = QJsonDocument::fromJson(buffer);
QJsonParseError parseError{};
doc = QJsonDocument::fromJson(buffer, &parseError);
if (parseError.error && !buffer.isEmpty())
stream.setStatus(QDataStream::ReadCorruptData);
return stream;
}
#endif

View File

@ -135,6 +135,8 @@ private slots:
void stream_QByteArray2();
void stream_QJsonDocument();
void setVersion_data();
void setVersion();
@ -2095,6 +2097,30 @@ void tst_QDataStream::stream_QByteArray2()
}
}
void tst_QDataStream::stream_QJsonDocument()
{
QByteArray buffer;
{
QDataStream save(&buffer, QIODevice::WriteOnly);
save << QByteArrayLiteral("invalidJson");
QDataStream load(&buffer, QIODevice::ReadOnly);
QJsonDocument doc;
load >> doc;
QVERIFY(doc.isEmpty());
QVERIFY(load.status() != QDataStream::Ok);
QCOMPARE(load.status(), QDataStream::ReadCorruptData);
}
{
QDataStream save(&buffer, QIODevice::WriteOnly);
QJsonDocument docSave(QJsonArray{1,2,3});
save << docSave;
QDataStream load(&buffer, QIODevice::ReadOnly);
QJsonDocument docLoad;
load >> docLoad;
QCOMPARE(docLoad, docSave);
}
}
void tst_QDataStream::setVersion_data()
{
QTest::addColumn<int>("vers");