Skip to content

Commit 2875a76

Browse files
committed
util: add ParseUInt16(), use it in SplitHostPort()
1 parent 6423c81 commit 2875a76

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/util/strencodings.cpp

+14-2
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,8 @@ void SplitHostPort(std::string in, uint16_t& portOut, std::string& hostOut)
115115
bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
116116
bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
117117
if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
118-
int32_t n;
119-
if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
118+
uint16_t n;
119+
if (ParseUInt16(in.substr(colon + 1), &n)) {
120120
in = in.substr(0, colon);
121121
portOut = n;
122122
}
@@ -335,6 +335,18 @@ bool ParseUInt8(const std::string& str, uint8_t *out)
335335
return true;
336336
}
337337

338+
bool ParseUInt16(const std::string& str, uint16_t* out)
339+
{
340+
uint32_t u32;
341+
if (!ParseUInt32(str, &u32) || u32 > std::numeric_limits<uint16_t>::max()) {
342+
return false;
343+
}
344+
if (out != nullptr) {
345+
*out = static_cast<uint16_t>(u32);
346+
}
347+
return true;
348+
}
349+
338350
bool ParseUInt32(const std::string& str, uint32_t *out)
339351
{
340352
if (!ParsePrechecks(str))

src/util/strencodings.h

+7
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,13 @@ constexpr inline bool IsSpace(char c) noexcept {
115115
*/
116116
[[nodiscard]] bool ParseUInt8(const std::string& str, uint8_t *out);
117117

118+
/**
119+
* Convert decimal string to unsigned 16-bit integer with strict parse error feedback.
120+
* @returns true if the entire string could be parsed as valid integer,
121+
* false if the entire string could not be parsed or if overflow or underflow occurred.
122+
*/
123+
[[nodiscard]] bool ParseUInt16(const std::string& str, uint16_t* out);
124+
118125
/**
119126
* Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
120127
* @returns true if the entire string could be parsed as valid integer,

0 commit comments

Comments
 (0)