From 4d16d54ff85d84723b8493e6a47caf70becc6660 Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Thu, 20 Sep 2018 15:53:29 -0700 Subject: Add atob() and btoa() (#776) --- js/text_encoding.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'js/text_encoding.ts') diff --git a/js/text_encoding.ts b/js/text_encoding.ts index c8e262f5e..087bbc952 100644 --- a/js/text_encoding.ts +++ b/js/text_encoding.ts @@ -1,4 +1,45 @@ // Copyright 2018 the Deno authors. All rights reserved. MIT license. +import * as base64 from "base64-js"; +import { DenoError, ErrorKind } from "./errors"; + +export function atob(s: string): string { + const rem = s.length % 4; + // base64-js requires length exactly times of 4 + if (rem > 0) { + s = s.padEnd(s.length + (4 - rem), "="); + } + let byteArray; + try { + byteArray = base64.toByteArray(s); + } catch (_) { + throw new DenoError( + ErrorKind.InvalidInput, + "The string to be decoded is not correctly encoded" + ); + } + let result = ""; + for (let i = 0; i < byteArray.length; i++) { + result += String.fromCharCode(byteArray[i]); + } + return result; +} + +export function btoa(s: string): string { + const byteArray = []; + for (let i = 0; i < s.length; i++) { + const charCode = s[i].charCodeAt(0); + if (charCode > 0xff) { + throw new DenoError( + ErrorKind.InvalidInput, + "The string to be encoded contains characters " + + "outside of the Latin1 range." + ); + } + byteArray.push(charCode); + } + const result = base64.fromByteArray(Uint8Array.from(byteArray)); + return result; +} // @types/text-encoding relies on lib.dom.d.ts for some interfaces. We do not // want to include lib.dom.d.ts (due to size) into deno's global type scope. -- cgit v1.2.3