Skip to content

Commit a0ce99b

Browse files
committed
sha1/md5: fix exception safety, remove copy, and own exception message
1 parent bc9807c commit a0ce99b

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/utils/sha1.h

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
#include <array>
2020
#include <cassert>
21+
#include <cstddef>
2122
#include <exception>
2223
#include <string>
2324
#include <string_view>
@@ -67,13 +68,17 @@ class DigestImpl {
6768
static std::string hexdigest(const std::string& input) {
6869
try {
6970
const auto digestBytes = calculateDigest(input);
71+
const auto *digestByteData =
72+
static_cast<const std::byte *>(static_cast<const void *>(digestBytes.data()));
7073
return utils::string::string_to_hex(
71-
digestBytes.data(), digestBytes.size());
74+
digestByteData, digestBytes.size());
7275
} catch (const DigestCalculationException&) {
7376
assert(false);
7477
const std::array<unsigned char, DigestSize> digestBytes = {};
78+
const auto *digestByteData =
79+
static_cast<const std::byte *>(static_cast<const void *>(digestBytes.data()));
7580
return utils::string::string_to_hex(
76-
digestBytes.data(), digestBytes.size());
81+
digestByteData, digestBytes.size());
7782
}
7883
}
7984

src/utils/string.h

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#ifndef SRC_UTILS_STRING_H_
1717
#define SRC_UTILS_STRING_H_
1818

19+
#include <cstddef>
1920
#include <ctime>
2021
#include <string>
2122
#include <cstring>
@@ -241,14 +242,14 @@ inline unsigned char *c2x(unsigned what, unsigned char *where) {
241242
}
242243

243244

244-
inline std::string string_to_hex(const unsigned char *input, size_t size) {
245+
inline std::string string_to_hex(const std::byte *input, size_t size) {
245246
static const char* const lut = "0123456789abcdef";
246247

247248
std::string a(size*2, 0);
248249
char *d = a.data();
249250

250251
for (size_t i = 0; i < size; ++i) {
251-
const unsigned char c = input[i];
252+
const unsigned char c = std::to_integer<unsigned char>(input[i]);
252253
*d++ = lut[c >> 4];
253254
*d++ = lut[c & 15];
254255
}
@@ -257,6 +258,13 @@ inline std::string string_to_hex(const unsigned char *input, size_t size) {
257258
}
258259

259260

261+
inline std::string string_to_hex(const unsigned char *input, size_t size) {
262+
return string_to_hex(
263+
static_cast<const std::byte *>(static_cast<const void *>(input)),
264+
size);
265+
}
266+
267+
260268
inline std::string string_to_hex(std::string_view input) {
261269
static const char* const lut = "0123456789abcdef";
262270

0 commit comments

Comments
 (0)