Skip to content

Instantly share code, notes, and snippets.

@headius
Created May 14, 2024 07:17
Show Gist options
  • Save headius/b4a8967b7e3bfbc9dc7aab7d5fa491ec to your computer and use it in GitHub Desktop.
Save headius/b4a8967b7e3bfbc9dc7aab7d5fa491ec to your computer and use it in GitHub Desktop.
diff --git a/core/src/main/java/org/jruby/RubyString.java b/core/src/main/java/org/jruby/RubyString.java
index 2b42e03515..3c2dd7dc11 100644
--- a/core/src/main/java/org/jruby/RubyString.java
+++ b/core/src/main/java/org/jruby/RubyString.java
@@ -1102,12 +1102,16 @@ public class RubyString extends RubyObject implements CharSequence, EncodingCapa
*/
public static class FString extends RubyString {
private IRubyObject converted;
+ private final RubyFixnum hash;
+ private final int hashCode;
protected FString(Ruby runtime, RubyClass rubyClass, ByteList value, int cr) {
super(runtime, rubyClass, value, cr);
// set flag for code that does not use isFrozen
setFrozen(true);
+
+ hash = RubyFixnum.newFixnum(runtime, hashCode = RubyString.calculateHash(runtime, value, cr));
}
@Override
@@ -1161,6 +1165,16 @@ public class RubyString extends RubyObject implements CharSequence, EncodingCapa
return super.to_f();
}
+
+ @Override
+ public RubyFixnum hash() {
+ return hash;
+ }
+
+ @Override
+ public int hashCode() {
+ return hashCode;
+ }
}
/** rb_str_resize
@@ -1404,12 +1418,16 @@ public class RubyString extends RubyObject implements CharSequence, EncodingCapa
*/
public int strHashCode(Ruby runtime) {
final ByteList value = this.value;
+ return calculateHash(runtime, value, scanForCodeRange());
+ }
+
+ private static int calculateHash(Ruby runtime, ByteList value, int cr) {
final Encoding enc = value.getEncoding();
long hash = runtime.isSiphashEnabled() ? SipHashInline.hash24(runtime.getHashSeedK0(),
runtime.getHashSeedK1(), value.getUnsafeBytes(), value.getBegin(),
value.getRealSize()) : PerlHash.hash(runtime.getHashSeedK0(),
value.getUnsafeBytes(), value.getBegin(), value.getRealSize());
- hash ^= (enc.isAsciiCompatible() && scanForCodeRange() == CR_7BIT ? 0 : enc.getIndex());
+ hash ^= (enc.isAsciiCompatible() && cr == CR_7BIT ? 0 : enc.getIndex());
return (int) hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment