export const hex = Object.freeze({
/**
- * Convert a hexadecimal string to an ArrayBuffer.
+ * Convert a hexadecimal string to an ArrayBuffer. The result must be at least
+ * one byte and no more than 4 GiB.
*
* @param {string} hex - Hexadecimal number string to convert
* @param {number} [padding=1] - Minimum length of the resulting array padded as necessary with starting 0x00 bytes
*/
toBytes (hex: string, padding: number = 1): Uint8Array<ArrayBuffer> {
if (typeof hex !== 'string' || !/^[0-9a-f]+$/i.test(hex)) {
- throw new TypeError('Invalid string when converting hex to array', { cause: hex })
+ throw new TypeError('Invalid string when converting hex to bytes', { cause: hex })
}
if (typeof padding !== 'number' || padding < 1 || padding > 0xffffffff) {
- throw new TypeError('Invalid padding when converting hex to array', { cause: padding })
+ throw new TypeError('Invalid padding when converting hex to bytes', { cause: padding })
}
if (hex.length & 1) hex = `0${hex}`
const hexArray = hex.match(/.{2}/g)
if (hexArray == null) {
- throw new RangeError('Invalid hex string when converting to array', { cause: hexArray })
+ throw new RangeError('Error converting hex string to bytes', { cause: hexArray })
}
const diff = padding - hexArray.length
const offset = diff & ~(diff >> 31)