Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

url: faster encodePathChars function. #43566

Closed
wants to merge 1 commit into from
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
50 changes: 31 additions & 19 deletions lib/internal/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@ const {
ReflectApply,
ReflectGetOwnPropertyDescriptor,
ReflectOwnKeys,
RegExp,
String,
StringPrototypeCharCodeAt,
StringPrototypeIncludes,
StringPrototypeReplace,
StringPrototypeSlice,
StringPrototypeSplit,
StringPrototypeStartsWith,
Expand Down Expand Up @@ -1500,25 +1499,38 @@ function fileURLToPath(path) {
// - CR: The carriage return character is also stripped out by the `pathname`
// setter.
// - TAB: The tab character is also stripped out by the `pathname` setter.
const percentRegEx = /%/g;
const backslashRegEx = /\\/g;
const newlineRegEx = /\n/g;
const carriageReturnRegEx = /\r/g;
const tabRegEx = /\t/g;
const escapePathRegExp = new RegExp(`%|\\n|\\r|\\t${isWindows ? '' : '|\\\\'}`);
const escapedPathChars = {
'%': '%25',
'\n': '%0A',
'\r': '%0D',
'\t': '%09',
'\\': '%5C',
};

// As of V8 10.2 the hand written replacer is faster than using replace with a
// replacer function.
function encodePathChars(filepath) {
if (StringPrototypeIncludes(filepath, '%'))
filepath = StringPrototypeReplace(filepath, percentRegEx, '%25');
// In posix, backslash is a valid character in paths:
if (!isWindows && StringPrototypeIncludes(filepath, '\\'))
filepath = StringPrototypeReplace(filepath, backslashRegEx, '%5C');
if (StringPrototypeIncludes(filepath, '\n'))
filepath = StringPrototypeReplace(filepath, newlineRegEx, '%0A');
if (StringPrototypeIncludes(filepath, '\r'))
filepath = StringPrototypeReplace(filepath, carriageReturnRegEx, '%0D');
if (StringPrototypeIncludes(filepath, '\t'))
filepath = StringPrototypeReplace(filepath, tabRegEx, '%09');
return filepath;
if (!escapePathRegExp.test(filepath)) {
return filepath;
}
let result = '';
let last = 0;
for (let i = 0; i < filepath.length; i++) {
const point = filepath.charCodeAt(i);
if (point <= 13 || point === 37 || (!isWindows && point === 92)) {
const replacingChar = escapedPathChars[filepath[i]];
if (replacingChar !== undefined) {
result += `${filepath.slice(last, i)}${replacingChar}`;
last = i + 1;
}
}
}

if (last !== filepath.length) {
result += filepath.slice(last);
}
return result;
}

function pathToFileURL(filepath) {
Expand Down