UNPKG

2.01 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.hexToU8a = void 0;
4const CHR = '0123456789abcdef';
5const U8 = new Uint8Array(256);
6const U16 = new Uint8Array(256 * 256);
7for (let i = 0, count = CHR.length; i < count; i++) {
8 U8[CHR[i].charCodeAt(0) | 0] = i | 0;
9 if (i > 9) {
10 U8[CHR[i].toUpperCase().charCodeAt(0) | 0] = i | 0;
11 }
12}
13for (let i = 0; i < 256; i++) {
14 const s = i << 8;
15 for (let j = 0; j < 256; j++) {
16 U16[s | j] = (U8[i] << 4) | U8[j];
17 }
18}
19/**
20 * @name hexToU8a
21 * @summary Creates a Uint8Array object from a hex string.
22 * @description
23 * `null` inputs returns an empty `Uint8Array` result. Hex input values return the actual bytes value converted to a Uint8Array. Anything that is not a hex string (including the `0x` prefix) throws an error.
24 * @example
25 * <BR>
26 *
27 * ```javascript
28 * import { hexToU8a } from '@polkadot/util';
29 *
30 * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f])
31 * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
32 * ```
33 */
34function hexToU8a(value, bitLength = -1) {
35 if (!value) {
36 return new Uint8Array();
37 }
38 let s = value.startsWith('0x')
39 ? 2
40 : 0;
41 const decLength = Math.ceil((value.length - s) / 2);
42 const endLength = Math.ceil(bitLength === -1
43 ? decLength
44 : bitLength / 8);
45 const result = new Uint8Array(endLength);
46 const offset = endLength > decLength
47 ? endLength - decLength
48 : 0;
49 for (let i = offset; i < endLength; i++, s += 2) {
50 // The big factor here is actually the string lookups. If we do
51 // HEX_TO_U16[value.substring()] we get an 10x slowdown. In the
52 // same vein using charCodeAt (as opposed to value[s] or value.charAt(s)) is
53 // also the faster operation by at least 2x with the character map above
54 result[i] = U16[(value.charCodeAt(s) << 8) | value.charCodeAt(s + 1)];
55 }
56 return result;
57}
58exports.hexToU8a = hexToU8a;