Skip to content

Commit 8eb9b1f

Browse files
fix(encoder): correct return value on .write
Due to not returning the success value on `.write`, the encoding was not finished. Closes #27
1 parent a042927 commit 8eb9b1f

File tree

2 files changed

+51
-3
lines changed

2 files changed

+51
-3
lines changed

src/encoder.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -372,10 +372,10 @@ class Encoder {
372372
* Alias for `.pushAny`
373373
*
374374
* @param {*} obj
375-
* @returns {undefind}
375+
* @returns {boolean} true on success
376376
*/
377377
write (obj) {
378-
this.pushAny(obj)
378+
return this.pushAny(obj)
379379
}
380380

381381
/**
@@ -500,7 +500,10 @@ class Encoder {
500500
*/
501501
static encode (o) {
502502
const enc = new Encoder()
503-
enc.pushAny(o)
503+
const ret = enc.pushAny(o)
504+
if (!ret) {
505+
throw new Error('Failed to encode input')
506+
}
504507

505508
return enc.finalize()
506509
}

test/encoder.spec.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,4 +172,49 @@ describe('encoder', () => {
172172
}
173173
})
174174
})
175+
176+
describe('nested classes', () => {
177+
class Serializable {
178+
serialize () {
179+
const encoder = new cbor.Encoder()
180+
const ret = this.encodeCBOR(encoder)
181+
if (!ret) {
182+
throw new Error('unable to serialize input')
183+
}
184+
return encoder.finalize()
185+
}
186+
187+
static deserialize (serialized) {
188+
return cbor.decodeAll(serialized)
189+
}
190+
}
191+
192+
class TestA extends Serializable {
193+
encodeCBOR (gen) {
194+
return gen.write(44)
195+
}
196+
}
197+
198+
class TestB extends Serializable {
199+
encodeCBOR (gen) {
200+
return gen.write([
201+
new TestA(),
202+
true
203+
])
204+
}
205+
}
206+
207+
it('flat', () => {
208+
const a1 = new TestA()
209+
210+
expect(a1.serialize()).to.be.eql(Buffer.from([24, 44]))
211+
expect(TestA.deserialize(a1.serialize())).to.be.eql([44])
212+
})
213+
214+
it('nested', () => {
215+
const b1 = new TestB()
216+
const encoded = b1.serialize()
217+
expect(TestB.deserialize(encoded)).to.be.eql([[44, true]])
218+
})
219+
})
175220
})

0 commit comments

Comments
 (0)