Skip to content

Commit

Permalink
SHA1 class can now compute hash from char span too
Browse files Browse the repository at this point in the history
  • Loading branch information
coornio committed Aug 26, 2024
1 parent d976e22 commit f99521c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Assistants/SHA1.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,25 @@ void SHA1::update(std::istream& is) {
}
}

void SHA1::update(std::span<const char> 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 };
Expand Down Expand Up @@ -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<const char> fileData) {
SHA1 checksum;
checksum.update(fileData);
return checksum.final();
}
4 changes: 4 additions & 0 deletions src/Assistants/SHA1.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@

#pragma once

#include <span>
#include <string>
#include <cstdint>
#include <sstream>
#include <filesystem>

class SHA1 {
Expand All @@ -22,7 +24,9 @@ class SHA1 {
SHA1();
void update(const std::string& s);
void update(std::istream& is);
void update(std::span<const char> data);
std::string final();

static std::string from_file(const std::filesystem::path& filePath);
static std::string from_span(const std::span<const char> fileData);
};

0 comments on commit f99521c

Please sign in to comment.