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

perf(base64): Replace random access with iteration #1982

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
53 changes: 33 additions & 20 deletions packages/base64/src/decode.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,45 +22,58 @@ import { monodu64, padding } from './common.js';
* @returns {Uint8Array} decoded bytes
*/
export const jsDecodeBase64 = (string, name = '<unknown>') => {
const data = new Uint8Array(Math.ceil((string.length * 4) / 3));
// String operations can be O(n) in XS as of 2024-01, so cache the length
// and use an iterator rather than sequential access by index.
const stringLength = string.length;
let paddingLength = 0;
const data = new Uint8Array(Math.ceil((stringLength * 3) / 4));
let register = 0;
let quantum = 0;
let i = 0; // index in string
let j = 0; // index in data
let done = false;

while (i < string.length && string[i] !== padding) {
const number = monodu64[string[i]];
for (const ch of string) {
if (done || ch === padding) {
if (ch !== padding) break;
done = true;
paddingLength += 1;
quantum -= 2;
i += 1;
// Padding is only expected to complete a short chunk of two or three data characters
// (i.e., the last two in the `quantum` cycle of [0, 6, 12 - 8 = 4, 10 - 8 = 2]).
if (quantum === 4 || quantum === 2) {
// We MAY reject non-zero padding bits, but choose not to.
// https://datatracker.ietf.org/doc/html/rfc4648#section-3.5
// eslint-disable-next-line no-continue
continue;
}
break;
}
const number = monodu64[ch];
if (number === undefined) {
throw Error(`Invalid base64 character ${string[i]} in string ${name}`);
throw Error(`Invalid base64 character ${ch} in string ${name}`);
}
register = (register << 6) | number;
quantum += 6;
if (quantum >= 8) {
quantum -= 8;
data[j] = register >>> quantum;
data[j] = register >> quantum;
j += 1;
register &= (1 << quantum) - 1;
}
i += 1;
}

while (i < string.length && quantum % 8 !== 0) {
if (string[i] !== padding) {
throw Error(`Missing padding at offset ${i} of string ${name}`);
}
i += 1;
quantum += 6;
}

if (i < string.length) {
if (quantum !== 0) {
throw Error(`Missing padding at offset ${i} of string ${name}`);
} else if (i < stringLength) {
throw Error(
`Base64 string has trailing garbage ${string.substr(
i,
)} in string ${name}`,
`Base64 string has trailing garbage ${string.slice(i)} in string ${name}`,
);
}

return data.subarray(0, j);
return paddingLength === 0
? data
: data.subarray(0, data.length - paddingLength);
};

// The XS Base64.decode function is faster, but might return ArrayBuffer (not
Expand Down
3 changes: 1 addition & 2 deletions packages/base64/src/encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ export const jsEncodeBase64 = data => {
let register = 0;
let quantum = 0;

for (let i = 0; i < data.length; i += 1) {
const b = data[i];
for (const b of data) {
register = (register << 8) | b;
quantum += 8;
if (quantum === 24) {
Expand Down
37 changes: 37 additions & 0 deletions packages/base64/test/test-main.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,40 @@ test('bytes conversions', t => {
t.is(atob(btoa(str)), str, `${str} round trips with atob(btoa)`);
}
});

test('invalid encodings', t => {
const badInputs = [
['%', /Invalid base64 character %/],
['=', undefined], // this input is bad in multiple ways

['Z%', /Invalid base64 character %/],
['Z', /Missing padding at offset 1/],
['Z=', /Missing padding at offset 2/],
['Z=%', /Missing padding at offset 2/],
['Z==%', /Missing padding at offset 3/],
['Z==m', /Missing padding at offset 3/],

['Zg%', /Invalid base64 character %/],
['Zg', /Missing padding at offset 2/],
['Zg=', /Missing padding at offset 3/],
['Zg=%', /Missing padding at offset 3/],
['Zg==%', /trailing garbage %/],
['Zg==m', /trailing garbage m/],

['Zm8%', /Invalid base64 character %/],
['Zm8', /Missing padding at offset 3/],
// not invalid: 'Zm8='
['Zm8=%', /trailing garbage %/],
['Zm8==%', /trailing garbage =%/],
['Zm8==m', /trailing garbage =m/],

// non-zero padding bits (MAY reject): ['Qf==', ...],
];
for (const [badInput, message] of badInputs) {
t.throws(
() => decodeBase64(badInput),
message && { message },
`${badInput} is rejected`,
);
}
});
Loading