From 8a7a55e5c2c1770db6a3e2b7450993369a3f48ad Mon Sep 17 00:00:00 2001 From: Jakub Onderka Date: Mon, 2 Nov 2026 22:41:43 +0100 Subject: [PATCH] Refactor toHexIfNeeded for better string handling Refactor toHexIfNeeded function for improved performance and clarity. --- src/utils/string.h | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/utils/string.h b/src/utils/string.h index ac3264aea..5021c1bf4 100644 --- a/src/utils/string.h +++ b/src/utils/string.h @@ -106,18 +106,23 @@ inline std::string limitTo(int amount, const std::string &str) { inline std::string toHexIfNeeded(const std::string &str, bool escape_spec = false) { // escape_spec: escape special chars or not // spec chars: '"' (quotation mark, ascii 34), '\' (backslash, ascii 92) - std::stringstream res; - - for (const auto ch : str) { - int c = (unsigned char)ch; - if (c < 32 || c > 126 || (escape_spec == true && (c == 34 || c == 92))) { - res << "\\x" << std::setw(2) << std::setfill('0') << std::hex << c; + static constexpr char hex[] = "0123456789abcdef"; + + std::string res; + res.reserve(str.size()); + + for (const char ch : str) { + const unsigned char c = static_cast(ch); + if (c < 32 || c > 126 || (escape_spec && (c == '"' || c == '\\'))) { + res += '\\'; + res += 'x'; + res += hex[c >> 4]; + res += hex[c & 0x0F]; } else { - res << ch; + res += ch; } } - - return res.str(); + return res; }