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@ */
971 static const PyTypeObject mp_pytype_skel
= {
972 PyVarObject_HEAD_INIT(0, 0) /* Header */
973 "MP", /* @tp_name@ */
974 sizeof(mp_pyobj
), /* @tp_basicsize@ */
975 0, /* @tp_itemsize@ */
977 mp_pydealloc
, /* @tp_dealloc@ */
979 0, /* @tp_getattr@ */
980 0, /* @tp_setattr@ */
981 mp_pycompare
, /* @tp_compare@ */
982 mp_pyrepr
, /* @tp_repr@ */
983 PYNUMBER(mp
), /* @tp_as_number@ */
984 0, /* @tp_as_sequence@ */
985 0, /* @tp_as_mapping@ */
986 mp_pyhash
, /* @tp_hash@ */
988 mp_pystr
, /* @tp_str@ */
989 0, /* @tp_getattro@ */
990 0, /* @tp_setattro@ */
991 0, /* @tp_as_buffer@ */
992 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
993 Py_TPFLAGS_CHECKTYPES
|
997 "Multiprecision integers, similar to `long' but more efficient and\n"
998 "versatile. Support all the standard arithmetic operations, with\n"
999 "implicit conversions from `PrimeFilter', and other objects which\n"
1000 "convert to `long'.\n"
1002 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1003 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1004 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1005 "points, group elements, Python `int' and `long' objects, and anything\n"
1006 "with an integer conversion.\n"
1010 " * Use `//' for integer division: `/' gives exact rational division.",
1012 0, /* @tp_traverse@ */
1014 mp_pyrichcompare
, /* @tp_richcompare@ */
1015 0, /* @tp_weaklistoffset@ */
1017 0, /* @tp_iternext@ */
1018 PYMETHODS(mp
), /* @tp_methods@ */
1019 0, /* @tp_members@ */
1020 PYGETSET(mp
), /* @tp_getset@ */
1023 0, /* @tp_descr_get@ */
1024 0, /* @tp_descr_set@ */
1025 0, /* @tp_dictoffset@ */
1027 PyType_GenericAlloc
, /* @tp_alloc@ */
1028 mp_pynew
, /* @tp_new@ */
1033 /*----- Products of small integers ----------------------------------------*/
1035 static PyTypeObject
*mpmul_pytype
;
1037 typedef struct mpmul_pyobj
{
1043 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1044 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1046 static void mpmul_pydealloc(PyObject
*me
)
1048 if (MPMUL_LIVEP(me
))
1049 mp_drop(mpmul_done(MPMUL_PY(me
)));
1053 static PyObject
*mmmeth_factor(PyObject
*me
, PyObject
*arg
)
1058 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1059 if (PyTuple_GET_SIZE(arg
) != 1)
1060 i
= PyObject_GetIter(arg
);
1062 if ((q
= PyTuple_GET_ITEM(arg
, 0)) == 0) goto end
;
1063 if ((i
= PyObject_GetIter(q
)) == 0) {
1064 PyErr_Clear(); /* that's ok */
1065 i
= PyObject_GetIter(arg
);
1069 while ((q
= PyIter_Next(i
)) != 0) {
1070 x
= getmp(q
); Py_DECREF(q
); if (!x
) {
1074 mpmul_add(MPMUL_PY(me
), x
);
1083 static PyObject
*mmmeth_done(PyObject
*me
)
1087 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1088 x
= mpmul_done(MPMUL_PY(me
));
1089 MPMUL_LIVEP(me
) = 0;
1090 return (mp_pywrap(x
));
1095 static PyObject
*mpmul_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1099 if (kw
) TYERR("keyword arguments not allowed here");
1100 mm
= (mpmul_pyobj
*)ty
->tp_alloc(ty
, 0);
1101 mpmul_init(&mm
->mm
);
1103 if (mmmeth_factor((PyObject
*)mm
, arg
) == 0) {
1107 return ((PyObject
*)mm
);
1112 static PyObject
*mmget_livep(PyObject
*me
, void *hunoz
)
1113 { return (getbool(MPMUL_LIVEP(me
))); }
1115 static const PyGetSetDef mpmul_pygetset
[] = {
1116 #define GETSETNAME(op, name) mm##op##_##name
1117 GET (livep
, "MM.livep -> flag: object still valid?")
1122 static const PyMethodDef mpmul_pymethods
[] = {
1123 #define METHNAME(name) mmmeth_##name
1124 METH (factor
, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1125 NAMETH(done
, "MM.done() -> PRODUCT")
1130 static const PyTypeObject mpmul_pytype_skel
= {
1131 PyVarObject_HEAD_INIT(0, 0) /* Header */
1132 "MPMul", /* @tp_name@ */
1133 sizeof(mpmul_pyobj
), /* @tp_basicsize@ */
1134 0, /* @tp_itemsize@ */
1136 mpmul_pydealloc
, /* @tp_dealloc@ */
1138 0, /* @tp_getattr@ */
1139 0, /* @tp_setattr@ */
1140 0, /* @tp_compare@ */
1142 0, /* @tp_as_number@ */
1143 0, /* @tp_as_sequence@ */
1144 0, /* @tp_as_mapping@ */
1148 0, /* @tp_getattro@ */
1149 0, /* @tp_setattro@ */
1150 0, /* @tp_as_buffer@ */
1151 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1152 Py_TPFLAGS_BASETYPE
,
1155 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1157 0, /* @tp_traverse@ */
1159 0, /* @tp_richcompare@ */
1160 0, /* @tp_weaklistoffset@ */
1162 0, /* @tp_iternext@ */
1163 PYMETHODS(mpmul
), /* @tp_methods@ */
1164 0, /* @tp_members@ */
1165 PYGETSET(mpmul
), /* @tp_getset@ */
1168 0, /* @tp_descr_get@ */
1169 0, /* @tp_descr_set@ */
1170 0, /* @tp_dictoffset@ */
1172 PyType_GenericAlloc
, /* @tp_alloc@ */
1173 mpmul_pynew
, /* @tp_new@ */
1178 /*----- Montgomery reduction ----------------------------------------------*/
1180 static PyTypeObject
*mpmont_pytype
;
1182 typedef struct mpmont_pyobj
{
1187 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1189 static PyObject
*mmmeth_int(PyObject
*me
, PyObject
*arg
)
1193 mpmont
*mm
= MPMONT_PY(me
);
1195 if (!PyArg_ParseTuple(arg
, "O&:in", convmp
, &yy
))
1197 mp_div(0, &yy
, yy
, mm
->m
);
1198 z
= mp_pywrap(mpmont_mul(mm
, MP_NEW
, yy
, mm
->r2
));
1200 if (yy
) MP_DROP(yy
);
1204 static PyObject
*mmmeth_mul(PyObject
*me
, PyObject
*arg
)
1207 mp
*yy
= 0, *zz
= 0;
1209 if (!PyArg_ParseTuple(arg
, "O&O&:mul", convmp
, &yy
, convmp
, &zz
))
1211 rc
= mp_pywrap(mpmont_mul(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1213 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1217 static PyObject
*mmmeth_exp(PyObject
*me
, PyObject
*arg
)
1220 mp
*yy
= 0, *zz
= 0;
1222 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1225 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1226 zz
= mp_neg(zz
, zz
);
1228 rc
= mp_pywrap(mpmont_exp(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1230 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1234 static PyObject
*mmmeth_expr(PyObject
*me
, PyObject
*arg
)
1237 mp
*yy
= 0, *zz
= 0;
1239 if (!PyArg_ParseTuple(arg
, "O&O&:expr", convmp
, &yy
, convmp
, &zz
))
1242 yy
= mpmont_reduce(MPMONT_PY(me
), yy
, yy
);
1243 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1244 yy
= mpmont_mul(MPMONT_PY(me
), yy
, yy
, MPMONT_PY(me
)->r2
);
1245 zz
= mp_neg(zz
, zz
);
1247 rc
= mp_pywrap(mpmont_expr(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1249 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1253 static PyObject
*mm_mexpr_id(PyObject
*me
)
1254 { return mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
)); }
1256 static int mm_mexpr_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1258 mp
*xx
= 0, *yy
= 0;
1259 mp_expfactor
*f
= p
;
1260 mpmont
*mm
= MPMONT_PY(me
);
1262 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1265 xx
= mpmont_reduce(mm
, xx
, xx
);
1266 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1268 xx
= mpmont_mul(mm
, xx
, xx
, mm
->r2
);
1269 yy
= mp_neg(yy
, yy
);
1276 mp_drop(xx
); mp_drop(yy
);
1280 static PyObject
*mm_mexpr(PyObject
*me
, void *v
, int n
)
1281 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1283 static void mp_mexp_drop(void *p
)
1285 mp_expfactor
*f
= p
;
1290 static PyObject
*mmmeth_mexpr(PyObject
*me
, PyObject
*arg
)
1292 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1293 mm_mexpr_id
, mm_mexpr_fill
, mm_mexpr
, mp_mexp_drop
);
1296 static PyObject
*mp_mexp_id(PyObject
*me
)
1297 { return mp_pywrap(MP_ONE
); }
1299 static int mp_mexp_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1301 mp
*xx
= 0, *yy
= 0;
1302 mp_expfactor
*f
= p
;
1304 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1307 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1309 yy
= mp_neg(yy
, yy
);
1316 mp_drop(xx
); mp_drop(yy
);
1320 static PyObject
*mm_mexp(PyObject
*me
, void *v
, int n
)
1321 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1323 static PyObject
*mmmeth_mexp(PyObject
*me
, PyObject
*arg
)
1325 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1326 mp_mexp_id
, mp_mexp_fill
, mm_mexp
, mp_mexp_drop
);
1329 #define mmmeth_ext mmmeth_reduce
1330 static PyObject
*mmmeth_reduce(PyObject
*me
, PyObject
*arg
)
1335 if (!PyArg_ParseTuple(arg
, "O&", convmp
, &yy
)) goto end
;
1336 z
= mp_pywrap(mpmont_reduce(MPMONT_PY(me
), MP_NEW
, yy
));
1341 static void mpmont_pydealloc(PyObject
*me
)
1343 mpmont_destroy(MPMONT_PY(me
));
1347 static PyObject
*mpmont_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1349 mpmont_pyobj
*mm
= 0;
1350 static const char *const kwlist
[] = { "m", 0 };
1353 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1355 if (!MP_POSP(xx
) || !MP_ODDP(xx
)) VALERR("m must be positive and odd");
1356 mm
= (mpmont_pyobj
*)ty
->tp_alloc(ty
, 0);
1357 mpmont_create(&mm
->mm
, xx
);
1359 if (xx
) MP_DROP(xx
);
1360 return ((PyObject
*)mm
);
1363 static PyObject
*mmget_m(PyObject
*me
, void *hunoz
)
1364 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->m
))); }
1366 static PyObject
*mmget_r(PyObject
*me
, void *hunoz
)
1367 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
))); }
1369 static PyObject
*mmget_r2(PyObject
*me
, void *hunoz
)
1370 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r2
))); }
1372 static const PyGetSetDef mpmont_pygetset
[] = {
1373 #define GETSETNAME(op, name) mm##op##_##name
1374 GET (m
, "M.m -> modulus for reduction")
1375 GET (r
, "M.r -> multiplicative identity")
1376 GET (r2
, "M.r2 -> M.r^2, Montgomerization factor")
1381 static const PyMethodDef mpmont_pymethods
[] = {
1382 #define METHNAME(name) mmmeth_##name
1383 METH (int, "M.int(X) -> XR")
1384 METH (mul
, "M.mul(XR, YR) -> ZR where Z = X Y")
1385 METH (expr
, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1386 METH (mexpr
, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1387 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1388 "\t(the list may be flattened if this more convenient.)")
1389 METH (reduce
, "M.reduce(XR) -> X")
1390 METH (ext
, "M.ext(XR) -> X")
1391 METH (exp
, "M.exp(X, N) -> X^N mod M.m")
1392 METH (mexp
, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1393 "X0^N0 X1^N1 ... mod M.m\n"
1394 "\t(the list may be flattened if this more convenient.)")
1399 static const PyTypeObject mpmont_pytype_skel
= {
1400 PyVarObject_HEAD_INIT(0, 0) /* Header */
1401 "MPMont", /* @tp_name@ */
1402 sizeof(mpmont_pyobj
), /* @tp_basicsize@ */
1403 0, /* @tp_itemsize@ */
1405 mpmont_pydealloc
, /* @tp_dealloc@ */
1407 0, /* @tp_getattr@ */
1408 0, /* @tp_setattr@ */
1409 0, /* @tp_compare@ */
1411 0, /* @tp_as_number@ */
1412 0, /* @tp_as_sequence@ */
1413 0, /* @tp_as_mapping@ */
1417 0, /* @tp_getattro@ */
1418 0, /* @tp_setattro@ */
1419 0, /* @tp_as_buffer@ */
1420 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1421 Py_TPFLAGS_BASETYPE
,
1424 "MPMont(N): a Montgomery reduction context.",
1426 0, /* @tp_traverse@ */
1428 0, /* @tp_richcompare@ */
1429 0, /* @tp_weaklistoffset@ */
1431 0, /* @tp_iternext@ */
1432 PYMETHODS(mpmont
), /* @tp_methods@ */
1433 0, /* @tp_members@ */
1434 PYGETSET(mpmont
), /* @tp_getset@ */
1437 0, /* @tp_descr_get@ */
1438 0, /* @tp_descr_set@ */
1439 0, /* @tp_dictoffset@ */
1441 PyType_GenericAlloc
, /* @tp_alloc@ */
1442 mpmont_pynew
, /* @tp_new@ */
1447 /*----- Barrett reduction -------------------------------------------------*/
1449 static PyTypeObject
*mpbarrett_pytype
;
1451 typedef struct mpbarrett_pyobj
{
1456 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1458 static PyObject
*mbmeth_exp(PyObject
*me
, PyObject
*arg
)
1461 mp
*yy
= 0, *zz
= 0;
1463 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1466 if ((yy
= mp_modinv_checked(yy
, yy
, MPBARRETT_PY(me
)->m
)) == 0) goto end
;
1467 zz
= mp_neg(zz
, zz
);
1469 rc
= mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me
), MP_NEW
, yy
, zz
));
1471 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1475 static PyObject
*mb_mexp(PyObject
*me
, void *v
, int n
)
1476 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me
), MP_NEW
, v
, n
)); }
1478 static PyObject
*mbmeth_mexp(PyObject
*me
, PyObject
*arg
)
1480 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1481 mp_mexp_id
, mp_mexp_fill
, mb_mexp
, mp_mexp_drop
);
1484 static PyObject
*mbmeth_reduce(PyObject
*me
, PyObject
*arg
)
1489 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
))
1491 z
= mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me
), MP_NEW
, yy
));
1496 static void mpbarrett_pydealloc(PyObject
*me
)
1498 mpbarrett_destroy(MPBARRETT_PY(me
));
1502 static PyObject
*mpbarrett_pynew(PyTypeObject
*ty
,
1503 PyObject
*arg
, PyObject
*kw
)
1505 mpbarrett_pyobj
*mb
= 0;
1506 static const char *const kwlist
[] = { "m", 0 };
1509 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1511 if (!MP_POSP(xx
)) VALERR("m must be positive");
1512 mb
= (mpbarrett_pyobj
*)ty
->tp_alloc(ty
, 0);
1513 mpbarrett_create(&mb
->mb
, xx
);
1515 if (xx
) MP_DROP(xx
);
1516 return ((PyObject
*)mb
);
1519 static PyObject
*mbget_m(PyObject
*me
, void *hunoz
)
1520 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me
)->m
))); }
1522 static const PyGetSetDef mpbarrett_pygetset
[] = {
1523 #define GETSETNAME(op, name) mb##op##_##name
1524 GET (m
, "B.m -> modulus for reduction")
1529 static const PyMethodDef mpbarrett_pymethods
[] = {
1530 #define METHNAME(name) mbmeth_##name
1531 METH (reduce
, "B.reduce(X) -> X mod B.m")
1532 METH (exp
, "B.exp(X, N) -> X^N mod B.m")
1533 METH (mexp
, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1534 "X0^N0 X1^N1 ... mod B.m\n"
1535 "\t(the list may be flattened if this more convenient.)")
1540 static const PyTypeObject mpbarrett_pytype_skel
= {
1541 PyVarObject_HEAD_INIT(0, 0) /* Header */
1542 "MPBarrett", /* @tp_name@ */
1543 sizeof(mpbarrett_pyobj
), /* @tp_basicsize@ */
1544 0, /* @tp_itemsize@ */
1546 mpbarrett_pydealloc
, /* @tp_dealloc@ */
1548 0, /* @tp_getattr@ */
1549 0, /* @tp_setattr@ */
1550 0, /* @tp_compare@ */
1552 0, /* @tp_as_number@ */
1553 0, /* @tp_as_sequence@ */
1554 0, /* @tp_as_mapping@ */
1558 0, /* @tp_getattro@ */
1559 0, /* @tp_setattro@ */
1560 0, /* @tp_as_buffer@ */
1561 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1562 Py_TPFLAGS_BASETYPE
,
1565 "MPBarrett(N): a Barrett reduction context.",
1567 0, /* @tp_traverse@ */
1569 0, /* @tp_richcompare@ */
1570 0, /* @tp_weaklistoffset@ */
1572 0, /* @tp_iternext@ */
1573 PYMETHODS(mpbarrett
), /* @tp_methods@ */
1574 0, /* @tp_members@ */
1575 PYGETSET(mpbarrett
), /* @tp_getset@ */
1578 0, /* @tp_descr_get@ */
1579 0, /* @tp_descr_set@ */
1580 0, /* @tp_dictoffset@ */
1582 PyType_GenericAlloc
, /* @tp_alloc@ */
1583 mpbarrett_pynew
, /* @tp_new@ */
1588 /*----- Nice prime reduction ----------------------------------------------*/
1590 static PyTypeObject
*mpreduce_pytype
;
1592 typedef struct mpreduce_pyobj
{
1597 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1599 static PyObject
*mrmeth_exp(PyObject
*me
, PyObject
*arg
)
1602 mp
*yy
= 0, *zz
= 0;
1604 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1607 if ((yy
= mp_modinv_checked(yy
, yy
, MPREDUCE_PY(me
)->p
)) == 0) goto end
;
1608 zz
= mp_neg(zz
, zz
);
1610 rc
= mp_pywrap(mpreduce_exp(MPREDUCE_PY(me
), MP_NEW
, yy
, zz
));
1612 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1616 static PyObject
*mrmeth_reduce(PyObject
*me
, PyObject
*arg
)
1621 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
)) goto end
;
1622 z
= mp_pywrap(mpreduce_do(MPREDUCE_PY(me
), MP_NEW
, yy
));
1627 static void mpreduce_pydealloc(PyObject
*me
)
1629 mpreduce_destroy(MPREDUCE_PY(me
));
1633 static PyObject
*mpreduce_pynew(PyTypeObject
*ty
,
1634 PyObject
*arg
, PyObject
*kw
)
1636 mpreduce_pyobj
*mr
= 0;
1638 static const char *const kwlist
[] = { "m", 0 };
1641 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1643 if (!MP_POSP(xx
)) VALERR("m must be positive");
1644 if (mpreduce_create(&r
, xx
)) VALERR("bad modulus (must be 2^k - ...)");
1645 mr
= (mpreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
1648 if (xx
) MP_DROP(xx
);
1649 return ((PyObject
*)mr
);
1652 static PyObject
*mrget_m(PyObject
*me
, void *hunoz
)
1653 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me
)->p
))); }
1655 static const PyGetSetDef mpreduce_pygetset
[] = {
1656 #define GETSETNAME(op, name) mr##op##_##name
1657 GET (m
, "R.m -> modulus for reduction")
1662 static const const PyMethodDef mpreduce_pymethods
[] = {
1663 #define METHNAME(name) mrmeth_##name
1664 METH (reduce
, "R.reduce(X) -> X mod B.m")
1665 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
1670 static const PyTypeObject mpreduce_pytype_skel
= {
1671 PyVarObject_HEAD_INIT(0, 0) /* Header */
1672 "MPReduce", /* @tp_name@ */
1673 sizeof(mpreduce_pyobj
), /* @tp_basicsize@ */
1674 0, /* @tp_itemsize@ */
1676 mpreduce_pydealloc
, /* @tp_dealloc@ */
1678 0, /* @tp_getattr@ */
1679 0, /* @tp_setattr@ */
1680 0, /* @tp_compare@ */
1682 0, /* @tp_as_number@ */
1683 0, /* @tp_as_sequence@ */
1684 0, /* @tp_as_mapping@ */
1688 0, /* @tp_getattro@ */
1689 0, /* @tp_setattro@ */
1690 0, /* @tp_as_buffer@ */
1691 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1692 Py_TPFLAGS_BASETYPE
,
1695 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1697 0, /* @tp_traverse@ */
1699 0, /* @tp_richcompare@ */
1700 0, /* @tp_weaklistoffset@ */
1702 0, /* @tp_iternext@ */
1703 PYMETHODS(mpreduce
), /* @tp_methods@ */
1704 0, /* @tp_members@ */
1705 PYGETSET(mpreduce
), /* @tp_getset@ */
1708 0, /* @tp_descr_get@ */
1709 0, /* @tp_descr_set@ */
1710 0, /* @tp_dictoffset@ */
1712 PyType_GenericAlloc
, /* @tp_alloc@ */
1713 mpreduce_pynew
, /* @tp_new@ */
1718 /*----- Chinese Remainder Theorem solution --------------------------------*/
1720 static PyTypeObject
*mpcrt_pytype
;
1722 typedef struct mpcrt_pyobj
{
1727 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1729 static PyObject
*mcmeth_solve(PyObject
*me
, PyObject
*arg
)
1731 mpcrt
*c
= MPCRT_PY(me
);
1732 PyObject
*q
= 0, *x
, *z
= 0;
1735 Py_ssize_t i
= 0, n
= c
->k
;
1738 if (PyTuple_GET_SIZE(arg
) == n
)
1740 else if (!PyArg_ParseTuple(arg
, "O:solve", &q
))
1743 if (!PySequence_Check(q
)) TYERR("want a sequence of residues");
1744 i
= PySequence_Size(q
); if (i
< 0) goto end
;
1745 if (i
!= n
) VALERR("residue count mismatch");
1746 v
= xmalloc(n
* sizeof(*v
));
1747 for (i
= 0; i
< n
; i
++) {
1748 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1749 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1752 z
= mp_pywrap(mpcrt_solve(c
, MP_NEW
, v
));
1756 for (i
= 0; i
< n
; i
++)
1765 static void mpcrt_pydealloc(PyObject
*me
)
1767 mpcrt
*c
= MPCRT_PY(me
);
1772 static PyObject
*mpcrt_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1775 Py_ssize_t n
, i
= 0, j
;
1776 static const char *const kwlist
[] = { "mv", 0 };
1777 PyObject
*q
= 0, *x
;
1778 mp
*xx
= MP_NEW
, *y
= MP_NEW
, *g
= MP_NEW
;
1782 if (PyTuple_GET_SIZE(arg
) > 1)
1784 else if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O:new", KWLIST
, &q
))
1787 if (!PySequence_Check(q
)) TYERR("want a sequence of moduli");
1788 n
= PySequence_Size(q
); if (n
< 0) goto end
;
1789 if (!n
) VALERR("want at least one modulus");
1790 v
= xmalloc(n
* sizeof(*v
));
1791 for (i
= 0; i
< n
; i
++) {
1792 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1793 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1794 if (MP_CMP(xx
, <=, MP_ZERO
)) VALERR("moduli must be positive");
1795 v
[i
].m
= xx
; v
[i
].n
= 0; v
[i
].ni
= 0; v
[i
].nni
= 0; xx
= MP_NEW
;
1798 for (j
= 0; j
< i
; j
++) mpmul_add(&mm
, v
[j
].m
);
1799 xx
= mpmul_done(&mm
);
1800 for (j
= 0; j
< i
; j
++) {
1801 mp_div(&y
, 0, xx
, v
[j
].m
);
1802 mp_gcd(&g
, 0, 0, y
, v
[j
].m
);
1803 if (!MP_EQ(g
, MP_ONE
)) VALERR("moduli must be pairwise coprime");
1806 c
= (mpcrt_pyobj
*)ty
->tp_alloc(ty
, 0);
1807 mpcrt_create(&c
->c
, v
, n
, 0);
1809 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1810 return ((PyObject
*)c
);
1815 for (i
= 0; i
< n
; i
++)
1820 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1824 static PyObject
*mcget_product(PyObject
*me
, void *hunoz
)
1825 { return (mp_pywrap(MP_COPY(MPCRT_PY(me
)->mb
.m
))); }
1827 static PyObject
*mcget_moduli(PyObject
*me
, void *hunoz
)
1831 mpcrt
*c
= MPCRT_PY(me
);
1833 if ((q
= PyList_New(c
->k
)) == 0) return (0);
1834 for (i
= 0; i
< c
->k
; i
++)
1835 PyList_SET_ITEM(q
, i
, mp_pywrap(c
->v
[i
].m
));
1839 static const PyGetSetDef mpcrt_pygetset
[] = {
1840 #define GETSETNAME(op, name) mc##op##_##name
1841 GET (product
, "C.product -> product of moduli")
1842 GET (moduli
, "C.moduli -> list of individual moduli")
1847 static const PyMethodDef mpcrt_pymethods
[] = {
1848 #define METHNAME(name) mcmeth_##name
1849 METH (solve
, "C.solve([R0, R1]) -> X mod C.product")
1854 static const PyTypeObject mpcrt_pytype_skel
= {
1855 PyVarObject_HEAD_INIT(0, 0) /* Header */
1856 "MPCRT", /* @tp_name@ */
1857 sizeof(mpcrt_pyobj
), /* @tp_basicsize@ */
1858 0, /* @tp_itemsize@ */
1860 mpcrt_pydealloc
, /* @tp_dealloc@ */
1862 0, /* @tp_getattr@ */
1863 0, /* @tp_setattr@ */
1864 0, /* @tp_compare@ */
1866 0, /* @tp_as_number@ */
1867 0, /* @tp_as_sequence@ */
1868 0, /* @tp_as_mapping@ */
1872 0, /* @tp_getattro@ */
1873 0, /* @tp_setattro@ */
1874 0, /* @tp_as_buffer@ */
1875 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1876 Py_TPFLAGS_BASETYPE
,
1879 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1881 0, /* @tp_traverse@ */
1883 0, /* @tp_richcompare@ */
1884 0, /* @tp_weaklistoffset@ */
1886 0, /* @tp_iternext@ */
1887 PYMETHODS(mpcrt
), /* @tp_methods@ */
1888 0, /* @tp_members@ */
1889 PYGETSET(mpcrt
), /* @tp_getset@ */
1892 0, /* @tp_descr_get@ */
1893 0, /* @tp_descr_set@ */
1894 0, /* @tp_dictoffset@ */
1896 PyType_GenericAlloc
, /* @tp_alloc@ */
1897 mpcrt_pynew
, /* @tp_new@ */
1902 /*----- Binary polynomials ------------------------------------------------*/
1904 static PyObject
*gf_pyrepr(PyObject
*o
)
1905 { return mp_topystring(MP_X(o
), 16, "GF(", "0x", ")"); }
1907 static PyObject
*gf_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
1913 if (gfbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
1915 case Py_EQ
: b
= MP_EQ(xx
, yy
); break;
1916 case Py_NE
: b
= !MP_EQ(xx
, yy
); break;
1921 case Py_LT
: b
= xl
< yl
; break;
1922 case Py_LE
: b
= xl
<= yl
; break;
1923 case Py_GT
: b
= xl
> yl
; break;
1924 case Py_GE
: b
= xl
>= yl
; break;
1929 MP_DROP(xx
); MP_DROP(yy
);
1930 return (getbool(b
));
1933 static PyObject
*gf_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1939 static const char *const kwlist
[] = { "x", "radix", 0 };
1941 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:gf", KWLIST
, &x
, &radix
))
1943 if (GF_PYCHECK(x
)) RETURN_OBJ(x
);
1944 if (!good_radix_p(radix
, 1)) VALERR("radix out of range");
1945 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
1946 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
1947 Py_TYPE(x
)->tp_name
);
1952 VALERR("gf cannot be negative");
1954 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
1957 return ((PyObject
*)zz
);
1960 static PyObject
*gf_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
1962 mp
*xx
= 0, *yy
= 0, *zz
= 0;
1966 if ((xx
= tomp(x
)) == 0 || (yy
= tomp(y
)) == 0 ||
1967 (z
&& z
!= Py_None
&& (zz
= tomp(z
)) == 0)) {
1968 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
1971 if (!z
|| z
== Py_None
) {
1972 if (MP_NEGP(yy
)) VALERR("negative exponent");
1973 r
= gf_exp(MP_NEW
, xx
, yy
);
1976 if (MP_ZEROP(zz
)) ZDIVERR("zero modulus");
1978 if ((xx
= gf_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
1979 yy
= mp_neg(yy
, yy
);
1981 gfreduce_create(&gr
, zz
);
1982 r
= gfreduce_exp(&gr
, MP_NEW
, xx
, yy
);
1983 gfreduce_destroy(&gr
);
1987 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
1991 static PyObject
*gfmeth_sqr(PyObject
*me
)
1992 { return (gf_pywrap(gf_sqr(MP_NEW
, MP_X(me
)))); }
1994 static PyObject
*gfmeth_gcd(PyObject
*me
, PyObject
*arg
)
1997 mp
*yy
= 0, *zz
= MP_NEW
;
1999 if (!PyArg_ParseTuple(arg
, "O&:gcd", convgf
, &yy
)) goto end
;
2000 gf_gcd(&zz
, 0, 0, MP_X(me
), yy
);
2003 if (yy
) MP_DROP(yy
);
2007 static PyObject
*gfmeth_gcdx(PyObject
*me
, PyObject
*arg
)
2010 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
2012 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convgf
, &yy
))
2014 gf_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
2015 z
= Py_BuildValue("(NNN)",
2016 gf_pywrap(zz
), gf_pywrap(uu
), gf_pywrap(vv
));
2018 if (yy
) MP_DROP(yy
);
2022 static PyObject
*gfmeth_modinv(PyObject
*me
, PyObject
*arg
)
2025 mp
*yy
= 0, *zz
= MP_NEW
;
2027 if (!PyArg_ParseTuple(arg
, "O&:modinv", convgf
, &yy
) ||
2028 (zz
= gf_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
2032 if (yy
) MP_DROP(yy
);
2036 static PyObject
*gfmeth_fromstring(PyObject
*me
,
2037 PyObject
*arg
, PyObject
*kw
)
2044 mptext_stringctx sc
;
2045 static const char *const kwlist
[] = { "x", "radix", 0 };
2047 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
2050 if (!good_radix_p(r
, 1)) VALERR("bad radix");
2051 sc
.buf
= p
; sc
.lim
= p
+ len
;
2052 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0 ||
2054 if (zz
) MP_DROP(zz
);
2055 VALERR("bad binary polynomial");
2057 z
= Py_BuildValue("(Ns#)", gf_pywrap(zz
),
2058 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
2063 static PyObject
*gfmeth_irreduciblep(PyObject
*me
)
2064 { return getbool(gf_irreduciblep(MP_X(me
))); }
2066 static PyObject
*gfget_degree(PyObject
*me
, void *hunoz
)
2067 { return (PyInt_FromLong(mp_bits(MP_X(me
)) - 1)); }
2069 static const PyGetSetDef gf_pygetset
[] = {
2070 #define GETSETNAME(op, name) gf##op##_##name
2071 GET (degree
, "X.degree -> polynomial degree of X")
2073 #define GETSETNAME(op, name) mp##op##_##name
2074 GET (nbits
, "X.nbits -> bit length of X")
2075 GET (noctets
, "X.noctets -> octet length of X")
2080 static const PyMethodDef gf_pymethods
[] = {
2081 #define METHNAME(func) gfmeth_##func
2082 METH (setbit
, "X.setbit(N) -> X with bit N set")
2083 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
2084 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
2085 NAMETH(sqr
, "X.sqr() -> X^2")
2086 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
2087 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2088 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2089 NAMETH(irreduciblep
, "X.irreduciblep() -> true/false")
2090 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2091 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2092 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2093 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2094 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
2095 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
2096 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
2098 #define METHNAME(func) mpmeth_##func
2099 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
2100 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
2101 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
2102 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
2103 "little-endian bytes, two's complement")
2104 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
2105 "big-endian bytes, two's complement")
2106 NAMETH(tobuf
, "X.tobuf() -> buffer format")
2111 static const PyNumberMethods gf_pynumber
= {
2112 gf_pyadd
, /* @nb_add@ */
2113 gf_pysub
, /* @nb_subtract@ */
2114 gf_pymul
, /* @nb_multiply@ */
2115 0, /* @nb_divide@ */
2116 gf_pymod
, /* @nb_remainder@ */
2117 gf_pydivmod
, /* @nb_divmod@ */
2118 gf_pyexp
, /* @nb_power@ */
2119 mp_pyid
, /* @nb_negative@ */
2120 mp_pyid
, /* @nb_positive@ */
2121 mp_pyid
, /* @nb_absolute@ */
2122 mp_pynonzerop
, /* @nb_nonzero@ */
2123 0 /* doesn't make any sense */, /* @nb_invert@ */
2124 gf_pylsl
, /* @nb_lshift@ */
2125 gf_pylsr
, /* @nb_rshift@ */
2126 gf_pyand
, /* @nb_and@ */
2127 gf_pyxor
, /* @nb_xor@ */
2128 gf_pyor
, /* @nb_or@ */
2129 gf_pycoerce
, /* @nb_coerce@ */
2130 mp_pyint
, /* @nb_int@ */
2131 mp_pylong
, /* @nb_long@ */
2132 0 /* doesn't make any sense */, /* @nb_float@ */
2133 mp_pyoct
, /* @nb_oct@ */
2134 mp_pyhex
, /* @nb_hex@ */
2136 0, /* @nb_inplace_add@ */
2137 0, /* @nb_inplace_subtract@ */
2138 0, /* @nb_inplace_multiply@ */
2139 0, /* @nb_inplace_divide@ */
2140 0, /* @nb_inplace_remainder@ */
2141 0, /* @nb_inplace_power@ */
2142 0, /* @nb_inplace_lshift@ */
2143 0, /* @nb_inplace_rshift@ */
2144 0, /* @nb_inplace_and@ */
2145 0, /* @nb_inplace_xor@ */
2146 0, /* @nb_inplace_or@ */
2148 gf_pydiv
, /* @nb_floor_divide@ */
2149 0, /* @nb_true_divide@ */
2150 0, /* @nb_inplace_floor_divide@ */
2151 0, /* @nb_inplace_true_divide@ */
2154 static const PyTypeObject gf_pytype_skel
= {
2155 PyVarObject_HEAD_INIT(0, 0) /* Header */
2156 "GF", /* @tp_name@ */
2157 sizeof(mp_pyobj
), /* @tp_basicsize@ */
2158 0, /* @tp_itemsize@ */
2160 mp_pydealloc
, /* @tp_dealloc@ */
2162 0, /* @tp_getattr@ */
2163 0, /* @tp_setattr@ */
2164 0, /* @tp_compare@ */
2165 gf_pyrepr
, /* @tp_repr@ */
2166 PYNUMBER(gf
), /* @tp_as_number@ */
2167 0, /* @tp_as_sequence@ */
2168 0, /* @tp_as_mapping@ */
2169 mp_pyhash
, /* @tp_hash@ */
2171 mp_pyhex
, /* @tp_str@ */
2172 0, /* @tp_getattro@ */
2173 0, /* @tp_setattro@ */
2174 0, /* @tp_as_buffer@ */
2175 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2176 Py_TPFLAGS_CHECKTYPES
|
2177 Py_TPFLAGS_BASETYPE
,
2180 "Binary polynomials. Support almost all the standard arithmetic\n"
2183 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2184 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2185 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2186 "points, group elements, Python `int' and `long' objects, and anything\n"
2187 "with an integer conversion.\n"
2189 "The name is hopelessly wrong from a technical point of view, but\n"
2190 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2194 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2196 0, /* @tp_traverse@ */
2198 gf_pyrichcompare
, /* @tp_richcompare@ */
2199 0, /* @tp_weaklistoffset@ */
2201 0, /* @tp_iternext@ */
2202 PYMETHODS(gf
), /* @tp_methods@ */
2203 0, /* @tp_members@ */
2204 PYGETSET(gf
), /* @tp_getset@ */
2207 0, /* @tp_descr_get@ */
2208 0, /* @tp_descr_set@ */
2209 0, /* @tp_dictoffset@ */
2211 PyType_GenericAlloc
, /* @tp_alloc@ */
2212 gf_pynew
, /* @tp_new@ */
2217 /*----- Sparse poly reduction ---------------------------------------------*/
2219 static PyTypeObject
*gfreduce_pytype
;
2221 typedef struct gfreduce_pyobj
{
2226 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2228 static PyObject
*grmeth_exp(PyObject
*me
, PyObject
*arg
)
2231 mp
*yy
= 0, *zz
= 0;
2233 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convgf
, &yy
, convgf
, &zz
))
2236 if ((yy
= gf_modinv_checked(yy
, yy
, GFREDUCE_PY(me
)->p
)) == 0) goto end
;
2237 zz
= mp_neg(zz
, zz
);
2239 rc
= gf_pywrap(gfreduce_exp(GFREDUCE_PY(me
), MP_NEW
, yy
, zz
));
2241 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
2245 static PyObject
*grmeth_trace(PyObject
*me
, PyObject
*arg
)
2250 if (!PyArg_ParseTuple(arg
, "O&:trace", convgf
, &xx
)) goto end
;
2251 rc
= PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me
), xx
));
2253 if (xx
) MP_DROP(xx
);
2257 static PyObject
*grmeth_halftrace(PyObject
*me
, PyObject
*arg
)
2262 if (!PyArg_ParseTuple(arg
, "O&:halftrace", convgf
, &xx
)) goto end
;
2263 rc
= gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me
), MP_NEW
, xx
));
2265 if (xx
) MP_DROP(xx
);
2269 static PyObject
*grmeth_sqrt(PyObject
*me
, PyObject
*arg
)
2274 if (!PyArg_ParseTuple(arg
, "O&:sqrt", convgf
, &xx
)) goto end
;
2275 if ((yy
= gfreduce_sqrt(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2276 VALERR("no modular square root");
2279 if (xx
) MP_DROP(xx
);
2283 static PyObject
*grmeth_quadsolve(PyObject
*me
, PyObject
*arg
)
2288 if (!PyArg_ParseTuple(arg
, "O&:quadsolve", convgf
, &xx
)) goto end
;
2289 if ((yy
= gfreduce_quadsolve(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2290 VALERR("no solution found");
2293 if (xx
) MP_DROP(xx
);
2297 static PyObject
*grmeth_reduce(PyObject
*me
, PyObject
*arg
)
2302 if (!PyArg_ParseTuple(arg
, "O&:reduce", convgf
, &yy
)) goto end
;
2303 z
= gf_pywrap(gfreduce_do(GFREDUCE_PY(me
), MP_NEW
, yy
));
2308 static void gfreduce_pydealloc(PyObject
*me
)
2310 gfreduce_destroy(GFREDUCE_PY(me
));
2314 static PyObject
*gfreduce_pynew(PyTypeObject
*ty
,
2315 PyObject
*arg
, PyObject
*kw
)
2317 gfreduce_pyobj
*mr
= 0;
2319 static const char *const kwlist
[] = { "m", 0 };
2322 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convgf
, &xx
))
2324 if (MP_ZEROP(xx
)) ZDIVERR("modulus is zero!");
2325 gfreduce_create(&r
, xx
);
2326 mr
= (gfreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
2329 if (xx
) MP_DROP(xx
);
2330 return ((PyObject
*)mr
);
2333 static PyObject
*grget_m(PyObject
*me
, void *hunoz
)
2334 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me
)->p
))); }
2336 static const PyGetSetDef gfreduce_pygetset
[] = {
2337 #define GETSETNAME(op, name) gr##op##_##name
2338 GET (m
, "R.m -> reduction polynomial")
2343 static const PyMethodDef gfreduce_pymethods
[] = {
2344 #define METHNAME(name) grmeth_##name
2345 METH (reduce
, "R.reduce(X) -> X mod B.m")
2346 METH (trace
, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2347 METH (halftrace
, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2348 METH (sqrt
, "R.sqrt(X) -> Y where Y^2 = X mod R")
2349 METH (quadsolve
, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2350 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
2355 static const PyTypeObject gfreduce_pytype_skel
= {
2356 PyVarObject_HEAD_INIT(0, 0) /* Header */
2357 "GFReduce", /* @tp_name@ */
2358 sizeof(gfreduce_pyobj
), /* @tp_basicsize@ */
2359 0, /* @tp_itemsize@ */
2361 gfreduce_pydealloc
, /* @tp_dealloc@ */
2363 0, /* @tp_getattr@ */
2364 0, /* @tp_setattr@ */
2365 0, /* @tp_compare@ */
2367 0, /* @tp_as_number@ */
2368 0, /* @tp_as_sequence@ */
2369 0, /* @tp_as_mapping@ */
2373 0, /* @tp_getattro@ */
2374 0, /* @tp_setattro@ */
2375 0, /* @tp_as_buffer@ */
2376 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2377 Py_TPFLAGS_BASETYPE
,
2380 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2382 0, /* @tp_traverse@ */
2384 0, /* @tp_richcompare@ */
2385 0, /* @tp_weaklistoffset@ */
2387 0, /* @tp_iternext@ */
2388 PYMETHODS(gfreduce
), /* @tp_methods@ */
2389 0, /* @tp_members@ */
2390 PYGETSET(gfreduce
), /* @tp_getset@ */
2393 0, /* @tp_descr_get@ */
2394 0, /* @tp_descr_set@ */
2395 0, /* @tp_dictoffset@ */
2397 PyType_GenericAlloc
, /* @tp_alloc@ */
2398 gfreduce_pynew
, /* @tp_new@ */
2403 /*----- Normal/poly transformation ----------------------------------------*/
2405 static PyTypeObject
*gfn_pytype
;
2407 typedef struct gfn_pyobj
{
2413 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2414 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2415 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2417 static PyObject
*gfn_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
2419 mp
*p
= 0, *beta
= 0;
2421 static const char *const kwlist
[] = { "p", "beta", 0 };
2423 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&O&:new", KWLIST
,
2424 convgf
, &p
, convgf
, &beta
))
2426 gg
= PyObject_New(gfn_pyobj
, ty
);
2428 if (gfn_create(p
, beta
, &gg
->ntop
, &gg
->pton
)) {
2431 VALERR("can't invert transformation matrix");
2437 return ((PyObject
*)gg
);
2440 static PyObject
*gfnget_p(PyObject
*me
, void *hunoz
)
2441 { return (gf_pywrap(MP_COPY(GFN_P(me
)))); }
2443 static PyObject
*gfnget_beta(PyObject
*me
, void *hunoz
)
2445 gfn
*n
= GFN_NTOP(me
);
2446 mp
*x
= n
->r
[n
->n
- 1];
2447 return (gf_pywrap(MP_COPY(x
)));
2450 #define XFORMOP(name, NAME) \
2451 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2456 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2457 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2460 if (!z) return (0); \
2461 return (gf_pywrap(z)); \
2467 static void gfn_pydealloc(PyObject
*me
)
2471 gfn_destroy(GFN_PTON(me
));
2472 gfn_destroy(GFN_NTOP(me
));
2477 static const PyGetSetDef gfn_pygetset
[] = {
2478 #define GETSETNAME(op, name) gfn##op##_##name
2479 GET (p
, "X.p -> polynomial basis, as polynomial")
2480 GET (beta
, "X.beta -> normal basis element, in poly form")
2485 static const PyMethodDef gfn_pymethods
[] = {
2486 #define METHNAME(name) gfnmeth_##name
2487 METH (pton
, "X.pton(A) -> normal-basis representation of A")
2488 METH (ntop
, "X.ntop(A) -> polynomial-basis representation of A")
2493 static const PyTypeObject gfn_pytype_skel
= {
2494 PyVarObject_HEAD_INIT(0, 0) /* Header */
2495 "GFN", /* @tp_name@ */
2496 sizeof(gfn_pyobj
), /* @tp_basicsize@ */
2497 0, /* @tp_itemsize@ */
2499 gfn_pydealloc
, /* @tp_dealloc@ */
2501 0, /* @tp_getattr@ */
2502 0, /* @tp_setattr@ */
2503 0, /* @tp_compare@ */
2505 0, /* @tp_as_number@ */
2506 0, /* @tp_as_sequence@ */
2507 0, /* @tp_as_mapping@ */
2511 0, /* @tp_getattro@ */
2512 0, /* @tp_setattro@ */
2513 0, /* @tp_as_buffer@ */
2514 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2515 Py_TPFLAGS_BASETYPE
,
2518 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2519 " between polynomial and normal basis representations.",
2521 0, /* @tp_traverse@ */
2523 0, /* @tp_richcompare@ */
2524 0, /* @tp_weaklistoffset@ */
2526 0, /* @tp_iternext@ */
2527 PYMETHODS(gfn
), /* @tp_methods@ */
2528 0, /* @tp_members@ */
2529 PYGETSET(gfn
), /* @tp_getset@ */
2532 0, /* @tp_descr_get@ */
2533 0, /* @tp_descr_set@ */
2534 0, /* @tp_dictoffset@ */
2536 PyType_GenericAlloc
, /* @tp_alloc@ */
2537 gfn_pynew
, /* @tp_new@ */
2542 /*----- Glue --------------------------------------------------------------*/
2544 static const struct nameval consts
[] = {
2549 void mp_pyinit(void)
2553 INITTYPE(mpmul
, root
);
2554 INITTYPE(mpmont
, root
);
2555 INITTYPE(mpbarrett
, root
);
2556 INITTYPE(mpreduce
, root
);
2557 INITTYPE(mpcrt
, root
);
2558 INITTYPE(gfreduce
, root
);
2559 INITTYPE(gfn
, root
);
2562 void mp_pyinsert(PyObject
*mod
)
2564 INSERT("MP", mp_pytype
);
2565 INSERT("MPMul", mpmul_pytype
);
2566 INSERT("MPMont", mpmont_pytype
);
2567 INSERT("MPBarrett", mpbarrett_pytype
);
2568 INSERT("MPReduce", mpreduce_pytype
);
2569 INSERT("MPCRT", mpcrt_pytype
);
2570 INSERT("GF", gf_pytype
);
2571 INSERT("GFReduce", gfreduce_pytype
);
2572 INSERT("GFN", gfn_pytype
);
2573 setconstants(mod
, consts
);
2576 /*----- That's all, folks -------------------------------------------------*/