UNPKG

2.08 kBJavaScriptView Raw
1/*
2 * base64-arraybuffer
3 * https://github.com/niklasvh/base64-arraybuffer
4 *
5 * Copyright (c) 2012 Niklas von Hertzen
6 * Licensed under the MIT license.
7 */
8(function () {
9 'use strict';
10
11 const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
12
13 // Use a lookup table to find the index.
14 const lookup = new Uint8Array(256);
15 for (let i = 0; i < chars.length; i++) {
16 lookup[chars.charCodeAt(i)] = i;
17 }
18
19 exports.encode = function (arraybuffer) {
20 const bytes = new Uint8Array(arraybuffer);
21 let i;
22 const len = bytes.length;
23 let base64 = '';
24
25 for (i = 0; i < len; i += 3) {
26 base64 += chars[bytes[i] >> 2];
27 base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
28 base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
29 base64 += chars[bytes[i + 2] & 63];
30 }
31
32 if (len % 3 === 2) {
33 base64 = `${base64.substring(0, base64.length - 1)}=`;
34 } else if (len % 3 === 1) {
35 base64 = `${base64.substring(0, base64.length - 2)}==`;
36 }
37
38 return base64;
39 };
40
41 exports.decode = function (base64) {
42 let bufferLength = base64.length * 0.75;
43 const len = base64.length; let i; let p = 0;
44 let encoded1; let encoded2; let encoded3; let encoded4;
45
46 if (base64[base64.length - 1] === '=') {
47 bufferLength--;
48 if (base64[base64.length - 2] === '=') {
49 bufferLength--;
50 }
51 }
52
53 const arraybuffer = new ArrayBuffer(bufferLength);
54 const bytes = new Uint8Array(arraybuffer);
55
56 for (i = 0; i < len; i += 4) {
57 encoded1 = lookup[base64.charCodeAt(i)];
58 encoded2 = lookup[base64.charCodeAt(i + 1)];
59 encoded3 = lookup[base64.charCodeAt(i + 2)];
60 encoded4 = lookup[base64.charCodeAt(i + 3)];
61
62 bytes[p++] = encoded1 << 2 | encoded2 >> 4;
63 bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
64 bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
65 }
66
67 return arraybuffer;
68 };
69 }());
70
\No newline at end of file