Skip to content

Commit 23aa85c

Browse files
junderwdcousens
andauthored
Fix fromHex invalid hex behavior (#303)
Co-authored-by: Daniel Cousens <[email protected]>
1 parent 7ca8fc5 commit 23aa85c

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

AUTHORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,5 +69,6 @@
6969
7070
- Deklan Webster ([email protected])
7171
- Martin Heidegger ([email protected])
72+
- junderw ([email protected])
7273

7374
#### Generated by bin/update-authors.sh.

index.js

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -860,9 +860,12 @@ function hexWrite (buf, string, offset, length) {
860860
}
861861
let i
862862
for (i = 0; i < length; ++i) {
863-
const parsed = parseInt(string.substr(i * 2, 2), 16)
864-
if (numberIsNaN(parsed)) return i
865-
buf[offset + i] = parsed
863+
const a = hexCharValueTable[string[i * 2]]
864+
const b = hexCharValueTable[string[i * 2 + 1]]
865+
if (a === undefined || b === undefined) {
866+
return i
867+
}
868+
buf[offset + i] = a << 4 | b
866869
}
867870
return i
868871
}
@@ -2114,6 +2117,32 @@ const hexSliceLookupTable = (function () {
21142117
return table
21152118
})()
21162119

2120+
// hex lookup table for Buffer.from(x, 'hex')
2121+
const hexCharValueTable = {
2122+
'0': 0,
2123+
'1': 1,
2124+
'2': 2,
2125+
'3': 3,
2126+
'4': 4,
2127+
'5': 5,
2128+
'6': 6,
2129+
'7': 7,
2130+
'8': 8,
2131+
'9': 9,
2132+
a: 10,
2133+
b: 11,
2134+
c: 12,
2135+
d: 13,
2136+
e: 14,
2137+
f: 15,
2138+
A: 10,
2139+
B: 11,
2140+
C: 12,
2141+
D: 13,
2142+
E: 14,
2143+
F: 15
2144+
}
2145+
21172146
// Return not function with Error if BigInt not supported
21182147
function defineBigIntMethod (fn) {
21192148
return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn

test/node/test-buffer-badhex.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ const assert = require('assert');
1414
assert.strictEqual(buf.write('abcdef01', 0, 'hex'), 4);
1515
assert.deepStrictEqual(buf, new Buffer([0xab, 0xcd, 0xef, 0x01]));
1616
assert.strictEqual(buf.toString('hex'), 'abcdef01');
17+
// Node Buffer behavior check
18+
// > Buffer.from('abc def01','hex')
19+
// <Buffer ab>
20+
assert.strictEqual(buf.write('abc def01', 0, 'hex'), 1);
21+
assert.deepStrictEqual(buf, new Buffer([0xab]));
22+
assert.strictEqual(buf.toString('hex'), 'ab');
1723

1824
const copy = Buffer.from(buf.toString('hex'), 'hex');
1925
assert.strictEqual(buf.toString('hex'), copy.toString('hex'));

0 commit comments

Comments
 (0)