From 38f6fcd822103f7e896532239c60c47b8fcc7d22 Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Tue, 29 Jul 2014 12:34:49 +0400 Subject: [PATCH] buffer: fix sign overflow in `readUIn32BE` `|` operation takes precendence on `+`, which will result in `new Buffer('ffffffff', 16).readUInt32BE(0)` returning `-1` instead of `ffffffff`. --- lib/buffer.js | 4 ++-- test/simple/test-buffer.js | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 39facdecbb9..e089aceb91f 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -621,8 +621,8 @@ Buffer.prototype.readUInt32BE = function(offset, noAssert) { return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | - (this[offset + 2] << 8)) | - (this[offset + 3]); + (this[offset + 2] << 8) | + this[offset + 3]); }; diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index f8b27986760..8ba024157ae 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -964,6 +964,22 @@ assert.throws(function() { buf.readInt8(0); }, /beyond buffer length/); ); }); +[16, 32].forEach(function(bits) { + var buf = new Buffer([0xFF, 0xFF, 0xFF, 0xFF]); + + assert.equal(buf['readUInt' + bits + 'BE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readUInt' + bits + 'LE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'BE'](0), + (0xFFFFFFFF >> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'LE'](0), + (0xFFFFFFFF >> (32 - bits))); +}); + // SlowBuffer sanity checks. assert.throws(function() { var len = 0xfffff;