diff options
author | skdltmxn <supershop@naver.com> | 2020-05-24 22:10:01 +0900 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-05-24 09:10:01 -0400 |
commit | f6e31603563bad38c663494ddec6a363989b5786 (patch) | |
tree | 3059f472cbe2616397d97c3b5eec3fbcbf0b7c2f /std/encoding/base64.ts | |
parent | 2bbe475dbbd46c505cdb2a5e511caadbd63dd1fd (diff) |
feat(std/encoding): add base64 (#5811)
Diffstat (limited to 'std/encoding/base64.ts')
-rw-r--r-- | std/encoding/base64.ts | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/std/encoding/base64.ts b/std/encoding/base64.ts new file mode 100644 index 000000000..2f74c8df0 --- /dev/null +++ b/std/encoding/base64.ts @@ -0,0 +1,41 @@ +// 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") { + return window.btoa(data); + } else { + const d = new Uint8Array(data); + let dataString = ""; + for (let i = 0; i < d.length; ++i) { + dataString += String.fromCharCode(d[i]); + } + + return window.btoa(dataString); + } +} + +/** + * 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 { + return window.atob(data); +} |