From a882d4b4b6801edb1e67fb17632d2da50ba22266 Mon Sep 17 00:00:00 2001 From: Brian Duff Date: Mon, 21 Jul 2014 15:07:41 -0700 Subject: Add MessageNano.messageNanoEquals(). Allows two messages to be compared directly for equality without generating an equals method for every generated message. (Ports CL58125010) Change-Id: I92ab5088539d1fd722fee7b5e28a8c825926c3b6 --- .../java/com/google/protobuf/nano/MessageNano.java | 26 ++++++++++++++++++++++ .../test/java/com/google/protobuf/NanoTest.java | 3 +++ 2 files changed, 29 insertions(+) diff --git a/java/src/main/java/com/google/protobuf/nano/MessageNano.java b/java/src/main/java/com/google/protobuf/nano/MessageNano.java index d6288c9..164f317 100644 --- a/java/src/main/java/com/google/protobuf/nano/MessageNano.java +++ b/java/src/main/java/com/google/protobuf/nano/MessageNano.java @@ -31,6 +31,7 @@ package com.google.protobuf.nano; import java.io.IOException; +import java.util.Arrays; /** * Abstract interface implemented by Protocol Message objects. @@ -151,6 +152,31 @@ public abstract class MessageNano { } /** + * Compares two {@code MessageNano}s and returns true if the message's are the same class and + * have serialized form equality (i.e. all of the field values are the same). + */ + public static final boolean messageNanoEquals(MessageNano a, MessageNano b) { + if (a == b) { + return true; + } + if (a == null || b == null) { + return false; + } + if (a.getClass() != b.getClass()) { + return false; + } + final int serializedSize = a.getSerializedSize(); + if (b.getSerializedSize() != serializedSize) { + return false; + } + final byte[] aByteArray = new byte[serializedSize]; + final byte[] bByteArray = new byte[serializedSize]; + toByteArray(a, aByteArray, 0, serializedSize); + toByteArray(b, bByteArray, 0, serializedSize); + return Arrays.equals(aByteArray, bByteArray); + } + + /** * Returns a string that is (mostly) compatible with ProtoBuffer's TextFormat. Note that groups * (which are deprecated) are not serialized with the correct field name. * diff --git a/java/src/test/java/com/google/protobuf/NanoTest.java b/java/src/test/java/com/google/protobuf/NanoTest.java index 6334e4b..6b69aa7 100644 --- a/java/src/test/java/com/google/protobuf/NanoTest.java +++ b/java/src/test/java/com/google/protobuf/NanoTest.java @@ -3212,6 +3212,9 @@ public class NanoTest extends TestCase { TestAllTypesNano a = createMessageForHashCodeEqualsTest(); TestAllTypesNano aEquivalent = createMessageForHashCodeEqualsTest(); + assertTrue(MessageNano.messageNanoEquals(a, aEquivalent)); + assertFalse(MessageNano.messageNanoEquals(a, new TestAllTypesNano())); + // Null and empty array for repeated fields equality: TestAllTypesNano b = createMessageForHashCodeEqualsTest(); b.repeatedBool = null; -- cgit v1.1