Skip to content

Commit

Permalink
Merge pull request brix#71 from pkaminski/fast-base64
Browse files Browse the repository at this point in the history
Improve enc.Base64 parse performance by x10.
  • Loading branch information
evanvosberg authored Oct 17, 2016
2 parents 8940297 + 2f7fa2b commit 48b77cc
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions src/enc-base64.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,32 +73,43 @@
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
var reverseMap = this._reverseMap;

if (!reverseMap) {
reverseMap = this._reverseMap = [];
for (var j = 0; j < map.length; j++) {
reverseMap[map.charCodeAt(j)] = j;
}
}

// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
if (paddingIndex !== -1) {
base64StrLength = paddingIndex;
}
}

// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
var bitsCombined = bits1 | bits2;
words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return parseLoop(base64Str, base64StrLength, reverseMap);

return WordArray.create(words, nBytes);
},

_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};

function parseLoop(base64Str, base64StrLength, reverseMap) {
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
}
}());

0 comments on commit 48b77cc

Please sign in to comment.