Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch sparse arrays #92

Merged
merged 2 commits into from
Feb 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion lib/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ module.exports = function buildEncode (encodingTypes, options) {
// and Buffer-like objects
return bl([getBufferHeader(obj.length), obj])
}
if (Array.isArray(obj)) return bl().append([ getHeader(obj.length, 0x90, 0xdc), ...obj.map(encode) ])
if (Array.isArray(obj)) return encodeArray(obj, encode)
if (typeof obj === 'object') return encodeExt(obj, encodingTypes) || encodeObject(obj, options, encode)
if (typeof obj === 'number') return encodeNumber(obj, options)

Expand All @@ -44,6 +44,22 @@ module.exports = function buildEncode (encodingTypes, options) {
//
//

function encodeArray (array, encode) {
const acc = [ getHeader(array.length, 0x90, 0xdc) ]

// This has to be forEach; Array.prototype.map preserves missing values and
// Array.prototype.values yields them as undefined
array.forEach(item => {
acc.push(encode(item))
})

if (acc.length !== array.length + 1) {
throw new Error('Sparse arrays are not encodable in msgpack')
}

return bl(acc)
}

function encodeMap (map, options, encode) {
const acc = [ getHeader(map.size, 0x80, 0xde) ]
const keys = [ ...map.keys() ]
Expand Down
18 changes: 18 additions & 0 deletions test/sparse-arrays.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict'

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

test('throws when encoding sparse arrays', function (t) {
const encoder = msgpack()

t.deepEqual(encoder.decode(encoder.encode(new Array(0))), [])
t.throws(() => encoder.encode(new Array(1)), /Sparse arrays/)
t.throws(() => encoder.encode(new Array(100)), /Sparse arrays/)

const sparse = [1, 2, 3, 4]
delete sparse[3]
t.throws(() => encoder.encode(sparse), /Sparse arrays/)

t.end()
})