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)
232 else if (PyInt_Check(o
))
233 return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
234 else if ((l
= PyNumber_Long(o
)) != 0) {
235 x
= mp_frompylong(l
);
244 mp
*getmp(PyObject
*o
)
248 if ((x
= tomp(o
)) == 0) {
249 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
250 Py_TYPE(o
)->tp_name
);
255 int convmp(PyObject
*o
, void *p
)
258 if ((x
= getmp(o
)) == 0) return (0);
263 mp
*getgf(PyObject
*o
)
267 if ((x
= tomp(o
)) == 0) {
268 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
269 Py_TYPE(o
)->tp_name
);
274 int convgf(PyObject
*o
, void *p
)
277 if ((x
= getgf(o
)) == 0) return (0);
282 static mp
*implicitmp(PyObject
*o
)
293 static mp
*implicitgf(PyObject
*o
)
304 static int mpbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
306 if ((*xx
= implicitmp(x
)) == 0)
308 if ((*yy
= implicitmp(y
)) == 0) {
315 static int gfbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
317 if ((*xx
= implicitgf(x
)) == 0)
319 if ((*yy
= implicitgf(y
)) == 0) {
326 #define FPBINOP(name, pyop) \
327 static PyObject *mp_py##name(PyObject *x, PyObject *y) { \
330 if (PyFloat_Check(x)) { \
331 l = mp_topylong(MP_X(y)); rc = PyNumber_##pyop(x, l); \
332 Py_DECREF(l); return (rc); \
333 } else if (PyFloat_Check(y)) { \
334 l = mp_topylong(MP_X(x)); rc = PyNumber_##pyop(l, y); \
335 Py_DECREF(l); return (rc); \
337 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
338 zz = mp_##name(MP_NEW, xx, yy); \
339 MP_DROP(xx); MP_DROP(yy); \
340 return (mp_pywrap(zz)); \
343 FPBINOP(sub
, Subtract
)
344 FPBINOP(mul
, Multiply
)
346 #define gf_and mp_and
348 #define gf_xor mp_xor
349 #define BINOP(pre, name) \
350 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
352 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
353 zz = pre##_##name(MP_NEW, xx, yy); \
354 MP_DROP(xx); MP_DROP(yy); \
355 return (pre##_pywrap(zz)); \
368 static mp
*mp_abs(mp
*d
, mp
*x
)
371 return (mp_neg(d
, x
));
377 #define UNOP(pre, name) \
378 static PyObject *pre##_py##name(PyObject *x) \
379 { return mp_pywrap(pre##_##name(MP_NEW, MP_X(x))); }
385 static PyObject
*mp_pyid(PyObject
*x
) { RETURN_OBJ(x
); }
387 #define gf_lsr mp_lsr
388 #define SHIFTOP(pre, name, rname) \
389 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
393 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
394 if (mp_tolong_checked(yy, &n, 1)) goto end; \
396 z = pre##_pywrap(mp_##rname(MP_NEW, xx, -n)); \
398 z = pre##_pywrap(mp_##name(MP_NEW, xx, n)); \
400 MP_DROP(xx); MP_DROP(yy); \
403 SHIFTOP(mp
, lsl2c
, lsr2c
)
404 SHIFTOP(mp
, lsr2c
, lsl2c
)
405 SHIFTOP(gf
, lsl
, lsr
)
406 SHIFTOP(gf
, lsr
, lsl
)
409 #define DIVOP(pre, name, qq, rr, gather) \
410 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
413 INIT_##qq(q) INIT_##rr(r) \
414 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
416 ZDIVERR("division by zero"); \
417 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
420 MP_DROP(xx); MP_DROP(yy); \
423 #define INIT_YES(p) mp *p = MP_NEW;
425 #define ARG_YES(p) &p
427 DIVOP(mp
, divmod
, YES
, YES
,
428 Py_BuildValue("(NN)", mp_pywrap(q
), mp_pywrap(r
)))
429 DIVOP(mp
, div
, YES
, NO
, mp_pywrap(q
))
430 DIVOP(mp
, mod
, NO
, YES
, mp_pywrap(r
))
431 DIVOP(gf
, divmod
, YES
, YES
,
432 Py_BuildValue("(NN)", gf_pywrap(q
), gf_pywrap(r
)))
433 DIVOP(gf
, div
, YES
, NO
, gf_pywrap(q
))
434 DIVOP(gf
, mod
, NO
, YES
, gf_pywrap(r
))
441 static mp
*mp_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
444 mp_gcd(&g
, 0, &d
, p
, x
);
445 if (!MP_EQ(g
, MP_ONE
)) {
446 MP_DROP(g
); MP_DROP(d
);
447 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
450 MP_DROP(g
); return (d
);
453 static PyObject
*mp_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
455 mp
*xx
= 0, *yy
= 0, *zz
= 0;
459 if ((xx
= implicitmp(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
460 (z
&& z
!= Py_None
&& (zz
= tomp(z
)) == 0)) {
461 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
464 if (!z
|| z
== Py_None
) {
465 if (MP_NEGP(yy
)) VALERR("negative exponent");
466 r
= mp_exp(MP_NEW
, xx
, yy
);
468 if (!MP_POSP(zz
)) VALERR("modulus must be positive");
470 if ((xx
= mp_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
475 mpmont_create(&mm
, zz
);
476 r
= mpmont_exp(&mm
, MP_NEW
, xx
, yy
);
480 mpbarrett_create(&mb
, zz
);
481 r
= mpbarrett_exp(&mb
, MP_NEW
, xx
, yy
);
482 mpbarrett_destroy(&mb
);
487 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
491 static mp
*gf_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
494 gf_gcd(&g
, 0, &d
, p
, x
);
495 if (!MP_EQ(g
, MP_ONE
)) {
496 MP_DROP(g
); MP_DROP(d
);
497 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
500 MP_DROP(g
); return (d
);
503 #define BASEOP(name, radix, pre) \
504 static PyObject *mp_py##name(PyObject *x) \
505 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
507 BASEOP(hex
, 16, "0x");
510 static int mp_pynonzerop(PyObject
*x
) { return !MP_ZEROP(MP_X(x
)); }
512 static PyObject
*mp_pyint(PyObject
*x
)
515 if (!mp_tolong_checked(MP_X(x
), &l
, 0)) return (PyInt_FromLong(l
));
516 else return mp_topylong(MP_X(x
));
518 static PyObject
*mp_pylong(PyObject
*x
)
519 { return (mp_topylong(MP_X(x
))); }
520 static PyObject
*mp_pyfloat(PyObject
*x
)
522 PyObject
*l
= mp_topylong(MP_X(x
));
523 double f
= PyLong_AsDouble(l
);
525 return (PyFloat_FromDouble(f
));
528 #define COERCE(pre, PRE) \
529 static int pre##_pycoerce(PyObject **x, PyObject **y) \
533 if (PRE##_PYCHECK(*y)) { \
534 Py_INCREF(*x); Py_INCREF(*y); \
537 if ((z = tomp(*y)) != 0) { \
539 *y = pre##_pywrap(z); \
548 static PyObject
*mp_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
552 if (PyFloat_Check(y
)) {
553 l
= mp_topylong(MP_X(x
)); rc
= PyObject_RichCompare(l
, y
, op
);
554 Py_DECREF(l
); return (rc
);
556 if (mpbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
557 rc
= enrich_compare(op
, mp_cmp(xx
, yy
));
558 MP_DROP(xx
); MP_DROP(yy
);
562 static int mp_pycompare(PyObject
*x
, PyObject
*y
)
563 { return mp_cmp(MP_X(x
), MP_X(y
)); }
565 static PyObject
*mp_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
571 static const char *const kwlist
[] = { "x", "radix", 0 };
573 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:new", KWLIST
, &x
, &radix
))
575 if (MP_PYCHECK(x
)) RETURN_OBJ(x
);
576 if (!good_radix_p(radix
, 1)) VALERR("bad radix");
577 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
578 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
579 Py_TYPE(x
)->tp_name
);
582 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
585 return ((PyObject
*)zz
);
588 Py_hash_t
mphash(mp
*x
)
590 PyObject
*l
= mp_topylong(x
);
591 Py_hash_t h
= PyObject_Hash(l
);
592 Py_DECREF(l
); return (h
);
595 static Py_hash_t
mp_pyhash(PyObject
*me
) { return (mphash(MP_X(me
))); }
597 static PyObject
*mpmeth_jacobi(PyObject
*me
, PyObject
*arg
)
602 if (!PyArg_ParseTuple(arg
, "O&:jacobi", convmp
, &y
)) goto end
;
603 z
= PyInt_FromLong(mp_jacobi(y
, MP_X(me
)));
609 #define BITOP(pre, name, c) \
610 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
613 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
614 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
616 BITOP(mp
, setbit
, 2c
);
617 BITOP(mp
, clearbit
, 2c
);
619 BITOP(gf
, clearbit
, );
622 static PyObject
*mpmeth_testbit(PyObject
*me
, PyObject
*arg
)
625 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
626 return (getbool(mp_testbit2c(MP_X(me
), i
)));
629 static PyObject
*gfmeth_testbit(PyObject
*me
, PyObject
*arg
)
632 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
633 return (getbool(mp_testbit(MP_X(me
), i
)));
636 static PyObject
*mpmeth_odd(PyObject
*me
)
641 t
= mp_odd(MP_NEW
, MP_X(me
), &s
);
642 return (Py_BuildValue("(lN)", (long)s
, mp_pywrap(t
)));
645 static PyObject
*mpmeth_sqr(PyObject
*me
)
646 { return (mp_pywrap(mp_sqr(MP_NEW
, MP_X(me
)))); }
648 static PyObject
*mpmeth_sqrt(PyObject
*me
)
650 if (MP_NEGP(MP_X(me
))) VALERR("negative root");
651 return (mp_pywrap(mp_sqrt(MP_NEW
, MP_X(me
))));
656 static PyObject
*mpmeth_gcd(PyObject
*me
, PyObject
*arg
)
658 mp
*y
= 0, *zz
= MP_NEW
;
661 if (!PyArg_ParseTuple(arg
, "O&:gcd", convmp
, &y
)) goto end
;
662 mp_gcd(&zz
, 0, 0, MP_X(me
), y
);
669 static PyObject
*mpmeth_gcdx(PyObject
*me
, PyObject
*arg
)
672 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
674 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convmp
, &yy
)) goto end
;
675 mp_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
676 z
= Py_BuildValue("(NNN)",
677 mp_pywrap(zz
), mp_pywrap(uu
), mp_pywrap(vv
));
683 static PyObject
*mpmeth_modinv(PyObject
*me
, PyObject
*arg
)
686 mp
*yy
= 0, *zz
= MP_NEW
;
688 if (!PyArg_ParseTuple(arg
, "O&:modinv", convmp
, &yy
) ||
689 (zz
= mp_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
697 static PyObject
*mpmeth_tostring(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
700 static const char *const kwlist
[] = { "radix", 0 };
701 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|i:tostring", KWLIST
, &radix
))
703 if (!good_radix_p(radix
, 0)) VALERR("bad radix");
704 return (mp_topystring(MP_X(me
), radix
, 0, 0, 0));
709 static PyObject
*mpmeth_modsqrt(PyObject
*me
, PyObject
*arg
)
712 mp
*yy
= 0, *zz
= MP_NEW
;
714 if (!PyArg_ParseTuple(arg
, "O&:modsqrt", convmp
, &yy
)) goto end
;
715 if ((zz
= mp_modsqrt(MP_NEW
, yy
, MP_X(me
))) == 0)
716 VALERR("no modular square root");
723 static PyObject
*mpmeth_leastcongruent(PyObject
*me
, PyObject
*arg
)
728 if (!PyArg_ParseTuple(arg
, "O&O&:leastcongruent", convmp
, &b
, convmp
, &m
))
730 z
= mp_leastcongruent(MP_NEW
, b
, MP_X(me
), m
);
736 #define STOREOP(name, c) \
737 static PyObject *mpmeth_##name(PyObject *me, \
738 PyObject *arg, PyObject *kw) \
741 static const char *const kwlist[] = { "len", 0 }; \
744 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
748 len = mp_octets##c(MP_X(me)); \
751 rc = bytestring_pywrap(0, len); \
752 mp_##name(MP_X(me), BIN_PTR(rc), len); \
758 STOREOP(storel2c
, 2c
)
759 STOREOP(storeb2c
, 2c
)
763 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
770 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
771 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
772 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
773 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
774 bytestring_pywrapbuf(&b)); \
782 static PyObject
*mpmeth_tobuf(PyObject
*me
)
790 n
= mp_octets(x
) + 3;
791 rc
= bytestring_pywrap(0, n
);
792 buf_init(&b
, BIN_PTR(rc
), n
);
795 BIN_SETLEN(rc
, BLEN(&b
));
799 static PyObject
*mpmeth_primep(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
801 grand
*r
= &rand_global
;
802 static const char *const kwlist
[] = { "rng", 0 };
805 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|O&", KWLIST
, convgrand
, &r
))
807 rc
= getbool(pgen_primep(MP_X(me
), r
));
812 static PyObject
*mpmeth_fromstring(PyObject
*me
,
813 PyObject
*arg
, PyObject
*kw
)
821 static const char *const kwlist
[] = { "x", "radix", 0 };
823 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
826 if (!good_radix_p(r
, 1)) VALERR("bad radix");
827 sc
.buf
= p
; sc
.lim
= p
+ len
;
828 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0)
829 VALERR("bad integer");
830 z
= Py_BuildValue("(Ns#)", mp_pywrap(zz
),
831 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
836 static PyObject
*mpmeth_factorial(PyObject
*me
, PyObject
*arg
)
840 if (!PyArg_ParseTuple(arg
, "O&:factorial", convulong
, &i
)) return (0);
845 static PyObject
*mpmeth_fibonacci(PyObject
*me
, PyObject
*arg
)
849 if (!PyArg_ParseTuple(arg
, "l:fibonacci", &i
)) return (0);
854 #define LOADOP(pre, name) \
855 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
858 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
859 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
869 static PyObject
*mpget_nbits(PyObject
*me
, void *hunoz
)
870 { return (PyInt_FromLong(mp_bits(MP_X(me
)))); }
872 static PyObject
*mpget_noctets(PyObject
*me
, void *hunoz
)
873 { return (PyInt_FromLong(mp_octets(MP_X(me
)))); }
875 static PyObject
*mpget_noctets2c(PyObject
*me
, void *hunoz
)
876 { return (PyInt_FromLong(mp_octets2c(MP_X(me
)))); }
878 static const PyGetSetDef mp_pygetset
[] = {
879 #define GETSETNAME(op, func) mp##op##_##func
880 GET (nbits
, "X.nbits -> bit length of X")
881 GET (noctets
, "X.noctets -> octet length of X")
882 GET (noctets2c
, "X.noctets2c -> two's complement octet length of X")
887 static const PyMethodDef mp_pymethods
[] = {
888 #define METHNAME(func) mpmeth_##func
889 METH (jacobi
, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
890 METH (setbit
, "X.setbit(N) -> X with bit N set")
891 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
892 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
893 NAMETH(odd
, "X.odd() -> S, T where X = 2^S T with T odd")
894 NAMETH(sqr
, "X.sqr() -> X^2")
895 NAMETH(sqrt
, "X.sqrt() -> largest integer <= sqrt(X)")
896 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
897 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
898 "with X U + Y V = gcd(X, Y)")
899 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
900 METH (modsqrt
, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
901 METH (leastcongruent
, "X.leastcongruent(B, M) -> "
902 "smallest Z >= B with Z == X (mod M)")
903 KWMETH(primep
, "X.primep([rng = rand]) -> X is prime?")
904 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
905 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
906 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
907 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
908 "little-endian bytes, two's complement")
909 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
910 "big-endian bytes, two's complement")
911 NAMETH(tobuf
, "X.tobuf() -> buffer format")
912 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
913 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
914 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
915 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
916 SMTH (factorial
, "factorial(I) -> I!: compute factorial")
917 SMTH (fibonacci
, "fibonacci(I) -> F(I): compute Fibonacci number")
918 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
919 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
920 SMTH (loadl2c
, "loadl2c(STR) -> X: "
921 "read little-endian bytes, two's complement")
922 SMTH (loadb2c
, "loadb2c(STR) -> X: "
923 "read big-endian bytes, two's complement")
924 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
929 static const PyNumberMethods mp_pynumber
= {
930 mp_pyadd
, /* @nb_add@ */
931 mp_pysub
, /* @nb_subtract@ */
932 mp_pymul
, /* @nb_multiply@ */
934 mp_pymod
, /* @nb_remainder@ */
935 mp_pydivmod
, /* @nb_divmod@ */
936 mp_pyexp
, /* @nb_power@ */
937 mp_pyneg
, /* @nb_negative@ */
938 mp_pyid
, /* @nb_positive@ */
939 mp_pyabs
, /* @nb_absolute@ */
940 mp_pynonzerop
, /* @nb_nonzero@ */
941 mp_pynot2c
, /* @nb_invert@ */
942 mp_pylsl2c
, /* @nb_lshift@ */
943 mp_pylsr2c
, /* @nb_rshift@ */
944 mp_pyand2c
, /* @nb_and@ */
945 mp_pyxor2c
, /* @nb_xor@ */
946 mp_pyor2c
, /* @nb_or@ */
947 mp_pycoerce
, /* @nb_coerce@ */
948 mp_pyint
, /* @nb_int@ */
949 mp_pylong
, /* @nb_long@ */
950 mp_pyfloat
, /* @nb_float@ */
951 mp_pyoct
, /* @nb_oct@ */
952 mp_pyhex
, /* @nb_hex@ */
954 0, /* @nb_inplace_add@ */
955 0, /* @nb_inplace_subtract@ */
956 0, /* @nb_inplace_multiply@ */
957 0, /* @nb_inplace_divide@ */
958 0, /* @nb_inplace_remainder@ */
959 0, /* @nb_inplace_power@ */
960 0, /* @nb_inplace_lshift@ */
961 0, /* @nb_inplace_rshift@ */
962 0, /* @nb_inplace_and@ */
963 0, /* @nb_inplace_xor@ */
964 0, /* @nb_inplace_or@ */
966 mp_pydiv
, /* @nb_floor_divide@ */
967 0, /* @nb_true_divide@ */
968 0, /* @nb_inplace_floor_divide@ */
969 0, /* @nb_inplace_true_divide@ */
971 mp_pyint
, /* @nb_index@ */
974 static const PyTypeObject mp_pytype_skel
= {
975 PyVarObject_HEAD_INIT(0, 0) /* Header */
976 "MP", /* @tp_name@ */
977 sizeof(mp_pyobj
), /* @tp_basicsize@ */
978 0, /* @tp_itemsize@ */
980 mp_pydealloc
, /* @tp_dealloc@ */
982 0, /* @tp_getattr@ */
983 0, /* @tp_setattr@ */
984 mp_pycompare
, /* @tp_compare@ */
985 mp_pyrepr
, /* @tp_repr@ */
986 PYNUMBER(mp
), /* @tp_as_number@ */
987 0, /* @tp_as_sequence@ */
988 0, /* @tp_as_mapping@ */
989 mp_pyhash
, /* @tp_hash@ */
991 mp_pystr
, /* @tp_str@ */
992 0, /* @tp_getattro@ */
993 0, /* @tp_setattro@ */
994 0, /* @tp_as_buffer@ */
995 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
996 Py_TPFLAGS_CHECKTYPES
|
1000 "Multiprecision integers, similar to `long' but more efficient and\n"
1001 "versatile. Support all the standard arithmetic operations, with\n"
1002 "implicit conversions from `PrimeFilter', and other objects which\n"
1003 "convert to `long'.\n"
1005 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1006 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1007 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1008 "points, group elements, Python `int' and `long' objects, and anything\n"
1009 "with an integer conversion.\n"
1013 " * Use `//' for integer division: `/' gives exact rational division.",
1015 0, /* @tp_traverse@ */
1017 mp_pyrichcompare
, /* @tp_richcompare@ */
1018 0, /* @tp_weaklistoffset@ */
1020 0, /* @tp_iternext@ */
1021 PYMETHODS(mp
), /* @tp_methods@ */
1022 0, /* @tp_members@ */
1023 PYGETSET(mp
), /* @tp_getset@ */
1026 0, /* @tp_descr_get@ */
1027 0, /* @tp_descr_set@ */
1028 0, /* @tp_dictoffset@ */
1030 PyType_GenericAlloc
, /* @tp_alloc@ */
1031 mp_pynew
, /* @tp_new@ */
1036 /*----- Products of small integers ----------------------------------------*/
1038 static PyTypeObject
*mpmul_pytype
;
1040 typedef struct mpmul_pyobj
{
1046 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1047 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1049 static void mpmul_pydealloc(PyObject
*me
)
1051 if (MPMUL_LIVEP(me
))
1052 mp_drop(mpmul_done(MPMUL_PY(me
)));
1056 static PyObject
*mmmeth_factor(PyObject
*me
, PyObject
*arg
)
1061 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1062 if (PyTuple_GET_SIZE(arg
) != 1)
1063 i
= PyObject_GetIter(arg
);
1065 if ((q
= PyTuple_GET_ITEM(arg
, 0)) == 0) goto end
;
1066 if ((i
= PyObject_GetIter(q
)) == 0) {
1067 PyErr_Clear(); /* that's ok */
1068 i
= PyObject_GetIter(arg
);
1072 while ((q
= PyIter_Next(i
)) != 0) {
1073 x
= getmp(q
); Py_DECREF(q
); if (!x
) {
1077 mpmul_add(MPMUL_PY(me
), x
);
1086 static PyObject
*mmmeth_done(PyObject
*me
)
1090 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1091 x
= mpmul_done(MPMUL_PY(me
));
1092 MPMUL_LIVEP(me
) = 0;
1093 return (mp_pywrap(x
));
1098 static PyObject
*mpmul_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1102 if (kw
) TYERR("keyword arguments not allowed here");
1103 mm
= (mpmul_pyobj
*)ty
->tp_alloc(ty
, 0);
1104 mpmul_init(&mm
->mm
);
1106 if (mmmeth_factor((PyObject
*)mm
, arg
) == 0) {
1110 return ((PyObject
*)mm
);
1115 static PyObject
*mmget_livep(PyObject
*me
, void *hunoz
)
1116 { return (getbool(MPMUL_LIVEP(me
))); }
1118 static const PyGetSetDef mpmul_pygetset
[] = {
1119 #define GETSETNAME(op, name) mm##op##_##name
1120 GET (livep
, "MM.livep -> flag: object still valid?")
1125 static const PyMethodDef mpmul_pymethods
[] = {
1126 #define METHNAME(name) mmmeth_##name
1127 METH (factor
, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1128 NAMETH(done
, "MM.done() -> PRODUCT")
1133 static const PyTypeObject mpmul_pytype_skel
= {
1134 PyVarObject_HEAD_INIT(0, 0) /* Header */
1135 "MPMul", /* @tp_name@ */
1136 sizeof(mpmul_pyobj
), /* @tp_basicsize@ */
1137 0, /* @tp_itemsize@ */
1139 mpmul_pydealloc
, /* @tp_dealloc@ */
1141 0, /* @tp_getattr@ */
1142 0, /* @tp_setattr@ */
1143 0, /* @tp_compare@ */
1145 0, /* @tp_as_number@ */
1146 0, /* @tp_as_sequence@ */
1147 0, /* @tp_as_mapping@ */
1151 0, /* @tp_getattro@ */
1152 0, /* @tp_setattro@ */
1153 0, /* @tp_as_buffer@ */
1154 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1155 Py_TPFLAGS_BASETYPE
,
1158 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1160 0, /* @tp_traverse@ */
1162 0, /* @tp_richcompare@ */
1163 0, /* @tp_weaklistoffset@ */
1165 0, /* @tp_iternext@ */
1166 PYMETHODS(mpmul
), /* @tp_methods@ */
1167 0, /* @tp_members@ */
1168 PYGETSET(mpmul
), /* @tp_getset@ */
1171 0, /* @tp_descr_get@ */
1172 0, /* @tp_descr_set@ */
1173 0, /* @tp_dictoffset@ */
1175 PyType_GenericAlloc
, /* @tp_alloc@ */
1176 mpmul_pynew
, /* @tp_new@ */
1181 /*----- Montgomery reduction ----------------------------------------------*/
1183 static PyTypeObject
*mpmont_pytype
;
1185 typedef struct mpmont_pyobj
{
1190 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1192 static PyObject
*mmmeth_int(PyObject
*me
, PyObject
*arg
)
1196 mpmont
*mm
= MPMONT_PY(me
);
1198 if (!PyArg_ParseTuple(arg
, "O&:in", convmp
, &yy
))
1200 mp_div(0, &yy
, yy
, mm
->m
);
1201 z
= mp_pywrap(mpmont_mul(mm
, MP_NEW
, yy
, mm
->r2
));
1203 if (yy
) MP_DROP(yy
);
1207 static PyObject
*mmmeth_mul(PyObject
*me
, PyObject
*arg
)
1210 mp
*yy
= 0, *zz
= 0;
1212 if (!PyArg_ParseTuple(arg
, "O&O&:mul", convmp
, &yy
, convmp
, &zz
))
1214 rc
= mp_pywrap(mpmont_mul(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1216 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1220 static PyObject
*mmmeth_exp(PyObject
*me
, PyObject
*arg
)
1223 mp
*yy
= 0, *zz
= 0;
1225 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1228 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1229 zz
= mp_neg(zz
, zz
);
1231 rc
= mp_pywrap(mpmont_exp(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1233 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1237 static PyObject
*mmmeth_expr(PyObject
*me
, PyObject
*arg
)
1240 mp
*yy
= 0, *zz
= 0;
1242 if (!PyArg_ParseTuple(arg
, "O&O&:expr", convmp
, &yy
, convmp
, &zz
))
1245 yy
= mpmont_reduce(MPMONT_PY(me
), yy
, yy
);
1246 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1247 yy
= mpmont_mul(MPMONT_PY(me
), yy
, yy
, MPMONT_PY(me
)->r2
);
1248 zz
= mp_neg(zz
, zz
);
1250 rc
= mp_pywrap(mpmont_expr(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1252 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1256 static PyObject
*mm_mexpr_id(PyObject
*me
)
1257 { return mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
)); }
1259 static int mm_mexpr_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1261 mp
*xx
= 0, *yy
= 0;
1262 mp_expfactor
*f
= p
;
1263 mpmont
*mm
= MPMONT_PY(me
);
1265 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1268 xx
= mpmont_reduce(mm
, xx
, xx
);
1269 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1271 xx
= mpmont_mul(mm
, xx
, xx
, mm
->r2
);
1272 yy
= mp_neg(yy
, yy
);
1279 mp_drop(xx
); mp_drop(yy
);
1283 static PyObject
*mm_mexpr(PyObject
*me
, void *v
, int n
)
1284 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1286 static void mp_mexp_drop(void *p
)
1288 mp_expfactor
*f
= p
;
1293 static PyObject
*mmmeth_mexpr(PyObject
*me
, PyObject
*arg
)
1295 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1296 mm_mexpr_id
, mm_mexpr_fill
, mm_mexpr
, mp_mexp_drop
);
1299 static PyObject
*mp_mexp_id(PyObject
*me
)
1300 { return mp_pywrap(MP_ONE
); }
1302 static int mp_mexp_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1304 mp
*xx
= 0, *yy
= 0;
1305 mp_expfactor
*f
= p
;
1307 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1310 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1312 yy
= mp_neg(yy
, yy
);
1319 mp_drop(xx
); mp_drop(yy
);
1323 static PyObject
*mm_mexp(PyObject
*me
, void *v
, int n
)
1324 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1326 static PyObject
*mmmeth_mexp(PyObject
*me
, PyObject
*arg
)
1328 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1329 mp_mexp_id
, mp_mexp_fill
, mm_mexp
, mp_mexp_drop
);
1332 #define mmmeth_ext mmmeth_reduce
1333 static PyObject
*mmmeth_reduce(PyObject
*me
, PyObject
*arg
)
1338 if (!PyArg_ParseTuple(arg
, "O&", convmp
, &yy
)) goto end
;
1339 z
= mp_pywrap(mpmont_reduce(MPMONT_PY(me
), MP_NEW
, yy
));
1344 static void mpmont_pydealloc(PyObject
*me
)
1346 mpmont_destroy(MPMONT_PY(me
));
1350 static PyObject
*mpmont_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1352 mpmont_pyobj
*mm
= 0;
1353 static const char *const kwlist
[] = { "m", 0 };
1356 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1358 if (!MP_POSP(xx
) || !MP_ODDP(xx
)) VALERR("m must be positive and odd");
1359 mm
= (mpmont_pyobj
*)ty
->tp_alloc(ty
, 0);
1360 mpmont_create(&mm
->mm
, xx
);
1362 if (xx
) MP_DROP(xx
);
1363 return ((PyObject
*)mm
);
1366 static PyObject
*mmget_m(PyObject
*me
, void *hunoz
)
1367 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->m
))); }
1369 static PyObject
*mmget_r(PyObject
*me
, void *hunoz
)
1370 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
))); }
1372 static PyObject
*mmget_r2(PyObject
*me
, void *hunoz
)
1373 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r2
))); }
1375 static const PyGetSetDef mpmont_pygetset
[] = {
1376 #define GETSETNAME(op, name) mm##op##_##name
1377 GET (m
, "M.m -> modulus for reduction")
1378 GET (r
, "M.r -> multiplicative identity")
1379 GET (r2
, "M.r2 -> M.r^2, Montgomerization factor")
1384 static const PyMethodDef mpmont_pymethods
[] = {
1385 #define METHNAME(name) mmmeth_##name
1386 METH (int, "M.int(X) -> XR")
1387 METH (mul
, "M.mul(XR, YR) -> ZR where Z = X Y")
1388 METH (expr
, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1389 METH (mexpr
, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1390 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1391 "\t(the list may be flattened if this more convenient.)")
1392 METH (reduce
, "M.reduce(XR) -> X")
1393 METH (ext
, "M.ext(XR) -> X")
1394 METH (exp
, "M.exp(X, N) -> X^N mod M.m")
1395 METH (mexp
, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1396 "X0^N0 X1^N1 ... mod M.m\n"
1397 "\t(the list may be flattened if this more convenient.)")
1402 static const PyTypeObject mpmont_pytype_skel
= {
1403 PyVarObject_HEAD_INIT(0, 0) /* Header */
1404 "MPMont", /* @tp_name@ */
1405 sizeof(mpmont_pyobj
), /* @tp_basicsize@ */
1406 0, /* @tp_itemsize@ */
1408 mpmont_pydealloc
, /* @tp_dealloc@ */
1410 0, /* @tp_getattr@ */
1411 0, /* @tp_setattr@ */
1412 0, /* @tp_compare@ */
1414 0, /* @tp_as_number@ */
1415 0, /* @tp_as_sequence@ */
1416 0, /* @tp_as_mapping@ */
1420 0, /* @tp_getattro@ */
1421 0, /* @tp_setattro@ */
1422 0, /* @tp_as_buffer@ */
1423 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1424 Py_TPFLAGS_BASETYPE
,
1427 "MPMont(N): a Montgomery reduction context.",
1429 0, /* @tp_traverse@ */
1431 0, /* @tp_richcompare@ */
1432 0, /* @tp_weaklistoffset@ */
1434 0, /* @tp_iternext@ */
1435 PYMETHODS(mpmont
), /* @tp_methods@ */
1436 0, /* @tp_members@ */
1437 PYGETSET(mpmont
), /* @tp_getset@ */
1440 0, /* @tp_descr_get@ */
1441 0, /* @tp_descr_set@ */
1442 0, /* @tp_dictoffset@ */
1444 PyType_GenericAlloc
, /* @tp_alloc@ */
1445 mpmont_pynew
, /* @tp_new@ */
1450 /*----- Barrett reduction -------------------------------------------------*/
1452 static PyTypeObject
*mpbarrett_pytype
;
1454 typedef struct mpbarrett_pyobj
{
1459 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1461 static PyObject
*mbmeth_exp(PyObject
*me
, PyObject
*arg
)
1464 mp
*yy
= 0, *zz
= 0;
1466 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1469 if ((yy
= mp_modinv_checked(yy
, yy
, MPBARRETT_PY(me
)->m
)) == 0) goto end
;
1470 zz
= mp_neg(zz
, zz
);
1472 rc
= mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me
), MP_NEW
, yy
, zz
));
1474 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1478 static PyObject
*mb_mexp(PyObject
*me
, void *v
, int n
)
1479 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me
), MP_NEW
, v
, n
)); }
1481 static PyObject
*mbmeth_mexp(PyObject
*me
, PyObject
*arg
)
1483 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1484 mp_mexp_id
, mp_mexp_fill
, mb_mexp
, mp_mexp_drop
);
1487 static PyObject
*mbmeth_reduce(PyObject
*me
, PyObject
*arg
)
1492 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
))
1494 z
= mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me
), MP_NEW
, yy
));
1499 static void mpbarrett_pydealloc(PyObject
*me
)
1501 mpbarrett_destroy(MPBARRETT_PY(me
));
1505 static PyObject
*mpbarrett_pynew(PyTypeObject
*ty
,
1506 PyObject
*arg
, PyObject
*kw
)
1508 mpbarrett_pyobj
*mb
= 0;
1509 static const char *const kwlist
[] = { "m", 0 };
1512 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1514 if (!MP_POSP(xx
)) VALERR("m must be positive");
1515 mb
= (mpbarrett_pyobj
*)ty
->tp_alloc(ty
, 0);
1516 mpbarrett_create(&mb
->mb
, xx
);
1518 if (xx
) MP_DROP(xx
);
1519 return ((PyObject
*)mb
);
1522 static PyObject
*mbget_m(PyObject
*me
, void *hunoz
)
1523 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me
)->m
))); }
1525 static const PyGetSetDef mpbarrett_pygetset
[] = {
1526 #define GETSETNAME(op, name) mb##op##_##name
1527 GET (m
, "B.m -> modulus for reduction")
1532 static const PyMethodDef mpbarrett_pymethods
[] = {
1533 #define METHNAME(name) mbmeth_##name
1534 METH (reduce
, "B.reduce(X) -> X mod B.m")
1535 METH (exp
, "B.exp(X, N) -> X^N mod B.m")
1536 METH (mexp
, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1537 "X0^N0 X1^N1 ... mod B.m\n"
1538 "\t(the list may be flattened if this more convenient.)")
1543 static const PyTypeObject mpbarrett_pytype_skel
= {
1544 PyVarObject_HEAD_INIT(0, 0) /* Header */
1545 "MPBarrett", /* @tp_name@ */
1546 sizeof(mpbarrett_pyobj
), /* @tp_basicsize@ */
1547 0, /* @tp_itemsize@ */
1549 mpbarrett_pydealloc
, /* @tp_dealloc@ */
1551 0, /* @tp_getattr@ */
1552 0, /* @tp_setattr@ */
1553 0, /* @tp_compare@ */
1555 0, /* @tp_as_number@ */
1556 0, /* @tp_as_sequence@ */
1557 0, /* @tp_as_mapping@ */
1561 0, /* @tp_getattro@ */
1562 0, /* @tp_setattro@ */
1563 0, /* @tp_as_buffer@ */
1564 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1565 Py_TPFLAGS_BASETYPE
,
1568 "MPBarrett(N): a Barrett reduction context.",
1570 0, /* @tp_traverse@ */
1572 0, /* @tp_richcompare@ */
1573 0, /* @tp_weaklistoffset@ */
1575 0, /* @tp_iternext@ */
1576 PYMETHODS(mpbarrett
), /* @tp_methods@ */
1577 0, /* @tp_members@ */
1578 PYGETSET(mpbarrett
), /* @tp_getset@ */
1581 0, /* @tp_descr_get@ */
1582 0, /* @tp_descr_set@ */
1583 0, /* @tp_dictoffset@ */
1585 PyType_GenericAlloc
, /* @tp_alloc@ */
1586 mpbarrett_pynew
, /* @tp_new@ */
1591 /*----- Nice prime reduction ----------------------------------------------*/
1593 static PyTypeObject
*mpreduce_pytype
;
1595 typedef struct mpreduce_pyobj
{
1600 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1602 static PyObject
*mrmeth_exp(PyObject
*me
, PyObject
*arg
)
1605 mp
*yy
= 0, *zz
= 0;
1607 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1610 if ((yy
= mp_modinv_checked(yy
, yy
, MPREDUCE_PY(me
)->p
)) == 0) goto end
;
1611 zz
= mp_neg(zz
, zz
);
1613 rc
= mp_pywrap(mpreduce_exp(MPREDUCE_PY(me
), MP_NEW
, yy
, zz
));
1615 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1619 static PyObject
*mrmeth_reduce(PyObject
*me
, PyObject
*arg
)
1624 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
)) goto end
;
1625 z
= mp_pywrap(mpreduce_do(MPREDUCE_PY(me
), MP_NEW
, yy
));
1630 static void mpreduce_pydealloc(PyObject
*me
)
1632 mpreduce_destroy(MPREDUCE_PY(me
));
1636 static PyObject
*mpreduce_pynew(PyTypeObject
*ty
,
1637 PyObject
*arg
, PyObject
*kw
)
1639 mpreduce_pyobj
*mr
= 0;
1641 static const char *const kwlist
[] = { "m", 0 };
1644 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1646 if (!MP_POSP(xx
)) VALERR("m must be positive");
1647 if (mpreduce_create(&r
, xx
)) VALERR("bad modulus (must be 2^k - ...)");
1648 mr
= (mpreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
1651 if (xx
) MP_DROP(xx
);
1652 return ((PyObject
*)mr
);
1655 static PyObject
*mrget_m(PyObject
*me
, void *hunoz
)
1656 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me
)->p
))); }
1658 static const PyGetSetDef mpreduce_pygetset
[] = {
1659 #define GETSETNAME(op, name) mr##op##_##name
1660 GET (m
, "R.m -> modulus for reduction")
1665 static const const PyMethodDef mpreduce_pymethods
[] = {
1666 #define METHNAME(name) mrmeth_##name
1667 METH (reduce
, "R.reduce(X) -> X mod B.m")
1668 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
1673 static const PyTypeObject mpreduce_pytype_skel
= {
1674 PyVarObject_HEAD_INIT(0, 0) /* Header */
1675 "MPReduce", /* @tp_name@ */
1676 sizeof(mpreduce_pyobj
), /* @tp_basicsize@ */
1677 0, /* @tp_itemsize@ */
1679 mpreduce_pydealloc
, /* @tp_dealloc@ */
1681 0, /* @tp_getattr@ */
1682 0, /* @tp_setattr@ */
1683 0, /* @tp_compare@ */
1685 0, /* @tp_as_number@ */
1686 0, /* @tp_as_sequence@ */
1687 0, /* @tp_as_mapping@ */
1691 0, /* @tp_getattro@ */
1692 0, /* @tp_setattro@ */
1693 0, /* @tp_as_buffer@ */
1694 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1695 Py_TPFLAGS_BASETYPE
,
1698 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1700 0, /* @tp_traverse@ */
1702 0, /* @tp_richcompare@ */
1703 0, /* @tp_weaklistoffset@ */
1705 0, /* @tp_iternext@ */
1706 PYMETHODS(mpreduce
), /* @tp_methods@ */
1707 0, /* @tp_members@ */
1708 PYGETSET(mpreduce
), /* @tp_getset@ */
1711 0, /* @tp_descr_get@ */
1712 0, /* @tp_descr_set@ */
1713 0, /* @tp_dictoffset@ */
1715 PyType_GenericAlloc
, /* @tp_alloc@ */
1716 mpreduce_pynew
, /* @tp_new@ */
1721 /*----- Chinese Remainder Theorem solution --------------------------------*/
1723 static PyTypeObject
*mpcrt_pytype
;
1725 typedef struct mpcrt_pyobj
{
1730 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1732 static PyObject
*mcmeth_solve(PyObject
*me
, PyObject
*arg
)
1734 mpcrt
*c
= MPCRT_PY(me
);
1735 PyObject
*q
= 0, *x
, *z
= 0;
1738 Py_ssize_t i
= 0, n
= c
->k
;
1741 if (PyTuple_GET_SIZE(arg
) == n
)
1743 else if (!PyArg_ParseTuple(arg
, "O:solve", &q
))
1746 if (!PySequence_Check(q
)) TYERR("want a sequence of residues");
1747 i
= PySequence_Size(q
); if (i
< 0) goto end
;
1748 if (i
!= n
) VALERR("residue count mismatch");
1749 v
= xmalloc(n
* sizeof(*v
));
1750 for (i
= 0; i
< n
; i
++) {
1751 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1752 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1755 z
= mp_pywrap(mpcrt_solve(c
, MP_NEW
, v
));
1759 for (i
= 0; i
< n
; i
++)
1768 static void mpcrt_pydealloc(PyObject
*me
)
1770 mpcrt
*c
= MPCRT_PY(me
);
1775 static PyObject
*mpcrt_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1778 Py_ssize_t n
, i
= 0, j
;
1779 static const char *const kwlist
[] = { "mv", 0 };
1780 PyObject
*q
= 0, *x
;
1781 mp
*xx
= MP_NEW
, *y
= MP_NEW
, *g
= MP_NEW
;
1785 if (PyTuple_GET_SIZE(arg
) > 1)
1787 else if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O:new", KWLIST
, &q
))
1790 if (!PySequence_Check(q
)) TYERR("want a sequence of moduli");
1791 n
= PySequence_Size(q
); if (n
< 0) goto end
;
1792 if (!n
) VALERR("want at least one modulus");
1793 v
= xmalloc(n
* sizeof(*v
));
1794 for (i
= 0; i
< n
; i
++) {
1795 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1796 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1797 if (MP_CMP(xx
, <=, MP_ZERO
)) VALERR("moduli must be positive");
1798 v
[i
].m
= xx
; v
[i
].n
= 0; v
[i
].ni
= 0; v
[i
].nni
= 0; xx
= MP_NEW
;
1801 for (j
= 0; j
< i
; j
++) mpmul_add(&mm
, v
[j
].m
);
1802 xx
= mpmul_done(&mm
);
1803 for (j
= 0; j
< i
; j
++) {
1804 mp_div(&y
, 0, xx
, v
[j
].m
);
1805 mp_gcd(&g
, 0, 0, y
, v
[j
].m
);
1806 if (!MP_EQ(g
, MP_ONE
)) VALERR("moduli must be pairwise coprime");
1809 c
= (mpcrt_pyobj
*)ty
->tp_alloc(ty
, 0);
1810 mpcrt_create(&c
->c
, v
, n
, 0);
1812 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1813 return ((PyObject
*)c
);
1818 for (i
= 0; i
< n
; i
++)
1823 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1827 static PyObject
*mcget_product(PyObject
*me
, void *hunoz
)
1828 { return (mp_pywrap(MP_COPY(MPCRT_PY(me
)->mb
.m
))); }
1830 static PyObject
*mcget_moduli(PyObject
*me
, void *hunoz
)
1834 mpcrt
*c
= MPCRT_PY(me
);
1836 if ((q
= PyList_New(c
->k
)) == 0) return (0);
1837 for (i
= 0; i
< c
->k
; i
++)
1838 PyList_SET_ITEM(q
, i
, mp_pywrap(c
->v
[i
].m
));
1842 static const PyGetSetDef mpcrt_pygetset
[] = {
1843 #define GETSETNAME(op, name) mc##op##_##name
1844 GET (product
, "C.product -> product of moduli")
1845 GET (moduli
, "C.moduli -> list of individual moduli")
1850 static const PyMethodDef mpcrt_pymethods
[] = {
1851 #define METHNAME(name) mcmeth_##name
1852 METH (solve
, "C.solve([R0, R1]) -> X mod C.product")
1857 static const PyTypeObject mpcrt_pytype_skel
= {
1858 PyVarObject_HEAD_INIT(0, 0) /* Header */
1859 "MPCRT", /* @tp_name@ */
1860 sizeof(mpcrt_pyobj
), /* @tp_basicsize@ */
1861 0, /* @tp_itemsize@ */
1863 mpcrt_pydealloc
, /* @tp_dealloc@ */
1865 0, /* @tp_getattr@ */
1866 0, /* @tp_setattr@ */
1867 0, /* @tp_compare@ */
1869 0, /* @tp_as_number@ */
1870 0, /* @tp_as_sequence@ */
1871 0, /* @tp_as_mapping@ */
1875 0, /* @tp_getattro@ */
1876 0, /* @tp_setattro@ */
1877 0, /* @tp_as_buffer@ */
1878 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1879 Py_TPFLAGS_BASETYPE
,
1882 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1884 0, /* @tp_traverse@ */
1886 0, /* @tp_richcompare@ */
1887 0, /* @tp_weaklistoffset@ */
1889 0, /* @tp_iternext@ */
1890 PYMETHODS(mpcrt
), /* @tp_methods@ */
1891 0, /* @tp_members@ */
1892 PYGETSET(mpcrt
), /* @tp_getset@ */
1895 0, /* @tp_descr_get@ */
1896 0, /* @tp_descr_set@ */
1897 0, /* @tp_dictoffset@ */
1899 PyType_GenericAlloc
, /* @tp_alloc@ */
1900 mpcrt_pynew
, /* @tp_new@ */
1905 /*----- Binary polynomials ------------------------------------------------*/
1907 static PyObject
*gf_pyrepr(PyObject
*o
)
1908 { return mp_topystring(MP_X(o
), 16, "GF(", "0x", ")"); }
1910 static PyObject
*gf_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
1916 if (gfbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
1918 case Py_EQ
: b
= MP_EQ(xx
, yy
); break;
1919 case Py_NE
: b
= !MP_EQ(xx
, yy
); break;
1924 case Py_LT
: b
= xl
< yl
; break;
1925 case Py_LE
: b
= xl
<= yl
; break;
1926 case Py_GT
: b
= xl
> yl
; break;
1927 case Py_GE
: b
= xl
>= yl
; break;
1932 MP_DROP(xx
); MP_DROP(yy
);
1933 return (getbool(b
));
1936 static PyObject
*gf_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1942 static const char *const kwlist
[] = { "x", "radix", 0 };
1944 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:gf", KWLIST
, &x
, &radix
))
1946 if (GF_PYCHECK(x
)) RETURN_OBJ(x
);
1947 if (!good_radix_p(radix
, 1)) VALERR("radix out of range");
1948 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
1949 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
1950 Py_TYPE(x
)->tp_name
);
1955 VALERR("gf cannot be negative");
1957 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
1960 return ((PyObject
*)zz
);
1963 static PyObject
*gf_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
1965 mp
*xx
= 0, *yy
= 0, *zz
= 0;
1969 if ((xx
= tomp(x
)) == 0 || (yy
= tomp(y
)) == 0 ||
1970 (z
&& z
!= Py_None
&& (zz
= tomp(z
)) == 0)) {
1971 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
1974 if (!z
|| z
== Py_None
) {
1975 if (MP_NEGP(yy
)) VALERR("negative exponent");
1976 r
= gf_exp(MP_NEW
, xx
, yy
);
1979 if (MP_ZEROP(zz
)) ZDIVERR("zero modulus");
1981 if ((xx
= gf_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
1982 yy
= mp_neg(yy
, yy
);
1984 gfreduce_create(&gr
, zz
);
1985 r
= gfreduce_exp(&gr
, MP_NEW
, xx
, yy
);
1986 gfreduce_destroy(&gr
);
1990 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
1994 static PyObject
*gfmeth_sqr(PyObject
*me
)
1995 { return (gf_pywrap(gf_sqr(MP_NEW
, MP_X(me
)))); }
1997 static PyObject
*gfmeth_gcd(PyObject
*me
, PyObject
*arg
)
2000 mp
*yy
= 0, *zz
= MP_NEW
;
2002 if (!PyArg_ParseTuple(arg
, "O&:gcd", convgf
, &yy
)) goto end
;
2003 gf_gcd(&zz
, 0, 0, MP_X(me
), yy
);
2006 if (yy
) MP_DROP(yy
);
2010 static PyObject
*gfmeth_gcdx(PyObject
*me
, PyObject
*arg
)
2013 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
2015 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convgf
, &yy
))
2017 gf_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
2018 z
= Py_BuildValue("(NNN)",
2019 gf_pywrap(zz
), gf_pywrap(uu
), gf_pywrap(vv
));
2021 if (yy
) MP_DROP(yy
);
2025 static PyObject
*gfmeth_modinv(PyObject
*me
, PyObject
*arg
)
2028 mp
*yy
= 0, *zz
= MP_NEW
;
2030 if (!PyArg_ParseTuple(arg
, "O&:modinv", convgf
, &yy
) ||
2031 (zz
= gf_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
2035 if (yy
) MP_DROP(yy
);
2039 static PyObject
*gfmeth_fromstring(PyObject
*me
,
2040 PyObject
*arg
, PyObject
*kw
)
2047 mptext_stringctx sc
;
2048 static const char *const kwlist
[] = { "x", "radix", 0 };
2050 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
2053 if (!good_radix_p(r
, 1)) VALERR("bad radix");
2054 sc
.buf
= p
; sc
.lim
= p
+ len
;
2055 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0 ||
2057 if (zz
) MP_DROP(zz
);
2058 VALERR("bad binary polynomial");
2060 z
= Py_BuildValue("(Ns#)", gf_pywrap(zz
),
2061 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
2066 static PyObject
*gfmeth_irreduciblep(PyObject
*me
)
2067 { return getbool(gf_irreduciblep(MP_X(me
))); }
2069 static PyObject
*gfget_degree(PyObject
*me
, void *hunoz
)
2070 { return (PyInt_FromLong(mp_bits(MP_X(me
)) - 1)); }
2072 static const PyGetSetDef gf_pygetset
[] = {
2073 #define GETSETNAME(op, name) gf##op##_##name
2074 GET (degree
, "X.degree -> polynomial degree of X")
2076 #define GETSETNAME(op, name) mp##op##_##name
2077 GET (nbits
, "X.nbits -> bit length of X")
2078 GET (noctets
, "X.noctets -> octet length of X")
2083 static const PyMethodDef gf_pymethods
[] = {
2084 #define METHNAME(func) gfmeth_##func
2085 METH (setbit
, "X.setbit(N) -> X with bit N set")
2086 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
2087 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
2088 NAMETH(sqr
, "X.sqr() -> X^2")
2089 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
2090 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2091 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2092 NAMETH(irreduciblep
, "X.irreduciblep() -> true/false")
2093 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2094 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2095 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2096 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2097 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
2098 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
2099 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
2101 #define METHNAME(func) mpmeth_##func
2102 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
2103 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
2104 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
2105 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
2106 "little-endian bytes, two's complement")
2107 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
2108 "big-endian bytes, two's complement")
2109 NAMETH(tobuf
, "X.tobuf() -> buffer format")
2114 static const PyNumberMethods gf_pynumber
= {
2115 gf_pyadd
, /* @nb_add@ */
2116 gf_pysub
, /* @nb_subtract@ */
2117 gf_pymul
, /* @nb_multiply@ */
2118 0, /* @nb_divide@ */
2119 gf_pymod
, /* @nb_remainder@ */
2120 gf_pydivmod
, /* @nb_divmod@ */
2121 gf_pyexp
, /* @nb_power@ */
2122 mp_pyid
, /* @nb_negative@ */
2123 mp_pyid
, /* @nb_positive@ */
2124 mp_pyid
, /* @nb_absolute@ */
2125 mp_pynonzerop
, /* @nb_nonzero@ */
2126 0 /* doesn't make any sense */, /* @nb_invert@ */
2127 gf_pylsl
, /* @nb_lshift@ */
2128 gf_pylsr
, /* @nb_rshift@ */
2129 gf_pyand
, /* @nb_and@ */
2130 gf_pyxor
, /* @nb_xor@ */
2131 gf_pyor
, /* @nb_or@ */
2132 gf_pycoerce
, /* @nb_coerce@ */
2133 mp_pyint
, /* @nb_int@ */
2134 mp_pylong
, /* @nb_long@ */
2135 0 /* doesn't make any sense */, /* @nb_float@ */
2136 mp_pyoct
, /* @nb_oct@ */
2137 mp_pyhex
, /* @nb_hex@ */
2139 0, /* @nb_inplace_add@ */
2140 0, /* @nb_inplace_subtract@ */
2141 0, /* @nb_inplace_multiply@ */
2142 0, /* @nb_inplace_divide@ */
2143 0, /* @nb_inplace_remainder@ */
2144 0, /* @nb_inplace_power@ */
2145 0, /* @nb_inplace_lshift@ */
2146 0, /* @nb_inplace_rshift@ */
2147 0, /* @nb_inplace_and@ */
2148 0, /* @nb_inplace_xor@ */
2149 0, /* @nb_inplace_or@ */
2151 gf_pydiv
, /* @nb_floor_divide@ */
2152 0, /* @nb_true_divide@ */
2153 0, /* @nb_inplace_floor_divide@ */
2154 0, /* @nb_inplace_true_divide@ */
2156 mp_pyint
, /* @nb_index@ */
2159 static const PyTypeObject gf_pytype_skel
= {
2160 PyVarObject_HEAD_INIT(0, 0) /* Header */
2161 "GF", /* @tp_name@ */
2162 sizeof(mp_pyobj
), /* @tp_basicsize@ */
2163 0, /* @tp_itemsize@ */
2165 mp_pydealloc
, /* @tp_dealloc@ */
2167 0, /* @tp_getattr@ */
2168 0, /* @tp_setattr@ */
2169 0, /* @tp_compare@ */
2170 gf_pyrepr
, /* @tp_repr@ */
2171 PYNUMBER(gf
), /* @tp_as_number@ */
2172 0, /* @tp_as_sequence@ */
2173 0, /* @tp_as_mapping@ */
2174 mp_pyhash
, /* @tp_hash@ */
2176 mp_pyhex
, /* @tp_str@ */
2177 0, /* @tp_getattro@ */
2178 0, /* @tp_setattro@ */
2179 0, /* @tp_as_buffer@ */
2180 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2181 Py_TPFLAGS_CHECKTYPES
|
2182 Py_TPFLAGS_BASETYPE
,
2185 "Binary polynomials. Support almost all the standard arithmetic\n"
2188 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2189 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2190 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2191 "points, group elements, Python `int' and `long' objects, and anything\n"
2192 "with an integer conversion.\n"
2194 "The name is hopelessly wrong from a technical point of view, but\n"
2195 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2199 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2201 0, /* @tp_traverse@ */
2203 gf_pyrichcompare
, /* @tp_richcompare@ */
2204 0, /* @tp_weaklistoffset@ */
2206 0, /* @tp_iternext@ */
2207 PYMETHODS(gf
), /* @tp_methods@ */
2208 0, /* @tp_members@ */
2209 PYGETSET(gf
), /* @tp_getset@ */
2212 0, /* @tp_descr_get@ */
2213 0, /* @tp_descr_set@ */
2214 0, /* @tp_dictoffset@ */
2216 PyType_GenericAlloc
, /* @tp_alloc@ */
2217 gf_pynew
, /* @tp_new@ */
2222 /*----- Sparse poly reduction ---------------------------------------------*/
2224 static PyTypeObject
*gfreduce_pytype
;
2226 typedef struct gfreduce_pyobj
{
2231 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2233 static PyObject
*grmeth_exp(PyObject
*me
, PyObject
*arg
)
2236 mp
*yy
= 0, *zz
= 0;
2238 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convgf
, &yy
, convgf
, &zz
))
2241 if ((yy
= gf_modinv_checked(yy
, yy
, GFREDUCE_PY(me
)->p
)) == 0) goto end
;
2242 zz
= mp_neg(zz
, zz
);
2244 rc
= gf_pywrap(gfreduce_exp(GFREDUCE_PY(me
), MP_NEW
, yy
, zz
));
2246 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
2250 static PyObject
*grmeth_trace(PyObject
*me
, PyObject
*arg
)
2255 if (!PyArg_ParseTuple(arg
, "O&:trace", convgf
, &xx
)) goto end
;
2256 rc
= PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me
), xx
));
2258 if (xx
) MP_DROP(xx
);
2262 static PyObject
*grmeth_halftrace(PyObject
*me
, PyObject
*arg
)
2267 if (!PyArg_ParseTuple(arg
, "O&:halftrace", convgf
, &xx
)) goto end
;
2268 rc
= gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me
), MP_NEW
, xx
));
2270 if (xx
) MP_DROP(xx
);
2274 static PyObject
*grmeth_sqrt(PyObject
*me
, PyObject
*arg
)
2279 if (!PyArg_ParseTuple(arg
, "O&:sqrt", convgf
, &xx
)) goto end
;
2280 if ((yy
= gfreduce_sqrt(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2281 VALERR("no modular square root");
2284 if (xx
) MP_DROP(xx
);
2288 static PyObject
*grmeth_quadsolve(PyObject
*me
, PyObject
*arg
)
2293 if (!PyArg_ParseTuple(arg
, "O&:quadsolve", convgf
, &xx
)) goto end
;
2294 if ((yy
= gfreduce_quadsolve(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2295 VALERR("no solution found");
2298 if (xx
) MP_DROP(xx
);
2302 static PyObject
*grmeth_reduce(PyObject
*me
, PyObject
*arg
)
2307 if (!PyArg_ParseTuple(arg
, "O&:reduce", convgf
, &yy
)) goto end
;
2308 z
= gf_pywrap(gfreduce_do(GFREDUCE_PY(me
), MP_NEW
, yy
));
2313 static void gfreduce_pydealloc(PyObject
*me
)
2315 gfreduce_destroy(GFREDUCE_PY(me
));
2319 static PyObject
*gfreduce_pynew(PyTypeObject
*ty
,
2320 PyObject
*arg
, PyObject
*kw
)
2322 gfreduce_pyobj
*mr
= 0;
2324 static const char *const kwlist
[] = { "m", 0 };
2327 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convgf
, &xx
))
2329 if (MP_ZEROP(xx
)) ZDIVERR("modulus is zero!");
2330 gfreduce_create(&r
, xx
);
2331 mr
= (gfreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
2334 if (xx
) MP_DROP(xx
);
2335 return ((PyObject
*)mr
);
2338 static PyObject
*grget_m(PyObject
*me
, void *hunoz
)
2339 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me
)->p
))); }
2341 static const PyGetSetDef gfreduce_pygetset
[] = {
2342 #define GETSETNAME(op, name) gr##op##_##name
2343 GET (m
, "R.m -> reduction polynomial")
2348 static const PyMethodDef gfreduce_pymethods
[] = {
2349 #define METHNAME(name) grmeth_##name
2350 METH (reduce
, "R.reduce(X) -> X mod B.m")
2351 METH (trace
, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2352 METH (halftrace
, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2353 METH (sqrt
, "R.sqrt(X) -> Y where Y^2 = X mod R")
2354 METH (quadsolve
, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2355 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
2360 static const PyTypeObject gfreduce_pytype_skel
= {
2361 PyVarObject_HEAD_INIT(0, 0) /* Header */
2362 "GFReduce", /* @tp_name@ */
2363 sizeof(gfreduce_pyobj
), /* @tp_basicsize@ */
2364 0, /* @tp_itemsize@ */
2366 gfreduce_pydealloc
, /* @tp_dealloc@ */
2368 0, /* @tp_getattr@ */
2369 0, /* @tp_setattr@ */
2370 0, /* @tp_compare@ */
2372 0, /* @tp_as_number@ */
2373 0, /* @tp_as_sequence@ */
2374 0, /* @tp_as_mapping@ */
2378 0, /* @tp_getattro@ */
2379 0, /* @tp_setattro@ */
2380 0, /* @tp_as_buffer@ */
2381 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2382 Py_TPFLAGS_BASETYPE
,
2385 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2387 0, /* @tp_traverse@ */
2389 0, /* @tp_richcompare@ */
2390 0, /* @tp_weaklistoffset@ */
2392 0, /* @tp_iternext@ */
2393 PYMETHODS(gfreduce
), /* @tp_methods@ */
2394 0, /* @tp_members@ */
2395 PYGETSET(gfreduce
), /* @tp_getset@ */
2398 0, /* @tp_descr_get@ */
2399 0, /* @tp_descr_set@ */
2400 0, /* @tp_dictoffset@ */
2402 PyType_GenericAlloc
, /* @tp_alloc@ */
2403 gfreduce_pynew
, /* @tp_new@ */
2408 /*----- Normal/poly transformation ----------------------------------------*/
2410 static PyTypeObject
*gfn_pytype
;
2412 typedef struct gfn_pyobj
{
2418 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2419 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2420 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2422 static PyObject
*gfn_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
2424 mp
*p
= 0, *beta
= 0;
2426 static const char *const kwlist
[] = { "p", "beta", 0 };
2428 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&O&:new", KWLIST
,
2429 convgf
, &p
, convgf
, &beta
))
2431 gg
= PyObject_New(gfn_pyobj
, ty
);
2433 if (gfn_create(p
, beta
, &gg
->ntop
, &gg
->pton
)) {
2436 VALERR("can't invert transformation matrix");
2442 return ((PyObject
*)gg
);
2445 static PyObject
*gfnget_p(PyObject
*me
, void *hunoz
)
2446 { return (gf_pywrap(MP_COPY(GFN_P(me
)))); }
2448 static PyObject
*gfnget_beta(PyObject
*me
, void *hunoz
)
2450 gfn
*n
= GFN_NTOP(me
);
2451 mp
*x
= n
->r
[n
->n
- 1];
2452 return (gf_pywrap(MP_COPY(x
)));
2455 #define XFORMOP(name, NAME) \
2456 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2461 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2462 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2465 if (!z) return (0); \
2466 return (gf_pywrap(z)); \
2472 static void gfn_pydealloc(PyObject
*me
)
2476 gfn_destroy(GFN_PTON(me
));
2477 gfn_destroy(GFN_NTOP(me
));
2482 static const PyGetSetDef gfn_pygetset
[] = {
2483 #define GETSETNAME(op, name) gfn##op##_##name
2484 GET (p
, "X.p -> polynomial basis, as polynomial")
2485 GET (beta
, "X.beta -> normal basis element, in poly form")
2490 static const PyMethodDef gfn_pymethods
[] = {
2491 #define METHNAME(name) gfnmeth_##name
2492 METH (pton
, "X.pton(A) -> normal-basis representation of A")
2493 METH (ntop
, "X.ntop(A) -> polynomial-basis representation of A")
2498 static const PyTypeObject gfn_pytype_skel
= {
2499 PyVarObject_HEAD_INIT(0, 0) /* Header */
2500 "GFN", /* @tp_name@ */
2501 sizeof(gfn_pyobj
), /* @tp_basicsize@ */
2502 0, /* @tp_itemsize@ */
2504 gfn_pydealloc
, /* @tp_dealloc@ */
2506 0, /* @tp_getattr@ */
2507 0, /* @tp_setattr@ */
2508 0, /* @tp_compare@ */
2510 0, /* @tp_as_number@ */
2511 0, /* @tp_as_sequence@ */
2512 0, /* @tp_as_mapping@ */
2516 0, /* @tp_getattro@ */
2517 0, /* @tp_setattro@ */
2518 0, /* @tp_as_buffer@ */
2519 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2520 Py_TPFLAGS_BASETYPE
,
2523 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2524 " between polynomial and normal basis representations.",
2526 0, /* @tp_traverse@ */
2528 0, /* @tp_richcompare@ */
2529 0, /* @tp_weaklistoffset@ */
2531 0, /* @tp_iternext@ */
2532 PYMETHODS(gfn
), /* @tp_methods@ */
2533 0, /* @tp_members@ */
2534 PYGETSET(gfn
), /* @tp_getset@ */
2537 0, /* @tp_descr_get@ */
2538 0, /* @tp_descr_set@ */
2539 0, /* @tp_dictoffset@ */
2541 PyType_GenericAlloc
, /* @tp_alloc@ */
2542 gfn_pynew
, /* @tp_new@ */
2547 /*----- Glue --------------------------------------------------------------*/
2549 static const struct nameval consts
[] = {
2554 void mp_pyinit(void)
2558 INITTYPE(mpmul
, root
);
2559 INITTYPE(mpmont
, root
);
2560 INITTYPE(mpbarrett
, root
);
2561 INITTYPE(mpreduce
, root
);
2562 INITTYPE(mpcrt
, root
);
2563 INITTYPE(gfreduce
, root
);
2564 INITTYPE(gfn
, root
);
2567 void mp_pyinsert(PyObject
*mod
)
2569 INSERT("MP", mp_pytype
);
2570 INSERT("MPMul", mpmul_pytype
);
2571 INSERT("MPMont", mpmont_pytype
);
2572 INSERT("MPBarrett", mpbarrett_pytype
);
2573 INSERT("MPReduce", mpreduce_pytype
);
2574 INSERT("MPCRT", mpcrt_pytype
);
2575 INSERT("GF", gf_pytype
);
2576 INSERT("GFReduce", gfreduce_pytype
);
2577 INSERT("GFN", gfn_pytype
);
2578 setconstants(mod
, consts
);
2581 /*----- That's all, folks -------------------------------------------------*/