Skip to content
This repository was archived by the owner on Aug 11, 2021. It is now read-only.

Commit dfb9137

Browse files
brandonwestcottvmx
authored andcommitted
fix: make cbor Decoder configurable (#90)
It's now possible to encode data bigger than the default size.
1 parent 4469954 commit dfb9137

2 files changed

Lines changed: 39 additions & 10 deletions

File tree

src/util.js

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,6 @@ function tagCID (cid) {
2323
]))
2424
}
2525

26-
const decoder = new cbor.Decoder({
27-
tags: {
28-
[CID_CBOR_TAG]: (val) => {
29-
// remove that 0
30-
val = val.slice(1)
31-
return new CID(val)
32-
}
33-
}
34-
})
35-
3626
function replaceCIDbyTAG (dagNode) {
3727
let circular
3828
try {
@@ -87,6 +77,24 @@ function replaceCIDbyTAG (dagNode) {
8777

8878
exports = module.exports
8979

80+
let decoder = null
81+
82+
exports.configureDecoder = (opts) => {
83+
opts = opts || {}
84+
decoder = new cbor.Decoder({
85+
tags: Object.assign({
86+
[CID_CBOR_TAG]: (val) => {
87+
// remove that 0
88+
val = val.slice(1)
89+
return new CID(val)
90+
}
91+
}, opts.tags || {}),
92+
size: opts.size
93+
})
94+
}
95+
96+
exports.configureDecoder() // Setup default cbor.Decoder
97+
9098
exports.serialize = (dagNode, callback) => {
9199
let serialized
92100

test/util.spec.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,27 @@ describe('util', () => {
4444
})
4545
})
4646

47+
it('.serialize and .deserialize large objects', (done) => {
48+
const size = 65536 * 2
49+
const largeObj = { someKey: [].slice.call(new Uint8Array(size)) }
50+
// Configure decoder with custom size
51+
dagCBOR.util.configureDecoder({ size: size + 1 })
52+
53+
dagCBOR.util.serialize(largeObj, (err, serialized) => {
54+
expect(err).to.not.exist()
55+
expect(Buffer.isBuffer(serialized)).to.equal(true)
56+
57+
dagCBOR.util.deserialize(serialized, (err, deserialized) => {
58+
expect(err).to.not.exist()
59+
expect(largeObj).to.eql(deserialized)
60+
61+
// Reset decoder back to default
62+
dagCBOR.util.configureDecoder()
63+
done()
64+
})
65+
})
66+
})
67+
4768
it('error catching', (done) => {
4869
const circlarObj = {}
4970
circlarObj.a = circlarObj

0 commit comments

Comments
 (0)