Buffer short-circuit (onlky convert when non-Uint8Array) (#1499)

This commit is contained in:
Jaco
2022-05-24 17:27:47 +03:00
committed by GitHub
parent 5ada180d66
commit b20df563ce
4 changed files with 17 additions and 22 deletions
@@ -57,6 +57,14 @@ describe('compactFromU8a', (): void => {
).toEqual([7, new BN('5af3107a4000', 16)]);
});
it('decodes an actual value (Buffer)', (): void => {
expect(
compactFromU8a(
Buffer.from('0b00407a10f35a', 'hex')
)
).toEqual([7, new BN('5af3107a4000', 16)]);
});
it('decodes an actual value', (): void => {
expect(
compactFromU8a(
+3 -3
View File
@@ -20,7 +20,7 @@ const decoder = new TextDecoder('utf-8');
* ```
*/
export function u8aToString (value?: Uint8Array | null): string {
return !value?.length
? ''
: decoder.decode(value);
return value
? decoder.decode(value)
: '';
}
+4 -14
View File
@@ -39,28 +39,18 @@ describe('u8aToU8a', (): void => {
});
it('creates from a Buffer', (): void => {
const input = Buffer.from([1, 2, 3, 128, 0, 10, 11, 12]);
const output = u8aToU8a(input);
expect(
typeof input.readDoubleLE
).toEqual('function');
expect(
typeof (output as Buffer).readDoubleLE
).toEqual('undefined');
expect(
output
u8aToU8a(Buffer.from([1, 2, 3, 128, 0, 10, 11, 12])).buffer
).toEqual(
new Uint8Array([1, 2, 3, 128, 0, 10, 11, 12])
new Uint8Array([1, 2, 3, 128, 0, 10, 11, 12]).buffer
);
});
it('creates from a Buffer (hex)', (): void => {
expect(
u8aToU8a(Buffer.from('80000a', 'hex'))
u8aToU8a(Buffer.from('80000a', 'hex')).buffer
).toEqual(
new Uint8Array([128, 0, 10])
new Uint8Array([128, 0, 10]).buffer
);
});
+2 -5
View File
@@ -26,13 +26,10 @@ import { stringToU8a } from '../string/toU8a';
*/
export function u8aToU8a (value?: U8aLike | null): Uint8Array {
return isU8a(value)
// under Node, Buffer implements Uint8Array, check it first
? isBuffer(value)
? new Uint8Array(value)
: value
? value
: isHex(value)
? hexToU8a(value)
: Array.isArray(value)
: isBuffer(value) || Array.isArray(value)
? new Uint8Array(value)
: stringToU8a(value);
}