buffer: implement btoa and atob

Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/37529
Fixes: https://github.com/nodejs/node/issues/3462
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
James M Snell 2021-03-17 11:00:57 -07:00
parent a2fdef0e28
commit 08770bc24a
No known key found for this signature in database
GPG key ID: 7341B15C070877AC
2 changed files with 75 additions and 1 deletions

View file

@ -1211,6 +1211,40 @@ if (internalBinding('config').hasIntl) {
};
}
let DOMException;
const lazyInvalidCharError = hideStackFrames((message, name) => {
if (DOMException === undefined)
DOMException = internalBinding('messaging').DOMException;
throw new DOMException('Invalid character', 'InvalidCharacterError');
});
function btoa(input) {
// TODO(@jasnell): The implementation here has not been performance
// optimized in any way.
input = `${input}`;
for (let n = 0; n < input.length; n++) {
if (input[n].charCodeAt(0) > 0xff)
lazyInvalidCharError();
}
const buf = Buffer.from(input, 'latin1');
return buf.toString('base64');
}
const kBase64Digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function atob(input) {
// TODO(@jasnell): The implementation here has not been performance
// optimized in any way.
input = `${input}`;
for (let n = 0; n < input.length; n++) {
if (!kBase64Digits.includes(input[n]))
lazyInvalidCharError();
}
return Buffer.from(input, 'base64').toString('latin1');
}
module.exports = {
Blob,
Buffer,
@ -1218,7 +1252,9 @@ module.exports = {
transcode,
// Legacy
kMaxLength,
kStringMaxLength
kStringMaxLength,
btoa,
atob,
};
ObjectDefineProperties(module.exports, {