diff --git a/SerialPrograms/Source/CommonFramework/Tools/FileHash.cpp b/SerialPrograms/Source/CommonFramework/Tools/FileHash.cpp new file mode 100644 index 0000000000..9e89ff7b29 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/Tools/FileHash.cpp @@ -0,0 +1,50 @@ +/* File Hash + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include +#include +#include +#include "FileHash.h" + + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +std::string hash_file(CancellableScope& scope, const std::string& file_path, std::function hash_progress) { + QFile file(QString::fromStdString(file_path)); + if (!file.open(QIODevice::ReadOnly)) { + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "hash_file: Could not open file."); + } + + QCryptographicHash hash(QCryptographicHash::Sha256); + qint64 file_size = file.size(); + qint64 total_bytes_read = 0; + + QByteArray buffer(1024 * 1024, 0); // Pre-allocate 1MB once + while (!file.atEnd()) { + scope.throw_if_cancelled(); + + qint64 num_bytes_in_chunk = file.read(buffer.data(), buffer.size()); + if (num_bytes_in_chunk == -1) { + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "hash_file: Read error:" + file.errorString().toStdString()); + } + + hash.addData(QByteArrayView(buffer.data(), num_bytes_in_chunk)); + total_bytes_read += num_bytes_in_chunk; + + hash_progress(total_bytes_read, file_size); + } + + return hash.result().toHex().toStdString(); +} + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/FileHash.h b/SerialPrograms/Source/CommonFramework/Tools/FileHash.h new file mode 100644 index 0000000000..19b230dd13 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/Tools/FileHash.h @@ -0,0 +1,21 @@ +/* File Hash + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_FileHash_H +#define PokemonAutomation_FileHash_H + +#include +#include +#include "Common/Cpp/CancellableScope.h" + + +namespace PokemonAutomation{ + +// uses SHA 256 +std::string hash_file(CancellableScope& scope, const std::string& file_path, std::function hash_progress); + +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index bf2323086e..4255a98889 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -497,6 +497,8 @@ file(GLOB LIBRARY_SOURCES Source/CommonFramework/Tools/ErrorDumper.h Source/CommonFramework/Tools/FileDownloader.cpp Source/CommonFramework/Tools/FileDownloader.h + Source/CommonFramework/Tools/FileHash.cpp + Source/CommonFramework/Tools/FileHash.h Source/CommonFramework/Tools/FileUnzip.cpp Source/CommonFramework/Tools/FileUnzip.h Source/CommonFramework/Tools/GlobalThreadPools.cpp