From 9aaa7a77a03205e3e0a4b3688a896360da2526b5 Mon Sep 17 00:00:00 2001 From: Florian Albrechtskirchinger Date: Mon, 3 Feb 2025 14:01:05 +0100 Subject: [PATCH] Refactor detail::random_string() Refactor detail::random_string() to output random bytes in addition to random alphanumeric strings, and change the interface to fill a buffer given a char pointer and length, instead of returning a string. Rename the new function to random_bytes(). Add an overload random_string() that implements the old behavior on top of random_bytes(). --- httplib.h | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/httplib.h b/httplib.h index 097224b..1fec2fe 100644 --- a/httplib.h +++ b/httplib.h @@ -5132,7 +5132,7 @@ private: size_t buf_epos_ = 0; }; -inline std::string random_string(size_t length) { +inline void random_bytes(char *ptr, size_t length, bool alphanum) { static const char data[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; @@ -5147,11 +5147,26 @@ inline std::string random_string(size_t length) { static std::mt19937 engine(seed_sequence); - std::string result; - for (size_t i = 0; i < length; i++) { - result += data[engine() % (sizeof(data) - 1)]; + if (alphanum) { + for (size_t i = 0; i < length; i++) { + *(ptr++) = data[engine() % (sizeof(data) - 1)]; + } + } else { + for (size_t i = 0; i < length;) { + auto val = engine(); + for (size_t j = 0; i < length && j < sizeof(val); ++i, ++j) { + *(ptr++) = static_cast(val); + val >>= 8; + } + } } - return result; +} + +inline std::string random_string(size_t length) { + std::string s; + s.resize(length); + random_bytes(&s[0], length, true); + return s; } inline std::string make_multipart_data_boundary() {