Skip to content

Commit

Permalink
Seeding routine refactor, references #1
Browse files Browse the repository at this point in the history
The seed value is copied over and over until it fills the internal array.
  • Loading branch information
guilload committed May 29, 2014
1 parent f05be6b commit 88a98d2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
29 changes: 18 additions & 11 deletions pyisaac/pyisaac.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
#include <string.h>
#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[] =
Expand Down Expand Up @@ -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)
Expand All @@ -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;
}
Expand Down Expand Up @@ -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);
}
4 changes: 3 additions & 1 deletion tests/test_pyisaac.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ def test_pyisaac(self):
"""
Test pyisaac with a seed and results provided by Bob Jenkins.
"""
seed = 'This is <i>not</i> the right mytext.'
mytext = 'This is <i>not</i> the right mytext.'

seed = mytext + '\x00' * (1024 - len(mytext))
pyisaac.seed(seed)

self.assertListEqual([pyisaac.random() for _ in range(256 * 10)], RESULTS)

0 comments on commit 88a98d2

Please sign in to comment.