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
)
294 if (!o
|| GF_PYCHECK(o
) || FE_PYCHECK(o
)) return (0);
295 else if (MP_PYCHECK(o
)) return (MP_COPY(MP_X(o
)));
296 else if (PFILT_PYCHECK(o
)) return (MP_COPY(PFILT_F(o
)->m
));
298 else if (PyInt_Check(o
)) return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
300 else if ((l
= PyNumber_Index(o
)) != 0) {
302 if (PyInt_Check(o
)) return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
304 if (PyLong_Check(o
)) return (mp_frompylong(o
));
306 PyErr_Clear(); return (0);
309 mp
*implicitgf(PyObject
*o
)
311 if (GF_PYCHECK(o
)) return (MP_COPY(MP_X(o
)));
315 static int mpbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
317 if ((*xx
= implicitmp(x
)) == 0)
319 if ((*yy
= implicitmp(y
)) == 0) {
326 static int gfbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
328 if ((*xx
= implicitgf(x
)) == 0)
330 if ((*yy
= implicitgf(y
)) == 0) {
337 #define FPBINOP(name, pyop) \
338 static PyObject *mp_py##name(PyObject *x, PyObject *y) { \
341 if (PyFloat_Check(x)) { \
342 l = mp_topylong(MP_X(y)); rc = PyNumber_##pyop(x, l); \
343 Py_DECREF(l); return (rc); \
344 } else if (PyFloat_Check(y)) { \
345 l = mp_topylong(MP_X(x)); rc = PyNumber_##pyop(l, y); \
346 Py_DECREF(l); return (rc); \
348 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
349 zz = mp_##name(MP_NEW, xx, yy); \
350 MP_DROP(xx); MP_DROP(yy); \
351 return (mp_pywrap(zz)); \
354 FPBINOP(sub
, Subtract
)
355 FPBINOP(mul
, Multiply
)
357 #define gf_and mp_and
359 #define gf_xor mp_xor
360 #define BINOP(pre, name) \
361 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
363 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
364 zz = pre##_##name(MP_NEW, xx, yy); \
365 MP_DROP(xx); MP_DROP(yy); \
366 return (pre##_pywrap(zz)); \
379 static mp
*mp_abs(mp
*d
, mp
*x
)
382 return (mp_neg(d
, x
));
388 #define UNOP(pre, name) \
389 static PyObject *pre##_py##name(PyObject *x) \
390 { return mp_pywrap(pre##_##name(MP_NEW, MP_X(x))); }
396 static PyObject
*mp_pyid(PyObject
*x
) { RETURN_OBJ(x
); }
398 #define gf_lsr mp_lsr
399 #define SHIFTOP(pre, PRE, name, rname) \
400 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
404 if (!PRE##_PYCHECK(x)) RETURN_NOTIMPL; \
405 if (GF_PYCHECK(y) || FE_PYCHECK(y)) RETURN_NOTIMPL; \
406 yix = PyNumber_Index(y); if (!yix) { PyErr_Clear(); RETURN_NOTIMPL; } \
407 n = PyInt_AsLong(yix); Py_DECREF(yix); \
408 if (n == -1 && PyErr_Occurred()) { PyErr_Clear(); RETURN_NOTIMPL; } \
409 if (n < 0) z = pre##_pywrap(mp_##rname(MP_NEW, MP_X(x), -n)); \
410 else z = pre##_pywrap(mp_##name(MP_NEW, MP_X(x), n)); \
413 SHIFTOP(mp
, MP
, lsl2c
, lsr2c
)
414 SHIFTOP(mp
, MP
, lsr2c
, lsl2c
)
415 SHIFTOP(gf
, GF
, lsl
, lsr
)
416 SHIFTOP(gf
, GF
, lsr
, lsl
)
419 #define DIVOP(pre, name, qq, rr, gather) \
420 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
423 INIT_##qq(q) INIT_##rr(r) \
424 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
426 ZDIVERR("division by zero"); \
427 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
430 MP_DROP(xx); MP_DROP(yy); \
433 #define INIT_YES(p) mp *p = MP_NEW;
435 #define ARG_YES(p) &p
437 DIVOP(mp
, divmod
, YES
, YES
,
438 Py_BuildValue("(NN)", mp_pywrap(q
), mp_pywrap(r
)))
439 DIVOP(mp
, div
, YES
, NO
, mp_pywrap(q
))
440 DIVOP(mp
, mod
, NO
, YES
, mp_pywrap(r
))
441 DIVOP(gf
, divmod
, YES
, YES
,
442 Py_BuildValue("(NN)", gf_pywrap(q
), gf_pywrap(r
)))
443 DIVOP(gf
, div
, YES
, NO
, gf_pywrap(q
))
444 DIVOP(gf
, mod
, NO
, YES
, gf_pywrap(r
))
451 static mp
*mp_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
454 mp_gcd(&g
, 0, &d
, p
, x
);
455 if (!MP_EQ(g
, MP_ONE
)) {
456 MP_DROP(g
); MP_DROP(d
);
457 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
460 MP_DROP(g
); return (d
);
463 static PyObject
*mp_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
465 mp
*xx
= 0, *yy
= 0, *zz
= 0;
469 if ((xx
= implicitmp(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
470 (z
&& z
!= Py_None
&& (zz
= implicitmp(z
)) == 0)) {
471 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
474 if (!z
|| z
== Py_None
) {
475 if (MP_NEGP(yy
)) VALERR("negative exponent");
476 r
= mp_exp(MP_NEW
, xx
, yy
);
478 if (!MP_POSP(zz
)) VALERR("modulus must be positive");
480 if ((xx
= mp_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
485 mpmont_create(&mm
, zz
);
486 r
= mpmont_exp(&mm
, MP_NEW
, xx
, yy
);
490 mpbarrett_create(&mb
, zz
);
491 r
= mpbarrett_exp(&mb
, MP_NEW
, xx
, yy
);
492 mpbarrett_destroy(&mb
);
497 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
501 static mp
*gf_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
504 gf_gcd(&g
, 0, &d
, p
, x
);
505 if (!MP_EQ(g
, MP_ONE
)) {
506 MP_DROP(g
); MP_DROP(d
);
507 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
510 MP_DROP(g
); return (d
);
513 #define BASEOP(name, radix, pre) \
514 static PyObject *mp_py##name(PyObject *x) \
515 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
519 BASEOP(hex
, 16, "0x");
522 static int mp_pynonzerop(PyObject
*x
) { return !MP_ZEROP(MP_X(x
)); }
524 static PyObject
*mp_pyint(PyObject
*x
)
527 if (!mp_tolong_checked(MP_X(x
), &l
, 0)) return (PyInt_FromLong(l
));
528 else return mp_topylong(MP_X(x
));
531 static PyObject
*mp_pylong(PyObject
*x
)
532 { return (mp_topylong(MP_X(x
))); }
534 static PyObject
*mp_pyfloat(PyObject
*x
)
536 PyObject
*l
= mp_topylong(MP_X(x
));
537 double f
= PyLong_AsDouble(l
);
539 return (PyFloat_FromDouble(f
));
543 #define COERCE(pre, PRE) \
544 static int pre##_pycoerce(PyObject **x, PyObject **y) \
548 if (PRE##_PYCHECK(*y)) { \
549 Py_INCREF(*x); Py_INCREF(*y); \
552 if ((z = implicit##pre(*y)) != 0) { \
554 *y = pre##_pywrap(z); \
564 static PyObject
*mp_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
568 if (PyFloat_Check(y
)) {
569 l
= mp_topylong(MP_X(x
)); rc
= PyObject_RichCompare(l
, y
, op
);
570 Py_DECREF(l
); return (rc
);
572 if (mpbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
573 rc
= enrich_compare(op
, mp_cmp(xx
, yy
));
574 MP_DROP(xx
); MP_DROP(yy
);
579 static int mp_pycompare(PyObject
*x
, PyObject
*y
)
580 { return mp_cmp(MP_X(x
), MP_X(y
)); }
583 static PyObject
*mp_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
589 static const char *const kwlist
[] = { "x", "radix", 0 };
591 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:new", KWLIST
, &x
, &radix
))
593 if (MP_PYCHECK(x
)) RETURN_OBJ(x
);
594 if (!good_radix_p(radix
, 1)) VALERR("bad radix");
595 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
596 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
597 Py_TYPE(x
)->tp_name
);
600 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
603 return ((PyObject
*)zz
);
606 #define IMPLICIT(pre) \
607 static PyObject *pre##meth__implicit(PyObject *me, PyObject *arg) \
609 PyObject *x, *rc = 0; \
611 if (!PyArg_ParseTuple(arg, "O:_implicit", &x)) goto end; \
612 y = implicit##pre(x); \
613 if (!y) TYERR("can't convert implicitly to " #pre); \
614 rc = pre##_pywrap(y); \
622 Py_hash_t
mphash(mp
*x
)
624 PyObject
*l
= mp_topylong(x
);
625 Py_hash_t h
= PyObject_Hash(l
);
626 Py_DECREF(l
); return (h
);
629 static Py_hash_t
mp_pyhash(PyObject
*me
) { return (mphash(MP_X(me
))); }
631 static PyObject
*mpmeth_jacobi(PyObject
*me
, PyObject
*arg
)
636 if (!PyArg_ParseTuple(arg
, "O&:jacobi", convmp
, &y
)) goto end
;
637 z
= PyInt_FromLong(mp_jacobi(y
, MP_X(me
)));
643 #define BITOP(pre, name, c) \
644 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
647 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
648 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
650 BITOP(mp
, setbit
, 2c
);
651 BITOP(mp
, clearbit
, 2c
);
653 BITOP(gf
, clearbit
, );
656 static PyObject
*mpmeth_testbit(PyObject
*me
, PyObject
*arg
)
659 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
660 return (getbool(mp_testbit2c(MP_X(me
), i
)));
663 static PyObject
*gfmeth_testbit(PyObject
*me
, PyObject
*arg
)
666 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
667 return (getbool(mp_testbit(MP_X(me
), i
)));
670 static PyObject
*mpmeth_odd(PyObject
*me
)
675 t
= mp_odd(MP_NEW
, MP_X(me
), &s
);
676 return (Py_BuildValue("(lN)", (long)s
, mp_pywrap(t
)));
679 static PyObject
*mpmeth_sqr(PyObject
*me
)
680 { return (mp_pywrap(mp_sqr(MP_NEW
, MP_X(me
)))); }
682 static PyObject
*mpmeth_sqrt(PyObject
*me
)
684 if (MP_NEGP(MP_X(me
))) VALERR("negative root");
685 return (mp_pywrap(mp_sqrt(MP_NEW
, MP_X(me
))));
690 static PyObject
*mpmeth_gcd(PyObject
*me
, PyObject
*arg
)
692 mp
*y
= 0, *zz
= MP_NEW
;
695 if (!PyArg_ParseTuple(arg
, "O&:gcd", convmp
, &y
)) goto end
;
696 mp_gcd(&zz
, 0, 0, MP_X(me
), y
);
703 static PyObject
*mpmeth_gcdx(PyObject
*me
, PyObject
*arg
)
706 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
708 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convmp
, &yy
)) goto end
;
709 mp_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
710 z
= Py_BuildValue("(NNN)",
711 mp_pywrap(zz
), mp_pywrap(uu
), mp_pywrap(vv
));
717 static PyObject
*mpmeth_modinv(PyObject
*me
, PyObject
*arg
)
720 mp
*yy
= 0, *zz
= MP_NEW
;
722 if (!PyArg_ParseTuple(arg
, "O&:modinv", convmp
, &yy
) ||
723 (zz
= mp_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
731 static PyObject
*mpmeth_tostring(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
734 static const char *const kwlist
[] = { "radix", 0 };
735 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|i:tostring", KWLIST
, &radix
))
737 if (!good_radix_p(radix
, 0)) VALERR("bad radix");
738 return (mp_topystring(MP_X(me
), radix
, 0, 0, 0));
743 static PyObject
*mpmeth_modsqrt(PyObject
*me
, PyObject
*arg
)
746 mp
*yy
= 0, *zz
= MP_NEW
;
748 if (!PyArg_ParseTuple(arg
, "O&:modsqrt", convmp
, &yy
)) goto end
;
749 if ((zz
= mp_modsqrt(MP_NEW
, yy
, MP_X(me
))) == 0)
750 VALERR("no modular square root");
757 static PyObject
*mpmeth_leastcongruent(PyObject
*me
, PyObject
*arg
)
762 if (!PyArg_ParseTuple(arg
, "O&O&:leastcongruent", convmp
, &b
, convmp
, &m
))
764 z
= mp_leastcongruent(MP_NEW
, b
, MP_X(me
), m
);
770 #define STOREOP(name, c) \
771 static PyObject *mpmeth_##name(PyObject *me, \
772 PyObject *arg, PyObject *kw) \
775 static const char *const kwlist[] = { "len", 0 }; \
778 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
782 len = mp_octets##c(MP_X(me)); \
785 rc = bytestring_pywrap(0, len); \
786 mp_##name(MP_X(me), BIN_PTR(rc), len); \
792 STOREOP(storel2c
, 2c
)
793 STOREOP(storeb2c
, 2c
)
797 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
804 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
805 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
806 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
807 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
808 bytestring_pywrapbuf(&b)); \
816 static PyObject
*mpmeth_tobuf(PyObject
*me
)
824 n
= mp_octets(x
) + 3;
825 rc
= bytestring_pywrap(0, n
);
826 buf_init(&b
, BIN_PTR(rc
), n
);
829 BIN_SETLEN(rc
, BLEN(&b
));
833 static PyObject
*mpmeth_primep(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
835 grand
*r
= &rand_global
;
836 static const char *const kwlist
[] = { "rng", 0 };
839 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|O&", KWLIST
, convgrand
, &r
))
841 rc
= getbool(pgen_primep(MP_X(me
), r
));
846 static PyObject
*mpmeth_fromstring(PyObject
*me
,
847 PyObject
*arg
, PyObject
*kw
)
855 static const char *const kwlist
[] = { "x", "radix", 0 };
857 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
860 if (!good_radix_p(r
, 1)) VALERR("bad radix");
861 sc
.buf
= p
; sc
.lim
= p
+ len
;
862 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0)
863 VALERR("bad integer");
864 z
= Py_BuildValue("(Ns#)", mp_pywrap(zz
),
865 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
870 static PyObject
*mpmeth_factorial(PyObject
*me
, PyObject
*arg
)
874 if (!PyArg_ParseTuple(arg
, "O&:factorial", convulong
, &i
)) return (0);
879 static PyObject
*mpmeth_fibonacci(PyObject
*me
, PyObject
*arg
)
883 if (!PyArg_ParseTuple(arg
, "l:fibonacci", &i
)) return (0);
888 #define LOADOP(pre, name) \
889 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
892 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
893 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
903 static PyObject
*mpget_nbits(PyObject
*me
, void *hunoz
)
904 { return (PyInt_FromLong(mp_bits(MP_X(me
)))); }
906 static PyObject
*mpget_noctets(PyObject
*me
, void *hunoz
)
907 { return (PyInt_FromLong(mp_octets(MP_X(me
)))); }
909 static PyObject
*mpget_noctets2c(PyObject
*me
, void *hunoz
)
910 { return (PyInt_FromLong(mp_octets2c(MP_X(me
)))); }
912 static const PyGetSetDef mp_pygetset
[] = {
913 #define GETSETNAME(op, func) mp##op##_##func
914 GET (nbits
, "X.nbits -> bit length of X")
915 GET (noctets
, "X.noctets -> octet length of X")
916 GET (noctets2c
, "X.noctets2c -> two's complement octet length of X")
921 static const PyMethodDef mp_pymethods
[] = {
922 #define METHNAME(func) mpmeth_##func
923 METH (jacobi
, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
924 METH (setbit
, "X.setbit(N) -> X with bit N set")
925 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
926 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
927 NAMETH(odd
, "X.odd() -> S, T where X = 2^S T with T odd")
928 NAMETH(sqr
, "X.sqr() -> X^2")
929 NAMETH(sqrt
, "X.sqrt() -> largest integer <= sqrt(X)")
930 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
931 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
932 "with X U + Y V = gcd(X, Y)")
933 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
934 METH (modsqrt
, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
935 METH (leastcongruent
, "X.leastcongruent(B, M) -> "
936 "smallest Z >= B with Z == X (mod M)")
937 KWMETH(primep
, "X.primep([rng = rand]) -> X is prime?")
938 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
939 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
940 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
941 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
942 "little-endian bytes, two's complement")
943 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
944 "big-endian bytes, two's complement")
945 NAMETH(tobuf
, "X.tobuf() -> buffer format")
946 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
947 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
948 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
949 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
951 SMTH (factorial
, "factorial(I) -> I!: compute factorial")
952 SMTH (fibonacci
, "fibonacci(I) -> F(I): compute Fibonacci number")
953 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
954 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
955 SMTH (loadl2c
, "loadl2c(STR) -> X: "
956 "read little-endian bytes, two's complement")
957 SMTH (loadb2c
, "loadb2c(STR) -> X: "
958 "read big-endian bytes, two's complement")
959 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
964 static const PyNumberMethods mp_pynumber
= {
965 mp_pyadd
, /* @nb_add@ */
966 mp_pysub
, /* @nb_subtract@ */
967 mp_pymul
, /* @nb_multiply@ */
971 mp_pymod
, /* @nb_remainder@ */
972 mp_pydivmod
, /* @nb_divmod@ */
973 mp_pyexp
, /* @nb_power@ */
974 mp_pyneg
, /* @nb_negative@ */
975 mp_pyid
, /* @nb_positive@ */
976 mp_pyabs
, /* @nb_absolute@ */
977 mp_pynonzerop
, /* @nb_nonzero@ */
978 mp_pynot2c
, /* @nb_invert@ */
979 mp_pylsl2c
, /* @nb_lshift@ */
980 mp_pylsr2c
, /* @nb_rshift@ */
981 mp_pyand2c
, /* @nb_and@ */
982 mp_pyxor2c
, /* @nb_xor@ */
983 mp_pyor2c
, /* @nb_or@ */
985 mp_pycoerce
, /* @nb_coerce@ */
987 mp_pyint
, /* @nb_int@ */
988 PY23(mp_pylong
, 0), /* @nb_long@ */
989 mp_pyfloat
, /* @nb_float@ */
991 mp_pyoct
, /* @nb_oct@ */
992 mp_pyhex
, /* @nb_hex@ */
995 0, /* @nb_inplace_add@ */
996 0, /* @nb_inplace_subtract@ */
997 0, /* @nb_inplace_multiply@ */
999 0, /* @nb_inplace_divide@ */
1001 0, /* @nb_inplace_remainder@ */
1002 0, /* @nb_inplace_power@ */
1003 0, /* @nb_inplace_lshift@ */
1004 0, /* @nb_inplace_rshift@ */
1005 0, /* @nb_inplace_and@ */
1006 0, /* @nb_inplace_xor@ */
1007 0, /* @nb_inplace_or@ */
1009 mp_pydiv
, /* @nb_floor_divide@ */
1010 0, /* @nb_true_divide@ */
1011 0, /* @nb_inplace_floor_divide@ */
1012 0, /* @nb_inplace_true_divide@ */
1014 mp_pyint
, /* @nb_index@ */
1017 static const PyTypeObject mp_pytype_skel
= {
1018 PyVarObject_HEAD_INIT(0, 0) /* Header */
1019 "MP", /* @tp_name@ */
1020 sizeof(mp_pyobj
), /* @tp_basicsize@ */
1021 0, /* @tp_itemsize@ */
1023 mp_pydealloc
, /* @tp_dealloc@ */
1025 0, /* @tp_getattr@ */
1026 0, /* @tp_setattr@ */
1027 PY23(mp_pycompare
, 0), /* @tp_compare@/@tp_as_async@ */
1028 mp_pyrepr
, /* @tp_repr@ */
1029 PYNUMBER(mp
), /* @tp_as_number@ */
1030 0, /* @tp_as_sequence@ */
1031 0, /* @tp_as_mapping@ */
1032 mp_pyhash
, /* @tp_hash@ */
1034 mp_pystr
, /* @tp_str@ */
1035 0, /* @tp_getattro@ */
1036 0, /* @tp_setattro@ */
1037 0, /* @tp_as_buffer@ */
1038 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1039 Py_TPFLAGS_CHECKTYPES
|
1040 Py_TPFLAGS_BASETYPE
,
1043 "Multiprecision integers, similar to `long' but more efficient and\n"
1044 "versatile. Support all the standard arithmetic operations, with\n"
1045 "implicit conversions from `PrimeFilter', and other objects which\n"
1046 "convert to `" PY23("long", "int") "'.\n"
1048 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1049 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1050 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1052 "points, group elements, Python `int' and `long' objects, and anything\n"
1053 "with an integer conversion.\n",
1054 "points, group elements, Python `int' objects, and anything with an\n"
1055 "integer conversion.\n")
1059 " * Use `//' for integer division: `/' gives exact rational division.",
1061 0, /* @tp_traverse@ */
1063 mp_pyrichcompare
, /* @tp_richcompare@ */
1064 0, /* @tp_weaklistoffset@ */
1066 0, /* @tp_iternext@ */
1067 PYMETHODS(mp
), /* @tp_methods@ */
1068 0, /* @tp_members@ */
1069 PYGETSET(mp
), /* @tp_getset@ */
1072 0, /* @tp_descr_get@ */
1073 0, /* @tp_descr_set@ */
1074 0, /* @tp_dictoffset@ */
1076 PyType_GenericAlloc
, /* @tp_alloc@ */
1077 mp_pynew
, /* @tp_new@ */
1082 /*----- Products of small integers ----------------------------------------*/
1084 static PyTypeObject
*mpmul_pytype
;
1086 typedef struct mpmul_pyobj
{
1092 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1093 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1095 static void mpmul_pydealloc(PyObject
*me
)
1097 if (MPMUL_LIVEP(me
))
1098 mp_drop(mpmul_done(MPMUL_PY(me
)));
1102 static PyObject
*mmmeth_factor(PyObject
*me
, PyObject
*arg
)
1107 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1108 if (PyTuple_GET_SIZE(arg
) != 1)
1109 i
= PyObject_GetIter(arg
);
1111 if ((q
= PyTuple_GET_ITEM(arg
, 0)) == 0) goto end
;
1112 if ((i
= PyObject_GetIter(q
)) == 0) {
1113 PyErr_Clear(); /* that's ok */
1114 i
= PyObject_GetIter(arg
);
1118 while ((q
= PyIter_Next(i
)) != 0) {
1119 x
= getmp(q
); Py_DECREF(q
); if (!x
) {
1123 mpmul_add(MPMUL_PY(me
), x
);
1132 static PyObject
*mmmeth_done(PyObject
*me
)
1136 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1137 x
= mpmul_done(MPMUL_PY(me
));
1138 MPMUL_LIVEP(me
) = 0;
1139 return (mp_pywrap(x
));
1144 static PyObject
*mpmul_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1148 if (kw
) TYERR("keyword arguments not allowed here");
1149 mm
= (mpmul_pyobj
*)ty
->tp_alloc(ty
, 0);
1150 mpmul_init(&mm
->mm
);
1152 if (mmmeth_factor((PyObject
*)mm
, arg
) == 0) {
1156 return ((PyObject
*)mm
);
1161 static PyObject
*mmget_livep(PyObject
*me
, void *hunoz
)
1162 { return (getbool(MPMUL_LIVEP(me
))); }
1164 static const PyGetSetDef mpmul_pygetset
[] = {
1165 #define GETSETNAME(op, name) mm##op##_##name
1166 GET (livep
, "MM.livep -> flag: object still valid?")
1171 static const PyMethodDef mpmul_pymethods
[] = {
1172 #define METHNAME(name) mmmeth_##name
1173 METH (factor
, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1174 NAMETH(done
, "MM.done() -> PRODUCT")
1179 static const PyTypeObject mpmul_pytype_skel
= {
1180 PyVarObject_HEAD_INIT(0, 0) /* Header */
1181 "MPMul", /* @tp_name@ */
1182 sizeof(mpmul_pyobj
), /* @tp_basicsize@ */
1183 0, /* @tp_itemsize@ */
1185 mpmul_pydealloc
, /* @tp_dealloc@ */
1187 0, /* @tp_getattr@ */
1188 0, /* @tp_setattr@ */
1189 0, /* @tp_compare@ */
1191 0, /* @tp_as_number@ */
1192 0, /* @tp_as_sequence@ */
1193 0, /* @tp_as_mapping@ */
1197 0, /* @tp_getattro@ */
1198 0, /* @tp_setattro@ */
1199 0, /* @tp_as_buffer@ */
1200 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1201 Py_TPFLAGS_BASETYPE
,
1204 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1206 0, /* @tp_traverse@ */
1208 0, /* @tp_richcompare@ */
1209 0, /* @tp_weaklistoffset@ */
1211 0, /* @tp_iternext@ */
1212 PYMETHODS(mpmul
), /* @tp_methods@ */
1213 0, /* @tp_members@ */
1214 PYGETSET(mpmul
), /* @tp_getset@ */
1217 0, /* @tp_descr_get@ */
1218 0, /* @tp_descr_set@ */
1219 0, /* @tp_dictoffset@ */
1221 PyType_GenericAlloc
, /* @tp_alloc@ */
1222 mpmul_pynew
, /* @tp_new@ */
1227 /*----- Montgomery reduction ----------------------------------------------*/
1229 static PyTypeObject
*mpmont_pytype
;
1231 typedef struct mpmont_pyobj
{
1236 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1238 static PyObject
*mmmeth_int(PyObject
*me
, PyObject
*arg
)
1242 mpmont
*mm
= MPMONT_PY(me
);
1244 if (!PyArg_ParseTuple(arg
, "O&:in", convmp
, &yy
))
1246 mp_div(0, &yy
, yy
, mm
->m
);
1247 z
= mp_pywrap(mpmont_mul(mm
, MP_NEW
, yy
, mm
->r2
));
1249 if (yy
) MP_DROP(yy
);
1253 static PyObject
*mmmeth_mul(PyObject
*me
, PyObject
*arg
)
1256 mp
*yy
= 0, *zz
= 0;
1258 if (!PyArg_ParseTuple(arg
, "O&O&:mul", convmp
, &yy
, convmp
, &zz
))
1260 rc
= mp_pywrap(mpmont_mul(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1262 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1266 static PyObject
*mmmeth_exp(PyObject
*me
, PyObject
*arg
)
1269 mp
*yy
= 0, *zz
= 0;
1271 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1274 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1275 zz
= mp_neg(zz
, zz
);
1277 rc
= mp_pywrap(mpmont_exp(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1279 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1283 static PyObject
*mmmeth_expr(PyObject
*me
, PyObject
*arg
)
1286 mp
*yy
= 0, *zz
= 0;
1288 if (!PyArg_ParseTuple(arg
, "O&O&:expr", convmp
, &yy
, convmp
, &zz
))
1291 yy
= mpmont_reduce(MPMONT_PY(me
), yy
, yy
);
1292 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1293 yy
= mpmont_mul(MPMONT_PY(me
), yy
, yy
, MPMONT_PY(me
)->r2
);
1294 zz
= mp_neg(zz
, zz
);
1296 rc
= mp_pywrap(mpmont_expr(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1298 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1302 static PyObject
*mm_mexpr_id(PyObject
*me
)
1303 { return mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
)); }
1305 static int mm_mexpr_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1307 mp
*xx
= 0, *yy
= 0;
1308 mp_expfactor
*f
= p
;
1309 mpmont
*mm
= MPMONT_PY(me
);
1311 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1314 xx
= mpmont_reduce(mm
, xx
, xx
);
1315 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1317 xx
= mpmont_mul(mm
, xx
, xx
, mm
->r2
);
1318 yy
= mp_neg(yy
, yy
);
1325 mp_drop(xx
); mp_drop(yy
);
1329 static PyObject
*mm_mexpr(PyObject
*me
, void *v
, int n
)
1330 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1332 static void mp_mexp_drop(void *p
)
1334 mp_expfactor
*f
= p
;
1339 static PyObject
*mmmeth_mexpr(PyObject
*me
, PyObject
*arg
)
1341 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1342 mm_mexpr_id
, mm_mexpr_fill
, mm_mexpr
, mp_mexp_drop
);
1345 static PyObject
*mp_mexp_id(PyObject
*me
)
1346 { return mp_pywrap(MP_ONE
); }
1348 static int mp_mexp_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1350 mp
*xx
= 0, *yy
= 0;
1351 mp_expfactor
*f
= p
;
1353 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1356 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1358 yy
= mp_neg(yy
, yy
);
1365 mp_drop(xx
); mp_drop(yy
);
1369 static PyObject
*mm_mexp(PyObject
*me
, void *v
, int n
)
1370 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1372 static PyObject
*mmmeth_mexp(PyObject
*me
, PyObject
*arg
)
1374 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1375 mp_mexp_id
, mp_mexp_fill
, mm_mexp
, mp_mexp_drop
);
1378 #define mmmeth_ext mmmeth_reduce
1379 static PyObject
*mmmeth_reduce(PyObject
*me
, PyObject
*arg
)
1384 if (!PyArg_ParseTuple(arg
, "O&", convmp
, &yy
)) goto end
;
1385 z
= mp_pywrap(mpmont_reduce(MPMONT_PY(me
), MP_NEW
, yy
));
1390 static void mpmont_pydealloc(PyObject
*me
)
1392 mpmont_destroy(MPMONT_PY(me
));
1396 static PyObject
*mpmont_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1398 mpmont_pyobj
*mm
= 0;
1399 static const char *const kwlist
[] = { "m", 0 };
1402 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1404 if (!MP_POSP(xx
) || !MP_ODDP(xx
)) VALERR("m must be positive and odd");
1405 mm
= (mpmont_pyobj
*)ty
->tp_alloc(ty
, 0);
1406 mpmont_create(&mm
->mm
, xx
);
1408 if (xx
) MP_DROP(xx
);
1409 return ((PyObject
*)mm
);
1412 static PyObject
*mmget_m(PyObject
*me
, void *hunoz
)
1413 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->m
))); }
1415 static PyObject
*mmget_r(PyObject
*me
, void *hunoz
)
1416 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
))); }
1418 static PyObject
*mmget_r2(PyObject
*me
, void *hunoz
)
1419 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r2
))); }
1421 static const PyGetSetDef mpmont_pygetset
[] = {
1422 #define GETSETNAME(op, name) mm##op##_##name
1423 GET (m
, "M.m -> modulus for reduction")
1424 GET (r
, "M.r -> multiplicative identity")
1425 GET (r2
, "M.r2 -> M.r^2, Montgomerization factor")
1430 static const PyMethodDef mpmont_pymethods
[] = {
1431 #define METHNAME(name) mmmeth_##name
1432 METH (int, "M.int(X) -> XR")
1433 METH (mul
, "M.mul(XR, YR) -> ZR where Z = X Y")
1434 METH (expr
, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1435 METH (mexpr
, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1436 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1437 "\t(the list may be flattened if this more convenient.)")
1438 METH (reduce
, "M.reduce(XR) -> X")
1439 METH (ext
, "M.ext(XR) -> X")
1440 METH (exp
, "M.exp(X, N) -> X^N mod M.m")
1441 METH (mexp
, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1442 "X0^N0 X1^N1 ... mod M.m\n"
1443 "\t(the list may be flattened if this more convenient.)")
1448 static const PyTypeObject mpmont_pytype_skel
= {
1449 PyVarObject_HEAD_INIT(0, 0) /* Header */
1450 "MPMont", /* @tp_name@ */
1451 sizeof(mpmont_pyobj
), /* @tp_basicsize@ */
1452 0, /* @tp_itemsize@ */
1454 mpmont_pydealloc
, /* @tp_dealloc@ */
1456 0, /* @tp_getattr@ */
1457 0, /* @tp_setattr@ */
1458 0, /* @tp_compare@ */
1460 0, /* @tp_as_number@ */
1461 0, /* @tp_as_sequence@ */
1462 0, /* @tp_as_mapping@ */
1466 0, /* @tp_getattro@ */
1467 0, /* @tp_setattro@ */
1468 0, /* @tp_as_buffer@ */
1469 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1470 Py_TPFLAGS_BASETYPE
,
1473 "MPMont(N): a Montgomery reduction context.",
1475 0, /* @tp_traverse@ */
1477 0, /* @tp_richcompare@ */
1478 0, /* @tp_weaklistoffset@ */
1480 0, /* @tp_iternext@ */
1481 PYMETHODS(mpmont
), /* @tp_methods@ */
1482 0, /* @tp_members@ */
1483 PYGETSET(mpmont
), /* @tp_getset@ */
1486 0, /* @tp_descr_get@ */
1487 0, /* @tp_descr_set@ */
1488 0, /* @tp_dictoffset@ */
1490 PyType_GenericAlloc
, /* @tp_alloc@ */
1491 mpmont_pynew
, /* @tp_new@ */
1496 /*----- Barrett reduction -------------------------------------------------*/
1498 static PyTypeObject
*mpbarrett_pytype
;
1500 typedef struct mpbarrett_pyobj
{
1505 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1507 static PyObject
*mbmeth_exp(PyObject
*me
, PyObject
*arg
)
1510 mp
*yy
= 0, *zz
= 0;
1512 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1515 if ((yy
= mp_modinv_checked(yy
, yy
, MPBARRETT_PY(me
)->m
)) == 0) goto end
;
1516 zz
= mp_neg(zz
, zz
);
1518 rc
= mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me
), MP_NEW
, yy
, zz
));
1520 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1524 static PyObject
*mb_mexp(PyObject
*me
, void *v
, int n
)
1525 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me
), MP_NEW
, v
, n
)); }
1527 static PyObject
*mbmeth_mexp(PyObject
*me
, PyObject
*arg
)
1529 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1530 mp_mexp_id
, mp_mexp_fill
, mb_mexp
, mp_mexp_drop
);
1533 static PyObject
*mbmeth_reduce(PyObject
*me
, PyObject
*arg
)
1538 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
))
1540 z
= mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me
), MP_NEW
, yy
));
1545 static void mpbarrett_pydealloc(PyObject
*me
)
1547 mpbarrett_destroy(MPBARRETT_PY(me
));
1551 static PyObject
*mpbarrett_pynew(PyTypeObject
*ty
,
1552 PyObject
*arg
, PyObject
*kw
)
1554 mpbarrett_pyobj
*mb
= 0;
1555 static const char *const kwlist
[] = { "m", 0 };
1558 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1560 if (!MP_POSP(xx
)) VALERR("m must be positive");
1561 mb
= (mpbarrett_pyobj
*)ty
->tp_alloc(ty
, 0);
1562 mpbarrett_create(&mb
->mb
, xx
);
1564 if (xx
) MP_DROP(xx
);
1565 return ((PyObject
*)mb
);
1568 static PyObject
*mbget_m(PyObject
*me
, void *hunoz
)
1569 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me
)->m
))); }
1571 static const PyGetSetDef mpbarrett_pygetset
[] = {
1572 #define GETSETNAME(op, name) mb##op##_##name
1573 GET (m
, "B.m -> modulus for reduction")
1578 static const PyMethodDef mpbarrett_pymethods
[] = {
1579 #define METHNAME(name) mbmeth_##name
1580 METH (reduce
, "B.reduce(X) -> X mod B.m")
1581 METH (exp
, "B.exp(X, N) -> X^N mod B.m")
1582 METH (mexp
, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1583 "X0^N0 X1^N1 ... mod B.m\n"
1584 "\t(the list may be flattened if this more convenient.)")
1589 static const PyTypeObject mpbarrett_pytype_skel
= {
1590 PyVarObject_HEAD_INIT(0, 0) /* Header */
1591 "MPBarrett", /* @tp_name@ */
1592 sizeof(mpbarrett_pyobj
), /* @tp_basicsize@ */
1593 0, /* @tp_itemsize@ */
1595 mpbarrett_pydealloc
, /* @tp_dealloc@ */
1597 0, /* @tp_getattr@ */
1598 0, /* @tp_setattr@ */
1599 0, /* @tp_compare@ */
1601 0, /* @tp_as_number@ */
1602 0, /* @tp_as_sequence@ */
1603 0, /* @tp_as_mapping@ */
1607 0, /* @tp_getattro@ */
1608 0, /* @tp_setattro@ */
1609 0, /* @tp_as_buffer@ */
1610 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1611 Py_TPFLAGS_BASETYPE
,
1614 "MPBarrett(N): a Barrett reduction context.",
1616 0, /* @tp_traverse@ */
1618 0, /* @tp_richcompare@ */
1619 0, /* @tp_weaklistoffset@ */
1621 0, /* @tp_iternext@ */
1622 PYMETHODS(mpbarrett
), /* @tp_methods@ */
1623 0, /* @tp_members@ */
1624 PYGETSET(mpbarrett
), /* @tp_getset@ */
1627 0, /* @tp_descr_get@ */
1628 0, /* @tp_descr_set@ */
1629 0, /* @tp_dictoffset@ */
1631 PyType_GenericAlloc
, /* @tp_alloc@ */
1632 mpbarrett_pynew
, /* @tp_new@ */
1637 /*----- Nice prime reduction ----------------------------------------------*/
1639 static PyTypeObject
*mpreduce_pytype
;
1641 typedef struct mpreduce_pyobj
{
1646 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1648 static PyObject
*mrmeth_exp(PyObject
*me
, PyObject
*arg
)
1651 mp
*yy
= 0, *zz
= 0;
1653 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1656 if ((yy
= mp_modinv_checked(yy
, yy
, MPREDUCE_PY(me
)->p
)) == 0) goto end
;
1657 zz
= mp_neg(zz
, zz
);
1659 rc
= mp_pywrap(mpreduce_exp(MPREDUCE_PY(me
), MP_NEW
, yy
, zz
));
1661 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1665 static PyObject
*mrmeth_reduce(PyObject
*me
, PyObject
*arg
)
1670 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
)) goto end
;
1671 z
= mp_pywrap(mpreduce_do(MPREDUCE_PY(me
), MP_NEW
, yy
));
1676 static void mpreduce_pydealloc(PyObject
*me
)
1678 mpreduce_destroy(MPREDUCE_PY(me
));
1682 static PyObject
*mpreduce_pynew(PyTypeObject
*ty
,
1683 PyObject
*arg
, PyObject
*kw
)
1685 mpreduce_pyobj
*mr
= 0;
1687 static const char *const kwlist
[] = { "m", 0 };
1690 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1692 if (!MP_POSP(xx
)) VALERR("m must be positive");
1693 if (mpreduce_create(&r
, xx
)) VALERR("bad modulus (must be 2^k - ...)");
1694 mr
= (mpreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
1697 if (xx
) MP_DROP(xx
);
1698 return ((PyObject
*)mr
);
1701 static PyObject
*mrget_m(PyObject
*me
, void *hunoz
)
1702 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me
)->p
))); }
1704 static const PyGetSetDef mpreduce_pygetset
[] = {
1705 #define GETSETNAME(op, name) mr##op##_##name
1706 GET (m
, "R.m -> modulus for reduction")
1711 static const const PyMethodDef mpreduce_pymethods
[] = {
1712 #define METHNAME(name) mrmeth_##name
1713 METH (reduce
, "R.reduce(X) -> X mod B.m")
1714 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
1719 static const PyTypeObject mpreduce_pytype_skel
= {
1720 PyVarObject_HEAD_INIT(0, 0) /* Header */
1721 "MPReduce", /* @tp_name@ */
1722 sizeof(mpreduce_pyobj
), /* @tp_basicsize@ */
1723 0, /* @tp_itemsize@ */
1725 mpreduce_pydealloc
, /* @tp_dealloc@ */
1727 0, /* @tp_getattr@ */
1728 0, /* @tp_setattr@ */
1729 0, /* @tp_compare@ */
1731 0, /* @tp_as_number@ */
1732 0, /* @tp_as_sequence@ */
1733 0, /* @tp_as_mapping@ */
1737 0, /* @tp_getattro@ */
1738 0, /* @tp_setattro@ */
1739 0, /* @tp_as_buffer@ */
1740 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1741 Py_TPFLAGS_BASETYPE
,
1744 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1746 0, /* @tp_traverse@ */
1748 0, /* @tp_richcompare@ */
1749 0, /* @tp_weaklistoffset@ */
1751 0, /* @tp_iternext@ */
1752 PYMETHODS(mpreduce
), /* @tp_methods@ */
1753 0, /* @tp_members@ */
1754 PYGETSET(mpreduce
), /* @tp_getset@ */
1757 0, /* @tp_descr_get@ */
1758 0, /* @tp_descr_set@ */
1759 0, /* @tp_dictoffset@ */
1761 PyType_GenericAlloc
, /* @tp_alloc@ */
1762 mpreduce_pynew
, /* @tp_new@ */
1767 /*----- Chinese Remainder Theorem solution --------------------------------*/
1769 static PyTypeObject
*mpcrt_pytype
;
1771 typedef struct mpcrt_pyobj
{
1776 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1778 static PyObject
*mcmeth_solve(PyObject
*me
, PyObject
*arg
)
1780 mpcrt
*c
= MPCRT_PY(me
);
1781 PyObject
*q
= 0, *x
, *z
= 0;
1784 Py_ssize_t i
= 0, n
= c
->k
;
1786 if (PyTuple_GET_SIZE(arg
) == n
)
1788 else if (!PyArg_ParseTuple(arg
, "O:solve", &q
))
1790 if (!PySequence_Check(q
)) TYERR("want a sequence of residues");
1791 i
= PySequence_Size(q
); if (i
< 0) goto end
;
1792 if (i
!= n
) VALERR("residue count mismatch");
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
;
1799 z
= mp_pywrap(mpcrt_solve(c
, MP_NEW
, v
));
1803 for (i
= 0; i
< n
; i
++)
1810 static void mpcrt_pydealloc(PyObject
*me
)
1812 mpcrt
*c
= MPCRT_PY(me
);
1817 static PyObject
*mpcrt_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1820 Py_ssize_t n
, i
= 0, j
;
1821 static const char *const kwlist
[] = { "mv", 0 };
1822 PyObject
*q
= 0, *x
;
1823 mp
*xx
= MP_NEW
, *y
= MP_NEW
, *g
= MP_NEW
;
1827 if (PyTuple_GET_SIZE(arg
) > 1)
1829 else if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O:new", KWLIST
, &q
))
1831 if (!PySequence_Check(q
)) TYERR("want a sequence of moduli");
1832 n
= PySequence_Size(q
); if (n
< 0) goto end
;
1833 if (!n
) VALERR("want at least one modulus");
1834 v
= xmalloc(n
* sizeof(*v
));
1835 for (i
= 0; i
< n
; i
++) {
1836 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1837 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1838 if (MP_CMP(xx
, <=, MP_ZERO
)) VALERR("moduli must be positive");
1839 v
[i
].m
= xx
; v
[i
].n
= 0; v
[i
].ni
= 0; v
[i
].nni
= 0; xx
= MP_NEW
;
1842 for (j
= 0; j
< i
; j
++) mpmul_add(&mm
, v
[j
].m
);
1843 xx
= mpmul_done(&mm
);
1844 for (j
= 0; j
< i
; j
++) {
1845 mp_div(&y
, 0, xx
, v
[j
].m
);
1846 mp_gcd(&g
, 0, 0, y
, v
[j
].m
);
1847 if (!MP_EQ(g
, MP_ONE
)) VALERR("moduli must be pairwise coprime");
1850 c
= (mpcrt_pyobj
*)ty
->tp_alloc(ty
, 0);
1851 mpcrt_create(&c
->c
, v
, n
, 0);
1852 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1853 return ((PyObject
*)c
);
1858 for (i
= 0; i
< n
; i
++)
1862 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1866 static PyObject
*mcget_product(PyObject
*me
, void *hunoz
)
1867 { return (mp_pywrap(MP_COPY(MPCRT_PY(me
)->mb
.m
))); }
1869 static PyObject
*mcget_moduli(PyObject
*me
, void *hunoz
)
1873 mpcrt
*c
= MPCRT_PY(me
);
1875 if ((q
= PyList_New(c
->k
)) == 0) return (0);
1876 for (i
= 0; i
< c
->k
; i
++)
1877 PyList_SET_ITEM(q
, i
, mp_pywrap(c
->v
[i
].m
));
1881 static const PyGetSetDef mpcrt_pygetset
[] = {
1882 #define GETSETNAME(op, name) mc##op##_##name
1883 GET (product
, "C.product -> product of moduli")
1884 GET (moduli
, "C.moduli -> list of individual moduli")
1889 static const PyMethodDef mpcrt_pymethods
[] = {
1890 #define METHNAME(name) mcmeth_##name
1891 METH (solve
, "C.solve([R0, R1]) -> X mod C.product")
1896 static const PyTypeObject mpcrt_pytype_skel
= {
1897 PyVarObject_HEAD_INIT(0, 0) /* Header */
1898 "MPCRT", /* @tp_name@ */
1899 sizeof(mpcrt_pyobj
), /* @tp_basicsize@ */
1900 0, /* @tp_itemsize@ */
1902 mpcrt_pydealloc
, /* @tp_dealloc@ */
1904 0, /* @tp_getattr@ */
1905 0, /* @tp_setattr@ */
1906 0, /* @tp_compare@ */
1908 0, /* @tp_as_number@ */
1909 0, /* @tp_as_sequence@ */
1910 0, /* @tp_as_mapping@ */
1914 0, /* @tp_getattro@ */
1915 0, /* @tp_setattro@ */
1916 0, /* @tp_as_buffer@ */
1917 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1918 Py_TPFLAGS_BASETYPE
,
1921 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1923 0, /* @tp_traverse@ */
1925 0, /* @tp_richcompare@ */
1926 0, /* @tp_weaklistoffset@ */
1928 0, /* @tp_iternext@ */
1929 PYMETHODS(mpcrt
), /* @tp_methods@ */
1930 0, /* @tp_members@ */
1931 PYGETSET(mpcrt
), /* @tp_getset@ */
1934 0, /* @tp_descr_get@ */
1935 0, /* @tp_descr_set@ */
1936 0, /* @tp_dictoffset@ */
1938 PyType_GenericAlloc
, /* @tp_alloc@ */
1939 mpcrt_pynew
, /* @tp_new@ */
1944 /*----- Binary polynomials ------------------------------------------------*/
1946 static PyObject
*gf_pyrepr(PyObject
*o
)
1947 { return mp_topystring(MP_X(o
), 16, "GF(", "0x", ")"); }
1949 static PyObject
*gf_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
1955 if (gfbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
1957 case Py_EQ
: b
= MP_EQ(xx
, yy
); break;
1958 case Py_NE
: b
= !MP_EQ(xx
, yy
); break;
1963 case Py_LT
: b
= xl
< yl
; break;
1964 case Py_LE
: b
= xl
<= yl
; break;
1965 case Py_GT
: b
= xl
> yl
; break;
1966 case Py_GE
: b
= xl
>= yl
; break;
1971 MP_DROP(xx
); MP_DROP(yy
);
1972 return (getbool(b
));
1975 static PyObject
*gf_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1981 static const char *const kwlist
[] = { "x", "radix", 0 };
1983 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:gf", KWLIST
, &x
, &radix
))
1985 if (GF_PYCHECK(x
)) RETURN_OBJ(x
);
1986 if (!good_radix_p(radix
, 1)) VALERR("radix out of range");
1987 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
1988 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
1989 Py_TYPE(x
)->tp_name
);
1994 VALERR("gf cannot be negative");
1996 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
1999 return ((PyObject
*)zz
);
2002 static PyObject
*gf_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
2004 mp
*xx
= 0, *yy
= 0, *zz
= 0;
2008 if ((xx
= implicitgf(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
2009 (z
&& z
!= Py_None
&& (zz
= implicitgf(z
)) == 0)) {
2010 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2013 if (!z
|| z
== Py_None
) {
2014 if (MP_NEGP(yy
)) VALERR("negative exponent");
2015 r
= gf_exp(MP_NEW
, xx
, yy
);
2018 if (MP_ZEROP(zz
)) ZDIVERR("zero modulus");
2020 if ((xx
= gf_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
2021 yy
= mp_neg(yy
, yy
);
2023 gfreduce_create(&gr
, zz
);
2024 r
= gfreduce_exp(&gr
, MP_NEW
, xx
, yy
);
2025 gfreduce_destroy(&gr
);
2029 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2033 static PyObject
*gfmeth_sqr(PyObject
*me
)
2034 { return (gf_pywrap(gf_sqr(MP_NEW
, MP_X(me
)))); }
2036 static PyObject
*gfmeth_gcd(PyObject
*me
, PyObject
*arg
)
2039 mp
*yy
= 0, *zz
= MP_NEW
;
2041 if (!PyArg_ParseTuple(arg
, "O&:gcd", convgf
, &yy
)) goto end
;
2042 gf_gcd(&zz
, 0, 0, MP_X(me
), yy
);
2045 if (yy
) MP_DROP(yy
);
2049 static PyObject
*gfmeth_gcdx(PyObject
*me
, PyObject
*arg
)
2052 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
2054 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convgf
, &yy
))
2056 gf_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
2057 z
= Py_BuildValue("(NNN)",
2058 gf_pywrap(zz
), gf_pywrap(uu
), gf_pywrap(vv
));
2060 if (yy
) MP_DROP(yy
);
2064 static PyObject
*gfmeth_modinv(PyObject
*me
, PyObject
*arg
)
2067 mp
*yy
= 0, *zz
= MP_NEW
;
2069 if (!PyArg_ParseTuple(arg
, "O&:modinv", convgf
, &yy
) ||
2070 (zz
= gf_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
2074 if (yy
) MP_DROP(yy
);
2078 static PyObject
*gfmeth_fromstring(PyObject
*me
,
2079 PyObject
*arg
, PyObject
*kw
)
2086 mptext_stringctx sc
;
2087 static const char *const kwlist
[] = { "x", "radix", 0 };
2089 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
2092 if (!good_radix_p(r
, 1)) VALERR("bad radix");
2093 sc
.buf
= p
; sc
.lim
= p
+ len
;
2094 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0 ||
2096 if (zz
) MP_DROP(zz
);
2097 VALERR("bad binary polynomial");
2099 z
= Py_BuildValue("(Ns#)", gf_pywrap(zz
),
2100 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
2105 static PyObject
*gfmeth_irreduciblep(PyObject
*me
)
2106 { return getbool(gf_irreduciblep(MP_X(me
))); }
2108 static PyObject
*gfget_degree(PyObject
*me
, void *hunoz
)
2109 { return (PyInt_FromLong(mp_bits(MP_X(me
)) - 1)); }
2111 static const PyGetSetDef gf_pygetset
[] = {
2112 #define GETSETNAME(op, name) gf##op##_##name
2113 GET (degree
, "X.degree -> polynomial degree of X")
2115 #define GETSETNAME(op, name) mp##op##_##name
2116 GET (nbits
, "X.nbits -> bit length of X")
2117 GET (noctets
, "X.noctets -> octet length of X")
2122 static const PyMethodDef gf_pymethods
[] = {
2123 #define METHNAME(func) gfmeth_##func
2124 METH (setbit
, "X.setbit(N) -> X with bit N set")
2125 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
2126 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
2127 NAMETH(sqr
, "X.sqr() -> X^2")
2128 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
2129 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2130 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2131 NAMETH(irreduciblep
, "X.irreduciblep() -> true/false")
2132 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2133 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2134 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2135 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2137 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
2138 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
2139 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
2141 #define METHNAME(func) mpmeth_##func
2142 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
2143 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
2144 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
2145 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
2146 "little-endian bytes, two's complement")
2147 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
2148 "big-endian bytes, two's complement")
2149 NAMETH(tobuf
, "X.tobuf() -> buffer format")
2154 static const PyNumberMethods gf_pynumber
= {
2155 gf_pyadd
, /* @nb_add@ */
2156 gf_pysub
, /* @nb_subtract@ */
2157 gf_pymul
, /* @nb_multiply@ */
2159 0, /* @nb_divide@ */
2161 gf_pymod
, /* @nb_remainder@ */
2162 gf_pydivmod
, /* @nb_divmod@ */
2163 gf_pyexp
, /* @nb_power@ */
2164 mp_pyid
, /* @nb_negative@ */
2165 mp_pyid
, /* @nb_positive@ */
2166 mp_pyid
, /* @nb_absolute@ */
2167 mp_pynonzerop
, /* @nb_nonzero@ */
2168 0 /* doesn't make any sense */, /* @nb_invert@ */
2169 gf_pylsl
, /* @nb_lshift@ */
2170 gf_pylsr
, /* @nb_rshift@ */
2171 gf_pyand
, /* @nb_and@ */
2172 gf_pyxor
, /* @nb_xor@ */
2173 gf_pyor
, /* @nb_or@ */
2175 gf_pycoerce
, /* @nb_coerce@ */
2177 mp_pyint
, /* @nb_int@ */
2178 PY23(mp_pylong
, 0), /* @nb_long@ */
2179 0 /* doesn't make any sense */, /* @nb_float@ */
2181 mp_pyoct
, /* @nb_oct@ */
2182 mp_pyhex
, /* @nb_hex@ */
2185 0, /* @nb_inplace_add@ */
2186 0, /* @nb_inplace_subtract@ */
2187 0, /* @nb_inplace_multiply@ */
2189 0, /* @nb_inplace_divide@ */
2191 0, /* @nb_inplace_remainder@ */
2192 0, /* @nb_inplace_power@ */
2193 0, /* @nb_inplace_lshift@ */
2194 0, /* @nb_inplace_rshift@ */
2195 0, /* @nb_inplace_and@ */
2196 0, /* @nb_inplace_xor@ */
2197 0, /* @nb_inplace_or@ */
2199 gf_pydiv
, /* @nb_floor_divide@ */
2200 0, /* @nb_true_divide@ */
2201 0, /* @nb_inplace_floor_divide@ */
2202 0, /* @nb_inplace_true_divide@ */
2204 mp_pyint
, /* @nb_index@ */
2207 static const PyTypeObject gf_pytype_skel
= {
2208 PyVarObject_HEAD_INIT(0, 0) /* Header */
2209 "GF", /* @tp_name@ */
2210 sizeof(mp_pyobj
), /* @tp_basicsize@ */
2211 0, /* @tp_itemsize@ */
2213 mp_pydealloc
, /* @tp_dealloc@ */
2215 0, /* @tp_getattr@ */
2216 0, /* @tp_setattr@ */
2217 0, /* @tp_compare@ */
2218 gf_pyrepr
, /* @tp_repr@ */
2219 PYNUMBER(gf
), /* @tp_as_number@ */
2220 0, /* @tp_as_sequence@ */
2221 0, /* @tp_as_mapping@ */
2222 mp_pyhash
, /* @tp_hash@ */
2224 mp_pyhex
, /* @tp_str@ */
2225 0, /* @tp_getattro@ */
2226 0, /* @tp_setattro@ */
2227 0, /* @tp_as_buffer@ */
2228 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2229 Py_TPFLAGS_CHECKTYPES
|
2230 Py_TPFLAGS_BASETYPE
,
2233 "Binary polynomials. Support almost all the standard arithmetic\n"
2236 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2237 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2238 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2240 "points, group elements, Python `int' and `long' objects, and anything\n"
2241 "with an integer conversion.\n",
2242 "points, group elements, Python `int' objects, and anything with an\n"
2243 "integer conversion.\n")
2245 "The name is hopelessly wrong from a technical point of view, but\n"
2246 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2250 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2252 0, /* @tp_traverse@ */
2254 gf_pyrichcompare
, /* @tp_richcompare@ */
2255 0, /* @tp_weaklistoffset@ */
2257 0, /* @tp_iternext@ */
2258 PYMETHODS(gf
), /* @tp_methods@ */
2259 0, /* @tp_members@ */
2260 PYGETSET(gf
), /* @tp_getset@ */
2263 0, /* @tp_descr_get@ */
2264 0, /* @tp_descr_set@ */
2265 0, /* @tp_dictoffset@ */
2267 PyType_GenericAlloc
, /* @tp_alloc@ */
2268 gf_pynew
, /* @tp_new@ */
2273 /*----- Sparse poly reduction ---------------------------------------------*/
2275 static PyTypeObject
*gfreduce_pytype
;
2277 typedef struct gfreduce_pyobj
{
2282 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2284 static PyObject
*grmeth_exp(PyObject
*me
, PyObject
*arg
)
2287 mp
*yy
= 0, *zz
= 0;
2289 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convgf
, &yy
, convgf
, &zz
))
2292 if ((yy
= gf_modinv_checked(yy
, yy
, GFREDUCE_PY(me
)->p
)) == 0) goto end
;
2293 zz
= mp_neg(zz
, zz
);
2295 rc
= gf_pywrap(gfreduce_exp(GFREDUCE_PY(me
), MP_NEW
, yy
, zz
));
2297 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
2301 static PyObject
*grmeth_trace(PyObject
*me
, PyObject
*arg
)
2306 if (!PyArg_ParseTuple(arg
, "O&:trace", convgf
, &xx
)) goto end
;
2307 rc
= PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me
), xx
));
2309 if (xx
) MP_DROP(xx
);
2313 static PyObject
*grmeth_halftrace(PyObject
*me
, PyObject
*arg
)
2318 if (!PyArg_ParseTuple(arg
, "O&:halftrace", convgf
, &xx
)) goto end
;
2319 rc
= gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me
), MP_NEW
, xx
));
2321 if (xx
) MP_DROP(xx
);
2325 static PyObject
*grmeth_sqrt(PyObject
*me
, PyObject
*arg
)
2330 if (!PyArg_ParseTuple(arg
, "O&:sqrt", convgf
, &xx
)) goto end
;
2331 if ((yy
= gfreduce_sqrt(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2332 VALERR("no modular square root");
2335 if (xx
) MP_DROP(xx
);
2339 static PyObject
*grmeth_quadsolve(PyObject
*me
, PyObject
*arg
)
2344 if (!PyArg_ParseTuple(arg
, "O&:quadsolve", convgf
, &xx
)) goto end
;
2345 if ((yy
= gfreduce_quadsolve(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2346 VALERR("no solution found");
2349 if (xx
) MP_DROP(xx
);
2353 static PyObject
*grmeth_reduce(PyObject
*me
, PyObject
*arg
)
2358 if (!PyArg_ParseTuple(arg
, "O&:reduce", convgf
, &yy
)) goto end
;
2359 z
= gf_pywrap(gfreduce_do(GFREDUCE_PY(me
), MP_NEW
, yy
));
2364 static void gfreduce_pydealloc(PyObject
*me
)
2366 gfreduce_destroy(GFREDUCE_PY(me
));
2370 static PyObject
*gfreduce_pynew(PyTypeObject
*ty
,
2371 PyObject
*arg
, PyObject
*kw
)
2373 gfreduce_pyobj
*mr
= 0;
2375 static const char *const kwlist
[] = { "m", 0 };
2378 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convgf
, &xx
))
2380 if (MP_ZEROP(xx
)) ZDIVERR("modulus is zero!");
2381 gfreduce_create(&r
, xx
);
2382 mr
= (gfreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
2385 if (xx
) MP_DROP(xx
);
2386 return ((PyObject
*)mr
);
2389 static PyObject
*grget_m(PyObject
*me
, void *hunoz
)
2390 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me
)->p
))); }
2392 static const PyGetSetDef gfreduce_pygetset
[] = {
2393 #define GETSETNAME(op, name) gr##op##_##name
2394 GET (m
, "R.m -> reduction polynomial")
2399 static const PyMethodDef gfreduce_pymethods
[] = {
2400 #define METHNAME(name) grmeth_##name
2401 METH (reduce
, "R.reduce(X) -> X mod B.m")
2402 METH (trace
, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2403 METH (halftrace
, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2404 METH (sqrt
, "R.sqrt(X) -> Y where Y^2 = X mod R")
2405 METH (quadsolve
, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2406 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
2411 static const PyTypeObject gfreduce_pytype_skel
= {
2412 PyVarObject_HEAD_INIT(0, 0) /* Header */
2413 "GFReduce", /* @tp_name@ */
2414 sizeof(gfreduce_pyobj
), /* @tp_basicsize@ */
2415 0, /* @tp_itemsize@ */
2417 gfreduce_pydealloc
, /* @tp_dealloc@ */
2419 0, /* @tp_getattr@ */
2420 0, /* @tp_setattr@ */
2421 0, /* @tp_compare@ */
2423 0, /* @tp_as_number@ */
2424 0, /* @tp_as_sequence@ */
2425 0, /* @tp_as_mapping@ */
2429 0, /* @tp_getattro@ */
2430 0, /* @tp_setattro@ */
2431 0, /* @tp_as_buffer@ */
2432 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2433 Py_TPFLAGS_BASETYPE
,
2436 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2438 0, /* @tp_traverse@ */
2440 0, /* @tp_richcompare@ */
2441 0, /* @tp_weaklistoffset@ */
2443 0, /* @tp_iternext@ */
2444 PYMETHODS(gfreduce
), /* @tp_methods@ */
2445 0, /* @tp_members@ */
2446 PYGETSET(gfreduce
), /* @tp_getset@ */
2449 0, /* @tp_descr_get@ */
2450 0, /* @tp_descr_set@ */
2451 0, /* @tp_dictoffset@ */
2453 PyType_GenericAlloc
, /* @tp_alloc@ */
2454 gfreduce_pynew
, /* @tp_new@ */
2459 /*----- Normal/poly transformation ----------------------------------------*/
2461 static PyTypeObject
*gfn_pytype
;
2463 typedef struct gfn_pyobj
{
2469 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2470 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2471 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2473 static PyObject
*gfn_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
2475 mp
*p
= 0, *beta
= 0;
2477 static const char *const kwlist
[] = { "p", "beta", 0 };
2479 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&O&:new", KWLIST
,
2480 convgf
, &p
, convgf
, &beta
))
2482 gg
= PyObject_New(gfn_pyobj
, ty
);
2484 if (gfn_create(p
, beta
, &gg
->ntop
, &gg
->pton
)) {
2487 VALERR("can't invert transformation matrix");
2493 return ((PyObject
*)gg
);
2496 static PyObject
*gfnget_p(PyObject
*me
, void *hunoz
)
2497 { return (gf_pywrap(MP_COPY(GFN_P(me
)))); }
2499 static PyObject
*gfnget_beta(PyObject
*me
, void *hunoz
)
2501 gfn
*n
= GFN_NTOP(me
);
2502 mp
*x
= n
->r
[n
->n
- 1];
2503 return (gf_pywrap(MP_COPY(x
)));
2506 #define XFORMOP(name, NAME) \
2507 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2512 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2513 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2516 if (!z) return (0); \
2517 return (gf_pywrap(z)); \
2523 static void gfn_pydealloc(PyObject
*me
)
2527 gfn_destroy(GFN_PTON(me
));
2528 gfn_destroy(GFN_NTOP(me
));
2533 static const PyGetSetDef gfn_pygetset
[] = {
2534 #define GETSETNAME(op, name) gfn##op##_##name
2535 GET (p
, "X.p -> polynomial basis, as polynomial")
2536 GET (beta
, "X.beta -> normal basis element, in poly form")
2541 static const PyMethodDef gfn_pymethods
[] = {
2542 #define METHNAME(name) gfnmeth_##name
2543 METH (pton
, "X.pton(A) -> normal-basis representation of A")
2544 METH (ntop
, "X.ntop(A) -> polynomial-basis representation of A")
2549 static const PyTypeObject gfn_pytype_skel
= {
2550 PyVarObject_HEAD_INIT(0, 0) /* Header */
2551 "GFN", /* @tp_name@ */
2552 sizeof(gfn_pyobj
), /* @tp_basicsize@ */
2553 0, /* @tp_itemsize@ */
2555 gfn_pydealloc
, /* @tp_dealloc@ */
2557 0, /* @tp_getattr@ */
2558 0, /* @tp_setattr@ */
2559 0, /* @tp_compare@ */
2561 0, /* @tp_as_number@ */
2562 0, /* @tp_as_sequence@ */
2563 0, /* @tp_as_mapping@ */
2567 0, /* @tp_getattro@ */
2568 0, /* @tp_setattro@ */
2569 0, /* @tp_as_buffer@ */
2570 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2571 Py_TPFLAGS_BASETYPE
,
2574 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2575 " between polynomial and normal basis representations.",
2577 0, /* @tp_traverse@ */
2579 0, /* @tp_richcompare@ */
2580 0, /* @tp_weaklistoffset@ */
2582 0, /* @tp_iternext@ */
2583 PYMETHODS(gfn
), /* @tp_methods@ */
2584 0, /* @tp_members@ */
2585 PYGETSET(gfn
), /* @tp_getset@ */
2588 0, /* @tp_descr_get@ */
2589 0, /* @tp_descr_set@ */
2590 0, /* @tp_dictoffset@ */
2592 PyType_GenericAlloc
, /* @tp_alloc@ */
2593 gfn_pynew
, /* @tp_new@ */
2598 /*----- Glue --------------------------------------------------------------*/
2600 static const struct nameval consts
[] = {
2605 void mp_pyinit(void)
2609 INITTYPE(mpmul
, root
);
2610 INITTYPE(mpmont
, root
);
2611 INITTYPE(mpbarrett
, root
);
2612 INITTYPE(mpreduce
, root
);
2613 INITTYPE(mpcrt
, root
);
2614 INITTYPE(gfreduce
, root
);
2615 INITTYPE(gfn
, root
);
2618 void mp_pyinsert(PyObject
*mod
)
2620 INSERT("MP", mp_pytype
);
2621 INSERT("MPMul", mpmul_pytype
);
2622 INSERT("MPMont", mpmont_pytype
);
2623 INSERT("MPBarrett", mpbarrett_pytype
);
2624 INSERT("MPReduce", mpreduce_pytype
);
2625 INSERT("MPCRT", mpcrt_pytype
);
2626 INSERT("GF", gf_pytype
);
2627 INSERT("GFReduce", gfreduce_pytype
);
2628 INSERT("GFN", gfn_pytype
);
2629 setconstants(mod
, consts
);
2632 /*----- That's all, folks -------------------------------------------------*/