t/t-algorithms.py (HashBufferTestMixin): Assemble method names dynamically.
[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
31a298bb
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,
ff1993c7
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
d472b9a1
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
f984b31a 65 sz = Py_SIZE(l);
d7ab1bab 66 if (sz < 0) sz = -sz;
31a298bb 67 bits = (unsigned long)sz * PyLong_SHIFT;
d7ab1bab 68 w = (bits + MPW_BITS - 1)/MPW_BITS;
f984b31a 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;
31a298bb 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);
31a298bb 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;
31a298bb
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) {
31a298bb
MW
109 l->ob_digit[i++] = r & PyLong_MASK;
110 r >>= PyLong_SHIFT;
d7ab1bab 111 }
f984b31a 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
cfb291f0 120 if (TEXT_CHECK(o)) {
d7ab1bab 121 mptext_stringctx sc;
122 mp *x;
cfb291f0
MW
123 size_t sz;
124 TEXT_PTRLEN(o, sc.buf, sz); sc.lim = sc.buf + sz;
a4cc2ca5
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);
cfb291f0 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);
cfb291f0 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
9a3b6339 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)
e8cd4ca5 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
1810cc51 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);
4ea7701c 243 }
d472b9a1 244#ifdef PY2
4ea7701c 245 else if (PyInt_Check(o))
d7ab1bab 246 return (mp_fromlong(MP_NEW, PyInt_AS_LONG(o)));
d472b9a1 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",
f984b31a 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",
f984b31a 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
ef6b9516 296mp *implicitmp(PyObject *o)
bf8910bd 297{
7032ee7c
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
ef6b9516 315mp *implicitgf(PyObject *o)
bf8910bd 316{
7032ee7c
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
1810cc51
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
535b6476 405#define SHIFTOP(pre, PRE, name, rname) \
d7ab1bab 406 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
535b6476 407 PyObject *yix = 0; \
d7ab1bab 408 PyObject *z = 0; \
409 long n; \
535b6476
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 }
535b6476
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 ||
f3e22904 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); }
d472b9a1 522#ifdef PY2
d7ab1bab 523BASEOP(oct, 8, "0");
d472b9a1 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}
d472b9a1 536#ifdef PY2
d7ab1bab 537static PyObject *mp_pylong(PyObject *x)
f368b46e 538 { return (mp_topylong(MP_X(x))); }
d472b9a1 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
d472b9a1 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 } \
a70a5a80 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
d472b9a1 568#endif
d7ab1bab 569
1810cc51
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
d472b9a1 584#ifdef PY2
d7ab1bab 585static int mp_pycompare(PyObject *x, PyObject *y)
586 { return mp_cmp(MP_X(x), MP_X(y)); }
d472b9a1 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",
f984b31a 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
1e8aaf8b
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
620169ae 628Py_hash_t mphash(mp *x)
d7ab1bab 629{
be6df1c3 630 PyObject *l = mp_topylong(x);
620169ae 631 Py_hash_t h = PyObject_Hash(l);
f368b46e 632 Py_DECREF(l); return (h);
d7ab1bab 633}
634
620169ae 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
7a75bb76 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
7a75bb76
MW
685static PyObject *mpmeth_sqr(PyObject *me)
686 { return (mp_pywrap(mp_sqr(MP_NEW, MP_X(me)))); }
d7ab1bab 687
7a75bb76 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; \
f927b002 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); \
cfb291f0 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
b16009b0
MW
802#define BUFOP(ty) \
803 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
d7ab1bab 804 { \
805 buf b; \
be17c8c2 806 struct bin in; \
d7ab1bab 807 PyObject *rc = 0; \
808 mp *x; \
809 \
be17c8c2
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 }
b16009b0
MW
818BUFOP(mp)
819BUFOP(gf)
d7ab1bab 820#undef BUFOP
821
7a75bb76 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);
cfb291f0 832 buf_init(&b, BIN_PTR(rc), n);
d7ab1bab 833 buf_putmp(&b, x);
834 assert(BOK(&b));
cfb291f0 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
b16009b0
MW
852static PyObject *mpmeth_fromstring(PyObject *me,
853 PyObject *arg, PyObject *kw)
27cbcf9d
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;
b16009b0 861 static const char *const kwlist[] = { "x", "radix", 0 };
27cbcf9d 862
b16009b0
MW
863 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
864 &p, &len, &r))
27cbcf9d
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
b16009b0 876static PyObject *mpmeth_factorial(PyObject *me, PyObject *arg)
27cbcf9d
MW
877{
878 unsigned long i;
879 mp *x;
b16009b0 880 if (!PyArg_ParseTuple(arg, "O&:factorial", convulong, &i)) return (0);
27cbcf9d
MW
881 x = mp_factorial(i);
882 return mp_pywrap(x);
883}
884
b16009b0 885static PyObject *mpmeth_fibonacci(PyObject *me, PyObject *arg)
27cbcf9d
MW
886{
887 long i;
888 mp *x;
b16009b0 889 if (!PyArg_ParseTuple(arg, "l:fibonacci", &i)) return (0);
27cbcf9d
MW
890 x = mp_fibonacci(i);
891 return mp_pywrap(x);
892}
893
b16009b0
MW
894#define LOADOP(pre, name) \
895 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
27cbcf9d 896 { \
be17c8c2
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))); \
27cbcf9d 900 }
b16009b0
MW
901LOADOP(mp, loadl)
902LOADOP(mp, loadb)
903LOADOP(mp, loadl2c)
904LOADOP(mp, loadb2c)
905LOADOP(gf, loadl)
906LOADOP(gf, loadb)
27cbcf9d
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
637b9140 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
637b9140 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")
7a75bb76
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)")
ef783f91
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")
ef783f91
MW
941 METH (leastcongruent, "X.leastcongruent(B, M) -> "
942 "smallest Z >= B with Z == X (mod M)")
f3f76093 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")
ef783f91
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")
7a75bb76 951 NAMETH(tobuf, "X.tobuf() -> buffer format")
b16009b0
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.")
1e8aaf8b 956 SMTH (_implicit, 0)
b16009b0
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
637b9140 970static const PyNumberMethods mp_pynumber = {
d7ab1bab 971 mp_pyadd, /* @nb_add@ */
972 mp_pysub, /* @nb_subtract@ */
973 mp_pymul, /* @nb_multiply@ */
d472b9a1 974#ifdef PY2
d7ab1bab 975 0, /* @nb_divide@ */
d472b9a1 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@ */
d472b9a1 990#ifdef PY2
d7ab1bab 991 mp_pycoerce, /* @nb_coerce@ */
d472b9a1 992#endif
d7ab1bab 993 mp_pyint, /* @nb_int@ */
d472b9a1 994 PY23(mp_pylong, 0), /* @nb_long@ */
d7ab1bab 995 mp_pyfloat, /* @nb_float@ */
d472b9a1 996#ifdef PY2
d7ab1bab 997 mp_pyoct, /* @nb_oct@ */
998 mp_pyhex, /* @nb_hex@ */
d472b9a1 999#endif
d7ab1bab 1000
1001 0, /* @nb_inplace_add@ */
1002 0, /* @nb_inplace_subtract@ */
1003 0, /* @nb_inplace_multiply@ */
d472b9a1 1004#ifdef PY2
d7ab1bab 1005 0, /* @nb_inplace_divide@ */
d472b9a1 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@ */
8aafc119
MW
1019
1020 mp_pyint, /* @nb_index@ */
d7ab1bab 1021};
1022
ddd4720b 1023static const PyTypeObject mp_pytype_skel = {
4648f560 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@ */
d472b9a1 1033 PY23(mp_pycompare, 0), /* @tp_compare@/@tp_as_async@ */
d7ab1bab 1034 mp_pyrepr, /* @tp_repr@ */
637b9140 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@ */
ef783f91
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"
d472b9a1 1052 "convert to `" PY23("long", "int") "'.\n"
ef783f91
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"
d472b9a1 1057 PY23(
ef783f91 1058 "points, group elements, Python `int' and `long' objects, and anything\n"
d472b9a1
MW
1059 "with an integer conversion.\n",
1060 "points, group elements, Python `int' objects, and anything with an\n"
1061 "integer conversion.\n")
ef783f91
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@ */
1810cc51 1069 mp_pyrichcompare, /* @tp_richcompare@ */
d7ab1bab 1070 0, /* @tp_weaklistoffset@ */
1071 0, /* @tp_iter@ */
963a6148 1072 0, /* @tp_iternext@ */
637b9140 1073 PYMETHODS(mp), /* @tp_methods@ */
d7ab1bab 1074 0, /* @tp_members@ */
637b9140 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
ddd4720b
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");
8dd6ebb3 1114 if (PyTuple_GET_SIZE(arg) != 1)
d7ab1bab 1115 i = PyObject_GetIter(arg);
32507e35 1116 else {
8dd6ebb3 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
7a75bb76 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
637b9140 1170static const PyGetSetDef mpmul_pygetset[] = {
32507e35 1171#define GETSETNAME(op, name) mm##op##_##name
ef783f91 1172 GET (livep, "MM.livep -> flag: object still valid?")
32507e35
MW
1173#undef GETSETNAME
1174 { 0 }
1175};
1176
637b9140 1177static const PyMethodDef mpmul_pymethods[] = {
32507e35 1178#define METHNAME(name) mmmeth_##name
ef783f91 1179 METH (factor, "MM.factor(ITERABLE) or MM.factor(I, ...)")
7a75bb76 1180 NAMETH(done, "MM.done() -> PRODUCT")
32507e35
MW
1181#undef METHNAME
1182 { 0 }
1183};
1184
ddd4720b 1185static const PyTypeObject mpmul_pytype_skel = {
4648f560 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@ */
ef783f91 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@ */
637b9140 1218 PYMETHODS(mpmul), /* @tp_methods@ */
32507e35 1219 0, /* @tp_members@ */
637b9140 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
ddd4720b
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
af974107 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
af974107 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
637b9140 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
637b9140 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")
ef783f91
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")
ef783f91
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
ddd4720b 1454static const PyTypeObject mpmont_pytype_skel = {
4648f560 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@ */
ef783f91 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@ */
637b9140 1487 PYMETHODS(mpmont), /* @tp_methods@ */
d7ab1bab 1488 0, /* @tp_members@ */
637b9140 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
ddd4720b
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
af974107 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
637b9140 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
637b9140 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")
ef783f91
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
ddd4720b 1595static const PyTypeObject mpbarrett_pytype_skel = {
4648f560 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@ */
ef783f91 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@ */
637b9140 1628 PYMETHODS(mpbarrett), /* @tp_methods@ */
d7ab1bab 1629 0, /* @tp_members@ */
637b9140 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
ddd4720b
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
637b9140 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
637b9140 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
ddd4720b 1725static const PyTypeObject mpreduce_pytype_skel = {
4648f560 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@ */
ef783f91 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@ */
637b9140 1758 PYMETHODS(mpreduce), /* @tp_methods@ */
d7ab1bab 1759 0, /* @tp_members@ */
637b9140 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
ddd4720b
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);
d91d53e0 1787 PyObject *q = 0, *it, *x, *z = 0;
d7ab1bab 1788 mp *xx;
1789 mp **v = 0;
77a0d53f 1790 Py_ssize_t i = 0, n = c->k;
d7ab1bab 1791
8dd6ebb3 1792 if (PyTuple_GET_SIZE(arg) == n)
d7ab1bab 1793 q = arg;
1794 else if (!PyArg_ParseTuple(arg, "O:solve", &q))
1795 goto end;
d91d53e0
MW
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 }
d7ab1bab 1804 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
d91d53e0 1805 v[i++] = xx; xx = 0;
d7ab1bab 1806 }
d91d53e0
MW
1807 x = PyIter_Next(it);
1808 if (x) { Py_DECREF(x); VALERR("residue count mismatch"); }
1809 else if (PyErr_Occurred()) goto end;
d7ab1bab 1810 z = mp_pywrap(mpcrt_solve(c, MP_NEW, v));
1811end:
1812 if (v) {
d2d15504 1813 while (i--) MP_DROP(v[i]);
d7ab1bab 1814 xfree(v);
1815 }
d7ab1bab 1816 return (z);
1817}
1818
1819static void mpcrt_pydealloc(PyObject *me)
1820{
1821 mpcrt *c = MPCRT_PY(me);
1822 mpcrt_destroy(c);
1823 xfree(c->v);
1824}
1825
1826static PyObject *mpcrt_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1827{
1828 mpcrt_mod *v = 0;
77a0d53f 1829 Py_ssize_t n, i = 0, j;
827f89d7 1830 static const char *const kwlist[] = { "mv", 0 };
d91d53e0 1831 PyObject *q, *it = 0, *x;
d2b7e92c
MW
1832 mp *xx = MP_NEW, *y = MP_NEW, *g = MP_NEW;
1833 mpmul mm;
d7ab1bab 1834 mpcrt_pyobj *c = 0;
1835
8dd6ebb3 1836 if (PyTuple_GET_SIZE(arg) > 1)
d7ab1bab 1837 q = arg;
827f89d7 1838 else if (!PyArg_ParseTupleAndKeywords(arg, kw, "O:new", KWLIST, &q))
d7ab1bab 1839 goto end;
d91d53e0
MW
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;
d7ab1bab 1852 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
684cd535 1853 if (MP_CMP(xx, <=, MP_ZERO)) VALERR("moduli must be positive");
d91d53e0
MW
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;
d7ab1bab 1856 }
d91d53e0
MW
1857 if (PyErr_Occurred()) goto end;
1858 Py_DECREF(it); it = 0;
1859
d2b7e92c
MW
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
d7ab1bab 1869 c = (mpcrt_pyobj *)ty->tp_alloc(ty, 0);
d91d53e0 1870 mpcrt_create(&c->c, v, i, 0);
d2b7e92c 1871 mp_drop(xx); mp_drop(y); mp_drop(g);
d7ab1bab 1872 return ((PyObject *)c);
1873
1874end:
1875 if (v) {
d2d15504 1876 while (i--) MP_DROP(v[i].m);
d7ab1bab 1877 xfree(v);
1878 }
d2b7e92c 1879 mp_drop(xx); mp_drop(y); mp_drop(g);
d91d53e0 1880 Py_XDECREF(it);
d7ab1bab 1881 return (0);
1882}
1883
1884static PyObject *mcget_product(PyObject *me, void *hunoz)
1885 { return (mp_pywrap(MP_COPY(MPCRT_PY(me)->mb.m))); }
1886
1887static 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++)
8dd6ebb3 1895 PyList_SET_ITEM(q, i, mp_pywrap(c->v[i].m));
d7ab1bab 1896 return (q);
1897}
1898
637b9140 1899static const PyGetSetDef mpcrt_pygetset[] = {
d7ab1bab 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
637b9140 1907static const PyMethodDef mpcrt_pymethods[] = {
d7ab1bab 1908#define METHNAME(name) mcmeth_##name
1909 METH (solve, "C.solve([R0, R1]) -> X mod C.product")
1910#undef METHNAME
1911 { 0 }
1912};
1913
ddd4720b 1914static const PyTypeObject mpcrt_pytype_skel = {
4648f560 1915 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 1916 "MPCRT", /* @tp_name@ */
d7ab1bab 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@ */
ef783f91 1939 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
d7ab1bab 1940
1941 0, /* @tp_traverse@ */
1942 0, /* @tp_clear@ */
1943 0, /* @tp_richcompare@ */
1944 0, /* @tp_weaklistoffset@ */
1945 0, /* @tp_iter@ */
963a6148 1946 0, /* @tp_iternext@ */
637b9140 1947 PYMETHODS(mpcrt), /* @tp_methods@ */
d7ab1bab 1948 0, /* @tp_members@ */
637b9140 1949 PYGETSET(mpcrt), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 1958 0, /* @tp_free@ */
d7ab1bab 1959 0 /* @tp_is_gc@ */
1960};
1961
1962/*----- Binary polynomials ------------------------------------------------*/
1963
1964static PyObject *gf_pyrepr(PyObject *o)
e8cd4ca5 1965 { return mp_topystring(MP_X(o), 16, "GF(", "0x", ")"); }
d7ab1bab 1966
1967static PyObject *gf_pyrichcompare(PyObject *x, PyObject *y, int op)
1968{
1969 mp *xx, *yy;
1970 int xl, yl;
1971 int b;
1972
bf8910bd 1973 if (gfbinop(x, y, &xx, &yy)) RETURN_NOTIMPL;
d7ab1bab 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
1993static 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;
827f89d7 1999 static const char *const kwlist[] = { "x", "radix", 0 };
d7ab1bab 2000
827f89d7 2001 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|i:gf", KWLIST, &x, &radix))
d7ab1bab 2002 goto end;
2003 if (GF_PYCHECK(x)) RETURN_OBJ(x);
f368b46e 2004 if (!good_radix_p(radix, 1)) VALERR("radix out of range");
d7ab1bab 2005 if ((z = mp_frompyobject(x, radix)) == 0) {
2006 PyErr_Format(PyExc_TypeError, "can't convert %.100s to gf",
f984b31a 2007 Py_TYPE(x)->tp_name);
d7ab1bab 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;
2016end:
2017 return ((PyObject *)zz);
2018}
2019
d7ab1bab 2020static 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
f3e22904
MW
2026 if ((xx = implicitgf(x)) == 0 || (yy = implicitmp(y)) == 0 ||
2027 (z && z != Py_None && (zz = implicitgf(z)) == 0)) {
d7ab1bab 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);
2046end:
2047 mp_drop(xx); mp_drop(yy); mp_drop(zz);
2048 return (rc);
2049}
2050
7a75bb76
MW
2051static PyObject *gfmeth_sqr(PyObject *me)
2052 { return (gf_pywrap(gf_sqr(MP_NEW, MP_X(me)))); }
d7ab1bab 2053
2054static 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);
2062end:
2063 if (yy) MP_DROP(yy);
2064 return (z);
2065}
2066
2067static 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));
2077end:
2078 if (yy) MP_DROP(yy);
2079 return (z);
2080}
2081
2082static 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);
2091end:
2092 if (yy) MP_DROP(yy);
2093 return (z);
2094}
2095
b16009b0
MW
2096static PyObject *gfmeth_fromstring(PyObject *me,
2097 PyObject *arg, PyObject *kw)
27cbcf9d
MW
2098{
2099 int r = 0;
2100 char *p;
2101 Py_ssize_t len;
2102 PyObject *z = 0;
2103 mp *zz;
2104 mptext_stringctx sc;
b16009b0 2105 static const char *const kwlist[] = { "x", "radix", 0 };
27cbcf9d 2106
b16009b0
MW
2107 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
2108 &p, &len, &r))
27cbcf9d
MW
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));
2119end:
2120 return (z);
2121}
2122
7a75bb76
MW
2123static PyObject *gfmeth_irreduciblep(PyObject *me)
2124 { return getbool(gf_irreduciblep(MP_X(me))); }
d7ab1bab 2125
2126static PyObject *gfget_degree(PyObject *me, void *hunoz)
2127 { return (PyInt_FromLong(mp_bits(MP_X(me)) - 1)); }
2128
637b9140 2129static const PyGetSetDef gf_pygetset[] = {
d7ab1bab 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
637b9140 2140static const PyMethodDef gf_pymethods[] = {
d7ab1bab 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")
7a75bb76 2145 NAMETH(sqr, "X.sqr() -> X^2")
d7ab1bab 2146 METH (gcd, "X.gcd(Y) -> gcd(X, Y)")
ef783f91 2147 METH (gcdx, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
d7ab1bab 2148 METH (modinv, "X.modinv(Y) -> multiplicative inverse of Y mod X")
7a75bb76 2149 NAMETH(irreduciblep, "X.irreduciblep() -> true/false")
b16009b0
MW
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.")
1e8aaf8b 2154 SMTH (_implicit, 0)
b16009b0
MW
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")
d7ab1bab 2158#undef METHNAME
2159#define METHNAME(func) mpmeth_##func
1df8d5fe
MW
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")
ef783f91
MW
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")
7a75bb76 2167 NAMETH(tobuf, "X.tobuf() -> buffer format")
d7ab1bab 2168#undef METHNAME
2169 { 0 }
2170};
2171
637b9140 2172static const PyNumberMethods gf_pynumber = {
d7ab1bab 2173 gf_pyadd, /* @nb_add@ */
2174 gf_pysub, /* @nb_subtract@ */
2175 gf_pymul, /* @nb_multiply@ */
d472b9a1 2176#ifdef PY2
d7ab1bab 2177 0, /* @nb_divide@ */
d472b9a1 2178#endif
d7ab1bab 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@ */
d472b9a1 2192#ifdef PY2
d7ab1bab 2193 gf_pycoerce, /* @nb_coerce@ */
d472b9a1 2194#endif
d7ab1bab 2195 mp_pyint, /* @nb_int@ */
d472b9a1 2196 PY23(mp_pylong, 0), /* @nb_long@ */
d7ab1bab 2197 0 /* doesn't make any sense */, /* @nb_float@ */
d472b9a1 2198#ifdef PY2
d7ab1bab 2199 mp_pyoct, /* @nb_oct@ */
2200 mp_pyhex, /* @nb_hex@ */
d472b9a1 2201#endif
d7ab1bab 2202
2203 0, /* @nb_inplace_add@ */
2204 0, /* @nb_inplace_subtract@ */
2205 0, /* @nb_inplace_multiply@ */
d472b9a1 2206#ifdef PY2
d7ab1bab 2207 0, /* @nb_inplace_divide@ */
d472b9a1 2208#endif
d7ab1bab 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@ */
8aafc119
MW
2221
2222 mp_pyint, /* @nb_index@ */
d7ab1bab 2223};
2224
ddd4720b 2225static const PyTypeObject gf_pytype_skel = {
4648f560 2226 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 2227 "GF", /* @tp_name@ */
d7ab1bab 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@ */
637b9140 2237 PYNUMBER(gf), /* @tp_as_number@ */
d7ab1bab 2238 0, /* @tp_as_sequence@ */
2239 0, /* @tp_as_mapping@ */
ab723d73 2240 mp_pyhash, /* @tp_hash@ */
d7ab1bab 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@ */
ef783f91
MW
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"
d472b9a1 2257 PY23(
ef783f91 2258 "points, group elements, Python `int' and `long' objects, and anything\n"
d472b9a1
MW
2259 "with an integer conversion.\n",
2260 "points, group elements, Python `int' objects, and anything with an\n"
2261 "integer conversion.\n")
ef783f91
MW
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.",
d7ab1bab 2269
2270 0, /* @tp_traverse@ */
2271 0, /* @tp_clear@ */
2272 gf_pyrichcompare, /* @tp_richcompare@ */
2273 0, /* @tp_weaklistoffset@ */
2274 0, /* @tp_iter@ */
963a6148 2275 0, /* @tp_iternext@ */
637b9140 2276 PYMETHODS(gf), /* @tp_methods@ */
d7ab1bab 2277 0, /* @tp_members@ */
637b9140 2278 PYGETSET(gf), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 2287 0, /* @tp_free@ */
d7ab1bab 2288 0 /* @tp_is_gc@ */
2289};
2290
d7ab1bab 2291/*----- Sparse poly reduction ---------------------------------------------*/
2292
ddd4720b
MW
2293static PyTypeObject *gfreduce_pytype;
2294
d7ab1bab 2295typedef struct gfreduce_pyobj {
2296 PyObject_HEAD
2297 gfreduce mr;
2298} gfreduce_pyobj;
2299
2300#define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2301
2302static 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));
2314end:
2315 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
2316 return (rc);
2317}
2318
fbc145f3
MW
2319static 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));
2326end:
2327 if (xx) MP_DROP(xx);
2328 return (rc);
2329}
2330
2331static 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));
2338end:
2339 if (xx) MP_DROP(xx);
2340 return (rc);
2341}
2342
2343static 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);
2352end:
2353 if (xx) MP_DROP(xx);
2354 return (rc);
2355}
2356
2357static 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);
2366end:
2367 if (xx) MP_DROP(xx);
2368 return (rc);
2369}
2370
d7ab1bab 2371static 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));
2378end:
2379 return (z);
2380}
2381
2382static void gfreduce_pydealloc(PyObject *me)
2383{
2384 gfreduce_destroy(GFREDUCE_PY(me));
3aa33042 2385 FREEOBJ(me);
d7ab1bab 2386}
2387
2388static PyObject *gfreduce_pynew(PyTypeObject *ty,
2389 PyObject *arg, PyObject *kw)
2390{
2391 gfreduce_pyobj *mr = 0;
2392 gfreduce r;
827f89d7 2393 static const char *const kwlist[] = { "m", 0 };
d7ab1bab 2394 mp *xx = 0;
2395
827f89d7 2396 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convgf, &xx))
d7ab1bab 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;
2402end:
2403 if (xx) MP_DROP(xx);
2404 return ((PyObject *)mr);
2405}
2406
2407static PyObject *grget_m(PyObject *me, void *hunoz)
2408 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me)->p))); }
2409
637b9140 2410static const PyGetSetDef gfreduce_pygetset[] = {
d7ab1bab 2411#define GETSETNAME(op, name) gr##op##_##name
2412 GET (m, "R.m -> reduction polynomial")
2413#undef GETSETNAME
2414 { 0 }
2415};
2416
637b9140 2417static const PyMethodDef gfreduce_pymethods[] = {
d7ab1bab 2418#define METHNAME(name) grmeth_##name
2419 METH (reduce, "R.reduce(X) -> X mod B.m")
fbc145f3 2420 METH (trace, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
ef783f91 2421 METH (halftrace, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
fbc145f3
MW
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")
d7ab1bab 2424 METH (exp, "R.exp(X, N) -> X^N mod B.m")
2425#undef METHNAME
2426 { 0 }
2427};
2428
ddd4720b 2429static const PyTypeObject gfreduce_pytype_skel = {
4648f560 2430 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 2431 "GFReduce", /* @tp_name@ */
d7ab1bab 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@ */
ef783f91 2454 "GFReduce(N): a context for reduction modulo sparse polynomials.",
d7ab1bab 2455
2456 0, /* @tp_traverse@ */
2457 0, /* @tp_clear@ */
2458 0, /* @tp_richcompare@ */
2459 0, /* @tp_weaklistoffset@ */
2460 0, /* @tp_iter@ */
963a6148 2461 0, /* @tp_iternext@ */
637b9140 2462 PYMETHODS(gfreduce), /* @tp_methods@ */
d7ab1bab 2463 0, /* @tp_members@ */
637b9140 2464 PYGETSET(gfreduce), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 2473 0, /* @tp_free@ */
d7ab1bab 2474 0 /* @tp_is_gc@ */
2475};
2476
2477/*----- Normal/poly transformation ----------------------------------------*/
2478
ddd4720b
MW
2479static PyTypeObject *gfn_pytype;
2480
d7ab1bab 2481typedef struct gfn_pyobj {
2482 PyObject_HEAD
2483 mp *p;
2484 gfn ntop, pton;
2485} gfn_pyobj;
2486
d7ab1bab 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
2491static PyObject *gfn_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
2492{
2493 mp *p = 0, *beta = 0;
2494 gfn_pyobj *gg = 0;
827f89d7 2495 static const char *const kwlist[] = { "p", "beta", 0 };
d7ab1bab 2496
827f89d7 2497 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&:new", KWLIST,
d7ab1bab 2498 convgf, &p, convgf, &beta))
2499 goto end;
2500 gg = PyObject_New(gfn_pyobj, ty);
79ac6c22 2501 gg->p = 0;
d7ab1bab 2502 if (gfn_create(p, beta, &gg->ntop, &gg->pton)) {
79ac6c22 2503 Py_DECREF(gg);
d7ab1bab 2504 gg = 0;
2505 VALERR("can't invert transformation matrix");
2506 }
2507 gg->p = MP_COPY(p);
2508end:
2509 mp_drop(p);
2510 mp_drop(beta);
2511 return ((PyObject *)gg);
2512}
2513
2514static PyObject *gfnget_p(PyObject *me, void *hunoz)
2515 { return (gf_pywrap(MP_COPY(GFN_P(me)))); }
2516
2517static 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); \
62ce807d 2535 return (gf_pywrap(z)); \
d7ab1bab 2536 }
2537XFORMOP(pton, PTON)
2538XFORMOP(ntop, NTOP)
2539#undef XFORMOP
2540
2541static void gfn_pydealloc(PyObject *me)
2542{
79ac6c22 2543 if (GFN_P(me)) {
b76bb841 2544 MP_DROP(GFN_P(me));
79ac6c22
MW
2545 gfn_destroy(GFN_PTON(me));
2546 gfn_destroy(GFN_NTOP(me));
2547 }
3aa33042 2548 FREEOBJ(me);
d7ab1bab 2549}
2550
637b9140 2551static const PyGetSetDef gfn_pygetset[] = {
d7ab1bab 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
637b9140 2559static const PyMethodDef gfn_pymethods[] = {
d7ab1bab 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
ddd4720b 2567static const PyTypeObject gfn_pytype_skel = {
4648f560 2568 PyVarObject_HEAD_INIT(0, 0) /* Header */
c461c9b3 2569 "GFN", /* @tp_name@ */
d7ab1bab 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@ */
ef783f91
MW
2592 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2593 " between polynomial and normal basis representations.",
d7ab1bab 2594
2595 0, /* @tp_traverse@ */
2596 0, /* @tp_clear@ */
2597 0, /* @tp_richcompare@ */
2598 0, /* @tp_weaklistoffset@ */
2599 0, /* @tp_iter@ */
963a6148 2600 0, /* @tp_iternext@ */
637b9140 2601 PYMETHODS(gfn), /* @tp_methods@ */
d7ab1bab 2602 0, /* @tp_members@ */
637b9140 2603 PYGETSET(gfn), /* @tp_getset@ */
d7ab1bab 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@ */
3aa33042 2612 0, /* @tp_free@ */
d7ab1bab 2613 0 /* @tp_is_gc@ */
2614};
2615
2616/*----- Glue --------------------------------------------------------------*/
2617
cc36f2d8
MW
2618static const struct nameval consts[] = {
2619 CONST(MPW_MAX),
2620 { 0 }
2621};
2622
d7ab1bab 2623void mp_pyinit(void)
2624{
2625 INITTYPE(mp, root);
2626 INITTYPE(gf, root);
32507e35 2627 INITTYPE(mpmul, root);
d7ab1bab 2628 INITTYPE(mpmont, root);
2629 INITTYPE(mpbarrett, root);
2630 INITTYPE(mpreduce, root);
2631 INITTYPE(mpcrt, root);
2632 INITTYPE(gfreduce, root);
2633 INITTYPE(gfn, root);
d7ab1bab 2634}
2635
2636void mp_pyinsert(PyObject *mod)
2637{
2638 INSERT("MP", mp_pytype);
32507e35 2639 INSERT("MPMul", mpmul_pytype);
d7ab1bab 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);
cc36f2d8 2647 setconstants(mod, consts);
d7ab1bab 2648}
2649
2650/*----- That's all, folks -------------------------------------------------*/