From d2932b5d687660c14eaba632cfe48a4052e8bc58 Mon Sep 17 00:00:00 2001 From: Peter Keresztes Schmidt Date: Wed, 26 May 2021 20:03:40 +0200 Subject: [PATCH] Utils: Add a ByteArrayToHexString helper --- src/zm_utils.cpp | 17 +++++++++++++++++ src/zm_utils.h | 4 ++++ tests/zm_utils.cpp | 12 ++++++++++++ 3 files changed, 33 insertions(+) diff --git a/src/zm_utils.cpp b/src/zm_utils.cpp index 7d2bbc888..890b288e4 100644 --- a/src/zm_utils.cpp +++ b/src/zm_utils.cpp @@ -116,6 +116,23 @@ std::string Join(const StringVector &values, const std::string &delim) { return ss.str(); } +std::string ByteArrayToHexString(nonstd::span bytes) { + static constexpr char lowercase_table[] = "0123456789abcdef"; + std::string buf; + buf.resize(2 * bytes.size()); + + const uint8 *srcPtr = bytes.data(); + char *dstPtr = &buf[0]; + + for (size_t i = 0; i < bytes.size(); ++i) { + uint8 c = *srcPtr++; + *dstPtr++ = lowercase_table[c >> 4]; + *dstPtr++ = lowercase_table[c & 0x0f]; + } + + return buf; +} + std::string Base64Encode(const std::string &str) { static char base64_table[64] = {'\0'}; diff --git a/src/zm_utils.h b/src/zm_utils.h index 87f9132eb..6ce096318 100644 --- a/src/zm_utils.h +++ b/src/zm_utils.h @@ -20,12 +20,14 @@ #ifndef ZM_UTILS_H #define ZM_UTILS_H +#include "zm_define.h" #include #include #include #include #include #include +#include "span.hpp" #include #include #include @@ -67,6 +69,8 @@ std::string stringtf(const std::string &format, Args... args) { return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside } +std::string ByteArrayToHexString(nonstd::span bytes); + std::string Base64Encode(const std::string &str); void TimespecDiff(timespec *start, timespec *end, timespec *diff); diff --git a/tests/zm_utils.cpp b/tests/zm_utils.cpp index 4745ad60b..dcb2a6d07 100644 --- a/tests/zm_utils.cpp +++ b/tests/zm_utils.cpp @@ -140,6 +140,18 @@ TEST_CASE("Join") { REQUIRE(Join({"a", "b"}, "") == "ab"); } +TEST_CASE("ByteArrayToHexString") { + std::vector bytes; + + REQUIRE(ByteArrayToHexString(bytes) == ""); + + bytes = {0x00}; + REQUIRE(ByteArrayToHexString(bytes) == "00"); + + bytes = {0x00, 0x01, 0x02, 0xff}; + REQUIRE(ByteArrayToHexString(bytes) == "000102ff"); +} + TEST_CASE("Base64Encode") { REQUIRE(Base64Encode("") == ""); REQUIRE(Base64Encode("f") == "Zg==");