Skip to content

Commit

Permalink
Write default values to oneof fields in generated code (#135)
Browse files Browse the repository at this point in the history
* Write default values to oneof field anyway

* update oneof test fixture

---------

Co-authored-by: farwayer <farwayer@gmail.com>
  • Loading branch information
mourner and farwayer authored Jul 5, 2024
1 parent 1d724b1 commit 2995e6d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
2 changes: 1 addition & 1 deletion compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ function getDefaultWriteTest(ctx, field) {
let code = ` if (obj.${field.name}`;

if (!field.repeated && (!type || !type._proto.fields)) {
if (def === undefined || def) {
if (def === undefined || def || field.oneof) {
code += ' != null';
}
if (def) {
Expand Down
9 changes: 9 additions & 0 deletions test/compile.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,15 @@ test('sets oneof field name', () => {

assert.equal(data.value, 'float');
assert.equal(data[data.value], 1.5);

pbf = new Pbf();
writeEnvelope({
float: 0
}, pbf);
data = readEnvelope(new Pbf(pbf.finish()));

assert.equal(data.value, 'float');
assert.equal(data[data.value], 0);
});

test('handles jstype=JS_STRING', () => {
Expand Down
6 changes: 3 additions & 3 deletions test/fixtures/oneof.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function readEnvelopeField(tag, obj, pbf) {
}
export function writeEnvelope(obj, pbf) {
if (obj.id) pbf.writeVarintField(1, obj.id);
if (obj.int) pbf.writeVarintField(2, obj.int);
if (obj.float) pbf.writeFloatField(3, obj.float);
if (obj.string) pbf.writeStringField(4, obj.string);
if (obj.int != null) pbf.writeVarintField(2, obj.int);
if (obj.float != null) pbf.writeFloatField(3, obj.float);
if (obj.string != null) pbf.writeStringField(4, obj.string);
}

0 comments on commit 2995e6d

Please sign in to comment.