Skip to content

Commit fae1006

Browse files
author
MarcoFalke
committed
util: Add ParseHex<std::byte>() helper
1 parent fabdf81 commit fae1006

File tree

3 files changed

+11
-4
lines changed

3 files changed

+11
-4
lines changed

src/test/fuzz/hex.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ FUZZ_TARGET_INIT(hex, initialize_hex)
2525
{
2626
const std::string random_hex_string(buffer.begin(), buffer.end());
2727
const std::vector<unsigned char> data = ParseHex(random_hex_string);
28+
const std::vector<std::byte> bytes{ParseHex<std::byte>(random_hex_string)};
29+
assert(AsBytes(Span{data}) == Span{bytes});
2830
const std::string hex_data = HexStr(data);
2931
if (IsHex(random_hex_string)) {
3032
assert(ToLower(random_hex_string) == hex_data);

src/util/strencodings.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,10 @@ bool IsHexNumber(std::string_view str)
7676
return str.size() > 0;
7777
}
7878

79-
std::vector<unsigned char> ParseHex(std::string_view str)
79+
template <typename Byte>
80+
std::vector<Byte> ParseHex(std::string_view str)
8081
{
81-
std::vector<unsigned char> vch;
82+
std::vector<Byte> vch;
8283
auto it = str.begin();
8384
while (it != str.end() && it + 1 != str.end()) {
8485
if (IsSpace(*it)) {
@@ -88,10 +89,12 @@ std::vector<unsigned char> ParseHex(std::string_view str)
8889
auto c1 = HexDigit(*(it++));
8990
auto c2 = HexDigit(*(it++));
9091
if (c1 < 0 || c2 < 0) break;
91-
vch.push_back(uint8_t(c1 << 4) | c2);
92+
vch.push_back(Byte(c1 << 4) | Byte(c2));
9293
}
9394
return vch;
9495
}
96+
template std::vector<std::byte> ParseHex(std::string_view);
97+
template std::vector<uint8_t> ParseHex(std::string_view);
9598

9699
void SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut)
97100
{

src/util/strencodings.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ enum class ByteUnit : uint64_t {
5555
* @return A new string without unsafe chars
5656
*/
5757
std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT);
58-
std::vector<unsigned char> ParseHex(std::string_view str);
58+
/** Parse the hex string into bytes (uint8_t or std::byte). Ignores whitespace. */
59+
template <typename Byte = uint8_t>
60+
std::vector<Byte> ParseHex(std::string_view str);
5961
signed char HexDigit(char c);
6062
/* Returns true if each character in str is a hex character, and has an even
6163
* number of hex digits.*/

0 commit comments

Comments
 (0)