Skip to content

Commit

Permalink
refactor(base64): factor out binary string <-> array buffer conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
raphinesse committed Oct 17, 2021
1 parent d83f8d8 commit 4c4eea9
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/common/base64.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,15 @@
var base64 = exports;

base64.fromArrayBuffer = function (arrayBuffer) {
var array = new Uint8Array(arrayBuffer);
return btoa(bytesToBinaryString(array));
return btoa(bufferToBinaryString(arrayBuffer));
};

base64.toArrayBuffer = function (str) {
var decodedStr = atob(str);
var arrayBuffer = new ArrayBuffer(decodedStr.length);
var array = new Uint8Array(arrayBuffer);
for (var i = 0, len = decodedStr.length; i < len; i++) {
array[i] = decodedStr.charCodeAt(i);
}
return arrayBuffer;
return binaryStringToBuffer(atob(str));
};

function bytesToBinaryString (bytes) {
function bufferToBinaryString (buffer) {
var bytes = new Uint8Array(buffer);
var CHUNK_SIZE = 1 << 15;
var string = '';
for (var i = 0; i < bytes.length; i += CHUNK_SIZE) {
Expand All @@ -45,3 +39,11 @@ function bytesToBinaryString (bytes) {
}
return string;
}

function binaryStringToBuffer (binaryString) {
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < bytes.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}

0 comments on commit 4c4eea9

Please sign in to comment.