made hasing task async

Signed-off-by: Trial97 <alexandru.tripon97@gmail.com>
This commit is contained in:
Trial97 2024-06-18 17:27:17 +03:00
parent 766ddc80e3
commit 9cbdbddb08
No known key found for this signature in database
GPG Key ID: 55EF5DA53DB36318
3 changed files with 32 additions and 17 deletions

View File

@ -213,7 +213,7 @@ class ExtractZipTask : public Task {
{}
virtual ~ExtractZipTask() = default;
typedef std::optional<QString> ZipResult;
using ZipResult = std::optional<QString>;
protected:
virtual void executeTask() override;

View File

@ -1,16 +1,11 @@
#include "HashUtils.h"
#include <QBuffer>
#include <QDebug>
#include <QFile>
#include "FileSystem.h"
#include "StringUtils.h"
#include <QtConcurrentRun>
#include <MurmurHash2.h>
#include <qbuffer.h>
#include <qcryptographichash.h>
#include <qdebug.h>
#include <qfiledevice.h>
namespace Hashing {
@ -143,12 +138,28 @@ QString hash(QByteArray data, Algorithm type)
void Hasher::executeTask()
{
m_result = hash(m_path, m_alg);
if (m_result.isEmpty()) {
emitFailed("Empty hash!");
} else {
emitSucceeded();
emit resultsReady(m_result);
m_zip_future = QtConcurrent::run(QThreadPool::globalInstance(), [this]() { return hash(m_path, m_alg); });
connect(&m_zip_watcher, &QFutureWatcher<QString>::finished, this, [this] {
if (m_zip_future.isCanceled()) {
emitAborted();
} else if (m_result = m_zip_future.result(); m_result.isEmpty()) {
emitFailed("Empty hash!");
} else {
emitSucceeded();
emit resultsReady(m_result);
}
});
m_zip_watcher.setFuture(m_zip_future);
}
bool Hasher::abort()
{
if (m_zip_future.isRunning()) {
m_zip_future.cancel();
// NOTE: Here we don't do `emitAborted()` because it will be done when `m_build_zip_future` actually cancels, which may not
// occur immediately.
return true;
}
return false;
}
} // namespace Hashing

View File

@ -1,6 +1,8 @@
#pragma once
#include <QCryptographicHash>
#include <QFuture>
#include <QFutureWatcher>
#include <QString>
#include "modplatform/ModIndex.h"
@ -24,8 +26,7 @@ class Hasher : public Task {
Hasher(QString file_path, Algorithm alg) : m_path(file_path), m_alg(alg) {}
Hasher(QString file_path, QString alg) : Hasher(file_path, algorithmFromString(alg)) {}
/* We can't really abort this task, but we can say we aborted and finish our thing quickly :) */
bool abort() override { return true; }
bool abort() override;
void executeTask() override;
@ -35,10 +36,13 @@ class Hasher : public Task {
signals:
void resultsReady(QString hash);
protected:
private:
QString m_result;
QString m_path;
Algorithm m_alg;
QFuture<QString> m_zip_future;
QFutureWatcher<QString> m_zip_watcher;
};
Hasher::Ptr createHasher(QString file_path, ModPlatform::ResourceProvider provider);