Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions SerialPrograms/Source/CommonFramework/Tools/FileHash.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/* File Hash
*
* From: https://github.com/PokemonAutomation/
*
*/

#include "Common/Cpp/Exceptions.h"
#include <QFile>
#include <QCryptographicHash>
#include <QDebug>
#include "FileHash.h"


#include <iostream>
using std::cout;
using std::endl;

namespace PokemonAutomation{



std::string hash_file(CancellableScope& scope, const std::string& file_path, std::function<void(uint64_t bytes_done, uint64_t total_bytes)> 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();
}

}
21 changes: 21 additions & 0 deletions SerialPrograms/Source/CommonFramework/Tools/FileHash.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/* File Hash
*
* From: https://github.com/PokemonAutomation/
*
*/

#ifndef PokemonAutomation_FileHash_H
#define PokemonAutomation_FileHash_H

#include <string>
#include <functional>
#include "Common/Cpp/CancellableScope.h"


namespace PokemonAutomation{

// uses SHA 256
std::string hash_file(CancellableScope& scope, const std::string& file_path, std::function<void(uint64_t bytes_done, uint64_t total_bytes)> hash_progress);

}
#endif
2 changes: 2 additions & 0 deletions SerialPrograms/cmake/SourceFiles.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down