From 3669c5bc58b4ee7c0fc04dbdcb98666d3964f5b8 Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Sat, 20 Mar 2021 18:09:02 +0100 Subject: [PATCH] checksums: add functions for returning results as a hex string --- src/common/checksums/base.cpp | 30 ++++++++++++++++++++++++++++++ src/common/checksums/base_fwd.h | 2 ++ 2 files changed, 32 insertions(+) diff --git a/src/common/checksums/base.cpp b/src/common/checksums/base.cpp index 2c047df39..94b100047 100644 --- a/src/common/checksums/base.cpp +++ b/src/common/checksums/base.cpp @@ -91,6 +91,36 @@ calculate_as_uint(algorithm_e algorithm, return dynamic_cast(*worker).get_result_as_uint(); } +std::string +calculate_as_hex_string(algorithm_e algorithm, + memory_c const &buffer, + uint64_t initial_value) { + return calculate_as_hex_string(algorithm, buffer.get_buffer(), buffer.get_size(), initial_value); +} + +std::string +calculate_as_hex_string(algorithm_e algorithm, + void const *buffer, + size_t size, + uint64_t initial_value) { + auto worker = for_algorithm(algorithm, initial_value); + + worker->add(buffer, size); + worker->finish(); + + auto result = worker->get_result(); + auto result_size = result->get_size(); + auto result_buffer = result->get_buffer(); + + std::string hex_string; + hex_string.reserve(result_size * 2); + + for (auto idx = 0u; idx < result_size; ++idx) + hex_string += fmt::format("{0:02x}", result_buffer[idx]); + + return hex_string; +} + // ---------------------------------------------------------------------- base_c & diff --git a/src/common/checksums/base_fwd.h b/src/common/checksums/base_fwd.h index 256903750..d8c1ea8c7 100644 --- a/src/common/checksums/base_fwd.h +++ b/src/common/checksums/base_fwd.h @@ -39,5 +39,7 @@ memory_cptr calculate(algorithm_e algorithm, memory_c const &buffer, uint64_t in memory_cptr calculate(algorithm_e algorithm, void const *buffer, size_t size, uint64_t initial_value = 0); uint64_t calculate_as_uint(algorithm_e algorithm, memory_c const &buffer, uint64_t initial_value = 0); uint64_t calculate_as_uint(algorithm_e algorithm, void const *buffer, size_t size, uint64_t initial_value = 0); +std::string calculate_as_hex_string(algorithm_e algorithm, memory_c const &buffer, uint64_t initial_value = 0); +std::string calculate_as_hex_string(algorithm_e algorithm, void const *buffer, size_t size, uint64_t initial_value = 0); } // namespace mtx::checksum