Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: optimize hexToBytes #3203

Merged
merged 3 commits into from
Dec 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 30 additions & 12 deletions packages/util/src/bytes.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { getRandomBytesSync } from 'ethereum-cryptography/random.js'
// eslint-disable-next-line no-restricted-imports
import {
bytesToHex as _bytesToUnprefixedHex,
hexToBytes as _unprefixedHexToBytes,
} from 'ethereum-cryptography/utils.js'
import { bytesToHex as _bytesToUnprefixedHex } from 'ethereum-cryptography/utils.js'

import { assertIsArray, assertIsBytes, assertIsHexString } from './helpers.js'
import { isHexPrefixed, isHexString, padToEven, stripHexPrefix } from './internal.js'
Expand All @@ -17,6 +14,34 @@ const BIGINT_0 = BigInt(0)
*/
export const bytesToUnprefixedHex = _bytesToUnprefixedHex

// hexToBytes cache
const hexToBytesMapFirstKey: { [key: string]: number } = {}
const hexToBytesMapSecondKey: { [key: string]: number } = {}

for (let i = 0; i < 16; i++) {
const vSecondKey = i
const vFirstKey = i * 16
const key = i.toString(16).toLowerCase()
hexToBytesMapSecondKey[key] = vSecondKey
hexToBytesMapSecondKey[key.toUpperCase()] = vSecondKey
hexToBytesMapFirstKey[key] = vFirstKey
hexToBytesMapFirstKey[key.toUpperCase()] = vFirstKey
}

/**
* NOTE: only use this function if the string is even, and only consists of hex characters
* If this is not the case, this function could return weird results
* @deprecated
*/
function _unprefixedHexToBytes(hex: string): Uint8Array {
const byteLen = hex.length
const bytes = new Uint8Array(byteLen / 2)
for (let i = 0; i < byteLen; i += 2) {
bytes[i / 2] = hexToBytesMapFirstKey[hex[i]] + hexToBytesMapSecondKey[hex[i + 1]]
}
return bytes
}

/**
* @deprecated
*/
Expand Down Expand Up @@ -96,14 +121,7 @@ export const hexToBytes = (hex: string): Uint8Array => {
if (hex.length % 2 !== 0) {
hex = padToEven(hex)
}

const byteLen = hex.length
const bytes = new Uint8Array(byteLen / 2)
for (let i = 0; i < byteLen; i += 2) {
const byte = parseInt(hex.slice(i, i + 2), 16)
bytes[i / 2] = byte
}
return bytes
return _unprefixedHexToBytes(hex)
}

/******************************************/
Expand Down
Loading