| 1 |
#include "pythoncapi_compat.h" |
| 2 |
|
| 3 |
#define PY_SSIZE_T_CLEAN |
| 4 |
#include <Python.h> |
| 5 |
#include <stdint.h> |
| 6 |
#include <string.h> |
| 7 |
|
| 8 |
#ifdef _WIN32 |
| 9 |
#include <windows.h> |
| 10 |
#else |
| 11 |
#include <pthread.h> |
| 12 |
#endif |
| 13 |
|
| 14 |
#include "mypyc_util.h" |
| 15 |
#include "CPy.h" |
| 16 |
#include "librt_random.h" |
| 17 |
|
| 18 |
// |
| 19 |
// ChaCha8 PRNG with forward secrecy |
| 20 |
// |
| 21 |
|
| 22 |
#define CHACHA8_RESEED_INTERVAL 16 |
| 23 |
|
| 24 |
typedef struct { |
| 25 |
uint32_t seed[8]; // 256-bit key |
| 26 |
uint32_t buf[16]; // output buffer: one ChaCha8 block |
| 27 |
uint32_t counter; // block counter |
| 28 |
uint8_t used; // index into buf |
| 29 |
uint8_t n; // usable values in buf (8 or 16) |
| 30 |
uint8_t blocks_left; // blocks until next reseed |
| 31 |
} chacha8_rng; |
| 32 |
|
| 33 |
static inline uint32_t |
| 34 |
rotl32(uint32_t x, int n) { |
| 35 |
return (x << n) | (x >> (32 - n)); |
| 36 |
} |
| 37 |
|
| 38 |
#define QUARTERROUND(a, b, c, d) \ |
| 39 |
do { \ |
| 40 |
a += b; d ^= a; d = rotl32(d, 16); \ |
| 41 |
c += d; b ^= c; b = rotl32(b, 12); \ |
| 42 |
a += b; d ^= a; d = rotl32(d, 8); \ |
| 43 |
c += d; b ^= c; b = rotl32(b, 7); \ |
| 44 |
} while (0) |
| 45 |
|
| 46 |
static void |
| 47 |
chacha8_block(const uint32_t seed[8], uint32_t counter, uint32_t out[16]) |
| 48 |
{ |
| 49 |
// "expand 32-byte k" |
| 50 |
uint32_t s[16] = { |
| 51 |
0x61707865, 0x3320646e, 0x79622d32, 0x6b206574, |
| 52 |
seed[0], seed[1], seed[2], seed[3], |
| 53 |
seed[4], seed[5], seed[6], seed[7], |
| 54 |
counter, 0, 0, 0 // counter (low 32), counter (high 32), nonce |
| 55 |
}; |
| 56 |
|
| 57 |
memcpy(out, s, sizeof(uint32_t) * 16); |
| 58 |
|
| 59 |
// 4 double-rounds = 8 rounds |
| 60 |
for (int i = 0; i < 4; i++) { |
| 61 |
// Column rounds |
| 62 |
QUARTERROUND(out[0], out[4], out[ 8], out[12]); |
| 63 |
QUARTERROUND(out[1], out[5], out[ 9], out[13]); |
| 64 |
QUARTERROUND(out[2], out[6], out[10], out[14]); |
| 65 |
QUARTERROUND(out[3], out[7], out[11], out[15]); |
| 66 |
// Diagonal rounds |
| 67 |
QUARTERROUND(out[0], out[5], out[10], out[15]); |
| 68 |
QUARTERROUND(out[1], out[6], out[11], out[12]); |
| 69 |
QUARTERROUND(out[2], out[7], out[ 8], out[13]); |
| 70 |
QUARTERROUND(out[3], out[4], out[ 9], out[14]); |
| 71 |
} |
| 72 |
|
| 73 |
// Add original state back (standard ChaCha finalization) |
| 74 |
for (int i = 0; i < 16; i++) |
| 75 |
out[i] += s[i]; |
| 76 |
} |
| 77 |
|
| 78 |
// Fill entropy from OS via os.urandom(), which handles short reads, |
| 79 |
// EINTR, and platform differences internally. |
| 80 |
// Returns 0 on success, -1 on failure (with Python exception set). |
| 81 |
static int |
| 82 |
fill_os_entropy(void *buf, size_t len) |
| 83 |
{ |
| 84 |
PyObject *os_mod = PyImport_ImportModule("os"); |
| 85 |
if (os_mod == NULL) |
| 86 |
return -1; |
| 87 |
PyObject *bytes = PyObject_CallMethod(os_mod, "urandom", "n", (Py_ssize_t)len); |
| 88 |
Py_DECREF(os_mod); |
| 89 |
if (bytes == NULL) |
| 90 |
return -1; |
| 91 |
memcpy(buf, PyBytes_AS_STRING(bytes), len); |
| 92 |
Py_DECREF(bytes); |
| 93 |
return 0; |
| 94 |
} |
| 95 |
|
| 96 |
static void |
| 97 |
chacha8_refill(chacha8_rng *rng) |
| 98 |
{ |
| 99 |
chacha8_block(rng->seed, rng->counter, rng->buf); |
| 100 |
rng->counter++; |
| 101 |
rng->used = 0; |
| 102 |
rng->blocks_left--; |
| 103 |
|
| 104 |
if (unlikely(rng->blocks_left == 0)) { |
| 105 |
// Forward secrecy reseed: steal last 8 words as new key |
| 106 |
memcpy(rng->seed, rng->buf + 8, sizeof(uint32_t) * 8); |
| 107 |
rng->n = 8; // only 8 words usable this block |
| 108 |
rng->counter = 0; |
| 109 |
rng->blocks_left = CHACHA8_RESEED_INTERVAL; |
| 110 |
} else { |
| 111 |
rng->n = 16; |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
static inline uint32_t |
| 116 |
chacha8_next(chacha8_rng *rng) |
| 117 |
{ |
| 118 |
if (unlikely(rng->used >= rng->n)) |
| 119 |
chacha8_refill(rng); |
| 120 |
return rng->buf[rng->used++]; |
| 121 |
} |
| 122 |
|
| 123 |
// Return 64 bits of randomness (two consecutive 32-bit words, single bounds check). |
| 124 |
static inline uint64_t |
| 125 |
chacha8_next64(chacha8_rng *rng) |
| 126 |
{ |
| 127 |
// Need 2 words available; if fewer than 2, refill first. |
| 128 |
if (unlikely(rng->used + 1 >= rng->n)) |
| 129 |
// Use two separate calls to handle block boundary correctly. |
| 130 |
return ((uint64_t)chacha8_next(rng) << 32) | chacha8_next(rng); |
| 131 |
uint32_t hi = rng->buf[rng->used++]; |
| 132 |
uint32_t lo = rng->buf[rng->used++]; |
| 133 |
return ((uint64_t)hi << 32) | lo; |
| 134 |
} |
| 135 |
|
| 136 |
// Return a uniformly distributed random value in [0, range). |
| 137 |
// Use Lemire's nearly divisionless method for small ranges, and a portable |
| 138 |
// rejection sampler for larger ranges to avoid non-standard 128-bit arithmetic. |
| 139 |
static inline uint64_t |
| 140 |
chacha8_next_ranged(chacha8_rng *rng, uint64_t range) |
| 141 |
{ |
| 142 |
assert(range != 0); |
| 143 |
if (likely(range <= UINT32_MAX)) { |
| 144 |
// 32-bit Lemire: multiply r * range to get 64-bit product, |
| 145 |
// upper 32 bits are the result in [0, range). |
| 146 |
uint64_t m = (uint64_t)chacha8_next(rng) * range; |
| 147 |
uint32_t lo = (uint32_t)m; |
| 148 |
if (unlikely(lo < range)) { |
| 149 |
uint32_t thresh = (uint32_t)(-(uint32_t)range) % (uint32_t)range; |
| 150 |
while (lo < thresh) { |
| 151 |
m = (uint64_t)chacha8_next(rng) * range; |
| 152 |
lo = (uint32_t)m; |
| 153 |
} |
| 154 |
} |
| 155 |
return m >> 32; |
| 156 |
} |
| 157 |
// If range is a power of two, masking produces an unbiased result. |
| 158 |
if ((range & (range - 1)) == 0) { |
| 159 |
return chacha8_next64(rng) & (range - 1); |
| 160 |
} |
| 161 |
uint64_t r; |
| 162 |
// In unsigned arithmetic, -range is 2**64 - range, so this computes |
| 163 |
// 2**64 % range. Rejecting values below this threshold leaves exactly |
| 164 |
// floor(2**64 / range) full buckets of size range, avoiding modulo bias. |
| 165 |
uint64_t thresh = -range % range; |
| 166 |
do { |
| 167 |
r = chacha8_next64(rng); |
| 168 |
} while (unlikely(r < thresh)); |
| 169 |
return r % range; |
| 170 |
} |
| 171 |
|
| 172 |
// Return a random i64 starting at 'start', with 'range' possible values. |
| 173 |
// A zero range represents the full 2**64 i64 domain. |
| 174 |
static inline int64_t |
| 175 |
random_i64_from_range(chacha8_rng *rng, int64_t start, uint64_t range) |
| 176 |
{ |
| 177 |
uint64_t offset = range == 0 ? chacha8_next64(rng) : chacha8_next_ranged(rng, range); |
| 178 |
return (int64_t)((uint64_t)start + offset); |
| 179 |
} |
| 180 |
|
| 181 |
static void |
| 182 |
chacha8_reset(chacha8_rng *rng) |
| 183 |
{ |
| 184 |
rng->counter = 0; |
| 185 |
rng->used = 16; // force immediate refill on first call |
| 186 |
rng->n = 16; |
| 187 |
rng->blocks_left = CHACHA8_RESEED_INTERVAL; |
| 188 |
} |
| 189 |
|
| 190 |
static int |
| 191 |
chacha8_init(chacha8_rng *rng) |
| 192 |
{ |
| 193 |
if (fill_os_entropy(rng->seed, sizeof(rng->seed)) < 0) |
| 194 |
return -1; |
| 195 |
chacha8_reset(rng); |
| 196 |
return 0; |
| 197 |
} |
| 198 |
|
| 199 |
// Seed from an integer by hashing it through ChaCha8 to fill the 256-bit key. |
| 200 |
static void |
| 201 |
chacha8_seed_int(chacha8_rng *rng, int64_t seed_val) |
| 202 |
{ |
| 203 |
// Use the integer to construct a simple initial key, then run one |
| 204 |
// ChaCha8 block to diffuse it across all 256 bits. |
| 205 |
memset(rng->seed, 0, sizeof(rng->seed)); |
| 206 |
rng->seed[0] = (uint32_t)(seed_val & 0xFFFFFFFF); |
| 207 |
rng->seed[1] = (uint32_t)((uint64_t)seed_val >> 32); |
| 208 |
|
| 209 |
uint32_t out[16]; |
| 210 |
chacha8_block(rng->seed, 0, out); |
| 211 |
memcpy(rng->seed, out, sizeof(rng->seed)); |
| 212 |
chacha8_reset(rng); |
| 213 |
} |
| 214 |
|
| 215 |
// |
| 216 |
// Thread-local global RNG for module-level random()/randint() |
| 217 |
// |
| 218 |
// thread_local pointer for fast access (direct %fs/%gs-relative load), |
| 219 |
// platform TLS key with destructor for cleanup on thread exit. |
| 220 |
// |
| 221 |
|
| 222 |
#ifdef _WIN32 |
| 223 |
static __declspec(thread) chacha8_rng *tls_rng = NULL; |
| 224 |
#else |
| 225 |
static __thread chacha8_rng *tls_rng = NULL; |
| 226 |
#endif |
| 227 |
|
| 228 |
#ifdef _WIN32 |
| 229 |
static DWORD tls_key = FLS_OUT_OF_INDEXES; |
| 230 |
|
| 231 |
static void NTAPI |
| 232 |
tls_rng_destructor(void *ptr) |
| 233 |
{ |
| 234 |
if (ptr != NULL) { |
| 235 |
memset(ptr, 0, sizeof(chacha8_rng)); |
| 236 |
PyMem_RawFree(ptr); |
| 237 |
} |
| 238 |
} |
| 239 |
#else |
| 240 |
static pthread_key_t tls_key; |
| 241 |
|
| 242 |
static void |
| 243 |
tls_rng_destructor(void *ptr) |
| 244 |
{ |
| 245 |
if (ptr != NULL) { |
| 246 |
memset(ptr, 0, sizeof(chacha8_rng)); |
| 247 |
PyMem_RawFree(ptr); |
| 248 |
} |
| 249 |
} |
| 250 |
#endif |
| 251 |
|
| 252 |
static int tls_key_created = 0; |
| 253 |
|
| 254 |
static int |
| 255 |
ensure_tls_key(void) |
| 256 |
{ |
| 257 |
if (likely(tls_key_created)) |
| 258 |
return 0; |
| 259 |
#ifdef _WIN32 |
| 260 |
tls_key = FlsAlloc(tls_rng_destructor); |
| 261 |
if (tls_key == FLS_OUT_OF_INDEXES) { |
| 262 |
PyErr_SetString(PyExc_OSError, "FlsAlloc failed"); |
| 263 |
return -1; |
| 264 |
} |
| 265 |
#else |
| 266 |
if (pthread_key_create(&tls_key, tls_rng_destructor) != 0) { |
| 267 |
PyErr_SetString(PyExc_OSError, "pthread_key_create failed"); |
| 268 |
return -1; |
| 269 |
} |
| 270 |
#endif |
| 271 |
tls_key_created = 1; |
| 272 |
return 0; |
| 273 |
} |
| 274 |
|
| 275 |
// Get the thread-local RNG, initializing on first use. |
| 276 |
// Returns NULL with Python exception set on failure. |
| 277 |
static inline chacha8_rng * |
| 278 |
get_thread_rng(void) |
| 279 |
{ |
| 280 |
chacha8_rng *rng = tls_rng; |
| 281 |
if (likely(rng != NULL)) |
| 282 |
return rng; |
| 283 |
|
| 284 |
// First use on this thread — allocate and seed |
| 285 |
rng = PyMem_RawMalloc(sizeof(chacha8_rng)); |
| 286 |
if (rng == NULL) { |
| 287 |
PyErr_NoMemory(); |
| 288 |
return NULL; |
| 289 |
} |
| 290 |
if (chacha8_init(rng) < 0) { |
| 291 |
PyMem_RawFree(rng); |
| 292 |
return NULL; |
| 293 |
} |
| 294 |
|
| 295 |
// Register with platform TLS for destructor |
| 296 |
#ifdef _WIN32 |
| 297 |
FlsSetValue(tls_key, rng); |
| 298 |
#else |
| 299 |
pthread_setspecific(tls_key, rng); |
| 300 |
#endif |
| 301 |
|
| 302 |
tls_rng = rng; |
| 303 |
return rng; |
| 304 |
} |
| 305 |
|
| 306 |
// Return a random double in [0.0, 1.0) with 53 bits of mantissa precision. |
| 307 |
static inline double |
| 308 |
random_double_impl(chacha8_rng *rng) |
| 309 |
{ |
| 310 |
uint64_t r = chacha8_next64(rng); |
| 311 |
return (double)(r >> 11) * (1.0 / 9007199254740992.0); // 1/2^53 |
| 312 |
} |
| 313 |
|
| 314 |
// |
| 315 |
// Module-level random() and randint() |
| 316 |
// |
| 317 |
|
| 318 |
static PyObject* |
| 319 |
module_random(PyObject *module, PyObject *Py_UNUSED(ignored)) |
| 320 |
{ |
| 321 |
chacha8_rng *rng = get_thread_rng(); |
| 322 |
if (rng == NULL) |
| 323 |
return NULL; |
| 324 |
return PyFloat_FromDouble(random_double_impl(rng)); |
| 325 |
} |
| 326 |
|
| 327 |
// Generate random integer in [a, b] using the given RNG. |
| 328 |
static inline PyObject* |
| 329 |
randint_impl(chacha8_rng *rng, int64_t a, int64_t b) |
| 330 |
{ |
| 331 |
uint64_t range = (uint64_t)b - (uint64_t)a + 1; |
| 332 |
return PyLong_FromLongLong(random_i64_from_range(rng, a, range)); |
| 333 |
} |
| 334 |
|
| 335 |
static PyObject* |
| 336 |
module_randint(PyObject *module, PyObject *const *args, Py_ssize_t nargs) |
| 337 |
{ |
| 338 |
if (nargs != 2) { |
| 339 |
PyErr_Format(PyExc_TypeError, |
| 340 |
"randint() takes exactly 2 arguments (%zd given)", nargs); |
| 341 |
return NULL; |
| 342 |
} |
| 343 |
|
| 344 |
int64_t a = CPyLong_AsInt64(args[0]); |
| 345 |
if (unlikely(a == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 346 |
return NULL; |
| 347 |
|
| 348 |
int64_t b = CPyLong_AsInt64(args[1]); |
| 349 |
if (unlikely(b == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 350 |
return NULL; |
| 351 |
|
| 352 |
if (a > b) { |
| 353 |
PyErr_SetString(PyExc_ValueError, |
| 354 |
"empty range for randint()"); |
| 355 |
return NULL; |
| 356 |
} |
| 357 |
|
| 358 |
chacha8_rng *rng = get_thread_rng(); |
| 359 |
if (rng == NULL) |
| 360 |
return NULL; |
| 361 |
|
| 362 |
return randint_impl(rng, a, b); |
| 363 |
} |
| 364 |
|
| 365 |
// Parse 1 or 2 int args for randrange([start,] stop). |
| 366 |
// Sets *a to start (default 0), *b to stop-1. |
| 367 |
// Returns 0 on success, -1 on error (with exception set). |
| 368 |
static int |
| 369 |
parse_randrange_args(PyObject *const *args, Py_ssize_t nargs, |
| 370 |
int64_t *a, int64_t *b) |
| 371 |
{ |
| 372 |
if (nargs == 1) { |
| 373 |
*a = 0; |
| 374 |
int64_t stop = CPyLong_AsInt64(args[0]); |
| 375 |
if (unlikely(stop == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 376 |
return -1; |
| 377 |
if (stop <= 0) { |
| 378 |
PyErr_SetString(PyExc_ValueError, "empty range for randrange()"); |
| 379 |
return -1; |
| 380 |
} |
| 381 |
*b = stop - 1; |
| 382 |
} else if (nargs == 2) { |
| 383 |
*a = CPyLong_AsInt64(args[0]); |
| 384 |
if (unlikely(*a == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 385 |
return -1; |
| 386 |
int64_t stop = CPyLong_AsInt64(args[1]); |
| 387 |
if (unlikely(stop == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 388 |
return -1; |
| 389 |
if (*a >= stop) { |
| 390 |
PyErr_SetString(PyExc_ValueError, "empty range for randrange()"); |
| 391 |
return -1; |
| 392 |
} |
| 393 |
*b = stop - 1; |
| 394 |
} else { |
| 395 |
PyErr_Format(PyExc_TypeError, |
| 396 |
"randrange() takes 1 or 2 arguments (%zd given)", nargs); |
| 397 |
return -1; |
| 398 |
} |
| 399 |
return 0; |
| 400 |
} |
| 401 |
|
| 402 |
static PyObject* |
| 403 |
module_randrange(PyObject *module, PyObject *const *args, Py_ssize_t nargs) |
| 404 |
{ |
| 405 |
int64_t a, b; |
| 406 |
if (parse_randrange_args(args, nargs, &a, &b) < 0) |
| 407 |
return NULL; |
| 408 |
|
| 409 |
chacha8_rng *rng = get_thread_rng(); |
| 410 |
if (rng == NULL) |
| 411 |
return NULL; |
| 412 |
|
| 413 |
return randint_impl(rng, a, b); |
| 414 |
} |
| 415 |
|
| 416 |
static PyObject* |
| 417 |
module_seed(PyObject *module, PyObject *const *args, Py_ssize_t nargs) |
| 418 |
{ |
| 419 |
if (nargs != 1) { |
| 420 |
PyErr_Format(PyExc_TypeError, |
| 421 |
"seed() takes exactly 1 argument (%zd given)", nargs); |
| 422 |
return NULL; |
| 423 |
} |
| 424 |
int64_t seed_val = CPyLong_AsInt64(args[0]); |
| 425 |
if (unlikely(seed_val == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 426 |
return NULL; |
| 427 |
|
| 428 |
chacha8_rng *rng = get_thread_rng(); |
| 429 |
if (rng == NULL) |
| 430 |
return NULL; |
| 431 |
|
| 432 |
chacha8_seed_int(rng, seed_val); |
| 433 |
Py_RETURN_NONE; |
| 434 |
} |
| 435 |
|
| 436 |
// |
| 437 |
// Random Python type |
| 438 |
// |
| 439 |
|
| 440 |
typedef struct { |
| 441 |
PyObject_HEAD |
| 442 |
chacha8_rng rng; |
| 443 |
} RandomObject; |
| 444 |
|
| 445 |
static PyTypeObject RandomType; |
| 446 |
|
| 447 |
static PyObject* |
| 448 |
Random_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
| 449 |
{ |
| 450 |
if (type != &RandomType) { |
| 451 |
PyErr_SetString(PyExc_TypeError, "Random cannot be subclassed"); |
| 452 |
return NULL; |
| 453 |
} |
| 454 |
|
| 455 |
RandomObject *self = (RandomObject *)type->tp_alloc(type, 0); |
| 456 |
// Seeding is done in tp_init |
| 457 |
return (PyObject *)self; |
| 458 |
} |
| 459 |
|
| 460 |
static int |
| 461 |
Random_init(RandomObject *self, PyObject *args, PyObject *kwds) |
| 462 |
{ |
| 463 |
PyObject *seed_obj = NULL; |
| 464 |
|
| 465 |
if (!PyArg_ParseTuple(args, "|O", &seed_obj)) { |
| 466 |
return -1; |
| 467 |
} |
| 468 |
|
| 469 |
if (kwds != NULL && PyDict_Size(kwds) > 0) { |
| 470 |
PyErr_SetString(PyExc_TypeError, |
| 471 |
"Random() takes no keyword arguments"); |
| 472 |
return -1; |
| 473 |
} |
| 474 |
|
| 475 |
if (seed_obj == NULL || seed_obj == Py_None) { |
| 476 |
if (chacha8_init(&self->rng) < 0) |
| 477 |
return -1; |
| 478 |
} else { |
| 479 |
int64_t seed_val = CPyLong_AsInt64(seed_obj); |
| 480 |
if (unlikely(seed_val == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 481 |
return -1; |
| 482 |
chacha8_seed_int(&self->rng, seed_val); |
| 483 |
} |
| 484 |
|
| 485 |
return 0; |
| 486 |
} |
| 487 |
|
| 488 |
// Internal constructors for capsule API (bypass tp_new/tp_init) |
| 489 |
|
| 490 |
static PyObject * |
| 491 |
Random_internal(void) { |
| 492 |
RandomObject *self = (RandomObject *)RandomType.tp_alloc(&RandomType, 0); |
| 493 |
if (self == NULL) |
| 494 |
return NULL; |
| 495 |
if (chacha8_init(&self->rng) < 0) { |
| 496 |
Py_DECREF(self); |
| 497 |
return NULL; |
| 498 |
} |
| 499 |
return (PyObject *)self; |
| 500 |
} |
| 501 |
|
| 502 |
static PyObject * |
| 503 |
Random_from_seed_internal(int64_t seed_val) { |
| 504 |
RandomObject *self = (RandomObject *)RandomType.tp_alloc(&RandomType, 0); |
| 505 |
if (self == NULL) |
| 506 |
return NULL; |
| 507 |
chacha8_seed_int(&self->rng, seed_val); |
| 508 |
return (PyObject *)self; |
| 509 |
} |
| 510 |
|
| 511 |
static PyTypeObject * |
| 512 |
Random_type_internal(void) { |
| 513 |
return &RandomType; |
| 514 |
} |
| 515 |
|
| 516 |
static int64_t |
| 517 |
Random_randrange1_internal(PyObject *self, int64_t stop) { |
| 518 |
if (unlikely(stop <= 0)) { |
| 519 |
PyErr_SetString(PyExc_ValueError, "empty range for randrange()"); |
| 520 |
return CPY_LL_INT_ERROR; |
| 521 |
} |
| 522 |
return (int64_t)chacha8_next_ranged(&((RandomObject *)self)->rng, (uint64_t)stop); |
| 523 |
} |
| 524 |
|
| 525 |
static int64_t |
| 526 |
Random_randrange2_internal(PyObject *self, int64_t start, int64_t stop) { |
| 527 |
if (unlikely(start >= stop)) { |
| 528 |
PyErr_SetString(PyExc_ValueError, "empty range for randrange()"); |
| 529 |
return CPY_LL_INT_ERROR; |
| 530 |
} |
| 531 |
uint64_t range = (uint64_t)stop - (uint64_t)start; |
| 532 |
return random_i64_from_range(&((RandomObject *)self)->rng, start, range); |
| 533 |
} |
| 534 |
|
| 535 |
static int64_t |
| 536 |
Random_randint_internal(PyObject *self, int64_t a, int64_t b) { |
| 537 |
if (unlikely(a > b)) { |
| 538 |
PyErr_SetString(PyExc_ValueError, "empty range for randint()"); |
| 539 |
return CPY_LL_INT_ERROR; |
| 540 |
} |
| 541 |
uint64_t range = (uint64_t)b - (uint64_t)a + 1; |
| 542 |
return random_i64_from_range(&((RandomObject *)self)->rng, a, range); |
| 543 |
} |
| 544 |
|
| 545 |
static double |
| 546 |
Random_random_internal(PyObject *self) { |
| 547 |
return random_double_impl(&((RandomObject *)self)->rng); |
| 548 |
} |
| 549 |
|
| 550 |
static PyObject* |
| 551 |
Random_randint(RandomObject *self, PyObject *const *args, Py_ssize_t nargs) { |
| 552 |
if (nargs != 2) { |
| 553 |
PyErr_Format(PyExc_TypeError, |
| 554 |
"randint() takes exactly 2 arguments (%zd given)", nargs); |
| 555 |
return NULL; |
| 556 |
} |
| 557 |
|
| 558 |
int64_t a = CPyLong_AsInt64(args[0]); |
| 559 |
if (unlikely(a == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 560 |
return NULL; |
| 561 |
|
| 562 |
int64_t b = CPyLong_AsInt64(args[1]); |
| 563 |
if (unlikely(b == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 564 |
return NULL; |
| 565 |
|
| 566 |
if (a > b) { |
| 567 |
PyErr_SetString(PyExc_ValueError, |
| 568 |
"empty range for randint()"); |
| 569 |
return NULL; |
| 570 |
} |
| 571 |
|
| 572 |
return randint_impl(&self->rng, a, b); |
| 573 |
} |
| 574 |
|
| 575 |
static PyObject* |
| 576 |
Random_randrange(RandomObject *self, PyObject *const *args, Py_ssize_t nargs) { |
| 577 |
int64_t a, b; |
| 578 |
if (parse_randrange_args(args, nargs, &a, &b) < 0) |
| 579 |
return NULL; |
| 580 |
return randint_impl(&self->rng, a, b); |
| 581 |
} |
| 582 |
|
| 583 |
static PyObject* |
| 584 |
Random_random(RandomObject *self, PyObject *Py_UNUSED(ignored)) { |
| 585 |
return PyFloat_FromDouble(random_double_impl(&self->rng)); |
| 586 |
} |
| 587 |
|
| 588 |
static PyObject* |
| 589 |
Random_seed(RandomObject *self, PyObject *const *args, Py_ssize_t nargs) { |
| 590 |
if (nargs != 1) { |
| 591 |
PyErr_Format(PyExc_TypeError, |
| 592 |
"seed() takes exactly 1 argument (%zd given)", nargs); |
| 593 |
return NULL; |
| 594 |
} |
| 595 |
int64_t seed_val = CPyLong_AsInt64(args[0]); |
| 596 |
if (unlikely(seed_val == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 597 |
return NULL; |
| 598 |
chacha8_seed_int(&self->rng, seed_val); |
| 599 |
Py_RETURN_NONE; |
| 600 |
} |
| 601 |
|
| 602 |
static PyMethodDef Random_methods[] = { |
| 603 |
{"randint", (PyCFunction) Random_randint, METH_FASTCALL, |
| 604 |
PyDoc_STR("Return random integer in range [a, b], including both end points.") |
| 605 |
}, |
| 606 |
{"randrange", (PyCFunction) Random_randrange, METH_FASTCALL, |
| 607 |
PyDoc_STR("Return random integer in range [start, stop).") |
| 608 |
}, |
| 609 |
{"random", (PyCFunction) Random_random, METH_NOARGS, |
| 610 |
PyDoc_STR("Return random float in [0.0, 1.0).") |
| 611 |
}, |
| 612 |
{"seed", (PyCFunction) Random_seed, METH_FASTCALL, |
| 613 |
PyDoc_STR("Seed the random number generator with an integer.") |
| 614 |
}, |
| 615 |
{NULL} /* Sentinel */ |
| 616 |
}; |
| 617 |
|
| 618 |
static PyTypeObject RandomType = { |
| 619 |
.ob_base = PyVarObject_HEAD_INIT(NULL, 0) |
| 620 |
.tp_name = "Random", |
| 621 |
.tp_doc = PyDoc_STR("Fast random number generator using ChaCha8"), |
| 622 |
.tp_basicsize = sizeof(RandomObject), |
| 623 |
.tp_itemsize = 0, |
| 624 |
.tp_flags = Py_TPFLAGS_DEFAULT, |
| 625 |
.tp_new = Random_new, |
| 626 |
.tp_init = (initproc) Random_init, |
| 627 |
.tp_methods = Random_methods, |
| 628 |
}; |
| 629 |
|
| 630 |
// Module definition |
| 631 |
|
| 632 |
static PyMethodDef librt_random_module_methods[] = { |
| 633 |
{"random", (PyCFunction) module_random, METH_NOARGS, |
| 634 |
PyDoc_STR("Return random float in [0.0, 1.0) using thread-local RNG.") |
| 635 |
}, |
| 636 |
{"randint", (PyCFunction) module_randint, METH_FASTCALL, |
| 637 |
PyDoc_STR("Return random integer in range [a, b] using thread-local RNG.") |
| 638 |
}, |
| 639 |
{"randrange", (PyCFunction) module_randrange, METH_FASTCALL, |
| 640 |
PyDoc_STR("Return random integer in range [start, stop) using thread-local RNG.") |
| 641 |
}, |
| 642 |
{"seed", (PyCFunction) module_seed, METH_FASTCALL, |
| 643 |
PyDoc_STR("Seed the thread-local RNG with an integer.") |
| 644 |
}, |
| 645 |
{NULL, NULL, 0, NULL} |
| 646 |
}; |
| 647 |
|
| 648 |
// Module-level internal functions for mypyc primitives (use thread-local RNG) |
| 649 |
|
| 650 |
static double |
| 651 |
module_random_internal(void) { |
| 652 |
chacha8_rng *rng = get_thread_rng(); |
| 653 |
if (rng == NULL) |
| 654 |
return CPY_FLOAT_ERROR; |
| 655 |
return random_double_impl(rng); |
| 656 |
} |
| 657 |
|
| 658 |
static int64_t |
| 659 |
module_randint_internal(int64_t a, int64_t b) { |
| 660 |
if (unlikely(a > b)) { |
| 661 |
PyErr_SetString(PyExc_ValueError, "empty range for randint()"); |
| 662 |
return CPY_LL_INT_ERROR; |
| 663 |
} |
| 664 |
chacha8_rng *rng = get_thread_rng(); |
| 665 |
if (rng == NULL) |
| 666 |
return CPY_LL_INT_ERROR; |
| 667 |
uint64_t range = (uint64_t)b - (uint64_t)a + 1; |
| 668 |
return random_i64_from_range(rng, a, range); |
| 669 |
} |
| 670 |
|
| 671 |
static int64_t |
| 672 |
module_randrange1_internal(int64_t stop) { |
| 673 |
if (unlikely(stop <= 0)) { |
| 674 |
PyErr_SetString(PyExc_ValueError, "empty range for randrange()"); |
| 675 |
return CPY_LL_INT_ERROR; |
| 676 |
} |
| 677 |
chacha8_rng *rng = get_thread_rng(); |
| 678 |
if (rng == NULL) |
| 679 |
return CPY_LL_INT_ERROR; |
| 680 |
return (int64_t)chacha8_next_ranged(rng, (uint64_t)stop); |
| 681 |
} |
| 682 |
|
| 683 |
static int64_t |
| 684 |
module_randrange2_internal(int64_t start, int64_t stop) { |
| 685 |
if (unlikely(start >= stop)) { |
| 686 |
PyErr_SetString(PyExc_ValueError, "empty range for randrange()"); |
| 687 |
return CPY_LL_INT_ERROR; |
| 688 |
} |
| 689 |
chacha8_rng *rng = get_thread_rng(); |
| 690 |
if (rng == NULL) |
| 691 |
return CPY_LL_INT_ERROR; |
| 692 |
uint64_t range = (uint64_t)stop - (uint64_t)start; |
| 693 |
return random_i64_from_range(rng, start, range); |
| 694 |
} |
| 695 |
|
| 696 |
static int |
| 697 |
random_abi_version(void) { |
| 698 |
return LIBRT_RANDOM_ABI_VERSION; |
| 699 |
} |
| 700 |
|
| 701 |
static int |
| 702 |
random_api_version(void) { |
| 703 |
return LIBRT_RANDOM_API_VERSION; |
| 704 |
} |
| 705 |
|
| 706 |
static int |
| 707 |
librt_random_module_exec(PyObject *m) |
| 708 |
{ |
| 709 |
if (ensure_tls_key() < 0) { |
| 710 |
return -1; |
| 711 |
} |
| 712 |
if (PyType_Ready(&RandomType) < 0) { |
| 713 |
return -1; |
| 714 |
} |
| 715 |
if (PyModule_AddObjectRef(m, "Random", (PyObject *) &RandomType) < 0) { |
| 716 |
return -1; |
| 717 |
} |
| 718 |
// Export mypyc internal C API via capsule |
| 719 |
static void *librt_random_api[LIBRT_RANDOM_API_LEN] = { |
| 720 |
(void *)random_abi_version, |
| 721 |
(void *)random_api_version, |
| 722 |
(void *)Random_internal, |
| 723 |
(void *)Random_from_seed_internal, |
| 724 |
(void *)Random_type_internal, |
| 725 |
(void *)Random_random_internal, |
| 726 |
(void *)Random_randint_internal, |
| 727 |
(void *)Random_randrange1_internal, |
| 728 |
(void *)Random_randrange2_internal, |
| 729 |
(void *)module_random_internal, |
| 730 |
(void *)module_randint_internal, |
| 731 |
(void *)module_randrange1_internal, |
| 732 |
(void *)module_randrange2_internal, |
| 733 |
}; |
| 734 |
PyObject *c_api_object = PyCapsule_New((void *)librt_random_api, "librt.random._C_API", NULL); |
| 735 |
if (PyModule_Add(m, "_C_API", c_api_object) < 0) { |
| 736 |
return -1; |
| 737 |
} |
| 738 |
return 0; |
| 739 |
} |
| 740 |
|
| 741 |
static PyModuleDef_Slot librt_random_module_slots[] = { |
| 742 |
{Py_mod_exec, librt_random_module_exec}, |
| 743 |
#ifdef Py_MOD_GIL_NOT_USED |
| 744 |
{Py_mod_gil, Py_MOD_GIL_NOT_USED}, |
| 745 |
#endif |
| 746 |
{0, NULL} |
| 747 |
}; |
| 748 |
|
| 749 |
static PyModuleDef librt_random_module = { |
| 750 |
.m_base = PyModuleDef_HEAD_INIT, |
| 751 |
.m_name = "random", |
| 752 |
.m_doc = "Fast random number generation using ChaCha8", |
| 753 |
.m_size = 0, |
| 754 |
.m_methods = librt_random_module_methods, |
| 755 |
.m_slots = librt_random_module_slots, |
| 756 |
}; |
| 757 |
|
| 758 |
PyMODINIT_FUNC |
| 759 |
PyInit_random(void) |
| 760 |
{ |
| 761 |
return PyModuleDef_Init(&librt_random_module); |
| 762 |
} |