Skip to content

Commit 6e0d39f

Browse files
committed
Add a helper method for converting a Java Map to a RubyHash.
1 parent 74f6147 commit 6e0d39f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/main/java/org/truffleruby/core/hash/HashOperations.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,19 @@
99
*/
1010
package org.truffleruby.core.hash;
1111

12+
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
1213
import org.truffleruby.RubyContext;
1314
import org.truffleruby.RubyLanguage;
1415
import org.truffleruby.core.hash.library.EmptyHashStore;
16+
import org.truffleruby.core.hash.library.HashStoreLibrary;
1517
import org.truffleruby.core.numeric.BigIntegerOps;
1618
import org.truffleruby.core.numeric.RubyBignum;
1719
import org.truffleruby.language.RubyBaseNode;
1820

21+
import java.util.Map;
22+
import java.util.Optional;
23+
import java.util.function.Function;
24+
1925
public abstract class HashOperations {
2026

2127
public static RubyHash newEmptyHash(RubyContext context, RubyLanguage language) {
@@ -27,6 +33,22 @@ public static RubyHash newEmptyHash(RubyContext context, RubyLanguage language)
2733
0);
2834
}
2935

36+
@TruffleBoundary
37+
public static <K, V> RubyHash toRubyHash(RubyContext context, RubyLanguage language,
38+
HashStoreLibrary hashStoreLibrary, Map<K, V> map, Optional<Function<K, Object>> keyMapper,
39+
Optional<Function<V, Object>> valueMapper, boolean byIdentity) {
40+
final RubyHash ret = newEmptyHash(context, language);
41+
42+
for (Map.Entry<K, V> entry : map.entrySet()) {
43+
final Object key = keyMapper.isPresent() ? keyMapper.get().apply(entry.getKey()) : entry.getKey();
44+
final Object value = valueMapper.isPresent() ? valueMapper.get().apply(entry.getValue()) : entry.getValue();
45+
46+
hashStoreLibrary.set(ret.store, ret, key, value, byIdentity);
47+
}
48+
49+
return ret;
50+
}
51+
3052
// random number, stops hashes for similar values but different classes being the same, static because we want deterministic hashes
3153
public static final int BOOLEAN_CLASS_SALT = 55927484;
3254
public static final int INTEGER_CLASS_SALT = 1028093337;

0 commit comments

Comments
 (0)