Skip to content

Commit

Permalink
Handle NaN (#75)
Browse files Browse the repository at this point in the history
* Handle NaN

* Throw error when map contains NaN
  • Loading branch information
valichek authored and mcollina committed Sep 17, 2018
1 parent 569aa62 commit 2b96cd2
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ module.exports = function buildEncode (encodingTypes, forceFloat64, compatibilit

if (obj === undefined) {
throw new Error('undefined is not encodable in msgpack!')
} else if (isNaN(obj)) {
throw new Error('NaN is not encodable in msgpack!')
} else if (obj === null) {
buf = Buffer.allocUnsafe(1)
buf[0] = 0xc0
Expand Down Expand Up @@ -303,6 +305,12 @@ function isFloat (n) {
return n % 1 !== 0
}

function isNaN (n) {
/* eslint-disable no-self-compare */
return n !== n && typeof n === 'number'
/* eslint-enable no-self-compare */
}

function encodeFloat (obj, forceFloat64) {
var useDoublePrecision = true

Expand Down
10 changes: 10 additions & 0 deletions test/15-elements-maps.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ test('do not encode undefined in a map', function (t) {
t.end()
})

test('throw error on NaN in a map', function (t) {
var instance = msgpack()
var toEncode = { a: NaN, hello: 'world' }

t.throws(function () {
instance.encode(toEncode)
}, Error, 'must throw Error')
t.end()
})

test('encode/decode map with buf, ints and strings', function (t) {
var map = {
topic: 'hello',
Expand Down
14 changes: 14 additions & 0 deletions test/NaN.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict'

var test = require('tape').test
var msgpack = require('../')

test('encode NaN', function (t) {
var encoder = msgpack()

t.throws(function () {
encoder.encode(NaN)
}, Error, 'must throw Error')

t.end()
})

0 comments on commit 2b96cd2

Please sign in to comment.