perf: optimise normalisePath (#2162)
This commit is contained in:
+22
-14
@@ -3,6 +3,7 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cctype>
|
#include <cctype>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace FsHelpers {
|
namespace FsHelpers {
|
||||||
@@ -36,12 +37,14 @@ std::string decodeUriEscapes(const std::string& path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string normalisePath(const std::string& path) {
|
std::string normalisePath(const std::string& path) {
|
||||||
std::vector<std::string> components;
|
std::vector<std::string_view> components;
|
||||||
std::string component;
|
components.reserve(8); // Eight nested folders is more than we might expect
|
||||||
|
|
||||||
for (const auto c : path) {
|
size_t start = 0;
|
||||||
if (c == '/') {
|
for (size_t i = 0; i <= path.length(); ++i) {
|
||||||
if (!component.empty()) {
|
if (i == path.length() || path[i] == '/') {
|
||||||
|
if (i > start) {
|
||||||
|
std::string_view component(path.data() + start, i - start);
|
||||||
if (component == "..") {
|
if (component == "..") {
|
||||||
if (!components.empty()) {
|
if (!components.empty()) {
|
||||||
components.pop_back();
|
components.pop_back();
|
||||||
@@ -49,23 +52,28 @@ std::string normalisePath(const std::string& path) {
|
|||||||
} else {
|
} else {
|
||||||
components.push_back(component);
|
components.push_back(component);
|
||||||
}
|
}
|
||||||
component.clear();
|
|
||||||
}
|
}
|
||||||
} else {
|
start = i + 1;
|
||||||
component += c;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!component.empty()) {
|
if (components.empty()) {
|
||||||
components.push_back(component);
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t total_len = 0;
|
||||||
|
for (const auto& c : components) {
|
||||||
|
total_len += c.length() + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string result;
|
std::string result;
|
||||||
for (const auto& c : components) {
|
result.reserve(total_len - 1);
|
||||||
if (!result.empty()) {
|
|
||||||
result += "/";
|
for (size_t i = 0; i < components.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
result += '/';
|
||||||
}
|
}
|
||||||
result += c;
|
result.append(components[i].data(), components[i].length());
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
Reference in New Issue
Block a user