All files / src/utility utilityHelpers.buffer.ts

38.88% Statements 7/18
19.04% Branches 4/21
33.33% Functions 1/3
53.84% Lines 7/13

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              50x                             50x         50x   32x 32x 32x 32x  
/**
 * Coerce a value to Buffer if currently encoded as a string or 
 * @param val Buffer or string or number[]. If string, encoding param applies. If number[], Buffer.from constructor is used.
 * @param encoding defaults to 'hex'. Only applies to val of type string
 * @returns input val if it is a Buffer or new Buffer from string val
 * @publicbody
 */
export function asBuffer(val: Buffer | string | number[], encoding?: BufferEncoding): Buffer {
  let b: Buffer
  if (Buffer.isBuffer(val)) b = val
  else if (typeof val === 'string') b = Buffer.from(val, encoding ?? 'hex')
  else b = Buffer.from(val)
  return b
}
 
/**
 * Coerce a value to an encoded string if currently a Buffer or number[]
 * @param val Buffer or string or number[]. If string, encoding param applies. If number[], Buffer.from constructor is used.
 * @param encoding defaults to 'hex'
 * @returns input val if it is a string; or if number[], first converted to Buffer then as Buffer; if Buffer encoded using `encoding`
 * @publicbody
 */
export function asString(val: Buffer | string | number[], encoding?: BufferEncoding): string {
  Iif (Array.isArray(val)) val = Buffer.from(val)
  return Buffer.isBuffer(val) ? val.toString(encoding ?? 'hex') : val
}
 
export function asArray(val: Buffer | string | number[], encoding?: BufferEncoding): number[] {
  let a: number[]
  Iif (Array.isArray(val)) a = val
  else Iif (Buffer.isBuffer(val)) a = Array.from(val)
  else a = Array.from(Buffer.from(val, encoding || 'hex'))
  return a
}