From b5f96808a1f5a3728e6f6f46764fc1b9ae9ffaf6 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Thu, 27 Apr 2023 23:14:01 +0200 Subject: [PATCH] Fix: FormatArrayAsHex returns gibberish instead of a hex array --- src/string.cpp | 8 ++++---- src/tests/string_func.cpp | 9 +++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/string.cpp b/src/string.cpp index 0ff554f229..eef3ec6943 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -135,14 +135,14 @@ char *stredup(const char *s, const char *last) */ std::string FormatArrayAsHex(span data) { - std::ostringstream ss; - ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex; + std::string str; + str.reserve(data.size() * 2 + 1); for (auto b : data) { - ss << b; + fmt::format_to(std::back_inserter(str), "{:02X}", b); } - return ss.str(); + return str; } /** diff --git a/src/tests/string_func.cpp b/src/tests/string_func.cpp index d56d829fff..a8ddd56711 100644 --- a/src/tests/string_func.cpp +++ b/src/tests/string_func.cpp @@ -12,6 +12,7 @@ #include "../3rdparty/catch2/catch.hpp" #include "../string_func.h" +#include /**** String compare/equals *****/ @@ -516,3 +517,11 @@ TEST_CASE("StrEndsWithIgnoreCase - std::string_view") CHECK(!StrEndsWithIgnoreCase(base.substr(2, 1), base.substr(0, 1))); CHECK(!StrEndsWithIgnoreCase(base.substr(0, 1), base.substr(0, 2))); } + + +TEST_CASE("FormatArrayAsHex") +{ + CHECK(FormatArrayAsHex(std::array{}) == ""); + CHECK(FormatArrayAsHex(std::array{0x12}) == "12"); + CHECK(FormatArrayAsHex(std::array{0x13, 0x38, 0x42, 0xAF}) == "133842AF"); +}