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 long j
= PyLong_AsLongAndOverflow(obj
, &ov
);
62 if (!ov
) return mp_fromlong(MP_NEW
, j
);
67 bits
= (unsigned long)sz
* PyLong_SHIFT
;
68 w
= (bits
+ MPW_BITS
- 1)/MPW_BITS
;
69 x
= mp_new(w
, Py_SIZE(l
) < 0 ? MP_NEG
: 0);
71 for (i
= 0; i
< sz
; i
++) {
72 r
|= (mpd
)l
->ob_digit
[i
] << b
;
74 while (b
>= MPW_BITS
) {
89 PyObject
*mp_topylong(mp
*x
)
91 unsigned long bits
= mp_bits(x
);
92 int sz
= (bits
+ PyLong_SHIFT
- 1)/PyLong_SHIFT
;
93 PyLongObject
*l
= _PyLong_New(sz
);
99 while (i
< sz
&& p
< x
->vl
) {
102 while (i
< sz
&& b
>= PyLong_SHIFT
) {
103 l
->ob_digit
[i
++] = r
& PyLong_MASK
;
108 while (i
< sz
&& r
) {
109 l
->ob_digit
[i
++] = r
& PyLong_MASK
;
112 Py_SIZE(l
) = (x
->f
& MP_NEG
) ?
-sz
: sz
;
113 return ((PyObject
*)l
);
116 mp
*mp_frompyobject(PyObject
*o
, int radix
)
124 TEXT_PTRLEN(o
, sc
.buf
, sz
); sc
.lim
= sc
.buf
+ sz
;
125 x
= mp_read(MP_NEW
, radix
, &mptext_stringops
, &sc
);
127 if (sc
.buf
< sc
.lim
) { MP_DROP(x
); return (0); }
130 if ((x
= tomp(o
)) != 0)
135 PyObject
*mp_topystring(mp
*x
, int radix
, const char *xpre
,
136 const char *pre
, const char *post
)
138 int len
= mptext_len(x
, radix
) + 1;
141 size_t xprelen
= xpre ?
strlen(xpre
) : 0;
142 size_t prelen
= pre ?
strlen(pre
) : 0;
143 size_t postlen
= post ?
strlen(post
) : 0;
146 TEXT_PREPAREWRITE(o
, p
, len
+ 1 + xprelen
+ prelen
+ postlen
);
148 if (xpre
) { memcpy(sc
.buf
, xpre
, xprelen
); sc
.buf
+= xprelen
; }
149 if (MP_NEGP(x
)) { *sc
.buf
++ = '-'; x
= mp_neg(x
, x
); }
150 if (pre
) { memcpy(sc
.buf
, pre
, prelen
); sc
.buf
+= prelen
; }
151 sc
.lim
= sc
.buf
+ len
;
152 mp_write(x
, radix
, &mptext_stringops
, &sc
);
153 if (post
) { memcpy(sc
.buf
, post
, postlen
); sc
.buf
+= postlen
; }
155 TEXT_DONEWRITE(o
, sc
.buf
- p
);
159 static int good_radix_p(int r
, int readp
)
161 return ((r
>= -255 && r
<= -2) ||
163 (r
>= 2 && r
<= 62));
166 PyObject
*mp_pywrap(mp
*x
)
168 mp_pyobj
*z
= PyObject_New(mp_pyobj
, mp_pytype
);
170 return ((PyObject
*)z
);
173 PyObject
*gf_pywrap(mp
*x
)
175 mp_pyobj
*z
= PyObject_New(mp_pyobj
, gf_pytype
);
177 return ((PyObject
*)z
);
180 int mp_tolong_checked(mp
*x
, long *l
, int must
)
182 static mp
*longmin
= 0, *longmax
= 0;
186 longmin
= mp_fromlong(MP_NEW
, LONG_MIN
);
187 longmax
= mp_fromlong(MP_NEW
, LONG_MAX
);
189 if (MP_CMP(x
, <, longmin
) || MP_CMP(x
, >, longmax
)) {
190 if (must
) VALERR("mp out of range for int");
199 /*----- Python interface --------------------------------------------------*/
201 static void mp_pydealloc(PyObject
*o
)
207 static PyObject
*mp_pyrepr(PyObject
*o
)
208 { return mp_topystring(MP_X(o
), 10, "MP(", 0, ")"); }
210 static PyObject
*mp_pystr(PyObject
*o
)
211 { return mp_topystring(MP_X(o
), 10, 0, 0, 0); }
213 mp
*tomp(PyObject
*o
)
218 if (!o
|| PyFloat_Check(o
))
220 else if (MP_PYCHECK(o
) || GF_PYCHECK(o
))
221 return (MP_COPY(MP_X(o
)));
222 else if (FE_PYCHECK(o
))
223 return (F_OUT(FE_F(o
), MP_NEW
, FE_X(o
)));
224 else if (PFILT_PYCHECK(o
))
225 return (MP_COPY(PFILT_F(o
)->m
));
226 else if (ECPT_PYCHECK(o
)) {
228 if (EC_ATINF(ECPT_P(o
))) return (0);
233 } else if (GE_PYCHECK(o
)) {
234 if ((x
= G_TOINT(GE_G(o
), MP_NEW
, GE_X(o
))) == 0)
239 else if (PyInt_Check(o
))
240 return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
242 else if ((l
= PyNumber_Long(o
)) != 0) {
243 x
= mp_frompylong(l
);
252 mp
*getmp(PyObject
*o
)
256 if ((x
= tomp(o
)) == 0) {
257 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
258 Py_TYPE(o
)->tp_name
);
263 int convmp(PyObject
*o
, void *p
)
266 if ((x
= getmp(o
)) == 0) return (0);
271 mp
*getgf(PyObject
*o
)
275 if ((x
= tomp(o
)) == 0) {
276 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
277 Py_TYPE(o
)->tp_name
);
282 int convgf(PyObject
*o
, void *p
)
285 if ((x
= getgf(o
)) == 0) return (0);
290 mp
*implicitmp(PyObject
*o
)
301 mp
*implicitgf(PyObject
*o
)
312 static int mpbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
314 if ((*xx
= implicitmp(x
)) == 0)
316 if ((*yy
= implicitmp(y
)) == 0) {
323 static int gfbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
325 if ((*xx
= implicitgf(x
)) == 0)
327 if ((*yy
= implicitgf(y
)) == 0) {
334 #define FPBINOP(name, pyop) \
335 static PyObject *mp_py##name(PyObject *x, PyObject *y) { \
338 if (PyFloat_Check(x)) { \
339 l = mp_topylong(MP_X(y)); rc = PyNumber_##pyop(x, l); \
340 Py_DECREF(l); return (rc); \
341 } else if (PyFloat_Check(y)) { \
342 l = mp_topylong(MP_X(x)); rc = PyNumber_##pyop(l, y); \
343 Py_DECREF(l); return (rc); \
345 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
346 zz = mp_##name(MP_NEW, xx, yy); \
347 MP_DROP(xx); MP_DROP(yy); \
348 return (mp_pywrap(zz)); \
351 FPBINOP(sub
, Subtract
)
352 FPBINOP(mul
, Multiply
)
354 #define gf_and mp_and
356 #define gf_xor mp_xor
357 #define BINOP(pre, name) \
358 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
360 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
361 zz = pre##_##name(MP_NEW, xx, yy); \
362 MP_DROP(xx); MP_DROP(yy); \
363 return (pre##_pywrap(zz)); \
376 static mp
*mp_abs(mp
*d
, mp
*x
)
379 return (mp_neg(d
, x
));
385 #define UNOP(pre, name) \
386 static PyObject *pre##_py##name(PyObject *x) \
387 { return mp_pywrap(pre##_##name(MP_NEW, MP_X(x))); }
393 static PyObject
*mp_pyid(PyObject
*x
) { RETURN_OBJ(x
); }
395 #define gf_lsr mp_lsr
396 #define SHIFTOP(pre, PRE, name, rname) \
397 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
401 if (!PRE##_PYCHECK(x)) RETURN_NOTIMPL; \
402 if (GF_PYCHECK(y) || FE_PYCHECK(y)) RETURN_NOTIMPL; \
403 yix = PyNumber_Index(y); if (!yix) { PyErr_Clear(); RETURN_NOTIMPL; } \
404 n = PyInt_AsLong(yix); Py_DECREF(yix); \
405 if (n == -1 && PyErr_Occurred()) { PyErr_Clear(); RETURN_NOTIMPL; } \
406 if (n < 0) z = pre##_pywrap(mp_##rname(MP_NEW, MP_X(x), -n)); \
407 else z = pre##_pywrap(mp_##name(MP_NEW, MP_X(x), n)); \
410 SHIFTOP(mp
, MP
, lsl2c
, lsr2c
)
411 SHIFTOP(mp
, MP
, lsr2c
, lsl2c
)
412 SHIFTOP(gf
, GF
, lsl
, lsr
)
413 SHIFTOP(gf
, GF
, lsr
, lsl
)
416 #define DIVOP(pre, name, qq, rr, gather) \
417 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
420 INIT_##qq(q) INIT_##rr(r) \
421 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
423 ZDIVERR("division by zero"); \
424 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
427 MP_DROP(xx); MP_DROP(yy); \
430 #define INIT_YES(p) mp *p = MP_NEW;
432 #define ARG_YES(p) &p
434 DIVOP(mp
, divmod
, YES
, YES
,
435 Py_BuildValue("(NN)", mp_pywrap(q
), mp_pywrap(r
)))
436 DIVOP(mp
, div
, YES
, NO
, mp_pywrap(q
))
437 DIVOP(mp
, mod
, NO
, YES
, mp_pywrap(r
))
438 DIVOP(gf
, divmod
, YES
, YES
,
439 Py_BuildValue("(NN)", gf_pywrap(q
), gf_pywrap(r
)))
440 DIVOP(gf
, div
, YES
, NO
, gf_pywrap(q
))
441 DIVOP(gf
, mod
, NO
, YES
, gf_pywrap(r
))
448 static mp
*mp_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
451 mp_gcd(&g
, 0, &d
, p
, x
);
452 if (!MP_EQ(g
, MP_ONE
)) {
453 MP_DROP(g
); MP_DROP(d
);
454 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
457 MP_DROP(g
); return (d
);
460 static PyObject
*mp_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
462 mp
*xx
= 0, *yy
= 0, *zz
= 0;
466 if ((xx
= implicitmp(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
467 (z
&& z
!= Py_None
&& (zz
= implicitmp(z
)) == 0)) {
468 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
471 if (!z
|| z
== Py_None
) {
472 if (MP_NEGP(yy
)) VALERR("negative exponent");
473 r
= mp_exp(MP_NEW
, xx
, yy
);
475 if (!MP_POSP(zz
)) VALERR("modulus must be positive");
477 if ((xx
= mp_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
482 mpmont_create(&mm
, zz
);
483 r
= mpmont_exp(&mm
, MP_NEW
, xx
, yy
);
487 mpbarrett_create(&mb
, zz
);
488 r
= mpbarrett_exp(&mb
, MP_NEW
, xx
, yy
);
489 mpbarrett_destroy(&mb
);
494 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
498 static mp
*gf_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
501 gf_gcd(&g
, 0, &d
, p
, x
);
502 if (!MP_EQ(g
, MP_ONE
)) {
503 MP_DROP(g
); MP_DROP(d
);
504 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
507 MP_DROP(g
); return (d
);
510 #define BASEOP(name, radix, pre) \
511 static PyObject *mp_py##name(PyObject *x) \
512 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
516 BASEOP(hex
, 16, "0x");
519 static int mp_pynonzerop(PyObject
*x
) { return !MP_ZEROP(MP_X(x
)); }
521 static PyObject
*mp_pyint(PyObject
*x
)
524 if (!mp_tolong_checked(MP_X(x
), &l
, 0)) return (PyInt_FromLong(l
));
525 else return mp_topylong(MP_X(x
));
528 static PyObject
*mp_pylong(PyObject
*x
)
529 { return (mp_topylong(MP_X(x
))); }
531 static PyObject
*mp_pyfloat(PyObject
*x
)
533 PyObject
*l
= mp_topylong(MP_X(x
));
534 double f
= PyLong_AsDouble(l
);
536 return (PyFloat_FromDouble(f
));
540 #define COERCE(pre, PRE) \
541 static int pre##_pycoerce(PyObject **x, PyObject **y) \
545 if (PRE##_PYCHECK(*y)) { \
546 Py_INCREF(*x); Py_INCREF(*y); \
549 if ((z = implicit##pre(*y)) != 0) { \
551 *y = pre##_pywrap(z); \
561 static PyObject
*mp_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
565 if (PyFloat_Check(y
)) {
566 l
= mp_topylong(MP_X(x
)); rc
= PyObject_RichCompare(l
, y
, op
);
567 Py_DECREF(l
); return (rc
);
569 if (mpbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
570 rc
= enrich_compare(op
, mp_cmp(xx
, yy
));
571 MP_DROP(xx
); MP_DROP(yy
);
576 static int mp_pycompare(PyObject
*x
, PyObject
*y
)
577 { return mp_cmp(MP_X(x
), MP_X(y
)); }
580 static PyObject
*mp_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
586 static const char *const kwlist
[] = { "x", "radix", 0 };
588 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:new", KWLIST
, &x
, &radix
))
590 if (MP_PYCHECK(x
)) RETURN_OBJ(x
);
591 if (!good_radix_p(radix
, 1)) VALERR("bad radix");
592 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
593 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
594 Py_TYPE(x
)->tp_name
);
597 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
600 return ((PyObject
*)zz
);
603 Py_hash_t
mphash(mp
*x
)
605 PyObject
*l
= mp_topylong(x
);
606 Py_hash_t h
= PyObject_Hash(l
);
607 Py_DECREF(l
); return (h
);
610 static Py_hash_t
mp_pyhash(PyObject
*me
) { return (mphash(MP_X(me
))); }
612 static PyObject
*mpmeth_jacobi(PyObject
*me
, PyObject
*arg
)
617 if (!PyArg_ParseTuple(arg
, "O&:jacobi", convmp
, &y
)) goto end
;
618 z
= PyInt_FromLong(mp_jacobi(y
, MP_X(me
)));
624 #define BITOP(pre, name, c) \
625 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
628 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
629 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
631 BITOP(mp
, setbit
, 2c
);
632 BITOP(mp
, clearbit
, 2c
);
634 BITOP(gf
, clearbit
, );
637 static PyObject
*mpmeth_testbit(PyObject
*me
, PyObject
*arg
)
640 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
641 return (getbool(mp_testbit2c(MP_X(me
), i
)));
644 static PyObject
*gfmeth_testbit(PyObject
*me
, PyObject
*arg
)
647 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
648 return (getbool(mp_testbit(MP_X(me
), i
)));
651 static PyObject
*mpmeth_odd(PyObject
*me
)
656 t
= mp_odd(MP_NEW
, MP_X(me
), &s
);
657 return (Py_BuildValue("(lN)", (long)s
, mp_pywrap(t
)));
660 static PyObject
*mpmeth_sqr(PyObject
*me
)
661 { return (mp_pywrap(mp_sqr(MP_NEW
, MP_X(me
)))); }
663 static PyObject
*mpmeth_sqrt(PyObject
*me
)
665 if (MP_NEGP(MP_X(me
))) VALERR("negative root");
666 return (mp_pywrap(mp_sqrt(MP_NEW
, MP_X(me
))));
671 static PyObject
*mpmeth_gcd(PyObject
*me
, PyObject
*arg
)
673 mp
*y
= 0, *zz
= MP_NEW
;
676 if (!PyArg_ParseTuple(arg
, "O&:gcd", convmp
, &y
)) goto end
;
677 mp_gcd(&zz
, 0, 0, MP_X(me
), y
);
684 static PyObject
*mpmeth_gcdx(PyObject
*me
, PyObject
*arg
)
687 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
689 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convmp
, &yy
)) goto end
;
690 mp_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
691 z
= Py_BuildValue("(NNN)",
692 mp_pywrap(zz
), mp_pywrap(uu
), mp_pywrap(vv
));
698 static PyObject
*mpmeth_modinv(PyObject
*me
, PyObject
*arg
)
701 mp
*yy
= 0, *zz
= MP_NEW
;
703 if (!PyArg_ParseTuple(arg
, "O&:modinv", convmp
, &yy
) ||
704 (zz
= mp_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
712 static PyObject
*mpmeth_tostring(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
715 static const char *const kwlist
[] = { "radix", 0 };
716 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|i:tostring", KWLIST
, &radix
))
718 if (!good_radix_p(radix
, 0)) VALERR("bad radix");
719 return (mp_topystring(MP_X(me
), radix
, 0, 0, 0));
724 static PyObject
*mpmeth_modsqrt(PyObject
*me
, PyObject
*arg
)
727 mp
*yy
= 0, *zz
= MP_NEW
;
729 if (!PyArg_ParseTuple(arg
, "O&:modsqrt", convmp
, &yy
)) goto end
;
730 if ((zz
= mp_modsqrt(MP_NEW
, yy
, MP_X(me
))) == 0)
731 VALERR("no modular square root");
738 static PyObject
*mpmeth_leastcongruent(PyObject
*me
, PyObject
*arg
)
743 if (!PyArg_ParseTuple(arg
, "O&O&:leastcongruent", convmp
, &b
, convmp
, &m
))
745 z
= mp_leastcongruent(MP_NEW
, b
, MP_X(me
), m
);
751 #define STOREOP(name, c) \
752 static PyObject *mpmeth_##name(PyObject *me, \
753 PyObject *arg, PyObject *kw) \
756 static const char *const kwlist[] = { "len", 0 }; \
759 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
763 len = mp_octets##c(MP_X(me)); \
766 rc = bytestring_pywrap(0, len); \
767 mp_##name(MP_X(me), BIN_PTR(rc), len); \
773 STOREOP(storel2c
, 2c
)
774 STOREOP(storeb2c
, 2c
)
778 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
785 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
786 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
787 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
788 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
789 bytestring_pywrapbuf(&b)); \
797 static PyObject
*mpmeth_tobuf(PyObject
*me
)
805 n
= mp_octets(x
) + 3;
806 rc
= bytestring_pywrap(0, n
);
807 buf_init(&b
, BIN_PTR(rc
), n
);
810 BIN_SETLEN(rc
, BLEN(&b
));
814 static PyObject
*mpmeth_primep(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
816 grand
*r
= &rand_global
;
817 static const char *const kwlist
[] = { "rng", 0 };
820 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|O&", KWLIST
, convgrand
, &r
))
822 rc
= getbool(pgen_primep(MP_X(me
), r
));
827 static PyObject
*mpmeth_fromstring(PyObject
*me
,
828 PyObject
*arg
, PyObject
*kw
)
836 static const char *const kwlist
[] = { "x", "radix", 0 };
838 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
841 if (!good_radix_p(r
, 1)) VALERR("bad radix");
842 sc
.buf
= p
; sc
.lim
= p
+ len
;
843 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0)
844 VALERR("bad integer");
845 z
= Py_BuildValue("(Ns#)", mp_pywrap(zz
),
846 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
851 static PyObject
*mpmeth_factorial(PyObject
*me
, PyObject
*arg
)
855 if (!PyArg_ParseTuple(arg
, "O&:factorial", convulong
, &i
)) return (0);
860 static PyObject
*mpmeth_fibonacci(PyObject
*me
, PyObject
*arg
)
864 if (!PyArg_ParseTuple(arg
, "l:fibonacci", &i
)) return (0);
869 #define LOADOP(pre, name) \
870 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
873 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
874 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
884 static PyObject
*mpget_nbits(PyObject
*me
, void *hunoz
)
885 { return (PyInt_FromLong(mp_bits(MP_X(me
)))); }
887 static PyObject
*mpget_noctets(PyObject
*me
, void *hunoz
)
888 { return (PyInt_FromLong(mp_octets(MP_X(me
)))); }
890 static PyObject
*mpget_noctets2c(PyObject
*me
, void *hunoz
)
891 { return (PyInt_FromLong(mp_octets2c(MP_X(me
)))); }
893 static const PyGetSetDef mp_pygetset
[] = {
894 #define GETSETNAME(op, func) mp##op##_##func
895 GET (nbits
, "X.nbits -> bit length of X")
896 GET (noctets
, "X.noctets -> octet length of X")
897 GET (noctets2c
, "X.noctets2c -> two's complement octet length of X")
902 static const PyMethodDef mp_pymethods
[] = {
903 #define METHNAME(func) mpmeth_##func
904 METH (jacobi
, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
905 METH (setbit
, "X.setbit(N) -> X with bit N set")
906 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
907 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
908 NAMETH(odd
, "X.odd() -> S, T where X = 2^S T with T odd")
909 NAMETH(sqr
, "X.sqr() -> X^2")
910 NAMETH(sqrt
, "X.sqrt() -> largest integer <= sqrt(X)")
911 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
912 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
913 "with X U + Y V = gcd(X, Y)")
914 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
915 METH (modsqrt
, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
916 METH (leastcongruent
, "X.leastcongruent(B, M) -> "
917 "smallest Z >= B with Z == X (mod M)")
918 KWMETH(primep
, "X.primep([rng = rand]) -> X is prime?")
919 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
920 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
921 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
922 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
923 "little-endian bytes, two's complement")
924 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
925 "big-endian bytes, two's complement")
926 NAMETH(tobuf
, "X.tobuf() -> buffer format")
927 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
928 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
929 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
930 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
931 SMTH (factorial
, "factorial(I) -> I!: compute factorial")
932 SMTH (fibonacci
, "fibonacci(I) -> F(I): compute Fibonacci number")
933 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
934 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
935 SMTH (loadl2c
, "loadl2c(STR) -> X: "
936 "read little-endian bytes, two's complement")
937 SMTH (loadb2c
, "loadb2c(STR) -> X: "
938 "read big-endian bytes, two's complement")
939 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
944 static const PyNumberMethods mp_pynumber
= {
945 mp_pyadd
, /* @nb_add@ */
946 mp_pysub
, /* @nb_subtract@ */
947 mp_pymul
, /* @nb_multiply@ */
951 mp_pymod
, /* @nb_remainder@ */
952 mp_pydivmod
, /* @nb_divmod@ */
953 mp_pyexp
, /* @nb_power@ */
954 mp_pyneg
, /* @nb_negative@ */
955 mp_pyid
, /* @nb_positive@ */
956 mp_pyabs
, /* @nb_absolute@ */
957 mp_pynonzerop
, /* @nb_nonzero@ */
958 mp_pynot2c
, /* @nb_invert@ */
959 mp_pylsl2c
, /* @nb_lshift@ */
960 mp_pylsr2c
, /* @nb_rshift@ */
961 mp_pyand2c
, /* @nb_and@ */
962 mp_pyxor2c
, /* @nb_xor@ */
963 mp_pyor2c
, /* @nb_or@ */
965 mp_pycoerce
, /* @nb_coerce@ */
967 mp_pyint
, /* @nb_int@ */
968 PY23(mp_pylong
, 0), /* @nb_long@ */
969 mp_pyfloat
, /* @nb_float@ */
971 mp_pyoct
, /* @nb_oct@ */
972 mp_pyhex
, /* @nb_hex@ */
975 0, /* @nb_inplace_add@ */
976 0, /* @nb_inplace_subtract@ */
977 0, /* @nb_inplace_multiply@ */
979 0, /* @nb_inplace_divide@ */
981 0, /* @nb_inplace_remainder@ */
982 0, /* @nb_inplace_power@ */
983 0, /* @nb_inplace_lshift@ */
984 0, /* @nb_inplace_rshift@ */
985 0, /* @nb_inplace_and@ */
986 0, /* @nb_inplace_xor@ */
987 0, /* @nb_inplace_or@ */
989 mp_pydiv
, /* @nb_floor_divide@ */
990 0, /* @nb_true_divide@ */
991 0, /* @nb_inplace_floor_divide@ */
992 0, /* @nb_inplace_true_divide@ */
994 mp_pyint
, /* @nb_index@ */
997 static const PyTypeObject mp_pytype_skel
= {
998 PyVarObject_HEAD_INIT(0, 0) /* Header */
999 "MP", /* @tp_name@ */
1000 sizeof(mp_pyobj
), /* @tp_basicsize@ */
1001 0, /* @tp_itemsize@ */
1003 mp_pydealloc
, /* @tp_dealloc@ */
1005 0, /* @tp_getattr@ */
1006 0, /* @tp_setattr@ */
1007 PY23(mp_pycompare
, 0), /* @tp_compare@/@tp_as_async@ */
1008 mp_pyrepr
, /* @tp_repr@ */
1009 PYNUMBER(mp
), /* @tp_as_number@ */
1010 0, /* @tp_as_sequence@ */
1011 0, /* @tp_as_mapping@ */
1012 mp_pyhash
, /* @tp_hash@ */
1014 mp_pystr
, /* @tp_str@ */
1015 0, /* @tp_getattro@ */
1016 0, /* @tp_setattro@ */
1017 0, /* @tp_as_buffer@ */
1018 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1019 Py_TPFLAGS_CHECKTYPES
|
1020 Py_TPFLAGS_BASETYPE
,
1023 "Multiprecision integers, similar to `long' but more efficient and\n"
1024 "versatile. Support all the standard arithmetic operations, with\n"
1025 "implicit conversions from `PrimeFilter', and other objects which\n"
1026 "convert to `" PY23("long", "int") "'.\n"
1028 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1029 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1030 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1032 "points, group elements, Python `int' and `long' objects, and anything\n"
1033 "with an integer conversion.\n",
1034 "points, group elements, Python `int' objects, and anything with an\n"
1035 "integer conversion.\n")
1039 " * Use `//' for integer division: `/' gives exact rational division.",
1041 0, /* @tp_traverse@ */
1043 mp_pyrichcompare
, /* @tp_richcompare@ */
1044 0, /* @tp_weaklistoffset@ */
1046 0, /* @tp_iternext@ */
1047 PYMETHODS(mp
), /* @tp_methods@ */
1048 0, /* @tp_members@ */
1049 PYGETSET(mp
), /* @tp_getset@ */
1052 0, /* @tp_descr_get@ */
1053 0, /* @tp_descr_set@ */
1054 0, /* @tp_dictoffset@ */
1056 PyType_GenericAlloc
, /* @tp_alloc@ */
1057 mp_pynew
, /* @tp_new@ */
1062 /*----- Products of small integers ----------------------------------------*/
1064 static PyTypeObject
*mpmul_pytype
;
1066 typedef struct mpmul_pyobj
{
1072 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1073 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1075 static void mpmul_pydealloc(PyObject
*me
)
1077 if (MPMUL_LIVEP(me
))
1078 mp_drop(mpmul_done(MPMUL_PY(me
)));
1082 static PyObject
*mmmeth_factor(PyObject
*me
, PyObject
*arg
)
1087 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1088 if (PyTuple_GET_SIZE(arg
) != 1)
1089 i
= PyObject_GetIter(arg
);
1091 if ((q
= PyTuple_GET_ITEM(arg
, 0)) == 0) goto end
;
1092 if ((i
= PyObject_GetIter(q
)) == 0) {
1093 PyErr_Clear(); /* that's ok */
1094 i
= PyObject_GetIter(arg
);
1098 while ((q
= PyIter_Next(i
)) != 0) {
1099 x
= getmp(q
); Py_DECREF(q
); if (!x
) {
1103 mpmul_add(MPMUL_PY(me
), x
);
1112 static PyObject
*mmmeth_done(PyObject
*me
)
1116 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1117 x
= mpmul_done(MPMUL_PY(me
));
1118 MPMUL_LIVEP(me
) = 0;
1119 return (mp_pywrap(x
));
1124 static PyObject
*mpmul_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1128 if (kw
) TYERR("keyword arguments not allowed here");
1129 mm
= (mpmul_pyobj
*)ty
->tp_alloc(ty
, 0);
1130 mpmul_init(&mm
->mm
);
1132 if (mmmeth_factor((PyObject
*)mm
, arg
) == 0) {
1136 return ((PyObject
*)mm
);
1141 static PyObject
*mmget_livep(PyObject
*me
, void *hunoz
)
1142 { return (getbool(MPMUL_LIVEP(me
))); }
1144 static const PyGetSetDef mpmul_pygetset
[] = {
1145 #define GETSETNAME(op, name) mm##op##_##name
1146 GET (livep
, "MM.livep -> flag: object still valid?")
1151 static const PyMethodDef mpmul_pymethods
[] = {
1152 #define METHNAME(name) mmmeth_##name
1153 METH (factor
, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1154 NAMETH(done
, "MM.done() -> PRODUCT")
1159 static const PyTypeObject mpmul_pytype_skel
= {
1160 PyVarObject_HEAD_INIT(0, 0) /* Header */
1161 "MPMul", /* @tp_name@ */
1162 sizeof(mpmul_pyobj
), /* @tp_basicsize@ */
1163 0, /* @tp_itemsize@ */
1165 mpmul_pydealloc
, /* @tp_dealloc@ */
1167 0, /* @tp_getattr@ */
1168 0, /* @tp_setattr@ */
1169 0, /* @tp_compare@ */
1171 0, /* @tp_as_number@ */
1172 0, /* @tp_as_sequence@ */
1173 0, /* @tp_as_mapping@ */
1177 0, /* @tp_getattro@ */
1178 0, /* @tp_setattro@ */
1179 0, /* @tp_as_buffer@ */
1180 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1181 Py_TPFLAGS_BASETYPE
,
1184 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1186 0, /* @tp_traverse@ */
1188 0, /* @tp_richcompare@ */
1189 0, /* @tp_weaklistoffset@ */
1191 0, /* @tp_iternext@ */
1192 PYMETHODS(mpmul
), /* @tp_methods@ */
1193 0, /* @tp_members@ */
1194 PYGETSET(mpmul
), /* @tp_getset@ */
1197 0, /* @tp_descr_get@ */
1198 0, /* @tp_descr_set@ */
1199 0, /* @tp_dictoffset@ */
1201 PyType_GenericAlloc
, /* @tp_alloc@ */
1202 mpmul_pynew
, /* @tp_new@ */
1207 /*----- Montgomery reduction ----------------------------------------------*/
1209 static PyTypeObject
*mpmont_pytype
;
1211 typedef struct mpmont_pyobj
{
1216 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1218 static PyObject
*mmmeth_int(PyObject
*me
, PyObject
*arg
)
1222 mpmont
*mm
= MPMONT_PY(me
);
1224 if (!PyArg_ParseTuple(arg
, "O&:in", convmp
, &yy
))
1226 mp_div(0, &yy
, yy
, mm
->m
);
1227 z
= mp_pywrap(mpmont_mul(mm
, MP_NEW
, yy
, mm
->r2
));
1229 if (yy
) MP_DROP(yy
);
1233 static PyObject
*mmmeth_mul(PyObject
*me
, PyObject
*arg
)
1236 mp
*yy
= 0, *zz
= 0;
1238 if (!PyArg_ParseTuple(arg
, "O&O&:mul", convmp
, &yy
, convmp
, &zz
))
1240 rc
= mp_pywrap(mpmont_mul(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1242 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1246 static PyObject
*mmmeth_exp(PyObject
*me
, PyObject
*arg
)
1249 mp
*yy
= 0, *zz
= 0;
1251 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1254 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1255 zz
= mp_neg(zz
, zz
);
1257 rc
= mp_pywrap(mpmont_exp(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1259 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1263 static PyObject
*mmmeth_expr(PyObject
*me
, PyObject
*arg
)
1266 mp
*yy
= 0, *zz
= 0;
1268 if (!PyArg_ParseTuple(arg
, "O&O&:expr", convmp
, &yy
, convmp
, &zz
))
1271 yy
= mpmont_reduce(MPMONT_PY(me
), yy
, yy
);
1272 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1273 yy
= mpmont_mul(MPMONT_PY(me
), yy
, yy
, MPMONT_PY(me
)->r2
);
1274 zz
= mp_neg(zz
, zz
);
1276 rc
= mp_pywrap(mpmont_expr(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1278 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1282 static PyObject
*mm_mexpr_id(PyObject
*me
)
1283 { return mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
)); }
1285 static int mm_mexpr_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1287 mp
*xx
= 0, *yy
= 0;
1288 mp_expfactor
*f
= p
;
1289 mpmont
*mm
= MPMONT_PY(me
);
1291 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1294 xx
= mpmont_reduce(mm
, xx
, xx
);
1295 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1297 xx
= mpmont_mul(mm
, xx
, xx
, mm
->r2
);
1298 yy
= mp_neg(yy
, yy
);
1305 mp_drop(xx
); mp_drop(yy
);
1309 static PyObject
*mm_mexpr(PyObject
*me
, void *v
, int n
)
1310 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1312 static void mp_mexp_drop(void *p
)
1314 mp_expfactor
*f
= p
;
1319 static PyObject
*mmmeth_mexpr(PyObject
*me
, PyObject
*arg
)
1321 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1322 mm_mexpr_id
, mm_mexpr_fill
, mm_mexpr
, mp_mexp_drop
);
1325 static PyObject
*mp_mexp_id(PyObject
*me
)
1326 { return mp_pywrap(MP_ONE
); }
1328 static int mp_mexp_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1330 mp
*xx
= 0, *yy
= 0;
1331 mp_expfactor
*f
= p
;
1333 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1336 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1338 yy
= mp_neg(yy
, yy
);
1345 mp_drop(xx
); mp_drop(yy
);
1349 static PyObject
*mm_mexp(PyObject
*me
, void *v
, int n
)
1350 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1352 static PyObject
*mmmeth_mexp(PyObject
*me
, PyObject
*arg
)
1354 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1355 mp_mexp_id
, mp_mexp_fill
, mm_mexp
, mp_mexp_drop
);
1358 #define mmmeth_ext mmmeth_reduce
1359 static PyObject
*mmmeth_reduce(PyObject
*me
, PyObject
*arg
)
1364 if (!PyArg_ParseTuple(arg
, "O&", convmp
, &yy
)) goto end
;
1365 z
= mp_pywrap(mpmont_reduce(MPMONT_PY(me
), MP_NEW
, yy
));
1370 static void mpmont_pydealloc(PyObject
*me
)
1372 mpmont_destroy(MPMONT_PY(me
));
1376 static PyObject
*mpmont_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1378 mpmont_pyobj
*mm
= 0;
1379 static const char *const kwlist
[] = { "m", 0 };
1382 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1384 if (!MP_POSP(xx
) || !MP_ODDP(xx
)) VALERR("m must be positive and odd");
1385 mm
= (mpmont_pyobj
*)ty
->tp_alloc(ty
, 0);
1386 mpmont_create(&mm
->mm
, xx
);
1388 if (xx
) MP_DROP(xx
);
1389 return ((PyObject
*)mm
);
1392 static PyObject
*mmget_m(PyObject
*me
, void *hunoz
)
1393 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->m
))); }
1395 static PyObject
*mmget_r(PyObject
*me
, void *hunoz
)
1396 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
))); }
1398 static PyObject
*mmget_r2(PyObject
*me
, void *hunoz
)
1399 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r2
))); }
1401 static const PyGetSetDef mpmont_pygetset
[] = {
1402 #define GETSETNAME(op, name) mm##op##_##name
1403 GET (m
, "M.m -> modulus for reduction")
1404 GET (r
, "M.r -> multiplicative identity")
1405 GET (r2
, "M.r2 -> M.r^2, Montgomerization factor")
1410 static const PyMethodDef mpmont_pymethods
[] = {
1411 #define METHNAME(name) mmmeth_##name
1412 METH (int, "M.int(X) -> XR")
1413 METH (mul
, "M.mul(XR, YR) -> ZR where Z = X Y")
1414 METH (expr
, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1415 METH (mexpr
, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1416 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1417 "\t(the list may be flattened if this more convenient.)")
1418 METH (reduce
, "M.reduce(XR) -> X")
1419 METH (ext
, "M.ext(XR) -> X")
1420 METH (exp
, "M.exp(X, N) -> X^N mod M.m")
1421 METH (mexp
, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1422 "X0^N0 X1^N1 ... mod M.m\n"
1423 "\t(the list may be flattened if this more convenient.)")
1428 static const PyTypeObject mpmont_pytype_skel
= {
1429 PyVarObject_HEAD_INIT(0, 0) /* Header */
1430 "MPMont", /* @tp_name@ */
1431 sizeof(mpmont_pyobj
), /* @tp_basicsize@ */
1432 0, /* @tp_itemsize@ */
1434 mpmont_pydealloc
, /* @tp_dealloc@ */
1436 0, /* @tp_getattr@ */
1437 0, /* @tp_setattr@ */
1438 0, /* @tp_compare@ */
1440 0, /* @tp_as_number@ */
1441 0, /* @tp_as_sequence@ */
1442 0, /* @tp_as_mapping@ */
1446 0, /* @tp_getattro@ */
1447 0, /* @tp_setattro@ */
1448 0, /* @tp_as_buffer@ */
1449 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1450 Py_TPFLAGS_BASETYPE
,
1453 "MPMont(N): a Montgomery reduction context.",
1455 0, /* @tp_traverse@ */
1457 0, /* @tp_richcompare@ */
1458 0, /* @tp_weaklistoffset@ */
1460 0, /* @tp_iternext@ */
1461 PYMETHODS(mpmont
), /* @tp_methods@ */
1462 0, /* @tp_members@ */
1463 PYGETSET(mpmont
), /* @tp_getset@ */
1466 0, /* @tp_descr_get@ */
1467 0, /* @tp_descr_set@ */
1468 0, /* @tp_dictoffset@ */
1470 PyType_GenericAlloc
, /* @tp_alloc@ */
1471 mpmont_pynew
, /* @tp_new@ */
1476 /*----- Barrett reduction -------------------------------------------------*/
1478 static PyTypeObject
*mpbarrett_pytype
;
1480 typedef struct mpbarrett_pyobj
{
1485 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1487 static PyObject
*mbmeth_exp(PyObject
*me
, PyObject
*arg
)
1490 mp
*yy
= 0, *zz
= 0;
1492 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1495 if ((yy
= mp_modinv_checked(yy
, yy
, MPBARRETT_PY(me
)->m
)) == 0) goto end
;
1496 zz
= mp_neg(zz
, zz
);
1498 rc
= mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me
), MP_NEW
, yy
, zz
));
1500 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1504 static PyObject
*mb_mexp(PyObject
*me
, void *v
, int n
)
1505 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me
), MP_NEW
, v
, n
)); }
1507 static PyObject
*mbmeth_mexp(PyObject
*me
, PyObject
*arg
)
1509 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1510 mp_mexp_id
, mp_mexp_fill
, mb_mexp
, mp_mexp_drop
);
1513 static PyObject
*mbmeth_reduce(PyObject
*me
, PyObject
*arg
)
1518 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
))
1520 z
= mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me
), MP_NEW
, yy
));
1525 static void mpbarrett_pydealloc(PyObject
*me
)
1527 mpbarrett_destroy(MPBARRETT_PY(me
));
1531 static PyObject
*mpbarrett_pynew(PyTypeObject
*ty
,
1532 PyObject
*arg
, PyObject
*kw
)
1534 mpbarrett_pyobj
*mb
= 0;
1535 static const char *const kwlist
[] = { "m", 0 };
1538 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1540 if (!MP_POSP(xx
)) VALERR("m must be positive");
1541 mb
= (mpbarrett_pyobj
*)ty
->tp_alloc(ty
, 0);
1542 mpbarrett_create(&mb
->mb
, xx
);
1544 if (xx
) MP_DROP(xx
);
1545 return ((PyObject
*)mb
);
1548 static PyObject
*mbget_m(PyObject
*me
, void *hunoz
)
1549 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me
)->m
))); }
1551 static const PyGetSetDef mpbarrett_pygetset
[] = {
1552 #define GETSETNAME(op, name) mb##op##_##name
1553 GET (m
, "B.m -> modulus for reduction")
1558 static const PyMethodDef mpbarrett_pymethods
[] = {
1559 #define METHNAME(name) mbmeth_##name
1560 METH (reduce
, "B.reduce(X) -> X mod B.m")
1561 METH (exp
, "B.exp(X, N) -> X^N mod B.m")
1562 METH (mexp
, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1563 "X0^N0 X1^N1 ... mod B.m\n"
1564 "\t(the list may be flattened if this more convenient.)")
1569 static const PyTypeObject mpbarrett_pytype_skel
= {
1570 PyVarObject_HEAD_INIT(0, 0) /* Header */
1571 "MPBarrett", /* @tp_name@ */
1572 sizeof(mpbarrett_pyobj
), /* @tp_basicsize@ */
1573 0, /* @tp_itemsize@ */
1575 mpbarrett_pydealloc
, /* @tp_dealloc@ */
1577 0, /* @tp_getattr@ */
1578 0, /* @tp_setattr@ */
1579 0, /* @tp_compare@ */
1581 0, /* @tp_as_number@ */
1582 0, /* @tp_as_sequence@ */
1583 0, /* @tp_as_mapping@ */
1587 0, /* @tp_getattro@ */
1588 0, /* @tp_setattro@ */
1589 0, /* @tp_as_buffer@ */
1590 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1591 Py_TPFLAGS_BASETYPE
,
1594 "MPBarrett(N): a Barrett reduction context.",
1596 0, /* @tp_traverse@ */
1598 0, /* @tp_richcompare@ */
1599 0, /* @tp_weaklistoffset@ */
1601 0, /* @tp_iternext@ */
1602 PYMETHODS(mpbarrett
), /* @tp_methods@ */
1603 0, /* @tp_members@ */
1604 PYGETSET(mpbarrett
), /* @tp_getset@ */
1607 0, /* @tp_descr_get@ */
1608 0, /* @tp_descr_set@ */
1609 0, /* @tp_dictoffset@ */
1611 PyType_GenericAlloc
, /* @tp_alloc@ */
1612 mpbarrett_pynew
, /* @tp_new@ */
1617 /*----- Nice prime reduction ----------------------------------------------*/
1619 static PyTypeObject
*mpreduce_pytype
;
1621 typedef struct mpreduce_pyobj
{
1626 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1628 static PyObject
*mrmeth_exp(PyObject
*me
, PyObject
*arg
)
1631 mp
*yy
= 0, *zz
= 0;
1633 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1636 if ((yy
= mp_modinv_checked(yy
, yy
, MPREDUCE_PY(me
)->p
)) == 0) goto end
;
1637 zz
= mp_neg(zz
, zz
);
1639 rc
= mp_pywrap(mpreduce_exp(MPREDUCE_PY(me
), MP_NEW
, yy
, zz
));
1641 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1645 static PyObject
*mrmeth_reduce(PyObject
*me
, PyObject
*arg
)
1650 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
)) goto end
;
1651 z
= mp_pywrap(mpreduce_do(MPREDUCE_PY(me
), MP_NEW
, yy
));
1656 static void mpreduce_pydealloc(PyObject
*me
)
1658 mpreduce_destroy(MPREDUCE_PY(me
));
1662 static PyObject
*mpreduce_pynew(PyTypeObject
*ty
,
1663 PyObject
*arg
, PyObject
*kw
)
1665 mpreduce_pyobj
*mr
= 0;
1667 static const char *const kwlist
[] = { "m", 0 };
1670 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1672 if (!MP_POSP(xx
)) VALERR("m must be positive");
1673 if (mpreduce_create(&r
, xx
)) VALERR("bad modulus (must be 2^k - ...)");
1674 mr
= (mpreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
1677 if (xx
) MP_DROP(xx
);
1678 return ((PyObject
*)mr
);
1681 static PyObject
*mrget_m(PyObject
*me
, void *hunoz
)
1682 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me
)->p
))); }
1684 static const PyGetSetDef mpreduce_pygetset
[] = {
1685 #define GETSETNAME(op, name) mr##op##_##name
1686 GET (m
, "R.m -> modulus for reduction")
1691 static const const PyMethodDef mpreduce_pymethods
[] = {
1692 #define METHNAME(name) mrmeth_##name
1693 METH (reduce
, "R.reduce(X) -> X mod B.m")
1694 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
1699 static const PyTypeObject mpreduce_pytype_skel
= {
1700 PyVarObject_HEAD_INIT(0, 0) /* Header */
1701 "MPReduce", /* @tp_name@ */
1702 sizeof(mpreduce_pyobj
), /* @tp_basicsize@ */
1703 0, /* @tp_itemsize@ */
1705 mpreduce_pydealloc
, /* @tp_dealloc@ */
1707 0, /* @tp_getattr@ */
1708 0, /* @tp_setattr@ */
1709 0, /* @tp_compare@ */
1711 0, /* @tp_as_number@ */
1712 0, /* @tp_as_sequence@ */
1713 0, /* @tp_as_mapping@ */
1717 0, /* @tp_getattro@ */
1718 0, /* @tp_setattro@ */
1719 0, /* @tp_as_buffer@ */
1720 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1721 Py_TPFLAGS_BASETYPE
,
1724 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1726 0, /* @tp_traverse@ */
1728 0, /* @tp_richcompare@ */
1729 0, /* @tp_weaklistoffset@ */
1731 0, /* @tp_iternext@ */
1732 PYMETHODS(mpreduce
), /* @tp_methods@ */
1733 0, /* @tp_members@ */
1734 PYGETSET(mpreduce
), /* @tp_getset@ */
1737 0, /* @tp_descr_get@ */
1738 0, /* @tp_descr_set@ */
1739 0, /* @tp_dictoffset@ */
1741 PyType_GenericAlloc
, /* @tp_alloc@ */
1742 mpreduce_pynew
, /* @tp_new@ */
1747 /*----- Chinese Remainder Theorem solution --------------------------------*/
1749 static PyTypeObject
*mpcrt_pytype
;
1751 typedef struct mpcrt_pyobj
{
1756 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1758 static PyObject
*mcmeth_solve(PyObject
*me
, PyObject
*arg
)
1760 mpcrt
*c
= MPCRT_PY(me
);
1761 PyObject
*q
= 0, *x
, *z
= 0;
1764 Py_ssize_t i
= 0, n
= c
->k
;
1767 if (PyTuple_GET_SIZE(arg
) == n
)
1769 else if (!PyArg_ParseTuple(arg
, "O:solve", &q
))
1772 if (!PySequence_Check(q
)) TYERR("want a sequence of residues");
1773 i
= PySequence_Size(q
); if (i
< 0) goto end
;
1774 if (i
!= n
) VALERR("residue count mismatch");
1775 v
= xmalloc(n
* sizeof(*v
));
1776 for (i
= 0; i
< n
; i
++) {
1777 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1778 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1781 z
= mp_pywrap(mpcrt_solve(c
, MP_NEW
, v
));
1785 for (i
= 0; i
< n
; i
++)
1794 static void mpcrt_pydealloc(PyObject
*me
)
1796 mpcrt
*c
= MPCRT_PY(me
);
1801 static PyObject
*mpcrt_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1804 Py_ssize_t n
, i
= 0, j
;
1805 static const char *const kwlist
[] = { "mv", 0 };
1806 PyObject
*q
= 0, *x
;
1807 mp
*xx
= MP_NEW
, *y
= MP_NEW
, *g
= MP_NEW
;
1811 if (PyTuple_GET_SIZE(arg
) > 1)
1813 else if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O:new", KWLIST
, &q
))
1816 if (!PySequence_Check(q
)) TYERR("want a sequence of moduli");
1817 n
= PySequence_Size(q
); if (n
< 0) goto end
;
1818 if (!n
) VALERR("want at least one modulus");
1819 v
= xmalloc(n
* sizeof(*v
));
1820 for (i
= 0; i
< n
; i
++) {
1821 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1822 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1823 if (MP_CMP(xx
, <=, MP_ZERO
)) VALERR("moduli must be positive");
1824 v
[i
].m
= xx
; v
[i
].n
= 0; v
[i
].ni
= 0; v
[i
].nni
= 0; xx
= MP_NEW
;
1827 for (j
= 0; j
< i
; j
++) mpmul_add(&mm
, v
[j
].m
);
1828 xx
= mpmul_done(&mm
);
1829 for (j
= 0; j
< i
; j
++) {
1830 mp_div(&y
, 0, xx
, v
[j
].m
);
1831 mp_gcd(&g
, 0, 0, y
, v
[j
].m
);
1832 if (!MP_EQ(g
, MP_ONE
)) VALERR("moduli must be pairwise coprime");
1835 c
= (mpcrt_pyobj
*)ty
->tp_alloc(ty
, 0);
1836 mpcrt_create(&c
->c
, v
, n
, 0);
1838 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1839 return ((PyObject
*)c
);
1844 for (i
= 0; i
< n
; i
++)
1849 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1853 static PyObject
*mcget_product(PyObject
*me
, void *hunoz
)
1854 { return (mp_pywrap(MP_COPY(MPCRT_PY(me
)->mb
.m
))); }
1856 static PyObject
*mcget_moduli(PyObject
*me
, void *hunoz
)
1860 mpcrt
*c
= MPCRT_PY(me
);
1862 if ((q
= PyList_New(c
->k
)) == 0) return (0);
1863 for (i
= 0; i
< c
->k
; i
++)
1864 PyList_SET_ITEM(q
, i
, mp_pywrap(c
->v
[i
].m
));
1868 static const PyGetSetDef mpcrt_pygetset
[] = {
1869 #define GETSETNAME(op, name) mc##op##_##name
1870 GET (product
, "C.product -> product of moduli")
1871 GET (moduli
, "C.moduli -> list of individual moduli")
1876 static const PyMethodDef mpcrt_pymethods
[] = {
1877 #define METHNAME(name) mcmeth_##name
1878 METH (solve
, "C.solve([R0, R1]) -> X mod C.product")
1883 static const PyTypeObject mpcrt_pytype_skel
= {
1884 PyVarObject_HEAD_INIT(0, 0) /* Header */
1885 "MPCRT", /* @tp_name@ */
1886 sizeof(mpcrt_pyobj
), /* @tp_basicsize@ */
1887 0, /* @tp_itemsize@ */
1889 mpcrt_pydealloc
, /* @tp_dealloc@ */
1891 0, /* @tp_getattr@ */
1892 0, /* @tp_setattr@ */
1893 0, /* @tp_compare@ */
1895 0, /* @tp_as_number@ */
1896 0, /* @tp_as_sequence@ */
1897 0, /* @tp_as_mapping@ */
1901 0, /* @tp_getattro@ */
1902 0, /* @tp_setattro@ */
1903 0, /* @tp_as_buffer@ */
1904 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1905 Py_TPFLAGS_BASETYPE
,
1908 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1910 0, /* @tp_traverse@ */
1912 0, /* @tp_richcompare@ */
1913 0, /* @tp_weaklistoffset@ */
1915 0, /* @tp_iternext@ */
1916 PYMETHODS(mpcrt
), /* @tp_methods@ */
1917 0, /* @tp_members@ */
1918 PYGETSET(mpcrt
), /* @tp_getset@ */
1921 0, /* @tp_descr_get@ */
1922 0, /* @tp_descr_set@ */
1923 0, /* @tp_dictoffset@ */
1925 PyType_GenericAlloc
, /* @tp_alloc@ */
1926 mpcrt_pynew
, /* @tp_new@ */
1931 /*----- Binary polynomials ------------------------------------------------*/
1933 static PyObject
*gf_pyrepr(PyObject
*o
)
1934 { return mp_topystring(MP_X(o
), 16, "GF(", "0x", ")"); }
1936 static PyObject
*gf_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
1942 if (gfbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
1944 case Py_EQ
: b
= MP_EQ(xx
, yy
); break;
1945 case Py_NE
: b
= !MP_EQ(xx
, yy
); break;
1950 case Py_LT
: b
= xl
< yl
; break;
1951 case Py_LE
: b
= xl
<= yl
; break;
1952 case Py_GT
: b
= xl
> yl
; break;
1953 case Py_GE
: b
= xl
>= yl
; break;
1958 MP_DROP(xx
); MP_DROP(yy
);
1959 return (getbool(b
));
1962 static PyObject
*gf_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1968 static const char *const kwlist
[] = { "x", "radix", 0 };
1970 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:gf", KWLIST
, &x
, &radix
))
1972 if (GF_PYCHECK(x
)) RETURN_OBJ(x
);
1973 if (!good_radix_p(radix
, 1)) VALERR("radix out of range");
1974 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
1975 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
1976 Py_TYPE(x
)->tp_name
);
1981 VALERR("gf cannot be negative");
1983 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
1986 return ((PyObject
*)zz
);
1989 static PyObject
*gf_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
1991 mp
*xx
= 0, *yy
= 0, *zz
= 0;
1995 if ((xx
= implicitgf(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
1996 (z
&& z
!= Py_None
&& (zz
= implicitgf(z
)) == 0)) {
1997 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2000 if (!z
|| z
== Py_None
) {
2001 if (MP_NEGP(yy
)) VALERR("negative exponent");
2002 r
= gf_exp(MP_NEW
, xx
, yy
);
2005 if (MP_ZEROP(zz
)) ZDIVERR("zero modulus");
2007 if ((xx
= gf_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
2008 yy
= mp_neg(yy
, yy
);
2010 gfreduce_create(&gr
, zz
);
2011 r
= gfreduce_exp(&gr
, MP_NEW
, xx
, yy
);
2012 gfreduce_destroy(&gr
);
2016 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2020 static PyObject
*gfmeth_sqr(PyObject
*me
)
2021 { return (gf_pywrap(gf_sqr(MP_NEW
, MP_X(me
)))); }
2023 static PyObject
*gfmeth_gcd(PyObject
*me
, PyObject
*arg
)
2026 mp
*yy
= 0, *zz
= MP_NEW
;
2028 if (!PyArg_ParseTuple(arg
, "O&:gcd", convgf
, &yy
)) goto end
;
2029 gf_gcd(&zz
, 0, 0, MP_X(me
), yy
);
2032 if (yy
) MP_DROP(yy
);
2036 static PyObject
*gfmeth_gcdx(PyObject
*me
, PyObject
*arg
)
2039 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
2041 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convgf
, &yy
))
2043 gf_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
2044 z
= Py_BuildValue("(NNN)",
2045 gf_pywrap(zz
), gf_pywrap(uu
), gf_pywrap(vv
));
2047 if (yy
) MP_DROP(yy
);
2051 static PyObject
*gfmeth_modinv(PyObject
*me
, PyObject
*arg
)
2054 mp
*yy
= 0, *zz
= MP_NEW
;
2056 if (!PyArg_ParseTuple(arg
, "O&:modinv", convgf
, &yy
) ||
2057 (zz
= gf_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
2061 if (yy
) MP_DROP(yy
);
2065 static PyObject
*gfmeth_fromstring(PyObject
*me
,
2066 PyObject
*arg
, PyObject
*kw
)
2073 mptext_stringctx sc
;
2074 static const char *const kwlist
[] = { "x", "radix", 0 };
2076 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
2079 if (!good_radix_p(r
, 1)) VALERR("bad radix");
2080 sc
.buf
= p
; sc
.lim
= p
+ len
;
2081 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0 ||
2083 if (zz
) MP_DROP(zz
);
2084 VALERR("bad binary polynomial");
2086 z
= Py_BuildValue("(Ns#)", gf_pywrap(zz
),
2087 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
2092 static PyObject
*gfmeth_irreduciblep(PyObject
*me
)
2093 { return getbool(gf_irreduciblep(MP_X(me
))); }
2095 static PyObject
*gfget_degree(PyObject
*me
, void *hunoz
)
2096 { return (PyInt_FromLong(mp_bits(MP_X(me
)) - 1)); }
2098 static const PyGetSetDef gf_pygetset
[] = {
2099 #define GETSETNAME(op, name) gf##op##_##name
2100 GET (degree
, "X.degree -> polynomial degree of X")
2102 #define GETSETNAME(op, name) mp##op##_##name
2103 GET (nbits
, "X.nbits -> bit length of X")
2104 GET (noctets
, "X.noctets -> octet length of X")
2109 static const PyMethodDef gf_pymethods
[] = {
2110 #define METHNAME(func) gfmeth_##func
2111 METH (setbit
, "X.setbit(N) -> X with bit N set")
2112 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
2113 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
2114 NAMETH(sqr
, "X.sqr() -> X^2")
2115 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
2116 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2117 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2118 NAMETH(irreduciblep
, "X.irreduciblep() -> true/false")
2119 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2120 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2121 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2122 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2123 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
2124 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
2125 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
2127 #define METHNAME(func) mpmeth_##func
2128 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
2129 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
2130 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
2131 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
2132 "little-endian bytes, two's complement")
2133 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
2134 "big-endian bytes, two's complement")
2135 NAMETH(tobuf
, "X.tobuf() -> buffer format")
2140 static const PyNumberMethods gf_pynumber
= {
2141 gf_pyadd
, /* @nb_add@ */
2142 gf_pysub
, /* @nb_subtract@ */
2143 gf_pymul
, /* @nb_multiply@ */
2145 0, /* @nb_divide@ */
2147 gf_pymod
, /* @nb_remainder@ */
2148 gf_pydivmod
, /* @nb_divmod@ */
2149 gf_pyexp
, /* @nb_power@ */
2150 mp_pyid
, /* @nb_negative@ */
2151 mp_pyid
, /* @nb_positive@ */
2152 mp_pyid
, /* @nb_absolute@ */
2153 mp_pynonzerop
, /* @nb_nonzero@ */
2154 0 /* doesn't make any sense */, /* @nb_invert@ */
2155 gf_pylsl
, /* @nb_lshift@ */
2156 gf_pylsr
, /* @nb_rshift@ */
2157 gf_pyand
, /* @nb_and@ */
2158 gf_pyxor
, /* @nb_xor@ */
2159 gf_pyor
, /* @nb_or@ */
2161 gf_pycoerce
, /* @nb_coerce@ */
2163 mp_pyint
, /* @nb_int@ */
2164 PY23(mp_pylong
, 0), /* @nb_long@ */
2165 0 /* doesn't make any sense */, /* @nb_float@ */
2167 mp_pyoct
, /* @nb_oct@ */
2168 mp_pyhex
, /* @nb_hex@ */
2171 0, /* @nb_inplace_add@ */
2172 0, /* @nb_inplace_subtract@ */
2173 0, /* @nb_inplace_multiply@ */
2175 0, /* @nb_inplace_divide@ */
2177 0, /* @nb_inplace_remainder@ */
2178 0, /* @nb_inplace_power@ */
2179 0, /* @nb_inplace_lshift@ */
2180 0, /* @nb_inplace_rshift@ */
2181 0, /* @nb_inplace_and@ */
2182 0, /* @nb_inplace_xor@ */
2183 0, /* @nb_inplace_or@ */
2185 gf_pydiv
, /* @nb_floor_divide@ */
2186 0, /* @nb_true_divide@ */
2187 0, /* @nb_inplace_floor_divide@ */
2188 0, /* @nb_inplace_true_divide@ */
2190 mp_pyint
, /* @nb_index@ */
2193 static const PyTypeObject gf_pytype_skel
= {
2194 PyVarObject_HEAD_INIT(0, 0) /* Header */
2195 "GF", /* @tp_name@ */
2196 sizeof(mp_pyobj
), /* @tp_basicsize@ */
2197 0, /* @tp_itemsize@ */
2199 mp_pydealloc
, /* @tp_dealloc@ */
2201 0, /* @tp_getattr@ */
2202 0, /* @tp_setattr@ */
2203 0, /* @tp_compare@ */
2204 gf_pyrepr
, /* @tp_repr@ */
2205 PYNUMBER(gf
), /* @tp_as_number@ */
2206 0, /* @tp_as_sequence@ */
2207 0, /* @tp_as_mapping@ */
2208 mp_pyhash
, /* @tp_hash@ */
2210 mp_pyhex
, /* @tp_str@ */
2211 0, /* @tp_getattro@ */
2212 0, /* @tp_setattro@ */
2213 0, /* @tp_as_buffer@ */
2214 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2215 Py_TPFLAGS_CHECKTYPES
|
2216 Py_TPFLAGS_BASETYPE
,
2219 "Binary polynomials. Support almost all the standard arithmetic\n"
2222 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2223 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2224 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2226 "points, group elements, Python `int' and `long' objects, and anything\n"
2227 "with an integer conversion.\n",
2228 "points, group elements, Python `int' objects, and anything with an\n"
2229 "integer conversion.\n")
2231 "The name is hopelessly wrong from a technical point of view, but\n"
2232 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2236 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2238 0, /* @tp_traverse@ */
2240 gf_pyrichcompare
, /* @tp_richcompare@ */
2241 0, /* @tp_weaklistoffset@ */
2243 0, /* @tp_iternext@ */
2244 PYMETHODS(gf
), /* @tp_methods@ */
2245 0, /* @tp_members@ */
2246 PYGETSET(gf
), /* @tp_getset@ */
2249 0, /* @tp_descr_get@ */
2250 0, /* @tp_descr_set@ */
2251 0, /* @tp_dictoffset@ */
2253 PyType_GenericAlloc
, /* @tp_alloc@ */
2254 gf_pynew
, /* @tp_new@ */
2259 /*----- Sparse poly reduction ---------------------------------------------*/
2261 static PyTypeObject
*gfreduce_pytype
;
2263 typedef struct gfreduce_pyobj
{
2268 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2270 static PyObject
*grmeth_exp(PyObject
*me
, PyObject
*arg
)
2273 mp
*yy
= 0, *zz
= 0;
2275 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convgf
, &yy
, convgf
, &zz
))
2278 if ((yy
= gf_modinv_checked(yy
, yy
, GFREDUCE_PY(me
)->p
)) == 0) goto end
;
2279 zz
= mp_neg(zz
, zz
);
2281 rc
= gf_pywrap(gfreduce_exp(GFREDUCE_PY(me
), MP_NEW
, yy
, zz
));
2283 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
2287 static PyObject
*grmeth_trace(PyObject
*me
, PyObject
*arg
)
2292 if (!PyArg_ParseTuple(arg
, "O&:trace", convgf
, &xx
)) goto end
;
2293 rc
= PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me
), xx
));
2295 if (xx
) MP_DROP(xx
);
2299 static PyObject
*grmeth_halftrace(PyObject
*me
, PyObject
*arg
)
2304 if (!PyArg_ParseTuple(arg
, "O&:halftrace", convgf
, &xx
)) goto end
;
2305 rc
= gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me
), MP_NEW
, xx
));
2307 if (xx
) MP_DROP(xx
);
2311 static PyObject
*grmeth_sqrt(PyObject
*me
, PyObject
*arg
)
2316 if (!PyArg_ParseTuple(arg
, "O&:sqrt", convgf
, &xx
)) goto end
;
2317 if ((yy
= gfreduce_sqrt(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2318 VALERR("no modular square root");
2321 if (xx
) MP_DROP(xx
);
2325 static PyObject
*grmeth_quadsolve(PyObject
*me
, PyObject
*arg
)
2330 if (!PyArg_ParseTuple(arg
, "O&:quadsolve", convgf
, &xx
)) goto end
;
2331 if ((yy
= gfreduce_quadsolve(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2332 VALERR("no solution found");
2335 if (xx
) MP_DROP(xx
);
2339 static PyObject
*grmeth_reduce(PyObject
*me
, PyObject
*arg
)
2344 if (!PyArg_ParseTuple(arg
, "O&:reduce", convgf
, &yy
)) goto end
;
2345 z
= gf_pywrap(gfreduce_do(GFREDUCE_PY(me
), MP_NEW
, yy
));
2350 static void gfreduce_pydealloc(PyObject
*me
)
2352 gfreduce_destroy(GFREDUCE_PY(me
));
2356 static PyObject
*gfreduce_pynew(PyTypeObject
*ty
,
2357 PyObject
*arg
, PyObject
*kw
)
2359 gfreduce_pyobj
*mr
= 0;
2361 static const char *const kwlist
[] = { "m", 0 };
2364 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convgf
, &xx
))
2366 if (MP_ZEROP(xx
)) ZDIVERR("modulus is zero!");
2367 gfreduce_create(&r
, xx
);
2368 mr
= (gfreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
2371 if (xx
) MP_DROP(xx
);
2372 return ((PyObject
*)mr
);
2375 static PyObject
*grget_m(PyObject
*me
, void *hunoz
)
2376 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me
)->p
))); }
2378 static const PyGetSetDef gfreduce_pygetset
[] = {
2379 #define GETSETNAME(op, name) gr##op##_##name
2380 GET (m
, "R.m -> reduction polynomial")
2385 static const PyMethodDef gfreduce_pymethods
[] = {
2386 #define METHNAME(name) grmeth_##name
2387 METH (reduce
, "R.reduce(X) -> X mod B.m")
2388 METH (trace
, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2389 METH (halftrace
, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2390 METH (sqrt
, "R.sqrt(X) -> Y where Y^2 = X mod R")
2391 METH (quadsolve
, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2392 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
2397 static const PyTypeObject gfreduce_pytype_skel
= {
2398 PyVarObject_HEAD_INIT(0, 0) /* Header */
2399 "GFReduce", /* @tp_name@ */
2400 sizeof(gfreduce_pyobj
), /* @tp_basicsize@ */
2401 0, /* @tp_itemsize@ */
2403 gfreduce_pydealloc
, /* @tp_dealloc@ */
2405 0, /* @tp_getattr@ */
2406 0, /* @tp_setattr@ */
2407 0, /* @tp_compare@ */
2409 0, /* @tp_as_number@ */
2410 0, /* @tp_as_sequence@ */
2411 0, /* @tp_as_mapping@ */
2415 0, /* @tp_getattro@ */
2416 0, /* @tp_setattro@ */
2417 0, /* @tp_as_buffer@ */
2418 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2419 Py_TPFLAGS_BASETYPE
,
2422 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2424 0, /* @tp_traverse@ */
2426 0, /* @tp_richcompare@ */
2427 0, /* @tp_weaklistoffset@ */
2429 0, /* @tp_iternext@ */
2430 PYMETHODS(gfreduce
), /* @tp_methods@ */
2431 0, /* @tp_members@ */
2432 PYGETSET(gfreduce
), /* @tp_getset@ */
2435 0, /* @tp_descr_get@ */
2436 0, /* @tp_descr_set@ */
2437 0, /* @tp_dictoffset@ */
2439 PyType_GenericAlloc
, /* @tp_alloc@ */
2440 gfreduce_pynew
, /* @tp_new@ */
2445 /*----- Normal/poly transformation ----------------------------------------*/
2447 static PyTypeObject
*gfn_pytype
;
2449 typedef struct gfn_pyobj
{
2455 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2456 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2457 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2459 static PyObject
*gfn_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
2461 mp
*p
= 0, *beta
= 0;
2463 static const char *const kwlist
[] = { "p", "beta", 0 };
2465 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&O&:new", KWLIST
,
2466 convgf
, &p
, convgf
, &beta
))
2468 gg
= PyObject_New(gfn_pyobj
, ty
);
2470 if (gfn_create(p
, beta
, &gg
->ntop
, &gg
->pton
)) {
2473 VALERR("can't invert transformation matrix");
2479 return ((PyObject
*)gg
);
2482 static PyObject
*gfnget_p(PyObject
*me
, void *hunoz
)
2483 { return (gf_pywrap(MP_COPY(GFN_P(me
)))); }
2485 static PyObject
*gfnget_beta(PyObject
*me
, void *hunoz
)
2487 gfn
*n
= GFN_NTOP(me
);
2488 mp
*x
= n
->r
[n
->n
- 1];
2489 return (gf_pywrap(MP_COPY(x
)));
2492 #define XFORMOP(name, NAME) \
2493 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2498 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2499 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2502 if (!z) return (0); \
2503 return (gf_pywrap(z)); \
2509 static void gfn_pydealloc(PyObject
*me
)
2513 gfn_destroy(GFN_PTON(me
));
2514 gfn_destroy(GFN_NTOP(me
));
2519 static const PyGetSetDef gfn_pygetset
[] = {
2520 #define GETSETNAME(op, name) gfn##op##_##name
2521 GET (p
, "X.p -> polynomial basis, as polynomial")
2522 GET (beta
, "X.beta -> normal basis element, in poly form")
2527 static const PyMethodDef gfn_pymethods
[] = {
2528 #define METHNAME(name) gfnmeth_##name
2529 METH (pton
, "X.pton(A) -> normal-basis representation of A")
2530 METH (ntop
, "X.ntop(A) -> polynomial-basis representation of A")
2535 static const PyTypeObject gfn_pytype_skel
= {
2536 PyVarObject_HEAD_INIT(0, 0) /* Header */
2537 "GFN", /* @tp_name@ */
2538 sizeof(gfn_pyobj
), /* @tp_basicsize@ */
2539 0, /* @tp_itemsize@ */
2541 gfn_pydealloc
, /* @tp_dealloc@ */
2543 0, /* @tp_getattr@ */
2544 0, /* @tp_setattr@ */
2545 0, /* @tp_compare@ */
2547 0, /* @tp_as_number@ */
2548 0, /* @tp_as_sequence@ */
2549 0, /* @tp_as_mapping@ */
2553 0, /* @tp_getattro@ */
2554 0, /* @tp_setattro@ */
2555 0, /* @tp_as_buffer@ */
2556 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2557 Py_TPFLAGS_BASETYPE
,
2560 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2561 " between polynomial and normal basis representations.",
2563 0, /* @tp_traverse@ */
2565 0, /* @tp_richcompare@ */
2566 0, /* @tp_weaklistoffset@ */
2568 0, /* @tp_iternext@ */
2569 PYMETHODS(gfn
), /* @tp_methods@ */
2570 0, /* @tp_members@ */
2571 PYGETSET(gfn
), /* @tp_getset@ */
2574 0, /* @tp_descr_get@ */
2575 0, /* @tp_descr_set@ */
2576 0, /* @tp_dictoffset@ */
2578 PyType_GenericAlloc
, /* @tp_alloc@ */
2579 gfn_pynew
, /* @tp_new@ */
2584 /*----- Glue --------------------------------------------------------------*/
2586 static const struct nameval consts
[] = {
2591 void mp_pyinit(void)
2595 INITTYPE(mpmul
, root
);
2596 INITTYPE(mpmont
, root
);
2597 INITTYPE(mpbarrett
, root
);
2598 INITTYPE(mpreduce
, root
);
2599 INITTYPE(mpcrt
, root
);
2600 INITTYPE(gfreduce
, root
);
2601 INITTYPE(gfn
, root
);
2604 void mp_pyinsert(PyObject
*mod
)
2606 INSERT("MP", mp_pytype
);
2607 INSERT("MPMul", mpmul_pytype
);
2608 INSERT("MPMont", mpmont_pytype
);
2609 INSERT("MPBarrett", mpbarrett_pytype
);
2610 INSERT("MPReduce", mpreduce_pytype
);
2611 INSERT("MPCRT", mpcrt_pytype
);
2612 INSERT("GF", gf_pytype
);
2613 INSERT("GFReduce", gfreduce_pytype
);
2614 INSERT("GFN", gfn_pytype
);
2615 setconstants(mod
, consts
);
2618 /*----- That's all, folks -------------------------------------------------*/