Skip to content

Commit

Permalink
Fix proto3 extension presence for singular, non-optional scalar (#689)
Browse files Browse the repository at this point in the history
  • Loading branch information
timostamm authored Jan 31, 2024
1 parent 8a021d7 commit eeb911a
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
2 changes: 1 addition & 1 deletion packages/protobuf-bench/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ server would usually do.

| code generator | bundle size | minified | compressed |
|---------------------|------------------------:|-----------------------:|-------------------:|
| protobuf-es | 96,275 b | 41,035 b | 10,663 b |
| protobuf-es | 96,441 b | 41,150 b | 10,720 b |
| protobuf-javascript | 394,384 b | 288,654 b | 45,122 b |
5 changes: 3 additions & 2 deletions packages/protobuf-test/src/extensions-proto3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,11 @@ describe("setExtension() proto3", () => {
expect(hasExtension(msg, ext)).toBeTruthy();
expect(getExtension(msg, ext)).toStrictEqual(123);
});
it("should not set zero value", () => {
it("should set zero value, even without optional keyword", () => {
// Implicit presence does not apply to extensions, see https://github.com/protocolbuffers/protobuf/issues/8234
const msg = new FileOptions();
setExtension(msg, ext, 0);
expect(hasExtension(msg, ext)).toBeFalsy();
expect(hasExtension(msg, ext)).toBeTruthy();
expect(getExtension(msg, ext)).toStrictEqual(0);
});
});
Expand Down
9 changes: 8 additions & 1 deletion packages/protobuf/src/extension-accessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
filterUnknownFields,
} from "./private/extensions.js";
import type { Extension } from "./extension.js";
import type { FieldInfo } from "./field.js";

/**
* Retrieve an extension value from a message.
Expand Down Expand Up @@ -87,7 +88,13 @@ export function setExtension<E extends Message<E>, V>(
}
}
const writer = writeOpt.writerFactory();
extension.runtime.bin.writeField(extension.field, value, writer, writeOpt);
let f: FieldInfo = extension.field;
// Implicit presence does not apply to extensions, see https://github.com/protocolbuffers/protobuf/issues/8234
// We patch the field info to use explicit presence:
if (!f.opt && !f.repeated && (f.kind == "enum" || f.kind == "scalar")) {
f = { ...extension.field, opt: true } as FieldInfo;
}
extension.runtime.bin.writeField(f, value, writer, writeOpt);
const reader = readOpt.readerFactory(writer.finish());
while (reader.pos < reader.len) {
const [no, wireType] = reader.tag();
Expand Down

0 comments on commit eeb911a

Please sign in to comment.