blob: 6a48689204c5a580aa4596dc0e4393e20e228e3b [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 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 int index;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070085 uint32_t state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +000086} RandomObject;
87
88static PyTypeObject Random_Type;
89
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
Raymond Hettinger40f62172002-12-29 23:03:38 +000091
92
93/* Random methods */
94
95
96/* generates a random number on [0,0xffffffff]-interval */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070097static uint32_t
Raymond Hettinger40f62172002-12-29 23:03:38 +000098genrand_int32(RandomObject *self)
99{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700100 uint32_t y;
101 static const uint32_t mag01[2] = {0x0U, MATRIX_A};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 /* mag01[x] = x * MATRIX_A for x=0,1 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700103 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 mt = self->state;
106 if (self->index >= N) { /* generate N words at one time */
107 int kk;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 for (kk=0;kk<N-M;kk++) {
110 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300111 mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 }
113 for (;kk<N-1;kk++) {
114 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300115 mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 }
117 y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300118 mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 self->index = 0;
121 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000122
123 y = mt[self->index++];
124 y ^= (y >> 11);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300125 y ^= (y << 7) & 0x9d2c5680U;
126 y ^= (y << 15) & 0xefc60000U;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000127 y ^= (y >> 18);
128 return y;
129}
130
131/* random_random is the function named genrand_res53 in the original code;
132 * generates a random number on [0,1) with 53-bit resolution; note that
133 * 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
134 * multiply-by-reciprocal in the (likely vain) hope that the compiler will
135 * optimize the division away at compile-time. 67108864 is 2**26. In
136 * effect, a contains 27 random bits shifted left 26, and b fills in the
137 * lower 26 bits of the 53-bit numerator.
Berker Peksag0ac70c02016-04-29 16:54:10 +0300138 * The original code credited Isaku Wada for this algorithm, 2002/01/09.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000139 */
140static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530141random_random(RandomObject *self, PyObject *Py_UNUSED(ignored))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000142{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700143 uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
Raymond Hettinger40f62172002-12-29 23:03:38 +0000145}
146
147/* initializes mt[N] with a seed */
148static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700149init_genrand(RandomObject *self, uint32_t s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 int mti;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700152 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300155 mt[0]= s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 for (mti=1; mti<N; mti++) {
157 mt[mti] =
Serhiy Storchakadce04052015-05-13 15:02:12 +0300158 (1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
160 /* In the previous versions, MSBs of the seed affect */
161 /* only MSBs of the array mt[]. */
162 /* 2002/01/09 modified by Makoto Matsumoto */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
164 self->index = mti;
165 return;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000166}
167
168/* initialize by an array with array-length */
169/* init_key is the array for initializing keys */
170/* key_length is its length */
Victor Stinnere66987e2016-09-06 16:33:52 -0700171static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700172init_by_array(RandomObject *self, uint32_t init_key[], size_t key_length)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000173{
Mark Dickinson4cd60172012-12-21 21:52:49 +0000174 size_t i, j, k; /* was signed in the original code. RDH 12/16/2002 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700175 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300178 init_genrand(self, 19650218U);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 i=1; j=0;
180 k = (N>key_length ? N : key_length);
181 for (; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300182 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700183 + init_key[j] + (uint32_t)j; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 i++; j++;
185 if (i>=N) { mt[0] = mt[N-1]; i=1; }
186 if (j>=key_length) j=0;
187 }
188 for (k=N-1; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300189 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700190 - (uint32_t)i; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 i++;
192 if (i>=N) { mt[0] = mt[N-1]; i=1; }
193 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000194
Serhiy Storchakadce04052015-05-13 15:02:12 +0300195 mt[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000196}
197
198/*
199 * The rest is Python-specific code, neither part of, nor derived from, the
200 * Twister download.
201 */
202
Victor Stinnere66987e2016-09-06 16:33:52 -0700203static int
204random_seed_urandom(RandomObject *self)
205{
206 PY_UINT32_T key[N];
207
208 if (_PyOS_URandomNonblock(key, sizeof(key)) < 0) {
209 return -1;
210 }
211 init_by_array(self, key, Py_ARRAY_LENGTH(key));
212 return 0;
213}
214
215static void
216random_seed_time_pid(RandomObject *self)
217{
218 _PyTime_t now;
219 uint32_t key[5];
220
221 now = _PyTime_GetSystemClock();
222 key[0] = (PY_UINT32_T)(now & 0xffffffffU);
223 key[1] = (PY_UINT32_T)(now >> 32);
224
225 key[2] = (PY_UINT32_T)getpid();
226
227 now = _PyTime_GetMonotonicClock();
228 key[3] = (PY_UINT32_T)(now & 0xffffffffU);
229 key[4] = (PY_UINT32_T)(now >> 32);
230
231 init_by_array(self, key, Py_ARRAY_LENGTH(key));
232}
233
Raymond Hettinger40f62172002-12-29 23:03:38 +0000234static PyObject *
235random_seed(RandomObject *self, PyObject *args)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 PyObject *n = NULL;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700239 uint32_t *key = NULL;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300240 size_t bits, keyused;
Mark Dickinson4cd60172012-12-21 21:52:49 +0000241 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyObject *arg = NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
245 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000246
Victor Stinnere66987e2016-09-06 16:33:52 -0700247 if (arg == NULL || arg == Py_None) {
Benjamin Petersonacc2f742016-12-28 20:02:35 -0800248 if (random_seed_urandom(self) < 0) {
Victor Stinnere66987e2016-09-06 16:33:52 -0700249 PyErr_Clear();
Raymond Hettinger40f62172002-12-29 23:03:38 +0000250
Victor Stinnere66987e2016-09-06 16:33:52 -0700251 /* Reading system entropy failed, fall back on the worst entropy:
252 use the current time and process identifier. */
253 random_seed_time_pid(self);
254 }
255 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 }
Victor Stinnere66987e2016-09-06 16:33:52 -0700257
Larry Hastingsd60cd422012-06-24 02:52:21 -0700258 /* This algorithm relies on the number being unsigned.
259 * So: if the arg is a PyLong, use its absolute value.
260 * Otherwise use its hash value, cast to unsigned.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 */
Oren Milmand780b2d2017-09-28 10:50:01 +0300262 if (PyLong_Check(arg)) {
263 /* Calling int.__abs__() prevents calling arg.__abs__(), which might
264 return an invalid value. See issue #31478. */
265 n = PyLong_Type.tp_as_number->nb_absolute(arg);
266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 else {
Larry Hastingsd60cd422012-06-24 02:52:21 -0700268 Py_hash_t hash = PyObject_Hash(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (hash == -1)
270 goto Done;
Larry Hastingsd60cd422012-06-24 02:52:21 -0700271 n = PyLong_FromSize_t((size_t)hash);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 }
273 if (n == NULL)
274 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000275
Mark Dickinson4cd60172012-12-21 21:52:49 +0000276 /* Now split n into 32-bit chunks, from the right. */
277 bits = _PyLong_NumBits(n);
278 if (bits == (size_t)-1 && PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000280
Mark Dickinson4cd60172012-12-21 21:52:49 +0000281 /* Figure out how many 32-bit chunks this gives us. */
282 keyused = bits == 0 ? 1 : (bits - 1) / 32 + 1;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000283
Mark Dickinson4cd60172012-12-21 21:52:49 +0000284 /* Convert seed to byte sequence. */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700285 key = (uint32_t *)PyMem_Malloc((size_t)4 * keyused);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300286 if (key == NULL) {
Victor Stinnera4ced862013-07-15 20:00:36 +0200287 PyErr_NoMemory();
Mark Dickinson4cd60172012-12-21 21:52:49 +0000288 goto Done;
Victor Stinnera4ced862013-07-15 20:00:36 +0200289 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000290 res = _PyLong_AsByteArray((PyLongObject *)n,
Serhiy Storchakadce04052015-05-13 15:02:12 +0300291 (unsigned char *)key, keyused * 4,
292 PY_LITTLE_ENDIAN,
Mark Dickinson4cd60172012-12-21 21:52:49 +0000293 0); /* unsigned */
294 if (res == -1) {
Mark Dickinson4cd60172012-12-21 21:52:49 +0000295 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000297
Serhiy Storchakadce04052015-05-13 15:02:12 +0300298#if PY_BIG_ENDIAN
299 {
300 size_t i, j;
301 /* Reverse an array. */
Zachary Warec15ea4c2015-05-17 23:46:22 -0500302 for (i = 0, j = keyused - 1; i < j; i++, j--) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700303 uint32_t tmp = key[i];
Serhiy Storchakadce04052015-05-13 15:02:12 +0300304 key[i] = key[j];
305 key[j] = tmp;
306 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000307 }
Serhiy Storchakadce04052015-05-13 15:02:12 +0300308#endif
Victor Stinnere66987e2016-09-06 16:33:52 -0700309 init_by_array(self, key, keyused);
310
311 Py_INCREF(Py_None);
312 result = Py_None;
313
Raymond Hettinger40f62172002-12-29 23:03:38 +0000314Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 Py_XDECREF(n);
316 PyMem_Free(key);
317 return result;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000318}
319
320static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530321random_getstate(RandomObject *self, PyObject *Py_UNUSED(ignored))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyObject *state;
324 PyObject *element;
325 int i;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 state = PyTuple_New(N+1);
328 if (state == NULL)
329 return NULL;
330 for (i=0; i<N ; i++) {
331 element = PyLong_FromUnsignedLong(self->state[i]);
332 if (element == NULL)
333 goto Fail;
334 PyTuple_SET_ITEM(state, i, element);
335 }
336 element = PyLong_FromLong((long)(self->index));
337 if (element == NULL)
338 goto Fail;
339 PyTuple_SET_ITEM(state, i, element);
340 return state;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000341
342Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 Py_DECREF(state);
344 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000345}
346
347static PyObject *
348random_setstate(RandomObject *self, PyObject *state)
349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 int i;
351 unsigned long element;
352 long index;
bladebryan9616a822017-04-21 23:10:46 -0700353 uint32_t new_state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (!PyTuple_Check(state)) {
356 PyErr_SetString(PyExc_TypeError,
357 "state vector must be a tuple");
358 return NULL;
359 }
360 if (PyTuple_Size(state) != N+1) {
361 PyErr_SetString(PyExc_ValueError,
362 "state vector is the wrong size");
363 return NULL;
364 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 for (i=0; i<N ; i++) {
367 element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
368 if (element == (unsigned long)-1 && PyErr_Occurred())
369 return NULL;
bladebryan9616a822017-04-21 23:10:46 -0700370 new_state[i] = (uint32_t)element;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
374 if (index == -1 && PyErr_Occurred())
375 return NULL;
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300376 if (index < 0 || index > N) {
377 PyErr_SetString(PyExc_ValueError, "invalid state");
378 return NULL;
379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 self->index = (int)index;
bladebryan9616a822017-04-21 23:10:46 -0700381 for (i = 0; i < N; i++)
382 self->state[i] = new_state[i];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000383
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200384 Py_RETURN_NONE;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000385}
386
Raymond Hettinger40f62172002-12-29 23:03:38 +0000387static PyObject *
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000388random_getrandbits(RandomObject *self, PyObject *args)
389{
Serhiy Storchakadce04052015-05-13 15:02:12 +0300390 int k, i, words;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700391 uint32_t r;
392 uint32_t *wordarray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 PyObject *result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
396 return NULL;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (k <= 0) {
399 PyErr_SetString(PyExc_ValueError,
400 "number of bits must be greater than zero");
401 return NULL;
402 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000403
Serhiy Storchakad8a0bac2013-01-04 12:18:35 +0200404 if (k <= 32) /* Fast path */
405 return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));
406
Serhiy Storchakadce04052015-05-13 15:02:12 +0300407 words = (k - 1) / 32 + 1;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700408 wordarray = (uint32_t *)PyMem_Malloc(words * 4);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300409 if (wordarray == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyErr_NoMemory();
411 return NULL;
412 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000413
Serhiy Storchakadce04052015-05-13 15:02:12 +0300414 /* Fill-out bits of long integer, by 32-bit words, from least significant
415 to most significant. */
416#if PY_LITTLE_ENDIAN
417 for (i = 0; i < words; i++, k -= 32)
418#else
419 for (i = words - 1; i >= 0; i--, k -= 32)
420#endif
421 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 r = genrand_int32(self);
423 if (k < 32)
Serhiy Storchakadce04052015-05-13 15:02:12 +0300424 r >>= (32 - k); /* Drop least significant bits */
425 wordarray[i] = r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000427
Serhiy Storchakadce04052015-05-13 15:02:12 +0300428 result = _PyLong_FromByteArray((unsigned char *)wordarray, words * 4,
429 PY_LITTLE_ENDIAN, 0 /* unsigned */);
430 PyMem_Free(wordarray);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 return result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000432}
433
434static PyObject *
Raymond Hettinger40f62172002-12-29 23:03:38 +0000435random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 RandomObject *self;
438 PyObject *tmp;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000439
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300440 if (type == &Random_Type && !_PyArg_NoKeywords("Random", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return NULL;
Georg Brandl02c42872005-08-26 06:42:30 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 self = (RandomObject *)type->tp_alloc(type, 0);
444 if (self == NULL)
445 return NULL;
446 tmp = random_seed(self, args);
447 if (tmp == NULL) {
448 Py_DECREF(self);
449 return NULL;
450 }
451 Py_DECREF(tmp);
452 return (PyObject *)self;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000453}
454
455static PyMethodDef random_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 {"random", (PyCFunction)random_random, METH_NOARGS,
457 PyDoc_STR("random() -> x in the interval [0, 1).")},
458 {"seed", (PyCFunction)random_seed, METH_VARARGS,
459 PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
460 {"getstate", (PyCFunction)random_getstate, METH_NOARGS,
461 PyDoc_STR("getstate() -> tuple containing the current state.")},
462 {"setstate", (PyCFunction)random_setstate, METH_O,
463 PyDoc_STR("setstate(state) -> None. Restores generator state.")},
464 {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
Serhiy Storchaka95949422013-08-27 19:40:23 +0300465 PyDoc_STR("getrandbits(k) -> x. Generates an int with "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 "k random bits.")},
467 {NULL, NULL} /* sentinel */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000468};
469
470PyDoc_STRVAR(random_doc,
471"Random() -> create a random number generator with its own internal state.");
472
473static PyTypeObject Random_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyVarObject_HEAD_INIT(NULL, 0)
475 "_random.Random", /*tp_name*/
476 sizeof(RandomObject), /*tp_basicsize*/
477 0, /*tp_itemsize*/
478 /* methods */
479 0, /*tp_dealloc*/
480 0, /*tp_print*/
481 0, /*tp_getattr*/
482 0, /*tp_setattr*/
483 0, /*tp_reserved*/
484 0, /*tp_repr*/
485 0, /*tp_as_number*/
486 0, /*tp_as_sequence*/
487 0, /*tp_as_mapping*/
488 0, /*tp_hash*/
489 0, /*tp_call*/
490 0, /*tp_str*/
491 PyObject_GenericGetAttr, /*tp_getattro*/
492 0, /*tp_setattro*/
493 0, /*tp_as_buffer*/
494 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
495 random_doc, /*tp_doc*/
496 0, /*tp_traverse*/
497 0, /*tp_clear*/
498 0, /*tp_richcompare*/
499 0, /*tp_weaklistoffset*/
500 0, /*tp_iter*/
501 0, /*tp_iternext*/
502 random_methods, /*tp_methods*/
503 0, /*tp_members*/
504 0, /*tp_getset*/
505 0, /*tp_base*/
506 0, /*tp_dict*/
507 0, /*tp_descr_get*/
508 0, /*tp_descr_set*/
509 0, /*tp_dictoffset*/
510 0, /*tp_init*/
511 0, /*tp_alloc*/
512 random_new, /*tp_new*/
513 PyObject_Free, /*tp_free*/
514 0, /*tp_is_gc*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000515};
516
517PyDoc_STRVAR(module_doc,
518"Module implements the Mersenne Twister random number generator.");
519
Martin v. Löwis1a214512008-06-11 05:26:20 +0000520
521static struct PyModuleDef _randommodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyModuleDef_HEAD_INIT,
523 "_random",
524 module_doc,
525 -1,
526 NULL,
527 NULL,
528 NULL,
529 NULL,
530 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000531};
532
Raymond Hettinger40f62172002-12-29 23:03:38 +0000533PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000534PyInit__random(void)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 PyObject *m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (PyType_Ready(&Random_Type) < 0)
539 return NULL;
540 m = PyModule_Create(&_randommodule);
541 if (m == NULL)
542 return NULL;
543 Py_INCREF(&Random_Type);
544 PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
545 return m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000546}