Debian Codegraph @

pypy/module/_random/interp_random.py

raw symbols SCIP
1 import time
2
3 from pypy.interpreter.error import oefmt, OperationError
4 from pypy.interpreter.typedef import TypeDef
5 from pypy.interpreter.gateway import interp2app, unwrap_spec
6 from pypy.interpreter.baseobjspace import W_Root
7 from pypy.module.posix import interp_posix
8 from rpython.rlib.rarithmetic import r_uint, intmask, widen, LONG_BIT
9 from rpython.rlib import rbigint, rrandom, rstring
10
11 def descr_new__(space, w_subtype, __args__):
12 w_anything = __args__.firstarg()
13 x = space.allocate_instance(W_Random, w_subtype)
14 x = space.interp_w(W_Random, x)
15 W_Random.__init__(x, space, w_anything)
16 return x
17
18
19 class W_Random(W_Root):
20 def __init__(self, space, w_anything):
21 self._rnd = rrandom.Random()
22 self.seed(space, w_anything)
23
24 def random(self, space):
25 return space.newfloat(self._rnd.random())
26
27 def seed(self, space, w_n=None):
28 if space.is_none(w_n):
29 # TODO: Use a non-blocking version of urandom
30 try:
31 w_n = interp_posix.urandom(space, 8)
32 except OperationError as e:
33 if not e.match(space, space.w_OSError):
34 raise
35 w_n = space.newint(int(time.time() * 256))
36 if space.isinstance_w(w_n, space.w_int):
37 w_n = space.abs(w_n)
38 else:
39 n = space.hash_w(w_n)
40 w_n = space.newint(r_uint(n))
41 key = []
42 w_one = space.newint(1)
43 w_two = space.newint(2)
44 w_thirtytwo = space.newint(32)
45 # 0xffffffff
46 w_masklower = space.sub(space.pow(w_two, w_thirtytwo, space.w_None),
47 w_one)
48 while space.is_true(w_n):
49 w_chunk = space.and_(w_n, w_masklower)
50 chunk = space.uint_w(w_chunk)
51 key.append(chunk)
52 w_n = space.rshift(w_n, w_thirtytwo)
53 if not key:
54 key = [r_uint(0)]
55 self._rnd.init_by_array(key)
56
57 def getstate(self, space):
58 state = [None] * (rrandom.N + 1)
59 for i in range(rrandom.N):
60 state[i] = space.newint(widen(self._rnd.state[i]))
61 state[rrandom.N] = space.newlong(self._rnd.index)
62 return space.newtuple(state)
63
64 def setstate(self, space, w_state):
65 if not space.isinstance_w(w_state, space.w_tuple):
66 raise oefmt(space.w_TypeError, "state vector must be tuple")
67 if space.len_w(w_state) != rrandom.N + 1:
68 raise oefmt(space.w_ValueError, "state vector is the wrong size")
69 w_zero = space.newint(0)
70 # independent of platfrom, since the below condition is only
71 # true on 32 bit platforms anyway
72 w_add = space.pow(space.newint(2), space.newint(32), space.w_None)
73 _state = [r_uint(0)] * rrandom.N
74 for i in range(rrandom.N):
75 w_item = space.getitem(w_state, space.newint(i))
76 if space.is_true(space.lt(w_item, w_zero)):
77 w_item = space.add(w_item, w_add)
78 _state[i] = space.uint_w(w_item)
79 w_item = space.getitem(w_state, space.newint(rrandom.N))
80 index = space.int_w(w_item)
81 if index < 0 or index > rrandom.N:
82 raise oefmt(space.w_ValueError, "invalid state")
83 self._rnd.state = _state
84 self._rnd.index = index
85
86 @unwrap_spec(k=int)
87 def getrandbits(self, space, k):
88 if k < 0:
89 raise oefmt(space.w_ValueError,
90 "number of bits must be non-negative")
91 if k == 0:
92 return space.newint(0)
93 if k < 32: # XXX could go up to 63 bits, but let's start with this
94 # fits an int, don't do the bytes-to-long-to-int dance
95 r = self._rnd.genrand32()
96 r >>= (32 - k)
97 return space.newint(intmask(r))
98 bytes = ((k - 1) // 32 + 1) * 4
99 bytesarray = rstring.StringBuilder(bytes)
100 for i in range(0, bytes, 4):
101 r = self._rnd.genrand32()
102 if k < 32:
103 r >>= (32 - k)
104 bytesarray.append(chr(r & r_uint(0xff)))
105 bytesarray.append(chr((r >> 8) & r_uint(0xff)))
106 bytesarray.append(chr((r >> 16) & r_uint(0xff)))
107 bytesarray.append(chr((r >> 24) & r_uint(0xff)))
108 k -= 32
109
110 # little endian order to match bytearray assignment order
111 result = rbigint.rbigint.frombytes(
112 bytesarray.build(), 'little', signed=False)
113 return space.newlong_from_rbigint(result)
114
115
116 W_Random.typedef = TypeDef("Random",
117 __new__ = interp2app(descr_new__),
118 random = interp2app(W_Random.random),
119 seed = interp2app(W_Random.seed),
120 getstate = interp2app(W_Random.getstate),
121 setstate = interp2app(W_Random.setstate),
122 getrandbits = interp2app(W_Random.getrandbits),
123 )