1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-29 16:30:56 -05:00
denoland-deno/extensions/web/05_base64.js
Luca Casonato c73ef5fa14
refactor(web): use encoding_rs for text encoding (#10844)
This commit removes all JS based text encoding / text decoding. Instead
encoding now happens in Rust via encoding_rs (already in tree). This
implementation retains stream support, but adds the last missing
encodings. We are incredibly close to 100% WPT on text encoding now.

This should reduce our baseline heap by quite a bit.
2021-06-05 23:10:07 +02:00

62 lines
1.5 KiB
JavaScript

// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
// @ts-check
/// <reference path="../webidl/internal.d.ts" />
/// <reference path="../web/internal.d.ts" />
/// <reference lib="esnext" />
"use strict";
((window) => {
const webidl = window.__bootstrap.webidl;
const {
forgivingBase64Encode,
forgivingBase64Decode,
} = window.__bootstrap.infra;
/**
* @param {string} data
* @returns {string}
*/
function atob(data) {
data = webidl.converters.DOMString(data, {
prefix: "Failed to execute 'atob'",
context: "Argument 1",
});
const uint8Array = forgivingBase64Decode(data);
const result = [...uint8Array]
.map((byte) => String.fromCharCode(byte))
.join("");
return result;
}
/**
* @param {string} data
* @returns {string}
*/
function btoa(data) {
const prefix = "Failed to execute 'btoa'";
webidl.requiredArguments(arguments.length, 1, { prefix });
data = webidl.converters.DOMString(data, {
prefix,
context: "Argument 1",
});
const byteArray = [...data].map((char) => {
const charCode = char.charCodeAt(0);
if (charCode > 0xff) {
throw new DOMException(
"The string to be encoded contains characters outside of the Latin1 range.",
"InvalidCharacterError",
);
}
return charCode;
});
return forgivingBase64Encode(Uint8Array.from(byteArray));
}
window.__bootstrap.base64 = {
atob,
btoa,
};
})(globalThis);