Browse Source

use typedarray, about 15% faster

master
Dominic Tarr 11 years ago
parent
commit
3deb9b4365
  1. 28
      lib/b64.js

28
lib/b64.js

@ -3,6 +3,10 @@
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function decode (c) {
return indexOf(lookup, c)
}
function b64ToByteArray(b64) {
var i, j, l, tmp, placeHolders, arr;
@ -19,25 +23,31 @@
placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;
// base64 is 4/3 + up to two characters of the original data
arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders);
arr = new Uint8Array(b64.length * 3 / 4 - placeHolders);
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length;
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (indexOf(lookup, b64.charAt(i)) << 18) | (indexOf(lookup, b64.charAt(i + 1)) << 12) | (indexOf(lookup, b64.charAt(i + 2)) << 6) | indexOf(lookup, b64.charAt(i + 3));
arr.push((tmp & 0xFF0000) >> 16);
arr.push((tmp & 0xFF00) >> 8);
arr.push(tmp & 0xFF);
tmp = (decode(b64.charAt(i)) << 18) | (indexOf(lookup, b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3));
push((tmp & 0xFF0000) >> 16);
push((tmp & 0xFF00) >> 8);
push(tmp & 0xFF);
}
if (placeHolders === 2) {
tmp = (indexOf(lookup, b64.charAt(i)) << 2) | (indexOf(lookup, b64.charAt(i + 1)) >> 4);
arr.push(tmp & 0xFF);
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4);
push(tmp & 0xFF);
} else if (placeHolders === 1) {
tmp = (indexOf(lookup, b64.charAt(i)) << 10) | (indexOf(lookup, b64.charAt(i + 1)) << 4) | (indexOf(lookup, b64.charAt(i + 2)) >> 2);
arr.push((tmp >> 8) & 0xFF);
arr.push(tmp & 0xFF);
push((tmp >> 8) & 0xFF);
push(tmp & 0xFF);
}
return arr;

Loading…
Cancel
Save