From 88a98d2d292874d8ac7464e737651b305470c768 Mon Sep 17 00:00:00 2001 From: Adrien Guillo Date: Thu, 29 May 2014 17:38:10 +0200 Subject: [PATCH] Seeding routine refactor, references #1 The seed value is copied over and over until it fills the internal array. --- pyisaac/pyisaac.c | 29 ++++++++++++++++++----------- tests/test_pyisaac.py | 4 +++- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/pyisaac/pyisaac.c b/pyisaac/pyisaac.c index 9febf6e..b39f0ae 100644 --- a/pyisaac/pyisaac.c +++ b/pyisaac/pyisaac.c @@ -3,12 +3,13 @@ #include #include "rand.h" +#define RANDSIZB (RANDSIZ * sizeof(ub4)) static randctx rctx; static void devrandom(char *buffer, int size); -static void seed(char *sd); +static void seed(char *sd, int length); static char module_docstring[] = @@ -39,14 +40,14 @@ static PyMethodDef module_methods[] = { PyMODINIT_FUNC initpyisaac(void) { - char sd[RANDSIZ]; + char sd[RANDSIZB]; PyObject *m = Py_InitModule3("pyisaac", module_methods, module_docstring); if (m == NULL) return; - devrandom(sd, RANDSIZ); - seed(sd); + devrandom(sd, RANDSIZB); + seed(sd, RANDSIZB); } static PyObject *pyisaac_random(PyObject *self) @@ -57,11 +58,12 @@ static PyObject *pyisaac_random(PyObject *self) static PyObject *pyisaac_seed(PyObject *self, PyObject *args) { const char *sd; + int length; - if (!PyArg_ParseTuple(args, "s", &sd)) + if (!PyArg_ParseTuple(args, "s#", &sd, &length)) return NULL; - seed(sd); + seed(sd, length); Py_RETURN_NONE; } @@ -96,13 +98,18 @@ static void devrandom(char *buffer, int size) close(fd); } -static void seed(char *sd) +static void seed(char *sd, int length) { - int i; + int i, q, r; // q = quotient, r = remainder - for (i = 0; i < RANDSIZ; ++i) - rctx.randrsl[i] = 0; + q = (RANDSIZB) / length; + r = (RANDSIZB) % length; + + for (i = 0; i < q; i++) + memcpy((char *)rctx.randrsl + i * length, sd, length); + + if (r) + memcpy((char *)rctx.randrsl + q * length, sd, r); - memcpy((char *)rctx.randrsl, sd, strnlen(sd, RANDSIZ)); randinit(&rctx, TRUE); } diff --git a/tests/test_pyisaac.py b/tests/test_pyisaac.py index cbb41c6..2f59bb6 100644 --- a/tests/test_pyisaac.py +++ b/tests/test_pyisaac.py @@ -11,7 +11,9 @@ def test_pyisaac(self): """ Test pyisaac with a seed and results provided by Bob Jenkins. """ - seed = 'This is not the right mytext.' + mytext = 'This is not the right mytext.' + + seed = mytext + '\x00' * (1024 - len(mytext)) pyisaac.seed(seed) self.assertListEqual([pyisaac.random() for _ in range(256 * 10)], RESULTS) \ No newline at end of file