chiark / gitweb /
pgen.c (pgev_python): Delete pointless refcount manipulation.
[catacomb-python] / pgen.c
1 /* -*-c-*-
2  *
3  * Prime number generation
4  *
5  * (c) 2005 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of the Python interface to Catacomb.
11  *
12  * Catacomb/Python is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * Catacomb/Python is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with Catacomb/Python; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "catacomb-python.h"
30
31 /*----- Filters -----------------------------------------------------------*/
32
33 PyTypeObject *pfilt_pytype;
34
35 static PyObject *pfilt_pywrap(pfilt *f)
36 {
37   pfilt_pyobj *o = 0;
38   o = PyObject_New(pfilt_pyobj, pfilt_pytype);
39   o->f = *f;
40   o->st = pfilt_step(f, 0);
41   return ((PyObject *)o);
42 }
43
44 static PyObject *pfilt_pymake(PyTypeObject *ty, PyObject *xobj)
45 {
46   mp *x = 0;
47   pfilt_pyobj *o = 0;
48
49   if (PFILT_PYCHECK(xobj)) RETURN_OBJ(xobj);
50   if ((x = getmp(xobj)) == 0) goto end;
51   o = (pfilt_pyobj *)ty->tp_alloc(ty, 0);
52   o->st = pfilt_create(&o->f, x);
53 end:
54   mp_drop(x);
55   return ((PyObject *)o);
56 }
57
58 static PyObject *pfilt_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
59 {
60   char *kwlist[] = { "x", 0 };
61   PyObject *xobj;
62
63   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O:new", kwlist, &xobj))
64     return (0);
65   return (pfilt_pymake(ty, xobj));
66 }
67
68 static void pfilt_pydealloc(PyObject *me)
69   { pfilt_destroy(PFILT_F(me)); FREEOBJ(me); }
70
71 static PyObject *pfmeth_step(PyObject *me, PyObject *arg)
72 {
73   mpw x;
74
75   if (!PyArg_ParseTuple(arg, "O&:step", convmpw, &x)) return (0);
76   PFILT_ST(me) = pfilt_step(PFILT_F(me), x);
77   RETURN_ME;
78 }
79
80 static PyObject *pfmeth_muladd(PyObject *me, PyObject *arg)
81 {
82   mpw m, a;
83   pfilt_pyobj *o = 0;
84
85   if (!PyArg_ParseTuple(arg, "O&O&:muladd", convmpw, &m, convmpw, &a))
86     return (0);
87   o = PyObject_New(pfilt_pyobj, pfilt_pytype);
88   o->st = pfilt_muladd(&o->f, PFILT_F(me), m, a);
89   return ((PyObject *)o);
90 }
91
92 static CONVFUNC(pfilt, pfilt *, PFILT_F)
93
94 static PyObject *pfmeth_jump(PyObject *me, PyObject *arg)
95 {
96   pfilt *f;
97
98   if (!PyArg_ParseTuple(arg, "O&:jump", convpfilt, &f)) return (0);
99   PFILT_ST(me) = pfilt_jump(PFILT_F(me), f);
100   RETURN_ME;
101 }
102
103 static PyObject *meth__PrimeFilter_smallfactor(PyObject *me, PyObject *arg)
104 {
105   mp *x = 0;
106   PyObject *rc = 0;
107
108   if (!PyArg_ParseTuple(arg, "OO&:smallfactor", &me, convmp, &x)) goto end;
109   rc = PyInt_FromLong(pfilt_smallfactor(x));
110 end:
111   mp_drop(x);
112   return (rc);
113 }
114
115 static int pfilt_pynonzerop(PyObject *me)
116   { return (PFILT_ST(me) != PGEN_FAIL); }
117
118 static PyObject *pfilt_pyint(PyObject *me)
119 {
120   long l;
121   PyObject *rc = 0;
122
123   if (!mp_tolong_checked(PFILT_F(me)->m, &l, 0)) rc = PyInt_FromLong(l);
124   else rc = mp_topylong(PFILT_F(me)->m);
125   return (rc);
126 }
127
128 static PyObject *pfilt_pylong(PyObject *me)
129   { return (mp_topylong(PFILT_F(me)->m)); }
130
131 static PyObject *pfget_x(PyObject *me, void *hunoz)
132   { return (mp_pywrap(MP_COPY(PFILT_F(me)->m))); }
133
134 static PyObject *pfget_status(PyObject *me, void *hunoz)
135   { return (PyInt_FromLong(PFILT_ST(me))); }
136
137 static PyGetSetDef pfilt_pygetset[] = {
138 #define GETSETNAME(op, name) pf##op##_##name
139   GET   (x,             "F.x -> current position of filter")
140   GET   (status,        "F.status -> primality status of filter")
141 #undef GETSETNAME
142   { 0 }
143 };
144
145 static PyMethodDef pfilt_pymethods[] = {
146 #define METHNAME(name) pfmeth_##name
147   METH  (step,          "F.step(N)")
148   METH  (muladd,        "F.muladd(M, A)")
149   METH  (jump,          "F.jump(FF)")
150 #undef METHNAME
151   { 0 }
152 };
153
154 static PyNumberMethods pfilt_pynumber = {
155   0,                                    /* @nb_add@ */
156   0,                                    /* @nb_subtract@ */
157   0,                                    /* @nb_multiply@ */
158   0,                                    /* @nb_divide@ */
159   0,                                    /* @nb_remainder@ */
160   0,                                    /* @nb_divmod@ */
161   0,                                    /* @nb_power@ */
162   0,                                    /* @nb_negative@ */
163   0,                                    /* @nb_positive@ */
164   0,                                    /* @nb_absolute@ */
165   pfilt_pynonzerop,                     /* @nb_nonzero@ */
166   0,                                    /* @nb_invert@ */
167   0,                                    /* @nb_lshift@ */
168   0,                                    /* @nb_rshift@ */
169   0,                                    /* @nb_and@ */
170   0,                                    /* @nb_xor@ */
171   0,                                    /* @nb_or@ */
172   0,                                    /* @nb_coerce@ */
173   pfilt_pyint,                          /* @nb_int@ */
174   pfilt_pylong,                         /* @nb_long@ */
175   0,                                    /* @nb_float@ */
176   0,                                    /* @nb_oct@ */
177   0,                                    /* @nb_hex@ */
178
179   0,                                    /* @nb_inplace_add@ */
180   0,                                    /* @nb_inplace_subtract@ */
181   0,                                    /* @nb_inplace_multiply@ */
182   0,                                    /* @nb_inplace_divide@ */
183   0,                                    /* @nb_inplace_remainder@ */
184   0,                                    /* @nb_inplace_power@ */
185   0,                                    /* @nb_inplace_lshift@ */
186   0,                                    /* @nb_inplace_rshift@ */
187   0,                                    /* @nb_inplace_and@ */
188   0,                                    /* @nb_inplace_xor@ */
189   0,                                    /* @nb_inplace_or@ */
190
191   0,                                    /* @nb_floor_divide@ */
192   0,                                    /* @nb_true_divide@ */
193   0,                                    /* @nb_inplace_floor_divide@ */
194   0,                                    /* @nb_inplace_true_divide@ */
195 };
196
197 static PyTypeObject pfilt_pytype_skel = {
198   PyObject_HEAD_INIT(0) 0,              /* Header */
199   "PrimeFilter",                        /* @tp_name@ */
200   sizeof(pfilt_pyobj),                  /* @tp_basicsize@ */
201   0,                                    /* @tp_itemsize@ */
202
203   pfilt_pydealloc,                      /* @tp_dealloc@ */
204   0,                                    /* @tp_print@ */
205   0,                                    /* @tp_getattr@ */
206   0,                                    /* @tp_setattr@ */
207   0,                                    /* @tp_compare@ */
208   0,                                    /* @tp_repr@ */
209   &pfilt_pynumber,                      /* @tp_as_number@ */
210   0,                                    /* @tp_as_sequence@ */
211   0,                                    /* @tp_as_mapping@ */
212   0,                                    /* @tp_hash@ */
213   0,                                    /* @tp_call@ */
214   0,                                    /* @tp_str@ */
215   0,                                    /* @tp_getattro@ */
216   0,                                    /* @tp_setattro@ */
217   0,                                    /* @tp_as_buffer@ */
218   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
219     Py_TPFLAGS_BASETYPE,
220
221   /* @tp_doc@ */
222 "Small-primes filter.",
223
224   0,                                    /* @tp_traverse@ */
225   0,                                    /* @tp_clear@ */
226   0,                                    /* @tp_richcompare@ */
227   0,                                    /* @tp_weaklistoffset@ */
228   0,                                    /* @tp_iter@ */
229   0,                                    /* @tp_iternext@ */
230   pfilt_pymethods,                      /* @tp_methods@ */
231   0,                                    /* @tp_members@ */
232   pfilt_pygetset,                       /* @tp_getset@ */
233   0,                                    /* @tp_base@ */
234   0,                                    /* @tp_dict@ */
235   0,                                    /* @tp_descr_get@ */
236   0,                                    /* @tp_descr_set@ */
237   0,                                    /* @tp_dictoffset@ */
238   0,                                    /* @tp_init@ */
239   PyType_GenericAlloc,                  /* @tp_alloc@ */
240   pfilt_pynew,                          /* @tp_new@ */
241   0,                                    /* @tp_free@ */
242   0                                     /* @tp_is_gc@ */
243 };
244
245 /*----- Rabin-Miller testing ----------------------------------------------*/
246
247 typedef struct rabin_pyobj {
248   PyObject_HEAD
249   rabin r;
250 } rabin_pyobj;
251
252 static PyTypeObject *rabin_pytype;
253 #define RABIN_R(o) (&((rabin_pyobj *)(o))->r)
254
255 static PyObject *rabin_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
256 {
257   mp *x = 0;
258   rabin_pyobj *o = 0;
259   char *kwlist[] = { "x", 0 };
260
261   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", kwlist, convmp, &x))
262     goto end;
263   if (!MP_POSP(x) || MP_EVENP(x)) VALERR("must be positive and odd");
264   o = (rabin_pyobj *)ty->tp_alloc(ty, 0);
265   rabin_create(&o->r, x);
266 end:
267   return ((PyObject *)o);
268 }
269
270 static void rabin_pydealloc(PyObject *me)
271 {
272   rabin_destroy(RABIN_R(me));
273   FREEOBJ(me);
274 }
275
276 static PyObject *rmeth_test(PyObject *me, PyObject *arg)
277 {
278   mp *w = 0;
279   PyObject *rc = 0;
280
281   if (!PyArg_ParseTuple(arg, "O&:test", convmp, &w)) goto end;
282   rc = PyInt_FromLong(rabin_test(RABIN_R(me), w));
283 end:
284   mp_drop(w);
285   return (rc);
286 }
287
288 static PyObject *rmeth_rtest(PyObject *me, PyObject *arg)
289 {
290   mp *w = 0;
291   PyObject *rc = 0;
292
293   if (!PyArg_ParseTuple(arg, "O&:rtest", convmp, &w)) goto end;
294   rc = PyInt_FromLong(rabin_rtest(RABIN_R(me), w));
295 end:
296   mp_drop(w);
297   return (rc);
298 }
299
300 static PyObject *rget_niters(PyObject *me, void *hunoz)
301   { return (PyInt_FromLong(rabin_iters(mp_bits(RABIN_R(me)->mm.m)))); }
302
303 static PyObject *rget_x(PyObject *me, void *hunoz)
304   { return (mp_pywrap(MP_COPY(RABIN_R(me)->mm.m))); }
305
306 static PyObject *meth__RabinMiller_iters(PyObject *me, PyObject *arg)
307 {
308   unsigned n;
309
310   if (!PyArg_ParseTuple(arg, "OO&:iters", &me, convuint, &n)) return (0);
311   return (PyInt_FromLong(rabin_iters(n)));
312 }
313
314 static PyGetSetDef rabin_pygetset[] = {
315 #define GETSETNAME(op, name) r##op##_##name
316   GET   (x,             "R.x -> number under test")
317   GET   (niters,        "R.niters -> suggested number of tests")
318 #undef GETSETNAME
319   { 0 }
320 };
321
322 static PyMethodDef rabin_pymethods[] = {
323 #define METHNAME(name) rmeth_##name
324   METH  (test,          "R.test(W) -> PGST")
325   METH  (rtest,         "R.rtest(W) -> PGST")
326 #undef METHNAME
327   { 0 }
328 };
329
330 static PyTypeObject rabin_pytype_skel = {
331   PyObject_HEAD_INIT(0) 0,              /* Header */
332   "RabinMiller",                        /* @tp_name@ */
333   sizeof(rabin_pyobj),                  /* @tp_basicsize@ */
334   0,                                    /* @tp_itemsize@ */
335
336   rabin_pydealloc,                      /* @tp_dealloc@ */
337   0,                                    /* @tp_print@ */
338   0,                                    /* @tp_getattr@ */
339   0,                                    /* @tp_setattr@ */
340   0,                                    /* @tp_compare@ */
341   0,                                    /* @tp_repr@ */
342   0,                                    /* @tp_as_number@ */
343   0,                                    /* @tp_as_sequence@ */
344   0,                                    /* @tp_as_mapping@ */
345   0,                                    /* @tp_hash@ */
346   0,                                    /* @tp_call@ */
347   0,                                    /* @tp_str@ */
348   0,                                    /* @tp_getattro@ */
349   0,                                    /* @tp_setattro@ */
350   0,                                    /* @tp_as_buffer@ */
351   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
352     Py_TPFLAGS_BASETYPE,
353
354   /* @tp_doc@ */
355 "Rabin-Miller strong primality test.",
356
357   0,                                    /* @tp_traverse@ */
358   0,                                    /* @tp_clear@ */
359   0,                                    /* @tp_richcompare@ */
360   0,                                    /* @tp_weaklistoffset@ */
361   0,                                    /* @tp_iter@ */
362   0,                                    /* @tp_iternext@ */
363   rabin_pymethods,                      /* @tp_methods@ */
364   0,                                    /* @tp_members@ */
365   rabin_pygetset,                       /* @tp_getset@ */
366   0,                                    /* @tp_base@ */
367   0,                                    /* @tp_dict@ */
368   0,                                    /* @tp_descr_get@ */
369   0,                                    /* @tp_descr_set@ */
370   0,                                    /* @tp_dictoffset@ */
371   0,                                    /* @tp_init@ */
372   PyType_GenericAlloc,                  /* @tp_alloc@ */
373   rabin_pynew,                          /* @tp_new@ */
374   0,                                    /* @tp_free@ */
375   0                                     /* @tp_is_gc@ */
376 };
377
378 /*----- Events ------------------------------------------------------------*/
379
380 typedef struct pgevent_pyobj {
381   PyObject_HEAD
382   pgen_event *ev;
383 } pgevent_pyobj;
384
385 static PyTypeObject *pgevent_pytype;
386 #define PGEVENT_EV(o) (((pgevent_pyobj *)(o))->ev)
387
388 static PyObject *pgevent_pywrap(pgen_event *ev)
389 {
390   pgevent_pyobj *o = PyObject_New(pgevent_pyobj, pgevent_pytype);
391   o->ev = ev;
392   return ((PyObject *)o);
393 }
394
395 static CONVFUNC(pgevent, pgen_event *, PGEVENT_EV)
396
397 static void pgevent_kill(PyObject *me) { PGEVENT_EV(me) = 0; }
398 static void pgevent_pydealloc(PyObject *me) { FREEOBJ(me); }
399
400 #define PGEVENT_CHECK(me) do {                                          \
401   if (!PGEVENT_EV(me)) {                                                \
402     PyErr_SetString(PyExc_ValueError, "event object is dead");          \
403     return (0);                                                         \
404   }                                                                     \
405 } while (0)
406
407 static PyObject *peget_name(PyObject *me, void *hunoz)
408   { PGEVENT_CHECK(me); return (PyString_FromString(PGEVENT_EV(me)->name)); }
409
410 static PyObject *peget_x(PyObject *me, void *hunoz)
411   { PGEVENT_CHECK(me); return (mp_pywrap(MP_COPY(PGEVENT_EV(me)->m))); }
412
413 static PyObject *peget_steps(PyObject *me, void *hunoz)
414   { PGEVENT_CHECK(me); return (PyInt_FromLong(PGEVENT_EV(me)->steps)); }
415
416 static PyObject *peget_tests(PyObject *me, void *hunoz)
417   { PGEVENT_CHECK(me); return (PyInt_FromLong(PGEVENT_EV(me)->tests)); }
418
419 static PyObject *peget_rng(PyObject *me, void *hunoz)
420   { PGEVENT_CHECK(me); return (grand_pywrap(PGEVENT_EV(me)->r, 0)); }
421
422 static int peset_x(PyObject *me, PyObject *xobj, void *hunoz)
423 {
424   mp *x = 0;
425   pgen_event *ev = PGEVENT_EV(me);
426   int rc = -1;
427   if (!xobj) NIERR("__del__");
428   PGEVENT_CHECK(me);
429   if ((x = getmp(xobj)) == 0) goto end;
430   mp_drop(ev->m);
431   ev->m = MP_COPY(x);
432   rc = 0;
433 end:
434   mp_drop(x);
435   return (rc);
436 }
437
438 static PyGetSetDef pgevent_pygetset[] = {
439 #define GETSETNAME(op, name) pe##op##_##name
440   GET   (name,          "EV.name -> value being generated")
441   GETSET(x,             "EV.x -> value under test")
442   GET   (steps,         "EV.steps -> number of steps left")
443   GET   (tests,         "EV.tests -> tests before passing")
444   GET   (rng,           "EV.rng -> (noncrypto) random number generator")
445 #undef GETSETNAME
446   { 0 }
447 };
448
449 static PyTypeObject pgevent_pytype_skel = {
450   PyObject_HEAD_INIT(0) 0,              /* Header */
451   "PrimeGenEvent",                      /* @tp_name@ */
452   sizeof(pgevent_pyobj),                /* @tp_basicsize@ */
453   0,                                    /* @tp_itemsize@ */
454
455   pgevent_pydealloc,                    /* @tp_dealloc@ */
456   0,                                    /* @tp_print@ */
457   0,                                    /* @tp_getattr@ */
458   0,                                    /* @tp_setattr@ */
459   0,                                    /* @tp_compare@ */
460   0,                                    /* @tp_repr@ */
461   0,                                    /* @tp_as_number@ */
462   0,                                    /* @tp_as_sequence@ */
463   0,                                    /* @tp_as_mapping@ */
464   0,                                    /* @tp_hash@ */
465   0,                                    /* @tp_call@ */
466   0,                                    /* @tp_str@ */
467   0,                                    /* @tp_getattro@ */
468   0,                                    /* @tp_setattro@ */
469   0,                                    /* @tp_as_buffer@ */
470   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
471     Py_TPFLAGS_BASETYPE,
472
473   /* @tp_doc@ */
474 "Prime-generation event.",
475
476   0,                                    /* @tp_traverse@ */
477   0,                                    /* @tp_clear@ */
478   0,                                    /* @tp_richcompare@ */
479   0,                                    /* @tp_weaklistoffset@ */
480   0,                                    /* @tp_iter@ */
481   0,                                    /* @tp_iternext@ */
482   0,                                    /* @tp_methods@ */
483   0,                                    /* @tp_members@ */
484   pgevent_pygetset,                     /* @tp_getset@ */
485   0,                                    /* @tp_base@ */
486   0,                                    /* @tp_dict@ */
487   0,                                    /* @tp_descr_get@ */
488   0,                                    /* @tp_descr_set@ */
489   0,                                    /* @tp_dictoffset@ */
490   0,                                    /* @tp_init@ */
491   PyType_GenericAlloc,                  /* @tp_alloc@ */
492   abstract_pynew,                       /* @tp_new@ */
493   0,                                    /* @tp_free@ */
494   0                                     /* @tp_is_gc@ */
495 };
496
497 /*----- Event handlers ----------------------------------------------------*/
498
499 PyTypeObject *pgev_pytype;
500
501 typedef struct pgstep_pyobj {
502   PGEV_HEAD
503   pgen_filterctx f;
504 } pgstep_pyobj;
505
506 static PyTypeObject *pgstep_pytype;
507 #define PGSTEP_STEP(o) (((pgstep_pyobj *)(o))->f.step)
508
509 typedef struct pgjump_pyobj {
510   PGEV_HEAD
511   PyObject *fobj;
512   pgen_jumpctx j;
513 } pgjump_pyobj;
514
515 static PyTypeObject *pgjump_pytype;
516 #define PGJUMP_FOBJ(o) (((pgjump_pyobj *)(o))->fobj)
517 #define PGJUMP_J(o) (&((pgjump_pyobj *)(o))->j)
518
519 typedef struct pgtest_pyobj {
520   PGEV_HEAD
521   rabin r;
522 } pgtest_pyobj;
523
524 static PyTypeObject *pgtest_pytype;
525
526 static int pgev_python(int rq, pgen_event *ev, void *p)
527 {
528   PyObject *py = p;
529   PyObject *pyev = 0;
530   PyObject *rc = 0;
531   int st = PGEN_ABORT;
532   long l;
533   char *meth[] = {
534     "pg_abort", "pg_done", "pg_begin", "pg_try", "pg_fail", "pg_pass"
535   };
536
537   rq++;
538   if (rq > N(meth)) SYSERR("event code out of range");
539   pyev = pgevent_pywrap(ev);
540   if ((rc = PyObject_CallMethod(py, meth[rq], "(O)", pyev)) == 0)
541     goto end;
542   if (rc == Py_None)
543     st = PGEN_TRY;
544   else if ((l = PyInt_AsLong(rc)) == -1 && PyErr_Occurred())
545     goto end;
546   else if (l < PGEN_ABORT || l > PGEN_PASS)
547     VALERR("return code out of range");
548   else
549     st = l;
550 end:
551   if (pyev) {
552     pgevent_kill(pyev);
553     Py_DECREF(pyev);
554   }
555   Py_XDECREF(rc);
556   return (st);
557 }
558
559 static PyObject *pgev_pywrap(const pgev *pg)
560 {
561   pgev_pyobj *o;
562
563   o = PyObject_New(pgev_pyobj, pgev_pytype);
564   o->pg = *pg;
565   return ((PyObject *)o);
566 }
567
568 int convpgev(PyObject *o, void *p)
569 {
570   pgev *pg = p;
571
572   if (PGEV_PYCHECK(o))
573     *pg = *PGEV_PG(o);
574   else {
575     pg->proc = pgev_python;
576     pg->ctx = o;
577     Py_INCREF(o);
578   }
579   return (1);
580 }
581
582 void droppgev(pgev *p)
583 {
584   if (p->proc == pgev_python) {
585     PyObject *py = p->ctx;
586     Py_DECREF(py);
587   }
588 }
589
590 static PyObject *pgmeth_common(PyObject *me, PyObject *arg, int rq)
591 {
592   pgen_event *ev;
593   pgev *pg = PGEV_PG(me);
594   PyObject *rc = 0;
595
596   if (!PyArg_ParseTuple(arg, "O&", convpgevent, &ev)) goto end;
597   rc = PyInt_FromLong(!pg->proc ? rq : pg->proc(rq, ev, pg->ctx));
598 end:
599   return (rc);
600 }
601
602 #define PGMETH(lc, uc)                                                  \
603   static PyObject *pgmeth_pg_##lc(PyObject *me, PyObject *arg)          \
604     { return pgmeth_common(me, arg, PGEN_##uc); }
605 PGMETH(abort,   ABORT)
606 PGMETH(done,    DONE)
607 PGMETH(begin,   BEGIN)
608 PGMETH(try,     TRY)
609 PGMETH(pass,    PASS)
610 PGMETH(fail,    FAIL)
611 #undef PGMETH
612
613 static PyObject *pgev_stdev(pgen_proc *proc)
614   { pgev pg; pg.proc = proc; pg.ctx = 0; return (pgev_pywrap(&pg)); }
615
616 static PyMethodDef pgev_pymethods[] = {
617 #define METHNAME(name) pgmeth_##name
618   METH  (pg_abort,      "E.pg_abort(EV) -> PGRC -- prime generation aborted")
619   METH  (pg_done,       "E.pg_done(EV) -> PGRC -- prime generation finished")
620   METH  (pg_begin,     "E.pg_begin(EV) -> PGRC -- commence stepping/testing")
621   METH  (pg_try,        "E.pg_try(EV) -> PGRC -- found new candidate")
622   METH  (pg_pass,       "E.pg_pass(EV) -> PGRC -- passed primality test")
623   METH  (pg_fail,       "E.pg_fail(EV) -> PGRC -- failed primality test")
624 #undef METHNAME
625   { 0 }
626 };
627
628 static PyTypeObject pgev_pytype_skel = {
629   PyObject_HEAD_INIT(0) 0,              /* Header */
630   "PrimeGenBuiltinHandler",             /* @tp_name@ */
631   sizeof(pgev_pyobj),                   /* @tp_basicsize@ */
632   0,                                    /* @tp_itemsize@ */
633
634   0,                                    /* @tp_dealloc@ */
635   0,                                    /* @tp_print@ */
636   0,                                    /* @tp_getattr@ */
637   0,                                    /* @tp_setattr@ */
638   0,                                    /* @tp_compare@ */
639   0,                                    /* @tp_repr@ */
640   0,                                    /* @tp_as_number@ */
641   0,                                    /* @tp_as_sequence@ */
642   0,                                    /* @tp_as_mapping@ */
643   0,                                    /* @tp_hash@ */
644   0,                                    /* @tp_call@ */
645   0,                                    /* @tp_str@ */
646   0,                                    /* @tp_getattro@ */
647   0,                                    /* @tp_setattro@ */
648   0,                                    /* @tp_as_buffer@ */
649   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
650     Py_TPFLAGS_BASETYPE,
651
652   /* @tp_doc@ */
653 "Built-in prime-generation event handler, base class.",
654
655   0,                                    /* @tp_traverse@ */
656   0,                                    /* @tp_clear@ */
657   0,                                    /* @tp_richcompare@ */
658   0,                                    /* @tp_weaklistoffset@ */
659   0,                                    /* @tp_iter@ */
660   0,                                    /* @tp_iternext@ */
661   pgev_pymethods,                       /* @tp_methods@ */
662   0,                                    /* @tp_members@ */
663   0,                                    /* @tp_getset@ */
664   0,                                    /* @tp_base@ */
665   0,                                    /* @tp_dict@ */
666   0,                                    /* @tp_descr_get@ */
667   0,                                    /* @tp_descr_set@ */
668   0,                                    /* @tp_dictoffset@ */
669   0,                                    /* @tp_init@ */
670   PyType_GenericAlloc,                  /* @tp_alloc@ */
671   abstract_pynew,                       /* @tp_new@ */
672   0,                                    /* @tp_free@ */
673   0                                     /* @tp_is_gc@ */
674 };
675
676 static PyObject *pgstep_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
677 {
678   mpw s;
679   pgstep_pyobj *rc = 0;
680   char *kwlist[] = { "step", 0 };
681
682   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", kwlist, convmpw, &s))
683     goto end;
684   rc = (pgstep_pyobj *)ty->tp_alloc(ty, 0);
685   rc->f.step = s;
686   rc->pg.proc = pgen_filter;
687   rc->pg.ctx = &rc->f;
688 end:
689   return ((PyObject *)rc);
690 }
691
692 static PyObject *psget_step(PyObject *me, void *hunoz)
693   { return (PyInt_FromLong(PGSTEP_STEP(me))); }
694
695 static PyGetSetDef pgstep_pygetset[] = {
696 #define GETSETNAME(op, name) ps##op##_##name
697   GET   (step,          "S.step -> step size for the stepper")
698 #undef GETSETNAME
699   { 0 }
700 };
701
702 static PyTypeObject pgstep_pytype_skel = {
703   PyObject_HEAD_INIT(0) 0,              /* Header */
704   "PrimeGenStepper",                    /* @tp_name@ */
705   sizeof(pgstep_pyobj),                 /* @tp_basicsize@ */
706   0,                                    /* @tp_itemsize@ */
707
708   0,                                    /* @tp_dealloc@ */
709   0,                                    /* @tp_print@ */
710   0,                                    /* @tp_getattr@ */
711   0,                                    /* @tp_setattr@ */
712   0,                                    /* @tp_compare@ */
713   0,                                    /* @tp_repr@ */
714   0,                                    /* @tp_as_number@ */
715   0,                                    /* @tp_as_sequence@ */
716   0,                                    /* @tp_as_mapping@ */
717   0,                                    /* @tp_hash@ */
718   0,                                    /* @tp_call@ */
719   0,                                    /* @tp_str@ */
720   0,                                    /* @tp_getattro@ */
721   0,                                    /* @tp_setattro@ */
722   0,                                    /* @tp_as_buffer@ */
723   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
724     Py_TPFLAGS_BASETYPE,
725
726   /* @tp_doc@ */
727   "Simple prime-number stepper with small-factors filter.",
728
729   0,                                    /* @tp_traverse@ */
730   0,                                    /* @tp_clear@ */
731   0,                                    /* @tp_richcompare@ */
732   0,                                    /* @tp_weaklistoffset@ */
733   0,                                    /* @tp_iter@ */
734   0,                                    /* @tp_iternext@ */
735   0,                                    /* @tp_methods@ */
736   0,                                    /* @tp_members@ */
737   pgstep_pygetset,                      /* @tp_getset@ */
738   0,                                    /* @tp_base@ */
739   0,                                    /* @tp_dict@ */
740   0,                                    /* @tp_descr_get@ */
741   0,                                    /* @tp_descr_set@ */
742   0,                                    /* @tp_dictoffset@ */
743   0,                                    /* @tp_init@ */
744   PyType_GenericAlloc,                  /* @tp_alloc@ */
745   pgstep_pynew,                         /* @tp_new@ */
746   0,                                    /* @tp_free@ */
747   0                                     /* @tp_is_gc@ */
748 };
749
750 static PyObject *pgjump_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
751 {
752   PyObject *o, *fobj;
753   pgjump_pyobj *rc = 0;
754   char *kwlist[] = { "jump", 0 };
755
756   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O:new", kwlist, &o) ||
757       (fobj = pfilt_pymake(pfilt_pytype, o)) == 0)
758     goto end;
759   rc = (pgjump_pyobj *)ty->tp_alloc(ty, 0);
760   rc->fobj = fobj;
761   rc->j.j = PFILT_F(fobj);
762   rc->pg.proc = pgen_jump;
763   rc->pg.ctx = &rc->j;
764 end:
765   return ((PyObject *)rc);
766 }
767
768 static void pgjump_pydealloc(PyObject *me)
769 {
770   Py_DECREF(PGJUMP_FOBJ(me));
771   FREEOBJ(me);
772 }
773
774 static PyObject *pjget_jump(PyObject *me, void *hunoz)
775   { RETURN_OBJ(PGJUMP_FOBJ(me)); }
776
777 static PyGetSetDef pgjump_pygetset[] = {
778 #define GETSETNAME(op, name) pj##op##_##name
779   GET   (jump,          "S.jump -> jump size for the stepper")
780 #undef GETSETNAME
781   { 0 }
782 };
783
784 static PyTypeObject pgjump_pytype_skel = {
785   PyObject_HEAD_INIT(0) 0,              /* Header */
786   "PrimeGenJumper",                     /* @tp_name@ */
787   sizeof(pgjump_pyobj),                 /* @tp_basicsize@ */
788   0,                                    /* @tp_itemsize@ */
789
790   pgjump_pydealloc,                     /* @tp_dealloc@ */
791   0,                                    /* @tp_print@ */
792   0,                                    /* @tp_getattr@ */
793   0,                                    /* @tp_setattr@ */
794   0,                                    /* @tp_compare@ */
795   0,                                    /* @tp_repr@ */
796   0,                                    /* @tp_as_number@ */
797   0,                                    /* @tp_as_sequence@ */
798   0,                                    /* @tp_as_mapping@ */
799   0,                                    /* @tp_hash@ */
800   0,                                    /* @tp_call@ */
801   0,                                    /* @tp_str@ */
802   0,                                    /* @tp_getattro@ */
803   0,                                    /* @tp_setattro@ */
804   0,                                    /* @tp_as_buffer@ */
805   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
806     Py_TPFLAGS_BASETYPE,
807
808   /* @tp_doc@ */
809 "Stepper for larger steps, with small-factors filter.",
810
811   0,                                    /* @tp_traverse@ */
812   0,                                    /* @tp_clear@ */
813   0,                                    /* @tp_richcompare@ */
814   0,                                    /* @tp_weaklistoffset@ */
815   0,                                    /* @tp_iter@ */
816   0,                                    /* @tp_iternext@ */
817   0,                                    /* @tp_methods@ */
818   0,                                    /* @tp_members@ */
819   pgjump_pygetset,                      /* @tp_getset@ */
820   0,                                    /* @tp_base@ */
821   0,                                    /* @tp_dict@ */
822   0,                                    /* @tp_descr_get@ */
823   0,                                    /* @tp_descr_set@ */
824   0,                                    /* @tp_dictoffset@ */
825   0,                                    /* @tp_init@ */
826   PyType_GenericAlloc,                  /* @tp_alloc@ */
827   pgjump_pynew,                         /* @tp_new@ */
828   0,                                    /* @tp_free@ */
829   0                                     /* @tp_is_gc@ */
830 };
831
832 static PyObject *pgtest_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
833 {
834   pgtest_pyobj *rc = 0;
835   char *kwlist[] = { 0 };
836
837   if (!PyArg_ParseTupleAndKeywords(arg, kw, ":new", kwlist)) goto end;
838   rc = (pgtest_pyobj *)ty->tp_alloc(ty, 0);
839   rc->pg.proc = pgen_test;
840   rc->pg.ctx = &rc->r;
841 end:
842   return ((PyObject *)rc);
843 }
844
845 static PyTypeObject pgtest_pytype_skel = {
846   PyObject_HEAD_INIT(0) 0,              /* Header */
847   "PrimeGenTester",                     /* @tp_name@ */
848   sizeof(pgtest_pyobj),                 /* @tp_basicsize@ */
849   0,                                    /* @tp_itemsize@ */
850
851   0,                                    /* @tp_dealloc@ */
852   0,                                    /* @tp_print@ */
853   0,                                    /* @tp_getattr@ */
854   0,                                    /* @tp_setattr@ */
855   0,                                    /* @tp_compare@ */
856   0,                                    /* @tp_repr@ */
857   0,                                    /* @tp_as_number@ */
858   0,                                    /* @tp_as_sequence@ */
859   0,                                    /* @tp_as_mapping@ */
860   0,                                    /* @tp_hash@ */
861   0,                                    /* @tp_call@ */
862   0,                                    /* @tp_str@ */
863   0,                                    /* @tp_getattro@ */
864   0,                                    /* @tp_setattro@ */
865   0,                                    /* @tp_as_buffer@ */
866   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
867     Py_TPFLAGS_BASETYPE,
868
869   /* @tp_doc@ */
870 "Rabin-Miller tester.",
871
872   0,                                    /* @tp_traverse@ */
873   0,                                    /* @tp_clear@ */
874   0,                                    /* @tp_richcompare@ */
875   0,                                    /* @tp_weaklistoffset@ */
876   0,                                    /* @tp_iter@ */
877   0,                                    /* @tp_iternext@ */
878   0,                                    /* @tp_methods@ */
879   0,                                    /* @tp_members@ */
880   0,                                    /* @tp_getset@ */
881   0,                                    /* @tp_base@ */
882   0,                                    /* @tp_dict@ */
883   0,                                    /* @tp_descr_get@ */
884   0,                                    /* @tp_descr_set@ */
885   0,                                    /* @tp_dictoffset@ */
886   0,                                    /* @tp_init@ */
887   PyType_GenericAlloc,                  /* @tp_alloc@ */
888   pgtest_pynew,                         /* @tp_new@ */
889   0,                                    /* @tp_free@ */
890   0                                     /* @tp_is_gc@ */
891 };
892
893 /*----- Prime generation functions ----------------------------------------*/
894
895 void pgenerr(void)
896 {
897   if (!PyErr_Occurred())
898     PyErr_SetString(PyExc_ValueError, "prime generation failed");
899 }
900
901 static PyObject *meth_pgen(PyObject *me, PyObject *arg, PyObject *kw)
902 {
903   mp *x = 0;
904   mp *r = 0;
905   PyObject *rc = 0;
906   char *p = "p";
907   pgen_filterctx fc = { 2 };
908   rabin tc;
909   pgev step = { 0 }, test = { 0 }, evt = { 0 };
910   unsigned nsteps = 0, ntests = 0;
911   char *kwlist[] = { "start", "name", "stepper", "tester", "event",
912                      "nsteps", "ntests", 0 };
913
914   step.proc = pgen_filter; step.ctx = &fc;
915   test.proc = pgen_test; test.ctx = &tc;
916   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&|sO&O&O&O&O&:pgen", kwlist,
917                                    convmp, &x, &p, convpgev, &step,
918                                    convpgev, &test, convpgev, &evt,
919                                    convuint, &nsteps, convuint, &ntests))
920     goto end;
921   if (!ntests) ntests = rabin_iters(mp_bits(x));
922   if ((r = pgen(p, MP_NEW, x, evt.proc, evt.ctx,
923                 nsteps, step.proc, step.ctx,
924                 ntests, test.proc, test.ctx)) == 0)
925     PGENERR;
926   if (PyErr_Occurred()) goto end;
927   rc = mp_pywrap(r);
928   r = 0;
929 end:
930   mp_drop(r); mp_drop(x);
931   droppgev(&step); droppgev(&test); droppgev(&evt);
932   return (rc);
933 }
934
935 static PyObject *meth_strongprime_setup(PyObject *me,
936                                         PyObject *arg, PyObject *kw)
937 {
938   mp *x = 0;
939   pfilt f;
940   grand *r = &rand_global;
941   unsigned nbits;
942   char *name = "p";
943   unsigned n = 0;
944   pgev evt = { 0 };
945   PyObject *rc = 0;
946   char *kwlist[] = { "nbits", "name", "event", "rng", "nsteps", 0 };
947
948   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&|sO&O&O&", kwlist,
949                                    convuint, &nbits, &name,
950                                    convpgev, &evt, convgrand, &r,
951                                    convuint, &n))
952     goto end;
953   if ((x = strongprime_setup(name, MP_NEW, &f, nbits,
954                              r, n, evt.proc, evt.ctx)) == 0)
955     PGENERR;
956   rc = Py_BuildValue("(NN)", mp_pywrap(x), pfilt_pywrap(&f));
957   x = 0;
958 end:
959   mp_drop(x);
960   droppgev(&evt);
961   return (rc);
962 }
963
964 static PyObject *meth_strongprime(PyObject *me, PyObject *arg, PyObject *kw)
965 {
966   mp *x = 0;
967   grand *r = &rand_global;
968   unsigned nbits;
969   char *name = "p";
970   unsigned n = 0;
971   pgev evt = { 0 };
972   PyObject *rc = 0;
973   char *kwlist[] = { "nbits", "name", "event", "rng", "nsteps", 0 };
974
975   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&|sO&O&O&", kwlist,
976                                    convuint, &nbits, &name,
977                                    convpgev, &evt, convgrand, &r,
978                                    convuint, &n))
979     goto end;
980   if ((x = strongprime(name, MP_NEW, nbits,
981                        r, n, evt.proc, evt.ctx)) == 0)
982     PGENERR;
983   rc = mp_pywrap(x);
984   x = 0;
985 end:
986   mp_drop(x);
987   droppgev(&evt);
988   return (rc);
989 }
990
991 static PyObject *meth_limlee(PyObject *me, PyObject *arg, PyObject *kw)
992 {
993   char *p = "p";
994   pgev ie = { 0 }, oe = { 0 };
995   unsigned ql, pl;
996   grand *r = &rand_global;
997   unsigned on = 0;
998   size_t i, nf = 0;
999   PyObject *rc = 0, *vec;
1000   char *kwlist[] = { "pbits", "qbits", "name", "event", "ievent",
1001                      "rng", "nsteps", 0 };
1002   mp *x = 0, **v = 0;
1003
1004   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&|sO&O&O&O&:limlee", kwlist,
1005                                    convuint, &pl, convuint, &ql,
1006                                    &p, convpgev, &oe, convpgev, &ie,
1007                                    convgrand, &r, convuint, &on))
1008     goto end;
1009   if ((x = limlee(p, MP_NEW, MP_NEW, ql, pl, r, on,
1010                   oe.proc, oe.ctx, ie.proc, ie.ctx, &nf, &v)) == 0)
1011     PGENERR;
1012   vec = PyList_New(nf);
1013   for (i = 0; i < nf; i++)
1014     PyList_SetItem(vec, i, mp_pywrap(v[i]));
1015   xfree(v);
1016   rc = Py_BuildValue("(NN)", mp_pywrap(x), vec);
1017 end:
1018   droppgev(&oe); droppgev(&ie);
1019   return (rc);
1020 }
1021
1022 /*----- Global stuff ------------------------------------------------------*/
1023
1024 static PyMethodDef methods[] = {
1025 #define METHNAME(name) meth_##name
1026   METH  (_PrimeFilter_smallfactor,      "smallfactor(X) -> PGRC")
1027   METH  (_RabinMiller_iters,            "iters(NBITS) -> NITERS")
1028   KWMETH(pgen,                          "\
1029 pgen(START, [name = 'p'[, [stepper = PrimeGenStepper(2)],\n\
1030      [tester = PrimeGenTester()], [event = pgen_nullev],\n\
1031      [nsteps = 0], [ntests = RabinMiller.iters(START.nbits)]) -> P")
1032   KWMETH(strongprime_setup,             "\
1033 strongprime_setup(NBITS, [name = 'p'], [event = pgen_nullev],\n\
1034                   [rng = rand], [nsteps = 0]) -> (START, JUMP)")
1035   KWMETH(strongprime,                   "\
1036 strongprime(NBITS, [name = 'p'], [event = pgen_nullev],\n\
1037             [rng = rand], [nsteps = 0]) -> P")
1038   KWMETH(limlee,                        "\
1039 limlee(PBITS, QBITS, [name = 'p'], [event = pgen_nullev],\n\
1040        [ievent = pgen_nullev], [rng = rand], [nsteps = 0]) -> (P, [Q, ...])")
1041 #undef METHNAME
1042   { 0 }
1043 };
1044
1045 void pgen_pyinit(void)
1046 {
1047   INITTYPE(pfilt, root);
1048   INITTYPE(rabin, root);
1049   INITTYPE(pgevent, root);
1050   INITTYPE(pgev, root);
1051   INITTYPE(pgstep, pgev);
1052   INITTYPE(pgjump, pgev);
1053   INITTYPE(pgtest, pgev);
1054   addmethods(methods);
1055 }
1056
1057 static PyObject *obj;
1058
1059 void pgen_pyinsert(PyObject *mod)
1060 {
1061   INSERT("PrimeFilter", pfilt_pytype);
1062   INSERT("RabinMiller", rabin_pytype);
1063   INSERT("PrimeGenEvent", pgevent_pytype);
1064   INSERT("PrimeGenBuiltinHandler", pgev_pytype);
1065   INSERT("PrimeGenStepper", pgstep_pytype);
1066   INSERT("PrimeGenJumper", pgjump_pytype);
1067   INSERT("PrimeGenTester", pgtest_pytype);
1068   INSERT("pgen_nullev", obj = pgev_stdev(0));
1069   INSERT("pgen_stdev", pgev_stdev(pgen_ev));
1070   INSERT("pgen_spinev", pgev_stdev(pgen_evspin));
1071   INSERT("pgen_subev", pgev_stdev(pgen_subev));
1072 }
1073
1074 /*----- That's all, folks -------------------------------------------------*/