1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-25 16:49:18 -05:00
denoland-deno/std/encoding/base64.ts

42 lines
1,012 B
TypeScript
Raw Normal View History

2020-05-24 09:10:01 -04:00
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
/**
* Converts given data with base64 encoding
* @param data input to encode
*/
export function encode(data: string | ArrayBuffer): string {
if (typeof data === "string") {
2020-07-07 14:43:11 -04:00
return btoa(data);
2020-05-24 09:10:01 -04:00
} else {
const d = new Uint8Array(data);
let dataString = "";
for (let i = 0; i < d.length; ++i) {
dataString += String.fromCharCode(d[i]);
}
2020-07-07 14:43:11 -04:00
return btoa(dataString);
2020-05-24 09:10:01 -04:00
}
}
/**
* Converts given base64 encoded data back to original
* @param data input to decode
*/
export function decode(data: string): ArrayBuffer {
const binaryString = decodeString(data);
const binary = new Uint8Array(binaryString.length);
for (let i = 0; i < binary.length; ++i) {
binary[i] = binaryString.charCodeAt(i);
}
return binary.buffer;
}
/**
* Decodes data assuming the output is in string type
* @param data input to decode
*/
export function decodeString(data: string): string {
2020-07-07 14:43:11 -04:00
return atob(data);
2020-05-24 09:10:01 -04:00
}