Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
src: reduced substring calls
Reduced the number of substring calls by 1 as it is a linear time
complexity function. Thus having a larger path might lead to decrease in
performance. Also removed unnecessary string allocation happening in the
block.
  • Loading branch information
yashLadha committed Sep 6, 2020
commit ec75ce21ed647beed6f24442a5cd896f2b213992
23 changes: 15 additions & 8 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -84,19 +84,26 @@ const char* const kPathSeparator = "\\/";
#endif

std::string Basename(const std::string& str, const std::string& extension) {
std::string ret = str;

// Remove everything leading up to and including the final path separator.
std::string::size_type pos = ret.find_last_of(kPathSeparator);
if (pos != std::string::npos) ret = ret.substr(pos + 1);
std::string::size_type pos = str.find_last_of(kPathSeparator);

// Starting index for the resulting string
std::size_t start_pos = 0;
// String size to return
std::size_t str_size = str.size();
if (pos != std::string::npos) {
start_pos = pos + 1;
str_size -= start_pos;
}

// Strip away the extension, if any.
if (ret.size() >= extension.size() &&
ret.substr(ret.size() - extension.size()) == extension) {
ret = ret.substr(0, ret.size() - extension.size());
if (str_size >= extension.size() &&
str.compare(str.size() - extension.size(),
extension.size(), extension) == 0) {
str_size -= extension.size();
}

return ret;
return str.substr(start_pos, str_size);
}

inline int64_t GetOffset(Local<Value> value) {
Expand Down