Skip to content

Commit 4f379f8

Browse files
authored
Merge pull request protocolbuffers#2144 from abscondment/fix-jruby-hash
Fix hash computation for JRuby's RubyMessage
2 parents 7b00595 + 05aa0df commit 4f379f8

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java

+17-2
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@
4141
import org.jruby.runtime.builtin.IRubyObject;
4242
import org.jruby.util.ByteList;
4343

44+
import java.security.MessageDigest;
45+
import java.security.NoSuchAlgorithmException;
4446
import java.util.HashMap;
4547
import java.util.Map;
4648

@@ -164,8 +166,21 @@ public IRubyObject inspect() {
164166
*/
165167
@JRubyMethod
166168
public IRubyObject hash(ThreadContext context) {
167-
int hashCode = System.identityHashCode(this);
168-
return context.runtime.newFixnum(hashCode);
169+
try {
170+
MessageDigest digest = MessageDigest.getInstance("SHA-256");
171+
for (RubyMap map : maps.values()) {
172+
digest.update((byte) map.hashCode());
173+
}
174+
for (RubyRepeatedField repeatedField : repeatedFields.values()) {
175+
digest.update((byte) repeatedFields.hashCode());
176+
}
177+
for (IRubyObject field : fields.values()) {
178+
digest.update((byte) field.hashCode());
179+
}
180+
return context.runtime.newString(new ByteList(digest.digest()));
181+
} catch (NoSuchAlgorithmException ignore) {
182+
return context.runtime.newFixnum(System.identityHashCode(this));
183+
}
169184
}
170185

171186
/*

0 commit comments

Comments
 (0)