From cd93cdb5562f542db5eee4b758921632c2de0e25 Mon Sep 17 00:00:00 2001 From: tsctx <91457664+tsctx@users.noreply.github.com> Date: Fri, 1 Dec 2023 09:07:01 +0900 Subject: [PATCH] perf: avoid replace --- lib/fetch/dataURL.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/fetch/dataURL.js b/lib/fetch/dataURL.js index aff8403f0cd..04b5c39af23 100644 --- a/lib/fetch/dataURL.js +++ b/lib/fetch/dataURL.js @@ -412,17 +412,20 @@ function forgivingBase64 (data) { // 1. Remove all ASCII whitespace from data. data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line + let dataLength = data.length // 2. If data’s code point length divides by 4 leaving // no remainder, then: - if (data.length % 4 === 0) { + if (dataLength % 4 === 0) { // 1. If data ends with one or two U+003D (=) code points, // then remove them from data. - data = data.replace(/=?=$/, '') + if (data.charCodeAt(dataLength - 1) === 0x003D && data.charCodeAt(--dataLength) === 0x003D) { + --dataLength + } } // 3. If data’s code point length divides by 4 leaving // a remainder of 1, then return failure. - if (data.length % 4 === 1) { + if (dataLength % 4 === 1) { return 'failure' } @@ -431,7 +434,7 @@ function forgivingBase64 (data) { // U+002F (/) // ASCII alphanumeric // then return failure. - if (/[^+/0-9A-Za-z]/.test(data)) { + if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : (data = data.substring(0, dataLength)))) { return 'failure' }