From f5979918571af01751afa40d9c41cb6070f56f99 Mon Sep 17 00:00:00 2001
From: Protobuf Team Bot <protobuf-github-bot@google.com>
Date: Mon, 6 May 2024 16:03:04 -0700
Subject: [PATCH] Return the default instance when parsing from an empty
 byte[].

PiperOrigin-RevId: 631213831
---
 .../com/google/protobuf/GeneratedMessageLite.java     | 11 +++++++++--
 .../src/test/java/com/google/protobuf/LiteTest.java   |  8 +++++++-
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
index 115f4288cd..0937114e42 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
@@ -1621,10 +1621,17 @@ public abstract class GeneratedMessageLite<
 
   /** 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(
diff --git a/java/lite/src/test/java/com/google/protobuf/LiteTest.java b/java/lite/src/test/java/com/google/protobuf/LiteTest.java
index 754ed7d5fc..0c7b8b535b 100644
--- a/java/lite/src/test/java/com/google/protobuf/LiteTest.java
+++ b/java/lite/src/test/java/com/google/protobuf/LiteTest.java
@@ -2423,6 +2423,12 @@ public class LiteTest {
     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 =
@@ -2718,7 +2724,7 @@ public class LiteTest {
   @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) {
     }