blob: 0137e34da650a186010953157654b6fe41173c51 [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
Victor Stinner9f5fe792020-04-17 19:05:35 +020014 * genrand_uint32() and the helper functions, init_genrand()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000015 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"
Victor Stinnercdad2722021-04-22 00:52:52 +020070#include "pycore_moduleobject.h" // _PyModule_GetState()
Victor Stinner9f2a9202016-09-06 17:03:03 -070071#ifdef HAVE_PROCESS_H
Victor Stinner9f5fe792020-04-17 19:05:35 +020072# include <process.h> // getpid()
Victor Stinner9f2a9202016-09-06 17:03:03 -070073#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
Hai Shif707d942020-03-16 21:15:01 +080087static inline _randomstate*
88get_random_state(PyObject *module)
89{
Victor Stinnercdad2722021-04-22 00:52:52 +020090 void *state = _PyModule_GetState(module);
Hai Shif707d942020-03-16 21:15:01 +080091 assert(state != NULL);
92 return (_randomstate *)state;
93}
Dino Viehland04f0bbf2019-09-13 11:12:27 +010094
95static struct PyModuleDef _randommodule;
96
Christian Heimescc0cd432020-11-19 08:46:29 +010097#define _randomstate_type(type) \
98 (get_random_state(_PyType_GetModuleByDef(type, &_randommodule)))
Dino Viehland04f0bbf2019-09-13 11:12:27 +010099
100typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 int index;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700103 uint32_t state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000104} RandomObject;
105
Raymond Hettinger40f62172002-12-29 23:03:38 +0000106
Pablo Galindo561612d2019-05-24 22:09:23 +0100107#include "clinic/_randommodule.c.h"
108
109/*[clinic input]
110module _random
Christian Heimescc0cd432020-11-19 08:46:29 +0100111class _random.Random "RandomObject *" "_randomstate_type(type)->Random_Type"
Pablo Galindo561612d2019-05-24 22:09:23 +0100112[clinic start generated code]*/
Christian Heimescc0cd432020-11-19 08:46:29 +0100113/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70a2c99619474983]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000114
115/* Random methods */
116
117
118/* generates a random number on [0,0xffffffff]-interval */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700119static uint32_t
Victor Stinner9f5fe792020-04-17 19:05:35 +0200120genrand_uint32(RandomObject *self)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000121{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700122 uint32_t y;
123 static const uint32_t mag01[2] = {0x0U, MATRIX_A};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* mag01[x] = x * MATRIX_A for x=0,1 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700125 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 mt = self->state;
128 if (self->index >= N) { /* generate N words at one time */
129 int kk;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 for (kk=0;kk<N-M;kk++) {
132 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300133 mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 }
135 for (;kk<N-1;kk++) {
136 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300137 mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 }
139 y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300140 mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 self->index = 0;
143 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000144
145 y = mt[self->index++];
146 y ^= (y >> 11);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300147 y ^= (y << 7) & 0x9d2c5680U;
148 y ^= (y << 15) & 0xefc60000U;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000149 y ^= (y >> 18);
150 return y;
151}
152
153/* random_random is the function named genrand_res53 in the original code;
154 * generates a random number on [0,1) with 53-bit resolution; note that
155 * 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
156 * multiply-by-reciprocal in the (likely vain) hope that the compiler will
157 * optimize the division away at compile-time. 67108864 is 2**26. In
158 * effect, a contains 27 random bits shifted left 26, and b fills in the
159 * lower 26 bits of the 53-bit numerator.
Berker Peksag0ac70c02016-04-29 16:54:10 +0300160 * The original code credited Isaku Wada for this algorithm, 2002/01/09.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000161 */
Pablo Galindo561612d2019-05-24 22:09:23 +0100162
163/*[clinic input]
164_random.Random.random
165
166 self: self(type="RandomObject *")
167
168random() -> x in the interval [0, 1).
169[clinic start generated code]*/
170
Raymond Hettinger40f62172002-12-29 23:03:38 +0000171static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100172_random_Random_random_impl(RandomObject *self)
173/*[clinic end generated code: output=117ff99ee53d755c input=afb2a59cbbb00349]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000174{
Victor Stinner9f5fe792020-04-17 19:05:35 +0200175 uint32_t a=genrand_uint32(self)>>5, b=genrand_uint32(self)>>6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
Raymond Hettinger40f62172002-12-29 23:03:38 +0000177}
178
179/* initializes mt[N] with a seed */
180static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700181init_genrand(RandomObject *self, uint32_t s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 int mti;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700184 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300187 mt[0]= s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 for (mti=1; mti<N; mti++) {
189 mt[mti] =
Serhiy Storchakadce04052015-05-13 15:02:12 +0300190 (1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
192 /* In the previous versions, MSBs of the seed affect */
193 /* only MSBs of the array mt[]. */
194 /* 2002/01/09 modified by Makoto Matsumoto */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 }
196 self->index = mti;
197 return;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000198}
199
200/* initialize by an array with array-length */
201/* init_key is the array for initializing keys */
202/* key_length is its length */
Victor Stinnere66987e2016-09-06 16:33:52 -0700203static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700204init_by_array(RandomObject *self, uint32_t init_key[], size_t key_length)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000205{
Mark Dickinson4cd60172012-12-21 21:52:49 +0000206 size_t i, j, k; /* was signed in the original code. RDH 12/16/2002 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700207 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300210 init_genrand(self, 19650218U);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 i=1; j=0;
212 k = (N>key_length ? N : key_length);
213 for (; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300214 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700215 + init_key[j] + (uint32_t)j; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 i++; j++;
217 if (i>=N) { mt[0] = mt[N-1]; i=1; }
218 if (j>=key_length) j=0;
219 }
220 for (k=N-1; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300221 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700222 - (uint32_t)i; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 i++;
224 if (i>=N) { mt[0] = mt[N-1]; i=1; }
225 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000226
Serhiy Storchakadce04052015-05-13 15:02:12 +0300227 mt[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000228}
229
230/*
231 * The rest is Python-specific code, neither part of, nor derived from, the
232 * Twister download.
233 */
234
Victor Stinnere66987e2016-09-06 16:33:52 -0700235static int
236random_seed_urandom(RandomObject *self)
237{
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200238 uint32_t key[N];
Victor Stinnere66987e2016-09-06 16:33:52 -0700239
240 if (_PyOS_URandomNonblock(key, sizeof(key)) < 0) {
241 return -1;
242 }
243 init_by_array(self, key, Py_ARRAY_LENGTH(key));
244 return 0;
245}
246
247static void
248random_seed_time_pid(RandomObject *self)
249{
250 _PyTime_t now;
251 uint32_t key[5];
252
253 now = _PyTime_GetSystemClock();
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200254 key[0] = (uint32_t)(now & 0xffffffffU);
255 key[1] = (uint32_t)(now >> 32);
Victor Stinnere66987e2016-09-06 16:33:52 -0700256
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200257 key[2] = (uint32_t)getpid();
Victor Stinnere66987e2016-09-06 16:33:52 -0700258
259 now = _PyTime_GetMonotonicClock();
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200260 key[3] = (uint32_t)(now & 0xffffffffU);
261 key[4] = (uint32_t)(now >> 32);
Victor Stinnere66987e2016-09-06 16:33:52 -0700262
263 init_by_array(self, key, Py_ARRAY_LENGTH(key));
264}
265
Raymond Hettinger40f62172002-12-29 23:03:38 +0000266static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100267random_seed(RandomObject *self, PyObject *arg)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 PyObject *n = NULL;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700271 uint32_t *key = NULL;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300272 size_t bits, keyused;
Mark Dickinson4cd60172012-12-21 21:52:49 +0000273 int res;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000274
Pablo Galindo561612d2019-05-24 22:09:23 +0100275 if (arg == NULL || arg == Py_None) {
276 if (random_seed_urandom(self) < 0) {
Victor Stinnere66987e2016-09-06 16:33:52 -0700277 PyErr_Clear();
Raymond Hettinger40f62172002-12-29 23:03:38 +0000278
Victor Stinnere66987e2016-09-06 16:33:52 -0700279 /* Reading system entropy failed, fall back on the worst entropy:
280 use the current time and process identifier. */
281 random_seed_time_pid(self);
282 }
283 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 }
Victor Stinnere66987e2016-09-06 16:33:52 -0700285
Larry Hastingsd60cd422012-06-24 02:52:21 -0700286 /* This algorithm relies on the number being unsigned.
287 * So: if the arg is a PyLong, use its absolute value.
288 * Otherwise use its hash value, cast to unsigned.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 */
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100290 if (PyLong_CheckExact(arg)) {
291 n = PyNumber_Absolute(arg);
292 } else if (PyLong_Check(arg)) {
Oren Milmand780b2d2017-09-28 10:50:01 +0300293 /* Calling int.__abs__() prevents calling arg.__abs__(), which might
294 return an invalid value. See issue #31478. */
Christian Heimescc0cd432020-11-19 08:46:29 +0100295 _randomstate *state = _randomstate_type(Py_TYPE(self));
296 n = PyObject_CallOneArg(state->Long___abs__, arg);
Oren Milmand780b2d2017-09-28 10:50:01 +0300297 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 else {
Larry Hastingsd60cd422012-06-24 02:52:21 -0700299 Py_hash_t hash = PyObject_Hash(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (hash == -1)
301 goto Done;
Larry Hastingsd60cd422012-06-24 02:52:21 -0700302 n = PyLong_FromSize_t((size_t)hash);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 }
304 if (n == NULL)
305 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000306
Mark Dickinson4cd60172012-12-21 21:52:49 +0000307 /* Now split n into 32-bit chunks, from the right. */
308 bits = _PyLong_NumBits(n);
309 if (bits == (size_t)-1 && PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000311
Mark Dickinson4cd60172012-12-21 21:52:49 +0000312 /* Figure out how many 32-bit chunks this gives us. */
313 keyused = bits == 0 ? 1 : (bits - 1) / 32 + 1;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000314
Mark Dickinson4cd60172012-12-21 21:52:49 +0000315 /* Convert seed to byte sequence. */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700316 key = (uint32_t *)PyMem_Malloc((size_t)4 * keyused);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300317 if (key == NULL) {
Victor Stinnera4ced862013-07-15 20:00:36 +0200318 PyErr_NoMemory();
Mark Dickinson4cd60172012-12-21 21:52:49 +0000319 goto Done;
Victor Stinnera4ced862013-07-15 20:00:36 +0200320 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000321 res = _PyLong_AsByteArray((PyLongObject *)n,
Serhiy Storchakadce04052015-05-13 15:02:12 +0300322 (unsigned char *)key, keyused * 4,
323 PY_LITTLE_ENDIAN,
Mark Dickinson4cd60172012-12-21 21:52:49 +0000324 0); /* unsigned */
325 if (res == -1) {
Mark Dickinson4cd60172012-12-21 21:52:49 +0000326 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000328
Serhiy Storchakadce04052015-05-13 15:02:12 +0300329#if PY_BIG_ENDIAN
330 {
331 size_t i, j;
332 /* Reverse an array. */
Zachary Warec15ea4c2015-05-17 23:46:22 -0500333 for (i = 0, j = keyused - 1; i < j; i++, j--) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700334 uint32_t tmp = key[i];
Serhiy Storchakadce04052015-05-13 15:02:12 +0300335 key[i] = key[j];
336 key[j] = tmp;
337 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000338 }
Serhiy Storchakadce04052015-05-13 15:02:12 +0300339#endif
Victor Stinnere66987e2016-09-06 16:33:52 -0700340 init_by_array(self, key, keyused);
341
342 Py_INCREF(Py_None);
343 result = Py_None;
344
Raymond Hettinger40f62172002-12-29 23:03:38 +0000345Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 Py_XDECREF(n);
347 PyMem_Free(key);
348 return result;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000349}
350
Pablo Galindo561612d2019-05-24 22:09:23 +0100351/*[clinic input]
352_random.Random.seed
353
354 self: self(type="RandomObject *")
355 n: object = None
356 /
357
358seed([n]) -> None.
359
360Defaults to use urandom and falls back to a combination
361of the current time and the process identifier.
362[clinic start generated code]*/
363
Raymond Hettinger40f62172002-12-29 23:03:38 +0000364static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100365_random_Random_seed_impl(RandomObject *self, PyObject *n)
366/*[clinic end generated code: output=0fad1e16ba883681 input=78d6ef0d52532a54]*/
367{
368 return random_seed(self, n);
369}
370
371/*[clinic input]
372_random.Random.getstate
373
374 self: self(type="RandomObject *")
375
376getstate() -> tuple containing the current state.
377[clinic start generated code]*/
378
379static PyObject *
380_random_Random_getstate_impl(RandomObject *self)
381/*[clinic end generated code: output=bf6cef0c092c7180 input=b937a487928c0e89]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *state;
384 PyObject *element;
385 int i;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 state = PyTuple_New(N+1);
388 if (state == NULL)
389 return NULL;
390 for (i=0; i<N ; i++) {
391 element = PyLong_FromUnsignedLong(self->state[i]);
392 if (element == NULL)
393 goto Fail;
394 PyTuple_SET_ITEM(state, i, element);
395 }
396 element = PyLong_FromLong((long)(self->index));
397 if (element == NULL)
398 goto Fail;
399 PyTuple_SET_ITEM(state, i, element);
400 return state;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000401
402Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 Py_DECREF(state);
404 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000405}
406
Pablo Galindo561612d2019-05-24 22:09:23 +0100407
408/*[clinic input]
409_random.Random.setstate
410
411 self: self(type="RandomObject *")
412 state: object
413 /
414
415setstate(state) -> None. Restores generator state.
416[clinic start generated code]*/
417
Raymond Hettinger40f62172002-12-29 23:03:38 +0000418static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100419_random_Random_setstate(RandomObject *self, PyObject *state)
420/*[clinic end generated code: output=fd1c3cd0037b6681 input=b3b4efbb1bc66af8]*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 int i;
423 unsigned long element;
424 long index;
bladebryan9616a822017-04-21 23:10:46 -0700425 uint32_t new_state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (!PyTuple_Check(state)) {
428 PyErr_SetString(PyExc_TypeError,
429 "state vector must be a tuple");
430 return NULL;
431 }
432 if (PyTuple_Size(state) != N+1) {
433 PyErr_SetString(PyExc_ValueError,
434 "state vector is the wrong size");
435 return NULL;
436 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 for (i=0; i<N ; i++) {
439 element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
440 if (element == (unsigned long)-1 && PyErr_Occurred())
441 return NULL;
bladebryan9616a822017-04-21 23:10:46 -0700442 new_state[i] = (uint32_t)element;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
446 if (index == -1 && PyErr_Occurred())
447 return NULL;
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300448 if (index < 0 || index > N) {
449 PyErr_SetString(PyExc_ValueError, "invalid state");
450 return NULL;
451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 self->index = (int)index;
bladebryan9616a822017-04-21 23:10:46 -0700453 for (i = 0; i < N; i++)
454 self->state[i] = new_state[i];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000455
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200456 Py_RETURN_NONE;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000457}
458
Pablo Galindo561612d2019-05-24 22:09:23 +0100459/*[clinic input]
460
461_random.Random.getrandbits
462
463 self: self(type="RandomObject *")
464 k: int
465 /
466
467getrandbits(k) -> x. Generates an int with k random bits.
468[clinic start generated code]*/
469
Raymond Hettinger40f62172002-12-29 23:03:38 +0000470static PyObject *
Pablo Galindo561612d2019-05-24 22:09:23 +0100471_random_Random_getrandbits_impl(RandomObject *self, int k)
472/*[clinic end generated code: output=b402f82a2158887f input=8c0e6396dd176fc0]*/
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000473{
Pablo Galindo561612d2019-05-24 22:09:23 +0100474 int i, words;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700475 uint32_t r;
476 uint32_t *wordarray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyObject *result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000478
Antoine Pitrou75a33782020-04-17 19:32:14 +0200479 if (k < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PyErr_SetString(PyExc_ValueError,
Antoine Pitrou75a33782020-04-17 19:32:14 +0200481 "number of bits must be non-negative");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return NULL;
483 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000484
Antoine Pitrou75a33782020-04-17 19:32:14 +0200485 if (k == 0)
486 return PyLong_FromLong(0);
487
Serhiy Storchakad8a0bac2013-01-04 12:18:35 +0200488 if (k <= 32) /* Fast path */
Victor Stinner9f5fe792020-04-17 19:05:35 +0200489 return PyLong_FromUnsignedLong(genrand_uint32(self) >> (32 - k));
Serhiy Storchakad8a0bac2013-01-04 12:18:35 +0200490
Serhiy Storchakadce04052015-05-13 15:02:12 +0300491 words = (k - 1) / 32 + 1;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700492 wordarray = (uint32_t *)PyMem_Malloc(words * 4);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300493 if (wordarray == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 PyErr_NoMemory();
495 return NULL;
496 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000497
Serhiy Storchakadce04052015-05-13 15:02:12 +0300498 /* Fill-out bits of long integer, by 32-bit words, from least significant
499 to most significant. */
500#if PY_LITTLE_ENDIAN
501 for (i = 0; i < words; i++, k -= 32)
502#else
503 for (i = words - 1; i >= 0; i--, k -= 32)
504#endif
505 {
Victor Stinner9f5fe792020-04-17 19:05:35 +0200506 r = genrand_uint32(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 if (k < 32)
Serhiy Storchakadce04052015-05-13 15:02:12 +0300508 r >>= (32 - k); /* Drop least significant bits */
509 wordarray[i] = r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000511
Serhiy Storchakadce04052015-05-13 15:02:12 +0300512 result = _PyLong_FromByteArray((unsigned char *)wordarray, words * 4,
513 PY_LITTLE_ENDIAN, 0 /* unsigned */);
514 PyMem_Free(wordarray);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 return result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000516}
517
518static PyObject *
Raymond Hettinger40f62172002-12-29 23:03:38 +0000519random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 RandomObject *self;
522 PyObject *tmp;
AMIRb8fde8b2020-12-22 03:15:50 +0330523 PyObject *arg = NULL;
Christian Heimescc0cd432020-11-19 08:46:29 +0100524 _randomstate *state = _randomstate_type(type);
Raymond Hettinger40f62172002-12-29 23:03:38 +0000525
Christian Heimescc0cd432020-11-19 08:46:29 +0100526 if (type == (PyTypeObject*)state->Random_Type &&
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100527 !_PyArg_NoKeywords("Random()", kwds)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 return NULL;
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100529 }
Georg Brandl02c42872005-08-26 06:42:30 +0000530
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100531 self = (RandomObject *)PyType_GenericAlloc(type, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (self == NULL)
533 return NULL;
AMIRb8fde8b2020-12-22 03:15:50 +0330534
535 if (PyTuple_GET_SIZE(args) > 1) {
536 PyErr_SetString(PyExc_TypeError, "Random() requires 0 or 1 argument");
537 return NULL;
538 }
539
540 if (PyTuple_GET_SIZE(args) == 1)
541 arg = PyTuple_GET_ITEM(args, 0);
Victor Stinnercdad2722021-04-22 00:52:52 +0200542
AMIRb8fde8b2020-12-22 03:15:50 +0330543 tmp = random_seed(self, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (tmp == NULL) {
545 Py_DECREF(self);
546 return NULL;
547 }
548 Py_DECREF(tmp);
AMIRb8fde8b2020-12-22 03:15:50 +0330549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return (PyObject *)self;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000551}
552
Dong-hee Na6989af02020-06-21 18:44:58 +0900553
Raymond Hettinger40f62172002-12-29 23:03:38 +0000554static PyMethodDef random_methods[] = {
Pablo Galindo561612d2019-05-24 22:09:23 +0100555 _RANDOM_RANDOM_RANDOM_METHODDEF
556 _RANDOM_RANDOM_SEED_METHODDEF
557 _RANDOM_RANDOM_GETSTATE_METHODDEF
558 _RANDOM_RANDOM_SETSTATE_METHODDEF
559 _RANDOM_RANDOM_GETRANDBITS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 {NULL, NULL} /* sentinel */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000561};
562
563PyDoc_STRVAR(random_doc,
564"Random() -> create a random number generator with its own internal state.");
565
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100566static PyType_Slot Random_Type_slots[] = {
Victor Stinner2f902612019-10-01 12:45:52 +0200567 {Py_tp_doc, (void *)random_doc},
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100568 {Py_tp_methods, random_methods},
569 {Py_tp_new, random_new},
570 {Py_tp_free, PyObject_Free},
571 {0, 0},
572};
573
574static PyType_Spec Random_Type_spec = {
575 "_random.Random",
576 sizeof(RandomObject),
577 0,
578 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
579 Random_Type_slots
Raymond Hettinger40f62172002-12-29 23:03:38 +0000580};
581
582PyDoc_STRVAR(module_doc,
583"Module implements the Mersenne Twister random number generator.");
584
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100585static int
Christian Heimescc0cd432020-11-19 08:46:29 +0100586_random_exec(PyObject *module)
587{
588 _randomstate *state = get_random_state(module);
589
590 state->Random_Type = PyType_FromModuleAndSpec(
591 module, &Random_Type_spec, NULL);
592 if (state->Random_Type == NULL) {
593 return -1;
594 }
595 if (PyModule_AddType(module, (PyTypeObject *)state->Random_Type) < 0) {
596 return -1;
597 }
598
599 /* Look up and save int.__abs__, which is needed in random_seed(). */
Miss Islington (bot)b19ec7f2021-05-04 21:39:09 -0700600 PyObject *longval = PyLong_FromLong(0);
Christian Heimescc0cd432020-11-19 08:46:29 +0100601 if (longval == NULL) {
602 return -1;
603 }
604
605 PyObject *longtype = PyObject_Type(longval);
606 Py_DECREF(longval);
607 if (longtype == NULL) {
608 return -1;
609 }
610
611 state->Long___abs__ = PyObject_GetAttrString(longtype, "__abs__");
612 Py_DECREF(longtype);
613 if (state->Long___abs__ == NULL) {
614 return -1;
615 }
616 return 0;
617}
618
619static PyModuleDef_Slot _random_slots[] = {
620 {Py_mod_exec, _random_exec},
621 {0, NULL}
622};
623
624static int
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100625_random_traverse(PyObject *module, visitproc visit, void *arg)
626{
Hai Shif707d942020-03-16 21:15:01 +0800627 Py_VISIT(get_random_state(module)->Random_Type);
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100628 return 0;
629}
630
631static int
632_random_clear(PyObject *module)
633{
Hai Shif707d942020-03-16 21:15:01 +0800634 Py_CLEAR(get_random_state(module)->Random_Type);
635 Py_CLEAR(get_random_state(module)->Long___abs__);
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100636 return 0;
637}
638
639static void
640_random_free(void *module)
641{
642 _random_clear((PyObject *)module);
643}
Martin v. Löwis1a214512008-06-11 05:26:20 +0000644
645static struct PyModuleDef _randommodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyModuleDef_HEAD_INIT,
647 "_random",
648 module_doc,
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100649 sizeof(_randomstate),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 NULL,
Christian Heimescc0cd432020-11-19 08:46:29 +0100651 _random_slots,
Dino Viehland04f0bbf2019-09-13 11:12:27 +0100652 _random_traverse,
653 _random_clear,
654 _random_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +0000655};
656
Raymond Hettinger40f62172002-12-29 23:03:38 +0000657PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000658PyInit__random(void)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000659{
Christian Heimescc0cd432020-11-19 08:46:29 +0100660 return PyModuleDef_Init(&_randommodule);
Raymond Hettinger40f62172002-12-29 23:03:38 +0000661}