3 * Multiprecision arithmetic
5 * (c) 2004 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the Python interface to Catacomb.
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.
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.
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.
27 /*----- Header files ------------------------------------------------------*/
29 #include "catacomb-python.h"
31 /*----- General utilities -------------------------------------------------*/
33 PyTypeObject
*mp_pytype
= 0;
34 PyTypeObject
*gf_pytype
= 0;
37 # define PyLong_SHIFT SHIFT
41 # define PyLong_MASK MASK
44 STATIC_ASSERT(MPW_BITS
>= PyLong_SHIFT
,
45 "Catacomb's limbs are now narrower than than Python's!");
47 mp
*mp_frompylong(PyObject
*obj
)
50 PyLongObject
*l
= (PyLongObject
*)obj
;
61 bits
= (unsigned long)sz
* PyLong_SHIFT
;
62 w
= (bits
+ MPW_BITS
- 1)/MPW_BITS
;
63 x
= mp_new(w
, Py_SIZE(l
) < 0 ? MP_NEG
: 0);
65 for (i
= 0; i
< sz
; i
++) {
66 r
|= (mpd
)l
->ob_digit
[i
] << b
;
68 while (b
>= MPW_BITS
) {
83 PyObject
*mp_topylong(mp
*x
)
85 unsigned long bits
= mp_bits(x
);
86 int sz
= (bits
+ PyLong_SHIFT
- 1)/PyLong_SHIFT
;
87 PyLongObject
*l
= _PyLong_New(sz
);
93 while (i
< sz
&& p
< x
->vl
) {
96 while (i
< sz
&& b
>= PyLong_SHIFT
) {
97 l
->ob_digit
[i
++] = r
& PyLong_MASK
;
102 while (i
< sz
&& r
) {
103 l
->ob_digit
[i
++] = r
& PyLong_MASK
;
106 Py_SIZE(l
) = (x
->f
& MP_NEG
) ?
-sz
: sz
;
107 return ((PyObject
*)l
);
110 mp
*mp_frompyobject(PyObject
*o
, int radix
)
118 TEXT_PTRLEN(o
, sc
.buf
, sz
); sc
.lim
= sc
.buf
+ sz
;
119 x
= mp_read(MP_NEW
, radix
, &mptext_stringops
, &sc
);
121 if (sc
.buf
< sc
.lim
) { MP_DROP(x
); return (0); }
124 if ((x
= tomp(o
)) != 0)
129 PyObject
*mp_topystring(mp
*x
, int radix
, const char *xpre
,
130 const char *pre
, const char *post
)
132 int len
= mptext_len(x
, radix
) + 1;
135 size_t xprelen
= xpre ?
strlen(xpre
) : 0;
136 size_t prelen
= pre ?
strlen(pre
) : 0;
137 size_t postlen
= post ?
strlen(post
) : 0;
140 TEXT_PREPAREWRITE(o
, p
, len
+ 1 + xprelen
+ prelen
+ postlen
);
142 if (xpre
) { memcpy(sc
.buf
, xpre
, xprelen
); sc
.buf
+= xprelen
; }
143 if (MP_NEGP(x
)) { *sc
.buf
++ = '-'; x
= mp_neg(x
, x
); }
144 if (pre
) { memcpy(sc
.buf
, pre
, prelen
); sc
.buf
+= prelen
; }
145 sc
.lim
= sc
.buf
+ len
;
146 mp_write(x
, radix
, &mptext_stringops
, &sc
);
147 if (post
) { memcpy(sc
.buf
, post
, postlen
); sc
.buf
+= postlen
; }
149 TEXT_DONEWRITE(o
, sc
.buf
- p
);
153 static int good_radix_p(int r
, int readp
)
155 return ((r
>= -255 && r
<= -2) ||
157 (r
>= 2 && r
<= 62));
160 PyObject
*mp_pywrap(mp
*x
)
162 mp_pyobj
*z
= PyObject_New(mp_pyobj
, mp_pytype
);
164 return ((PyObject
*)z
);
167 PyObject
*gf_pywrap(mp
*x
)
169 mp_pyobj
*z
= PyObject_New(mp_pyobj
, gf_pytype
);
171 return ((PyObject
*)z
);
174 int mp_tolong_checked(mp
*x
, long *l
, int must
)
176 static mp
*longmin
= 0, *longmax
= 0;
180 longmin
= mp_fromlong(MP_NEW
, LONG_MIN
);
181 longmax
= mp_fromlong(MP_NEW
, LONG_MAX
);
183 if (MP_CMP(x
, <, longmin
) || MP_CMP(x
, >, longmax
)) {
184 if (must
) VALERR("mp out of range for int");
193 /*----- Python interface --------------------------------------------------*/
195 static void mp_pydealloc(PyObject
*o
)
201 static PyObject
*mp_pyrepr(PyObject
*o
)
202 { return mp_topystring(MP_X(o
), 10, "MP(", 0, ")"); }
204 static PyObject
*mp_pystr(PyObject
*o
)
205 { return mp_topystring(MP_X(o
), 10, 0, 0, 0); }
207 mp
*tomp(PyObject
*o
)
212 if (!o
|| PyFloat_Check(o
))
214 else if (MP_PYCHECK(o
) || GF_PYCHECK(o
))
215 return (MP_COPY(MP_X(o
)));
216 else if (FE_PYCHECK(o
))
217 return (F_OUT(FE_F(o
), MP_NEW
, FE_X(o
)));
218 else if (PFILT_PYCHECK(o
))
219 return (MP_COPY(PFILT_F(o
)->m
));
220 else if (ECPT_PYCHECK(o
)) {
222 if (EC_ATINF(ECPT_P(o
))) return (0);
227 } else if (GE_PYCHECK(o
)) {
228 if ((x
= G_TOINT(GE_G(o
), MP_NEW
, GE_X(o
))) == 0)
231 } else if (PyInt_Check(o
))
232 return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
233 else if ((l
= PyNumber_Long(o
)) != 0) {
234 x
= mp_frompylong(l
);
243 mp
*getmp(PyObject
*o
)
247 if ((x
= tomp(o
)) == 0) {
248 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
249 Py_TYPE(o
)->tp_name
);
254 int convmp(PyObject
*o
, void *p
)
257 if ((x
= getmp(o
)) == 0) return (0);
262 mp
*getgf(PyObject
*o
)
266 if ((x
= tomp(o
)) == 0) {
267 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
268 Py_TYPE(o
)->tp_name
);
273 int convgf(PyObject
*o
, void *p
)
276 if ((x
= getgf(o
)) == 0) return (0);
281 static mp
*implicitmp(PyObject
*o
)
292 static mp
*implicitgf(PyObject
*o
)
303 static int mpbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
305 if ((*xx
= implicitmp(x
)) == 0)
307 if ((*yy
= implicitmp(y
)) == 0) {
314 static int gfbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
316 if ((*xx
= implicitgf(x
)) == 0)
318 if ((*yy
= implicitgf(y
)) == 0) {
325 #define FPBINOP(name, pyop) \
326 static PyObject *mp_py##name(PyObject *x, PyObject *y) { \
329 if (PyFloat_Check(x)) { \
330 l = mp_topylong(MP_X(y)); rc = PyNumber_##pyop(x, l); \
331 Py_DECREF(l); return (rc); \
332 } else if (PyFloat_Check(y)) { \
333 l = mp_topylong(MP_X(x)); rc = PyNumber_##pyop(l, y); \
334 Py_DECREF(l); return (rc); \
336 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
337 zz = mp_##name(MP_NEW, xx, yy); \
338 MP_DROP(xx); MP_DROP(yy); \
339 return (mp_pywrap(zz)); \
342 FPBINOP(sub
, Subtract
)
343 FPBINOP(mul
, Multiply
)
345 #define gf_and mp_and
347 #define gf_xor mp_xor
348 #define BINOP(pre, name) \
349 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
351 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
352 zz = pre##_##name(MP_NEW, xx, yy); \
353 MP_DROP(xx); MP_DROP(yy); \
354 return (pre##_pywrap(zz)); \
367 static mp
*mp_abs(mp
*d
, mp
*x
)
370 return (mp_neg(d
, x
));
376 #define UNOP(pre, name) \
377 static PyObject *pre##_py##name(PyObject *x) \
378 { return mp_pywrap(pre##_##name(MP_NEW, MP_X(x))); }
384 static PyObject
*mp_pyid(PyObject
*x
) { RETURN_OBJ(x
); }
386 #define gf_lsr mp_lsr
387 #define SHIFTOP(pre, name, rname) \
388 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
392 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
393 if (mp_tolong_checked(yy, &n, 1)) goto end; \
395 z = pre##_pywrap(mp_##rname(MP_NEW, xx, -n)); \
397 z = pre##_pywrap(mp_##name(MP_NEW, xx, n)); \
399 MP_DROP(xx); MP_DROP(yy); \
402 SHIFTOP(mp
, lsl2c
, lsr2c
)
403 SHIFTOP(mp
, lsr2c
, lsl2c
)
404 SHIFTOP(gf
, lsl
, lsr
)
405 SHIFTOP(gf
, lsr
, lsl
)
408 #define DIVOP(pre, name, qq, rr, gather) \
409 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
412 INIT_##qq(q) INIT_##rr(r) \
413 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
415 ZDIVERR("division by zero"); \
416 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
419 MP_DROP(xx); MP_DROP(yy); \
422 #define INIT_YES(p) mp *p = MP_NEW;
424 #define ARG_YES(p) &p
426 DIVOP(mp
, divmod
, YES
, YES
,
427 Py_BuildValue("(NN)", mp_pywrap(q
), mp_pywrap(r
)))
428 DIVOP(mp
, div
, YES
, NO
, mp_pywrap(q
))
429 DIVOP(mp
, mod
, NO
, YES
, mp_pywrap(r
))
430 DIVOP(gf
, divmod
, YES
, YES
,
431 Py_BuildValue("(NN)", gf_pywrap(q
), gf_pywrap(r
)))
432 DIVOP(gf
, div
, YES
, NO
, gf_pywrap(q
))
433 DIVOP(gf
, mod
, NO
, YES
, gf_pywrap(r
))
440 static mp
*mp_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
443 mp_gcd(&g
, 0, &d
, p
, x
);
444 if (!MP_EQ(g
, MP_ONE
)) {
445 MP_DROP(g
); MP_DROP(d
);
446 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
449 MP_DROP(g
); return (d
);
452 static PyObject
*mp_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
454 mp
*xx
= 0, *yy
= 0, *zz
= 0;
458 if ((xx
= implicitmp(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
459 (z
&& z
!= Py_None
&& (zz
= tomp(z
)) == 0)) {
460 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
463 if (!z
|| z
== Py_None
) {
464 if (MP_NEGP(yy
)) VALERR("negative exponent");
465 r
= mp_exp(MP_NEW
, xx
, yy
);
467 if (!MP_POSP(zz
)) VALERR("modulus must be positive");
469 if ((xx
= mp_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
474 mpmont_create(&mm
, zz
);
475 r
= mpmont_exp(&mm
, MP_NEW
, xx
, yy
);
479 mpbarrett_create(&mb
, zz
);
480 r
= mpbarrett_exp(&mb
, MP_NEW
, xx
, yy
);
481 mpbarrett_destroy(&mb
);
486 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
490 static mp
*gf_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
493 gf_gcd(&g
, 0, &d
, p
, x
);
494 if (!MP_EQ(g
, MP_ONE
)) {
495 MP_DROP(g
); MP_DROP(d
);
496 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
499 MP_DROP(g
); return (d
);
502 #define BASEOP(name, radix, pre) \
503 static PyObject *mp_py##name(PyObject *x) \
504 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
506 BASEOP(hex
, 16, "0x");
509 static int mp_pynonzerop(PyObject
*x
) { return !MP_ZEROP(MP_X(x
)); }
511 static PyObject
*mp_pyint(PyObject
*x
)
514 if (!mp_tolong_checked(MP_X(x
), &l
, 0)) return (PyInt_FromLong(l
));
515 else return mp_topylong(MP_X(x
));
517 static PyObject
*mp_pylong(PyObject
*x
)
518 { return (mp_topylong(MP_X(x
))); }
519 static PyObject
*mp_pyfloat(PyObject
*x
)
521 PyObject
*l
= mp_topylong(MP_X(x
));
522 double f
= PyLong_AsDouble(l
);
524 return (PyFloat_FromDouble(f
));
527 #define COERCE(pre, PRE) \
528 static int pre##_pycoerce(PyObject **x, PyObject **y) \
532 if (PRE##_PYCHECK(*y)) { \
533 Py_INCREF(*x); Py_INCREF(*y); \
536 if ((z = tomp(*y)) != 0) { \
538 *y = pre##_pywrap(z); \
547 static PyObject
*mp_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
551 if (PyFloat_Check(y
)) {
552 l
= mp_topylong(MP_X(x
)); rc
= PyObject_RichCompare(l
, y
, op
);
553 Py_DECREF(l
); return (rc
);
555 if (mpbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
556 rc
= enrich_compare(op
, mp_cmp(xx
, yy
));
557 MP_DROP(xx
); MP_DROP(yy
);
561 static int mp_pycompare(PyObject
*x
, PyObject
*y
)
562 { return mp_cmp(MP_X(x
), MP_X(y
)); }
564 static PyObject
*mp_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
570 static const char *const kwlist
[] = { "x", "radix", 0 };
572 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:new", KWLIST
, &x
, &radix
))
574 if (MP_PYCHECK(x
)) RETURN_OBJ(x
);
575 if (!good_radix_p(radix
, 1)) VALERR("bad radix");
576 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
577 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
578 Py_TYPE(x
)->tp_name
);
581 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
584 return ((PyObject
*)zz
);
587 Py_hash_t
mphash(mp
*x
)
589 PyObject
*l
= mp_topylong(x
);
590 Py_hash_t h
= PyObject_Hash(l
);
591 Py_DECREF(l
); return (h
);
594 static Py_hash_t
mp_pyhash(PyObject
*me
) { return (mphash(MP_X(me
))); }
596 static PyObject
*mpmeth_jacobi(PyObject
*me
, PyObject
*arg
)
601 if (!PyArg_ParseTuple(arg
, "O&:jacobi", convmp
, &y
)) goto end
;
602 z
= PyInt_FromLong(mp_jacobi(y
, MP_X(me
)));
608 #define BITOP(pre, name, c) \
609 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
612 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
613 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
615 BITOP(mp
, setbit
, 2c
);
616 BITOP(mp
, clearbit
, 2c
);
618 BITOP(gf
, clearbit
, );
621 static PyObject
*mpmeth_testbit(PyObject
*me
, PyObject
*arg
)
624 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
625 return (getbool(mp_testbit2c(MP_X(me
), i
)));
628 static PyObject
*gfmeth_testbit(PyObject
*me
, PyObject
*arg
)
631 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
632 return (getbool(mp_testbit(MP_X(me
), i
)));
635 static PyObject
*mpmeth_odd(PyObject
*me
)
640 t
= mp_odd(MP_NEW
, MP_X(me
), &s
);
641 return (Py_BuildValue("(lN)", (long)s
, mp_pywrap(t
)));
644 static PyObject
*mpmeth_sqr(PyObject
*me
)
645 { return (mp_pywrap(mp_sqr(MP_NEW
, MP_X(me
)))); }
647 static PyObject
*mpmeth_sqrt(PyObject
*me
)
649 if (MP_NEGP(MP_X(me
))) VALERR("negative root");
650 return (mp_pywrap(mp_sqrt(MP_NEW
, MP_X(me
))));
655 static PyObject
*mpmeth_gcd(PyObject
*me
, PyObject
*arg
)
657 mp
*y
= 0, *zz
= MP_NEW
;
660 if (!PyArg_ParseTuple(arg
, "O&:gcd", convmp
, &y
)) goto end
;
661 mp_gcd(&zz
, 0, 0, MP_X(me
), y
);
668 static PyObject
*mpmeth_gcdx(PyObject
*me
, PyObject
*arg
)
671 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
673 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convmp
, &yy
)) goto end
;
674 mp_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
675 z
= Py_BuildValue("(NNN)",
676 mp_pywrap(zz
), mp_pywrap(uu
), mp_pywrap(vv
));
682 static PyObject
*mpmeth_modinv(PyObject
*me
, PyObject
*arg
)
685 mp
*yy
= 0, *zz
= MP_NEW
;
687 if (!PyArg_ParseTuple(arg
, "O&:modinv", convmp
, &yy
) ||
688 (zz
= mp_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
696 static PyObject
*mpmeth_tostring(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
699 static const char *const kwlist
[] = { "radix", 0 };
700 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|i:tostring", KWLIST
, &radix
))
702 if (!good_radix_p(radix
, 0)) VALERR("bad radix");
703 return (mp_topystring(MP_X(me
), radix
, 0, 0, 0));
708 static PyObject
*mpmeth_modsqrt(PyObject
*me
, PyObject
*arg
)
711 mp
*yy
= 0, *zz
= MP_NEW
;
713 if (!PyArg_ParseTuple(arg
, "O&:modsqrt", convmp
, &yy
)) goto end
;
714 if ((zz
= mp_modsqrt(MP_NEW
, yy
, MP_X(me
))) == 0)
715 VALERR("no modular square root");
722 static PyObject
*mpmeth_leastcongruent(PyObject
*me
, PyObject
*arg
)
727 if (!PyArg_ParseTuple(arg
, "O&O&:leastcongruent", convmp
, &b
, convmp
, &m
))
729 z
= mp_leastcongruent(MP_NEW
, b
, MP_X(me
), m
);
735 #define STOREOP(name, c) \
736 static PyObject *mpmeth_##name(PyObject *me, \
737 PyObject *arg, PyObject *kw) \
740 static const char *const kwlist[] = { "len", 0 }; \
743 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
747 len = mp_octets##c(MP_X(me)); \
750 rc = bytestring_pywrap(0, len); \
751 mp_##name(MP_X(me), BIN_PTR(rc), len); \
757 STOREOP(storel2c
, 2c
)
758 STOREOP(storeb2c
, 2c
)
762 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
769 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
770 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
771 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
772 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
773 bytestring_pywrapbuf(&b)); \
781 static PyObject
*mpmeth_tobuf(PyObject
*me
)
789 n
= mp_octets(x
) + 3;
790 rc
= bytestring_pywrap(0, n
);
791 buf_init(&b
, BIN_PTR(rc
), n
);
794 BIN_SETLEN(rc
, BLEN(&b
));
798 static PyObject
*mpmeth_primep(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
800 grand
*r
= &rand_global
;
801 static const char *const kwlist
[] = { "rng", 0 };
804 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|O&", KWLIST
, convgrand
, &r
))
806 rc
= getbool(pgen_primep(MP_X(me
), r
));
811 static PyObject
*mpmeth_fromstring(PyObject
*me
,
812 PyObject
*arg
, PyObject
*kw
)
820 static const char *const kwlist
[] = { "x", "radix", 0 };
822 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
825 if (!good_radix_p(r
, 1)) VALERR("bad radix");
826 sc
.buf
= p
; sc
.lim
= p
+ len
;
827 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0)
828 VALERR("bad integer");
829 z
= Py_BuildValue("(Ns#)", mp_pywrap(zz
),
830 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
835 static PyObject
*mpmeth_factorial(PyObject
*me
, PyObject
*arg
)
839 if (!PyArg_ParseTuple(arg
, "O&:factorial", convulong
, &i
)) return (0);
844 static PyObject
*mpmeth_fibonacci(PyObject
*me
, PyObject
*arg
)
848 if (!PyArg_ParseTuple(arg
, "l:fibonacci", &i
)) return (0);
853 #define LOADOP(pre, name) \
854 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
857 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
858 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
868 static PyObject
*mpget_nbits(PyObject
*me
, void *hunoz
)
869 { return (PyInt_FromLong(mp_bits(MP_X(me
)))); }
871 static PyObject
*mpget_noctets(PyObject
*me
, void *hunoz
)
872 { return (PyInt_FromLong(mp_octets(MP_X(me
)))); }
874 static PyObject
*mpget_noctets2c(PyObject
*me
, void *hunoz
)
875 { return (PyInt_FromLong(mp_octets2c(MP_X(me
)))); }
877 static const PyGetSetDef mp_pygetset
[] = {
878 #define GETSETNAME(op, func) mp##op##_##func
879 GET (nbits
, "X.nbits -> bit length of X")
880 GET (noctets
, "X.noctets -> octet length of X")
881 GET (noctets2c
, "X.noctets2c -> two's complement octet length of X")
886 static const PyMethodDef mp_pymethods
[] = {
887 #define METHNAME(func) mpmeth_##func
888 METH (jacobi
, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
889 METH (setbit
, "X.setbit(N) -> X with bit N set")
890 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
891 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
892 NAMETH(odd
, "X.odd() -> S, T where X = 2^S T with T odd")
893 NAMETH(sqr
, "X.sqr() -> X^2")
894 NAMETH(sqrt
, "X.sqrt() -> largest integer <= sqrt(X)")
895 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
896 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
897 "with X U + Y V = gcd(X, Y)")
898 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
899 METH (modsqrt
, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
900 METH (leastcongruent
, "X.leastcongruent(B, M) -> "
901 "smallest Z >= B with Z == X (mod M)")
902 KWMETH(primep
, "X.primep([rng = rand]) -> X is prime?")
903 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
904 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
905 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
906 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
907 "little-endian bytes, two's complement")
908 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
909 "big-endian bytes, two's complement")
910 NAMETH(tobuf
, "X.tobuf() -> buffer format")
911 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
912 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
913 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
914 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
915 SMTH (factorial
, "factorial(I) -> I!: compute factorial")
916 SMTH (fibonacci
, "fibonacci(I) -> F(I): compute Fibonacci number")
917 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
918 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
919 SMTH (loadl2c
, "loadl2c(STR) -> X: "
920 "read little-endian bytes, two's complement")
921 SMTH (loadb2c
, "loadb2c(STR) -> X: "
922 "read big-endian bytes, two's complement")
923 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
928 static const PyNumberMethods mp_pynumber
= {
929 mp_pyadd
, /* @nb_add@ */
930 mp_pysub
, /* @nb_subtract@ */
931 mp_pymul
, /* @nb_multiply@ */
933 mp_pymod
, /* @nb_remainder@ */
934 mp_pydivmod
, /* @nb_divmod@ */
935 mp_pyexp
, /* @nb_power@ */
936 mp_pyneg
, /* @nb_negative@ */
937 mp_pyid
, /* @nb_positive@ */
938 mp_pyabs
, /* @nb_absolute@ */
939 mp_pynonzerop
, /* @nb_nonzero@ */
940 mp_pynot2c
, /* @nb_invert@ */
941 mp_pylsl2c
, /* @nb_lshift@ */
942 mp_pylsr2c
, /* @nb_rshift@ */
943 mp_pyand2c
, /* @nb_and@ */
944 mp_pyxor2c
, /* @nb_xor@ */
945 mp_pyor2c
, /* @nb_or@ */
946 mp_pycoerce
, /* @nb_coerce@ */
947 mp_pyint
, /* @nb_int@ */
948 mp_pylong
, /* @nb_long@ */
949 mp_pyfloat
, /* @nb_float@ */
950 mp_pyoct
, /* @nb_oct@ */
951 mp_pyhex
, /* @nb_hex@ */
953 0, /* @nb_inplace_add@ */
954 0, /* @nb_inplace_subtract@ */
955 0, /* @nb_inplace_multiply@ */
956 0, /* @nb_inplace_divide@ */
957 0, /* @nb_inplace_remainder@ */
958 0, /* @nb_inplace_power@ */
959 0, /* @nb_inplace_lshift@ */
960 0, /* @nb_inplace_rshift@ */
961 0, /* @nb_inplace_and@ */
962 0, /* @nb_inplace_xor@ */
963 0, /* @nb_inplace_or@ */
965 mp_pydiv
, /* @nb_floor_divide@ */
966 0, /* @nb_true_divide@ */
967 0, /* @nb_inplace_floor_divide@ */
968 0, /* @nb_inplace_true_divide@ */
970 mp_pyint
, /* @nb_index@ */
973 static const PyTypeObject mp_pytype_skel
= {
974 PyVarObject_HEAD_INIT(0, 0) /* Header */
975 "MP", /* @tp_name@ */
976 sizeof(mp_pyobj
), /* @tp_basicsize@ */
977 0, /* @tp_itemsize@ */
979 mp_pydealloc
, /* @tp_dealloc@ */
981 0, /* @tp_getattr@ */
982 0, /* @tp_setattr@ */
983 mp_pycompare
, /* @tp_compare@ */
984 mp_pyrepr
, /* @tp_repr@ */
985 PYNUMBER(mp
), /* @tp_as_number@ */
986 0, /* @tp_as_sequence@ */
987 0, /* @tp_as_mapping@ */
988 mp_pyhash
, /* @tp_hash@ */
990 mp_pystr
, /* @tp_str@ */
991 0, /* @tp_getattro@ */
992 0, /* @tp_setattro@ */
993 0, /* @tp_as_buffer@ */
994 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
995 Py_TPFLAGS_CHECKTYPES
|
999 "Multiprecision integers, similar to `long' but more efficient and\n"
1000 "versatile. Support all the standard arithmetic operations, with\n"
1001 "implicit conversions from `PrimeFilter', and other objects which\n"
1002 "convert to `long'.\n"
1004 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1005 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1006 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1007 "points, group elements, Python `int' and `long' objects, and anything\n"
1008 "with an integer conversion.\n"
1012 " * Use `//' for integer division: `/' gives exact rational division.",
1014 0, /* @tp_traverse@ */
1016 mp_pyrichcompare
, /* @tp_richcompare@ */
1017 0, /* @tp_weaklistoffset@ */
1019 0, /* @tp_iternext@ */
1020 PYMETHODS(mp
), /* @tp_methods@ */
1021 0, /* @tp_members@ */
1022 PYGETSET(mp
), /* @tp_getset@ */
1025 0, /* @tp_descr_get@ */
1026 0, /* @tp_descr_set@ */
1027 0, /* @tp_dictoffset@ */
1029 PyType_GenericAlloc
, /* @tp_alloc@ */
1030 mp_pynew
, /* @tp_new@ */
1035 /*----- Products of small integers ----------------------------------------*/
1037 static PyTypeObject
*mpmul_pytype
;
1039 typedef struct mpmul_pyobj
{
1045 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1046 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1048 static void mpmul_pydealloc(PyObject
*me
)
1050 if (MPMUL_LIVEP(me
))
1051 mp_drop(mpmul_done(MPMUL_PY(me
)));
1055 static PyObject
*mmmeth_factor(PyObject
*me
, PyObject
*arg
)
1060 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1061 if (PyTuple_GET_SIZE(arg
) != 1)
1062 i
= PyObject_GetIter(arg
);
1064 if ((q
= PyTuple_GET_ITEM(arg
, 0)) == 0) goto end
;
1065 if ((i
= PyObject_GetIter(q
)) == 0) {
1066 PyErr_Clear(); /* that's ok */
1067 i
= PyObject_GetIter(arg
);
1071 while ((q
= PyIter_Next(i
)) != 0) {
1072 x
= getmp(q
); Py_DECREF(q
); if (!x
) {
1076 mpmul_add(MPMUL_PY(me
), x
);
1085 static PyObject
*mmmeth_done(PyObject
*me
)
1089 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1090 x
= mpmul_done(MPMUL_PY(me
));
1091 MPMUL_LIVEP(me
) = 0;
1092 return (mp_pywrap(x
));
1097 static PyObject
*mpmul_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1101 if (kw
) TYERR("keyword arguments not allowed here");
1102 mm
= (mpmul_pyobj
*)ty
->tp_alloc(ty
, 0);
1103 mpmul_init(&mm
->mm
);
1105 if (mmmeth_factor((PyObject
*)mm
, arg
) == 0) {
1109 return ((PyObject
*)mm
);
1114 static PyObject
*mmget_livep(PyObject
*me
, void *hunoz
)
1115 { return (getbool(MPMUL_LIVEP(me
))); }
1117 static const PyGetSetDef mpmul_pygetset
[] = {
1118 #define GETSETNAME(op, name) mm##op##_##name
1119 GET (livep
, "MM.livep -> flag: object still valid?")
1124 static const PyMethodDef mpmul_pymethods
[] = {
1125 #define METHNAME(name) mmmeth_##name
1126 METH (factor
, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1127 NAMETH(done
, "MM.done() -> PRODUCT")
1132 static const PyTypeObject mpmul_pytype_skel
= {
1133 PyVarObject_HEAD_INIT(0, 0) /* Header */
1134 "MPMul", /* @tp_name@ */
1135 sizeof(mpmul_pyobj
), /* @tp_basicsize@ */
1136 0, /* @tp_itemsize@ */
1138 mpmul_pydealloc
, /* @tp_dealloc@ */
1140 0, /* @tp_getattr@ */
1141 0, /* @tp_setattr@ */
1142 0, /* @tp_compare@ */
1144 0, /* @tp_as_number@ */
1145 0, /* @tp_as_sequence@ */
1146 0, /* @tp_as_mapping@ */
1150 0, /* @tp_getattro@ */
1151 0, /* @tp_setattro@ */
1152 0, /* @tp_as_buffer@ */
1153 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1154 Py_TPFLAGS_BASETYPE
,
1157 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1159 0, /* @tp_traverse@ */
1161 0, /* @tp_richcompare@ */
1162 0, /* @tp_weaklistoffset@ */
1164 0, /* @tp_iternext@ */
1165 PYMETHODS(mpmul
), /* @tp_methods@ */
1166 0, /* @tp_members@ */
1167 PYGETSET(mpmul
), /* @tp_getset@ */
1170 0, /* @tp_descr_get@ */
1171 0, /* @tp_descr_set@ */
1172 0, /* @tp_dictoffset@ */
1174 PyType_GenericAlloc
, /* @tp_alloc@ */
1175 mpmul_pynew
, /* @tp_new@ */
1180 /*----- Montgomery reduction ----------------------------------------------*/
1182 static PyTypeObject
*mpmont_pytype
;
1184 typedef struct mpmont_pyobj
{
1189 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1191 static PyObject
*mmmeth_int(PyObject
*me
, PyObject
*arg
)
1195 mpmont
*mm
= MPMONT_PY(me
);
1197 if (!PyArg_ParseTuple(arg
, "O&:in", convmp
, &yy
))
1199 mp_div(0, &yy
, yy
, mm
->m
);
1200 z
= mp_pywrap(mpmont_mul(mm
, MP_NEW
, yy
, mm
->r2
));
1202 if (yy
) MP_DROP(yy
);
1206 static PyObject
*mmmeth_mul(PyObject
*me
, PyObject
*arg
)
1209 mp
*yy
= 0, *zz
= 0;
1211 if (!PyArg_ParseTuple(arg
, "O&O&:mul", convmp
, &yy
, convmp
, &zz
))
1213 rc
= mp_pywrap(mpmont_mul(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1215 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1219 static PyObject
*mmmeth_exp(PyObject
*me
, PyObject
*arg
)
1222 mp
*yy
= 0, *zz
= 0;
1224 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1227 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1228 zz
= mp_neg(zz
, zz
);
1230 rc
= mp_pywrap(mpmont_exp(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1232 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1236 static PyObject
*mmmeth_expr(PyObject
*me
, PyObject
*arg
)
1239 mp
*yy
= 0, *zz
= 0;
1241 if (!PyArg_ParseTuple(arg
, "O&O&:expr", convmp
, &yy
, convmp
, &zz
))
1244 yy
= mpmont_reduce(MPMONT_PY(me
), yy
, yy
);
1245 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1246 yy
= mpmont_mul(MPMONT_PY(me
), yy
, yy
, MPMONT_PY(me
)->r2
);
1247 zz
= mp_neg(zz
, zz
);
1249 rc
= mp_pywrap(mpmont_expr(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1251 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1255 static PyObject
*mm_mexpr_id(PyObject
*me
)
1256 { return mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
)); }
1258 static int mm_mexpr_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1260 mp
*xx
= 0, *yy
= 0;
1261 mp_expfactor
*f
= p
;
1262 mpmont
*mm
= MPMONT_PY(me
);
1264 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1267 xx
= mpmont_reduce(mm
, xx
, xx
);
1268 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1270 xx
= mpmont_mul(mm
, xx
, xx
, mm
->r2
);
1271 yy
= mp_neg(yy
, yy
);
1278 mp_drop(xx
); mp_drop(yy
);
1282 static PyObject
*mm_mexpr(PyObject
*me
, void *v
, int n
)
1283 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1285 static void mp_mexp_drop(void *p
)
1287 mp_expfactor
*f
= p
;
1292 static PyObject
*mmmeth_mexpr(PyObject
*me
, PyObject
*arg
)
1294 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1295 mm_mexpr_id
, mm_mexpr_fill
, mm_mexpr
, mp_mexp_drop
);
1298 static PyObject
*mp_mexp_id(PyObject
*me
)
1299 { return mp_pywrap(MP_ONE
); }
1301 static int mp_mexp_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1303 mp
*xx
= 0, *yy
= 0;
1304 mp_expfactor
*f
= p
;
1306 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1309 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1311 yy
= mp_neg(yy
, yy
);
1318 mp_drop(xx
); mp_drop(yy
);
1322 static PyObject
*mm_mexp(PyObject
*me
, void *v
, int n
)
1323 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1325 static PyObject
*mmmeth_mexp(PyObject
*me
, PyObject
*arg
)
1327 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1328 mp_mexp_id
, mp_mexp_fill
, mm_mexp
, mp_mexp_drop
);
1331 #define mmmeth_ext mmmeth_reduce
1332 static PyObject
*mmmeth_reduce(PyObject
*me
, PyObject
*arg
)
1337 if (!PyArg_ParseTuple(arg
, "O&", convmp
, &yy
)) goto end
;
1338 z
= mp_pywrap(mpmont_reduce(MPMONT_PY(me
), MP_NEW
, yy
));
1343 static void mpmont_pydealloc(PyObject
*me
)
1345 mpmont_destroy(MPMONT_PY(me
));
1349 static PyObject
*mpmont_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1351 mpmont_pyobj
*mm
= 0;
1352 static const char *const kwlist
[] = { "m", 0 };
1355 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1357 if (!MP_POSP(xx
) || !MP_ODDP(xx
)) VALERR("m must be positive and odd");
1358 mm
= (mpmont_pyobj
*)ty
->tp_alloc(ty
, 0);
1359 mpmont_create(&mm
->mm
, xx
);
1361 if (xx
) MP_DROP(xx
);
1362 return ((PyObject
*)mm
);
1365 static PyObject
*mmget_m(PyObject
*me
, void *hunoz
)
1366 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->m
))); }
1368 static PyObject
*mmget_r(PyObject
*me
, void *hunoz
)
1369 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
))); }
1371 static PyObject
*mmget_r2(PyObject
*me
, void *hunoz
)
1372 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r2
))); }
1374 static const PyGetSetDef mpmont_pygetset
[] = {
1375 #define GETSETNAME(op, name) mm##op##_##name
1376 GET (m
, "M.m -> modulus for reduction")
1377 GET (r
, "M.r -> multiplicative identity")
1378 GET (r2
, "M.r2 -> M.r^2, Montgomerization factor")
1383 static const PyMethodDef mpmont_pymethods
[] = {
1384 #define METHNAME(name) mmmeth_##name
1385 METH (int, "M.int(X) -> XR")
1386 METH (mul
, "M.mul(XR, YR) -> ZR where Z = X Y")
1387 METH (expr
, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1388 METH (mexpr
, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1389 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1390 "\t(the list may be flattened if this more convenient.)")
1391 METH (reduce
, "M.reduce(XR) -> X")
1392 METH (ext
, "M.ext(XR) -> X")
1393 METH (exp
, "M.exp(X, N) -> X^N mod M.m")
1394 METH (mexp
, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1395 "X0^N0 X1^N1 ... mod M.m\n"
1396 "\t(the list may be flattened if this more convenient.)")
1401 static const PyTypeObject mpmont_pytype_skel
= {
1402 PyVarObject_HEAD_INIT(0, 0) /* Header */
1403 "MPMont", /* @tp_name@ */
1404 sizeof(mpmont_pyobj
), /* @tp_basicsize@ */
1405 0, /* @tp_itemsize@ */
1407 mpmont_pydealloc
, /* @tp_dealloc@ */
1409 0, /* @tp_getattr@ */
1410 0, /* @tp_setattr@ */
1411 0, /* @tp_compare@ */
1413 0, /* @tp_as_number@ */
1414 0, /* @tp_as_sequence@ */
1415 0, /* @tp_as_mapping@ */
1419 0, /* @tp_getattro@ */
1420 0, /* @tp_setattro@ */
1421 0, /* @tp_as_buffer@ */
1422 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1423 Py_TPFLAGS_BASETYPE
,
1426 "MPMont(N): a Montgomery reduction context.",
1428 0, /* @tp_traverse@ */
1430 0, /* @tp_richcompare@ */
1431 0, /* @tp_weaklistoffset@ */
1433 0, /* @tp_iternext@ */
1434 PYMETHODS(mpmont
), /* @tp_methods@ */
1435 0, /* @tp_members@ */
1436 PYGETSET(mpmont
), /* @tp_getset@ */
1439 0, /* @tp_descr_get@ */
1440 0, /* @tp_descr_set@ */
1441 0, /* @tp_dictoffset@ */
1443 PyType_GenericAlloc
, /* @tp_alloc@ */
1444 mpmont_pynew
, /* @tp_new@ */
1449 /*----- Barrett reduction -------------------------------------------------*/
1451 static PyTypeObject
*mpbarrett_pytype
;
1453 typedef struct mpbarrett_pyobj
{
1458 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1460 static PyObject
*mbmeth_exp(PyObject
*me
, PyObject
*arg
)
1463 mp
*yy
= 0, *zz
= 0;
1465 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1468 if ((yy
= mp_modinv_checked(yy
, yy
, MPBARRETT_PY(me
)->m
)) == 0) goto end
;
1469 zz
= mp_neg(zz
, zz
);
1471 rc
= mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me
), MP_NEW
, yy
, zz
));
1473 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1477 static PyObject
*mb_mexp(PyObject
*me
, void *v
, int n
)
1478 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me
), MP_NEW
, v
, n
)); }
1480 static PyObject
*mbmeth_mexp(PyObject
*me
, PyObject
*arg
)
1482 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1483 mp_mexp_id
, mp_mexp_fill
, mb_mexp
, mp_mexp_drop
);
1486 static PyObject
*mbmeth_reduce(PyObject
*me
, PyObject
*arg
)
1491 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
))
1493 z
= mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me
), MP_NEW
, yy
));
1498 static void mpbarrett_pydealloc(PyObject
*me
)
1500 mpbarrett_destroy(MPBARRETT_PY(me
));
1504 static PyObject
*mpbarrett_pynew(PyTypeObject
*ty
,
1505 PyObject
*arg
, PyObject
*kw
)
1507 mpbarrett_pyobj
*mb
= 0;
1508 static const char *const kwlist
[] = { "m", 0 };
1511 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1513 if (!MP_POSP(xx
)) VALERR("m must be positive");
1514 mb
= (mpbarrett_pyobj
*)ty
->tp_alloc(ty
, 0);
1515 mpbarrett_create(&mb
->mb
, xx
);
1517 if (xx
) MP_DROP(xx
);
1518 return ((PyObject
*)mb
);
1521 static PyObject
*mbget_m(PyObject
*me
, void *hunoz
)
1522 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me
)->m
))); }
1524 static const PyGetSetDef mpbarrett_pygetset
[] = {
1525 #define GETSETNAME(op, name) mb##op##_##name
1526 GET (m
, "B.m -> modulus for reduction")
1531 static const PyMethodDef mpbarrett_pymethods
[] = {
1532 #define METHNAME(name) mbmeth_##name
1533 METH (reduce
, "B.reduce(X) -> X mod B.m")
1534 METH (exp
, "B.exp(X, N) -> X^N mod B.m")
1535 METH (mexp
, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1536 "X0^N0 X1^N1 ... mod B.m\n"
1537 "\t(the list may be flattened if this more convenient.)")
1542 static const PyTypeObject mpbarrett_pytype_skel
= {
1543 PyVarObject_HEAD_INIT(0, 0) /* Header */
1544 "MPBarrett", /* @tp_name@ */
1545 sizeof(mpbarrett_pyobj
), /* @tp_basicsize@ */
1546 0, /* @tp_itemsize@ */
1548 mpbarrett_pydealloc
, /* @tp_dealloc@ */
1550 0, /* @tp_getattr@ */
1551 0, /* @tp_setattr@ */
1552 0, /* @tp_compare@ */
1554 0, /* @tp_as_number@ */
1555 0, /* @tp_as_sequence@ */
1556 0, /* @tp_as_mapping@ */
1560 0, /* @tp_getattro@ */
1561 0, /* @tp_setattro@ */
1562 0, /* @tp_as_buffer@ */
1563 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1564 Py_TPFLAGS_BASETYPE
,
1567 "MPBarrett(N): a Barrett reduction context.",
1569 0, /* @tp_traverse@ */
1571 0, /* @tp_richcompare@ */
1572 0, /* @tp_weaklistoffset@ */
1574 0, /* @tp_iternext@ */
1575 PYMETHODS(mpbarrett
), /* @tp_methods@ */
1576 0, /* @tp_members@ */
1577 PYGETSET(mpbarrett
), /* @tp_getset@ */
1580 0, /* @tp_descr_get@ */
1581 0, /* @tp_descr_set@ */
1582 0, /* @tp_dictoffset@ */
1584 PyType_GenericAlloc
, /* @tp_alloc@ */
1585 mpbarrett_pynew
, /* @tp_new@ */
1590 /*----- Nice prime reduction ----------------------------------------------*/
1592 static PyTypeObject
*mpreduce_pytype
;
1594 typedef struct mpreduce_pyobj
{
1599 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1601 static PyObject
*mrmeth_exp(PyObject
*me
, PyObject
*arg
)
1604 mp
*yy
= 0, *zz
= 0;
1606 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1609 if ((yy
= mp_modinv_checked(yy
, yy
, MPREDUCE_PY(me
)->p
)) == 0) goto end
;
1610 zz
= mp_neg(zz
, zz
);
1612 rc
= mp_pywrap(mpreduce_exp(MPREDUCE_PY(me
), MP_NEW
, yy
, zz
));
1614 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1618 static PyObject
*mrmeth_reduce(PyObject
*me
, PyObject
*arg
)
1623 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
)) goto end
;
1624 z
= mp_pywrap(mpreduce_do(MPREDUCE_PY(me
), MP_NEW
, yy
));
1629 static void mpreduce_pydealloc(PyObject
*me
)
1631 mpreduce_destroy(MPREDUCE_PY(me
));
1635 static PyObject
*mpreduce_pynew(PyTypeObject
*ty
,
1636 PyObject
*arg
, PyObject
*kw
)
1638 mpreduce_pyobj
*mr
= 0;
1640 static const char *const kwlist
[] = { "m", 0 };
1643 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1645 if (!MP_POSP(xx
)) VALERR("m must be positive");
1646 if (mpreduce_create(&r
, xx
)) VALERR("bad modulus (must be 2^k - ...)");
1647 mr
= (mpreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
1650 if (xx
) MP_DROP(xx
);
1651 return ((PyObject
*)mr
);
1654 static PyObject
*mrget_m(PyObject
*me
, void *hunoz
)
1655 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me
)->p
))); }
1657 static const PyGetSetDef mpreduce_pygetset
[] = {
1658 #define GETSETNAME(op, name) mr##op##_##name
1659 GET (m
, "R.m -> modulus for reduction")
1664 static const const PyMethodDef mpreduce_pymethods
[] = {
1665 #define METHNAME(name) mrmeth_##name
1666 METH (reduce
, "R.reduce(X) -> X mod B.m")
1667 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
1672 static const PyTypeObject mpreduce_pytype_skel
= {
1673 PyVarObject_HEAD_INIT(0, 0) /* Header */
1674 "MPReduce", /* @tp_name@ */
1675 sizeof(mpreduce_pyobj
), /* @tp_basicsize@ */
1676 0, /* @tp_itemsize@ */
1678 mpreduce_pydealloc
, /* @tp_dealloc@ */
1680 0, /* @tp_getattr@ */
1681 0, /* @tp_setattr@ */
1682 0, /* @tp_compare@ */
1684 0, /* @tp_as_number@ */
1685 0, /* @tp_as_sequence@ */
1686 0, /* @tp_as_mapping@ */
1690 0, /* @tp_getattro@ */
1691 0, /* @tp_setattro@ */
1692 0, /* @tp_as_buffer@ */
1693 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1694 Py_TPFLAGS_BASETYPE
,
1697 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1699 0, /* @tp_traverse@ */
1701 0, /* @tp_richcompare@ */
1702 0, /* @tp_weaklistoffset@ */
1704 0, /* @tp_iternext@ */
1705 PYMETHODS(mpreduce
), /* @tp_methods@ */
1706 0, /* @tp_members@ */
1707 PYGETSET(mpreduce
), /* @tp_getset@ */
1710 0, /* @tp_descr_get@ */
1711 0, /* @tp_descr_set@ */
1712 0, /* @tp_dictoffset@ */
1714 PyType_GenericAlloc
, /* @tp_alloc@ */
1715 mpreduce_pynew
, /* @tp_new@ */
1720 /*----- Chinese Remainder Theorem solution --------------------------------*/
1722 static PyTypeObject
*mpcrt_pytype
;
1724 typedef struct mpcrt_pyobj
{
1729 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1731 static PyObject
*mcmeth_solve(PyObject
*me
, PyObject
*arg
)
1733 mpcrt
*c
= MPCRT_PY(me
);
1734 PyObject
*q
= 0, *x
, *z
= 0;
1737 Py_ssize_t i
= 0, n
= c
->k
;
1740 if (PyTuple_GET_SIZE(arg
) == n
)
1742 else if (!PyArg_ParseTuple(arg
, "O:solve", &q
))
1745 if (!PySequence_Check(q
)) TYERR("want a sequence of residues");
1746 i
= PySequence_Size(q
); if (i
< 0) goto end
;
1747 if (i
!= n
) VALERR("residue count mismatch");
1748 v
= xmalloc(n
* sizeof(*v
));
1749 for (i
= 0; i
< n
; i
++) {
1750 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1751 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1754 z
= mp_pywrap(mpcrt_solve(c
, MP_NEW
, v
));
1758 for (i
= 0; i
< n
; i
++)
1767 static void mpcrt_pydealloc(PyObject
*me
)
1769 mpcrt
*c
= MPCRT_PY(me
);
1774 static PyObject
*mpcrt_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1777 Py_ssize_t n
, i
= 0, j
;
1778 static const char *const kwlist
[] = { "mv", 0 };
1779 PyObject
*q
= 0, *x
;
1780 mp
*xx
= MP_NEW
, *y
= MP_NEW
, *g
= MP_NEW
;
1784 if (PyTuple_GET_SIZE(arg
) > 1)
1786 else if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O:new", KWLIST
, &q
))
1789 if (!PySequence_Check(q
)) TYERR("want a sequence of moduli");
1790 n
= PySequence_Size(q
); if (n
< 0) goto end
;
1791 if (!n
) VALERR("want at least one modulus");
1792 v
= xmalloc(n
* sizeof(*v
));
1793 for (i
= 0; i
< n
; i
++) {
1794 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1795 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1796 if (MP_CMP(xx
, <=, MP_ZERO
)) VALERR("moduli must be positive");
1797 v
[i
].m
= xx
; v
[i
].n
= 0; v
[i
].ni
= 0; v
[i
].nni
= 0; xx
= MP_NEW
;
1800 for (j
= 0; j
< i
; j
++) mpmul_add(&mm
, v
[j
].m
);
1801 xx
= mpmul_done(&mm
);
1802 for (j
= 0; j
< i
; j
++) {
1803 mp_div(&y
, 0, xx
, v
[j
].m
);
1804 mp_gcd(&g
, 0, 0, y
, v
[j
].m
);
1805 if (!MP_EQ(g
, MP_ONE
)) VALERR("moduli must be pairwise coprime");
1808 c
= (mpcrt_pyobj
*)ty
->tp_alloc(ty
, 0);
1809 mpcrt_create(&c
->c
, v
, n
, 0);
1811 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1812 return ((PyObject
*)c
);
1817 for (i
= 0; i
< n
; i
++)
1822 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1826 static PyObject
*mcget_product(PyObject
*me
, void *hunoz
)
1827 { return (mp_pywrap(MP_COPY(MPCRT_PY(me
)->mb
.m
))); }
1829 static PyObject
*mcget_moduli(PyObject
*me
, void *hunoz
)
1833 mpcrt
*c
= MPCRT_PY(me
);
1835 if ((q
= PyList_New(c
->k
)) == 0) return (0);
1836 for (i
= 0; i
< c
->k
; i
++)
1837 PyList_SET_ITEM(q
, i
, mp_pywrap(c
->v
[i
].m
));
1841 static const PyGetSetDef mpcrt_pygetset
[] = {
1842 #define GETSETNAME(op, name) mc##op##_##name
1843 GET (product
, "C.product -> product of moduli")
1844 GET (moduli
, "C.moduli -> list of individual moduli")
1849 static const PyMethodDef mpcrt_pymethods
[] = {
1850 #define METHNAME(name) mcmeth_##name
1851 METH (solve
, "C.solve([R0, R1]) -> X mod C.product")
1856 static const PyTypeObject mpcrt_pytype_skel
= {
1857 PyVarObject_HEAD_INIT(0, 0) /* Header */
1858 "MPCRT", /* @tp_name@ */
1859 sizeof(mpcrt_pyobj
), /* @tp_basicsize@ */
1860 0, /* @tp_itemsize@ */
1862 mpcrt_pydealloc
, /* @tp_dealloc@ */
1864 0, /* @tp_getattr@ */
1865 0, /* @tp_setattr@ */
1866 0, /* @tp_compare@ */
1868 0, /* @tp_as_number@ */
1869 0, /* @tp_as_sequence@ */
1870 0, /* @tp_as_mapping@ */
1874 0, /* @tp_getattro@ */
1875 0, /* @tp_setattro@ */
1876 0, /* @tp_as_buffer@ */
1877 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1878 Py_TPFLAGS_BASETYPE
,
1881 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1883 0, /* @tp_traverse@ */
1885 0, /* @tp_richcompare@ */
1886 0, /* @tp_weaklistoffset@ */
1888 0, /* @tp_iternext@ */
1889 PYMETHODS(mpcrt
), /* @tp_methods@ */
1890 0, /* @tp_members@ */
1891 PYGETSET(mpcrt
), /* @tp_getset@ */
1894 0, /* @tp_descr_get@ */
1895 0, /* @tp_descr_set@ */
1896 0, /* @tp_dictoffset@ */
1898 PyType_GenericAlloc
, /* @tp_alloc@ */
1899 mpcrt_pynew
, /* @tp_new@ */
1904 /*----- Binary polynomials ------------------------------------------------*/
1906 static PyObject
*gf_pyrepr(PyObject
*o
)
1907 { return mp_topystring(MP_X(o
), 16, "GF(", "0x", ")"); }
1909 static PyObject
*gf_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
1915 if (gfbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
1917 case Py_EQ
: b
= MP_EQ(xx
, yy
); break;
1918 case Py_NE
: b
= !MP_EQ(xx
, yy
); break;
1923 case Py_LT
: b
= xl
< yl
; break;
1924 case Py_LE
: b
= xl
<= yl
; break;
1925 case Py_GT
: b
= xl
> yl
; break;
1926 case Py_GE
: b
= xl
>= yl
; break;
1931 MP_DROP(xx
); MP_DROP(yy
);
1932 return (getbool(b
));
1935 static PyObject
*gf_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1941 static const char *const kwlist
[] = { "x", "radix", 0 };
1943 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:gf", KWLIST
, &x
, &radix
))
1945 if (GF_PYCHECK(x
)) RETURN_OBJ(x
);
1946 if (!good_radix_p(radix
, 1)) VALERR("radix out of range");
1947 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
1948 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
1949 Py_TYPE(x
)->tp_name
);
1954 VALERR("gf cannot be negative");
1956 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
1959 return ((PyObject
*)zz
);
1962 static PyObject
*gf_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
1964 mp
*xx
= 0, *yy
= 0, *zz
= 0;
1968 if ((xx
= tomp(x
)) == 0 || (yy
= tomp(y
)) == 0 ||
1969 (z
&& z
!= Py_None
&& (zz
= tomp(z
)) == 0)) {
1970 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
1973 if (!z
|| z
== Py_None
) {
1974 if (MP_NEGP(yy
)) VALERR("negative exponent");
1975 r
= gf_exp(MP_NEW
, xx
, yy
);
1978 if (MP_ZEROP(zz
)) ZDIVERR("zero modulus");
1980 if ((xx
= gf_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
1981 yy
= mp_neg(yy
, yy
);
1983 gfreduce_create(&gr
, zz
);
1984 r
= gfreduce_exp(&gr
, MP_NEW
, xx
, yy
);
1985 gfreduce_destroy(&gr
);
1989 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
1993 static PyObject
*gfmeth_sqr(PyObject
*me
)
1994 { return (gf_pywrap(gf_sqr(MP_NEW
, MP_X(me
)))); }
1996 static PyObject
*gfmeth_gcd(PyObject
*me
, PyObject
*arg
)
1999 mp
*yy
= 0, *zz
= MP_NEW
;
2001 if (!PyArg_ParseTuple(arg
, "O&:gcd", convgf
, &yy
)) goto end
;
2002 gf_gcd(&zz
, 0, 0, MP_X(me
), yy
);
2005 if (yy
) MP_DROP(yy
);
2009 static PyObject
*gfmeth_gcdx(PyObject
*me
, PyObject
*arg
)
2012 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
2014 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convgf
, &yy
))
2016 gf_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
2017 z
= Py_BuildValue("(NNN)",
2018 gf_pywrap(zz
), gf_pywrap(uu
), gf_pywrap(vv
));
2020 if (yy
) MP_DROP(yy
);
2024 static PyObject
*gfmeth_modinv(PyObject
*me
, PyObject
*arg
)
2027 mp
*yy
= 0, *zz
= MP_NEW
;
2029 if (!PyArg_ParseTuple(arg
, "O&:modinv", convgf
, &yy
) ||
2030 (zz
= gf_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
2034 if (yy
) MP_DROP(yy
);
2038 static PyObject
*gfmeth_fromstring(PyObject
*me
,
2039 PyObject
*arg
, PyObject
*kw
)
2046 mptext_stringctx sc
;
2047 static const char *const kwlist
[] = { "x", "radix", 0 };
2049 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
2052 if (!good_radix_p(r
, 1)) VALERR("bad radix");
2053 sc
.buf
= p
; sc
.lim
= p
+ len
;
2054 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0 ||
2056 if (zz
) MP_DROP(zz
);
2057 VALERR("bad binary polynomial");
2059 z
= Py_BuildValue("(Ns#)", gf_pywrap(zz
),
2060 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
2065 static PyObject
*gfmeth_irreduciblep(PyObject
*me
)
2066 { return getbool(gf_irreduciblep(MP_X(me
))); }
2068 static PyObject
*gfget_degree(PyObject
*me
, void *hunoz
)
2069 { return (PyInt_FromLong(mp_bits(MP_X(me
)) - 1)); }
2071 static const PyGetSetDef gf_pygetset
[] = {
2072 #define GETSETNAME(op, name) gf##op##_##name
2073 GET (degree
, "X.degree -> polynomial degree of X")
2075 #define GETSETNAME(op, name) mp##op##_##name
2076 GET (nbits
, "X.nbits -> bit length of X")
2077 GET (noctets
, "X.noctets -> octet length of X")
2082 static const PyMethodDef gf_pymethods
[] = {
2083 #define METHNAME(func) gfmeth_##func
2084 METH (setbit
, "X.setbit(N) -> X with bit N set")
2085 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
2086 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
2087 NAMETH(sqr
, "X.sqr() -> X^2")
2088 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
2089 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2090 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2091 NAMETH(irreduciblep
, "X.irreduciblep() -> true/false")
2092 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2093 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2094 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2095 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2096 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
2097 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
2098 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
2100 #define METHNAME(func) mpmeth_##func
2101 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
2102 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
2103 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
2104 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
2105 "little-endian bytes, two's complement")
2106 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
2107 "big-endian bytes, two's complement")
2108 NAMETH(tobuf
, "X.tobuf() -> buffer format")
2113 static const PyNumberMethods gf_pynumber
= {
2114 gf_pyadd
, /* @nb_add@ */
2115 gf_pysub
, /* @nb_subtract@ */
2116 gf_pymul
, /* @nb_multiply@ */
2117 0, /* @nb_divide@ */
2118 gf_pymod
, /* @nb_remainder@ */
2119 gf_pydivmod
, /* @nb_divmod@ */
2120 gf_pyexp
, /* @nb_power@ */
2121 mp_pyid
, /* @nb_negative@ */
2122 mp_pyid
, /* @nb_positive@ */
2123 mp_pyid
, /* @nb_absolute@ */
2124 mp_pynonzerop
, /* @nb_nonzero@ */
2125 0 /* doesn't make any sense */, /* @nb_invert@ */
2126 gf_pylsl
, /* @nb_lshift@ */
2127 gf_pylsr
, /* @nb_rshift@ */
2128 gf_pyand
, /* @nb_and@ */
2129 gf_pyxor
, /* @nb_xor@ */
2130 gf_pyor
, /* @nb_or@ */
2131 gf_pycoerce
, /* @nb_coerce@ */
2132 mp_pyint
, /* @nb_int@ */
2133 mp_pylong
, /* @nb_long@ */
2134 0 /* doesn't make any sense */, /* @nb_float@ */
2135 mp_pyoct
, /* @nb_oct@ */
2136 mp_pyhex
, /* @nb_hex@ */
2138 0, /* @nb_inplace_add@ */
2139 0, /* @nb_inplace_subtract@ */
2140 0, /* @nb_inplace_multiply@ */
2141 0, /* @nb_inplace_divide@ */
2142 0, /* @nb_inplace_remainder@ */
2143 0, /* @nb_inplace_power@ */
2144 0, /* @nb_inplace_lshift@ */
2145 0, /* @nb_inplace_rshift@ */
2146 0, /* @nb_inplace_and@ */
2147 0, /* @nb_inplace_xor@ */
2148 0, /* @nb_inplace_or@ */
2150 gf_pydiv
, /* @nb_floor_divide@ */
2151 0, /* @nb_true_divide@ */
2152 0, /* @nb_inplace_floor_divide@ */
2153 0, /* @nb_inplace_true_divide@ */
2155 mp_pyint
, /* @nb_index@ */
2158 static const PyTypeObject gf_pytype_skel
= {
2159 PyVarObject_HEAD_INIT(0, 0) /* Header */
2160 "GF", /* @tp_name@ */
2161 sizeof(mp_pyobj
), /* @tp_basicsize@ */
2162 0, /* @tp_itemsize@ */
2164 mp_pydealloc
, /* @tp_dealloc@ */
2166 0, /* @tp_getattr@ */
2167 0, /* @tp_setattr@ */
2168 0, /* @tp_compare@ */
2169 gf_pyrepr
, /* @tp_repr@ */
2170 PYNUMBER(gf
), /* @tp_as_number@ */
2171 0, /* @tp_as_sequence@ */
2172 0, /* @tp_as_mapping@ */
2173 mp_pyhash
, /* @tp_hash@ */
2175 mp_pyhex
, /* @tp_str@ */
2176 0, /* @tp_getattro@ */
2177 0, /* @tp_setattro@ */
2178 0, /* @tp_as_buffer@ */
2179 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2180 Py_TPFLAGS_CHECKTYPES
|
2181 Py_TPFLAGS_BASETYPE
,
2184 "Binary polynomials. Support almost all the standard arithmetic\n"
2187 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2188 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2189 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2190 "points, group elements, Python `int' and `long' objects, and anything\n"
2191 "with an integer conversion.\n"
2193 "The name is hopelessly wrong from a technical point of view, but\n"
2194 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2198 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2200 0, /* @tp_traverse@ */
2202 gf_pyrichcompare
, /* @tp_richcompare@ */
2203 0, /* @tp_weaklistoffset@ */
2205 0, /* @tp_iternext@ */
2206 PYMETHODS(gf
), /* @tp_methods@ */
2207 0, /* @tp_members@ */
2208 PYGETSET(gf
), /* @tp_getset@ */
2211 0, /* @tp_descr_get@ */
2212 0, /* @tp_descr_set@ */
2213 0, /* @tp_dictoffset@ */
2215 PyType_GenericAlloc
, /* @tp_alloc@ */
2216 gf_pynew
, /* @tp_new@ */
2221 /*----- Sparse poly reduction ---------------------------------------------*/
2223 static PyTypeObject
*gfreduce_pytype
;
2225 typedef struct gfreduce_pyobj
{
2230 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2232 static PyObject
*grmeth_exp(PyObject
*me
, PyObject
*arg
)
2235 mp
*yy
= 0, *zz
= 0;
2237 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convgf
, &yy
, convgf
, &zz
))
2240 if ((yy
= gf_modinv_checked(yy
, yy
, GFREDUCE_PY(me
)->p
)) == 0) goto end
;
2241 zz
= mp_neg(zz
, zz
);
2243 rc
= gf_pywrap(gfreduce_exp(GFREDUCE_PY(me
), MP_NEW
, yy
, zz
));
2245 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
2249 static PyObject
*grmeth_trace(PyObject
*me
, PyObject
*arg
)
2254 if (!PyArg_ParseTuple(arg
, "O&:trace", convgf
, &xx
)) goto end
;
2255 rc
= PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me
), xx
));
2257 if (xx
) MP_DROP(xx
);
2261 static PyObject
*grmeth_halftrace(PyObject
*me
, PyObject
*arg
)
2266 if (!PyArg_ParseTuple(arg
, "O&:halftrace", convgf
, &xx
)) goto end
;
2267 rc
= gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me
), MP_NEW
, xx
));
2269 if (xx
) MP_DROP(xx
);
2273 static PyObject
*grmeth_sqrt(PyObject
*me
, PyObject
*arg
)
2278 if (!PyArg_ParseTuple(arg
, "O&:sqrt", convgf
, &xx
)) goto end
;
2279 if ((yy
= gfreduce_sqrt(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2280 VALERR("no modular square root");
2283 if (xx
) MP_DROP(xx
);
2287 static PyObject
*grmeth_quadsolve(PyObject
*me
, PyObject
*arg
)
2292 if (!PyArg_ParseTuple(arg
, "O&:quadsolve", convgf
, &xx
)) goto end
;
2293 if ((yy
= gfreduce_quadsolve(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2294 VALERR("no solution found");
2297 if (xx
) MP_DROP(xx
);
2301 static PyObject
*grmeth_reduce(PyObject
*me
, PyObject
*arg
)
2306 if (!PyArg_ParseTuple(arg
, "O&:reduce", convgf
, &yy
)) goto end
;
2307 z
= gf_pywrap(gfreduce_do(GFREDUCE_PY(me
), MP_NEW
, yy
));
2312 static void gfreduce_pydealloc(PyObject
*me
)
2314 gfreduce_destroy(GFREDUCE_PY(me
));
2318 static PyObject
*gfreduce_pynew(PyTypeObject
*ty
,
2319 PyObject
*arg
, PyObject
*kw
)
2321 gfreduce_pyobj
*mr
= 0;
2323 static const char *const kwlist
[] = { "m", 0 };
2326 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convgf
, &xx
))
2328 if (MP_ZEROP(xx
)) ZDIVERR("modulus is zero!");
2329 gfreduce_create(&r
, xx
);
2330 mr
= (gfreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
2333 if (xx
) MP_DROP(xx
);
2334 return ((PyObject
*)mr
);
2337 static PyObject
*grget_m(PyObject
*me
, void *hunoz
)
2338 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me
)->p
))); }
2340 static const PyGetSetDef gfreduce_pygetset
[] = {
2341 #define GETSETNAME(op, name) gr##op##_##name
2342 GET (m
, "R.m -> reduction polynomial")
2347 static const PyMethodDef gfreduce_pymethods
[] = {
2348 #define METHNAME(name) grmeth_##name
2349 METH (reduce
, "R.reduce(X) -> X mod B.m")
2350 METH (trace
, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2351 METH (halftrace
, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2352 METH (sqrt
, "R.sqrt(X) -> Y where Y^2 = X mod R")
2353 METH (quadsolve
, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2354 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
2359 static const PyTypeObject gfreduce_pytype_skel
= {
2360 PyVarObject_HEAD_INIT(0, 0) /* Header */
2361 "GFReduce", /* @tp_name@ */
2362 sizeof(gfreduce_pyobj
), /* @tp_basicsize@ */
2363 0, /* @tp_itemsize@ */
2365 gfreduce_pydealloc
, /* @tp_dealloc@ */
2367 0, /* @tp_getattr@ */
2368 0, /* @tp_setattr@ */
2369 0, /* @tp_compare@ */
2371 0, /* @tp_as_number@ */
2372 0, /* @tp_as_sequence@ */
2373 0, /* @tp_as_mapping@ */
2377 0, /* @tp_getattro@ */
2378 0, /* @tp_setattro@ */
2379 0, /* @tp_as_buffer@ */
2380 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2381 Py_TPFLAGS_BASETYPE
,
2384 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2386 0, /* @tp_traverse@ */
2388 0, /* @tp_richcompare@ */
2389 0, /* @tp_weaklistoffset@ */
2391 0, /* @tp_iternext@ */
2392 PYMETHODS(gfreduce
), /* @tp_methods@ */
2393 0, /* @tp_members@ */
2394 PYGETSET(gfreduce
), /* @tp_getset@ */
2397 0, /* @tp_descr_get@ */
2398 0, /* @tp_descr_set@ */
2399 0, /* @tp_dictoffset@ */
2401 PyType_GenericAlloc
, /* @tp_alloc@ */
2402 gfreduce_pynew
, /* @tp_new@ */
2407 /*----- Normal/poly transformation ----------------------------------------*/
2409 static PyTypeObject
*gfn_pytype
;
2411 typedef struct gfn_pyobj
{
2417 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2418 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2419 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2421 static PyObject
*gfn_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
2423 mp
*p
= 0, *beta
= 0;
2425 static const char *const kwlist
[] = { "p", "beta", 0 };
2427 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&O&:new", KWLIST
,
2428 convgf
, &p
, convgf
, &beta
))
2430 gg
= PyObject_New(gfn_pyobj
, ty
);
2432 if (gfn_create(p
, beta
, &gg
->ntop
, &gg
->pton
)) {
2435 VALERR("can't invert transformation matrix");
2441 return ((PyObject
*)gg
);
2444 static PyObject
*gfnget_p(PyObject
*me
, void *hunoz
)
2445 { return (gf_pywrap(MP_COPY(GFN_P(me
)))); }
2447 static PyObject
*gfnget_beta(PyObject
*me
, void *hunoz
)
2449 gfn
*n
= GFN_NTOP(me
);
2450 mp
*x
= n
->r
[n
->n
- 1];
2451 return (gf_pywrap(MP_COPY(x
)));
2454 #define XFORMOP(name, NAME) \
2455 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2460 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2461 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2464 if (!z) return (0); \
2465 return (gf_pywrap(z)); \
2471 static void gfn_pydealloc(PyObject
*me
)
2475 gfn_destroy(GFN_PTON(me
));
2476 gfn_destroy(GFN_NTOP(me
));
2481 static const PyGetSetDef gfn_pygetset
[] = {
2482 #define GETSETNAME(op, name) gfn##op##_##name
2483 GET (p
, "X.p -> polynomial basis, as polynomial")
2484 GET (beta
, "X.beta -> normal basis element, in poly form")
2489 static const PyMethodDef gfn_pymethods
[] = {
2490 #define METHNAME(name) gfnmeth_##name
2491 METH (pton
, "X.pton(A) -> normal-basis representation of A")
2492 METH (ntop
, "X.ntop(A) -> polynomial-basis representation of A")
2497 static const PyTypeObject gfn_pytype_skel
= {
2498 PyVarObject_HEAD_INIT(0, 0) /* Header */
2499 "GFN", /* @tp_name@ */
2500 sizeof(gfn_pyobj
), /* @tp_basicsize@ */
2501 0, /* @tp_itemsize@ */
2503 gfn_pydealloc
, /* @tp_dealloc@ */
2505 0, /* @tp_getattr@ */
2506 0, /* @tp_setattr@ */
2507 0, /* @tp_compare@ */
2509 0, /* @tp_as_number@ */
2510 0, /* @tp_as_sequence@ */
2511 0, /* @tp_as_mapping@ */
2515 0, /* @tp_getattro@ */
2516 0, /* @tp_setattro@ */
2517 0, /* @tp_as_buffer@ */
2518 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2519 Py_TPFLAGS_BASETYPE
,
2522 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2523 " between polynomial and normal basis representations.",
2525 0, /* @tp_traverse@ */
2527 0, /* @tp_richcompare@ */
2528 0, /* @tp_weaklistoffset@ */
2530 0, /* @tp_iternext@ */
2531 PYMETHODS(gfn
), /* @tp_methods@ */
2532 0, /* @tp_members@ */
2533 PYGETSET(gfn
), /* @tp_getset@ */
2536 0, /* @tp_descr_get@ */
2537 0, /* @tp_descr_set@ */
2538 0, /* @tp_dictoffset@ */
2540 PyType_GenericAlloc
, /* @tp_alloc@ */
2541 gfn_pynew
, /* @tp_new@ */
2546 /*----- Glue --------------------------------------------------------------*/
2548 static const struct nameval consts
[] = {
2553 void mp_pyinit(void)
2557 INITTYPE(mpmul
, root
);
2558 INITTYPE(mpmont
, root
);
2559 INITTYPE(mpbarrett
, root
);
2560 INITTYPE(mpreduce
, root
);
2561 INITTYPE(mpcrt
, root
);
2562 INITTYPE(gfreduce
, root
);
2563 INITTYPE(gfn
, root
);
2566 void mp_pyinsert(PyObject
*mod
)
2568 INSERT("MP", mp_pytype
);
2569 INSERT("MPMul", mpmul_pytype
);
2570 INSERT("MPMont", mpmont_pytype
);
2571 INSERT("MPBarrett", mpbarrett_pytype
);
2572 INSERT("MPReduce", mpreduce_pytype
);
2573 INSERT("MPCRT", mpcrt_pytype
);
2574 INSERT("GF", gf_pytype
);
2575 INSERT("GFReduce", gfreduce_pytype
);
2576 INSERT("GFN", gfn_pytype
);
2577 setconstants(mod
, consts
);
2580 /*----- That's all, folks -------------------------------------------------*/