blob: f0fdb0382c5d3501f503fde295336ef237853eef [file] [log] [blame]
Raymond Hettinger40f62172002-12-29 23:03:38 +00001/* Random objects */
2
3/* ------------------------------------------------------------------
4 The code in this module was based on a download from:
Hiroki Nodaf15fa872017-02-15 18:04:43 +09005 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html
Raymond Hettinger40f62172002-12-29 23:03:38 +00006
7 It was modified in 2002 by Raymond Hettinger as follows:
8
Benjamin Petersond8e5f2d2010-08-24 18:08:22 +00009 * the principal computational lines untouched.
Raymond Hettinger40f62172002-12-29 23:03:38 +000010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * renamed genrand_res53() to random_random() and wrapped
12 in python calling/return code.
Raymond Hettinger40f62172002-12-29 23:03:38 +000013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000014 * genrand_int32() and the helper functions, init_genrand()
15 and init_by_array(), were declared static, wrapped in
16 Python calling/return code. also, their global data
17 references were replaced with structure references.
Raymond Hettinger40f62172002-12-29 23:03:38 +000018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019 * unused functions from the original were deleted.
20 new, original C python code was added to implement the
21 Random() interface.
Raymond Hettinger40f62172002-12-29 23:03:38 +000022
23 The following are the verbatim comments from the original code:
24
25 A C-program for MT19937, with initialization improved 2002/1/26.
26 Coded by Takuji Nishimura and Makoto Matsumoto.
27
28 Before using, initialize the state by using init_genrand(seed)
29 or init_by_array(init_key, key_length).
30
31 Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
32 All rights reserved.
33
34 Redistribution and use in source and binary forms, with or without
35 modification, are permitted provided that the following conditions
36 are met:
37
38 1. Redistributions of source code must retain the above copyright
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 notice, this list of conditions and the following disclaimer.
Raymond Hettinger40f62172002-12-29 23:03:38 +000040
41 2. Redistributions in binary form must reproduce the above copyright
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 notice, this list of conditions and the following disclaimer in the
43 documentation and/or other materials provided with the distribution.
Raymond Hettinger40f62172002-12-29 23:03:38 +000044
45 3. The names of its contributors may not be used to endorse or promote
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 products derived from this software without specific prior written
47 permission.
Raymond Hettinger40f62172002-12-29 23:03:38 +000048
49 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
50 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
51 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
52 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
53 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
54 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
55 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
56 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
57 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
58 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
59 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
60
61
62 Any feedback is very welcome.
Hiroki Nodaf15fa872017-02-15 18:04:43 +090063 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
64 email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
Raymond Hettinger40f62172002-12-29 23:03:38 +000065*/
66
67/* ---------------------------------------------------------------*/
68
69#include "Python.h"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070#include <time.h> /* for seeding to current time */
Victor Stinner9f2a9202016-09-06 17:03:03 -070071#ifdef HAVE_PROCESS_H
72# include <process.h> /* needed for getpid() */
73#endif
Raymond Hettinger40f62172002-12-29 23:03:38 +000074
75/* Period parameters -- These are all magic. Don't change. */
76#define N 624
77#define M 397
Serhiy Storchakadce04052015-05-13 15:02:12 +030078#define MATRIX_A 0x9908b0dfU /* constant vector a */
79#define UPPER_MASK 0x80000000U /* most significant w-r bits */
80#define LOWER_MASK 0x7fffffffU /* least significant r bits */
Raymond Hettinger40f62172002-12-29 23:03:38 +000081
82typedef struct {
Dino Viehland04f0bbf2019-09-13 11:12:27 +010083 PyObject *Random_Type;
84 PyObject *Long___abs__;
85} _randomstate;
86
87#define _randomstate(o) ((_randomstate *)PyModule_GetState(o))
88
89static struct PyModuleDef _randommodule;
90
91#define _randomstate_global _randomstate(PyState_FindModule(&_randommodule))
92
93typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 int index;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070096 uint32_t state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +000097} RandomObject;
98
Raymond Hettinger40f62172002-12-29 23:03:38 +000099
Pablo Galindo561612d2019-05-24 22:09:23 +0100100#include "clinic/_randommodule.c.h"
101
102/*[clinic input]
103module _random
104class _random.Random "RandomObject *" "&Random_Type"
105[clinic start generated code]*/
106/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f79898ae7847c321]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000107
108/* Random methods */
109
110
111/* generates a random number on [0,0xffffffff]-interval */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700112static uint32_t
Raymond Hettinger40f62172002-12-29 23:03:38 +0000113genrand_int32(RandomObject *self)
114{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700115 uint32_t y;
116 static const uint32_t mag01[2] = {0x0U, MATRIX_A};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 /* mag01[x] = x * MATRIX_A for x=0,1 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700118 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 mt = self->state;
121 if (self->index >= N) { /* generate N words at one time */
122 int kk;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 for (kk=0;kk<N-M;kk++) {
125 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300126 mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 }
128 for (;kk<N-1;kk++) {
129 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300130 mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 }
132 y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300133 mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 self->index = 0;
136 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000137
138 y = mt[self->index++];
139 y ^= (y >> 11);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300140 y ^= (y << 7) & 0x9d2c5680U;
141 y ^= (y << 15) & 0xefc60000U;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000142 y ^= (y >> 18);
143 return y;
144}
145
146/* random_random is the function named genrand_res53 in the original code;
147 * generates a random number on [0,1) with 53-bit resolution; note that
148 * 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
149 * multiply-by-reciprocal in the (likely vain) hope that the compiler will
150 * optimize the division away at compile-time. 67108864 is 2**26. In
151 * effect, a contains 27 random bits shifted left 26, and b fills in the
152 * lower 26 bits of the 53-bit numerator.
Berker Peksag0ac70c02016-04-29 16:54:10 +0300153 * The original code credited Isaku Wada for this algorithm, 2002/01/09.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000154 */
Pablo Galindo561612d2019-05-24 22:09:23 +0100155
156/*[clinic input]
157_random.Random.random
158
159 self: self(type="RandomObject *")
160
161random() -> x in the interval [0, 1).
162[clinic start generated code]*/
163
Raymond Hettinger40f62172002-12-29 23:03:38 +0000164static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100165_random_Random_random_impl(RandomObject *self)
166/*[clinic end generated code: output=117ff99ee53d755c input=afb2a59cbbb00349]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000167{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700168 uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
Raymond Hettinger40f62172002-12-29 23:03:38 +0000170}
171
172/* initializes mt[N] with a seed */
173static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700174init_genrand(RandomObject *self, uint32_t s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 int mti;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700177 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300180 mt[0]= s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 for (mti=1; mti<N; mti++) {
182 mt[mti] =
Serhiy Storchakadce04052015-05-13 15:02:12 +0300183 (1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
185 /* In the previous versions, MSBs of the seed affect */
186 /* only MSBs of the array mt[]. */
187 /* 2002/01/09 modified by Makoto Matsumoto */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 }
189 self->index = mti;
190 return;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000191}
192
193/* initialize by an array with array-length */
194/* init_key is the array for initializing keys */
195/* key_length is its length */
Victor Stinnere66987e2016-09-06 16:33:52 -0700196static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700197init_by_array(RandomObject *self, uint32_t init_key[], size_t key_length)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000198{
Mark Dickinson4cd60172012-12-21 21:52:49 +0000199 size_t i, j, k; /* was signed in the original code. RDH 12/16/2002 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700200 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300203 init_genrand(self, 19650218U);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 i=1; j=0;
205 k = (N>key_length ? N : key_length);
206 for (; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300207 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700208 + init_key[j] + (uint32_t)j; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 i++; j++;
210 if (i>=N) { mt[0] = mt[N-1]; i=1; }
211 if (j>=key_length) j=0;
212 }
213 for (k=N-1; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300214 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700215 - (uint32_t)i; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 i++;
217 if (i>=N) { mt[0] = mt[N-1]; i=1; }
218 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000219
Serhiy Storchakadce04052015-05-13 15:02:12 +0300220 mt[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000221}
222
223/*
224 * The rest is Python-specific code, neither part of, nor derived from, the
225 * Twister download.
226 */
227
Victor Stinnere66987e2016-09-06 16:33:52 -0700228static int
229random_seed_urandom(RandomObject *self)
230{
231 PY_UINT32_T key[N];
232
233 if (_PyOS_URandomNonblock(key, sizeof(key)) < 0) {
234 return -1;
235 }
236 init_by_array(self, key, Py_ARRAY_LENGTH(key));
237 return 0;
238}
239
240static void
241random_seed_time_pid(RandomObject *self)
242{
243 _PyTime_t now;
244 uint32_t key[5];
245
246 now = _PyTime_GetSystemClock();
247 key[0] = (PY_UINT32_T)(now & 0xffffffffU);
248 key[1] = (PY_UINT32_T)(now >> 32);
249
250 key[2] = (PY_UINT32_T)getpid();
251
252 now = _PyTime_GetMonotonicClock();
253 key[3] = (PY_UINT32_T)(now & 0xffffffffU);
254 key[4] = (PY_UINT32_T)(now >> 32);
255
256 init_by_array(self, key, Py_ARRAY_LENGTH(key));
257}
258
Raymond Hettinger40f62172002-12-29 23:03:38 +0000259static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100260random_seed(RandomObject *self, PyObject *arg)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 PyObject *n = NULL;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700264 uint32_t *key = NULL;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300265 size_t bits, keyused;
Mark Dickinson4cd60172012-12-21 21:52:49 +0000266 int res;
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100267 PyObject *args[1];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000268
Pablo Galindo561612d2019-05-24 22:09:23 +0100269 if (arg == NULL || arg == Py_None) {
270 if (random_seed_urandom(self) < 0) {
Victor Stinnere66987e2016-09-06 16:33:52 -0700271 PyErr_Clear();
Raymond Hettinger40f62172002-12-29 23:03:38 +0000272
Victor Stinnere66987e2016-09-06 16:33:52 -0700273 /* Reading system entropy failed, fall back on the worst entropy:
274 use the current time and process identifier. */
275 random_seed_time_pid(self);
276 }
277 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 }
Victor Stinnere66987e2016-09-06 16:33:52 -0700279
Larry Hastingsd60cd422012-06-24 02:52:21 -0700280 /* This algorithm relies on the number being unsigned.
281 * So: if the arg is a PyLong, use its absolute value.
282 * Otherwise use its hash value, cast to unsigned.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 */
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100284 if (PyLong_CheckExact(arg)) {
285 n = PyNumber_Absolute(arg);
286 } else if (PyLong_Check(arg)) {
Oren Milmand780b2d2017-09-28 10:50:01 +0300287 /* Calling int.__abs__() prevents calling arg.__abs__(), which might
288 return an invalid value. See issue #31478. */
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100289 args[0] = arg;
Petr Viktorinffd97532020-02-11 17:46:57 +0100290 n = PyObject_Vectorcall(_randomstate_global->Long___abs__, args, 0,
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100291 NULL);
Oren Milmand780b2d2017-09-28 10:50:01 +0300292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 else {
Larry Hastingsd60cd422012-06-24 02:52:21 -0700294 Py_hash_t hash = PyObject_Hash(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (hash == -1)
296 goto Done;
Larry Hastingsd60cd422012-06-24 02:52:21 -0700297 n = PyLong_FromSize_t((size_t)hash);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 }
299 if (n == NULL)
300 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000301
Mark Dickinson4cd60172012-12-21 21:52:49 +0000302 /* Now split n into 32-bit chunks, from the right. */
303 bits = _PyLong_NumBits(n);
304 if (bits == (size_t)-1 && PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000306
Mark Dickinson4cd60172012-12-21 21:52:49 +0000307 /* Figure out how many 32-bit chunks this gives us. */
308 keyused = bits == 0 ? 1 : (bits - 1) / 32 + 1;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000309
Mark Dickinson4cd60172012-12-21 21:52:49 +0000310 /* Convert seed to byte sequence. */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700311 key = (uint32_t *)PyMem_Malloc((size_t)4 * keyused);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300312 if (key == NULL) {
Victor Stinnera4ced862013-07-15 20:00:36 +0200313 PyErr_NoMemory();
Mark Dickinson4cd60172012-12-21 21:52:49 +0000314 goto Done;
Victor Stinnera4ced862013-07-15 20:00:36 +0200315 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000316 res = _PyLong_AsByteArray((PyLongObject *)n,
Serhiy Storchakadce04052015-05-13 15:02:12 +0300317 (unsigned char *)key, keyused * 4,
318 PY_LITTLE_ENDIAN,
Mark Dickinson4cd60172012-12-21 21:52:49 +0000319 0); /* unsigned */
320 if (res == -1) {
Mark Dickinson4cd60172012-12-21 21:52:49 +0000321 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000323
Serhiy Storchakadce04052015-05-13 15:02:12 +0300324#if PY_BIG_ENDIAN
325 {
326 size_t i, j;
327 /* Reverse an array. */
Zachary Warec15ea4c2015-05-17 23:46:22 -0500328 for (i = 0, j = keyused - 1; i < j; i++, j--) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700329 uint32_t tmp = key[i];
Serhiy Storchakadce04052015-05-13 15:02:12 +0300330 key[i] = key[j];
331 key[j] = tmp;
332 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000333 }
Serhiy Storchakadce04052015-05-13 15:02:12 +0300334#endif
Victor Stinnere66987e2016-09-06 16:33:52 -0700335 init_by_array(self, key, keyused);
336
337 Py_INCREF(Py_None);
338 result = Py_None;
339
Raymond Hettinger40f62172002-12-29 23:03:38 +0000340Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 Py_XDECREF(n);
342 PyMem_Free(key);
343 return result;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000344}
345
Pablo Galindo561612d2019-05-24 22:09:23 +0100346/*[clinic input]
347_random.Random.seed
348
349 self: self(type="RandomObject *")
350 n: object = None
351 /
352
353seed([n]) -> None.
354
355Defaults to use urandom and falls back to a combination
356of the current time and the process identifier.
357[clinic start generated code]*/
358
Raymond Hettinger40f62172002-12-29 23:03:38 +0000359static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100360_random_Random_seed_impl(RandomObject *self, PyObject *n)
361/*[clinic end generated code: output=0fad1e16ba883681 input=78d6ef0d52532a54]*/
362{
363 return random_seed(self, n);
364}
365
366/*[clinic input]
367_random.Random.getstate
368
369 self: self(type="RandomObject *")
370
371getstate() -> tuple containing the current state.
372[clinic start generated code]*/
373
374static PyObject *
375_random_Random_getstate_impl(RandomObject *self)
376/*[clinic end generated code: output=bf6cef0c092c7180 input=b937a487928c0e89]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 PyObject *state;
379 PyObject *element;
380 int i;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 state = PyTuple_New(N+1);
383 if (state == NULL)
384 return NULL;
385 for (i=0; i<N ; i++) {
386 element = PyLong_FromUnsignedLong(self->state[i]);
387 if (element == NULL)
388 goto Fail;
389 PyTuple_SET_ITEM(state, i, element);
390 }
391 element = PyLong_FromLong((long)(self->index));
392 if (element == NULL)
393 goto Fail;
394 PyTuple_SET_ITEM(state, i, element);
395 return state;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000396
397Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 Py_DECREF(state);
399 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000400}
401
Pablo Galindo561612d2019-05-24 22:09:23 +0100402
403/*[clinic input]
404_random.Random.setstate
405
406 self: self(type="RandomObject *")
407 state: object
408 /
409
410setstate(state) -> None. Restores generator state.
411[clinic start generated code]*/
412
Raymond Hettinger40f62172002-12-29 23:03:38 +0000413static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100414_random_Random_setstate(RandomObject *self, PyObject *state)
415/*[clinic end generated code: output=fd1c3cd0037b6681 input=b3b4efbb1bc66af8]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 int i;
418 unsigned long element;
419 long index;
bladebryan9616a822017-04-21 23:10:46 -0700420 uint32_t new_state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (!PyTuple_Check(state)) {
423 PyErr_SetString(PyExc_TypeError,
424 "state vector must be a tuple");
425 return NULL;
426 }
427 if (PyTuple_Size(state) != N+1) {
428 PyErr_SetString(PyExc_ValueError,
429 "state vector is the wrong size");
430 return NULL;
431 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 for (i=0; i<N ; i++) {
434 element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
435 if (element == (unsigned long)-1 && PyErr_Occurred())
436 return NULL;
bladebryan9616a822017-04-21 23:10:46 -0700437 new_state[i] = (uint32_t)element;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
441 if (index == -1 && PyErr_Occurred())
442 return NULL;
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300443 if (index < 0 || index > N) {
444 PyErr_SetString(PyExc_ValueError, "invalid state");
445 return NULL;
446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 self->index = (int)index;
bladebryan9616a822017-04-21 23:10:46 -0700448 for (i = 0; i < N; i++)
449 self->state[i] = new_state[i];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000450
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200451 Py_RETURN_NONE;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000452}
453
Pablo Galindo561612d2019-05-24 22:09:23 +0100454/*[clinic input]
455
456_random.Random.getrandbits
457
458 self: self(type="RandomObject *")
459 k: int
460 /
461
462getrandbits(k) -> x. Generates an int with k random bits.
463[clinic start generated code]*/
464
Raymond Hettinger40f62172002-12-29 23:03:38 +0000465static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100466_random_Random_getrandbits_impl(RandomObject *self, int k)
467/*[clinic end generated code: output=b402f82a2158887f input=8c0e6396dd176fc0]*/
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000468{
Pablo Galindo561612d2019-05-24 22:09:23 +0100469 int i, words;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700470 uint32_t r;
471 uint32_t *wordarray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (k <= 0) {
475 PyErr_SetString(PyExc_ValueError,
476 "number of bits must be greater than zero");
477 return NULL;
478 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000479
Serhiy Storchakad8a0bac2013-01-04 12:18:35 +0200480 if (k <= 32) /* Fast path */
481 return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));
482
Serhiy Storchakadce04052015-05-13 15:02:12 +0300483 words = (k - 1) / 32 + 1;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700484 wordarray = (uint32_t *)PyMem_Malloc(words * 4);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300485 if (wordarray == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyErr_NoMemory();
487 return NULL;
488 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000489
Serhiy Storchakadce04052015-05-13 15:02:12 +0300490 /* Fill-out bits of long integer, by 32-bit words, from least significant
491 to most significant. */
492#if PY_LITTLE_ENDIAN
493 for (i = 0; i < words; i++, k -= 32)
494#else
495 for (i = words - 1; i >= 0; i--, k -= 32)
496#endif
497 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 r = genrand_int32(self);
499 if (k < 32)
Serhiy Storchakadce04052015-05-13 15:02:12 +0300500 r >>= (32 - k); /* Drop least significant bits */
501 wordarray[i] = r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000503
Serhiy Storchakadce04052015-05-13 15:02:12 +0300504 result = _PyLong_FromByteArray((unsigned char *)wordarray, words * 4,
505 PY_LITTLE_ENDIAN, 0 /* unsigned */);
506 PyMem_Free(wordarray);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 return result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000508}
509
510static PyObject *
Raymond Hettinger40f62172002-12-29 23:03:38 +0000511random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 RandomObject *self;
514 PyObject *tmp;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000515
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100516 if (type == (PyTypeObject*)_randomstate_global->Random_Type &&
517 !_PyArg_NoKeywords("Random()", kwds)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return NULL;
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100519 }
Georg Brandl02c42872005-08-26 06:42:30 +0000520
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100521 self = (RandomObject *)PyType_GenericAlloc(type, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (self == NULL)
523 return NULL;
524 tmp = random_seed(self, args);
525 if (tmp == NULL) {
526 Py_DECREF(self);
527 return NULL;
528 }
529 Py_DECREF(tmp);
530 return (PyObject *)self;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000531}
532
533static PyMethodDef random_methods[] = {
Pablo Galindo561612d2019-05-24 22:09:23 +0100534 _RANDOM_RANDOM_RANDOM_METHODDEF
535 _RANDOM_RANDOM_SEED_METHODDEF
536 _RANDOM_RANDOM_GETSTATE_METHODDEF
537 _RANDOM_RANDOM_SETSTATE_METHODDEF
538 _RANDOM_RANDOM_GETRANDBITS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 {NULL, NULL} /* sentinel */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000540};
541
542PyDoc_STRVAR(random_doc,
543"Random() -> create a random number generator with its own internal state.");
544
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100545static PyType_Slot Random_Type_slots[] = {
Victor Stinner2f902612019-10-01 12:45:52 +0200546 {Py_tp_doc, (void *)random_doc},
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100547 {Py_tp_methods, random_methods},
548 {Py_tp_new, random_new},
549 {Py_tp_free, PyObject_Free},
550 {0, 0},
551};
552
553static PyType_Spec Random_Type_spec = {
554 "_random.Random",
555 sizeof(RandomObject),
556 0,
557 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
558 Random_Type_slots
Raymond Hettinger40f62172002-12-29 23:03:38 +0000559};
560
561PyDoc_STRVAR(module_doc,
562"Module implements the Mersenne Twister random number generator.");
563
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100564static int
565_random_traverse(PyObject *module, visitproc visit, void *arg)
566{
567 Py_VISIT(_randomstate(module)->Random_Type);
568 return 0;
569}
570
571static int
572_random_clear(PyObject *module)
573{
574 Py_CLEAR(_randomstate(module)->Random_Type);
Dino Viehland09dc2c62019-09-15 15:51:44 +0100575 Py_CLEAR(_randomstate(module)->Long___abs__);
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100576 return 0;
577}
578
579static void
580_random_free(void *module)
581{
582 _random_clear((PyObject *)module);
583}
Martin v. Löwis1a214512008-06-11 05:26:20 +0000584
585static struct PyModuleDef _randommodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PyModuleDef_HEAD_INIT,
587 "_random",
588 module_doc,
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100589 sizeof(_randomstate),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 NULL,
591 NULL,
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100592 _random_traverse,
593 _random_clear,
594 _random_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +0000595};
596
Raymond Hettinger40f62172002-12-29 23:03:38 +0000597PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000598PyInit__random(void)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyObject *m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000601
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100602 PyObject *Random_Type = PyType_FromSpec(&Random_Type_spec);
603 if (Random_Type == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 return NULL;
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100605 }
606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 m = PyModule_Create(&_randommodule);
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100608 if (m == NULL) {
609 Py_DECREF(Random_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return NULL;
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100611 }
612 _randomstate(m)->Random_Type = Random_Type;
613
614 Py_INCREF(Random_Type);
615 PyModule_AddObject(m, "Random", Random_Type);
616
617 /* Look up and save int.__abs__, which is needed in random_seed(). */
618 PyObject *longval = NULL, *longtype = NULL;
619 longval = PyLong_FromLong(0);
620 if (longval == NULL) goto fail;
621
622 longtype = PyObject_Type(longval);
623 if (longtype == NULL) goto fail;
624
625 PyObject *abs = PyObject_GetAttrString(longtype, "__abs__");
626 if (abs == NULL) goto fail;
627
628 Py_DECREF(longtype);
629 Py_DECREF(longval);
630 _randomstate(m)->Long___abs__ = abs;
631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return m;
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100633
634fail:
635 Py_XDECREF(longtype);
636 Py_XDECREF(longval);
637 Py_DECREF(m);
638 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000639}