Skip to content

Commit 92f39e0

Browse files
Fix unnecessary required field checking on serialize of message-typed map fields.
On map fields the Serialize and SerializedLength create temporary instances of synthetic map entries and .build() on them: this change switches it to instead use buildPartial() in these cases. This is a semantics observable change in a corner case, but in a bugfix direction: JavaProto's normal semantics is to only check required fields at .build() time, which allows for buildPartial() and then serialize if you want to intentionally serialize with required fields missing or as a microoptimization skip checking for required fields being set. Only in the case of message-typed-values of map fields serialize may fail with missing required fields: it will happen if the user does buildPartial(), sets it on a map, and then serializes, since the build() on the synthetic map entry will recheck for required fields. After this change the behavior on that shape of flow is consistent with our standard serialize. PiperOrigin-RevId: 849485221
1 parent 93b5196 commit 92f39e0

File tree

2 files changed

+2
-2
lines changed

2 files changed

+2
-2
lines changed

java/core/src/main/java/com/google/protobuf/GeneratedMessage.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3511,7 +3511,7 @@ private static <K, V> void serializeMapTo(
35113511
.newBuilderForType()
35123512
.setKey(entry.getKey())
35133513
.setValue(entry.getValue())
3514-
.build());
3514+
.buildPartial());
35153515
}
35163516
}
35173517
}

src/google/protobuf/compiler/java/full/map_field.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1043,7 +1043,7 @@ void ImmutableMapFieldGenerator::GenerateSerializedSizeCode(
10431043
" $name$__ = $default_entry$.newBuilderForType()\n"
10441044
" .setKey(entry.getKey())\n"
10451045
" .setValue(entry.getValue())\n"
1046-
" .build();\n"
1046+
" .buildPartial();\n"
10471047
" size += com.google.protobuf.CodedOutputStream\n"
10481048
" .computeMessageSize($number$, $name$__);\n"
10491049
"}\n");

0 commit comments

Comments
 (0)