const bytesSet = Function.prototype.call.bind(Bytes.prototype.set)
const bytesFill = Function.prototype.call.bind(Bytes.prototype.fill)
const charCodeAt = Function.prototype.call.bind(String.prototype.charCodeAt)
+const fromCharCode = Function.prototype.call.bind(String.fromCharCode)
function get<T> (target: object, key: PropertyKey): (this: unknown) => T {
const found = Object.getOwnPropertyDescriptor(target, key)
NIBBLE[UPPER[i]] = i
}
+/** 0-9a-f for a valid hex digit 0..15 */
+function hexcode (c: number): number {
+ const isDigit = (c - 10) >> 31
+ const digit = (c + 0x30) & isDigit
+ const alpha = (c + 0x57) & ~isDigit
+ return digit | alpha
+}
+
+/** 0..15 for a valid hex char code, else set bit 9 which is past 0xff */
+function nibble (c: number): number {
+ const isDigit = ((0x2f - c) & (c - 0x3a)) >> 31
+ const digit = (c - 0x30) & isDigit
+ c |= 0x20
+ const isAlpha = ((0x60 - c) & (c - 0x67)) >> 31
+ const alpha = (c - 0x57) & isAlpha
+ const valid = ~(isDigit | isAlpha)
+ return digit | alpha | valid
+}
+
/** Lowercase hexadecimal encoding of `bytes`. */
export function bytesToHex (bytes: Uint8Array): string {
const byteLength = getByteLength(bytes)
let hex = ''
for (let i = 0; i < byteLength; i++) {
const byte = bytes[i]
- hex += LOWER[byte >> 4] + LOWER[byte & 15]
+ hex += fromCharCode(hexcode(byte >> 4), hexcode(byte & 15))
}
return hex
}
/**
- * Decodes hex string to Bytes..
+ * Decodes hex string to Bytes.
*/
function hexToBytes (hex: string): Bytes {
const length = hex.length
const bytes = new Bytes(length >> 1)
let d = 0
for (let i = 0, b = 0; i < length; i += 2, b++) {
- const hi = charCodeAt(hex, i)
- const lo = charCodeAt(hex, i + 1)
+ const hi = nibble(charCodeAt(hex, i))
+ const lo = nibble(charCodeAt(hex, i + 1))
d |= hi | lo
- bytes[b] = (NIBBLE[hi] << 4) | NIBBLE[lo]
+ bytes[b] = (hi << 4) | lo
}
- if (d & 0x100) {
+ if (d >> 4) {
fill(bytes, 0)
throw new TypeError('Invalid hexadecimal character')
}