Skip to content

Commit

Permalink
support for map32
Browse files Browse the repository at this point in the history
This adds support and test for map32 - a map with items of up to
length 2^32-1

A few tests were added to check that the support is working as
expected.

Fixes mcollina#54
  • Loading branch information
imnotjames committed May 16, 2018
1 parent 005eceb commit 2dc73e4
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/decoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,8 @@ module.exports = function buildDecode (decodingTypes) {
length = buf.readUInt16BE(offset + 1)
return decodeMap(buf, offset, length, 3)
case 0xdf:
throw new Error('map too big to decode in JS')
length = buf.readUInt32BE(offset + 1)
return decodeMap(buf, offset, length, 5)
case 0xd4:
return decodeFixExt(buf, offset, 1)
case 0xd5:
Expand Down
6 changes: 5 additions & 1 deletion lib/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,14 @@ module.exports = function buildEncode (encodingTypes, forceFloat64, compatibilit
if (length < 16) {
header = Buffer.allocUnsafe(1)
header[0] = 0x80 | length
} else {
} else if (length < 0xFFFF) {
header = Buffer.allocUnsafe(3)
header[0] = 0xde
header.writeUInt16BE(length, 1)
} else {
header = Buffer.allocUnsafe(5)
header[0] = 0xdf
header.writeUInt32BE(length, 1)
}

acc.unshift(header)
Expand Down
71 changes: 71 additions & 0 deletions test/object-with-many-keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
'use strict'

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

test('encode/decode map with 10 keys', function (t) {
var map = {}

for (var i = 0; i < 10; i++) {
map[i] = i
}

var pack = msgpack()

var encoded = pack.encode(map)

// map16 byte
t.equal(encoded[0], 0x8A)

t.deepEqual(pack.decode(encoded), map)
t.end()
})

test('encode/decode map with 10000 keys', function (t) {
var map = {}

for (var i = 0; i < 10000; i++) {
map[i] = i
}

var pack = msgpack()

var encoded = pack.encode(map)

// map16 byte
t.equal(encoded[0], 0xde)

t.deepEqual(pack.decode(encoded), map)
t.end()
})

test('encode/decode map with 100000 keys', function (t) {
var map = {}

for (var i = 0; i < 100000; i++) {
map[i] = i
}

var pack = msgpack()

var encoded = pack.encode(map)

// map32 byte
t.equal(encoded[0], 0xdf)

t.deepEqual(pack.decode(encoded), map)
t.end()
})

test('encode/decode map with 1000000 keys', function (t) {
var map = {}

for (var i = 0; i < 1000000; i++) {
map[i] = i
}

var pack = msgpack()

t.deepEqual(pack.decode(pack.encode(map)), map)
t.end()
})

0 comments on commit 2dc73e4

Please sign in to comment.