File indexing completed on 2024-06-23 05:48:48

0001 /*
0002     This file is part of the Okteta Kasten module, made within the KDE community.
0003 
0004     SPDX-FileCopyrightText: 2009, 2023 Friedrich W. H. Kossebau <kossebau@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
0007 */
0008 
0009 #include "qcryptographicbytearraychecksumalgorithm.hpp"
0010 
0011 // Okteta core
0012 #include <Okteta/AbstractByteArrayModel>
0013 // Qt
0014 #include <QByteArray>
0015 
0016 QCryptographicByteArrayChecksumAlgorithm::QCryptographicByteArrayChecksumAlgorithm(const QString& name,
0017                                                                                    const QString& id,
0018                                                                                    QCryptographicHash::Algorithm algorithm)
0019     : AbstractByteArrayChecksumAlgorithm(name, id)
0020     , m_algorithm(algorithm)
0021 {
0022 }
0023 
0024 QCryptographicByteArrayChecksumAlgorithm::~QCryptographicByteArrayChecksumAlgorithm() = default;
0025 
0026 AbstractByteArrayChecksumParameterSet* QCryptographicByteArrayChecksumAlgorithm::parameterSet() { return &mParameterSet; }
0027 
0028 bool QCryptographicByteArrayChecksumAlgorithm::calculateChecksum(QString* result,
0029                                                                  const Okteta::AbstractByteArrayModel* model,
0030                                                                  const Okteta::AddressRange& range) const
0031 {
0032     QCryptographicHash hash(m_algorithm);
0033 
0034     // TODO: find a way without needing to copy, perhaps by smart iterator which can return spans of original data or using some QIODevice wrapper
0035     // TODO: see if buffer size could be a value which matches the algorithm and QCryptographicHash
0036 
0037     char buffer[CalculatedByteCountSignalLimit];
0038     int bufferLength = CalculatedByteCountSignalLimit;
0039     Okteta::Address nextBlockEnd = range.start() + CalculatedByteCountSignalLimit;
0040     for (Okteta::Address i = range.start(); i <= range.end(); i += CalculatedByteCountSignalLimit) {
0041         if (range.end() < i + CalculatedByteCountSignalLimit) {
0042             bufferLength = range.end() - i + 1;
0043         }
0044         model->copyTo(reinterpret_cast<Okteta::Byte*>(buffer), i, bufferLength);
0045         hash.addData(buffer, bufferLength);
0046 
0047         if (i >= nextBlockEnd) {
0048             nextBlockEnd += CalculatedByteCountSignalLimit;
0049             Q_EMIT calculatedBytes(range.localIndex(i) + 1);
0050         }
0051     }
0052 
0053     const QByteArray hashResult = hash.result();
0054 
0055     *result = QString::fromLatin1(hashResult.toHex());
0056     return true;
0057 }
0058 
0059 #include "moc_qcryptographicbytearraychecksumalgorithm.cpp"