Skip to content

Commit

Permalink
Union: use provided property names in default union encode
Browse files Browse the repository at this point in the history
The union definition may have provided property names in which case the
default ones are not what should be used when encoding.

Fixes #6.
  • Loading branch information
pabigot committed Nov 17, 2015
1 parent 17bfe3e commit bb9c505
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lib/Layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -793,12 +793,12 @@ Union.prototype.encode = function (src, b, offset) {
if (undefined === offset) {
offset = 0;
}
var dlo = this.discr_layout,
vlo = this.default_layout,
discr = src.variant,
content = src.content;
var dlo = this.layout.fields[0],
vlo = this.layout.fields[1],
discr = src[dlo.property],
content = src[vlo.property];
if ((undefined === discr) || (undefined === content)) {
throw new Error("default union encode must be provided variant and content");
throw new Error("default union encode must be provided " + dlo.property + " and " + vlo.property);
}
dlo.encode(discr, b, offset);
vlo.encode(content, b, offset + dlo.span);
Expand Down
15 changes: 15 additions & 0 deletions test/LayoutTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,21 @@ suite("Layout", function () {
assert.equal(un.layout.fields[0].property, 'number');
assert.equal(un.layout.fields[1].property, 'payload');
});
test("issue#6", function () {
var dlo = lo.u8('number'),
vlo = new lo.Sequence(lo.u8(), 8, 'payload'),
un = new lo.Union(dlo, vlo),
b = Buffer("000102030405060708", 'hex'),
obj = un.decode(b);
assert.equal(obj.number, 0);
assert(_.isEqual(obj.payload, [1,2,3,4,5,6,7,8]));
var b2 = new Buffer(un.span);
un.encode(obj, b2);
assert.equal(b2.toString('hex'), b.toString('hex'));
var obj2 = { 'variant': obj.number,
'content': obj.payload };
assert.throws(function () { un.encode(obj2, b2); });
});
});
test("fromArray", function () {
assert.strictEqual(lo.u8().fromArray([1]), undefined);
Expand Down

0 comments on commit bb9c505

Please sign in to comment.