From 23493b7d3d11e2e5def74694b9ed7454a623b302 Mon Sep 17 00:00:00 2001 From: Sadie Powell Date: Mon, 10 May 2021 16:47:35 +0100 Subject: Refactor the hex encoding function. --- src/inspstring.cpp | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) (limited to 'src/inspstring.cpp') diff --git a/src/inspstring.cpp b/src/inspstring.cpp index df93ddd71..bb3eab2bb 100644 --- a/src/inspstring.cpp +++ b/src/inspstring.cpp @@ -26,20 +26,27 @@ #include "inspircd.h" -static const char hextable[] = "0123456789abcdef"; - -std::string BinToHex(const void* raw, size_t l) +std::string Hex::Encode(const void* data, size_t length, const char* table, char separator) { - const char* data = static_cast(raw); - std::string rv; - rv.reserve(l * 2); - for (size_t i = 0; i < l; i++) + if (!table) + table = Hex::TABLE_LOWER; + + // Preallocate the output buffer to avoid constant reallocations. + std::string buffer; + buffer.reserve((length * 2) + (!!separator * length)); + + const unsigned char* udata = reinterpret_cast(data); + for (size_t idx = 0; idx < length; ++idx) { - unsigned char c = data[i]; - rv.push_back(hextable[c >> 4]); - rv.push_back(hextable[c & 0xF]); + if (idx && separator) + buffer.push_back(separator); + + const unsigned char chr = udata[idx]; + buffer.push_back(table[chr >> 4]); + buffer.push_back(table[chr & 15]); } - return rv; + + return buffer; } std::string Base64::Encode(const void* data, size_t length, const char* table, char padding) -- cgit v1.3.1-10-gc9f91