Skip to content
Permalink
Browse files
refactor(base64): factor out binary string <-> array buffer conversion (
  • Loading branch information
raphinesse committed Oct 17, 2021
1 parent d83f8d8 commit 7c2f830418f80a773da04bec0fd0c282556bb41d
Showing 1 changed file with 12 additions and 10 deletions.
@@ -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) {
@@ -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 7c2f830

Please sign in to comment.