dropshell/src/utils/hash.cpp
2025-04-29 22:49:03 +12:00

114 lines
3.3 KiB
C++

#include "utils/hash.hpp"
#define XXH_INLINE_ALL
#include "contrib/xxhash.hpp"
#include <fstream>
#include <filesystem>
#include <iostream>
namespace dropshell {
uint64_t hash_file(const std::string &path) {
// Create hash state
XXH3_state_t* const state = XXH3_createState();
if (state == nullptr) {
std::cerr << "Failed to create hash state" << std::endl;
return 0;
}
// Initialize state with seed 0
XXH3_64bits_reset(state);
// Open file
std::ifstream file(path, std::ios::binary);
if (!file.is_open()) {
std::cerr << "Failed to open file: " << path << std::endl;
XXH3_freeState(state);
return 0;
}
// Read file in chunks and update hash
const size_t buffer_size = 4096;
char buffer[buffer_size];
while (file.read(buffer, buffer_size)) {
if (XXH3_64bits_update(state, buffer, file.gcount()) == XXH_ERROR) {
std::cerr << "Failed to update hash" << std::endl;
XXH3_freeState(state);
return 0;
}
}
// Handle any remaining bytes
if (file.gcount() > 0) {
if (XXH3_64bits_update(state, buffer, file.gcount()) == XXH_ERROR) {
std::cerr << "Failed to update hash" << std::endl;
XXH3_freeState(state);
return 0;
}
}
// Get final hash
XXH64_hash_t hash = XXH3_64bits_digest(state);
XXH3_freeState(state);
return hash;
}
uint64_t hash_directory_recursive(const std::string &path) {
// Create hash state
XXH3_state_t* const state = XXH3_createState();
if (state == nullptr) {
std::cerr << "Failed to create hash state" << std::endl;
return 0;
}
// Initialize state with seed 0
if (XXH3_64bits_reset(state) == XXH_ERROR) {
std::cerr << "Failed to reset hash state" << std::endl;
XXH3_freeState(state);
return 0;
}
try {
// Iterate through all files in directory recursively
for (const auto& entry : std::filesystem::recursive_directory_iterator(path)) {
if (entry.is_regular_file()) {
// Get file hash
XXH64_hash_t file_hash = hash_file(entry.path().string());
XXH3_64bits_update(state, &file_hash, sizeof(file_hash));
}
}
} catch (const std::filesystem::filesystem_error& e) {
std::cerr << "Filesystem error: " << e.what() << std::endl;
XXH3_freeState(state);
return 0;
}
// Get final hash
XXH64_hash_t hash = XXH3_64bits_digest(state);
XXH3_freeState(state);
return hash;
}
void hash_demo(const std::string & path)
{
std::cout << "Hashing directory: " << path << std::endl;
auto start = std::chrono::high_resolution_clock::now();
XXH64_hash_t hash = hash_directory_recursive(path);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Hash: " << hash << " (took " << duration.count() << "ms)" << std::endl;
}
int hash_demo_raw(const std::string & path)
{
if (!std::filesystem::exists(path)) {
std::cout << 0 <<std::endl; return 1;
}
XXH64_hash_t hash = hash_directory_recursive(path);
std::cout << hash << std::endl;
return 0;
}
} // namespace dropshell