From b6cd83dc361f8715db8e316d1c40de3edb44b032 Mon Sep 17 00:00:00 2001 From: Mohit Pal Date: Tue, 14 May 2024 01:43:39 +0530 Subject: [PATCH 1/2] add ascii encoding conversion --- index.d.ts | 13 +++++++++++++ index.js | 16 ++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/index.d.ts b/index.d.ts index a9a91b7..9f5d15a 100644 --- a/index.d.ts +++ b/index.d.ts @@ -249,3 +249,16 @@ console.log(hexToUint8Array('48656c6c6f')); ``` */ export function hexToUint8Array(hexString: string): Uint8Array; + +/** +Convert a string to a `Uint8Array` using ASCII encoding. + +@example +``` +import { asciiStringToUint8Array } from 'uint8array-extras'; + +console.log(asciiStringToUint8Array('Hello')); +//=> Uint8Array [72, 101, 108, 108, 111] +``` +*/ +export function asciiStringToUint8Array(string: string): Uint8Array; \ No newline at end of file diff --git a/index.js b/index.js index acf22b4..8389c42 100644 --- a/index.js +++ b/index.js @@ -220,3 +220,19 @@ export function hexToUint8Array(hexString) { return bytes; } + +export function asciiStringToUint8Array(string) { + assertString(string); + + const bytes = new Uint8Array(string.length); + + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code > 127) { + throw new Error(`Non-ASCII character detected at position ${i}`); + } + bytes[i] = code; + } + + return bytes; +} \ No newline at end of file From b1e624fca75040917afd7acaa3109f941fcecade Mon Sep 17 00:00:00 2001 From: Mohit Pal Date: Tue, 14 May 2024 01:52:50 +0530 Subject: [PATCH 2/2] ascii encoding --- index.d.ts | 2 +- index.js | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/index.d.ts b/index.d.ts index 9f5d15a..9d130f2 100644 --- a/index.d.ts +++ b/index.d.ts @@ -261,4 +261,4 @@ console.log(asciiStringToUint8Array('Hello')); //=> Uint8Array [72, 101, 108, 108, 111] ``` */ -export function asciiStringToUint8Array(string: string): Uint8Array; \ No newline at end of file +export function asciiStringToUint8Array(string: string): Uint8Array; diff --git a/index.js b/index.js index 8389c42..cae5621 100644 --- a/index.js +++ b/index.js @@ -223,16 +223,16 @@ export function hexToUint8Array(hexString) { export function asciiStringToUint8Array(string) { assertString(string); - + const bytes = new Uint8Array(string.length); - + for (let i = 0; i < string.length; i++) { - const code = string.charCodeAt(i); - if (code > 127) { - throw new Error(`Non-ASCII character detected at position ${i}`); - } - bytes[i] = code; + const code = string.charCodeAt(i); + if (code > 127) { + throw new Error(`Non-ASCII character detected at position ${i}`); + } + bytes[i] = code; } - + return bytes; -} \ No newline at end of file +}