Skip to content

Commit

Permalink
Optimize spicy::bytes_to_hexstring and spicy::bytes_to_mac.
Browse files Browse the repository at this point in the history
  • Loading branch information
rsmmr committed Sep 30, 2024
1 parent ee53b9f commit 916ae42
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions spicy/runtime/src/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,41 @@ std::string spicy::rt::version() {
#endif
}


static inline void byte_to_hex(unsigned char byte, char* hex_out) {
static constexpr char hex_chars[] = "0123456789ABCDEF";
hex_out[0] = hex_chars[(byte & 0xf0) >> 4];
hex_out[1] = hex_chars[byte & 0x0f];
}

std::string spicy::rt::bytes_to_hexstring(const hilti::rt::Bytes& value) {
const auto& data = value.str();

if ( data.empty() )
return "";

std::string result;
result.resize(data.size() * 2); // 2 digits per hex byte

for ( auto x : value )
result += hilti::rt::fmt("%02X", x);
for ( unsigned long i = 0; i < data.size(); i++ )
byte_to_hex(data[i], &result[i * 2]);

return result;
}

std::string spicy::rt::bytes_to_mac(const hilti::rt::Bytes& value) {
std::vector<std::string> bytes;
bytes.reserve(value.size());
const auto& data = value.str();

if ( data.empty() )
return "";

for ( auto x : value )
bytes.emplace_back(hilti::rt::fmt("%02X", x));
// Two digits per hex byte, plus one colon per byte except the last.
std::string result((data.size() * 2) + (data.size() - 1), ':');

return hilti::rt::join(bytes, ":");
for ( unsigned long i = 0; i < data.size(); i++ )
byte_to_hex(data[i], &result[i * 3]);

return result;
}

const hilti::rt::Vector<
Expand Down

0 comments on commit 916ae42

Please sign in to comment.