Open History to see the last commit
1import { describe, it, expect } from 'vitest'
2import { arrayBufferToBase64, base64ToArrayBuffer } from '../src/base64'
3
4describe('base64 helpers', () => {
5 it('round-trips bytes through arrayBufferToBase64 and base64ToArrayBuffer', () => {
6 const bytes = new Uint8Array([0, 1, 2, 3, 254, 255, 128, 64, 32])
7 const base64 = arrayBufferToBase64(bytes.buffer)
8 const decoded = new Uint8Array(base64ToArrayBuffer(base64))
9 expect(Array.from(decoded)).toEqual(Array.from(bytes))
10 })
11
12 it('encodes a known string to the expected base64', () => {
13 const bytes = new TextEncoder().encode('hello world')
14 expect(arrayBufferToBase64(bytes.buffer)).toBe('aGVsbG8gd29ybGQ=')
15 })
16
17 it('decodes a known base64 string to the expected bytes', () => {
18 const decoded = new Uint8Array(base64ToArrayBuffer('aGVsbG8gd29ybGQ='))
19 expect(new TextDecoder().decode(decoded)).toBe('hello world')
20 })
21
22 it('handles a multi-megabyte buffer without overflowing the call stack', () => {
23 // 1.5 MiB of pseudo-random bytes — exercises the chunked btoa fallback
24 // when the fast Uint8Array.toBase64 path is unavailable.
25 const size = 1.5 * 1024 * 1024
26 const bytes = new Uint8Array(size)
27 for (let i = 0; i < size; i++) bytes[i] = i & 0xff
28
29 const base64 = arrayBufferToBase64(bytes.buffer)
30 const decoded = new Uint8Array(base64ToArrayBuffer(base64))
31 expect(decoded.length).toBe(size)
32 // Spot-check a few entries rather than comparing the full buffer.
33 expect(decoded[0]).toBe(0)
34 expect(decoded[255]).toBe(255)
35 expect(decoded[size - 1]).toBe((size - 1) & 0xff)
36 })
37})