buffer
buffer copied to clipboard
Writing NaN differs from nodejs Buffer
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?
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...
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.
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.)
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 Thank you for digging into this and finding the root cause. I left a comment on your PR.