Skip to content

Commit b4eadf3

Browse files
committed
subclass java Random so we can save/restore state more easily
1 parent 000a501 commit b4eadf3

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/random/PRandom.java

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,17 @@
66
import com.oracle.graal.python.builtins.objects.type.PythonClass;
77

88
public class PRandom extends PythonBuiltinObject {
9-
private Random javaRandom = new Random();
9+
private static class PythonRandom extends Random {
10+
private static final long serialVersionUID = 1L;
11+
12+
long getSeed() {
13+
int nextseed = this.next(48); // 48 magic number of bits shifted away in superclass
14+
this.setSeed(nextseed);
15+
return nextseed;
16+
}
17+
}
18+
19+
private PythonRandom javaRandom = new PythonRandom();
1020

1121
public PRandom(PythonClass cls) {
1222
super(cls);
@@ -16,6 +26,10 @@ public void setSeed(long seed) {
1626
javaRandom.setSeed(seed);
1727
}
1828

29+
public long getSeed() {
30+
return javaRandom.getSeed();
31+
}
32+
1933
public long nextLong() {
2034
return javaRandom.nextLong();
2135
}
@@ -28,7 +42,7 @@ public Random getJavaRandom() {
2842
return javaRandom;
2943
}
3044

31-
public void setJavaRandom(Random random) {
32-
javaRandom = random;
45+
public void resetJavaRandom() {
46+
javaRandom = new PythonRandom();
3347
}
3448
}

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/random/RandomBuiltins.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import java.math.BigInteger;
44
import java.util.List;
5-
import java.util.Random;
65

76
import com.oracle.graal.python.builtins.Builtin;
87
import com.oracle.graal.python.builtins.CoreFunctions;
@@ -73,7 +72,8 @@ public PNone setstate(PRandom random, PTuple tuple) {
7372
if (arr.length == 1) {
7473
Object object = arr[0];
7574
if (object instanceof Long) {
76-
random.setJavaRandom(new Random((Long) object));
75+
random.resetJavaRandom();
76+
random.setSeed((Long) object);
7777
return PNone.NONE;
7878
}
7979
}
@@ -88,7 +88,7 @@ public abstract static class GetStateNode extends PythonBuiltinNode {
8888
@Specialization
8989
@TruffleBoundary
9090
public PTuple getstate(PRandom random) {
91-
return factory().createTuple(new Object[]{random.nextLong()});
91+
return factory().createTuple(new Object[]{random.getSeed()});
9292
}
9393
}
9494

0 commit comments

Comments
 (0)