Переглянути джерело

Fix issue 256: compute the correct size for negative enum values, which need to be sign extended.

jasonh@google.com 14 роки тому
батько
коміт
eab9b5d47f

+ 1 - 1
java/src/main/java/com/google/protobuf/CodedOutputStream.java

@@ -751,7 +751,7 @@ public final class CodedOutputStream {
    * Caller is responsible for converting the enum value to its numeric value.
    */
   public static int computeEnumSizeNoTag(final int value) {
-    return computeRawVarint32Size(value);
+    return computeInt32SizeNoTag(value);
   }
 
   /**

+ 15 - 0
java/src/test/java/com/google/protobuf/CodedOutputStreamTest.java

@@ -300,4 +300,19 @@ public class CodedOutputStreamTest extends TestCase {
     assertEqualBytes(TestUtil.getGoldenPackedFieldsMessage().toByteArray(),
                      rawBytes);
   }
+
+  /** Test writing a message containing a negative enum value. This used to
+   * fail because the size was not properly computed as a sign-extended varint. */
+  public void testWriteMessageWithNegativeEnumValue() throws Exception {
+    protobuf_unittest.UnittestProto.SparseEnumMessage message =
+        protobuf_unittest.UnittestProto.SparseEnumMessage.newBuilder()
+        .setSparseEnum(protobuf_unittest.UnittestProto.TestSparseEnum.SPARSE_E)
+        .build();
+    assertTrue(message.getSparseEnum().getNumber() < 0);
+    byte[] rawBytes = message.toByteArray();
+    protobuf_unittest.UnittestProto.SparseEnumMessage message2 =
+        protobuf_unittest.UnittestProto.SparseEnumMessage.parseFrom(rawBytes);
+    assertEquals(protobuf_unittest.UnittestProto.TestSparseEnum.SPARSE_E,
+                 message2.getSparseEnum());
+  }
 }