All files / src/common encoding-hex.ts

85.41% Statements 41/48
36.36% Branches 4/11
77.77% Functions 7/9
86.11% Lines 31/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5768x 68x   68x   68x 17408x     68x 2307x   2307x   2307x 2307x 56082x 56082x   2307x     68x 1709x 53159x 1709x     68x         68x 152x     152x     68x 1152x 1152x     152x   68x   68x 35x   68x 4x 4x    
import { IntegerType, intToBigInt } from './ints';
import { bytesToUtf8 } from './encoding-utf8';
 
const byteToHexCache: string[] = new Array(0xff);
 
for (let n = 0; n <= 0xff; ++n) {
  byteToHexCache[n] = n.toString(16).padStart(2, '0');
}
 
export function hexToBytes(hex: string): Uint8Array {
  Iif (typeof hex !== 'string')
    throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
  Iif (hex.length % 2)
    throw new Error(`hexToBytes: received invalid unpadded hex, got: ${hex.length}`);
  const array = new Uint8Array(hex.length / 2);
  for (let i = 0; i < array.length; i++) {
    const j = i * 2;
    array[i] = Number.parseInt(hex.slice(j, j + 2), 16);
  }
  return array;
}
 
export function bytesToHex(uint8a: Uint8Array) {
  const hexOctets = new Array(uint8a.length);
  for (let i = 0; i < uint8a.length; ++i) hexOctets[i] = byteToHexCache[uint8a[i]];
  return hexOctets.join('');
}
 
export function numberToHex(num: number | bigint): string {
  const hex = num.toString(16);
  return hex.length & 1 ? `0${hex}` : hex;
}
 
export function hexToBigInt(hex: string): bigint {
  Iif (typeof hex !== 'string')
    throw new TypeError('hexToNumber: expected string, got ' + typeof hex);
  // Big Endian
  return BigInt(`0x${hex}`);
}
 
export const intToHexString = (integer: IntegerType, lengthBytes = 8): string => {
  const value = typeof integer === 'bigint' ? integer : intToBigInt(integer, false);
  return value.toString(16).padStart(lengthBytes * 2, '0');
};
 
export const hexStringToInt = (hexString: string): number => parseInt(hexString, 16);
 
export const hexToJSON = (hex: string) => JSON.parse(bytesToUtf8(hexToBytes(hex)));
 
export const ensureHexBytes = (bytesOrHex: string | Uint8Array): Uint8Array =>
  typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex;
 
export const cleanHex = (hexMaybePrefixed: string): string => {
  Iif (!hexMaybePrefixed.startsWith('0x')) return hexMaybePrefixed;
  return hexMaybePrefixed.replace('0x', '');
};