|
4 | 4 | #include <QSharedPointer>
|
5 | 5 | #include <QString>
|
6 | 6 | #include <QDir>
|
| 7 | +#include <QDataStream> |
7 | 8 | #include <stdexcept>
|
8 | 9 |
|
9 | 10 | #ifdef Q_OS_UNIX
|
@@ -148,11 +149,19 @@ void BitArray::initFromIO(QIODevice *dataStream, qint64 sizeInBits)
|
148 | 149 | if (sizeInBits < 0) {
|
149 | 150 | sizeInBits = dataStream->bytesAvailable() * 8;
|
150 | 151 | }
|
| 152 | + |
| 153 | + QDataStream stream(dataStream); |
| 154 | + initFromStream(stream, sizeInBits); |
| 155 | +} |
| 156 | + |
| 157 | +void BitArray::initFromStream(QDataStream &dataStream, qint64 sizeInBits) |
| 158 | +{ |
151 | 159 | m_size = sizeInBits;
|
152 | 160 | qint64 bytesToRead = this->sizeInBytes();
|
153 | 161 | char *byteBuffer = new char[CACHE_CHUNK_BYTE_SIZE];
|
154 | 162 | while (bytesToRead > 0) {
|
155 |
| - qint64 bytesRead = dataStream->read(byteBuffer, CACHE_CHUNK_BYTE_SIZE); |
| 163 | + qint64 actualBytes = qMin(bytesToRead, qint64(CACHE_CHUNK_BYTE_SIZE)); |
| 164 | + qint64 bytesRead = dataStream.readRawData(byteBuffer, actualBytes); |
156 | 165 | m_dataFile.write(byteBuffer, bytesRead);
|
157 | 166 | bytesToRead -= bytesRead;
|
158 | 167 |
|
@@ -629,13 +638,40 @@ QByteArray BitArray::readBytes(qint64 byteOffset, qint64 maxBytes) const
|
629 | 638 | }
|
630 | 639 |
|
631 | 640 | void BitArray::writeTo(QIODevice *outputStream) const
|
| 641 | +{ |
| 642 | + QDataStream stream(outputStream); |
| 643 | + writeToStream(stream); |
| 644 | +} |
| 645 | + |
| 646 | +BitArray* BitArray::deserialize(QDataStream &stream) |
| 647 | +{ |
| 648 | + qint64 sizeInBits; |
| 649 | + stream >> sizeInBits; |
| 650 | + if (sizeInBits < 0) { |
| 651 | + stream.setStatus(QDataStream::Status::ReadCorruptData); |
| 652 | + return nullptr; |
| 653 | + } |
| 654 | + |
| 655 | + auto bitArray = new BitArray(); |
| 656 | + bitArray->initFromStream(stream, sizeInBits); |
| 657 | + return bitArray; |
| 658 | +} |
| 659 | + |
| 660 | +void BitArray::serialize(QDataStream &stream) const |
| 661 | +{ |
| 662 | + stream << m_size; |
| 663 | + writeToStream(stream); |
| 664 | +} |
| 665 | + |
| 666 | +void BitArray::writeToStream(QDataStream &dataStream) const |
632 | 667 | {
|
633 | 668 | QIODevice *reader = dataReader();
|
634 | 669 | char *byteBuffer = new char[CACHE_CHUNK_BYTE_SIZE];
|
635 | 670 | qint64 bytesToWrite = sizeInBytes();
|
636 | 671 | while (bytesToWrite > 0) {
|
637 |
| - qint64 bytesRead = reader->read(byteBuffer, CACHE_CHUNK_BYTE_SIZE); |
638 |
| - outputStream->write(byteBuffer, bytesRead); |
| 672 | + qint64 actualBytes = qMin(bytesToWrite, qint64(CACHE_CHUNK_BYTE_SIZE)); |
| 673 | + qint64 bytesRead = reader->read(byteBuffer, actualBytes); |
| 674 | + dataStream.writeRawData(byteBuffer, bytesRead); |
639 | 675 | bytesToWrite -= bytesRead;
|
640 | 676 |
|
641 | 677 | if (bytesToWrite > 0 && bytesRead < 1) {
|
|
0 commit comments