Skip to content

Commit

Permalink
Rewrite base64 helpers using atob/btoa.
Browse files Browse the repository at this point in the history
  • Loading branch information
hulkholden committed Oct 26, 2023
1 parent 18aac0d commit de15e25
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 50 deletions.
54 changes: 6 additions & 48 deletions src/base64.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,9 @@
const lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

// TODO: use btoa()/atob() to simplify.

export function encodeArray(arr) {
var t = '';
for (let i = 0; i < arr.length; i += 3) {
var c0 = arr[i + 0];
var c1 = arr[i + 1];
var c2 = arr[i + 2];

// aaaaaabb bbbbcccc ccdddddd
var a = c0 >>> 2;
var b = ((c0 & 3) << 4) | (c1 >>> 4);
var c = ((c1 & 15) << 2) | (c2 >>> 6);
var d = c2 & 63;

if (i + 1 >= arr.length) {
c = 64;
}
if (i + 2 >= arr.length) {
d = 64;
}

t += lookup.charAt(a) + lookup.charAt(b) + lookup.charAt(c) + lookup.charAt(d);
}
return t;
export function encodeArray(bytes) {
const binString = String.fromCodePoint(...bytes);
return btoa(binString);
}

export function decodeArray(str, arr) {
var outi = 0;

for (let i = 0; i < str.length; i += 4) {
var a = lookup.indexOf(str.charAt(i + 0));
var b = lookup.indexOf(str.charAt(i + 1));
var c = lookup.indexOf(str.charAt(i + 2));
var d = lookup.indexOf(str.charAt(i + 3));

var c0 = (a << 2) | (b >>> 4);
var c1 = ((b & 15) << 4) | (c >>> 2);
var c2 = ((c & 3) << 6) | d;

arr[outi++] = c0;
if (c !== 64) {
arr[outi++] = c1;
}
if (d !== 64) {
arr[outi++] = c2;
}
}
export function decodeArray(base64) {
const binString = atob(base64);
return Uint8Array.from(binString, m => m.codePointAt(0));
}
10 changes: 8 additions & 2 deletions src/hardware.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ class Mempack {
}
// Restore from local storage if provided.
if (item && item.data) {
base64.decodeArray(item.data, this.data);
const arr = base64.decodeArray(item.data);
for (let i = 0; i < arr.length && i < this.data.length; i++) {
this.data[i] = arr[i];
}
}
}
}
Expand Down Expand Up @@ -215,7 +218,10 @@ export class Hardware {
const memory = new MemoryRegion(new ArrayBuffer(saveSize));
const saveItem = n64js.getLocalStorageItem('save');
if (saveItem && saveItem.data) {
base64.decodeArray(saveItem.data, memory.u8);
const arr = base64.decodeArray(saveItem.data);
for (let i = 0; i < arr.length && i < memory.u8.length; i++) {
memory.u8[i] = arr[i];
}
}
this.saveMem = memory;
} else {
Expand Down

0 comments on commit de15e25

Please sign in to comment.