From 785c82dbdea5085628f2a41437aa1198860f3342 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Thu, 14 Sep 2023 11:20:50 -0700 Subject: [PATCH] Fix a bad cast in putBuilderIfAbsent when already present due to using the result of put() directly (which is null if it currently has no value) PiperOrigin-RevId: 565425310 --- java/core/src/test/java/com/google/protobuf/MapTest.java | 5 +++++ src/google/protobuf/compiler/java/map_field.cc | 9 +++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/java/core/src/test/java/com/google/protobuf/MapTest.java b/java/core/src/test/java/com/google/protobuf/MapTest.java index c00874a8ac..7058d43168 100644 --- a/java/core/src/test/java/com/google/protobuf/MapTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapTest.java @@ -553,11 +553,16 @@ public class MapTest { public void testPutBuilderIfAbsent() { TestMap.Builder builder = TestMap.newBuilder(); MessageValue.Builder subBuilder = builder.putInt32ToMessageFieldBuilderIfAbsent(1); + assertThat(builder.putInt32ToMessageFieldBuilderIfAbsent(1)).isSameInstanceAs(subBuilder); + subBuilder.setValue(11); assertThat(builder.getInt32ToMessageFieldOrThrow(1).getValue()).isEqualTo(11); builder.putInt32ToMessageFieldBuilderIfAbsent(1).setValue(22); assertThat(builder.getInt32ToMessageFieldOrThrow(1).getValue()).isEqualTo(22); + + builder.putInt32ToMessageField(2, MessageValue.newBuilder().setValue(33).build()); + assertThat(builder.putInt32ToMessageFieldBuilderIfAbsent(2).getValue()).isEqualTo(33); } @Test diff --git a/src/google/protobuf/compiler/java/map_field.cc b/src/google/protobuf/compiler/java/map_field.cc index 21fddeb549..d15a753e78 100644 --- a/src/google/protobuf/compiler/java/map_field.cc +++ b/src/google/protobuf/compiler/java/map_field.cc @@ -877,10 +877,11 @@ void ImmutableMapFieldGenerator::GenerateMessageMapBuilderMembers( " entry = $value_type$.newBuilder();\n" " builderMap.put(key, entry);\n" " }\n" - " if (entry instanceof $value_builder_type$) { return " - "($value_builder_type$) entry; }\n" - " return ($value_builder_type$) builderMap.put(key, " - "(($value_type$) entry).toBuilder());\n" + " if (entry instanceof $value_type$) {\n" + " entry = (($value_type$) entry).toBuilder();\n" + " builderMap.put(key, entry);\n" + " }\n" + " return ($value_builder_type$) entry;\n" "}\n"); printer->Annotate("{", "}", descriptor_, Semantic::kSet); }