Skip to content

Commit a6f124b

Browse files
authored
perf: replace O(n²) hex-encoding loops with std::to_chars (#230)
1 parent f35873b commit a6f124b

2 files changed

Lines changed: 20 additions & 6 deletions

File tree

src/signer.cc

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include <openssl/hmac.h>
2222

2323
#include <array>
24+
#include <charconv>
2425
#include <cstdio>
2526
#include <string>
2627
#include <type_traits>
@@ -86,10 +87,16 @@ std::string GetSignature(std::string_view signing_key,
8687
std::string_view string_to_sign) {
8788
std::string hash = HmacHash(signing_key, string_to_sign);
8889
std::string signature;
89-
char buf[3];
90+
signature.resize(hash.size() * 2);
91+
char* out = signature.data();
9092
for (std::size_t i = 0, n_size = hash.size(); i < n_size; ++i) {
91-
snprintf(buf, 3, "%02x", (unsigned char)hash[i]);
92-
signature += buf;
93+
auto [ptr, ec] =
94+
std::to_chars(out, out + 2, static_cast<unsigned char>(hash[i]), 16);
95+
if (ptr - out == 1) {
96+
out[1] = out[0];
97+
out[0] = '0';
98+
}
99+
out += 2;
93100
}
94101
return signature;
95102
}

src/utils.cc

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
#include "miniocpp/utils.h"
1919

20+
#include <charconv>
21+
2022
#include "miniocpp/error.h"
2123

2224
#ifdef _WIN32
@@ -266,10 +268,15 @@ std::string Sha256Hash(std::string_view str) {
266268
EVP_MD_CTX_destroy(ctx);
267269

268270
std::string hash;
269-
char buf[3];
271+
hash.resize(length * 2);
272+
char* out = hash.data();
270273
for (unsigned int i = 0; i < length; ++i) {
271-
snprintf(buf, 3, "%02x", digest[i]);
272-
hash += buf;
274+
if (auto [ptr, ec] = std::to_chars(out, out + 2, digest[i], 16);
275+
ptr - out == 1) {
276+
out[1] = out[0];
277+
out[0] = '0';
278+
}
279+
out += 2;
273280
}
274281

275282
OPENSSL_free(digest);

0 commit comments

Comments
 (0)