Skip to content

Commit

Permalink
refactor: optimize and deprecate stringToArrayBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
NguyenTuanCanh authored and penovicp committed Nov 2, 2023
1 parent 29f7eb7 commit 972f8ba
Showing 1 changed file with 14 additions and 15 deletions.
29 changes: 14 additions & 15 deletions src/utils/encode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,28 @@ export function arrayBufferToString(array: ArrayBuffer): string {
}

/**
* Convert string to array buffer
* Convert utf8-string to Uint8Array
*
* *[internal usage]*
*/
export function stringToArrayBuffer(s: string): Uint8Array {
return Uint8Array.from(s, (c) => c.charCodeAt(0));
export function utf8ToArray(str: string): Uint8Array {
return new TextEncoder().encode(str);
}

/**
* Convert utf8-string to Uint8Array
*
* @deprecated equivalent to 'utf8ToArray', alias will be removed
*/
export function stringToArrayBuffer(str: string): Uint8Array {
return utf8ToArray(str);
}

/**
* Convert string to array buffer (browser and node compatible)
*/
export function atobUniversal(a: string): Uint8Array {
return IS_BROWSER ? stringToArrayBuffer(atob(a)) : Buffer.from(a, 'base64');
return IS_BROWSER ? utf8ToArray(atob(a)) : Buffer.from(a, 'base64');
}

/**
Expand All @@ -45,7 +54,7 @@ export function btoaUniversal(b: ArrayBuffer): string {
* @returns format: hex-string
*/
export function buf2hex(buffer: Uint8Array) {
return [...buffer].map((x) => x.toString(16).padStart(2, '0')).join('');
return buffer.reduce((r, x) => r + x.toString(16).padStart(2, '0'), '');
}

/**
Expand Down Expand Up @@ -124,16 +133,6 @@ export function sanitizeHex(hex: string): string {
return hex;
}

/**
* Convert utf8-string to Uint8Array
*
* Implemented using TextEncoder to make it isomorphic
* @param str utf8-string
*/
export function utf8ToArray(str: string): Uint8Array {
return new TextEncoder().encode(str);
}

/**
* String transformation util
*
Expand Down

0 comments on commit 972f8ba

Please sign in to comment.