Skip to content

Commit

Permalink
fix(encoder): correct return value on .write
Browse files Browse the repository at this point in the history
Due to not returning the success value on `.write`, the encoding was
not finished.

Closes #27
  • Loading branch information
dignifiedquire committed Mar 13, 2018
1 parent a042927 commit 8eb9b1f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -372,10 +372,10 @@ class Encoder {
* Alias for `.pushAny`
*
* @param {*} obj
* @returns {undefind}
* @returns {boolean} true on success
*/
write (obj) {
this.pushAny(obj)
return this.pushAny(obj)
}

/**
Expand Down Expand Up @@ -500,7 +500,10 @@ class Encoder {
*/
static encode (o) {
const enc = new Encoder()
enc.pushAny(o)
const ret = enc.pushAny(o)
if (!ret) {
throw new Error('Failed to encode input')
}

return enc.finalize()
}
Expand Down
45 changes: 45 additions & 0 deletions test/encoder.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,49 @@ describe('encoder', () => {
}
})
})

describe('nested classes', () => {
class Serializable {
serialize () {
const encoder = new cbor.Encoder()
const ret = this.encodeCBOR(encoder)
if (!ret) {
throw new Error('unable to serialize input')
}
return encoder.finalize()
}

static deserialize (serialized) {
return cbor.decodeAll(serialized)
}
}

class TestA extends Serializable {
encodeCBOR (gen) {
return gen.write(44)
}
}

class TestB extends Serializable {
encodeCBOR (gen) {
return gen.write([
new TestA(),
true
])
}
}

it('flat', () => {
const a1 = new TestA()

expect(a1.serialize()).to.be.eql(Buffer.from([24, 44]))
expect(TestA.deserialize(a1.serialize())).to.be.eql([44])
})

it('nested', () => {
const b1 = new TestB()
const encoded = b1.serialize()
expect(TestB.deserialize(encoded)).to.be.eql([[44, true]])
})
})
})

0 comments on commit 8eb9b1f

Please sign in to comment.