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