Helpers for 256/512 hashing (#1303)

* Helpers for 256/512 hashing

* Adjust u8aToU8a (u8a-only check earlier)

* Fix export

* Simplify

* revert
This commit is contained in:
Jaco
2021-12-09 10:10:51 +02:00
committed by GitHub
parent 000d097de2
commit 7955022ce5
13 changed files with 93 additions and 102 deletions
+19 -16
View File
@@ -4,10 +4,16 @@
import { u8aToU8a } from '.';
describe('u8aToU8a', (): void => {
it('returns an empty Uint8Array when null provided', (): void => {
it('returns an empty Uint8Array when null/undefined/"" provided', (): void => {
expect(
u8aToU8a(null)
).toHaveLength(0);
expect(
u8aToU8a()
).toHaveLength(0);
expect(
u8aToU8a('')
).toHaveLength(0);
});
it('returns a Uint8Array (hex input)', (): void => {
@@ -24,14 +30,6 @@ describe('u8aToU8a', (): void => {
).toEqual(new Uint8Array([97, 98, 99, 100, 101, 32, 102, 103, 104, 105, 106]));
});
it('returns a Uint8Array (buffer input)', (): void => {
expect(
u8aToU8a(Buffer.from('80000a', 'hex'))
).toEqual(
new Uint8Array([128, 0, 10])
);
});
it('creates from Array', (): void => {
expect(
u8aToU8a([128, 0, 10, 11, 12])
@@ -46,20 +44,25 @@ describe('u8aToU8a', (): void => {
).toEqual(
new Uint8Array([1, 2, 3, 128, 0, 10, 11, 12])
);
});
it('returns a Uint8Array as-is (u8a input)', (): void => {
expect(
u8aToU8a(new Uint8Array([128, 0, 10]))
u8aToU8a(Buffer.from('80000a', 'hex'))
).toEqual(
new Uint8Array([128, 0, 10])
);
});
it('fails to create from unknown typed values', (): void => {
it('returns a Uint8Array as-is (u8a input)', (): void => {
const input = new Uint8Array([128, 0, 10]);
expect(
u8aToU8a(input) === input
).toEqual(true);
});
it('creates unknowns via string conversion', (): void => {
expect(
// this is where completely invalid data is being passed
() => u8aToU8a(123 as unknown as Uint8Array)
).toThrow('Unable to convert 123 (typeof number) to a Uint8Array');
u8aToU8a(123 as unknown as Uint8Array)
).toEqual(new Uint8Array([49, 50, 51]));
});
});
+9 -15
View File
@@ -3,11 +3,9 @@
import type { U8aLike } from '../types';
import { assert } from '../assert';
import { hexToU8a } from '../hex/toU8a';
import { isBuffer } from '../is/buffer';
import { isHex } from '../is/hex';
import { isString } from '../is/string';
import { isU8a } from '../is/u8a';
import { stringToU8a } from '../string/toU8a';
@@ -27,17 +25,13 @@ import { stringToU8a } from '../string/toU8a';
* ```
*/
export function u8aToU8a (value?: U8aLike | null): Uint8Array {
if (!value) {
return new Uint8Array();
} else if (isHex(value)) {
return hexToU8a(value);
} else if (isString(value)) {
return stringToU8a(value);
} else if (Array.isArray(value) || isBuffer(value)) {
return new Uint8Array(value);
}
assert(isU8a(value), () => `Unable to convert ${value.toString()} (typeof ${typeof value}) to a Uint8Array`);
return value;
return !value
? new Uint8Array()
: Array.isArray(value) || isBuffer(value)
? new Uint8Array(value)
: isU8a(value)
? value
: isHex(value)
? hexToU8a(value)
: stringToU8a(value);
}