mirror of
https://github.com/nodejs/node.git
synced 2025-08-15 13:48:44 +02:00
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:
parent
a2fdef0e28
commit
08770bc24a
2 changed files with 75 additions and 1 deletions
|
@ -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, {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue