Skip to content

Commit

Permalink
js: fast hexToUint8Array for nodejs
Browse files Browse the repository at this point in the history
  • Loading branch information
cdump committed Dec 13, 2023
1 parent 099b25a commit 4f16820
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions js/src/utils.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
export function hexToUint8Array(str) {
let start = 0
if (str.startsWith('0x')) {
start = 2
str = str.slice(2)
if (str.length % 2 !== 0) {
str = '0' + str;
}
}
if (typeof Buffer !== 'undefined') { // fast path for nodejs:
return Buffer.from(str, 'hex');
}
const arr = new Uint8Array((str.length - start + 1) / 2)
let p = 0
for (let i = start; i < str.length; i += 2) {
const arr = new Uint8Array(str.length / 2)
for (let i = 0, p = 0; i < str.length; i += 2, p += 1) {
arr[p] = parseInt(str.slice(i, i + 2), 16)
p++
}
return arr
}
Expand Down

0 comments on commit 4f16820

Please sign in to comment.