Skip to content

Commit

Permalink
Fix fromHex invalid hex behavior (#303)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel Cousens <[email protected]>
  • Loading branch information
junderw and dcousens authored Oct 11, 2023
1 parent 7ca8fc5 commit 23aa85c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
1 change: 1 addition & 0 deletions AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,6 @@
- jkkang ([email protected])
- Deklan Webster ([email protected])
- Martin Heidegger ([email protected])
- junderw ([email protected])

#### Generated by bin/update-authors.sh.
35 changes: 32 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -860,9 +860,12 @@ function hexWrite (buf, string, offset, length) {
}
let i
for (i = 0; i < length; ++i) {
const parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
const a = hexCharValueTable[string[i * 2]]
const b = hexCharValueTable[string[i * 2 + 1]]
if (a === undefined || b === undefined) {
return i
}
buf[offset + i] = a << 4 | b
}
return i
}
Expand Down Expand Up @@ -2114,6 +2117,32 @@ const hexSliceLookupTable = (function () {
return table
})()

// hex lookup table for Buffer.from(x, 'hex')
const hexCharValueTable = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
a: 10,
b: 11,
c: 12,
d: 13,
e: 14,
f: 15,
A: 10,
B: 11,
C: 12,
D: 13,
E: 14,
F: 15
}

// Return not function with Error if BigInt not supported
function defineBigIntMethod (fn) {
return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
Expand Down
6 changes: 6 additions & 0 deletions test/node/test-buffer-badhex.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ const assert = require('assert');
assert.strictEqual(buf.write('abcdef01', 0, 'hex'), 4);
assert.deepStrictEqual(buf, new Buffer([0xab, 0xcd, 0xef, 0x01]));
assert.strictEqual(buf.toString('hex'), 'abcdef01');
// Node Buffer behavior check
// > Buffer.from('abc def01','hex')
// <Buffer ab>
assert.strictEqual(buf.write('abc def01', 0, 'hex'), 1);
assert.deepStrictEqual(buf, new Buffer([0xab]));
assert.strictEqual(buf.toString('hex'), 'ab');

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

0 comments on commit 23aa85c

Please sign in to comment.