Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { describe, expect, it } from "vitest";
import { decodeBase64, encodeBase64 } from "./base64";

describe("base64 encoding", () => {
it("encodes large byte arrays without exceeding the call stack", () => {
const bytes = new Uint8Array(200_000);
bytes.fill(65);

expect(() => encodeBase64(bytes)).not.toThrow();
expect(decodeBase64(encodeBase64(bytes))).toEqual(bytes);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
export function encodeBase64(bytes: Uint8Array): string {
return btoa(String.fromCharCode.apply(null, Array.from(bytes)));
let binary = "";
const chunkSize = 0x8000;

for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}

return btoa(binary);
}

export function decodeBase64(base64: string): Uint8Array {
Expand Down