Browse Source

Fixed bug in map key sorting for Java TextFormat. (#7508)

Fixes: https://github.com/protocolbuffers/protobuf/issues/7505
Joshua Haberman 5 years ago
parent
commit
7276738e79

+ 3 - 19
java/core/src/main/java/com/google/protobuf/TextFormat.java

@@ -490,27 +490,11 @@ public final class TextFormat {
         }
         }
         switch (fieldType) {
         switch (fieldType) {
           case BOOLEAN:
           case BOOLEAN:
-            boolean aBoolean = (boolean) getKey();
-            boolean bBoolean = (boolean) b.getKey();
-            if (aBoolean == bBoolean) {
-              return 0;
-            } else if (aBoolean) {
-              return 1;
-            } else {
-              return -1;
-            }
+            return Boolean.compare((boolean) getKey(), (boolean) b.getKey());
           case LONG:
           case LONG:
-            long aLong = (long) getKey();
-            long bLong = (long) b.getKey();
-            if (aLong < bLong) {
-              return -1;
-            } else if (aLong > bLong) {
-              return 1;
-            } else {
-              return 0;
-            }
+            return Long.compare((long) getKey(), (long) b.getKey());
           case INT:
           case INT:
-            return (int) getKey() - (int) b.getKey();
+            return Integer.compare((int) getKey(), (int) b.getKey());
           case STRING:
           case STRING:
             String aString = (String) getKey();
             String aString = (String) getKey();
             String bString = (String) b.getKey();
             String bString = (String) b.getKey();

+ 21 - 0
java/core/src/test/java/com/google/protobuf/TextFormatTest.java

@@ -1404,6 +1404,27 @@ public class TextFormatTest extends TestCase {
     }
     }
   }
   }
 
 
+  public void testMapDuplicateKeys() throws Exception {
+    String input =
+        "int32_to_int32_field: {\n"
+            + "  key: 1\n"
+            + "  value: 1\n"
+            + "}\n"
+            + "int32_to_int32_field: {\n"
+            + "  key: -2147483647\n"
+            + "  value: 5\n"
+            + "}\n"
+            + "int32_to_int32_field: {\n"
+            + "  key: 1\n"
+            + "  value: -1\n"
+            + "}\n";
+    TestMap msg = TextFormat.parse(input, TestMap.class);
+    int val1 = msg.getInt32ToInt32Field().get(1);
+    TestMap msg2 = TextFormat.parse(msg.toString(), TestMap.class);
+    int val2 = msg2.getInt32ToInt32Field().get(1);
+    assertEquals(val1, val2);
+  }
+
   public void testMapShortForm() throws Exception {
   public void testMapShortForm() throws Exception {
     String text =
     String text =
         "string_to_int32_field [{ key: 'x' value: 10 }, { key: 'y' value: 20 }]\n"
         "string_to_int32_field [{ key: 'x' value: 10 }, { key: 'y' value: 20 }]\n"