@@@ py_buffer/freebin wip
[catacomb-python] / mp.c
1 /* -*-c-*-
2 *
3 * Multiprecision arithmetic
4 *
5 * (c) 2004 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 /*----- General utilities -------------------------------------------------*/
32
33 PyTypeObject *mp_pytype = 0;
34 PyTypeObject *gf_pytype = 0;
35
36 #ifndef PyLong_SHIFT
37 # define PyLong_SHIFT SHIFT
38 #endif
39
40 #ifndef PyLong_MASK
41 # define PyLong_MASK MASK
42 #endif
43
44 STATIC_ASSERT(MPW_BITS >= PyLong_SHIFT,
45 "Catacomb's limbs are now narrower than than Python's!");
46
47 mp *mp_frompylong(PyObject *obj)
48 {
49 unsigned long bits;
50 PyLongObject *l = (PyLongObject *)obj;
51 int sz;
52 size_t w;
53 mpd r = 0;
54 int b = 0;
55 int i;
56 mp *x;
57 mpw *p;
58
59 #ifdef PY3
60 int ov;
61 long j = PyLong_AsLongAndOverflow(obj, &ov);
62 if (!ov) return mp_fromlong(MP_NEW, j);
63 #endif
64
65 sz = Py_SIZE(l);
66 if (sz < 0) sz = -sz;
67 bits = (unsigned long)sz * PyLong_SHIFT;
68 w = (bits + MPW_BITS - 1)/MPW_BITS;
69 x = mp_new(w, Py_SIZE(l) < 0 ? MP_NEG : 0);
70 p = x->v;
71 for (i = 0; i < sz; i++) {
72 r |= (mpd)l->ob_digit[i] << b;
73 b += PyLong_SHIFT;
74 while (b >= MPW_BITS) {
75 *p++ = MPW(r);
76 r >>= MPW_BITS;
77 b -= MPW_BITS;
78 }
79 }
80 while (r) {
81 *p++ = MPW(r);
82 r >>= MPW_BITS;
83 }
84 x->vl = p;
85 MP_SHRINK(x);
86 return (x);
87 }
88
89 PyObject *mp_topylong(mp *x)
90 {
91 unsigned long bits = mp_bits(x);
92 int sz = (bits + PyLong_SHIFT - 1)/PyLong_SHIFT;
93 PyLongObject *l = _PyLong_New(sz);
94 mpd r = 0;
95 int b = 0;
96 mpw *p = x->v;
97 int i = 0;
98
99 while (i < sz && p < x->vl) {
100 r |= (mpd)*p++ << b;
101 b += MPW_BITS;
102 while (i < sz && b >= PyLong_SHIFT) {
103 l->ob_digit[i++] = r & PyLong_MASK;
104 r >>= PyLong_SHIFT;
105 b -= PyLong_SHIFT;
106 }
107 }
108 while (i < sz && r) {
109 l->ob_digit[i++] = r & PyLong_MASK;
110 r >>= PyLong_SHIFT;
111 }
112 Py_SIZE(l) = (x->f & MP_NEG) ? -sz : sz;
113 return ((PyObject *)l);
114 }
115
116 mp *mp_frompyobject(PyObject *o, int radix)
117 {
118 mp *x;
119
120 if (TEXT_CHECK(o)) {
121 mptext_stringctx sc;
122 mp *x;
123 size_t sz;
124 TEXT_PTRLEN(o, sc.buf, sz); sc.lim = sc.buf + sz;
125 if (sc.buf + 2 < sc.lim && sc.buf[0] == '0' &&
126 (radix == 16 ? (sc.buf[1] == 'x' || sc.buf[1] == 'X') :
127 radix == 8 ? (sc.buf[1] == 'o' || sc.buf[1] == 'O') :
128 radix == 2 ? (sc.buf[1] == 'b' || sc.buf[1] == 'B') :
129 0))
130 sc.buf += 2;
131 x = mp_read(MP_NEW, radix, &mptext_stringops, &sc);
132 if (!x) return (0);
133 if (sc.buf < sc.lim) { MP_DROP(x); return (0); }
134 return (x);
135 }
136 if ((x = tomp(o)) != 0)
137 return (x);
138 return (0);
139 }
140
141 PyObject *mp_topystring(mp *x, int radix, const char *xpre,
142 const char *pre, const char *post)
143 {
144 int len = mptext_len(x, radix) + 1;
145 mptext_stringctx sc;
146 PyObject *o;
147 size_t xprelen = xpre ? strlen(xpre) : 0;
148 size_t prelen = pre ? strlen(pre) : 0;
149 size_t postlen = post ? strlen(post) : 0;
150 char *p;
151 MP_COPY(x);
152 TEXT_PREPAREWRITE(o, p, len + 1 + xprelen + prelen + postlen);
153 sc.buf = p;
154 if (xpre) { memcpy(sc.buf, xpre, xprelen); sc.buf += xprelen; }
155 if (MP_NEGP(x)) { *sc.buf++ = '-'; x = mp_neg(x, x); }
156 if (pre) { memcpy(sc.buf, pre, prelen); sc.buf += prelen; }
157 sc.lim = sc.buf + len;
158 mp_write(x, radix, &mptext_stringops, &sc);
159 if (post) { memcpy(sc.buf, post, postlen); sc.buf += postlen; }
160 MP_DROP(x);
161 TEXT_DONEWRITE(o, sc.buf - p);
162 return (o);
163 }
164
165 static int good_radix_p(int r, int readp)
166 {
167 return ((r >= -255 && r <= -2) ||
168 (readp && r == 0) ||
169 (r >= 2 && r <= 62));
170 }
171
172 PyObject *mp_pywrap(mp *x)
173 {
174 mp_pyobj *z = PyObject_New(mp_pyobj, mp_pytype);
175 z->x = x;
176 return ((PyObject *)z);
177 }
178
179 PyObject *gf_pywrap(mp *x)
180 {
181 mp_pyobj *z = PyObject_New(mp_pyobj, gf_pytype);
182 z->x = x;
183 return ((PyObject *)z);
184 }
185
186 int mp_tolong_checked(mp *x, long *l, int must)
187 {
188 static mp *longmin = 0, *longmax = 0;
189 int rc = -1;
190
191 if (!longmax) {
192 longmin = mp_fromlong(MP_NEW, LONG_MIN);
193 longmax = mp_fromlong(MP_NEW, LONG_MAX);
194 }
195 if (MP_CMP(x, <, longmin) || MP_CMP(x, >, longmax)) {
196 if (must) VALERR("mp out of range for int");
197 else goto end;
198 }
199 *l = mp_tolong(x);
200 rc = 0;
201 end:
202 return (rc);
203 }
204
205 /*----- Arbitrary-precision integers --------------------------------------*/
206
207 static void mp_pydealloc(PyObject *o)
208 {
209 MP_DROP(MP_X(o));
210 FREEOBJ(o);
211 }
212
213 static PyObject *mp_pyrepr(PyObject *o)
214 { return mp_topystring(MP_X(o), 10, "MP(", 0, ")"); }
215
216 static PyObject *mp_pystr(PyObject *o)
217 { return mp_topystring(MP_X(o), 10, 0, 0, 0); }
218
219 mp *tomp(PyObject *o)
220 {
221 PyObject *l;
222 mp *x;
223
224 if (!o || PyFloat_Check(o))
225 return (0);
226 else if (MP_PYCHECK(o) || GF_PYCHECK(o))
227 return (MP_COPY(MP_X(o)));
228 else if (FE_PYCHECK(o))
229 return (F_OUT(FE_F(o), MP_NEW, FE_X(o)));
230 else if (PFILT_PYCHECK(o))
231 return (MP_COPY(PFILT_F(o)->m));
232 else if (ECPT_PYCHECK(o)) {
233 ec p = EC_INIT;
234 if (EC_ATINF(ECPT_P(o))) return (0);
235 getecptout(&p, o);
236 x = MP_COPY(p.x);
237 EC_DESTROY(&p);
238 return (x);
239 } else if (GE_PYCHECK(o)) {
240 if ((x = G_TOINT(GE_G(o), MP_NEW, GE_X(o))) == 0)
241 return (0);
242 return (x);
243 }
244 #ifdef PY2
245 else if (PyInt_Check(o))
246 return (mp_fromlong(MP_NEW, PyInt_AS_LONG(o)));
247 #endif
248 else if ((l = PyNumber_Long(o)) != 0) {
249 x = mp_frompylong(l);
250 Py_DECREF(l);
251 return (x);
252 } else {
253 PyErr_Clear();
254 return (0);
255 }
256 }
257
258 mp *getmp(PyObject *o)
259 {
260 mp *x = 0;
261 if (!o) return (0);
262 if ((x = tomp(o)) == 0) {
263 PyErr_Format(PyExc_TypeError, "can't convert %.100s to mp",
264 Py_TYPE(o)->tp_name);
265 }
266 return (x);
267 }
268
269 int convmp(PyObject *o, void *p)
270 {
271 mp *x;
272 if ((x = getmp(o)) == 0) return (0);
273 *(mp **)p = x;
274 return (1);
275 }
276
277 mp *getgf(PyObject *o)
278 {
279 mp *x = 0;
280 if (!o) return (0);
281 if ((x = tomp(o)) == 0) {
282 PyErr_Format(PyExc_TypeError, "can't convert %.100s to gf",
283 Py_TYPE(o)->tp_name);
284 }
285 return (x);
286 }
287
288 int convgf(PyObject *o, void *p)
289 {
290 mp *x;
291 if ((x = getgf(o)) == 0) return (0);
292 *(mp **)p = x;
293 return (1);
294 }
295
296 mp *implicitmp(PyObject *o)
297 {
298 PyObject *l;
299
300 if (!o || GF_PYCHECK(o) || FE_PYCHECK(o)) return (0);
301 else if (MP_PYCHECK(o)) return (MP_COPY(MP_X(o)));
302 else if (PFILT_PYCHECK(o)) return (MP_COPY(PFILT_F(o)->m));
303 #ifdef PY2
304 else if (PyInt_Check(o)) return (mp_fromlong(MP_NEW, PyInt_AS_LONG(o)));
305 #endif
306 else if ((l = PyNumber_Index(o)) != 0) {
307 #ifdef PY2
308 if (PyInt_Check(o)) return (mp_fromlong(MP_NEW, PyInt_AS_LONG(o)));
309 #endif
310 if (PyLong_Check(o)) return (mp_frompylong(o));
311 }
312 PyErr_Clear(); return (0);
313 }
314
315 mp *implicitgf(PyObject *o)
316 {
317 if (GF_PYCHECK(o)) return (MP_COPY(MP_X(o)));
318 return (0);
319 }
320
321 static int mpbinop(PyObject *x, PyObject *y, mp **xx, mp **yy)
322 {
323 if ((*xx = implicitmp(x)) == 0)
324 return (-1);
325 if ((*yy = implicitmp(y)) == 0) {
326 MP_DROP(*xx);
327 return (-1);
328 }
329 return (0);
330 }
331
332 static int gfbinop(PyObject *x, PyObject *y, mp **xx, mp **yy)
333 {
334 if ((*xx = implicitgf(x)) == 0)
335 return (-1);
336 if ((*yy = implicitgf(y)) == 0) {
337 MP_DROP(*xx);
338 return (-1);
339 }
340 return (0);
341 }
342
343 #define FPBINOP(name, pyop) \
344 static PyObject *mp_py##name(PyObject *x, PyObject *y) { \
345 mp *xx, *yy, *zz; \
346 PyObject *l, *rc; \
347 if (PyFloat_Check(x)) { \
348 l = mp_topylong(MP_X(y)); rc = PyNumber_##pyop(x, l); \
349 Py_DECREF(l); return (rc); \
350 } else if (PyFloat_Check(y)) { \
351 l = mp_topylong(MP_X(x)); rc = PyNumber_##pyop(l, y); \
352 Py_DECREF(l); return (rc); \
353 } \
354 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
355 zz = mp_##name(MP_NEW, xx, yy); \
356 MP_DROP(xx); MP_DROP(yy); \
357 return (mp_pywrap(zz)); \
358 }
359 FPBINOP(add, Add)
360 FPBINOP(sub, Subtract)
361 FPBINOP(mul, Multiply)
362
363 #define gf_and mp_and
364 #define gf_or mp_or
365 #define gf_xor mp_xor
366 #define BINOP(pre, name) \
367 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
368 mp *xx, *yy, *zz; \
369 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
370 zz = pre##_##name(MP_NEW, xx, yy); \
371 MP_DROP(xx); MP_DROP(yy); \
372 return (pre##_pywrap(zz)); \
373 }
374 BINOP(mp, and2c)
375 BINOP(mp, or2c)
376 BINOP(mp, xor2c)
377 BINOP(gf, add)
378 BINOP(gf, sub)
379 BINOP(gf, mul)
380 BINOP(gf, and)
381 BINOP(gf, or)
382 BINOP(gf, xor)
383 #undef BINOP
384
385 static mp *mp_abs(mp *d, mp *x)
386 {
387 if (MP_NEGP(x))
388 return (mp_neg(d, x));
389 MP_COPY(x);
390 if (d) MP_DROP(d);
391 return (x);
392 }
393
394 #define UNOP(pre, name) \
395 static PyObject *pre##_py##name(PyObject *x) \
396 { return mp_pywrap(pre##_##name(MP_NEW, MP_X(x))); }
397 UNOP(mp, neg)
398 UNOP(mp, abs)
399 UNOP(mp, not2c)
400 #undef UNOP
401
402 static PyObject *mp_pyid(PyObject *x) { RETURN_OBJ(x); }
403
404 #define gf_lsr mp_lsr
405 #define SHIFTOP(pre, PRE, name, rname) \
406 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
407 PyObject *yix = 0; \
408 PyObject *z = 0; \
409 long n; \
410 if (!PRE##_PYCHECK(x)) RETURN_NOTIMPL; \
411 if (GF_PYCHECK(y) || FE_PYCHECK(y)) RETURN_NOTIMPL; \
412 yix = PyNumber_Index(y); if (!yix) { PyErr_Clear(); RETURN_NOTIMPL; } \
413 n = PyInt_AsLong(yix); Py_DECREF(yix); \
414 if (n == -1 && PyErr_Occurred()) { PyErr_Clear(); RETURN_NOTIMPL; } \
415 if (n < 0) z = pre##_pywrap(mp_##rname(MP_NEW, MP_X(x), -n)); \
416 else z = pre##_pywrap(mp_##name(MP_NEW, MP_X(x), n)); \
417 return (z); \
418 }
419 SHIFTOP(mp, MP, lsl2c, lsr2c)
420 SHIFTOP(mp, MP, lsr2c, lsl2c)
421 SHIFTOP(gf, GF, lsl, lsr)
422 SHIFTOP(gf, GF, lsr, lsl)
423 #undef SHIFTOP
424
425 #define DIVOP(pre, name, qq, rr, gather) \
426 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
427 mp *xx, *yy; \
428 PyObject *z = 0; \
429 INIT_##qq(q) INIT_##rr(r) \
430 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
431 if (MP_ZEROP(yy)) \
432 ZDIVERR("division by zero"); \
433 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
434 z = gather; \
435 end: \
436 MP_DROP(xx); MP_DROP(yy); \
437 return (z); \
438 }
439 #define INIT_YES(p) mp *p = MP_NEW;
440 #define INIT_NO(p)
441 #define ARG_YES(p) &p
442 #define ARG_NO(p) 0
443 DIVOP(mp, divmod, YES, YES,
444 Py_BuildValue("(NN)", mp_pywrap(q), mp_pywrap(r)))
445 DIVOP(mp, div, YES, NO, mp_pywrap(q))
446 DIVOP(mp, mod, NO, YES, mp_pywrap(r))
447 DIVOP(gf, divmod, YES, YES,
448 Py_BuildValue("(NN)", gf_pywrap(q), gf_pywrap(r)))
449 DIVOP(gf, div, YES, NO, gf_pywrap(q))
450 DIVOP(gf, mod, NO, YES, gf_pywrap(r))
451 #undef INIT_YES
452 #undef INIT_NO
453 #undef ARG_YES
454 #undef ARG_NO
455 #undef DIVOP
456
457 static mp *mp_modinv_checked(mp *d, mp *x, mp *p)
458 {
459 mp *g = MP_NEW;
460 mp_gcd(&g, 0, &d, p, x);
461 if (!MP_EQ(g, MP_ONE)) {
462 MP_DROP(g); MP_DROP(d);
463 PyErr_SetString(PyExc_ZeroDivisionError, "no modular inverse");
464 return (0);
465 }
466 MP_DROP(g); return (d);
467 }
468
469 static PyObject *mp_pyexp(PyObject *x, PyObject *y, PyObject *z)
470 {
471 mp *xx = 0, *yy = 0, *zz = 0;
472 mp *r = 0;
473 PyObject *rc = 0;
474
475 if ((xx = implicitmp(x)) == 0 || (yy = implicitmp(y)) == 0 ||
476 (z && z != Py_None && (zz = implicitmp(z)) == 0)) {
477 mp_drop(xx); mp_drop(yy); mp_drop(zz);
478 RETURN_NOTIMPL;
479 }
480 if (!z || z == Py_None) {
481 if (MP_NEGP(yy)) VALERR("negative exponent");
482 r = mp_exp(MP_NEW, xx, yy);
483 } else {
484 if (!MP_POSP(zz)) VALERR("modulus must be positive");
485 if (MP_NEGP(yy)) {
486 if ((xx = mp_modinv_checked(xx, xx, zz)) == 0) goto end;
487 yy = mp_neg(yy, yy);
488 }
489 if (MP_ODDP(zz)) {
490 mpmont mm;
491 mpmont_create(&mm, zz);
492 r = mpmont_exp(&mm, MP_NEW, xx, yy);
493 mpmont_destroy(&mm);
494 } else {
495 mpbarrett mb;
496 mpbarrett_create(&mb, zz);
497 r = mpbarrett_exp(&mb, MP_NEW, xx, yy);
498 mpbarrett_destroy(&mb);
499 }
500 }
501 rc = mp_pywrap(r);
502 end:
503 mp_drop(xx); mp_drop(yy); mp_drop(zz);
504 return (rc);
505 }
506
507 static mp *gf_modinv_checked(mp *d, mp *x, mp *p)
508 {
509 mp *g = MP_NEW;
510 gf_gcd(&g, 0, &d, p, x);
511 if (!MP_EQ(g, MP_ONE)) {
512 MP_DROP(g); MP_DROP(d);
513 PyErr_SetString(PyExc_ZeroDivisionError, "no modular inverse");
514 return (0);
515 }
516 MP_DROP(g); return (d);
517 }
518
519 #define BASEOP(name, radix, pre) \
520 static PyObject *mp_py##name(PyObject *x) \
521 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
522 #ifdef PY2
523 BASEOP(oct, 8, "0");
524 #endif
525 BASEOP(hex, 16, "0x");
526 #undef BASEOP
527
528 static int mp_pynonzerop(PyObject *x) { return !MP_ZEROP(MP_X(x)); }
529
530 static PyObject *mp_pyint(PyObject *x)
531 {
532 long l;
533 if (!mp_tolong_checked(MP_X(x), &l, 0)) return (PyInt_FromLong(l));
534 else return mp_topylong(MP_X(x));
535 }
536 #ifdef PY2
537 static PyObject *mp_pylong(PyObject *x)
538 { return (mp_topylong(MP_X(x))); }
539 #endif
540 static PyObject *mp_pyfloat(PyObject *x)
541 {
542 PyObject *l = mp_topylong(MP_X(x));
543 double f = PyLong_AsDouble(l);
544 Py_DECREF(l);
545 return (PyFloat_FromDouble(f));
546 }
547
548 #ifdef PY2
549 #define COERCE(pre, PRE) \
550 static int pre##_pycoerce(PyObject **x, PyObject **y) \
551 { \
552 mp *z; \
553 \
554 if (PRE##_PYCHECK(*y)) { \
555 Py_INCREF(*x); Py_INCREF(*y); \
556 return (0); \
557 } \
558 if ((z = implicit##pre(*y)) != 0) { \
559 Py_INCREF(*x); \
560 *y = pre##_pywrap(z); \
561 return (0); \
562 } \
563 return (1); \
564 }
565 COERCE(mp, MP)
566 COERCE(gf, GF)
567 #undef COERCE
568 #endif
569
570 static PyObject *mp_pyrichcompare(PyObject *x, PyObject *y, int op)
571 {
572 mp *xx, *yy;
573 PyObject *l, *rc;
574 if (PyFloat_Check(y)) {
575 l = mp_topylong(MP_X(x)); rc = PyObject_RichCompare(l, y, op);
576 Py_DECREF(l); return (rc);
577 }
578 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL;
579 rc = enrich_compare(op, mp_cmp(xx, yy));
580 MP_DROP(xx); MP_DROP(yy);
581 return (rc);
582 }
583
584 #ifdef PY2
585 static int mp_pycompare(PyObject *x, PyObject *y)
586 { return mp_cmp(MP_X(x), MP_X(y)); }
587 #endif
588
589 static PyObject *mp_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
590 {
591 PyObject *x;
592 mp *z;
593 mp_pyobj *zz = 0;
594 int radix = 0;
595 static const char *const kwlist[] = { "x", "radix", 0 };
596
597 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|i:new", KWLIST, &x, &radix))
598 goto end;
599 if (MP_PYCHECK(x)) RETURN_OBJ(x);
600 if (!good_radix_p(radix, 1)) VALERR("bad radix");
601 if ((z = mp_frompyobject(x, radix)) == 0) {
602 PyErr_Format(PyExc_TypeError, "can't convert %.100s to mp",
603 Py_TYPE(x)->tp_name);
604 goto end;
605 }
606 zz = (mp_pyobj *)ty->tp_alloc(ty, 0);
607 zz->x = z;
608 end:
609 return ((PyObject *)zz);
610 }
611
612 #define IMPLICIT(pre) \
613 static PyObject *pre##meth__implicit(PyObject *me, PyObject *arg) \
614 { \
615 PyObject *x, *rc = 0; \
616 mp *y = MP_NEW; \
617 if (!PyArg_ParseTuple(arg, "O:_implicit", &x)) goto end; \
618 y = implicit##pre(x); \
619 if (!y) TYERR("can't convert implicitly to " #pre); \
620 rc = pre##_pywrap(y); \
621 end: \
622 return (rc); \
623 }
624 IMPLICIT(mp)
625 IMPLICIT(gf)
626 #undef IMPLICIT
627
628 Py_hash_t mphash(mp *x)
629 {
630 PyObject *l = mp_topylong(x);
631 Py_hash_t h = PyObject_Hash(l);
632 Py_DECREF(l); return (h);
633 }
634
635 static Py_hash_t mp_pyhash(PyObject *me) { return (mphash(MP_X(me))); }
636
637 static PyObject *mpmeth_jacobi(PyObject *me, PyObject *arg)
638 {
639 mp *y = 0;
640 PyObject *z = 0;
641
642 if (!PyArg_ParseTuple(arg, "O&:jacobi", convmp, &y)) goto end;
643 z = PyInt_FromLong(mp_jacobi(y, MP_X(me)));
644 end:
645 if (y) MP_DROP(y);
646 return (z);
647 }
648
649 #define BITOP(pre, name, c) \
650 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
651 { \
652 unsigned long i; \
653 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
654 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
655 }
656 BITOP(mp, setbit, 2c);
657 BITOP(mp, clearbit, 2c);
658 BITOP(gf, setbit, );
659 BITOP(gf, clearbit, );
660 #undef BITOP
661
662 static PyObject *mpmeth_testbit(PyObject *me, PyObject *arg)
663 {
664 unsigned long i;
665 if (!PyArg_ParseTuple(arg, "O&:testbit", convulong, &i)) return (0);
666 return (getbool(mp_testbit2c(MP_X(me), i)));
667 }
668
669 static PyObject *gfmeth_testbit(PyObject *me, PyObject *arg)
670 {
671 unsigned long i;
672 if (!PyArg_ParseTuple(arg, "O&:testbit", convulong, &i)) return (0);
673 return (getbool(mp_testbit(MP_X(me), i)));
674 }
675
676 static PyObject *mpmeth_odd(PyObject *me)
677 {
678 mp *t;
679 size_t s;
680
681 t = mp_odd(MP_NEW, MP_X(me), &s);
682 return (Py_BuildValue("(lN)", (long)s, mp_pywrap(t)));
683 }
684
685 static PyObject *mpmeth_sqr(PyObject *me)
686 { return (mp_pywrap(mp_sqr(MP_NEW, MP_X(me)))); }
687
688 static PyObject *mpmeth_sqrt(PyObject *me)
689 {
690 if (MP_NEGP(MP_X(me))) VALERR("negative root");
691 return (mp_pywrap(mp_sqrt(MP_NEW, MP_X(me))));
692 end:
693 return (0);
694 }
695
696 static PyObject *mpmeth_gcd(PyObject *me, PyObject *arg)
697 {
698 mp *y = 0, *zz = MP_NEW;
699 PyObject *z = 0;
700
701 if (!PyArg_ParseTuple(arg, "O&:gcd", convmp, &y)) goto end;
702 mp_gcd(&zz, 0, 0, MP_X(me), y);
703 z = mp_pywrap(zz);
704 end:
705 if (y) MP_DROP(y);
706 return (z);
707 }
708
709 static PyObject *mpmeth_gcdx(PyObject *me, PyObject *arg)
710 {
711 PyObject *z = 0;
712 mp *yy = 0, *zz = MP_NEW, *uu = MP_NEW, *vv = MP_NEW;
713
714 if (!PyArg_ParseTuple(arg, "O&:gcdx", convmp, &yy)) goto end;
715 mp_gcd(&zz, &uu, &vv, MP_X(me), yy);
716 z = Py_BuildValue("(NNN)",
717 mp_pywrap(zz), mp_pywrap(uu), mp_pywrap(vv));
718 end:
719 if (yy) MP_DROP(yy);
720 return (z);
721 }
722
723 static PyObject *mpmeth_modinv(PyObject *me, PyObject *arg)
724 {
725 PyObject *z = 0;
726 mp *yy = 0, *zz = MP_NEW;
727
728 if (!PyArg_ParseTuple(arg, "O&:modinv", convmp, &yy) ||
729 (zz = mp_modinv_checked(MP_NEW, yy, MP_X(me))) == 0)
730 goto end;
731 z = mp_pywrap(zz);
732 end:
733 if (yy) MP_DROP(yy);
734 return (z);
735 }
736
737 static PyObject *mpmeth_tostring(PyObject *me, PyObject *arg, PyObject *kw)
738 {
739 int radix = 10;
740 static const char *const kwlist[] = { "radix", 0 };
741 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|i:tostring", KWLIST, &radix))
742 goto end;
743 if (!good_radix_p(radix, 0)) VALERR("bad radix");
744 return (mp_topystring(MP_X(me), radix, 0, 0, 0));
745 end:
746 return (0);
747 }
748
749 static PyObject *mpmeth_modsqrt(PyObject *me, PyObject *arg)
750 {
751 PyObject *z = 0;
752 mp *yy = 0, *zz = MP_NEW;
753
754 if (!PyArg_ParseTuple(arg, "O&:modsqrt", convmp, &yy)) goto end;
755 if ((zz = mp_modsqrt(MP_NEW, yy, MP_X(me))) == 0)
756 VALERR("no modular square root");
757 z = mp_pywrap(zz);
758 end:
759 if (yy) MP_DROP(yy);
760 return (z);
761 }
762
763 static PyObject *mpmeth_leastcongruent(PyObject *me, PyObject *arg)
764 {
765 mp *z, *b, *m;
766 PyObject *rc = 0;
767
768 if (!PyArg_ParseTuple(arg, "O&O&:leastcongruent", convmp, &b, convmp, &m))
769 goto end;
770 z = mp_leastcongruent(MP_NEW, b, MP_X(me), m);
771 rc = mp_pywrap(z);
772 end:
773 return (rc);
774 }
775
776 #define STOREOP(name, c) \
777 static PyObject *mpmeth_##name(PyObject *me, \
778 PyObject *arg, PyObject *kw) \
779 { \
780 long len = -1; \
781 static const char *const kwlist[] = { "len", 0 }; \
782 PyObject *rc = 0; \
783 \
784 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
785 KWLIST, &len)) \
786 goto end; \
787 if (len < 0) { \
788 len = mp_octets##c(MP_X(me)); \
789 if (!len) len = 1; \
790 } \
791 rc = bytestring_pywrap(0, len); \
792 mp_##name(MP_X(me), BIN_PTR(rc), len); \
793 end: \
794 return (rc); \
795 }
796 STOREOP(storel, )
797 STOREOP(storeb, )
798 STOREOP(storel2c, 2c)
799 STOREOP(storeb2c, 2c)
800 #undef STOREOP
801
802 #define BUFOP(ty) \
803 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
804 { \
805 buf b; \
806 struct bin in; \
807 PyObject *rc = 0; \
808 mp *x; \
809 \
810 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
811 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
812 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
813 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
814 bytestring_pywrapbuf(&b)); \
815 end: \
816 return (rc); \
817 }
818 BUFOP(mp)
819 BUFOP(gf)
820 #undef BUFOP
821
822 static PyObject *mpmeth_tobuf(PyObject *me)
823 {
824 buf b;
825 PyObject *rc;
826 mp *x;
827 size_t n;
828
829 x = MP_X(me);
830 n = mp_octets(x) + 3;
831 rc = bytestring_pywrap(0, n);
832 buf_init(&b, BIN_PTR(rc), n);
833 buf_putmp(&b, x);
834 assert(BOK(&b));
835 BIN_SETLEN(rc, BLEN(&b));
836 return (rc);
837 }
838
839 static PyObject *mpmeth_primep(PyObject *me, PyObject *arg, PyObject *kw)
840 {
841 grand *r = &rand_global;
842 static const char *const kwlist[] = { "rng", 0 };
843 PyObject *rc = 0;
844
845 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&", KWLIST, convgrand, &r))
846 goto end;
847 rc = getbool(pgen_primep(MP_X(me), r));
848 end:
849 return (rc);
850 }
851
852 static PyObject *mpmeth_fromstring(PyObject *me,
853 PyObject *arg, PyObject *kw)
854 {
855 int r = 0;
856 char *p;
857 Py_ssize_t len;
858 PyObject *z = 0;
859 mp *zz;
860 mptext_stringctx sc;
861 static const char *const kwlist[] = { "x", "radix", 0 };
862
863 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
864 &p, &len, &r))
865 goto end;
866 if (!good_radix_p(r, 1)) VALERR("bad radix");
867 sc.buf = p; sc.lim = p + len;
868 if ((zz = mp_read(MP_NEW, r, &mptext_stringops, &sc)) == 0)
869 VALERR("bad integer");
870 z = Py_BuildValue("(Ns#)", mp_pywrap(zz),
871 sc.buf, (Py_ssize_t)(sc.lim - sc.buf));
872 end:
873 return (z);
874 }
875
876 static PyObject *mpmeth_factorial(PyObject *me, PyObject *arg)
877 {
878 unsigned long i;
879 mp *x;
880 if (!PyArg_ParseTuple(arg, "O&:factorial", convulong, &i)) return (0);
881 x = mp_factorial(i);
882 return mp_pywrap(x);
883 }
884
885 static PyObject *mpmeth_fibonacci(PyObject *me, PyObject *arg)
886 {
887 long i;
888 mp *x;
889 if (!PyArg_ParseTuple(arg, "l:fibonacci", &i)) return (0);
890 x = mp_fibonacci(i);
891 return mp_pywrap(x);
892 }
893
894 #define LOADOP(pre, name) \
895 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
896 { \
897 struct bin in; \
898 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
899 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
900 }
901 LOADOP(mp, loadl)
902 LOADOP(mp, loadb)
903 LOADOP(mp, loadl2c)
904 LOADOP(mp, loadb2c)
905 LOADOP(gf, loadl)
906 LOADOP(gf, loadb)
907 #undef LOADOP
908
909 static PyObject *mpget_nbits(PyObject *me, void *hunoz)
910 { return (PyInt_FromLong(mp_bits(MP_X(me)))); }
911
912 static PyObject *mpget_noctets(PyObject *me, void *hunoz)
913 { return (PyInt_FromLong(mp_octets(MP_X(me)))); }
914
915 static PyObject *mpget_noctets2c(PyObject *me, void *hunoz)
916 { return (PyInt_FromLong(mp_octets2c(MP_X(me)))); }
917
918 static const PyGetSetDef mp_pygetset[] = {
919 #define GETSETNAME(op, func) mp##op##_##func
920 GET (nbits, "X.nbits -> bit length of X")
921 GET (noctets, "X.noctets -> octet length of X")
922 GET (noctets2c, "X.noctets2c -> two's complement octet length of X")
923 #undef GETSETNAME
924 { 0 }
925 };
926
927 static const PyMethodDef mp_pymethods[] = {
928 #define METHNAME(func) mpmeth_##func
929 METH (jacobi, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
930 METH (setbit, "X.setbit(N) -> X with bit N set")
931 METH (clearbit, "X.clearbit(N) -> X with bit N clear")
932 METH (testbit, "X.testbit(N) -> true/false if bit N set/clear in X")
933 NAMETH(odd, "X.odd() -> S, T where X = 2^S T with T odd")
934 NAMETH(sqr, "X.sqr() -> X^2")
935 NAMETH(sqrt, "X.sqrt() -> largest integer <= sqrt(X)")
936 METH (gcd, "X.gcd(Y) -> gcd(X, Y)")
937 METH (gcdx, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
938 "with X U + Y V = gcd(X, Y)")
939 METH (modinv, "X.modinv(Y) -> multiplicative inverse of Y mod X")
940 METH (modsqrt, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
941 METH (leastcongruent, "X.leastcongruent(B, M) -> "
942 "smallest Z >= B with Z == X (mod M)")
943 KWMETH(primep, "X.primep([rng = rand]) -> X is prime?")
944 KWMETH(tostring, "X.tostring([radix = 10]) -> STR")
945 KWMETH(storel, "X.storel([len = -1]) -> little-endian bytes")
946 KWMETH(storeb, "X.storeb([len = -1]) -> big-endian bytes")
947 KWMETH(storel2c, "X.storel2c([len = -1]) -> "
948 "little-endian bytes, two's complement")
949 KWMETH(storeb2c, "X.storeb2c([len = -1]) -> "
950 "big-endian bytes, two's complement")
951 NAMETH(tobuf, "X.tobuf() -> buffer format")
952 KWSMTH(fromstring, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
953 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
954 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
955 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
956 SMTH (_implicit, 0)
957 SMTH (factorial, "factorial(I) -> I!: compute factorial")
958 SMTH (fibonacci, "fibonacci(I) -> F(I): compute Fibonacci number")
959 SMTH (loadl, "loadl(STR) -> X: read little-endian bytes")
960 SMTH (loadb, "loadb(STR) -> X: read big-endian bytes")
961 SMTH (loadl2c, "loadl2c(STR) -> X: "
962 "read little-endian bytes, two's complement")
963 SMTH (loadb2c, "loadb2c(STR) -> X: "
964 "read big-endian bytes, two's complement")
965 SMTH (frombuf, "frombuf(STR) -> (X, REST): read buffer format")
966 #undef METHNAME
967 { 0 }
968 };
969
970 static const PyNumberMethods mp_pynumber = {
971 mp_pyadd, /* @nb_add@ */
972 mp_pysub, /* @nb_subtract@ */
973 mp_pymul, /* @nb_multiply@ */
974 #ifdef PY2
975 0, /* @nb_divide@ */
976 #endif
977 mp_pymod, /* @nb_remainder@ */
978 mp_pydivmod, /* @nb_divmod@ */
979 mp_pyexp, /* @nb_power@ */
980 mp_pyneg, /* @nb_negative@ */
981 mp_pyid, /* @nb_positive@ */
982 mp_pyabs, /* @nb_absolute@ */
983 mp_pynonzerop, /* @nb_nonzero@ */
984 mp_pynot2c, /* @nb_invert@ */
985 mp_pylsl2c, /* @nb_lshift@ */
986 mp_pylsr2c, /* @nb_rshift@ */
987 mp_pyand2c, /* @nb_and@ */
988 mp_pyxor2c, /* @nb_xor@ */
989 mp_pyor2c, /* @nb_or@ */
990 #ifdef PY2
991 mp_pycoerce, /* @nb_coerce@ */
992 #endif
993 mp_pyint, /* @nb_int@ */
994 PY23(mp_pylong, 0), /* @nb_long@ */
995 mp_pyfloat, /* @nb_float@ */
996 #ifdef PY2
997 mp_pyoct, /* @nb_oct@ */
998 mp_pyhex, /* @nb_hex@ */
999 #endif
1000
1001 0, /* @nb_inplace_add@ */
1002 0, /* @nb_inplace_subtract@ */
1003 0, /* @nb_inplace_multiply@ */
1004 #ifdef PY2
1005 0, /* @nb_inplace_divide@ */
1006 #endif
1007 0, /* @nb_inplace_remainder@ */
1008 0, /* @nb_inplace_power@ */
1009 0, /* @nb_inplace_lshift@ */
1010 0, /* @nb_inplace_rshift@ */
1011 0, /* @nb_inplace_and@ */
1012 0, /* @nb_inplace_xor@ */
1013 0, /* @nb_inplace_or@ */
1014
1015 mp_pydiv, /* @nb_floor_divide@ */
1016 0, /* @nb_true_divide@ */
1017 0, /* @nb_inplace_floor_divide@ */
1018 0, /* @nb_inplace_true_divide@ */
1019
1020 mp_pyint, /* @nb_index@ */
1021 };
1022
1023 static const PyTypeObject mp_pytype_skel = {
1024 PyVarObject_HEAD_INIT(0, 0) /* Header */
1025 "MP", /* @tp_name@ */
1026 sizeof(mp_pyobj), /* @tp_basicsize@ */
1027 0, /* @tp_itemsize@ */
1028
1029 mp_pydealloc, /* @tp_dealloc@ */
1030 0, /* @tp_print@ */
1031 0, /* @tp_getattr@ */
1032 0, /* @tp_setattr@ */
1033 PY23(mp_pycompare, 0), /* @tp_compare@/@tp_as_async@ */
1034 mp_pyrepr, /* @tp_repr@ */
1035 PYNUMBER(mp), /* @tp_as_number@ */
1036 0, /* @tp_as_sequence@ */
1037 0, /* @tp_as_mapping@ */
1038 mp_pyhash, /* @tp_hash@ */
1039 0, /* @tp_call@ */
1040 mp_pystr, /* @tp_str@ */
1041 0, /* @tp_getattro@ */
1042 0, /* @tp_setattro@ */
1043 0, /* @tp_as_buffer@ */
1044 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1045 Py_TPFLAGS_CHECKTYPES |
1046 Py_TPFLAGS_BASETYPE,
1047
1048 /* @tp_doc@ */
1049 "Multiprecision integers, similar to `long' but more efficient and\n"
1050 "versatile. Support all the standard arithmetic operations, with\n"
1051 "implicit conversions from `PrimeFilter', and other objects which\n"
1052 "convert to `" PY23("long", "int") "'.\n"
1053 "\n"
1054 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1055 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1056 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1057 PY23(
1058 "points, group elements, Python `int' and `long' objects, and anything\n"
1059 "with an integer conversion.\n",
1060 "points, group elements, Python `int' objects, and anything with an\n"
1061 "integer conversion.\n")
1062 "\n"
1063 "Notes:\n"
1064 "\n"
1065 " * Use `//' for integer division: `/' gives exact rational division.",
1066
1067 0, /* @tp_traverse@ */
1068 0, /* @tp_clear@ */
1069 mp_pyrichcompare, /* @tp_richcompare@ */
1070 0, /* @tp_weaklistoffset@ */
1071 0, /* @tp_iter@ */
1072 0, /* @tp_iternext@ */
1073 PYMETHODS(mp), /* @tp_methods@ */
1074 0, /* @tp_members@ */
1075 PYGETSET(mp), /* @tp_getset@ */
1076 0, /* @tp_base@ */
1077 0, /* @tp_dict@ */
1078 0, /* @tp_descr_get@ */
1079 0, /* @tp_descr_set@ */
1080 0, /* @tp_dictoffset@ */
1081 0, /* @tp_init@ */
1082 PyType_GenericAlloc, /* @tp_alloc@ */
1083 mp_pynew, /* @tp_new@ */
1084 0, /* @tp_free@ */
1085 0 /* @tp_is_gc@ */
1086 };
1087
1088 /*----- Products of small integers ----------------------------------------*/
1089
1090 static PyTypeObject *mpmul_pytype;
1091
1092 typedef struct mpmul_pyobj {
1093 PyObject_HEAD
1094 int livep;
1095 mpmul mm;
1096 } mpmul_pyobj;
1097
1098 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1099 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1100
1101 static void mpmul_pydealloc(PyObject *me)
1102 {
1103 if (MPMUL_LIVEP(me))
1104 mp_drop(mpmul_done(MPMUL_PY(me)));
1105 FREEOBJ(me);
1106 }
1107
1108 static PyObject *mmmeth_factor(PyObject *me, PyObject *arg)
1109 {
1110 PyObject *q, *i;
1111 mp *x;
1112
1113 if (!MPMUL_LIVEP(me)) VALERR("MPMul object invalid");
1114 if (PyTuple_GET_SIZE(arg) != 1)
1115 i = PyObject_GetIter(arg);
1116 else {
1117 if ((q = PyTuple_GET_ITEM(arg, 0)) == 0) goto end;
1118 if ((i = PyObject_GetIter(q)) == 0) {
1119 PyErr_Clear(); /* that's ok */
1120 i = PyObject_GetIter(arg);
1121 }
1122 }
1123 if (!i) goto end;
1124 while ((q = PyIter_Next(i)) != 0) {
1125 x = getmp(q); Py_DECREF(q); if (!x) {
1126 Py_DECREF(i);
1127 goto end;
1128 }
1129 mpmul_add(MPMUL_PY(me), x);
1130 MP_DROP(x);
1131 }
1132 Py_DECREF(i);
1133 RETURN_ME;
1134 end:
1135 return (0);
1136 }
1137
1138 static PyObject *mmmeth_done(PyObject *me)
1139 {
1140 mp *x;
1141
1142 if (!MPMUL_LIVEP(me)) VALERR("MPMul object invalid");
1143 x = mpmul_done(MPMUL_PY(me));
1144 MPMUL_LIVEP(me) = 0;
1145 return (mp_pywrap(x));
1146 end:
1147 return (0);
1148 }
1149
1150 static PyObject *mpmul_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1151 {
1152 mpmul_pyobj *mm;
1153
1154 if (kw) TYERR("keyword arguments not allowed here");
1155 mm = (mpmul_pyobj *)ty->tp_alloc(ty, 0);
1156 mpmul_init(&mm->mm);
1157 mm->livep = 1;
1158 if (mmmeth_factor((PyObject *)mm, arg) == 0) {
1159 Py_DECREF(mm);
1160 goto end;
1161 }
1162 return ((PyObject *)mm);
1163 end:
1164 return (0);
1165 }
1166
1167 static PyObject *mmget_livep(PyObject *me, void *hunoz)
1168 { return (getbool(MPMUL_LIVEP(me))); }
1169
1170 static const PyGetSetDef mpmul_pygetset[] = {
1171 #define GETSETNAME(op, name) mm##op##_##name
1172 GET (livep, "MM.livep -> flag: object still valid?")
1173 #undef GETSETNAME
1174 { 0 }
1175 };
1176
1177 static const PyMethodDef mpmul_pymethods[] = {
1178 #define METHNAME(name) mmmeth_##name
1179 METH (factor, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1180 NAMETH(done, "MM.done() -> PRODUCT")
1181 #undef METHNAME
1182 { 0 }
1183 };
1184
1185 static const PyTypeObject mpmul_pytype_skel = {
1186 PyVarObject_HEAD_INIT(0, 0) /* Header */
1187 "MPMul", /* @tp_name@ */
1188 sizeof(mpmul_pyobj), /* @tp_basicsize@ */
1189 0, /* @tp_itemsize@ */
1190
1191 mpmul_pydealloc, /* @tp_dealloc@ */
1192 0, /* @tp_print@ */
1193 0, /* @tp_getattr@ */
1194 0, /* @tp_setattr@ */
1195 0, /* @tp_compare@ */
1196 0, /* @tp_repr@ */
1197 0, /* @tp_as_number@ */
1198 0, /* @tp_as_sequence@ */
1199 0, /* @tp_as_mapping@ */
1200 0, /* @tp_hash@ */
1201 0, /* @tp_call@ */
1202 0, /* @tp_str@ */
1203 0, /* @tp_getattro@ */
1204 0, /* @tp_setattro@ */
1205 0, /* @tp_as_buffer@ */
1206 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1207 Py_TPFLAGS_BASETYPE,
1208
1209 /* @tp_doc@ */
1210 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1211
1212 0, /* @tp_traverse@ */
1213 0, /* @tp_clear@ */
1214 0, /* @tp_richcompare@ */
1215 0, /* @tp_weaklistoffset@ */
1216 0, /* @tp_iter@ */
1217 0, /* @tp_iternext@ */
1218 PYMETHODS(mpmul), /* @tp_methods@ */
1219 0, /* @tp_members@ */
1220 PYGETSET(mpmul), /* @tp_getset@ */
1221 0, /* @tp_base@ */
1222 0, /* @tp_dict@ */
1223 0, /* @tp_descr_get@ */
1224 0, /* @tp_descr_set@ */
1225 0, /* @tp_dictoffset@ */
1226 0, /* @tp_init@ */
1227 PyType_GenericAlloc, /* @tp_alloc@ */
1228 mpmul_pynew, /* @tp_new@ */
1229 0, /* @tp_free@ */
1230 0 /* @tp_is_gc@ */
1231 };
1232
1233 /*----- Montgomery reduction ----------------------------------------------*/
1234
1235 static PyTypeObject *mpmont_pytype;
1236
1237 typedef struct mpmont_pyobj {
1238 PyObject_HEAD
1239 mpmont mm;
1240 } mpmont_pyobj;
1241
1242 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1243
1244 static PyObject *mmmeth_int(PyObject *me, PyObject *arg)
1245 {
1246 PyObject *z = 0;
1247 mp *yy = 0;
1248 mpmont *mm = MPMONT_PY(me);
1249
1250 if (!PyArg_ParseTuple(arg, "O&:in", convmp, &yy))
1251 goto end;
1252 mp_div(0, &yy, yy, mm->m);
1253 z = mp_pywrap(mpmont_mul(mm, MP_NEW, yy, mm->r2));
1254 end:
1255 if (yy) MP_DROP(yy);
1256 return (z);
1257 }
1258
1259 static PyObject *mmmeth_mul(PyObject *me, PyObject *arg)
1260 {
1261 PyObject *rc = 0;
1262 mp *yy = 0, *zz = 0;
1263
1264 if (!PyArg_ParseTuple(arg, "O&O&:mul", convmp, &yy, convmp, &zz))
1265 goto end;
1266 rc = mp_pywrap(mpmont_mul(MPMONT_PY(me), MP_NEW, yy, zz));
1267 end:
1268 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1269 return (rc);
1270 }
1271
1272 static PyObject *mmmeth_exp(PyObject *me, PyObject *arg)
1273 {
1274 PyObject *rc = 0;
1275 mp *yy = 0, *zz = 0;
1276
1277 if (!PyArg_ParseTuple(arg, "O&O&:exp", convmp, &yy, convmp, &zz))
1278 goto end;
1279 if (MP_NEGP(zz)) {
1280 if ((yy = mp_modinv_checked(yy, yy, MPMONT_PY(me)->m)) == 0) goto end;
1281 zz = mp_neg(zz, zz);
1282 }
1283 rc = mp_pywrap(mpmont_exp(MPMONT_PY(me), MP_NEW, yy, zz));
1284 end:
1285 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1286 return (rc);
1287 }
1288
1289 static PyObject *mmmeth_expr(PyObject *me, PyObject *arg)
1290 {
1291 PyObject *rc = 0;
1292 mp *yy = 0, *zz = 0;
1293
1294 if (!PyArg_ParseTuple(arg, "O&O&:expr", convmp, &yy, convmp, &zz))
1295 goto end;
1296 if (MP_NEGP(zz)) {
1297 yy = mpmont_reduce(MPMONT_PY(me), yy, yy);
1298 if ((yy = mp_modinv_checked(yy, yy, MPMONT_PY(me)->m)) == 0) goto end;
1299 yy = mpmont_mul(MPMONT_PY(me), yy, yy, MPMONT_PY(me)->r2);
1300 zz = mp_neg(zz, zz);
1301 }
1302 rc = mp_pywrap(mpmont_expr(MPMONT_PY(me), MP_NEW, yy, zz));
1303 end:
1304 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1305 return (rc);
1306 }
1307
1308 static PyObject *mm_mexpr_id(PyObject *me)
1309 { return mp_pywrap(MP_COPY(MPMONT_PY(me)->r)); }
1310
1311 static int mm_mexpr_fill(void *p, PyObject *me, PyObject *x, PyObject *y)
1312 {
1313 mp *xx = 0, *yy = 0;
1314 mp_expfactor *f = p;
1315 mpmont *mm = MPMONT_PY(me);
1316
1317 if ((xx = getmp(x)) == 0 || (yy = getmp(y)) == 0)
1318 goto fail;
1319 if (MP_NEGP(yy)) {
1320 xx = mpmont_reduce(mm, xx, xx);
1321 if ((xx = mp_modinv_checked(xx, xx, yy)) == 0)
1322 goto fail;
1323 xx = mpmont_mul(mm, xx, xx, mm->r2);
1324 yy = mp_neg(yy, yy);
1325 }
1326 f->base = xx;
1327 f->exp = yy;
1328 return (0);
1329
1330 fail:
1331 mp_drop(xx); mp_drop(yy);
1332 return (-1);
1333 }
1334
1335 static PyObject *mm_mexpr(PyObject *me, void *v, size_t n)
1336 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me), MP_NEW, v, n)); }
1337
1338 static void mp_mexp_drop(void *p)
1339 {
1340 mp_expfactor *f = p;
1341 mp_drop(f->base);
1342 mp_drop(f->exp);
1343 }
1344
1345 static PyObject *mmmeth_mexpr(PyObject *me, PyObject *arg)
1346 {
1347 return mexp_common(me, arg, sizeof(mp_expfactor),
1348 mm_mexpr_id, mm_mexpr_fill, mm_mexpr, mp_mexp_drop);
1349 }
1350
1351 static PyObject *mp_mexp_id(PyObject *me)
1352 { return mp_pywrap(MP_ONE); }
1353
1354 static int mp_mexp_fill(void *p, PyObject *me, PyObject *x, PyObject *y)
1355 {
1356 mp *xx = 0, *yy = 0;
1357 mp_expfactor *f = p;
1358
1359 if ((xx = getmp(x)) == 0 || (yy = getmp(y)) == 0)
1360 goto fail;
1361 if (MP_NEGP(yy)) {
1362 if ((xx = mp_modinv_checked(xx, xx, yy)) == 0)
1363 goto fail;
1364 yy = mp_neg(yy, yy);
1365 }
1366 f->base = xx;
1367 f->exp = yy;
1368 return (0);
1369
1370 fail:
1371 mp_drop(xx); mp_drop(yy);
1372 return (-1);
1373 }
1374
1375 static PyObject *mm_mexp(PyObject *me, void *v, size_t n)
1376 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me), MP_NEW, v, n)); }
1377
1378 static PyObject *mmmeth_mexp(PyObject *me, PyObject *arg)
1379 {
1380 return mexp_common(me, arg, sizeof(mp_expfactor),
1381 mp_mexp_id, mp_mexp_fill, mm_mexp, mp_mexp_drop);
1382 }
1383
1384 #define mmmeth_ext mmmeth_reduce
1385 static PyObject *mmmeth_reduce(PyObject *me, PyObject *arg)
1386 {
1387 PyObject *z = 0;
1388 mp *yy = 0;
1389
1390 if (!PyArg_ParseTuple(arg, "O&", convmp, &yy)) goto end;
1391 z = mp_pywrap(mpmont_reduce(MPMONT_PY(me), MP_NEW, yy));
1392 end:
1393 return (z);
1394 }
1395
1396 static void mpmont_pydealloc(PyObject *me)
1397 {
1398 mpmont_destroy(MPMONT_PY(me));
1399 FREEOBJ(me);
1400 }
1401
1402 static PyObject *mpmont_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1403 {
1404 mpmont_pyobj *mm = 0;
1405 static const char *const kwlist[] = { "m", 0 };
1406 mp *xx = 0;
1407
1408 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
1409 goto end;
1410 if (!MP_POSP(xx) || !MP_ODDP(xx)) VALERR("m must be positive and odd");
1411 mm = (mpmont_pyobj *)ty->tp_alloc(ty, 0);
1412 mpmont_create(&mm->mm, xx);
1413 end:
1414 if (xx) MP_DROP(xx);
1415 return ((PyObject *)mm);
1416 }
1417
1418 static PyObject *mmget_m(PyObject *me, void *hunoz)
1419 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->m))); }
1420
1421 static PyObject *mmget_r(PyObject *me, void *hunoz)
1422 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->r))); }
1423
1424 static PyObject *mmget_r2(PyObject *me, void *hunoz)
1425 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->r2))); }
1426
1427 static const PyGetSetDef mpmont_pygetset[] = {
1428 #define GETSETNAME(op, name) mm##op##_##name
1429 GET (m, "M.m -> modulus for reduction")
1430 GET (r, "M.r -> multiplicative identity")
1431 GET (r2, "M.r2 -> M.r^2, Montgomerization factor")
1432 #undef GETSETNAME
1433 { 0 }
1434 };
1435
1436 static const PyMethodDef mpmont_pymethods[] = {
1437 #define METHNAME(name) mmmeth_##name
1438 METH (int, "M.int(X) -> XR")
1439 METH (mul, "M.mul(XR, YR) -> ZR where Z = X Y")
1440 METH (expr, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1441 METH (mexpr, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1442 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1443 "\t(the list may be flattened if this more convenient.)")
1444 METH (reduce, "M.reduce(XR) -> X")
1445 METH (ext, "M.ext(XR) -> X")
1446 METH (exp, "M.exp(X, N) -> X^N mod M.m")
1447 METH (mexp, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1448 "X0^N0 X1^N1 ... mod M.m\n"
1449 "\t(the list may be flattened if this more convenient.)")
1450 #undef METHNAME
1451 { 0 }
1452 };
1453
1454 static const PyTypeObject mpmont_pytype_skel = {
1455 PyVarObject_HEAD_INIT(0, 0) /* Header */
1456 "MPMont", /* @tp_name@ */
1457 sizeof(mpmont_pyobj), /* @tp_basicsize@ */
1458 0, /* @tp_itemsize@ */
1459
1460 mpmont_pydealloc, /* @tp_dealloc@ */
1461 0, /* @tp_print@ */
1462 0, /* @tp_getattr@ */
1463 0, /* @tp_setattr@ */
1464 0, /* @tp_compare@ */
1465 0, /* @tp_repr@ */
1466 0, /* @tp_as_number@ */
1467 0, /* @tp_as_sequence@ */
1468 0, /* @tp_as_mapping@ */
1469 0, /* @tp_hash@ */
1470 0, /* @tp_call@ */
1471 0, /* @tp_str@ */
1472 0, /* @tp_getattro@ */
1473 0, /* @tp_setattro@ */
1474 0, /* @tp_as_buffer@ */
1475 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1476 Py_TPFLAGS_BASETYPE,
1477
1478 /* @tp_doc@ */
1479 "MPMont(N): a Montgomery reduction context.",
1480
1481 0, /* @tp_traverse@ */
1482 0, /* @tp_clear@ */
1483 0, /* @tp_richcompare@ */
1484 0, /* @tp_weaklistoffset@ */
1485 0, /* @tp_iter@ */
1486 0, /* @tp_iternext@ */
1487 PYMETHODS(mpmont), /* @tp_methods@ */
1488 0, /* @tp_members@ */
1489 PYGETSET(mpmont), /* @tp_getset@ */
1490 0, /* @tp_base@ */
1491 0, /* @tp_dict@ */
1492 0, /* @tp_descr_get@ */
1493 0, /* @tp_descr_set@ */
1494 0, /* @tp_dictoffset@ */
1495 0, /* @tp_init@ */
1496 PyType_GenericAlloc, /* @tp_alloc@ */
1497 mpmont_pynew, /* @tp_new@ */
1498 0, /* @tp_free@ */
1499 0 /* @tp_is_gc@ */
1500 };
1501
1502 /*----- Barrett reduction -------------------------------------------------*/
1503
1504 static PyTypeObject *mpbarrett_pytype;
1505
1506 typedef struct mpbarrett_pyobj {
1507 PyObject_HEAD
1508 mpbarrett mb;
1509 } mpbarrett_pyobj;
1510
1511 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1512
1513 static PyObject *mbmeth_exp(PyObject *me, PyObject *arg)
1514 {
1515 PyObject *rc = 0;
1516 mp *yy = 0, *zz = 0;
1517
1518 if (!PyArg_ParseTuple(arg, "O&O&:exp", convmp, &yy, convmp, &zz))
1519 goto end;
1520 if (MP_NEGP(zz)) {
1521 if ((yy = mp_modinv_checked(yy, yy, MPBARRETT_PY(me)->m)) == 0) goto end;
1522 zz = mp_neg(zz, zz);
1523 }
1524 rc = mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me), MP_NEW, yy, zz));
1525 end:
1526 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1527 return (rc);
1528 }
1529
1530 static PyObject *mb_mexp(PyObject *me, void *v, size_t n)
1531 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me), MP_NEW, v, n)); }
1532
1533 static PyObject *mbmeth_mexp(PyObject *me, PyObject *arg)
1534 {
1535 return mexp_common(me, arg, sizeof(mp_expfactor),
1536 mp_mexp_id, mp_mexp_fill, mb_mexp, mp_mexp_drop);
1537 }
1538
1539 static PyObject *mbmeth_reduce(PyObject *me, PyObject *arg)
1540 {
1541 PyObject *z = 0;
1542 mp *yy = 0;
1543
1544 if (!PyArg_ParseTuple(arg, "O&:reduce", convmp, &yy))
1545 goto end;
1546 z = mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me), MP_NEW, yy));
1547 end:
1548 return (z);
1549 }
1550
1551 static void mpbarrett_pydealloc(PyObject *me)
1552 {
1553 mpbarrett_destroy(MPBARRETT_PY(me));
1554 FREEOBJ(me);
1555 }
1556
1557 static PyObject *mpbarrett_pynew(PyTypeObject *ty,
1558 PyObject *arg, PyObject *kw)
1559 {
1560 mpbarrett_pyobj *mb = 0;
1561 static const char *const kwlist[] = { "m", 0 };
1562 mp *xx = 0;
1563
1564 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
1565 goto end;
1566 if (!MP_POSP(xx)) VALERR("m must be positive");
1567 mb = (mpbarrett_pyobj *)ty->tp_alloc(ty, 0);
1568 mpbarrett_create(&mb->mb, xx);
1569 end:
1570 if (xx) MP_DROP(xx);
1571 return ((PyObject *)mb);
1572 }
1573
1574 static PyObject *mbget_m(PyObject *me, void *hunoz)
1575 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me)->m))); }
1576
1577 static const PyGetSetDef mpbarrett_pygetset[] = {
1578 #define GETSETNAME(op, name) mb##op##_##name
1579 GET (m, "B.m -> modulus for reduction")
1580 #undef GETSETNAME
1581 { 0 }
1582 };
1583
1584 static const PyMethodDef mpbarrett_pymethods[] = {
1585 #define METHNAME(name) mbmeth_##name
1586 METH (reduce, "B.reduce(X) -> X mod B.m")
1587 METH (exp, "B.exp(X, N) -> X^N mod B.m")
1588 METH (mexp, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1589 "X0^N0 X1^N1 ... mod B.m\n"
1590 "\t(the list may be flattened if this more convenient.)")
1591 #undef METHNAME
1592 { 0 }
1593 };
1594
1595 static const PyTypeObject mpbarrett_pytype_skel = {
1596 PyVarObject_HEAD_INIT(0, 0) /* Header */
1597 "MPBarrett", /* @tp_name@ */
1598 sizeof(mpbarrett_pyobj), /* @tp_basicsize@ */
1599 0, /* @tp_itemsize@ */
1600
1601 mpbarrett_pydealloc, /* @tp_dealloc@ */
1602 0, /* @tp_print@ */
1603 0, /* @tp_getattr@ */
1604 0, /* @tp_setattr@ */
1605 0, /* @tp_compare@ */
1606 0, /* @tp_repr@ */
1607 0, /* @tp_as_number@ */
1608 0, /* @tp_as_sequence@ */
1609 0, /* @tp_as_mapping@ */
1610 0, /* @tp_hash@ */
1611 0, /* @tp_call@ */
1612 0, /* @tp_str@ */
1613 0, /* @tp_getattro@ */
1614 0, /* @tp_setattro@ */
1615 0, /* @tp_as_buffer@ */
1616 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1617 Py_TPFLAGS_BASETYPE,
1618
1619 /* @tp_doc@ */
1620 "MPBarrett(N): a Barrett reduction context.",
1621
1622 0, /* @tp_traverse@ */
1623 0, /* @tp_clear@ */
1624 0, /* @tp_richcompare@ */
1625 0, /* @tp_weaklistoffset@ */
1626 0, /* @tp_iter@ */
1627 0, /* @tp_iternext@ */
1628 PYMETHODS(mpbarrett), /* @tp_methods@ */
1629 0, /* @tp_members@ */
1630 PYGETSET(mpbarrett), /* @tp_getset@ */
1631 0, /* @tp_base@ */
1632 0, /* @tp_dict@ */
1633 0, /* @tp_descr_get@ */
1634 0, /* @tp_descr_set@ */
1635 0, /* @tp_dictoffset@ */
1636 0, /* @tp_init@ */
1637 PyType_GenericAlloc, /* @tp_alloc@ */
1638 mpbarrett_pynew, /* @tp_new@ */
1639 0, /* @tp_free@ */
1640 0 /* @tp_is_gc@ */
1641 };
1642
1643 /*----- Nice prime reduction ----------------------------------------------*/
1644
1645 static PyTypeObject *mpreduce_pytype;
1646
1647 typedef struct mpreduce_pyobj {
1648 PyObject_HEAD
1649 mpreduce mr;
1650 } mpreduce_pyobj;
1651
1652 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1653
1654 static PyObject *mrmeth_exp(PyObject *me, PyObject *arg)
1655 {
1656 PyObject *rc = 0;
1657 mp *yy = 0, *zz = 0;
1658
1659 if (!PyArg_ParseTuple(arg, "O&O&:exp", convmp, &yy, convmp, &zz))
1660 goto end;
1661 if (MP_NEGP(zz)) {
1662 if ((yy = mp_modinv_checked(yy, yy, MPREDUCE_PY(me)->p)) == 0) goto end;
1663 zz = mp_neg(zz, zz);
1664 }
1665 rc = mp_pywrap(mpreduce_exp(MPREDUCE_PY(me), MP_NEW, yy, zz));
1666 end:
1667 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1668 return (rc);
1669 }
1670
1671 static PyObject *mrmeth_reduce(PyObject *me, PyObject *arg)
1672 {
1673 PyObject *z = 0;
1674 mp *yy = 0;
1675
1676 if (!PyArg_ParseTuple(arg, "O&:reduce", convmp, &yy)) goto end;
1677 z = mp_pywrap(mpreduce_do(MPREDUCE_PY(me), MP_NEW, yy));
1678 end:
1679 return (z);
1680 }
1681
1682 static void mpreduce_pydealloc(PyObject *me)
1683 {
1684 mpreduce_destroy(MPREDUCE_PY(me));
1685 FREEOBJ(me);
1686 }
1687
1688 static PyObject *mpreduce_pynew(PyTypeObject *ty,
1689 PyObject *arg, PyObject *kw)
1690 {
1691 mpreduce_pyobj *mr = 0;
1692 mpreduce r;
1693 static const char *const kwlist[] = { "m", 0 };
1694 mp *xx = 0;
1695
1696 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
1697 goto end;
1698 if (!MP_POSP(xx)) VALERR("m must be positive");
1699 if (mpreduce_create(&r, xx)) VALERR("bad modulus (must be 2^k - ...)");
1700 mr = (mpreduce_pyobj *)ty->tp_alloc(ty, 0);
1701 mr->mr = r;
1702 end:
1703 if (xx) MP_DROP(xx);
1704 return ((PyObject *)mr);
1705 }
1706
1707 static PyObject *mrget_m(PyObject *me, void *hunoz)
1708 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me)->p))); }
1709
1710 static const PyGetSetDef mpreduce_pygetset[] = {
1711 #define GETSETNAME(op, name) mr##op##_##name
1712 GET (m, "R.m -> modulus for reduction")
1713 #undef GETSETNAME
1714 { 0 }
1715 };
1716
1717 static const const PyMethodDef mpreduce_pymethods[] = {
1718 #define METHNAME(name) mrmeth_##name
1719 METH (reduce, "R.reduce(X) -> X mod B.m")
1720 METH (exp, "R.exp(X, N) -> X^N mod B.m")
1721 #undef METHNAME
1722 { 0 }
1723 };
1724
1725 static const PyTypeObject mpreduce_pytype_skel = {
1726 PyVarObject_HEAD_INIT(0, 0) /* Header */
1727 "MPReduce", /* @tp_name@ */
1728 sizeof(mpreduce_pyobj), /* @tp_basicsize@ */
1729 0, /* @tp_itemsize@ */
1730
1731 mpreduce_pydealloc, /* @tp_dealloc@ */
1732 0, /* @tp_print@ */
1733 0, /* @tp_getattr@ */
1734 0, /* @tp_setattr@ */
1735 0, /* @tp_compare@ */
1736 0, /* @tp_repr@ */
1737 0, /* @tp_as_number@ */
1738 0, /* @tp_as_sequence@ */
1739 0, /* @tp_as_mapping@ */
1740 0, /* @tp_hash@ */
1741 0, /* @tp_call@ */
1742 0, /* @tp_str@ */
1743 0, /* @tp_getattro@ */
1744 0, /* @tp_setattro@ */
1745 0, /* @tp_as_buffer@ */
1746 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1747 Py_TPFLAGS_BASETYPE,
1748
1749 /* @tp_doc@ */
1750 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1751
1752 0, /* @tp_traverse@ */
1753 0, /* @tp_clear@ */
1754 0, /* @tp_richcompare@ */
1755 0, /* @tp_weaklistoffset@ */
1756 0, /* @tp_iter@ */
1757 0, /* @tp_iternext@ */
1758 PYMETHODS(mpreduce), /* @tp_methods@ */
1759 0, /* @tp_members@ */
1760 PYGETSET(mpreduce), /* @tp_getset@ */
1761 0, /* @tp_base@ */
1762 0, /* @tp_dict@ */
1763 0, /* @tp_descr_get@ */
1764 0, /* @tp_descr_set@ */
1765 0, /* @tp_dictoffset@ */
1766 0, /* @tp_init@ */
1767 PyType_GenericAlloc, /* @tp_alloc@ */
1768 mpreduce_pynew, /* @tp_new@ */
1769 0, /* @tp_free@ */
1770 0 /* @tp_is_gc@ */
1771 };
1772
1773 /*----- Chinese Remainder Theorem solution --------------------------------*/
1774
1775 static PyTypeObject *mpcrt_pytype;
1776
1777 typedef struct mpcrt_pyobj {
1778 PyObject_HEAD
1779 mpcrt c;
1780 } mpcrt_pyobj;
1781
1782 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1783
1784 static PyObject *mcmeth_solve(PyObject *me, PyObject *arg)
1785 {
1786 mpcrt *c = MPCRT_PY(me);
1787 PyObject *q = 0, *it, *x, *z = 0;
1788 mp *xx;
1789 mp **v = 0;
1790 Py_ssize_t i = 0, n = c->k;
1791
1792 if (PyTuple_GET_SIZE(arg) == n)
1793 q = arg;
1794 else if (!PyArg_ParseTuple(arg, "O:solve", &q))
1795 goto end;
1796 v = xmalloc(n*sizeof(*v));
1797 it = PyObject_GetIter(q); if (!it) goto end;
1798 while (i < n) {
1799 x = PyIter_Next(it);
1800 if (!x) {
1801 if (PyErr_Occurred()) goto end;
1802 VALERR("residue count mismatch");
1803 }
1804 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
1805 v[i++] = xx; xx = 0;
1806 }
1807 x = PyIter_Next(it);
1808 if (x) { Py_DECREF(x); VALERR("residue count mismatch"); }
1809 else if (PyErr_Occurred()) goto end;
1810 z = mp_pywrap(mpcrt_solve(c, MP_NEW, v));
1811 end:
1812 if (v) {
1813 while (i--) MP_DROP(v[i]);
1814 xfree(v);
1815 }
1816 return (z);
1817 }
1818
1819 static void mpcrt_pydealloc(PyObject *me)
1820 {
1821 mpcrt *c = MPCRT_PY(me);
1822 mpcrt_destroy(c);
1823 xfree(c->v);
1824 }
1825
1826 static PyObject *mpcrt_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1827 {
1828 mpcrt_mod *v = 0;
1829 Py_ssize_t n, i = 0, j;
1830 static const char *const kwlist[] = { "mv", 0 };
1831 PyObject *q, *it = 0, *x;
1832 mp *xx = MP_NEW, *y = MP_NEW, *g = MP_NEW;
1833 mpmul mm;
1834 mpcrt_pyobj *c = 0;
1835
1836 if (PyTuple_GET_SIZE(arg) > 1)
1837 q = arg;
1838 else if (!PyArg_ParseTupleAndKeywords(arg, kw, "O:new", KWLIST, &q))
1839 goto end;
1840
1841 if (!PySequence_Check(q))
1842 n = 16;
1843 else {
1844 n = PySequence_Size(arg);
1845 if (n == (size_t)-1 && PyErr_Occurred()) goto end;
1846 }
1847
1848 v = xmalloc(n*sizeof(*v));
1849 it = PyObject_GetIter(q); if (!it) goto end;
1850 for (;;) {
1851 x = PyIter_Next(it); if (!x) break;
1852 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
1853 if (MP_CMP(xx, <=, MP_ZERO)) VALERR("moduli must be positive");
1854 if (i >= n) { n *= 2; v = xrealloc(v, n*sizeof(*v), i*sizeof(*v)); }
1855 v[i].m = xx; v[i].n = 0; v[i].ni = 0; v[i].nni = 0; i++; xx = MP_NEW;
1856 }
1857 if (PyErr_Occurred()) goto end;
1858 Py_DECREF(it); it = 0;
1859
1860 mpmul_init(&mm);
1861 for (j = 0; j < i; j++) mpmul_add(&mm, v[j].m);
1862 xx = mpmul_done(&mm);
1863 for (j = 0; j < i; j++) {
1864 mp_div(&y, 0, xx, v[j].m);
1865 mp_gcd(&g, 0, 0, y, v[j].m);
1866 if (!MP_EQ(g, MP_ONE)) VALERR("moduli must be pairwise coprime");
1867 }
1868
1869 c = (mpcrt_pyobj *)ty->tp_alloc(ty, 0);
1870 mpcrt_create(&c->c, v, i, 0);
1871 mp_drop(xx); mp_drop(y); mp_drop(g);
1872 return ((PyObject *)c);
1873
1874 end:
1875 if (v) {
1876 while (i--) MP_DROP(v[i].m);
1877 xfree(v);
1878 }
1879 mp_drop(xx); mp_drop(y); mp_drop(g);
1880 Py_XDECREF(it);
1881 return (0);
1882 }
1883
1884 static PyObject *mcget_product(PyObject *me, void *hunoz)
1885 { return (mp_pywrap(MP_COPY(MPCRT_PY(me)->mb.m))); }
1886
1887 static PyObject *mcget_moduli(PyObject *me, void *hunoz)
1888 {
1889 int i;
1890 PyObject *q;
1891 mpcrt *c = MPCRT_PY(me);
1892
1893 if ((q = PyList_New(c->k)) == 0) return (0);
1894 for (i = 0; i < c->k; i++)
1895 PyList_SET_ITEM(q, i, mp_pywrap(c->v[i].m));
1896 return (q);
1897 }
1898
1899 static const PyGetSetDef mpcrt_pygetset[] = {
1900 #define GETSETNAME(op, name) mc##op##_##name
1901 GET (product, "C.product -> product of moduli")
1902 GET (moduli, "C.moduli -> list of individual moduli")
1903 #undef GETSETNAME
1904 { 0 }
1905 };
1906
1907 static const PyMethodDef mpcrt_pymethods[] = {
1908 #define METHNAME(name) mcmeth_##name
1909 METH (solve, "C.solve([R0, R1]) -> X mod C.product")
1910 #undef METHNAME
1911 { 0 }
1912 };
1913
1914 static const PyTypeObject mpcrt_pytype_skel = {
1915 PyVarObject_HEAD_INIT(0, 0) /* Header */
1916 "MPCRT", /* @tp_name@ */
1917 sizeof(mpcrt_pyobj), /* @tp_basicsize@ */
1918 0, /* @tp_itemsize@ */
1919
1920 mpcrt_pydealloc, /* @tp_dealloc@ */
1921 0, /* @tp_print@ */
1922 0, /* @tp_getattr@ */
1923 0, /* @tp_setattr@ */
1924 0, /* @tp_compare@ */
1925 0, /* @tp_repr@ */
1926 0, /* @tp_as_number@ */
1927 0, /* @tp_as_sequence@ */
1928 0, /* @tp_as_mapping@ */
1929 0, /* @tp_hash@ */
1930 0, /* @tp_call@ */
1931 0, /* @tp_str@ */
1932 0, /* @tp_getattro@ */
1933 0, /* @tp_setattro@ */
1934 0, /* @tp_as_buffer@ */
1935 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1936 Py_TPFLAGS_BASETYPE,
1937
1938 /* @tp_doc@ */
1939 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1940
1941 0, /* @tp_traverse@ */
1942 0, /* @tp_clear@ */
1943 0, /* @tp_richcompare@ */
1944 0, /* @tp_weaklistoffset@ */
1945 0, /* @tp_iter@ */
1946 0, /* @tp_iternext@ */
1947 PYMETHODS(mpcrt), /* @tp_methods@ */
1948 0, /* @tp_members@ */
1949 PYGETSET(mpcrt), /* @tp_getset@ */
1950 0, /* @tp_base@ */
1951 0, /* @tp_dict@ */
1952 0, /* @tp_descr_get@ */
1953 0, /* @tp_descr_set@ */
1954 0, /* @tp_dictoffset@ */
1955 0, /* @tp_init@ */
1956 PyType_GenericAlloc, /* @tp_alloc@ */
1957 mpcrt_pynew, /* @tp_new@ */
1958 0, /* @tp_free@ */
1959 0 /* @tp_is_gc@ */
1960 };
1961
1962 /*----- Binary polynomials ------------------------------------------------*/
1963
1964 static PyObject *gf_pyrepr(PyObject *o)
1965 { return mp_topystring(MP_X(o), 16, "GF(", "0x", ")"); }
1966
1967 static PyObject *gf_pyrichcompare(PyObject *x, PyObject *y, int op)
1968 {
1969 mp *xx, *yy;
1970 int xl, yl;
1971 int b;
1972
1973 if (gfbinop(x, y, &xx, &yy)) RETURN_NOTIMPL;
1974 switch (op) {
1975 case Py_EQ: b = MP_EQ(xx, yy); break;
1976 case Py_NE: b = !MP_EQ(xx, yy); break;
1977 default:
1978 xl = mp_bits(xx);
1979 yl = mp_bits(yy);
1980 switch (op) {
1981 case Py_LT: b = xl < yl; break;
1982 case Py_LE: b = xl <= yl; break;
1983 case Py_GT: b = xl > yl; break;
1984 case Py_GE: b = xl >= yl; break;
1985 default: abort();
1986 }
1987 break;
1988 }
1989 MP_DROP(xx); MP_DROP(yy);
1990 return (getbool(b));
1991 }
1992
1993 static PyObject *gf_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1994 {
1995 PyObject *x;
1996 mp *z;
1997 mp_pyobj *zz = 0;
1998 int radix = 0;
1999 static const char *const kwlist[] = { "x", "radix", 0 };
2000
2001 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|i:gf", KWLIST, &x, &radix))
2002 goto end;
2003 if (GF_PYCHECK(x)) RETURN_OBJ(x);
2004 if (!good_radix_p(radix, 1)) VALERR("radix out of range");
2005 if ((z = mp_frompyobject(x, radix)) == 0) {
2006 PyErr_Format(PyExc_TypeError, "can't convert %.100s to gf",
2007 Py_TYPE(x)->tp_name);
2008 goto end;
2009 }
2010 if (MP_NEGP(z)) {
2011 MP_DROP(z);
2012 VALERR("gf cannot be negative");
2013 }
2014 zz = (mp_pyobj *)ty->tp_alloc(ty, 0);
2015 zz->x = z;
2016 end:
2017 return ((PyObject *)zz);
2018 }
2019
2020 static PyObject *gf_pyexp(PyObject *x, PyObject *y, PyObject *z)
2021 {
2022 mp *xx = 0, *yy = 0, *zz = 0;
2023 mp *r = 0;
2024 PyObject *rc = 0;
2025
2026 if ((xx = implicitgf(x)) == 0 || (yy = implicitmp(y)) == 0 ||
2027 (z && z != Py_None && (zz = implicitgf(z)) == 0)) {
2028 mp_drop(xx); mp_drop(yy); mp_drop(zz);
2029 RETURN_NOTIMPL;
2030 }
2031 if (!z || z == Py_None) {
2032 if (MP_NEGP(yy)) VALERR("negative exponent");
2033 r = gf_exp(MP_NEW, xx, yy);
2034 } else {
2035 gfreduce gr;
2036 if (MP_ZEROP(zz)) ZDIVERR("zero modulus");
2037 if (MP_NEGP(yy)) {
2038 if ((xx = gf_modinv_checked(xx, xx, zz)) == 0) goto end;
2039 yy = mp_neg(yy, yy);
2040 }
2041 gfreduce_create(&gr, zz);
2042 r = gfreduce_exp(&gr, MP_NEW, xx, yy);
2043 gfreduce_destroy(&gr);
2044 }
2045 rc = gf_pywrap(r);
2046 end:
2047 mp_drop(xx); mp_drop(yy); mp_drop(zz);
2048 return (rc);
2049 }
2050
2051 static PyObject *gfmeth_sqr(PyObject *me)
2052 { return (gf_pywrap(gf_sqr(MP_NEW, MP_X(me)))); }
2053
2054 static PyObject *gfmeth_gcd(PyObject *me, PyObject *arg)
2055 {
2056 PyObject *z = 0;
2057 mp *yy = 0, *zz = MP_NEW;
2058
2059 if (!PyArg_ParseTuple(arg, "O&:gcd", convgf, &yy)) goto end;
2060 gf_gcd(&zz, 0, 0, MP_X(me), yy);
2061 z = gf_pywrap(zz);
2062 end:
2063 if (yy) MP_DROP(yy);
2064 return (z);
2065 }
2066
2067 static PyObject *gfmeth_gcdx(PyObject *me, PyObject *arg)
2068 {
2069 PyObject *z = 0;
2070 mp *yy = 0, *zz = MP_NEW, *uu = MP_NEW, *vv = MP_NEW;
2071
2072 if (!PyArg_ParseTuple(arg, "O&:gcdx", convgf, &yy))
2073 goto end;
2074 gf_gcd(&zz, &uu, &vv, MP_X(me), yy);
2075 z = Py_BuildValue("(NNN)",
2076 gf_pywrap(zz), gf_pywrap(uu), gf_pywrap(vv));
2077 end:
2078 if (yy) MP_DROP(yy);
2079 return (z);
2080 }
2081
2082 static PyObject *gfmeth_modinv(PyObject *me, PyObject *arg)
2083 {
2084 PyObject *z = 0;
2085 mp *yy = 0, *zz = MP_NEW;
2086
2087 if (!PyArg_ParseTuple(arg, "O&:modinv", convgf, &yy) ||
2088 (zz = gf_modinv_checked(MP_NEW, yy, MP_X(me))) == 0)
2089 goto end;
2090 z = gf_pywrap(zz);
2091 end:
2092 if (yy) MP_DROP(yy);
2093 return (z);
2094 }
2095
2096 static PyObject *gfmeth_fromstring(PyObject *me,
2097 PyObject *arg, PyObject *kw)
2098 {
2099 int r = 0;
2100 char *p;
2101 Py_ssize_t len;
2102 PyObject *z = 0;
2103 mp *zz;
2104 mptext_stringctx sc;
2105 static const char *const kwlist[] = { "x", "radix", 0 };
2106
2107 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
2108 &p, &len, &r))
2109 goto end;
2110 if (!good_radix_p(r, 1)) VALERR("bad radix");
2111 sc.buf = p; sc.lim = p + len;
2112 if ((zz = mp_read(MP_NEW, r, &mptext_stringops, &sc)) == 0 ||
2113 MP_NEGP(zz)) {
2114 if (zz) MP_DROP(zz);
2115 VALERR("bad binary polynomial");
2116 }
2117 z = Py_BuildValue("(Ns#)", gf_pywrap(zz),
2118 sc.buf, (Py_ssize_t)(sc.lim - sc.buf));
2119 end:
2120 return (z);
2121 }
2122
2123 static PyObject *gfmeth_irreduciblep(PyObject *me)
2124 { return getbool(gf_irreduciblep(MP_X(me))); }
2125
2126 static PyObject *gfget_degree(PyObject *me, void *hunoz)
2127 { return (PyInt_FromLong(mp_bits(MP_X(me)) - 1)); }
2128
2129 static const PyGetSetDef gf_pygetset[] = {
2130 #define GETSETNAME(op, name) gf##op##_##name
2131 GET (degree, "X.degree -> polynomial degree of X")
2132 #undef GETSETNAME
2133 #define GETSETNAME(op, name) mp##op##_##name
2134 GET (nbits, "X.nbits -> bit length of X")
2135 GET (noctets, "X.noctets -> octet length of X")
2136 #undef GETSETNAME
2137 { 0 }
2138 };
2139
2140 static const PyMethodDef gf_pymethods[] = {
2141 #define METHNAME(func) gfmeth_##func
2142 METH (setbit, "X.setbit(N) -> X with bit N set")
2143 METH (clearbit, "X.clearbit(N) -> X with bit N clear")
2144 METH (testbit, "X.testbit(N) -> true/false if bit N set/clear in X")
2145 NAMETH(sqr, "X.sqr() -> X^2")
2146 METH (gcd, "X.gcd(Y) -> gcd(X, Y)")
2147 METH (gcdx, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2148 METH (modinv, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2149 NAMETH(irreduciblep, "X.irreduciblep() -> true/false")
2150 KWSMTH(fromstring, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2151 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2152 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2153 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2154 SMTH (_implicit, 0)
2155 SMTH (loadl, "loadl(STR) -> X: read little-endian bytes")
2156 SMTH (loadb, "loadb(STR) -> X: read big-endian bytes")
2157 SMTH (frombuf, "frombuf(STR) -> (X, REST): read buffer format")
2158 #undef METHNAME
2159 #define METHNAME(func) mpmeth_##func
2160 KWMETH(tostring, "X.tostring([radix = 10]) -> STR")
2161 KWMETH(storel, "X.storel([len = -1]) -> little-endian bytes")
2162 KWMETH(storeb, "X.storeb([len = -1]) -> big-endian bytes")
2163 KWMETH(storel2c, "X.storel2c([len = -1]) -> "
2164 "little-endian bytes, two's complement")
2165 KWMETH(storeb2c, "X.storeb2c([len = -1]) -> "
2166 "big-endian bytes, two's complement")
2167 NAMETH(tobuf, "X.tobuf() -> buffer format")
2168 #undef METHNAME
2169 { 0 }
2170 };
2171
2172 static const PyNumberMethods gf_pynumber = {
2173 gf_pyadd, /* @nb_add@ */
2174 gf_pysub, /* @nb_subtract@ */
2175 gf_pymul, /* @nb_multiply@ */
2176 #ifdef PY2
2177 0, /* @nb_divide@ */
2178 #endif
2179 gf_pymod, /* @nb_remainder@ */
2180 gf_pydivmod, /* @nb_divmod@ */
2181 gf_pyexp, /* @nb_power@ */
2182 mp_pyid, /* @nb_negative@ */
2183 mp_pyid, /* @nb_positive@ */
2184 mp_pyid, /* @nb_absolute@ */
2185 mp_pynonzerop, /* @nb_nonzero@ */
2186 0 /* doesn't make any sense */, /* @nb_invert@ */
2187 gf_pylsl, /* @nb_lshift@ */
2188 gf_pylsr, /* @nb_rshift@ */
2189 gf_pyand, /* @nb_and@ */
2190 gf_pyxor, /* @nb_xor@ */
2191 gf_pyor, /* @nb_or@ */
2192 #ifdef PY2
2193 gf_pycoerce, /* @nb_coerce@ */
2194 #endif
2195 mp_pyint, /* @nb_int@ */
2196 PY23(mp_pylong, 0), /* @nb_long@ */
2197 0 /* doesn't make any sense */, /* @nb_float@ */
2198 #ifdef PY2
2199 mp_pyoct, /* @nb_oct@ */
2200 mp_pyhex, /* @nb_hex@ */
2201 #endif
2202
2203 0, /* @nb_inplace_add@ */
2204 0, /* @nb_inplace_subtract@ */
2205 0, /* @nb_inplace_multiply@ */
2206 #ifdef PY2
2207 0, /* @nb_inplace_divide@ */
2208 #endif
2209 0, /* @nb_inplace_remainder@ */
2210 0, /* @nb_inplace_power@ */
2211 0, /* @nb_inplace_lshift@ */
2212 0, /* @nb_inplace_rshift@ */
2213 0, /* @nb_inplace_and@ */
2214 0, /* @nb_inplace_xor@ */
2215 0, /* @nb_inplace_or@ */
2216
2217 gf_pydiv, /* @nb_floor_divide@ */
2218 0, /* @nb_true_divide@ */
2219 0, /* @nb_inplace_floor_divide@ */
2220 0, /* @nb_inplace_true_divide@ */
2221
2222 mp_pyint, /* @nb_index@ */
2223 };
2224
2225 static const PyTypeObject gf_pytype_skel = {
2226 PyVarObject_HEAD_INIT(0, 0) /* Header */
2227 "GF", /* @tp_name@ */
2228 sizeof(mp_pyobj), /* @tp_basicsize@ */
2229 0, /* @tp_itemsize@ */
2230
2231 mp_pydealloc, /* @tp_dealloc@ */
2232 0, /* @tp_print@ */
2233 0, /* @tp_getattr@ */
2234 0, /* @tp_setattr@ */
2235 0, /* @tp_compare@ */
2236 gf_pyrepr, /* @tp_repr@ */
2237 PYNUMBER(gf), /* @tp_as_number@ */
2238 0, /* @tp_as_sequence@ */
2239 0, /* @tp_as_mapping@ */
2240 mp_pyhash, /* @tp_hash@ */
2241 0, /* @tp_call@ */
2242 mp_pyhex, /* @tp_str@ */
2243 0, /* @tp_getattro@ */
2244 0, /* @tp_setattro@ */
2245 0, /* @tp_as_buffer@ */
2246 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2247 Py_TPFLAGS_CHECKTYPES |
2248 Py_TPFLAGS_BASETYPE,
2249
2250 /* @tp_doc@ */
2251 "Binary polynomials. Support almost all the standard arithmetic\n"
2252 "operations.\n"
2253 "\n"
2254 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2255 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2256 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2257 PY23(
2258 "points, group elements, Python `int' and `long' objects, and anything\n"
2259 "with an integer conversion.\n",
2260 "points, group elements, Python `int' objects, and anything with an\n"
2261 "integer conversion.\n")
2262 "\n"
2263 "The name is hopelessly wrong from a technical point of view, but\n"
2264 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2265 "\n"
2266 "Notes:\n"
2267 "\n"
2268 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2269
2270 0, /* @tp_traverse@ */
2271 0, /* @tp_clear@ */
2272 gf_pyrichcompare, /* @tp_richcompare@ */
2273 0, /* @tp_weaklistoffset@ */
2274 0, /* @tp_iter@ */
2275 0, /* @tp_iternext@ */
2276 PYMETHODS(gf), /* @tp_methods@ */
2277 0, /* @tp_members@ */
2278 PYGETSET(gf), /* @tp_getset@ */
2279 0, /* @tp_base@ */
2280 0, /* @tp_dict@ */
2281 0, /* @tp_descr_get@ */
2282 0, /* @tp_descr_set@ */
2283 0, /* @tp_dictoffset@ */
2284 0, /* @tp_init@ */
2285 PyType_GenericAlloc, /* @tp_alloc@ */
2286 gf_pynew, /* @tp_new@ */
2287 0, /* @tp_free@ */
2288 0 /* @tp_is_gc@ */
2289 };
2290
2291 /*----- Sparse poly reduction ---------------------------------------------*/
2292
2293 static PyTypeObject *gfreduce_pytype;
2294
2295 typedef struct gfreduce_pyobj {
2296 PyObject_HEAD
2297 gfreduce mr;
2298 } gfreduce_pyobj;
2299
2300 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2301
2302 static PyObject *grmeth_exp(PyObject *me, PyObject *arg)
2303 {
2304 PyObject *rc = 0;
2305 mp *yy = 0, *zz = 0;
2306
2307 if (!PyArg_ParseTuple(arg, "O&O&:exp", convgf, &yy, convgf, &zz))
2308 goto end;
2309 if (MP_NEGP(zz)) {
2310 if ((yy = gf_modinv_checked(yy, yy, GFREDUCE_PY(me)->p)) == 0) goto end;
2311 zz = mp_neg(zz, zz);
2312 }
2313 rc = gf_pywrap(gfreduce_exp(GFREDUCE_PY(me), MP_NEW, yy, zz));
2314 end:
2315 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
2316 return (rc);
2317 }
2318
2319 static PyObject *grmeth_trace(PyObject *me, PyObject *arg)
2320 {
2321 PyObject *rc = 0;
2322 mp *xx = 0;
2323
2324 if (!PyArg_ParseTuple(arg, "O&:trace", convgf, &xx)) goto end;
2325 rc = PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me), xx));
2326 end:
2327 if (xx) MP_DROP(xx);
2328 return (rc);
2329 }
2330
2331 static PyObject *grmeth_halftrace(PyObject *me, PyObject *arg)
2332 {
2333 PyObject *rc = 0;
2334 mp *xx = 0;
2335
2336 if (!PyArg_ParseTuple(arg, "O&:halftrace", convgf, &xx)) goto end;
2337 rc = gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me), MP_NEW, xx));
2338 end:
2339 if (xx) MP_DROP(xx);
2340 return (rc);
2341 }
2342
2343 static PyObject *grmeth_sqrt(PyObject *me, PyObject *arg)
2344 {
2345 PyObject *rc = 0;
2346 mp *xx = 0, *yy;
2347
2348 if (!PyArg_ParseTuple(arg, "O&:sqrt", convgf, &xx)) goto end;
2349 if ((yy = gfreduce_sqrt(GFREDUCE_PY(me), MP_NEW, xx)) == 0)
2350 VALERR("no modular square root");
2351 rc = gf_pywrap(yy);
2352 end:
2353 if (xx) MP_DROP(xx);
2354 return (rc);
2355 }
2356
2357 static PyObject *grmeth_quadsolve(PyObject *me, PyObject *arg)
2358 {
2359 PyObject *rc = 0;
2360 mp *xx = 0, *yy;
2361
2362 if (!PyArg_ParseTuple(arg, "O&:quadsolve", convgf, &xx)) goto end;
2363 if ((yy = gfreduce_quadsolve(GFREDUCE_PY(me), MP_NEW, xx)) == 0)
2364 VALERR("no solution found");
2365 rc = gf_pywrap(yy);
2366 end:
2367 if (xx) MP_DROP(xx);
2368 return (rc);
2369 }
2370
2371 static PyObject *grmeth_reduce(PyObject *me, PyObject *arg)
2372 {
2373 PyObject *z = 0;
2374 mp *yy = 0;
2375
2376 if (!PyArg_ParseTuple(arg, "O&:reduce", convgf, &yy)) goto end;
2377 z = gf_pywrap(gfreduce_do(GFREDUCE_PY(me), MP_NEW, yy));
2378 end:
2379 return (z);
2380 }
2381
2382 static void gfreduce_pydealloc(PyObject *me)
2383 {
2384 gfreduce_destroy(GFREDUCE_PY(me));
2385 FREEOBJ(me);
2386 }
2387
2388 static PyObject *gfreduce_pynew(PyTypeObject *ty,
2389 PyObject *arg, PyObject *kw)
2390 {
2391 gfreduce_pyobj *mr = 0;
2392 gfreduce r;
2393 static const char *const kwlist[] = { "m", 0 };
2394 mp *xx = 0;
2395
2396 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convgf, &xx))
2397 goto end;
2398 if (MP_ZEROP(xx)) ZDIVERR("modulus is zero!");
2399 gfreduce_create(&r, xx);
2400 mr = (gfreduce_pyobj *)ty->tp_alloc(ty, 0);
2401 mr->mr = r;
2402 end:
2403 if (xx) MP_DROP(xx);
2404 return ((PyObject *)mr);
2405 }
2406
2407 static PyObject *grget_m(PyObject *me, void *hunoz)
2408 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me)->p))); }
2409
2410 static const PyGetSetDef gfreduce_pygetset[] = {
2411 #define GETSETNAME(op, name) gr##op##_##name
2412 GET (m, "R.m -> reduction polynomial")
2413 #undef GETSETNAME
2414 { 0 }
2415 };
2416
2417 static const PyMethodDef gfreduce_pymethods[] = {
2418 #define METHNAME(name) grmeth_##name
2419 METH (reduce, "R.reduce(X) -> X mod B.m")
2420 METH (trace, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2421 METH (halftrace, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2422 METH (sqrt, "R.sqrt(X) -> Y where Y^2 = X mod R")
2423 METH (quadsolve, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2424 METH (exp, "R.exp(X, N) -> X^N mod B.m")
2425 #undef METHNAME
2426 { 0 }
2427 };
2428
2429 static const PyTypeObject gfreduce_pytype_skel = {
2430 PyVarObject_HEAD_INIT(0, 0) /* Header */
2431 "GFReduce", /* @tp_name@ */
2432 sizeof(gfreduce_pyobj), /* @tp_basicsize@ */
2433 0, /* @tp_itemsize@ */
2434
2435 gfreduce_pydealloc, /* @tp_dealloc@ */
2436 0, /* @tp_print@ */
2437 0, /* @tp_getattr@ */
2438 0, /* @tp_setattr@ */
2439 0, /* @tp_compare@ */
2440 0, /* @tp_repr@ */
2441 0, /* @tp_as_number@ */
2442 0, /* @tp_as_sequence@ */
2443 0, /* @tp_as_mapping@ */
2444 0, /* @tp_hash@ */
2445 0, /* @tp_call@ */
2446 0, /* @tp_str@ */
2447 0, /* @tp_getattro@ */
2448 0, /* @tp_setattro@ */
2449 0, /* @tp_as_buffer@ */
2450 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2451 Py_TPFLAGS_BASETYPE,
2452
2453 /* @tp_doc@ */
2454 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2455
2456 0, /* @tp_traverse@ */
2457 0, /* @tp_clear@ */
2458 0, /* @tp_richcompare@ */
2459 0, /* @tp_weaklistoffset@ */
2460 0, /* @tp_iter@ */
2461 0, /* @tp_iternext@ */
2462 PYMETHODS(gfreduce), /* @tp_methods@ */
2463 0, /* @tp_members@ */
2464 PYGETSET(gfreduce), /* @tp_getset@ */
2465 0, /* @tp_base@ */
2466 0, /* @tp_dict@ */
2467 0, /* @tp_descr_get@ */
2468 0, /* @tp_descr_set@ */
2469 0, /* @tp_dictoffset@ */
2470 0, /* @tp_init@ */
2471 PyType_GenericAlloc, /* @tp_alloc@ */
2472 gfreduce_pynew, /* @tp_new@ */
2473 0, /* @tp_free@ */
2474 0 /* @tp_is_gc@ */
2475 };
2476
2477 /*----- Normal/poly transformation ----------------------------------------*/
2478
2479 static PyTypeObject *gfn_pytype;
2480
2481 typedef struct gfn_pyobj {
2482 PyObject_HEAD
2483 mp *p;
2484 gfn ntop, pton;
2485 } gfn_pyobj;
2486
2487 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2488 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2489 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2490
2491 static PyObject *gfn_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
2492 {
2493 mp *p = 0, *beta = 0;
2494 gfn_pyobj *gg = 0;
2495 static const char *const kwlist[] = { "p", "beta", 0 };
2496
2497 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&:new", KWLIST,
2498 convgf, &p, convgf, &beta))
2499 goto end;
2500 gg = PyObject_New(gfn_pyobj, ty);
2501 gg->p = 0;
2502 if (gfn_create(p, beta, &gg->ntop, &gg->pton)) {
2503 Py_DECREF(gg);
2504 gg = 0;
2505 VALERR("can't invert transformation matrix");
2506 }
2507 gg->p = MP_COPY(p);
2508 end:
2509 mp_drop(p);
2510 mp_drop(beta);
2511 return ((PyObject *)gg);
2512 }
2513
2514 static PyObject *gfnget_p(PyObject *me, void *hunoz)
2515 { return (gf_pywrap(MP_COPY(GFN_P(me)))); }
2516
2517 static PyObject *gfnget_beta(PyObject *me, void *hunoz)
2518 {
2519 gfn *n = GFN_NTOP(me);
2520 mp *x = n->r[n->n - 1];
2521 return (gf_pywrap(MP_COPY(x)));
2522 }
2523
2524 #define XFORMOP(name, NAME) \
2525 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2526 { \
2527 mp *xx = 0; \
2528 mp *z = 0; \
2529 \
2530 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2531 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2532 end: \
2533 mp_drop(xx); \
2534 if (!z) return (0); \
2535 return (gf_pywrap(z)); \
2536 }
2537 XFORMOP(pton, PTON)
2538 XFORMOP(ntop, NTOP)
2539 #undef XFORMOP
2540
2541 static void gfn_pydealloc(PyObject *me)
2542 {
2543 if (GFN_P(me)) {
2544 MP_DROP(GFN_P(me));
2545 gfn_destroy(GFN_PTON(me));
2546 gfn_destroy(GFN_NTOP(me));
2547 }
2548 FREEOBJ(me);
2549 }
2550
2551 static const PyGetSetDef gfn_pygetset[] = {
2552 #define GETSETNAME(op, name) gfn##op##_##name
2553 GET (p, "X.p -> polynomial basis, as polynomial")
2554 GET (beta, "X.beta -> normal basis element, in poly form")
2555 #undef GETSETNAME
2556 { 0 }
2557 };
2558
2559 static const PyMethodDef gfn_pymethods[] = {
2560 #define METHNAME(name) gfnmeth_##name
2561 METH (pton, "X.pton(A) -> normal-basis representation of A")
2562 METH (ntop, "X.ntop(A) -> polynomial-basis representation of A")
2563 #undef METHNAME
2564 { 0 }
2565 };
2566
2567 static const PyTypeObject gfn_pytype_skel = {
2568 PyVarObject_HEAD_INIT(0, 0) /* Header */
2569 "GFN", /* @tp_name@ */
2570 sizeof(gfn_pyobj), /* @tp_basicsize@ */
2571 0, /* @tp_itemsize@ */
2572
2573 gfn_pydealloc, /* @tp_dealloc@ */
2574 0, /* @tp_print@ */
2575 0, /* @tp_getattr@ */
2576 0, /* @tp_setattr@ */
2577 0, /* @tp_compare@ */
2578 0, /* @tp_repr@ */
2579 0, /* @tp_as_number@ */
2580 0, /* @tp_as_sequence@ */
2581 0, /* @tp_as_mapping@ */
2582 0, /* @tp_hash@ */
2583 0, /* @tp_call@ */
2584 0, /* @tp_str@ */
2585 0, /* @tp_getattro@ */
2586 0, /* @tp_setattro@ */
2587 0, /* @tp_as_buffer@ */
2588 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2589 Py_TPFLAGS_BASETYPE,
2590
2591 /* @tp_doc@ */
2592 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2593 " between polynomial and normal basis representations.",
2594
2595 0, /* @tp_traverse@ */
2596 0, /* @tp_clear@ */
2597 0, /* @tp_richcompare@ */
2598 0, /* @tp_weaklistoffset@ */
2599 0, /* @tp_iter@ */
2600 0, /* @tp_iternext@ */
2601 PYMETHODS(gfn), /* @tp_methods@ */
2602 0, /* @tp_members@ */
2603 PYGETSET(gfn), /* @tp_getset@ */
2604 0, /* @tp_base@ */
2605 0, /* @tp_dict@ */
2606 0, /* @tp_descr_get@ */
2607 0, /* @tp_descr_set@ */
2608 0, /* @tp_dictoffset@ */
2609 0, /* @tp_init@ */
2610 PyType_GenericAlloc, /* @tp_alloc@ */
2611 gfn_pynew, /* @tp_new@ */
2612 0, /* @tp_free@ */
2613 0 /* @tp_is_gc@ */
2614 };
2615
2616 /*----- Glue --------------------------------------------------------------*/
2617
2618 static const struct nameval consts[] = {
2619 CONST(MPW_MAX),
2620 { 0 }
2621 };
2622
2623 void mp_pyinit(void)
2624 {
2625 INITTYPE(mp, root);
2626 INITTYPE(gf, root);
2627 INITTYPE(mpmul, root);
2628 INITTYPE(mpmont, root);
2629 INITTYPE(mpbarrett, root);
2630 INITTYPE(mpreduce, root);
2631 INITTYPE(mpcrt, root);
2632 INITTYPE(gfreduce, root);
2633 INITTYPE(gfn, root);
2634 }
2635
2636 void mp_pyinsert(PyObject *mod)
2637 {
2638 INSERT("MP", mp_pytype);
2639 INSERT("MPMul", mpmul_pytype);
2640 INSERT("MPMont", mpmont_pytype);
2641 INSERT("MPBarrett", mpbarrett_pytype);
2642 INSERT("MPReduce", mpreduce_pytype);
2643 INSERT("MPCRT", mpcrt_pytype);
2644 INSERT("GF", gf_pytype);
2645 INSERT("GFReduce", gfreduce_pytype);
2646 INSERT("GFN", gfn_pytype);
2647 setconstants(mod, consts);
2648 }
2649
2650 /*----- That's all, folks -------------------------------------------------*/