Skip to content

Commit e15d40f

Browse files
committed
avoid unnecessary number parsing in canonicalize_port.
In the final step of the function, we merely validate that it is a port number. But this does not work require parsing the port. E.g., any port string with 3 or 4 characters (like 8001) is obviously valid as long as it does not start with 0.
1 parent efbd82e commit e15d40f

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

src/url_pattern_helpers.cpp

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -328,22 +328,21 @@ tl::expected<std::string, errors> canonicalize_port(
328328
std::string_view digits_to_parse =
329329
std::string_view(trimmed.data(), first_non_digit - trimmed.begin());
330330

331-
// Parse the port number
332-
uint16_t parsed_port{};
333-
auto result = std::from_chars(digits_to_parse.data(),
334-
digits_to_parse.data() + digits_to_parse.size(),
335-
parsed_port);
336-
337-
if (result.ec == std::errc::result_out_of_range) {
331+
// Here we have that a range of ASCII digit characters identified
332+
// by digits_to_parse. It is none empty.
333+
// We want to determine whether it is a valid port number (0-65535).
334+
// Clearly, if the length is greater than 5, it is invalid.
335+
// If the length is 5, we need to compare lexicographically to "65535".
336+
// Otherwise it is valid.
337+
if (digits_to_parse.size() == 5) {
338+
if (digits_to_parse > "65535") {
339+
return tl::unexpected(errors::type_error);
340+
}
341+
} else if (digits_to_parse.size() > 5) {
338342
return tl::unexpected(errors::type_error);
339343
}
340-
341-
if (result.ec == std::errc()) {
342-
// Successfully parsed, return as string
343-
return std::to_string(parsed_port);
344-
}
345-
346-
return tl::unexpected(errors::type_error);
344+
// It is valid! Most times, we do not need to parse it into an integer.
345+
return std::string(digits_to_parse);
347346
}
348347

349348
tl::expected<std::string, errors> canonicalize_port_with_protocol(

0 commit comments

Comments
 (0)