Add Optional Strict Input Checking to u8aToU8a (#1994)

* fix: add error handling for null and undefined inputs in u8aToU8a function

* fix: update u8aToU8a function to handle null/undefined inputs with strict checking

* docs: update documentation for u8aToU8a
This commit is contained in:
Arjun Porwal
2025-06-30 15:49:42 +05:30
committed by GitHub
parent df044669e2
commit 538359fd49
2 changed files with 18 additions and 6 deletions
+11 -5
View File
@@ -20,23 +20,29 @@ const TESTS: [input: U8aLike | null | undefined, output: Uint8Array][] = [
describe('u8aToU8a', (): void => {
it('returns an empty Uint8Array when null/undefined/"" provided', (): void => {
expect(
u8aToU8a(null)
).toHaveLength(0);
expect(u8aToU8a(null)).toHaveLength(0);
expect(
u8aToU8a()
).toHaveLength(0);
expect(
u8aToU8a('')
).toHaveLength(0);
expect(
u8aToU8a('')
).toEqual(new Uint8Array());
});
it('Throw error on null/undefined values on strict checking', () => {
expect(() => u8aToU8a(undefined, true)).toThrow('u8aToU8a: Expected non-null, non-undefined value');
expect(() => u8aToU8a(null, true)).toThrow('u8aToU8a: Expected non-null, non-undefined value');
});
it('returns a Uint8Array as-is (u8a input)', (): void => {
const input = new Uint8Array([128, 0, 10]);
expect(
u8aToU8a(input) === input
).toEqual(true);
u8aToU8a(input)
).toEqual(input);
});
describe('conversion tests', (): void => {
+7 -1
View File
@@ -14,6 +14,8 @@ import { stringToU8a } from '../string/toU8a.js';
* @summary Creates a Uint8Array value from a Uint8Array, Buffer, string or hex input.
* @description
* `null` or `undefined` inputs returns a `[]` result, Uint8Array values returns the value, hex strings returns a Uint8Array representation.
* If `strict` is true, `null` or `undefined` will throw an error instead of returning an empty array.
* Supports input types: Uint8Array, Buffer, hex string, string, or number array.
* @example
* <BR>
*
@@ -24,7 +26,11 @@ import { stringToU8a } from '../string/toU8a.js';
* u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34])
* ```
*/
export function u8aToU8a (value?: U8aLike | null): Uint8Array {
export function u8aToU8a (value?: U8aLike | null, strict = false): Uint8Array {
if (strict && (value === null || value === undefined)) {
throw new Error('u8aToU8a: Expected non-null, non-undefined value');
}
return isU8a(value)
// NOTE isBuffer needs to go here since it actually extends
// Uint8Array on Node.js environments, so all Buffer are Uint8Array,