parser: add a test that the string copy functions properly terminate
Or don't terminate, as the case may be.
Relates to #194.
Signed-off-by: Thiago Macieira <thiago.macieira@intel.com>
diff --git a/tests/parser/tst_parser.cpp b/tests/parser/tst_parser.cpp
index 28967cc..1890234 100644
--- a/tests/parser/tst_parser.cpp
+++ b/tests/parser/tst_parser.cpp
@@ -990,22 +990,44 @@
err = cbor_value_calculate_string_length(©, &n);
QVERIFY2(!err, QByteArray("Got error \"") + cbor_error_string(err) + "\"");
- QByteArray buffer(n, Qt::Uninitialized);
+ size_t nn = n;
+ QByteArray buffer(n + 1, Qt::Uninitialized);
+ QByteArray buffer2(n + 1, Qt::Uninitialized);
+ buffer[int(n)] = 0xff;
+ buffer2[int(n)] = 0xff;
QString formatted;
if (cbor_value_is_byte_string(©)) {
- err = cbor_value_copy_byte_string(©, (uint8_t *)buffer.data(), &n, nullptr);
+ err = cbor_value_copy_byte_string(©, (uint8_t *)buffer.data(), &nn, nullptr);
QVERIFY2(!err, QByteArray("Got error \"") + cbor_error_string(err) + "\"");
- QCOMPARE(int(n), buffer.size());
+ QCOMPARE(nn, n);
- formatted = QString::fromLatin1("h'" + buffer.toHex() + '\'');
+ formatted = QString::fromLatin1("h'" + QByteArray::fromRawData(buffer.data(), n).toHex() + '\'');
+
+ // repeat by allowing the null termination
+ nn = n + 1;
+ err = cbor_value_copy_byte_string(©, (uint8_t *)buffer2.data(), &nn, nullptr);
} else {
err = cbor_value_copy_text_string(©, buffer.data(), &n, nullptr);
QVERIFY2(!err, QByteArray("Got error \"") + cbor_error_string(err) + "\"");
- QCOMPARE(int(n), buffer.size());
+ QCOMPARE(nn, n);
formatted = '"' + QString::fromUtf8(buffer.data(), n) + '"';
+
+ // repeat by allowing the null termination
+ nn = n + 1;
+ err = cbor_value_copy_text_string(©, buffer2.data(), &nn, nullptr);
}
+ QVERIFY2(!err, QByteArray("Got error \"") + cbor_error_string(err) + "\"");
QCOMPARE(formatted, concatenated);
+
+ // verify terminators
+ QCOMPARE(buffer.at(n), char(0xff));
+ QCOMPARE(buffer2.at(n), '\0');
+ QCOMPARE(nn, n);
+
+ buffer.truncate(n);
+ buffer2.truncate(n);
+ QCOMPARE(buffer2, buffer);
}
// confirm that the extra string we appended is still here