Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/src/lib/libbase64.js
4150 views
1
/**
2
* @license
3
* Copyright 2020 The Emscripten Authors
4
* SPDX-License-Identifier: MIT
5
*/
6
7
addToLibrary({
8
// Decodes a _known valid_ base64 string (without validation) and returns it as a new Uint8Array.
9
// Benchmarked to be around 5x faster compared to a simple
10
// "Uint8Array.from(atob(b64), c => c.charCodeAt(0))" (TODO: perhaps use this form in -Oz builds?)
11
$base64Decode__postset: `
12
// Precreate a reverse lookup table from chars
13
// "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" back to
14
// bytes to make decoding fast.
15
for (var base64ReverseLookup = new Uint8Array(123/*'z'+1*/), i = 25; i >= 0; --i) {
16
base64ReverseLookup[48+i] = 52+i; // '0-9'
17
base64ReverseLookup[65+i] = i; // 'A-Z'
18
base64ReverseLookup[97+i] = 26+i; // 'a-z'
19
}
20
base64ReverseLookup[43] = 62; // '+'
21
base64ReverseLookup[47] = 63; // '/'
22
`,
23
$base64Decode__docs: '/** @noinline */',
24
$base64Decode: (b64) => {
25
#if JS_BASE64_API
26
return Uint8Array.fromBase64(b64);
27
#else
28
#if ENVIRONMENT_MAY_BE_NODE
29
if (ENVIRONMENT_IS_NODE) {
30
var buf = Buffer.from(b64, 'base64');
31
return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
32
}
33
#endif
34
35
#if ASSERTIONS
36
assert(b64.length % 4 == 0);
37
#endif
38
var b1, b2, i = 0, j = 0, bLength = b64.length;
39
var output = new Uint8Array((bLength*3>>2) - (b64[bLength-2] == '=') - (b64[bLength-1] == '='));
40
for (; i < bLength; i += 4, j += 3) {
41
b1 = base64ReverseLookup[b64.charCodeAt(i+1)];
42
b2 = base64ReverseLookup[b64.charCodeAt(i+2)];
43
output[j] = base64ReverseLookup[b64.charCodeAt(i)] << 2 | b1 >> 4;
44
output[j+1] = b1 << 4 | b2 >> 2;
45
output[j+2] = b2 << 6 | base64ReverseLookup[b64.charCodeAt(i+3)];
46
}
47
return output;
48
#endif
49
},
50
});
51
52