@discoveryjs/discovery
Version:
Frontend framework for rapid data (JSON) analysis, shareable serverless reports and dashboards
74 lines (73 loc) • 2.26 kB
JavaScript
const encoder = /* @__PURE__ */ new TextEncoder();
const decoder = /* @__PURE__ */ new TextDecoder();
const [base64encodeMap, base64decodeMap] = /* @__PURE__ */ (() => {
const base64alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const base64encodeMap2 = new Uint8Array(64);
const base64decodeMap2 = new Uint8Array(256);
for (let i = 0; i < base64alphabet.length; i++) {
const charCode = base64alphabet.charCodeAt(i);
base64decodeMap2[charCode] = i;
base64encodeMap2[i] = charCode;
}
return [base64encodeMap2, base64decodeMap2];
})();
export function encode(input) {
return decoder.decode(encodeBytes(input));
}
export function encodeBytes(input) {
if (typeof input === "string") {
input = encoder.encode(input);
}
const output = new Uint8Array(Math.ceil(input.length / 3) * 4);
let outputIdx = 0;
let buffer = 0;
let bufferSize = 0;
for (let i = 0; i < input.length; i++) {
buffer = buffer << 8 | input[i];
bufferSize += 8;
while (bufferSize >= 6) {
const bits = buffer >> (bufferSize -= 6);
output[outputIdx++] = base64encodeMap[bits];
buffer -= bits << bufferSize;
}
}
if (bufferSize !== 0) {
output[outputIdx++] = base64encodeMap[buffer << 6 - bufferSize];
}
for (; outputIdx < output.length; ) {
output[outputIdx++] = "=".charCodeAt(0);
}
return output;
}
export function decode(input) {
return decoder.decode(decodeBytes(input));
}
export function decodeBytes(input) {
let inputSize = input.length;
while (inputSize > 0 && input[inputSize - 1] === "=") {
inputSize--;
}
const output = new Uint8Array(3 * Math.ceil(inputSize / 4));
let outputIndex = 0;
let buffer = 0;
let bufferSize = 0;
for (let i = 0; i < inputSize; i++) {
buffer = buffer << 6 | base64decodeMap[input.charCodeAt(i) & 255];
bufferSize += 6;
if (bufferSize > 8) {
const bits = buffer >> (bufferSize -= 8);
output[outputIndex++] = bits;
buffer -= bits << bufferSize;
}
}
if (bufferSize !== 0) {
output[outputIndex++] = buffer;
}
return output.subarray(
0,
// output size:
// (length / 4) * 3 +
(inputSize >> 2) * 3 + // (length % 4) * 6 / 8
(inputSize % 4 * 6 >> 3)
);
}