From f99521c835fc384b081a6e329143d6a86eafe601 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=AD=CF=86=CE=B1=CE=BD=CE=BF=CF=82=20=22Coor?= =?UTF-8?q?nio/8924th=22=20=CE=92=CE=BB=CE=B1=CF=83=CF=84=CF=8C=CF=82?= <8924th@gmail.com> Date: Tue, 27 Aug 2024 02:33:11 +0300 Subject: [PATCH] SHA1 class can now compute hash from char span too --- src/Assistants/SHA1.cpp | 25 +++++++++++++++++++++++++ src/Assistants/SHA1.hpp | 4 ++++ 2 files changed, 29 insertions(+) diff --git a/src/Assistants/SHA1.cpp b/src/Assistants/SHA1.cpp index 697a437..b55e6ab 100644 --- a/src/Assistants/SHA1.cpp +++ b/src/Assistants/SHA1.cpp @@ -210,6 +210,25 @@ void SHA1::update(std::istream& is) { } } +void SHA1::update(std::span data) { + std::size_t offset{}; + + while (offset < data.size()) { + const auto chunksize{ std::min(BLOCK_BYTES - buffer.size(), data.size() - offset) }; + + buffer.append(data.data() + offset, chunksize); + offset += chunksize; + + // If buffer is full, process the block + if (buffer.size() == BLOCK_BYTES) { + std::uint32_t block[BLOCK_INTS]{}; + buffer_to_block(buffer, block); + transform(digest, block, transforms); + buffer.clear(); + } + } +} + std::string SHA1::final() { // total number of hashed bits const std::uint64_t total_bits{ (transforms * BLOCK_BYTES + buffer.size()) * 8 }; @@ -253,3 +272,9 @@ std::string SHA1::from_file(const std::filesystem::path& filePath) { checksum.update(stream); return checksum.final(); } + +std::string SHA1::from_span(const std::span fileData) { + SHA1 checksum; + checksum.update(fileData); + return checksum.final(); +} diff --git a/src/Assistants/SHA1.hpp b/src/Assistants/SHA1.hpp index 343f8ed..b7182ef 100644 --- a/src/Assistants/SHA1.hpp +++ b/src/Assistants/SHA1.hpp @@ -9,8 +9,10 @@ #pragma once +#include #include #include +#include #include class SHA1 { @@ -22,7 +24,9 @@ class SHA1 { SHA1(); void update(const std::string& s); void update(std::istream& is); + void update(std::span data); std::string final(); static std::string from_file(const std::filesystem::path& filePath); + static std::string from_span(const std::span fileData); };