Skip to content

Commit

Permalink
fix(encode): fix encoding for non-finite numbers (#4)
Browse files Browse the repository at this point in the history
New format (instead of throwing an error):

NaN: <Buffer cb 7f f8 00 00 00 00 00 00>
Infinity: <Buffer cb 7f f0 00 00 00 00 00 00>
-Infinity: <Buffer cb ff f0 00 00 00 00 00 00>
  • Loading branch information
darrachequesne authored Jun 6, 2017
1 parent c6e8c35 commit f0ed0f3
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 12 deletions.
8 changes: 2 additions & 6 deletions browser/encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,10 @@ function _encode(bytes, defers, value) {
return size + length;
}
if (type === 'number') {
if (!isFinite(value)) {
throw new Error('Number is not finite');
}

// TODO: encode to float 32?

// float 64
if (Math.floor(value) !== value) {
if (Math.floor(value) !== value || !isFinite(value)) {
bytes.push(0xcb);
defers.push({ float: value, length: 8, offset: bytes.length });
return 9;
Expand Down Expand Up @@ -296,7 +292,7 @@ function encode(value) {
}
} else if (defer.str) {
utf8Write(view, offset, defer.str);
} else if (defer.float) {
} else if (defer.float !== undefined) {
view.setFloat64(offset, defer.float);
}
deferIndex++;
Expand Down
8 changes: 2 additions & 6 deletions lib/encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,10 @@ function _encode(bytes, defers, value) {
return size + length;
}
if (type === 'number') {
if (!isFinite(value)) {
throw new Error('Number is not finite');
}

// TODO: encode to float 32?

// float 64
if (Math.floor(value) !== value) {
if (Math.floor(value) !== value || !isFinite(value)) {
bytes.push(0xcb);
defers.push({ float: value, length: 8, offset: bytes.length });
return 9;
Expand Down Expand Up @@ -335,7 +331,7 @@ function encode(value) {
} else {
utf8Write(buf, offset, defer.str);
}
} else if (defer.float) {
} else if (defer.float !== undefined) {
buf.writeDoubleBE(defer.float, offset);
} else if (defer.arraybuffer) {
var arr = new Uint8Array(defer.arraybuffer);
Expand Down
3 changes: 3 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ describe('notepack', function () {
it('float 64', function () {
check(1.1, 'cb' + '3ff199999999999a');
check(1234567891234567.5, 'cb' + '43118b54f26ebc1e');
check(Infinity, 'cb' + '7ff0000000000000');
check(-Infinity, 'cb' + 'fff0000000000000');
check(NaN, 'cb' + '7ff8000000000000');
});

it('uint 8', function () {
Expand Down

0 comments on commit f0ed0f3

Please sign in to comment.