ec.c (ecptxl_1): Accept any iterable of coordinates.
[catacomb-python] / mp.c
CommitLineData
d7ab1bab 1/* -*-c-*-
2 *
d7ab1bab 3 * Multiprecision arithmetic
4 *
5 * (c) 2004 Straylight/Edgeware
6 */
7
b2687a0a 8/*----- Licensing notice --------------------------------------------------*
d7ab1bab 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.
b2687a0a 16 *
d7ab1bab 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.
b2687a0a 21 *
d7ab1bab 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
33PyTypeObject *mp_pytype = 0;
34PyTypeObject *gf_pytype = 0;
35
67ae8797
MW
36#ifndef PyLong_SHIFT
37# define PyLong_SHIFT SHIFT
38#endif
39
40#ifndef PyLong_MASK
41# define PyLong_MASK MASK
42#endif
43
44STATIC_ASSERT(MPW_BITS >= PyLong_SHIFT,
e2568047
MW
45 "Catacomb's limbs are now narrower than than Python's!");
46
f368b46e 47mp *mp_frompylong(PyObject *obj)
d7ab1bab 48{
49 unsigned long bits;
f368b46e 50 PyLongObject *l = (PyLongObject *)obj;
d7ab1bab 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
f7623015
MW
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
2a448f86 65 sz = Py_SIZE(l);
d7ab1bab 66 if (sz < 0) sz = -sz;
67ae8797 67 bits = (unsigned long)sz * PyLong_SHIFT;
d7ab1bab 68 w = (bits + MPW_BITS - 1)/MPW_BITS;
2a448f86 69 x = mp_new(w, Py_SIZE(l) < 0 ? MP_NEG : 0);
d7ab1bab 70 p = x->v;
71 for (i = 0; i < sz; i++) {
72 r |= (mpd)l->ob_digit[i] << b;
67ae8797 73 b += PyLong_SHIFT;
d7ab1bab 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
f368b46e 89PyObject *mp_topylong(mp *x)
d7ab1bab 90{
91 unsigned long bits = mp_bits(x);
67ae8797 92 int sz = (bits + PyLong_SHIFT - 1)/PyLong_SHIFT;
d7ab1bab 93 PyLongObject *l = _PyLong_New(sz);
94 mpd r = 0;
95 int b = 0;
96 mpw *p = x->v;
97 int i = 0;
98
d7ab1bab 99 while (i < sz && p < x->vl) {
f368b46e 100 r |= (mpd)*p++ << b;
d7ab1bab 101 b += MPW_BITS;
67ae8797
MW
102 while (i < sz && b >= PyLong_SHIFT) {
103 l->ob_digit[i++] = r & PyLong_MASK;
104 r >>= PyLong_SHIFT;
105 b -= PyLong_SHIFT;
d7ab1bab 106 }
107 }
108 while (i < sz && r) {
67ae8797
MW
109 l->ob_digit[i++] = r & PyLong_MASK;
110 r >>= PyLong_SHIFT;
d7ab1bab 111 }
2a448f86 112 Py_SIZE(l) = (x->f & MP_NEG) ? -sz : sz;
f368b46e 113 return ((PyObject *)l);
d7ab1bab 114}
115
116mp *mp_frompyobject(PyObject *o, int radix)
117{
118 mp *x;
119
2135a6d3 120 if (TEXT_CHECK(o)) {
d7ab1bab 121 mptext_stringctx sc;
122 mp *x;
2135a6d3
MW
123 size_t sz;
124 TEXT_PTRLEN(o, sc.buf, sz); sc.lim = sc.buf + sz;
08c09854
MW
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;
d7ab1bab 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 }
f368b46e
MW
136 if ((x = tomp(o)) != 0)
137 return (x);
d7ab1bab 138 return (0);
139}
140
141PyObject *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);
2135a6d3 152 TEXT_PREPAREWRITE(o, p, len + 1 + xprelen + prelen + postlen);
d7ab1bab 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);
2135a6d3 161 TEXT_DONEWRITE(o, sc.buf - p);
d7ab1bab 162 return (o);
163}
164
f368b46e
MW
165static 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
d7ab1bab 172PyObject *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
179PyObject *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
bc243788 186int mp_tolong_checked(mp *x, long *l, int must)
d7ab1bab 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 }
bc243788
MW
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 }
d7ab1bab 199 *l = mp_tolong(x);
200 rc = 0;
201end:
202 return (rc);
203}
204
0efbd2fc 205/*----- Arbitrary-precision integers --------------------------------------*/
d7ab1bab 206
207static void mp_pydealloc(PyObject *o)
208{
209 MP_DROP(MP_X(o));
3aa33042 210 FREEOBJ(o);
d7ab1bab 211}
212
213static PyObject *mp_pyrepr(PyObject *o)
e38168e2 214 { return mp_topystring(MP_X(o), 10, "MP(", 0, ")"); }
d7ab1bab 215
216static PyObject *mp_pystr(PyObject *o)
217 { return mp_topystring(MP_X(o), 10, 0, 0, 0); }
218
219mp *tomp(PyObject *o)
220{
221 PyObject *l;
222 mp *x;
223
77535854 224 if (!o || PyFloat_Check(o))
d7ab1bab 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;
46c13d77 234 if (EC_ATINF(ECPT_P(o))) return (0);
d7ab1bab 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);
6286102d 243 }
f7623015 244#ifdef PY2
6286102d 245 else if (PyInt_Check(o))
d7ab1bab 246 return (mp_fromlong(MP_NEW, PyInt_AS_LONG(o)));
f7623015 247#endif
d7ab1bab 248 else if ((l = PyNumber_Long(o)) != 0) {
f368b46e 249 x = mp_frompylong(l);
d7ab1bab 250 Py_DECREF(l);
251 return (x);
252 } else {
253 PyErr_Clear();
254 return (0);
255 }
256}
257
258mp *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",
2a448f86 264 Py_TYPE(o)->tp_name);
d7ab1bab 265 }
266 return (x);
267}
268
269int 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
277mp *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",
2a448f86 283 Py_TYPE(o)->tp_name);
d7ab1bab 284 }
285 return (x);
286}
287
288int 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
5b29dfaf 296mp *implicitmp(PyObject *o)
bf8910bd 297{
e7d2e2e2
MW
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);
bf8910bd
MW
313}
314
5b29dfaf 315mp *implicitgf(PyObject *o)
bf8910bd 316{
e7d2e2e2
MW
317 if (GF_PYCHECK(o)) return (MP_COPY(MP_X(o)));
318 return (0);
bf8910bd
MW
319}
320
d7ab1bab 321static int mpbinop(PyObject *x, PyObject *y, mp **xx, mp **yy)
322{
bf8910bd
MW
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
332static int gfbinop(PyObject *x, PyObject *y, mp **xx, mp **yy)
333{
334 if ((*xx = implicitgf(x)) == 0)
d7ab1bab 335 return (-1);
bf8910bd 336 if ((*yy = implicitgf(y)) == 0) {
d7ab1bab 337 MP_DROP(*xx);
338 return (-1);
339 }
340 return (0);
341}
342
77535854
MW
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 }
359FPBINOP(add, Add)
360FPBINOP(sub, Subtract)
361FPBINOP(mul, Multiply)
362
d7ab1bab 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; \
bf8910bd 369 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
d7ab1bab 370 zz = pre##_##name(MP_NEW, xx, yy); \
371 MP_DROP(xx); MP_DROP(yy); \
372 return (pre##_pywrap(zz)); \
373 }
d7ab1bab 374BINOP(mp, and2c)
375BINOP(mp, or2c)
376BINOP(mp, xor2c)
377BINOP(gf, add)
378BINOP(gf, sub)
379BINOP(gf, mul)
380BINOP(gf, and)
381BINOP(gf, or)
382BINOP(gf, xor)
383#undef BINOP
384
385static 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))); }
397UNOP(mp, neg)
398UNOP(mp, abs)
399UNOP(mp, not2c)
400#undef UNOP
401
402static PyObject *mp_pyid(PyObject *x) { RETURN_OBJ(x); }
403
404#define gf_lsr mp_lsr
34e3dbc6 405#define SHIFTOP(pre, PRE, name, rname) \
d7ab1bab 406 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
34e3dbc6 407 PyObject *yix = 0; \
d7ab1bab 408 PyObject *z = 0; \
409 long n; \
34e3dbc6
MW
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)); \
d7ab1bab 417 return (z); \
418 }
34e3dbc6
MW
419SHIFTOP(mp, MP, lsl2c, lsr2c)
420SHIFTOP(mp, MP, lsr2c, lsl2c)
421SHIFTOP(gf, GF, lsl, lsr)
422SHIFTOP(gf, GF, lsr, lsl)
d7ab1bab 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) \
bf8910bd 430 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
d7ab1bab 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
443DIVOP(mp, divmod, YES, YES,
444 Py_BuildValue("(NN)", mp_pywrap(q), mp_pywrap(r)))
445DIVOP(mp, div, YES, NO, mp_pywrap(q))
446DIVOP(mp, mod, NO, YES, mp_pywrap(r))
447DIVOP(gf, divmod, YES, YES,
448 Py_BuildValue("(NN)", gf_pywrap(q), gf_pywrap(r)))
449DIVOP(gf, div, YES, NO, gf_pywrap(q))
450DIVOP(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
457static 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
469static 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
bf8910bd 475 if ((xx = implicitmp(x)) == 0 || (yy = implicitmp(y)) == 0 ||
6311e4f7 476 (z && z != Py_None && (zz = implicitmp(z)) == 0)) {
d7ab1bab 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);
502end:
503 mp_drop(xx); mp_drop(yy); mp_drop(zz);
504 return (rc);
505}
506
507static 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); }
f7623015 522#ifdef PY2
d7ab1bab 523BASEOP(oct, 8, "0");
f7623015 524#endif
d7ab1bab 525BASEOP(hex, 16, "0x");
526#undef BASEOP
527
528static int mp_pynonzerop(PyObject *x) { return !MP_ZEROP(MP_X(x)); }
529
530static PyObject *mp_pyint(PyObject *x)
531{
532 long l;
bc243788
MW
533 if (!mp_tolong_checked(MP_X(x), &l, 0)) return (PyInt_FromLong(l));
534 else return mp_topylong(MP_X(x));
d7ab1bab 535}
f7623015 536#ifdef PY2
d7ab1bab 537static PyObject *mp_pylong(PyObject *x)
f368b46e 538 { return (mp_topylong(MP_X(x))); }
f7623015 539#endif
d7ab1bab 540static PyObject *mp_pyfloat(PyObject *x)
541{
f368b46e 542 PyObject *l = mp_topylong(MP_X(x));
d7ab1bab 543 double f = PyLong_AsDouble(l);
544 Py_DECREF(l);
545 return (PyFloat_FromDouble(f));
546}
547
f7623015 548#ifdef PY2
b2687a0a 549#define COERCE(pre, PRE) \
d7ab1bab 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 } \
712ebf4b 558 if ((z = implicit##pre(*y)) != 0) { \
d7ab1bab 559 Py_INCREF(*x); \
560 *y = pre##_pywrap(z); \
561 return (0); \
562 } \
563 return (1); \
564 }
565COERCE(mp, MP)
566COERCE(gf, GF)
567#undef COERCE
f7623015 568#endif
d7ab1bab 569
77535854
MW
570static 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
f7623015 584#ifdef PY2
d7ab1bab 585static int mp_pycompare(PyObject *x, PyObject *y)
586 { return mp_cmp(MP_X(x), MP_X(y)); }
f7623015 587#endif
d7ab1bab 588
589static 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;
827f89d7 595 static const char *const kwlist[] = { "x", "radix", 0 };
d7ab1bab 596
827f89d7 597 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|i:new", KWLIST, &x, &radix))
d7ab1bab 598 goto end;
599 if (MP_PYCHECK(x)) RETURN_OBJ(x);
f368b46e 600 if (!good_radix_p(radix, 1)) VALERR("bad radix");
d7ab1bab 601 if ((z = mp_frompyobject(x, radix)) == 0) {
602 PyErr_Format(PyExc_TypeError, "can't convert %.100s to mp",
2a448f86 603 Py_TYPE(x)->tp_name);
d7ab1bab 604 goto end;
605 }
606 zz = (mp_pyobj *)ty->tp_alloc(ty, 0);
607 zz->x = z;
608end:
609 return ((PyObject *)zz);
610}
611
ad52b46f
MW
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 }
624IMPLICIT(mp)
625IMPLICIT(gf)
626#undef IMPLICIT
627
d6d78edc 628Py_hash_t mphash(mp *x)
d7ab1bab 629{
be6df1c3 630 PyObject *l = mp_topylong(x);
d6d78edc 631 Py_hash_t h = PyObject_Hash(l);
f368b46e 632 Py_DECREF(l); return (h);
d7ab1bab 633}
634
d6d78edc 635static Py_hash_t mp_pyhash(PyObject *me) { return (mphash(MP_X(me))); }
be6df1c3 636
d7ab1bab 637static 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)));
644end:
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 { \
a1be89ad
MW
652 unsigned long i; \
653 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
d7ab1bab 654 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
655 }
656BITOP(mp, setbit, 2c);
657BITOP(mp, clearbit, 2c);
b2687a0a 658BITOP(gf, setbit, );
d7ab1bab 659BITOP(gf, clearbit, );
660#undef BITOP
661
662static PyObject *mpmeth_testbit(PyObject *me, PyObject *arg)
663{
a1be89ad
MW
664 unsigned long i;
665 if (!PyArg_ParseTuple(arg, "O&:testbit", convulong, &i)) return (0);
d7ab1bab 666 return (getbool(mp_testbit2c(MP_X(me), i)));
667}
668
669static PyObject *gfmeth_testbit(PyObject *me, PyObject *arg)
670{
a1be89ad
MW
671 unsigned long i;
672 if (!PyArg_ParseTuple(arg, "O&:testbit", convulong, &i)) return (0);
d7ab1bab 673 return (getbool(mp_testbit(MP_X(me), i)));
674}
675
91e56f06 676static PyObject *mpmeth_odd(PyObject *me)
d7ab1bab 677{
678 mp *t;
679 size_t s;
680
d7ab1bab 681 t = mp_odd(MP_NEW, MP_X(me), &s);
682 return (Py_BuildValue("(lN)", (long)s, mp_pywrap(t)));
683}
684
91e56f06
MW
685static PyObject *mpmeth_sqr(PyObject *me)
686 { return (mp_pywrap(mp_sqr(MP_NEW, MP_X(me)))); }
d7ab1bab 687
91e56f06 688static PyObject *mpmeth_sqrt(PyObject *me)
d7ab1bab 689{
d7ab1bab 690 if (MP_NEGP(MP_X(me))) VALERR("negative root");
691 return (mp_pywrap(mp_sqrt(MP_NEW, MP_X(me))));
692end:
693 return (0);
694}
695
696static 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);
704end:
705 if (y) MP_DROP(y);
706 return (z);
707}
708
709static 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));
718end:
719 if (yy) MP_DROP(yy);
720 return (z);
721}
722
723static 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);
732end:
733 if (yy) MP_DROP(yy);
734 return (z);
735}
736
737static PyObject *mpmeth_tostring(PyObject *me, PyObject *arg, PyObject *kw)
738{
739 int radix = 10;
827f89d7
MW
740 static const char *const kwlist[] = { "radix", 0 };
741 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|i:tostring", KWLIST, &radix))
d7ab1bab 742 goto end;
f368b46e 743 if (!good_radix_p(radix, 0)) VALERR("bad radix");
d7ab1bab 744 return (mp_topystring(MP_X(me), radix, 0, 0, 0));
745end:
746 return (0);
747}
748
749static 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);
758end:
759 if (yy) MP_DROP(yy);
760 return (z);
761}
762
d0d94587
MW
763static 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);
772end:
773 return (rc);
774}
775
d7ab1bab 776#define STOREOP(name, c) \
777 static PyObject *mpmeth_##name(PyObject *me, \
778 PyObject *arg, PyObject *kw) \
779 { \
780 long len = -1; \
a444923a 781 static const char *const kwlist[] = { "len", 0 }; \
d7ab1bab 782 PyObject *rc = 0; \
783 \
784 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
827f89d7 785 KWLIST, &len)) \
d7ab1bab 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); \
2135a6d3 792 mp_##name(MP_X(me), BIN_PTR(rc), len); \
d7ab1bab 793 end: \
794 return (rc); \
795 }
796STOREOP(storel, )
797STOREOP(storeb, )
798STOREOP(storel2c, 2c)
799STOREOP(storeb2c, 2c)
800#undef STOREOP
801
a157093f
MW
802#define BUFOP(ty) \
803 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
d7ab1bab 804 { \
805 buf b; \
67c75893 806 struct bin in; \
d7ab1bab 807 PyObject *rc = 0; \
808 mp *x; \
809 \
67c75893
MW
810 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
811 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
d7ab1bab 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 }
a157093f
MW
818BUFOP(mp)
819BUFOP(gf)
d7ab1bab 820#undef BUFOP
821
91e56f06 822static PyObject *mpmeth_tobuf(PyObject *me)
d7ab1bab 823{
824 buf b;
825 PyObject *rc;
826 mp *x;
827 size_t n;
828
d7ab1bab 829 x = MP_X(me);
830 n = mp_octets(x) + 3;
831 rc = bytestring_pywrap(0, n);
2135a6d3 832 buf_init(&b, BIN_PTR(rc), n);
d7ab1bab 833 buf_putmp(&b, x);
834 assert(BOK(&b));
2135a6d3 835 BIN_SETLEN(rc, BLEN(&b));
d7ab1bab 836 return (rc);
837}
838
839static PyObject *mpmeth_primep(PyObject *me, PyObject *arg, PyObject *kw)
840{
841 grand *r = &rand_global;
827f89d7 842 static const char *const kwlist[] = { "rng", 0 };
d7ab1bab 843 PyObject *rc = 0;
844
827f89d7 845 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&", KWLIST, convgrand, &r))
d7ab1bab 846 goto end;
847 rc = getbool(pgen_primep(MP_X(me), r));
848end:
849 return (rc);
850}
851
a157093f
MW
852static PyObject *mpmeth_fromstring(PyObject *me,
853 PyObject *arg, PyObject *kw)
f281293c
MW
854{
855 int r = 0;
856 char *p;
857 Py_ssize_t len;
858 PyObject *z = 0;
859 mp *zz;
860 mptext_stringctx sc;
a157093f 861 static const char *const kwlist[] = { "x", "radix", 0 };
f281293c 862
a157093f
MW
863 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
864 &p, &len, &r))
f281293c
MW
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));
872end:
873 return (z);
874}
875
a157093f 876static PyObject *mpmeth_factorial(PyObject *me, PyObject *arg)
f281293c
MW
877{
878 unsigned long i;
879 mp *x;
a157093f 880 if (!PyArg_ParseTuple(arg, "O&:factorial", convulong, &i)) return (0);
f281293c
MW
881 x = mp_factorial(i);
882 return mp_pywrap(x);
883}
884
a157093f 885static PyObject *mpmeth_fibonacci(PyObject *me, PyObject *arg)
f281293c
MW
886{
887 long i;
888 mp *x;
a157093f 889 if (!PyArg_ParseTuple(arg, "l:fibonacci", &i)) return (0);
f281293c
MW
890 x = mp_fibonacci(i);
891 return mp_pywrap(x);
892}
893
a157093f
MW
894#define LOADOP(pre, name) \
895 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
f281293c 896 { \
67c75893
MW
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))); \
f281293c 900 }
a157093f
MW
901LOADOP(mp, loadl)
902LOADOP(mp, loadb)
903LOADOP(mp, loadl2c)
904LOADOP(mp, loadb2c)
905LOADOP(gf, loadl)
906LOADOP(gf, loadb)
f281293c
MW
907#undef LOADOP
908
d7ab1bab 909static PyObject *mpget_nbits(PyObject *me, void *hunoz)
910 { return (PyInt_FromLong(mp_bits(MP_X(me)))); }
911
912static PyObject *mpget_noctets(PyObject *me, void *hunoz)
913 { return (PyInt_FromLong(mp_octets(MP_X(me)))); }
914
915static PyObject *mpget_noctets2c(PyObject *me, void *hunoz)
916 { return (PyInt_FromLong(mp_octets2c(MP_X(me)))); }
917
c90f712e 918static const PyGetSetDef mp_pygetset[] = {
d7ab1bab 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
c90f712e 927static const PyMethodDef mp_pymethods[] = {
d7ab1bab 928#define METHNAME(func) mpmeth_##func
c3060669 929 METH (jacobi, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
d7ab1bab 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")
91e56f06
MW
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)")
d7ab1bab 936 METH (gcd, "X.gcd(Y) -> gcd(X, Y)")
d96c882e
MW
937 METH (gcdx, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
938 "with X U + Y V = gcd(X, Y)")
d7ab1bab 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")
d96c882e
MW
941 METH (leastcongruent, "X.leastcongruent(B, M) -> "
942 "smallest Z >= B with Z == X (mod M)")
9edc275a 943 KWMETH(primep, "X.primep([rng = rand]) -> X is prime?")
1df8d5fe
MW
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")
d96c882e
MW
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")
91e56f06 951 NAMETH(tobuf, "X.tobuf() -> buffer format")
a157093f
MW
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.")
ad52b46f 956 SMTH (_implicit, 0)
a157093f
MW
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")
d7ab1bab 966#undef METHNAME
967 { 0 }
968};
969
c90f712e 970static const PyNumberMethods mp_pynumber = {
d7ab1bab 971 mp_pyadd, /* @nb_add@ */
972 mp_pysub, /* @nb_subtract@ */
973 mp_pymul, /* @nb_multiply@ */
f7623015 974#ifdef PY2
d7ab1bab 975 0, /* @nb_divide@ */
f7623015 976#endif
d7ab1bab 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@ */
f7623015 990#ifdef PY2
d7ab1bab 991 mp_pycoerce, /* @nb_coerce@ */
f7623015 992#endif
d7ab1bab 993 mp_pyint, /* @nb_int@ */
f7623015 994 PY23(mp_pylong, 0), /* @nb_long@ */
d7ab1bab 995 mp_pyfloat, /* @nb_float@ */
f7623015 996#ifdef PY2
d7ab1bab 997 mp_pyoct, /* @nb_oct@ */
998 mp_pyhex, /* @nb_hex@ */
f7623015 999#endif
d7ab1bab 1000
1001 0, /* @nb_inplace_add@ */
1002 0, /* @nb_inplace_subtract@ */
1003 0, /* @nb_inplace_multiply@ */
f7623015 1004#ifdef PY2
d7ab1bab 1005 0, /* @nb_inplace_divide@ */
f7623015 1006#endif
d7ab1bab 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@ */
a90a9c0e
MW
1019
1020 mp_pyint, /* @nb_index@ */
d7ab1bab 1021};
1022
c263b05c 1023static const PyTypeObject mp_pytype_skel = {
591bf41b 1024 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 1025 "MP", /* @tp_name@ */
d7ab1bab 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@ */
f7623015 1033 PY23(mp_pycompare, 0), /* @tp_compare@/@tp_as_async@ */
d7ab1bab 1034 mp_pyrepr, /* @tp_repr@ */
c90f712e 1035 PYNUMBER(mp), /* @tp_as_number@ */
d7ab1bab 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@ */
d96c882e
MW
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"
f7623015 1052 "convert to `" PY23("long", "int") "'.\n"
d96c882e
MW
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"
f7623015 1057 PY23(
d96c882e 1058 "points, group elements, Python `int' and `long' objects, and anything\n"
f7623015
MW
1059 "with an integer conversion.\n",
1060 "points, group elements, Python `int' objects, and anything with an\n"
1061 "integer conversion.\n")
d96c882e
MW
1062 "\n"
1063 "Notes:\n"
1064 "\n"
1065 " * Use `//' for integer division: `/' gives exact rational division.",
d7ab1bab 1066
1067 0, /* @tp_traverse@ */
1068 0, /* @tp_clear@ */
77535854 1069 mp_pyrichcompare, /* @tp_richcompare@ */
d7ab1bab 1070 0, /* @tp_weaklistoffset@ */
1071 0, /* @tp_iter@ */
963a6148 1072 0, /* @tp_iternext@ */
c90f712e 1073 PYMETHODS(mp), /* @tp_methods@ */
d7ab1bab 1074 0, /* @tp_members@ */
c90f712e 1075 PYGETSET(mp), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 1084 0, /* @tp_free@ */
d7ab1bab 1085 0 /* @tp_is_gc@ */
1086};
1087
32507e35
MW
1088/*----- Products of small integers ----------------------------------------*/
1089
c263b05c
MW
1090static PyTypeObject *mpmul_pytype;
1091
32507e35
MW
1092typedef 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
1101static void mpmul_pydealloc(PyObject *me)
1102{
1103 if (MPMUL_LIVEP(me))
1104 mp_drop(mpmul_done(MPMUL_PY(me)));
1105 FREEOBJ(me);
1106}
1107
1108static PyObject *mmmeth_factor(PyObject *me, PyObject *arg)
d7ab1bab 1109{
d7ab1bab 1110 PyObject *q, *i;
1111 mp *x;
1112
32507e35 1113 if (!MPMUL_LIVEP(me)) VALERR("MPMul object invalid");
c51a597d 1114 if (PyTuple_GET_SIZE(arg) != 1)
d7ab1bab 1115 i = PyObject_GetIter(arg);
32507e35 1116 else {
c51a597d 1117 if ((q = PyTuple_GET_ITEM(arg, 0)) == 0) goto end;
d7ab1bab 1118 if ((i = PyObject_GetIter(q)) == 0) {
1119 PyErr_Clear(); /* that's ok */
1120 i = PyObject_GetIter(arg);
1121 }
1122 }
32507e35 1123 if (!i) goto end;
d7ab1bab 1124 while ((q = PyIter_Next(i)) != 0) {
1125 x = getmp(q); Py_DECREF(q); if (!x) {
d7ab1bab 1126 Py_DECREF(i);
32507e35 1127 goto end;
d7ab1bab 1128 }
32507e35 1129 mpmul_add(MPMUL_PY(me), x);
d7ab1bab 1130 MP_DROP(x);
1131 }
d7ab1bab 1132 Py_DECREF(i);
32507e35
MW
1133 RETURN_ME;
1134end:
1135 return (0);
1136}
1137
91e56f06 1138static PyObject *mmmeth_done(PyObject *me)
32507e35
MW
1139{
1140 mp *x;
1141
32507e35
MW
1142 if (!MPMUL_LIVEP(me)) VALERR("MPMul object invalid");
1143 x = mpmul_done(MPMUL_PY(me));
1144 MPMUL_LIVEP(me) = 0;
d7ab1bab 1145 return (mp_pywrap(x));
32507e35
MW
1146end:
1147 return (0);
d7ab1bab 1148}
1149
32507e35
MW
1150static 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;
d7ab1bab 1161 }
32507e35
MW
1162 return ((PyObject *)mm);
1163end:
1164 return (0);
1165}
1166
1167static PyObject *mmget_livep(PyObject *me, void *hunoz)
1168 { return (getbool(MPMUL_LIVEP(me))); }
1169
c90f712e 1170static const PyGetSetDef mpmul_pygetset[] = {
32507e35 1171#define GETSETNAME(op, name) mm##op##_##name
d96c882e 1172 GET (livep, "MM.livep -> flag: object still valid?")
32507e35
MW
1173#undef GETSETNAME
1174 { 0 }
1175};
1176
c90f712e 1177static const PyMethodDef mpmul_pymethods[] = {
32507e35 1178#define METHNAME(name) mmmeth_##name
d96c882e 1179 METH (factor, "MM.factor(ITERABLE) or MM.factor(I, ...)")
91e56f06 1180 NAMETH(done, "MM.done() -> PRODUCT")
32507e35
MW
1181#undef METHNAME
1182 { 0 }
1183};
1184
c263b05c 1185static const PyTypeObject mpmul_pytype_skel = {
591bf41b 1186 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 1187 "MPMul", /* @tp_name@ */
32507e35
MW
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@ */
d96c882e 1210 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
32507e35
MW
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@ */
c90f712e 1218 PYMETHODS(mpmul), /* @tp_methods@ */
32507e35 1219 0, /* @tp_members@ */
c90f712e 1220 PYGETSET(mpmul), /* @tp_getset@ */
32507e35
MW
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};
d7ab1bab 1232
1233/*----- Montgomery reduction ----------------------------------------------*/
1234
c263b05c
MW
1235static PyTypeObject *mpmont_pytype;
1236
d7ab1bab 1237typedef struct mpmont_pyobj {
1238 PyObject_HEAD
1239 mpmont mm;
1240} mpmont_pyobj;
1241
1242#define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1243
1244static 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));
1254end:
1255 if (yy) MP_DROP(yy);
1256 return (z);
1257}
1258
1259static 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));
1267end:
1268 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1269 return (rc);
1270}
1271
1272static 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));
1284end:
1285 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1286 return (rc);
1287}
1288
1289static 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));
1303end:
1304 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1305 return (rc);
1306}
1307
1308static PyObject *mm_mexpr_id(PyObject *me)
1309 { return mp_pywrap(MP_COPY(MPMONT_PY(me)->r)); }
1310
1311static 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
1330fail:
1331 mp_drop(xx); mp_drop(yy);
1332 return (-1);
1333}
1334
01d4fd84 1335static PyObject *mm_mexpr(PyObject *me, void *v, size_t n)
d7ab1bab 1336 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me), MP_NEW, v, n)); }
b2687a0a 1337
d7ab1bab 1338static void mp_mexp_drop(void *p)
1339{
1340 mp_expfactor *f = p;
1341 mp_drop(f->base);
1342 mp_drop(f->exp);
1343}
1344
1345static 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
1351static PyObject *mp_mexp_id(PyObject *me)
1352 { return mp_pywrap(MP_ONE); }
1353
1354static 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
1370fail:
1371 mp_drop(xx); mp_drop(yy);
1372 return (-1);
1373}
1374
01d4fd84 1375static PyObject *mm_mexp(PyObject *me, void *v, size_t n)
d7ab1bab 1376 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me), MP_NEW, v, n)); }
b2687a0a 1377
d7ab1bab 1378static 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
1385static 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));
1392end:
1393 return (z);
1394}
1395
1396static void mpmont_pydealloc(PyObject *me)
1397{
1398 mpmont_destroy(MPMONT_PY(me));
3aa33042 1399 FREEOBJ(me);
d7ab1bab 1400}
1401
1402static PyObject *mpmont_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1403{
1404 mpmont_pyobj *mm = 0;
827f89d7 1405 static const char *const kwlist[] = { "m", 0 };
d7ab1bab 1406 mp *xx = 0;
1407
827f89d7 1408 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
d7ab1bab 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);
1413end:
1414 if (xx) MP_DROP(xx);
1415 return ((PyObject *)mm);
1416}
1417
1418static PyObject *mmget_m(PyObject *me, void *hunoz)
1419 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->m))); }
1420
1421static PyObject *mmget_r(PyObject *me, void *hunoz)
1422 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->r))); }
1423
1424static PyObject *mmget_r2(PyObject *me, void *hunoz)
1425 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->r2))); }
1426
c90f712e 1427static const PyGetSetDef mpmont_pygetset[] = {
d7ab1bab 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
c90f712e 1436static const PyMethodDef mpmont_pymethods[] = {
d7ab1bab 1437#define METHNAME(name) mmmeth_##name
986bcc44 1438 METH (int, "M.int(X) -> XR")
d7ab1bab 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")
d96c882e
MW
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.)")
d7ab1bab 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")
d96c882e
MW
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.)")
d7ab1bab 1450#undef METHNAME
1451 { 0 }
1452};
1453
c263b05c 1454static const PyTypeObject mpmont_pytype_skel = {
591bf41b 1455 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 1456 "MPMont", /* @tp_name@ */
d7ab1bab 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@ */
d96c882e 1479 "MPMont(N): a Montgomery reduction context.",
d7ab1bab 1480
1481 0, /* @tp_traverse@ */
1482 0, /* @tp_clear@ */
1483 0, /* @tp_richcompare@ */
1484 0, /* @tp_weaklistoffset@ */
1485 0, /* @tp_iter@ */
963a6148 1486 0, /* @tp_iternext@ */
c90f712e 1487 PYMETHODS(mpmont), /* @tp_methods@ */
d7ab1bab 1488 0, /* @tp_members@ */
c90f712e 1489 PYGETSET(mpmont), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 1498 0, /* @tp_free@ */
d7ab1bab 1499 0 /* @tp_is_gc@ */
1500};
1501
1502/*----- Barrett reduction -------------------------------------------------*/
1503
c263b05c
MW
1504static PyTypeObject *mpbarrett_pytype;
1505
d7ab1bab 1506typedef struct mpbarrett_pyobj {
1507 PyObject_HEAD
1508 mpbarrett mb;
1509} mpbarrett_pyobj;
1510
1511#define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1512
1513static 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));
1525end:
1526 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1527 return (rc);
1528}
1529
01d4fd84 1530static PyObject *mb_mexp(PyObject *me, void *v, size_t n)
d7ab1bab 1531 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me), MP_NEW, v, n)); }
b2687a0a 1532
d7ab1bab 1533static 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
1539static 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));
1547end:
1548 return (z);
1549}
1550
1551static void mpbarrett_pydealloc(PyObject *me)
1552{
1553 mpbarrett_destroy(MPBARRETT_PY(me));
3aa33042 1554 FREEOBJ(me);
d7ab1bab 1555}
1556
1557static PyObject *mpbarrett_pynew(PyTypeObject *ty,
1558 PyObject *arg, PyObject *kw)
1559{
1560 mpbarrett_pyobj *mb = 0;
827f89d7 1561 static const char *const kwlist[] = { "m", 0 };
d7ab1bab 1562 mp *xx = 0;
1563
827f89d7 1564 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
d7ab1bab 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);
1569end:
1570 if (xx) MP_DROP(xx);
1571 return ((PyObject *)mb);
1572}
1573
1574static PyObject *mbget_m(PyObject *me, void *hunoz)
1575 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me)->m))); }
1576
c90f712e 1577static const PyGetSetDef mpbarrett_pygetset[] = {
d7ab1bab 1578#define GETSETNAME(op, name) mb##op##_##name
1579 GET (m, "B.m -> modulus for reduction")
1580#undef GETSETNAME
1581 { 0 }
1582};
1583
c90f712e 1584static const PyMethodDef mpbarrett_pymethods[] = {
d7ab1bab 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")
d96c882e
MW
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.)")
d7ab1bab 1591#undef METHNAME
1592 { 0 }
1593};
1594
c263b05c 1595static const PyTypeObject mpbarrett_pytype_skel = {
591bf41b 1596 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 1597 "MPBarrett", /* @tp_name@ */
d7ab1bab 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@ */
d96c882e 1620 "MPBarrett(N): a Barrett reduction context.",
d7ab1bab 1621
1622 0, /* @tp_traverse@ */
1623 0, /* @tp_clear@ */
1624 0, /* @tp_richcompare@ */
1625 0, /* @tp_weaklistoffset@ */
1626 0, /* @tp_iter@ */
963a6148 1627 0, /* @tp_iternext@ */
c90f712e 1628 PYMETHODS(mpbarrett), /* @tp_methods@ */
d7ab1bab 1629 0, /* @tp_members@ */
c90f712e 1630 PYGETSET(mpbarrett), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 1639 0, /* @tp_free@ */
d7ab1bab 1640 0 /* @tp_is_gc@ */
1641};
1642
1643/*----- Nice prime reduction ----------------------------------------------*/
1644
c263b05c
MW
1645static PyTypeObject *mpreduce_pytype;
1646
d7ab1bab 1647typedef struct mpreduce_pyobj {
1648 PyObject_HEAD
1649 mpreduce mr;
1650} mpreduce_pyobj;
1651
1652#define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1653
1654static 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));
1666end:
1667 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1668 return (rc);
1669}
1670
1671static 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));
1678end:
1679 return (z);
1680}
1681
1682static void mpreduce_pydealloc(PyObject *me)
1683{
1684 mpreduce_destroy(MPREDUCE_PY(me));
3aa33042 1685 FREEOBJ(me);
d7ab1bab 1686}
1687
1688static PyObject *mpreduce_pynew(PyTypeObject *ty,
1689 PyObject *arg, PyObject *kw)
1690{
1691 mpreduce_pyobj *mr = 0;
1692 mpreduce r;
827f89d7 1693 static const char *const kwlist[] = { "m", 0 };
d7ab1bab 1694 mp *xx = 0;
1695
827f89d7 1696 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
d7ab1bab 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;
1702end:
1703 if (xx) MP_DROP(xx);
1704 return ((PyObject *)mr);
1705}
1706
1707static PyObject *mrget_m(PyObject *me, void *hunoz)
1708 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me)->p))); }
1709
c90f712e 1710static const PyGetSetDef mpreduce_pygetset[] = {
d7ab1bab 1711#define GETSETNAME(op, name) mr##op##_##name
1712 GET (m, "R.m -> modulus for reduction")
1713#undef GETSETNAME
1714 { 0 }
1715};
1716
c90f712e 1717static const const PyMethodDef mpreduce_pymethods[] = {
d7ab1bab 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
c263b05c 1725static const PyTypeObject mpreduce_pytype_skel = {
591bf41b 1726 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 1727 "MPReduce", /* @tp_name@ */
d7ab1bab 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@ */
d96c882e 1750 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
d7ab1bab 1751
1752 0, /* @tp_traverse@ */
1753 0, /* @tp_clear@ */
1754 0, /* @tp_richcompare@ */
1755 0, /* @tp_weaklistoffset@ */
1756 0, /* @tp_iter@ */
963a6148 1757 0, /* @tp_iternext@ */
c90f712e 1758 PYMETHODS(mpreduce), /* @tp_methods@ */
d7ab1bab 1759 0, /* @tp_members@ */
c90f712e 1760 PYGETSET(mpreduce), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 1769 0, /* @tp_free@ */
d7ab1bab 1770 0 /* @tp_is_gc@ */
1771};
1772
1773/*----- Chinese Remainder Theorem solution --------------------------------*/
1774
c263b05c
MW
1775static PyTypeObject *mpcrt_pytype;
1776
d7ab1bab 1777typedef struct mpcrt_pyobj {
1778 PyObject_HEAD
1779 mpcrt c;
1780} mpcrt_pyobj;
1781
1782#define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1783
1784static PyObject *mcmeth_solve(PyObject *me, PyObject *arg)
1785{
1786 mpcrt *c = MPCRT_PY(me);
1787 PyObject *q = 0, *x, *z = 0;
1788 mp *xx;
1789 mp **v = 0;
77a0d53f 1790 Py_ssize_t i = 0, n = c->k;
d7ab1bab 1791
c51a597d 1792 if (PyTuple_GET_SIZE(arg) == n)
d7ab1bab 1793 q = arg;
1794 else if (!PyArg_ParseTuple(arg, "O:solve", &q))
1795 goto end;
d7ab1bab 1796 if (!PySequence_Check(q)) TYERR("want a sequence of residues");
4281a7ee
MW
1797 i = PySequence_Size(q); if (i < 0) goto end;
1798 if (i != n) VALERR("residue count mismatch");
d7ab1bab 1799 v = xmalloc(n * sizeof(*v));
1800 for (i = 0; i < n; i++) {
1801 if ((x = PySequence_GetItem(q, i)) == 0) goto end;
1802 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
1803 v[i] = xx;
1804 }
1805 z = mp_pywrap(mpcrt_solve(c, MP_NEW, v));
1806end:
1807 if (v) {
21a9d6f0 1808 while (i--) MP_DROP(v[i]);
d7ab1bab 1809 xfree(v);
1810 }
d7ab1bab 1811 return (z);
1812}
1813
1814static void mpcrt_pydealloc(PyObject *me)
1815{
1816 mpcrt *c = MPCRT_PY(me);
1817 mpcrt_destroy(c);
1818 xfree(c->v);
1819}
1820
1821static PyObject *mpcrt_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1822{
1823 mpcrt_mod *v = 0;
77a0d53f 1824 Py_ssize_t n, i = 0, j;
827f89d7 1825 static const char *const kwlist[] = { "mv", 0 };
d7ab1bab 1826 PyObject *q = 0, *x;
d2b7e92c
MW
1827 mp *xx = MP_NEW, *y = MP_NEW, *g = MP_NEW;
1828 mpmul mm;
d7ab1bab 1829 mpcrt_pyobj *c = 0;
1830
c51a597d 1831 if (PyTuple_GET_SIZE(arg) > 1)
d7ab1bab 1832 q = arg;
827f89d7 1833 else if (!PyArg_ParseTupleAndKeywords(arg, kw, "O:new", KWLIST, &q))
d7ab1bab 1834 goto end;
d7ab1bab 1835 if (!PySequence_Check(q)) TYERR("want a sequence of moduli");
4281a7ee 1836 n = PySequence_Size(q); if (n < 0) goto end;
d7ab1bab 1837 if (!n) VALERR("want at least one modulus");
1838 v = xmalloc(n * sizeof(*v));
1839 for (i = 0; i < n; i++) {
1840 if ((x = PySequence_GetItem(q, i)) == 0) goto end;
1841 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
684cd535 1842 if (MP_CMP(xx, <=, MP_ZERO)) VALERR("moduli must be positive");
4e02c19c 1843 v[i].m = xx; v[i].n = 0; v[i].ni = 0; v[i].nni = 0; xx = MP_NEW;
d7ab1bab 1844 }
d2b7e92c
MW
1845 mpmul_init(&mm);
1846 for (j = 0; j < i; j++) mpmul_add(&mm, v[j].m);
1847 xx = mpmul_done(&mm);
1848 for (j = 0; j < i; j++) {
1849 mp_div(&y, 0, xx, v[j].m);
1850 mp_gcd(&g, 0, 0, y, v[j].m);
1851 if (!MP_EQ(g, MP_ONE)) VALERR("moduli must be pairwise coprime");
1852 }
1853
d7ab1bab 1854 c = (mpcrt_pyobj *)ty->tp_alloc(ty, 0);
1855 mpcrt_create(&c->c, v, n, 0);
d2b7e92c 1856 mp_drop(xx); mp_drop(y); mp_drop(g);
d7ab1bab 1857 return ((PyObject *)c);
1858
1859end:
1860 if (v) {
21a9d6f0 1861 while (i--) MP_DROP(v[i].m);
d7ab1bab 1862 xfree(v);
1863 }
d2b7e92c 1864 mp_drop(xx); mp_drop(y); mp_drop(g);
d7ab1bab 1865 return (0);
1866}
1867
1868static PyObject *mcget_product(PyObject *me, void *hunoz)
1869 { return (mp_pywrap(MP_COPY(MPCRT_PY(me)->mb.m))); }
1870
1871static PyObject *mcget_moduli(PyObject *me, void *hunoz)
1872{
1873 int i;
1874 PyObject *q;
1875 mpcrt *c = MPCRT_PY(me);
1876
1877 if ((q = PyList_New(c->k)) == 0) return (0);
1878 for (i = 0; i < c->k; i++)
c51a597d 1879 PyList_SET_ITEM(q, i, mp_pywrap(c->v[i].m));
d7ab1bab 1880 return (q);
1881}
1882
c90f712e 1883static const PyGetSetDef mpcrt_pygetset[] = {
d7ab1bab 1884#define GETSETNAME(op, name) mc##op##_##name
1885 GET (product, "C.product -> product of moduli")
1886 GET (moduli, "C.moduli -> list of individual moduli")
1887#undef GETSETNAME
1888 { 0 }
1889};
1890
c90f712e 1891static const PyMethodDef mpcrt_pymethods[] = {
d7ab1bab 1892#define METHNAME(name) mcmeth_##name
1893 METH (solve, "C.solve([R0, R1]) -> X mod C.product")
1894#undef METHNAME
1895 { 0 }
1896};
1897
c263b05c 1898static const PyTypeObject mpcrt_pytype_skel = {
591bf41b 1899 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 1900 "MPCRT", /* @tp_name@ */
d7ab1bab 1901 sizeof(mpcrt_pyobj), /* @tp_basicsize@ */
1902 0, /* @tp_itemsize@ */
1903
1904 mpcrt_pydealloc, /* @tp_dealloc@ */
1905 0, /* @tp_print@ */
1906 0, /* @tp_getattr@ */
1907 0, /* @tp_setattr@ */
1908 0, /* @tp_compare@ */
1909 0, /* @tp_repr@ */
1910 0, /* @tp_as_number@ */
1911 0, /* @tp_as_sequence@ */
1912 0, /* @tp_as_mapping@ */
1913 0, /* @tp_hash@ */
1914 0, /* @tp_call@ */
1915 0, /* @tp_str@ */
1916 0, /* @tp_getattro@ */
1917 0, /* @tp_setattro@ */
1918 0, /* @tp_as_buffer@ */
1919 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1920 Py_TPFLAGS_BASETYPE,
1921
1922 /* @tp_doc@ */
d96c882e 1923 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
d7ab1bab 1924
1925 0, /* @tp_traverse@ */
1926 0, /* @tp_clear@ */
1927 0, /* @tp_richcompare@ */
1928 0, /* @tp_weaklistoffset@ */
1929 0, /* @tp_iter@ */
963a6148 1930 0, /* @tp_iternext@ */
c90f712e 1931 PYMETHODS(mpcrt), /* @tp_methods@ */
d7ab1bab 1932 0, /* @tp_members@ */
c90f712e 1933 PYGETSET(mpcrt), /* @tp_getset@ */
d7ab1bab 1934 0, /* @tp_base@ */
1935 0, /* @tp_dict@ */
1936 0, /* @tp_descr_get@ */
1937 0, /* @tp_descr_set@ */
1938 0, /* @tp_dictoffset@ */
1939 0, /* @tp_init@ */
1940 PyType_GenericAlloc, /* @tp_alloc@ */
1941 mpcrt_pynew, /* @tp_new@ */
3aa33042 1942 0, /* @tp_free@ */
d7ab1bab 1943 0 /* @tp_is_gc@ */
1944};
1945
1946/*----- Binary polynomials ------------------------------------------------*/
1947
1948static PyObject *gf_pyrepr(PyObject *o)
e38168e2 1949 { return mp_topystring(MP_X(o), 16, "GF(", "0x", ")"); }
d7ab1bab 1950
1951static PyObject *gf_pyrichcompare(PyObject *x, PyObject *y, int op)
1952{
1953 mp *xx, *yy;
1954 int xl, yl;
1955 int b;
1956
bf8910bd 1957 if (gfbinop(x, y, &xx, &yy)) RETURN_NOTIMPL;
d7ab1bab 1958 switch (op) {
1959 case Py_EQ: b = MP_EQ(xx, yy); break;
1960 case Py_NE: b = !MP_EQ(xx, yy); break;
1961 default:
1962 xl = mp_bits(xx);
1963 yl = mp_bits(yy);
1964 switch (op) {
1965 case Py_LT: b = xl < yl; break;
1966 case Py_LE: b = xl <= yl; break;
1967 case Py_GT: b = xl > yl; break;
1968 case Py_GE: b = xl >= yl; break;
1969 default: abort();
1970 }
1971 break;
1972 }
1973 MP_DROP(xx); MP_DROP(yy);
1974 return (getbool(b));
1975}
1976
1977static PyObject *gf_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1978{
1979 PyObject *x;
1980 mp *z;
1981 mp_pyobj *zz = 0;
1982 int radix = 0;
827f89d7 1983 static const char *const kwlist[] = { "x", "radix", 0 };
d7ab1bab 1984
827f89d7 1985 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|i:gf", KWLIST, &x, &radix))
d7ab1bab 1986 goto end;
1987 if (GF_PYCHECK(x)) RETURN_OBJ(x);
f368b46e 1988 if (!good_radix_p(radix, 1)) VALERR("radix out of range");
d7ab1bab 1989 if ((z = mp_frompyobject(x, radix)) == 0) {
1990 PyErr_Format(PyExc_TypeError, "can't convert %.100s to gf",
2a448f86 1991 Py_TYPE(x)->tp_name);
d7ab1bab 1992 goto end;
1993 }
1994 if (MP_NEGP(z)) {
1995 MP_DROP(z);
1996 VALERR("gf cannot be negative");
1997 }
1998 zz = (mp_pyobj *)ty->tp_alloc(ty, 0);
1999 zz->x = z;
2000end:
2001 return ((PyObject *)zz);
2002}
2003
d7ab1bab 2004static PyObject *gf_pyexp(PyObject *x, PyObject *y, PyObject *z)
2005{
2006 mp *xx = 0, *yy = 0, *zz = 0;
2007 mp *r = 0;
2008 PyObject *rc = 0;
2009
6311e4f7
MW
2010 if ((xx = implicitgf(x)) == 0 || (yy = implicitmp(y)) == 0 ||
2011 (z && z != Py_None && (zz = implicitgf(z)) == 0)) {
d7ab1bab 2012 mp_drop(xx); mp_drop(yy); mp_drop(zz);
2013 RETURN_NOTIMPL;
2014 }
2015 if (!z || z == Py_None) {
2016 if (MP_NEGP(yy)) VALERR("negative exponent");
2017 r = gf_exp(MP_NEW, xx, yy);
2018 } else {
2019 gfreduce gr;
2020 if (MP_ZEROP(zz)) ZDIVERR("zero modulus");
2021 if (MP_NEGP(yy)) {
2022 if ((xx = gf_modinv_checked(xx, xx, zz)) == 0) goto end;
2023 yy = mp_neg(yy, yy);
2024 }
2025 gfreduce_create(&gr, zz);
2026 r = gfreduce_exp(&gr, MP_NEW, xx, yy);
2027 gfreduce_destroy(&gr);
2028 }
2029 rc = gf_pywrap(r);
2030end:
2031 mp_drop(xx); mp_drop(yy); mp_drop(zz);
2032 return (rc);
2033}
2034
91e56f06
MW
2035static PyObject *gfmeth_sqr(PyObject *me)
2036 { return (gf_pywrap(gf_sqr(MP_NEW, MP_X(me)))); }
d7ab1bab 2037
2038static PyObject *gfmeth_gcd(PyObject *me, PyObject *arg)
2039{
2040 PyObject *z = 0;
2041 mp *yy = 0, *zz = MP_NEW;
2042
2043 if (!PyArg_ParseTuple(arg, "O&:gcd", convgf, &yy)) goto end;
2044 gf_gcd(&zz, 0, 0, MP_X(me), yy);
2045 z = gf_pywrap(zz);
2046end:
2047 if (yy) MP_DROP(yy);
2048 return (z);
2049}
2050
2051static PyObject *gfmeth_gcdx(PyObject *me, PyObject *arg)
2052{
2053 PyObject *z = 0;
2054 mp *yy = 0, *zz = MP_NEW, *uu = MP_NEW, *vv = MP_NEW;
2055
2056 if (!PyArg_ParseTuple(arg, "O&:gcdx", convgf, &yy))
2057 goto end;
2058 gf_gcd(&zz, &uu, &vv, MP_X(me), yy);
2059 z = Py_BuildValue("(NNN)",
2060 gf_pywrap(zz), gf_pywrap(uu), gf_pywrap(vv));
2061end:
2062 if (yy) MP_DROP(yy);
2063 return (z);
2064}
2065
2066static PyObject *gfmeth_modinv(PyObject *me, PyObject *arg)
2067{
2068 PyObject *z = 0;
2069 mp *yy = 0, *zz = MP_NEW;
2070
2071 if (!PyArg_ParseTuple(arg, "O&:modinv", convgf, &yy) ||
2072 (zz = gf_modinv_checked(MP_NEW, yy, MP_X(me))) == 0)
2073 goto end;
2074 z = gf_pywrap(zz);
2075end:
2076 if (yy) MP_DROP(yy);
2077 return (z);
2078}
2079
a157093f
MW
2080static PyObject *gfmeth_fromstring(PyObject *me,
2081 PyObject *arg, PyObject *kw)
f281293c
MW
2082{
2083 int r = 0;
2084 char *p;
2085 Py_ssize_t len;
2086 PyObject *z = 0;
2087 mp *zz;
2088 mptext_stringctx sc;
a157093f 2089 static const char *const kwlist[] = { "x", "radix", 0 };
f281293c 2090
a157093f
MW
2091 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
2092 &p, &len, &r))
f281293c
MW
2093 goto end;
2094 if (!good_radix_p(r, 1)) VALERR("bad radix");
2095 sc.buf = p; sc.lim = p + len;
2096 if ((zz = mp_read(MP_NEW, r, &mptext_stringops, &sc)) == 0 ||
2097 MP_NEGP(zz)) {
2098 if (zz) MP_DROP(zz);
2099 VALERR("bad binary polynomial");
2100 }
2101 z = Py_BuildValue("(Ns#)", gf_pywrap(zz),
2102 sc.buf, (Py_ssize_t)(sc.lim - sc.buf));
2103end:
2104 return (z);
2105}
2106
91e56f06
MW
2107static PyObject *gfmeth_irreduciblep(PyObject *me)
2108 { return getbool(gf_irreduciblep(MP_X(me))); }
d7ab1bab 2109
2110static PyObject *gfget_degree(PyObject *me, void *hunoz)
2111 { return (PyInt_FromLong(mp_bits(MP_X(me)) - 1)); }
2112
c90f712e 2113static const PyGetSetDef gf_pygetset[] = {
d7ab1bab 2114#define GETSETNAME(op, name) gf##op##_##name
2115 GET (degree, "X.degree -> polynomial degree of X")
2116#undef GETSETNAME
2117#define GETSETNAME(op, name) mp##op##_##name
2118 GET (nbits, "X.nbits -> bit length of X")
2119 GET (noctets, "X.noctets -> octet length of X")
2120#undef GETSETNAME
2121 { 0 }
2122};
2123
c90f712e 2124static const PyMethodDef gf_pymethods[] = {
d7ab1bab 2125#define METHNAME(func) gfmeth_##func
2126 METH (setbit, "X.setbit(N) -> X with bit N set")
2127 METH (clearbit, "X.clearbit(N) -> X with bit N clear")
2128 METH (testbit, "X.testbit(N) -> true/false if bit N set/clear in X")
91e56f06 2129 NAMETH(sqr, "X.sqr() -> X^2")
d7ab1bab 2130 METH (gcd, "X.gcd(Y) -> gcd(X, Y)")
d96c882e 2131 METH (gcdx, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
d7ab1bab 2132 METH (modinv, "X.modinv(Y) -> multiplicative inverse of Y mod X")
91e56f06 2133 NAMETH(irreduciblep, "X.irreduciblep() -> true/false")
a157093f
MW
2134 KWSMTH(fromstring, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2135 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2136 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2137 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
ad52b46f 2138 SMTH (_implicit, 0)
a157093f
MW
2139 SMTH (loadl, "loadl(STR) -> X: read little-endian bytes")
2140 SMTH (loadb, "loadb(STR) -> X: read big-endian bytes")
2141 SMTH (frombuf, "frombuf(STR) -> (X, REST): read buffer format")
d7ab1bab 2142#undef METHNAME
2143#define METHNAME(func) mpmeth_##func
1df8d5fe
MW
2144 KWMETH(tostring, "X.tostring([radix = 10]) -> STR")
2145 KWMETH(storel, "X.storel([len = -1]) -> little-endian bytes")
2146 KWMETH(storeb, "X.storeb([len = -1]) -> big-endian bytes")
d96c882e
MW
2147 KWMETH(storel2c, "X.storel2c([len = -1]) -> "
2148 "little-endian bytes, two's complement")
2149 KWMETH(storeb2c, "X.storeb2c([len = -1]) -> "
2150 "big-endian bytes, two's complement")
91e56f06 2151 NAMETH(tobuf, "X.tobuf() -> buffer format")
d7ab1bab 2152#undef METHNAME
2153 { 0 }
2154};
2155
c90f712e 2156static const PyNumberMethods gf_pynumber = {
d7ab1bab 2157 gf_pyadd, /* @nb_add@ */
2158 gf_pysub, /* @nb_subtract@ */
2159 gf_pymul, /* @nb_multiply@ */
f7623015 2160#ifdef PY2
d7ab1bab 2161 0, /* @nb_divide@ */
f7623015 2162#endif
d7ab1bab 2163 gf_pymod, /* @nb_remainder@ */
2164 gf_pydivmod, /* @nb_divmod@ */
2165 gf_pyexp, /* @nb_power@ */
2166 mp_pyid, /* @nb_negative@ */
2167 mp_pyid, /* @nb_positive@ */
2168 mp_pyid, /* @nb_absolute@ */
2169 mp_pynonzerop, /* @nb_nonzero@ */
2170 0 /* doesn't make any sense */, /* @nb_invert@ */
2171 gf_pylsl, /* @nb_lshift@ */
2172 gf_pylsr, /* @nb_rshift@ */
2173 gf_pyand, /* @nb_and@ */
2174 gf_pyxor, /* @nb_xor@ */
2175 gf_pyor, /* @nb_or@ */
f7623015 2176#ifdef PY2
d7ab1bab 2177 gf_pycoerce, /* @nb_coerce@ */
f7623015 2178#endif
d7ab1bab 2179 mp_pyint, /* @nb_int@ */
f7623015 2180 PY23(mp_pylong, 0), /* @nb_long@ */
d7ab1bab 2181 0 /* doesn't make any sense */, /* @nb_float@ */
f7623015 2182#ifdef PY2
d7ab1bab 2183 mp_pyoct, /* @nb_oct@ */
2184 mp_pyhex, /* @nb_hex@ */
f7623015 2185#endif
d7ab1bab 2186
2187 0, /* @nb_inplace_add@ */
2188 0, /* @nb_inplace_subtract@ */
2189 0, /* @nb_inplace_multiply@ */
f7623015 2190#ifdef PY2
d7ab1bab 2191 0, /* @nb_inplace_divide@ */
f7623015 2192#endif
d7ab1bab 2193 0, /* @nb_inplace_remainder@ */
2194 0, /* @nb_inplace_power@ */
2195 0, /* @nb_inplace_lshift@ */
2196 0, /* @nb_inplace_rshift@ */
2197 0, /* @nb_inplace_and@ */
2198 0, /* @nb_inplace_xor@ */
2199 0, /* @nb_inplace_or@ */
2200
2201 gf_pydiv, /* @nb_floor_divide@ */
2202 0, /* @nb_true_divide@ */
2203 0, /* @nb_inplace_floor_divide@ */
2204 0, /* @nb_inplace_true_divide@ */
a90a9c0e
MW
2205
2206 mp_pyint, /* @nb_index@ */
d7ab1bab 2207};
2208
c263b05c 2209static const PyTypeObject gf_pytype_skel = {
591bf41b 2210 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 2211 "GF", /* @tp_name@ */
d7ab1bab 2212 sizeof(mp_pyobj), /* @tp_basicsize@ */
2213 0, /* @tp_itemsize@ */
2214
2215 mp_pydealloc, /* @tp_dealloc@ */
2216 0, /* @tp_print@ */
2217 0, /* @tp_getattr@ */
2218 0, /* @tp_setattr@ */
2219 0, /* @tp_compare@ */
2220 gf_pyrepr, /* @tp_repr@ */
c90f712e 2221 PYNUMBER(gf), /* @tp_as_number@ */
d7ab1bab 2222 0, /* @tp_as_sequence@ */
2223 0, /* @tp_as_mapping@ */
ab723d73 2224 mp_pyhash, /* @tp_hash@ */
d7ab1bab 2225 0, /* @tp_call@ */
2226 mp_pyhex, /* @tp_str@ */
2227 0, /* @tp_getattro@ */
2228 0, /* @tp_setattro@ */
2229 0, /* @tp_as_buffer@ */
2230 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2231 Py_TPFLAGS_CHECKTYPES |
2232 Py_TPFLAGS_BASETYPE,
2233
2234 /* @tp_doc@ */
d96c882e
MW
2235 "Binary polynomials. Support almost all the standard arithmetic\n"
2236 "operations.\n"
2237 "\n"
2238 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2239 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2240 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
f7623015 2241 PY23(
d96c882e 2242 "points, group elements, Python `int' and `long' objects, and anything\n"
f7623015
MW
2243 "with an integer conversion.\n",
2244 "points, group elements, Python `int' objects, and anything with an\n"
2245 "integer conversion.\n")
d96c882e
MW
2246 "\n"
2247 "The name is hopelessly wrong from a technical point of view, but\n"
2248 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2249 "\n"
2250 "Notes:\n"
2251 "\n"
2252 " * Use `//' for Euclidean division: `/' gives exact rational division.",
d7ab1bab 2253
2254 0, /* @tp_traverse@ */
2255 0, /* @tp_clear@ */
2256 gf_pyrichcompare, /* @tp_richcompare@ */
2257 0, /* @tp_weaklistoffset@ */
2258 0, /* @tp_iter@ */
963a6148 2259 0, /* @tp_iternext@ */
c90f712e 2260 PYMETHODS(gf), /* @tp_methods@ */
d7ab1bab 2261 0, /* @tp_members@ */
c90f712e 2262 PYGETSET(gf), /* @tp_getset@ */
d7ab1bab 2263 0, /* @tp_base@ */
2264 0, /* @tp_dict@ */
2265 0, /* @tp_descr_get@ */
2266 0, /* @tp_descr_set@ */
2267 0, /* @tp_dictoffset@ */
2268 0, /* @tp_init@ */
2269 PyType_GenericAlloc, /* @tp_alloc@ */
2270 gf_pynew, /* @tp_new@ */
3aa33042 2271 0, /* @tp_free@ */
d7ab1bab 2272 0 /* @tp_is_gc@ */
2273};
2274
d7ab1bab 2275/*----- Sparse poly reduction ---------------------------------------------*/
2276
c263b05c
MW
2277static PyTypeObject *gfreduce_pytype;
2278
d7ab1bab 2279typedef struct gfreduce_pyobj {
2280 PyObject_HEAD
2281 gfreduce mr;
2282} gfreduce_pyobj;
2283
2284#define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2285
2286static PyObject *grmeth_exp(PyObject *me, PyObject *arg)
2287{
2288 PyObject *rc = 0;
2289 mp *yy = 0, *zz = 0;
2290
2291 if (!PyArg_ParseTuple(arg, "O&O&:exp", convgf, &yy, convgf, &zz))
2292 goto end;
2293 if (MP_NEGP(zz)) {
2294 if ((yy = gf_modinv_checked(yy, yy, GFREDUCE_PY(me)->p)) == 0) goto end;
2295 zz = mp_neg(zz, zz);
2296 }
2297 rc = gf_pywrap(gfreduce_exp(GFREDUCE_PY(me), MP_NEW, yy, zz));
2298end:
2299 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
2300 return (rc);
2301}
2302
fbc145f3
MW
2303static PyObject *grmeth_trace(PyObject *me, PyObject *arg)
2304{
2305 PyObject *rc = 0;
2306 mp *xx = 0;
2307
2308 if (!PyArg_ParseTuple(arg, "O&:trace", convgf, &xx)) goto end;
2309 rc = PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me), xx));
2310end:
2311 if (xx) MP_DROP(xx);
2312 return (rc);
2313}
2314
2315static PyObject *grmeth_halftrace(PyObject *me, PyObject *arg)
2316{
2317 PyObject *rc = 0;
2318 mp *xx = 0;
2319
2320 if (!PyArg_ParseTuple(arg, "O&:halftrace", convgf, &xx)) goto end;
2321 rc = gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me), MP_NEW, xx));
2322end:
2323 if (xx) MP_DROP(xx);
2324 return (rc);
2325}
2326
2327static PyObject *grmeth_sqrt(PyObject *me, PyObject *arg)
2328{
2329 PyObject *rc = 0;
2330 mp *xx = 0, *yy;
2331
2332 if (!PyArg_ParseTuple(arg, "O&:sqrt", convgf, &xx)) goto end;
2333 if ((yy = gfreduce_sqrt(GFREDUCE_PY(me), MP_NEW, xx)) == 0)
2334 VALERR("no modular square root");
2335 rc = gf_pywrap(yy);
2336end:
2337 if (xx) MP_DROP(xx);
2338 return (rc);
2339}
2340
2341static PyObject *grmeth_quadsolve(PyObject *me, PyObject *arg)
2342{
2343 PyObject *rc = 0;
2344 mp *xx = 0, *yy;
2345
2346 if (!PyArg_ParseTuple(arg, "O&:quadsolve", convgf, &xx)) goto end;
2347 if ((yy = gfreduce_quadsolve(GFREDUCE_PY(me), MP_NEW, xx)) == 0)
2348 VALERR("no solution found");
2349 rc = gf_pywrap(yy);
2350end:
2351 if (xx) MP_DROP(xx);
2352 return (rc);
2353}
2354
d7ab1bab 2355static PyObject *grmeth_reduce(PyObject *me, PyObject *arg)
2356{
2357 PyObject *z = 0;
2358 mp *yy = 0;
2359
2360 if (!PyArg_ParseTuple(arg, "O&:reduce", convgf, &yy)) goto end;
2361 z = gf_pywrap(gfreduce_do(GFREDUCE_PY(me), MP_NEW, yy));
2362end:
2363 return (z);
2364}
2365
2366static void gfreduce_pydealloc(PyObject *me)
2367{
2368 gfreduce_destroy(GFREDUCE_PY(me));
3aa33042 2369 FREEOBJ(me);
d7ab1bab 2370}
2371
2372static PyObject *gfreduce_pynew(PyTypeObject *ty,
2373 PyObject *arg, PyObject *kw)
2374{
2375 gfreduce_pyobj *mr = 0;
2376 gfreduce r;
827f89d7 2377 static const char *const kwlist[] = { "m", 0 };
d7ab1bab 2378 mp *xx = 0;
2379
827f89d7 2380 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convgf, &xx))
d7ab1bab 2381 goto end;
2382 if (MP_ZEROP(xx)) ZDIVERR("modulus is zero!");
2383 gfreduce_create(&r, xx);
2384 mr = (gfreduce_pyobj *)ty->tp_alloc(ty, 0);
2385 mr->mr = r;
2386end:
2387 if (xx) MP_DROP(xx);
2388 return ((PyObject *)mr);
2389}
2390
2391static PyObject *grget_m(PyObject *me, void *hunoz)
2392 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me)->p))); }
2393
c90f712e 2394static const PyGetSetDef gfreduce_pygetset[] = {
d7ab1bab 2395#define GETSETNAME(op, name) gr##op##_##name
2396 GET (m, "R.m -> reduction polynomial")
2397#undef GETSETNAME
2398 { 0 }
2399};
2400
c90f712e 2401static const PyMethodDef gfreduce_pymethods[] = {
d7ab1bab 2402#define METHNAME(name) grmeth_##name
2403 METH (reduce, "R.reduce(X) -> X mod B.m")
fbc145f3 2404 METH (trace, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
d96c882e 2405 METH (halftrace, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
fbc145f3
MW
2406 METH (sqrt, "R.sqrt(X) -> Y where Y^2 = X mod R")
2407 METH (quadsolve, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
d7ab1bab 2408 METH (exp, "R.exp(X, N) -> X^N mod B.m")
2409#undef METHNAME
2410 { 0 }
2411};
2412
c263b05c 2413static const PyTypeObject gfreduce_pytype_skel = {
591bf41b 2414 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 2415 "GFReduce", /* @tp_name@ */
d7ab1bab 2416 sizeof(gfreduce_pyobj), /* @tp_basicsize@ */
2417 0, /* @tp_itemsize@ */
2418
2419 gfreduce_pydealloc, /* @tp_dealloc@ */
2420 0, /* @tp_print@ */
2421 0, /* @tp_getattr@ */
2422 0, /* @tp_setattr@ */
2423 0, /* @tp_compare@ */
2424 0, /* @tp_repr@ */
2425 0, /* @tp_as_number@ */
2426 0, /* @tp_as_sequence@ */
2427 0, /* @tp_as_mapping@ */
2428 0, /* @tp_hash@ */
2429 0, /* @tp_call@ */
2430 0, /* @tp_str@ */
2431 0, /* @tp_getattro@ */
2432 0, /* @tp_setattro@ */
2433 0, /* @tp_as_buffer@ */
2434 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2435 Py_TPFLAGS_BASETYPE,
2436
2437 /* @tp_doc@ */
d96c882e 2438 "GFReduce(N): a context for reduction modulo sparse polynomials.",
d7ab1bab 2439
2440 0, /* @tp_traverse@ */
2441 0, /* @tp_clear@ */
2442 0, /* @tp_richcompare@ */
2443 0, /* @tp_weaklistoffset@ */
2444 0, /* @tp_iter@ */
963a6148 2445 0, /* @tp_iternext@ */
c90f712e 2446 PYMETHODS(gfreduce), /* @tp_methods@ */
d7ab1bab 2447 0, /* @tp_members@ */
c90f712e 2448 PYGETSET(gfreduce), /* @tp_getset@ */
d7ab1bab 2449 0, /* @tp_base@ */
2450 0, /* @tp_dict@ */
2451 0, /* @tp_descr_get@ */
2452 0, /* @tp_descr_set@ */
2453 0, /* @tp_dictoffset@ */
2454 0, /* @tp_init@ */
2455 PyType_GenericAlloc, /* @tp_alloc@ */
2456 gfreduce_pynew, /* @tp_new@ */
3aa33042 2457 0, /* @tp_free@ */
d7ab1bab 2458 0 /* @tp_is_gc@ */
2459};
2460
2461/*----- Normal/poly transformation ----------------------------------------*/
2462
c263b05c
MW
2463static PyTypeObject *gfn_pytype;
2464
d7ab1bab 2465typedef struct gfn_pyobj {
2466 PyObject_HEAD
2467 mp *p;
2468 gfn ntop, pton;
2469} gfn_pyobj;
2470
d7ab1bab 2471#define GFN_P(o) (((gfn_pyobj *)(o))->p)
2472#define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2473#define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2474
2475static PyObject *gfn_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
2476{
2477 mp *p = 0, *beta = 0;
2478 gfn_pyobj *gg = 0;
827f89d7 2479 static const char *const kwlist[] = { "p", "beta", 0 };
d7ab1bab 2480
827f89d7 2481 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&:new", KWLIST,
d7ab1bab 2482 convgf, &p, convgf, &beta))
2483 goto end;
2484 gg = PyObject_New(gfn_pyobj, ty);
79ac6c22 2485 gg->p = 0;
d7ab1bab 2486 if (gfn_create(p, beta, &gg->ntop, &gg->pton)) {
79ac6c22 2487 Py_DECREF(gg);
d7ab1bab 2488 gg = 0;
2489 VALERR("can't invert transformation matrix");
2490 }
2491 gg->p = MP_COPY(p);
2492end:
2493 mp_drop(p);
2494 mp_drop(beta);
2495 return ((PyObject *)gg);
2496}
2497
2498static PyObject *gfnget_p(PyObject *me, void *hunoz)
2499 { return (gf_pywrap(MP_COPY(GFN_P(me)))); }
2500
2501static PyObject *gfnget_beta(PyObject *me, void *hunoz)
2502{
2503 gfn *n = GFN_NTOP(me);
2504 mp *x = n->r[n->n - 1];
2505 return (gf_pywrap(MP_COPY(x)));
2506}
2507
2508#define XFORMOP(name, NAME) \
2509 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2510 { \
2511 mp *xx = 0; \
2512 mp *z = 0; \
2513 \
2514 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2515 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2516 end: \
2517 mp_drop(xx); \
2518 if (!z) return (0); \
62ce807d 2519 return (gf_pywrap(z)); \
d7ab1bab 2520 }
2521XFORMOP(pton, PTON)
2522XFORMOP(ntop, NTOP)
2523#undef XFORMOP
2524
2525static void gfn_pydealloc(PyObject *me)
2526{
79ac6c22 2527 if (GFN_P(me)) {
b76bb841 2528 MP_DROP(GFN_P(me));
79ac6c22
MW
2529 gfn_destroy(GFN_PTON(me));
2530 gfn_destroy(GFN_NTOP(me));
2531 }
3aa33042 2532 FREEOBJ(me);
d7ab1bab 2533}
2534
c90f712e 2535static const PyGetSetDef gfn_pygetset[] = {
d7ab1bab 2536#define GETSETNAME(op, name) gfn##op##_##name
2537 GET (p, "X.p -> polynomial basis, as polynomial")
2538 GET (beta, "X.beta -> normal basis element, in poly form")
2539#undef GETSETNAME
2540 { 0 }
2541};
2542
c90f712e 2543static const PyMethodDef gfn_pymethods[] = {
d7ab1bab 2544#define METHNAME(name) gfnmeth_##name
2545 METH (pton, "X.pton(A) -> normal-basis representation of A")
2546 METH (ntop, "X.ntop(A) -> polynomial-basis representation of A")
2547#undef METHNAME
2548 { 0 }
2549};
2550
c263b05c 2551static const PyTypeObject gfn_pytype_skel = {
591bf41b 2552 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 2553 "GFN", /* @tp_name@ */
d7ab1bab 2554 sizeof(gfn_pyobj), /* @tp_basicsize@ */
2555 0, /* @tp_itemsize@ */
2556
2557 gfn_pydealloc, /* @tp_dealloc@ */
2558 0, /* @tp_print@ */
2559 0, /* @tp_getattr@ */
2560 0, /* @tp_setattr@ */
2561 0, /* @tp_compare@ */
2562 0, /* @tp_repr@ */
2563 0, /* @tp_as_number@ */
2564 0, /* @tp_as_sequence@ */
2565 0, /* @tp_as_mapping@ */
2566 0, /* @tp_hash@ */
2567 0, /* @tp_call@ */
2568 0, /* @tp_str@ */
2569 0, /* @tp_getattro@ */
2570 0, /* @tp_setattro@ */
2571 0, /* @tp_as_buffer@ */
2572 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2573 Py_TPFLAGS_BASETYPE,
2574
2575 /* @tp_doc@ */
d96c882e
MW
2576 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2577 " between polynomial and normal basis representations.",
d7ab1bab 2578
2579 0, /* @tp_traverse@ */
2580 0, /* @tp_clear@ */
2581 0, /* @tp_richcompare@ */
2582 0, /* @tp_weaklistoffset@ */
2583 0, /* @tp_iter@ */
963a6148 2584 0, /* @tp_iternext@ */
c90f712e 2585 PYMETHODS(gfn), /* @tp_methods@ */
d7ab1bab 2586 0, /* @tp_members@ */
c90f712e 2587 PYGETSET(gfn), /* @tp_getset@ */
d7ab1bab 2588 0, /* @tp_base@ */
2589 0, /* @tp_dict@ */
2590 0, /* @tp_descr_get@ */
2591 0, /* @tp_descr_set@ */
2592 0, /* @tp_dictoffset@ */
2593 0, /* @tp_init@ */
2594 PyType_GenericAlloc, /* @tp_alloc@ */
2595 gfn_pynew, /* @tp_new@ */
3aa33042 2596 0, /* @tp_free@ */
d7ab1bab 2597 0 /* @tp_is_gc@ */
2598};
2599
2600/*----- Glue --------------------------------------------------------------*/
2601
810542b0
MW
2602static const struct nameval consts[] = {
2603 CONST(MPW_MAX),
2604 { 0 }
2605};
2606
d7ab1bab 2607void mp_pyinit(void)
2608{
2609 INITTYPE(mp, root);
2610 INITTYPE(gf, root);
32507e35 2611 INITTYPE(mpmul, root);
d7ab1bab 2612 INITTYPE(mpmont, root);
2613 INITTYPE(mpbarrett, root);
2614 INITTYPE(mpreduce, root);
2615 INITTYPE(mpcrt, root);
2616 INITTYPE(gfreduce, root);
2617 INITTYPE(gfn, root);
d7ab1bab 2618}
2619
2620void mp_pyinsert(PyObject *mod)
2621{
2622 INSERT("MP", mp_pytype);
32507e35 2623 INSERT("MPMul", mpmul_pytype);
d7ab1bab 2624 INSERT("MPMont", mpmont_pytype);
2625 INSERT("MPBarrett", mpbarrett_pytype);
2626 INSERT("MPReduce", mpreduce_pytype);
2627 INSERT("MPCRT", mpcrt_pytype);
2628 INSERT("GF", gf_pytype);
2629 INSERT("GFReduce", gfreduce_pytype);
2630 INSERT("GFN", gfn_pytype);
810542b0 2631 setconstants(mod, consts);
d7ab1bab 2632}
2633
2634/*----- That's all, folks -------------------------------------------------*/