Skip to content

Commit

Permalink
fix: remove buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
diegodelrieu committed Nov 9, 2023
1 parent e94ed10 commit f8f1caa
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
34 changes: 34 additions & 0 deletions __tests__/utils/encode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { atobUniversal, btoaUniversal } from '../../src/utils/encode';

describe('atobUniversal and btoaUniversal functions', () => {
test('atobUniversal should decode base64 string to Uint8Array', () => {
const base64 = 'SGVsbG8sIFdvcmxkIQ=='; // "Hello, World!" in base64
const expected = new Uint8Array([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]);
const result = atobUniversal(base64);
expect(result).toEqual(expected);
});

test('btoaUniversal should encode ArrayBuffer to base64 string', () => {
const { buffer } = new Uint8Array([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]);

const expected = 'SGVsbG8sIFdvcmxkIQ=='; // "Hello, World!" in base64
const result = btoaUniversal(buffer);
expect(result).toBe(expected);
});

test('should round trip encode/decode correctly', () => {
const originalString = 'Hello, World!';
const { buffer } = new TextEncoder().encode(originalString);
const encoded = btoaUniversal(buffer);
const decoded = new TextDecoder().decode(atobUniversal(encoded));
expect(decoded).toBe(originalString);
});

test('should handle empty string', () => {
const emptyBuffer = new ArrayBuffer(0);
const encoded = btoaUniversal(emptyBuffer);
expect(encoded).toBe('');
const decoded = atobUniversal(encoded);
expect(decoded).toEqual(new Uint8Array([]));
});
});
6 changes: 4 additions & 2 deletions src/utils/encode.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { base64 } from '@scure/base';

/* eslint-disable no-param-reassign */
export const IS_BROWSER = typeof window !== 'undefined';

Expand Down Expand Up @@ -39,14 +41,14 @@ export function stringToArrayBuffer(str: string): Uint8Array {
* Convert string to array buffer (browser and node compatible)
*/
export function atobUniversal(a: string): Uint8Array {
return IS_BROWSER ? utf8ToArray(atob(a)) : Buffer.from(a, 'base64');
return base64.decode(a);
}

/**
* Convert array buffer to string (browser and node compatible)
*/
export function btoaUniversal(b: ArrayBuffer): string {
return IS_BROWSER ? btoa(arrayBufferToString(b)) : Buffer.from(b).toString('base64');
return base64.encode(new Uint8Array(b));
}

/**
Expand Down

0 comments on commit f8f1caa

Please sign in to comment.