diff --git a/src/node_file.cc b/src/node_file.cc index 247c1c530428e8..de5c455c7a2a85 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -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) {