Skip to content

Commit f96a152

Browse files
committed
feat: fromHex never to return pooled TypeArrays/Buffers
1 parent 363a714 commit f96a152

2 files changed

Lines changed: 25 additions & 3 deletions

File tree

hex.node.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ export const fromHex = Uint8Array.fromHex
2222
if (typeof str !== 'string') throw new TypeError(E_STRING)
2323
if (str.length % 2 !== 0) throw new SyntaxError(E_HEX)
2424
if (denoBug && /[^\dA-Fa-f]/.test(str)) throw new SyntaxError(E_HEX)
25-
const buf = Buffer.from(str, 'hex') // will stop on first non-hex character, so we can just validate length
26-
if (buf.length * 2 !== str.length) throw new SyntaxError(E_HEX)
27-
return typedView(buf, format)
25+
const length = str.length / 2
26+
const u8 = new Uint8Array(length)
27+
const count = Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength).hexWrite(str, 0, length)
28+
if (count !== length) throw new SyntaxError(E_HEX) // will stop on first non-hex character, so we can just validate length
29+
return typedView(u8, format)
2830
}

tests/hex.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,24 @@ describe('fromHex', () => {
147147
t.assert.deepStrictEqual(lib.fromHex(hex, 'buffer'), buffer)
148148
}
149149
})
150+
151+
test('fromHex returns non-pooled buffers', (t) => {
152+
for (const format of [undefined, 'uint8', 'buffer']) {
153+
for (let i = 0; i < 256; i++) {
154+
t.assert.strictEqual(fromHex('aa'.repeat(128), format).buffer.byteLength, 128)
155+
}
156+
157+
for (let i = 0; i < 256; i++) {
158+
t.assert.strictEqual(fromHex('aa'.repeat(64), format).buffer.byteLength, 64)
159+
}
160+
161+
for (let i = 0; i < 512; i++) {
162+
t.assert.strictEqual(fromHex('aa'.repeat(32), format).buffer.byteLength, 32)
163+
}
164+
165+
for (let i = 0; i < 512; i++) {
166+
t.assert.strictEqual(fromHex('', format).buffer.byteLength, 0)
167+
}
168+
}
169+
})
150170
})

0 commit comments

Comments
 (0)