Skip to content

Commit

Permalink
pad variable bytes instead of fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
darcys22 committed Nov 30, 2023
1 parent 845bf47 commit f14aca7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
3 changes: 3 additions & 0 deletions include/ethyl/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ namespace utils
std::array<unsigned char, 32> hash(std::string in);

std::string getFunctionSignature(const std::string& function);

std::string padToNBytes(const std::string& input, size_t byte_count, PaddingDirection direction = PaddingDirection::LEFT);
std::string padTo8Bytes(const std::string& input, PaddingDirection direction = PaddingDirection::LEFT);
std::string padTo32Bytes(const std::string& input, PaddingDirection direction = PaddingDirection::LEFT);

std::vector<unsigned char> intToBytes(uint64_t num);
Expand Down
25 changes: 16 additions & 9 deletions src/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ std::string utils::getFunctionSignature(const std::string& function) {
return "0x" + hashHex.substr(0, 8);
}

std::string utils::padTo32Bytes(const std::string& input, utils::PaddingDirection direction) {
constexpr size_t targetSize = 64;
std::string utils::padToNBytes(const std::string& input, size_t byte_count, utils::PaddingDirection direction) {
std::string output = input;
bool has0xPrefix = false;

Expand All @@ -92,17 +91,17 @@ std::string utils::padTo32Bytes(const std::string& input, utils::PaddingDirectio
output = output.substr(2); // remove "0x" prefix for now
}

// Calculate padding size based on targetSize
size_t nextMultiple = (output.size() + targetSize - 1) / targetSize * targetSize;
// Calculate padding size based on byteCount * 2 (since each byte is represented by 2 hex characters)
size_t targetHexStringSize = byte_count * 2;
size_t nextMultiple = (output.size() + targetHexStringSize - 1) / targetHexStringSize * targetHexStringSize;
size_t paddingSize = nextMultiple - output.size();
std::string padding(paddingSize, '0');
if(direction == utils::PaddingDirection::LEFT) {

if (direction == PaddingDirection::LEFT) {
output = padding + output;
}
else {
} else {
output += padding;
}
}

// If input started with "0x", add it back
if (has0xPrefix) {
Expand All @@ -112,6 +111,14 @@ std::string utils::padTo32Bytes(const std::string& input, utils::PaddingDirectio
return output;
}

std::string utils::padTo32Bytes(const std::string& input, PaddingDirection direction) {
return padToNBytes(input, 32, direction);
}

std::string utils::padTo8Bytes(const std::string& input, PaddingDirection direction) {
return padToNBytes(input, 8, direction);
}

std::vector<unsigned char> utils::intToBytes(uint64_t num) {
if (num == 0)
return std::vector<unsigned char>{};
Expand Down

0 comments on commit f14aca7

Please sign in to comment.