From a62088539ed02a8569814601b3b99b713c5d8a34 Mon Sep 17 00:00:00 2001 From: Lioncash Date: Wed, 12 Jun 2019 17:27:06 -0400 Subject: common/hex_util: Combine HexVectorToString() and HexArrayToString() These can be generified together by using a concept type to designate them. This also has the benefit of not making copies of potentially very large arrays. --- src/common/hex_util.cpp | 7 ------- src/common/hex_util.h | 11 +++++++---- 2 files changed, 7 insertions(+), 11 deletions(-) (limited to 'src/common') diff --git a/src/common/hex_util.cpp b/src/common/hex_util.cpp index 5b63f9e81..c2f6cf0f6 100644 --- a/src/common/hex_util.cpp +++ b/src/common/hex_util.cpp @@ -30,13 +30,6 @@ std::vector HexStringToVector(std::string_view str, bool little_endian) { return out; } -std::string HexVectorToString(const std::vector& vector, bool upper) { - std::string out; - for (u8 c : vector) - out += fmt::format(upper ? "{:02X}" : "{:02x}", c); - return out; -} - std::array operator""_array16(const char* str, std::size_t len) { if (len != 32) { LOG_ERROR(Common, diff --git a/src/common/hex_util.h b/src/common/hex_util.h index 68f003cb6..a64c9b485 100644 --- a/src/common/hex_util.h +++ b/src/common/hex_util.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include "common/common_types.h" @@ -30,13 +31,15 @@ std::array HexStringToArray(std::string_view str) { return out; } -std::string HexVectorToString(const std::vector& vector, bool upper = true); +template +std::string HexToString(const ContiguousContainer& data, bool upper = true) { + static_assert(std::is_same_v, + "Underlying type within the contiguous container must be u8."); -template -std::string HexArrayToString(std::array array, bool upper = true) { std::string out; - for (u8 c : array) + for (const u8 c : data) { out += fmt::format(upper ? "{:02X}" : "{:02x}", c); + } return out; } -- cgit v1.2.3 From 969cd6dc1d60acd98c89815dd53c11bf4dac2518 Mon Sep 17 00:00:00 2001 From: Lioncash Date: Wed, 12 Jun 2019 17:47:05 -0400 Subject: common/hex_util: Reserve std::string memory ahead of time Avoids potentially performing multiple reallocations (depending on the size of the input data) by reserving the necessary amount of memory ahead of time. This is trivially doable, so there's no harm in it. --- src/common/hex_util.h | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/common') diff --git a/src/common/hex_util.h b/src/common/hex_util.h index a64c9b485..bb4736f96 100644 --- a/src/common/hex_util.h +++ b/src/common/hex_util.h @@ -36,10 +36,15 @@ std::string HexToString(const ContiguousContainer& data, bool upper = true) { static_assert(std::is_same_v, "Underlying type within the contiguous container must be u8."); + constexpr std::size_t pad_width = 2; + std::string out; + out.reserve(std::size(data) * pad_width); + for (const u8 c : data) { out += fmt::format(upper ? "{:02X}" : "{:02x}", c); } + return out; } -- cgit v1.2.3