Skip to content

Commit b8a18eb

Browse files
committed
perf
1 parent a2e981d commit b8a18eb

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

base64.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ export function fromBase64(str, format = 'uint8') {
4242
assert(str[str.length - 3] !== '=', 'Excessive padding') // no more than two = at the end
4343
}
4444

45-
assert(!/[^0-9a-z=+/]/iu.test(str), 'Invalid character in base64 input')
4645
return fromTypedArray(fromBase64common(str, false), format)
4746
}
4847

@@ -54,20 +53,26 @@ export function fromBase64url(str, format = 'uint8') {
5453
assert(str.length % 4 !== 1, 'Invalid base64 length') // JSC misses this in fromBase64
5554
assert(!str.includes('='), 'Did not expect padding in base64url input')
5655

57-
assert(!/[^0-9a-z_-]/iu.test(str), 'Invalid character in base64url input')
5856
return fromTypedArray(fromBase64common(str, true), format)
5957
}
6058

6159
let fromBase64common
6260
if (Uint8Array.fromBase64) {
63-
// NOTICE: this is actually slower than our JS impl in JavaScriptCore and SpiderMonkey (but faster on V8)
61+
// NOTICE: this is actually slower than our JS impl in JavaScriptCore and (slightly) in SpiderMonkey, but faster on V8
6462
fromBase64common = (str, isBase64url) => {
63+
assert(!/\s/u.test(str), 'Invalid character in base64url input') // all other chars are checked natively
6564
const alphabet = isBase64url ? 'base64url' : 'base64'
6665
const padded = str.length % 4 > 0 ? `${str}${'='.repeat(4 - (str.length % 4))}` : str
6766
return Uint8Array.fromBase64(padded, { alphabet, lastChunkHandling: 'strict' })
6867
}
6968
} else {
7069
fromBase64common = (str, isBase64url) => {
70+
if (isBase64url) {
71+
assert(!/[^0-9a-z_-]/iu.test(str), 'Invalid character in base64url input')
72+
} else {
73+
assert(!/[^0-9a-z=+/]/iu.test(str), 'Invalid character in base64 input')
74+
}
75+
7176
let arr
7277
if (!haveNativeBuffer && atob) {
7378
// atob is faster than manual parsing on Hermes

0 commit comments

Comments
 (0)