UNPKG

1.2 kBJavaScriptView Raw
1import { hexToU8a } from '../hex/toU8a.js';
2import { isBuffer } from '../is/buffer.js';
3import { isHex } from '../is/hex.js';
4import { isU8a } from '../is/u8a.js';
5import { stringToU8a } from '../string/toU8a.js';
6/**
7 * @name u8aToU8a
8 * @summary Creates a Uint8Array value from a Uint8Array, Buffer, string or hex input.
9 * @description
10 * `null` or `undefined` inputs returns a `[]` result, Uint8Array values returns the value, hex strings returns a Uint8Array representation.
11 * @example
12 * <BR>
13 *
14 * ```javascript
15 * import { u8aToU8a } from '@polkadot/util';
16 *
17 * u8aToU8a(new Uint8Array([0x12, 0x34]); // => Uint8Array([0x12, 0x34])
18 * u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34])
19 * ```
20 */
21export function u8aToU8a(value) {
22 return isU8a(value)
23 // NOTE isBuffer needs to go here since it actually extends
24 // Uint8Array on Node.js environments, so all Buffer are Uint8Array,
25 // but Uint8Array is not Buffer
26 ? isBuffer(value)
27 ? new Uint8Array(value)
28 : value
29 : isHex(value)
30 ? hexToU8a(value)
31 : Array.isArray(value)
32 ? new Uint8Array(value)
33 : stringToU8a(value);
34}
\No newline at end of file