Skip to content

Commit 8d54290

Browse files
committed
refactor: prefer fromBuffer in hex.node, allow pooled Buffer
1 parent f8111ad commit 8d54290

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

hex.node.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { typedView } from './array.js'
2-
import { assertU8, fromUint8, E_STRING } from './fallback/_utils.js'
1+
import { assertU8, fromBuffer, fromUint8, E_STRING } from './fallback/_utils.js'
32
import { E_HEX } from './fallback/hex.js'
43

54
if (Buffer.TYPED_ARRAY_SUPPORT) throw new Error('Unexpected Buffer polyfill')
@@ -23,15 +22,16 @@ export const fromHex = Uint8Array.fromHex
2322
if (str.length % 2 !== 0) throw new SyntaxError(E_HEX)
2423
if (denoBug && /[^\dA-Fa-f]/.test(str)) throw new SyntaxError(E_HEX)
2524

25+
// 64 bytes or less, in heap
2626
if (str.length <= 128) {
27-
const u8 = new Uint8Array(Buffer.from(str, 'hex')) // just copy to not access .buffer
28-
if (u8.length * 2 !== str.length) throw new SyntaxError(E_HEX)
29-
return typedView(u8, format)
27+
const buf = Buffer.from(str, 'hex')
28+
if (buf.length * 2 !== str.length) throw new SyntaxError(E_HEX)
29+
return fromBuffer(buf, format)
3030
}
3131

3232
const length = str.length / 2
33-
const u8 = new Uint8Array(length)
34-
const count = Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength).hexWrite(str, 0, length)
33+
const buf = format === 'buffer' ? Buffer.allocUnsafe(length) : Buffer.allocUnsafeSlow(length) // avoid pooling
34+
const count = buf.hexWrite(str, 0, length)
3535
if (count !== length) throw new SyntaxError(E_HEX) // will stop on first non-hex character, so we can just validate length
36-
return typedView(u8, format)
36+
return fromBuffer(buf, format)
3737
}

0 commit comments

Comments
 (0)