Line data Source code
1 : // SPDX-License-Identifier: LGPL-2.1-or-later
2 : /*
3 : * These are the polyfills from Mozilla. It's pretty nasty that
4 : * these weren't in the typed array standardization.
5 : *
6 : * https://developer.mozilla.org/en-US/docs/Glossary/Base64
7 : */
8 :
9 3 : function uint6_to_b64 (x) {
10 1 : return x < 26 ? x + 65 : x < 52 ? x + 71 : x < 62 ? x - 4 : x === 62 ? 43 : x === 63 ? 47 : 65;
11 3 : }
12 :
13 3 : export function base64_encode(data) {
14 3 : if (typeof data === "string")
15 1 : return window.btoa(data);
16 : /* For when the caller has chosen to use ArrayBuffer */
17 3 : if (data instanceof window.ArrayBuffer)
18 1 : data = new window.Uint8Array(data);
19 3 : const length = data.length;
20 3 : let mod3 = 2;
21 3 : let str = "";
22 3 : for (let uint24 = 0, i = 0; i < length; i++) {
23 3 : mod3 = i % 3;
24 3 : uint24 |= data[i] << (16 >>> mod3 & 24);
25 3 : if (mod3 === 2 || length - i === 1) {
26 3 : str += String.fromCharCode(uint6_to_b64(uint24 >>> 18 & 63),
27 3 : uint6_to_b64(uint24 >>> 12 & 63),
28 3 : uint6_to_b64(uint24 >>> 6 & 63),
29 3 : uint6_to_b64(uint24 & 63));
30 3 : uint24 = 0;
31 3 : }
32 3 : }
33 :
34 1 : return str.substring(0, str.length - 2 + mod3) + (mod3 === 2 ? '' : mod3 === 1 ? '=' : '==');
35 3 : }
36 :
37 2 : function b64_to_uint6 (x) {
38 2 : return x > 64 && x < 91
39 2 : ? x - 65
40 2 : : x > 96 && x < 123
41 2 : ? x - 71
42 1 : : x > 47 && x < 58 ? x + 4 : x === 43 ? 62 : x === 47 ? 63 : 0;
43 2 : }
44 :
45 2 : export function base64_decode(str, constructor) {
46 2 : if (constructor === String)
47 1 : return window.atob(str);
48 2 : const ilen = str.length;
49 2 : let eq;
50 2 : for (eq = 0; eq < 3; eq++) {
51 2 : if (str[ilen - (eq + 1)] != '=')
52 2 : break;
53 2 : }
54 2 : const olen = (ilen * 3 + 1 >> 2) - eq;
55 2 : const data = new (constructor || Array)(olen);
56 2 : for (let mod3, mod4, uint24 = 0, oi = 0, ii = 0; ii < ilen; ii++) {
57 2 : mod4 = ii & 3;
58 2 : uint24 |= b64_to_uint6(str.charCodeAt(ii)) << 18 - 6 * mod4;
59 2 : if (mod4 === 3 || ilen - ii === 1) {
60 2 : for (mod3 = 0; mod3 < 3 && oi < olen; mod3++, oi++)
61 2 : data[oi] = uint24 >>> (16 >>> mod3 & 24) & 255;
62 2 : uint24 = 0;
63 2 : }
64 2 : }
65 2 : return data;
66 2 : }
|