Skip to content

Commit

Permalink
Return the default instance when parsing from an empty byte[].
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 631213831
  • Loading branch information
protobuf-github-bot authored and copybara-github committed May 6, 2024
1 parent 55592a2 commit f597991
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1621,10 +1621,17 @@ public T parsePartialFrom(

/** A static helper method for parsing a partial from byte array. */
private static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
T instance, byte[] input, int offset, int length, ExtensionRegistryLite extensionRegistry)
T defaultInstance,
byte[] input,
int offset,
int length,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
if (length == 0) {
return defaultInstance;
}
@SuppressWarnings("unchecked") // Guaranteed by protoc
T result = instance.newMutableInstance();
T result = defaultInstance.newMutableInstance();
try {
Schema<T> schema = Protobuf.getInstance().schemaFor(result);
schema.mergeFrom(
Expand Down
8 changes: 7 additions & 1 deletion java/lite/src/test/java/com/google/protobuf/LiteTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2423,6 +2423,12 @@ public void testRecursiveHashcode() {
int unused = TestRecursiveOneof.getDefaultInstance().hashCode();
}

@Test
public void testParseFromEmptyBytes() throws Exception {
assertThat(TestAllTypesLite.parseFrom(new byte[] {}))
.isSameInstanceAs(TestAllTypesLite.getDefaultInstance());
}

@Test
public void testParseFromByteBuffer() throws Exception {
TestAllTypesLite message =
Expand Down Expand Up @@ -2718,7 +2724,7 @@ public Iterator<T> iterator() {
@Test
public void testNullExtensionRegistry() throws Exception {
try {
TestAllTypesLite.parseFrom(new byte[] {}, null);
TestAllTypesLite.parseFrom(TestUtilLite.getAllLiteSetBuilder().build().toByteArray(), null);
assertWithMessage("expected exception").fail();
} catch (NullPointerException expected) {
}
Expand Down

0 comments on commit f597991

Please sign in to comment.