aboutsummaryrefslogtreecommitdiff
path: root/src/gleam_stdlib.js
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2021-09-07 19:53:09 +0100
committerLouis Pilfold <louis@lpil.uk>2021-09-07 19:53:09 +0100
commitf869915d92bf90c385ddaaa6c059b25784364ab0 (patch)
treec348709049004310d94f5160bc16eb19a05a44de /src/gleam_stdlib.js
parent43dad5dbfd3ef19257cbf8e781b0e8e0697b6b95 (diff)
downloadgleam_stdlib-f869915d92bf90c385ddaaa6c059b25784364ab0.tar.gz
gleam_stdlib-f869915d92bf90c385ddaaa6c059b25784364ab0.zip
base64 encode in JS
Diffstat (limited to 'src/gleam_stdlib.js')
-rw-r--r--src/gleam_stdlib.js44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/gleam_stdlib.js b/src/gleam_stdlib.js
index 3658142..d26a4b6 100644
--- a/src/gleam_stdlib.js
+++ b/src/gleam_stdlib.js
@@ -382,3 +382,47 @@ export function parse_query(query) {
return new Error(Nil);
}
}
+
+// From https://developer.mozilla.org/en-US/docs/Glossary/Base64#Solution_2_%E2%80%93_rewrite_the_DOMs_atob()_and_btoa()_using_JavaScript's_TypedArrays_and_UTF-8
+export function encode64(bit_string) {
+ let aBytes = bit_string.buffer;
+ let nMod3 = 2,
+ sB64Enc = "";
+
+ for (let nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
+ nMod3 = nIdx % 3;
+ if (nIdx > 0 && ((nIdx * 4) / 3) % 76 === 0) {
+ sB64Enc += "\r\n";
+ }
+ nUint24 |= aBytes[nIdx] << ((16 >>> nMod3) & 24);
+ if (nMod3 === 2 || aBytes.length - nIdx === 1) {
+ sB64Enc += String.fromCharCode(
+ uint6ToB64((nUint24 >>> 18) & 63),
+ uint6ToB64((nUint24 >>> 12) & 63),
+ uint6ToB64((nUint24 >>> 6) & 63),
+ uint6ToB64(nUint24 & 63)
+ );
+ nUint24 = 0;
+ }
+ }
+
+ return (
+ sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) +
+ (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "==")
+ );
+}
+
+// From https://developer.mozilla.org/en-US/docs/Glossary/Base64#Solution_2_%E2%80%93_rewrite_the_DOMs_atob()_and_btoa()_using_JavaScript's_TypedArrays_and_UTF-8
+function uint6ToB64(nUint6) {
+ return nUint6 < 26
+ ? nUint6 + 65
+ : nUint6 < 52
+ ? nUint6 + 71
+ : nUint6 < 62
+ ? nUint6 - 4
+ : nUint6 === 62
+ ? 43
+ : nUint6 === 63
+ ? 47
+ : 65;
+}