buffer icon indicating copy to clipboard operation
buffer copied to clipboard

Writing NaN differs from nodejs Buffer

Open superguineapig opened this issue 6 years ago • 5 comments

Hello,

I was recently attempting to swap out nodejs' Buffer with this one on a fork of another project, so I could use it in a non-node environment, when I noticed an inconsistency between nodejs' Buffer and this library when dealing with NaN

Here's a sample (using most recent npm install of 'buffer'):

const AltBuffer = require('buffer/').Buffer;

const alt_buf = new AltBuffer(8);
const node_buf = new Buffer(8);

alt_buf.writeDoubleLE(NaN, 0);
node_buf.writeDoubleLE(NaN, 0);

in node 6.x, 8.x, and 9.x, the resulting buffer objects are different

Node's (native) Buffer: 00 00 00 00 00 00 f8 7f

buffer library's Buffer: 01 00 00 00 00 00 f0 7f - bytes 0 and 6 are different

That's probably not supposed to happen, right?

superguineapig avatar May 15 '18 00:05 superguineapig

Don't use new Buffer(8).

Use Buffer.alloc(8).

~~The results are different because you are accessing uninitialized memory.~~

Wait, writeDoubleLE should overwrite all 8 bytes...

dcousens avatar May 15 '18 00:05 dcousens

Oops. I should have been using alloc() instead of new anyway.

Unfortunately, even after swapping out the new for alloc, the results are still different between Buffer implementations.

superguineapig avatar May 15 '18 02:05 superguineapig

To test this properly, use alloc() to get zeroed out memory. But this does indeed look like a bug.

var B = require('buffer/').Buffer
var assert = require('assert')

var b1 = B.alloc(8)
b1.writeDoubleLE(NaN, 0)

var b2 = Buffer.alloc(8)
b2.writeDoubleLE(NaN, 0)

assert.deepEqual(b1, b2)

This is probably related to #177. Eventually, we'll get all the Node.js tests passing again and get back in sync. (There are changes to Buffer in every version of Node.js, which is why we get out of date in the first place.)

feross avatar May 15 '18 07:05 feross

Spent some time digging down, and it leads to the ieee754. Created a PR trying to fix the bug, feel free to put down any comment.

geastwood avatar Aug 28 '19 20:08 geastwood

@geastwood Thank you for digging into this and finding the root cause. I left a comment on your PR.

feross avatar Sep 04 '19 22:09 feross