All files / kernel-utils/src hex.ts

100% Statements 17/17
100% Branches 2/2
100% Functions 2/2
100% Lines 17/17

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                                  101x 101x 3906x 3906x   101x                       64x 64x 64x 64x 64x 64x 64x 1197x 1197x 1197x 1197x   64x    
import { assert } from '@endo/errors';
 
// XXX TODO: The following two hex conversion functions are placeholders. In
// particular, they're not as paranoid as they ought to be, which I'll
// rationalize by observing that we only use them on data of strictly internal
// provenance. However, I'm quite prepared to bet we can find any number of better,
// off-the-shelf packages in NPM that we could just use, and one of them
// probably should be substituted.
 
/**
 * Convert a Uint8Array into a hex string.
 *
 * @param arr - The bytes to convert.
 *
 * @returns `arr` represented as a hex string.
 */
export function toHex(arr: Uint8Array): string {
  let result = '';
  for (const byte of arr) {
    const byteHex = byte.toString(16);
    result += byteHex.length === 1 ? `0${byteHex}` : byteHex;
  }
  return result;
}
 
/**
 * Convert a hex string into a 32-byte fixed-length Uint8Array.
 *
 * @param str - The hex string to convert.  If shorter than the 64 characters
 * needed to encode 32 bytes, remaining bytes in the result will be 0.
 *
 * @returns the bytes described by `str`.
 */
export function fromHex(str: string): Uint8Array {
  const len = str.length;
  assert(len <= 64);
  const resultLen = len / 2;
  const bytes = new Uint8Array(32);
  let inIdx = 0;
  let outIdx = 0;
  while (outIdx < resultLen) {
    const digits = str.slice(inIdx, inIdx + 2);
    bytes[outIdx] = parseInt(digits, 16);
    outIdx += 1;
    inIdx += 2;
  }
  return bytes;
}