From dfb91373301a5a88b50bcb348207be9853668573 Mon Sep 17 00:00:00 2001 From: Brandon Westcott Date: Wed, 13 Feb 2019 10:01:51 -0500 Subject: [PATCH] fix: make cbor Decoder configurable (#90) It's now possible to encode data bigger than the default size. --- src/util.js | 28 ++++++++++++++++++---------- test/util.spec.js | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/util.js b/src/util.js index 41d611a..9ce1093 100644 --- a/src/util.js +++ b/src/util.js @@ -23,16 +23,6 @@ function tagCID (cid) { ])) } -const decoder = new cbor.Decoder({ - tags: { - [CID_CBOR_TAG]: (val) => { - // remove that 0 - val = val.slice(1) - return new CID(val) - } - } -}) - function replaceCIDbyTAG (dagNode) { let circular try { @@ -87,6 +77,24 @@ function replaceCIDbyTAG (dagNode) { exports = module.exports +let decoder = null + +exports.configureDecoder = (opts) => { + opts = opts || {} + decoder = new cbor.Decoder({ + tags: Object.assign({ + [CID_CBOR_TAG]: (val) => { + // remove that 0 + val = val.slice(1) + return new CID(val) + } + }, opts.tags || {}), + size: opts.size + }) +} + +exports.configureDecoder() // Setup default cbor.Decoder + exports.serialize = (dagNode, callback) => { let serialized diff --git a/test/util.spec.js b/test/util.spec.js index ca5823e..e1ad08c 100644 --- a/test/util.spec.js +++ b/test/util.spec.js @@ -44,6 +44,27 @@ describe('util', () => { }) }) + it('.serialize and .deserialize large objects', (done) => { + const size = 65536 * 2 + const largeObj = { someKey: [].slice.call(new Uint8Array(size)) } + // Configure decoder with custom size + dagCBOR.util.configureDecoder({ size: size + 1 }) + + dagCBOR.util.serialize(largeObj, (err, serialized) => { + expect(err).to.not.exist() + expect(Buffer.isBuffer(serialized)).to.equal(true) + + dagCBOR.util.deserialize(serialized, (err, deserialized) => { + expect(err).to.not.exist() + expect(largeObj).to.eql(deserialized) + + // Reset decoder back to default + dagCBOR.util.configureDecoder() + done() + }) + }) + }) + it('error catching', (done) => { const circlarObj = {} circlarObj.a = circlarObj