Skip to content

Commit 9346f15

Browse files
lemireUlisesGascon
authored andcommitted
src: use find instead of char-by-char in FromFilePath()
PR-URL: #50288 Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Vinícius Lourenço Claro Cardoso <contact@viniciusl.com.br> Reviewed-By: Tobias Nießen <tniessen@tnie.de>
1 parent f87921d commit 9346f15

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

src/node_url.cc

+14-5
Original file line numberDiff line numberDiff line change
@@ -417,12 +417,21 @@ void BindingData::RegisterExternalReferences(
417417
}
418418
}
419419

420-
std::string FromFilePath(const std::string_view file_path) {
421-
std::string escaped_file_path;
422-
for (size_t i = 0; i < file_path.length(); ++i) {
423-
escaped_file_path += file_path[i];
424-
if (file_path[i] == '%') escaped_file_path += "25";
420+
std::string FromFilePath(std::string_view file_path) {
421+
// Avoid unnecessary allocations.
422+
size_t pos = file_path.empty() ? std::string_view::npos : file_path.find('%');
423+
if (pos == std::string_view::npos) {
424+
return ada::href_from_file(file_path);
425425
}
426+
// Escape '%' characters to a temporary string.
427+
std::string escaped_file_path;
428+
do {
429+
escaped_file_path += file_path.substr(0, pos + 1);
430+
escaped_file_path += "25";
431+
file_path = file_path.substr(pos + 1);
432+
pos = file_path.empty() ? std::string_view::npos : file_path.find('%');
433+
} while (pos != std::string_view::npos);
434+
escaped_file_path += file_path;
426435
return ada::href_from_file(escaped_file_path);
427436
}
428437

src/node_url.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ class BindingData : public SnapshotableObject {
8181
std::optional<std::string> base);
8282
};
8383

84-
std::string FromFilePath(const std::string_view file_path);
84+
std::string FromFilePath(std::string_view file_path);
8585

8686
} // namespace url
8787

0 commit comments

Comments
 (0)