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 static mp
*implicitmp(PyObject
*o
)
301 static 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, name, rname) \
397 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
401 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
402 if (mp_tolong_checked(yy, &n, 1)) goto end; \
404 z = pre##_pywrap(mp_##rname(MP_NEW, xx, -n)); \
406 z = pre##_pywrap(mp_##name(MP_NEW, xx, n)); \
408 MP_DROP(xx); MP_DROP(yy); \
411 SHIFTOP(mp
, lsl2c
, lsr2c
)
412 SHIFTOP(mp
, lsr2c
, lsl2c
)
413 SHIFTOP(gf
, lsl
, lsr
)
414 SHIFTOP(gf
, lsr
, lsl
)
417 #define DIVOP(pre, name, qq, rr, gather) \
418 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
421 INIT_##qq(q) INIT_##rr(r) \
422 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
424 ZDIVERR("division by zero"); \
425 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
428 MP_DROP(xx); MP_DROP(yy); \
431 #define INIT_YES(p) mp *p = MP_NEW;
433 #define ARG_YES(p) &p
435 DIVOP(mp
, divmod
, YES
, YES
,
436 Py_BuildValue("(NN)", mp_pywrap(q
), mp_pywrap(r
)))
437 DIVOP(mp
, div
, YES
, NO
, mp_pywrap(q
))
438 DIVOP(mp
, mod
, NO
, YES
, mp_pywrap(r
))
439 DIVOP(gf
, divmod
, YES
, YES
,
440 Py_BuildValue("(NN)", gf_pywrap(q
), gf_pywrap(r
)))
441 DIVOP(gf
, div
, YES
, NO
, gf_pywrap(q
))
442 DIVOP(gf
, mod
, NO
, YES
, gf_pywrap(r
))
449 static mp
*mp_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
452 mp_gcd(&g
, 0, &d
, p
, x
);
453 if (!MP_EQ(g
, MP_ONE
)) {
454 MP_DROP(g
); MP_DROP(d
);
455 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
458 MP_DROP(g
); return (d
);
461 static PyObject
*mp_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
463 mp
*xx
= 0, *yy
= 0, *zz
= 0;
467 if ((xx
= implicitmp(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
468 (z
&& z
!= Py_None
&& (zz
= tomp(z
)) == 0)) {
469 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
472 if (!z
|| z
== Py_None
) {
473 if (MP_NEGP(yy
)) VALERR("negative exponent");
474 r
= mp_exp(MP_NEW
, xx
, yy
);
476 if (!MP_POSP(zz
)) VALERR("modulus must be positive");
478 if ((xx
= mp_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
483 mpmont_create(&mm
, zz
);
484 r
= mpmont_exp(&mm
, MP_NEW
, xx
, yy
);
488 mpbarrett_create(&mb
, zz
);
489 r
= mpbarrett_exp(&mb
, MP_NEW
, xx
, yy
);
490 mpbarrett_destroy(&mb
);
495 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
499 static mp
*gf_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
502 gf_gcd(&g
, 0, &d
, p
, x
);
503 if (!MP_EQ(g
, MP_ONE
)) {
504 MP_DROP(g
); MP_DROP(d
);
505 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
508 MP_DROP(g
); return (d
);
511 #define BASEOP(name, radix, pre) \
512 static PyObject *mp_py##name(PyObject *x) \
513 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
517 BASEOP(hex
, 16, "0x");
520 static int mp_pynonzerop(PyObject
*x
) { return !MP_ZEROP(MP_X(x
)); }
522 static PyObject
*mp_pyint(PyObject
*x
)
525 if (!mp_tolong_checked(MP_X(x
), &l
, 0)) return (PyInt_FromLong(l
));
526 else return mp_topylong(MP_X(x
));
529 static PyObject
*mp_pylong(PyObject
*x
)
530 { return (mp_topylong(MP_X(x
))); }
532 static PyObject
*mp_pyfloat(PyObject
*x
)
534 PyObject
*l
= mp_topylong(MP_X(x
));
535 double f
= PyLong_AsDouble(l
);
537 return (PyFloat_FromDouble(f
));
541 #define COERCE(pre, PRE) \
542 static int pre##_pycoerce(PyObject **x, PyObject **y) \
546 if (PRE##_PYCHECK(*y)) { \
547 Py_INCREF(*x); Py_INCREF(*y); \
550 if ((z = tomp(*y)) != 0) { \
552 *y = pre##_pywrap(z); \
562 static PyObject
*mp_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
566 if (PyFloat_Check(y
)) {
567 l
= mp_topylong(MP_X(x
)); rc
= PyObject_RichCompare(l
, y
, op
);
568 Py_DECREF(l
); return (rc
);
570 if (mpbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
571 rc
= enrich_compare(op
, mp_cmp(xx
, yy
));
572 MP_DROP(xx
); MP_DROP(yy
);
577 static int mp_pycompare(PyObject
*x
, PyObject
*y
)
578 { return mp_cmp(MP_X(x
), MP_X(y
)); }
581 static PyObject
*mp_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
587 static const char *const kwlist
[] = { "x", "radix", 0 };
589 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:new", KWLIST
, &x
, &radix
))
591 if (MP_PYCHECK(x
)) RETURN_OBJ(x
);
592 if (!good_radix_p(radix
, 1)) VALERR("bad radix");
593 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
594 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
595 Py_TYPE(x
)->tp_name
);
598 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
601 return ((PyObject
*)zz
);
604 Py_hash_t
mphash(mp
*x
)
606 PyObject
*l
= mp_topylong(x
);
607 Py_hash_t h
= PyObject_Hash(l
);
608 Py_DECREF(l
); return (h
);
611 static Py_hash_t
mp_pyhash(PyObject
*me
) { return (mphash(MP_X(me
))); }
613 static PyObject
*mpmeth_jacobi(PyObject
*me
, PyObject
*arg
)
618 if (!PyArg_ParseTuple(arg
, "O&:jacobi", convmp
, &y
)) goto end
;
619 z
= PyInt_FromLong(mp_jacobi(y
, MP_X(me
)));
625 #define BITOP(pre, name, c) \
626 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
629 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
630 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
632 BITOP(mp
, setbit
, 2c
);
633 BITOP(mp
, clearbit
, 2c
);
635 BITOP(gf
, clearbit
, );
638 static PyObject
*mpmeth_testbit(PyObject
*me
, PyObject
*arg
)
641 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
642 return (getbool(mp_testbit2c(MP_X(me
), i
)));
645 static PyObject
*gfmeth_testbit(PyObject
*me
, PyObject
*arg
)
648 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
649 return (getbool(mp_testbit(MP_X(me
), i
)));
652 static PyObject
*mpmeth_odd(PyObject
*me
)
657 t
= mp_odd(MP_NEW
, MP_X(me
), &s
);
658 return (Py_BuildValue("(lN)", (long)s
, mp_pywrap(t
)));
661 static PyObject
*mpmeth_sqr(PyObject
*me
)
662 { return (mp_pywrap(mp_sqr(MP_NEW
, MP_X(me
)))); }
664 static PyObject
*mpmeth_sqrt(PyObject
*me
)
666 if (MP_NEGP(MP_X(me
))) VALERR("negative root");
667 return (mp_pywrap(mp_sqrt(MP_NEW
, MP_X(me
))));
672 static PyObject
*mpmeth_gcd(PyObject
*me
, PyObject
*arg
)
674 mp
*y
= 0, *zz
= MP_NEW
;
677 if (!PyArg_ParseTuple(arg
, "O&:gcd", convmp
, &y
)) goto end
;
678 mp_gcd(&zz
, 0, 0, MP_X(me
), y
);
685 static PyObject
*mpmeth_gcdx(PyObject
*me
, PyObject
*arg
)
688 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
690 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convmp
, &yy
)) goto end
;
691 mp_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
692 z
= Py_BuildValue("(NNN)",
693 mp_pywrap(zz
), mp_pywrap(uu
), mp_pywrap(vv
));
699 static PyObject
*mpmeth_modinv(PyObject
*me
, PyObject
*arg
)
702 mp
*yy
= 0, *zz
= MP_NEW
;
704 if (!PyArg_ParseTuple(arg
, "O&:modinv", convmp
, &yy
) ||
705 (zz
= mp_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
713 static PyObject
*mpmeth_tostring(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
716 static const char *const kwlist
[] = { "radix", 0 };
717 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|i:tostring", KWLIST
, &radix
))
719 if (!good_radix_p(radix
, 0)) VALERR("bad radix");
720 return (mp_topystring(MP_X(me
), radix
, 0, 0, 0));
725 static PyObject
*mpmeth_modsqrt(PyObject
*me
, PyObject
*arg
)
728 mp
*yy
= 0, *zz
= MP_NEW
;
730 if (!PyArg_ParseTuple(arg
, "O&:modsqrt", convmp
, &yy
)) goto end
;
731 if ((zz
= mp_modsqrt(MP_NEW
, yy
, MP_X(me
))) == 0)
732 VALERR("no modular square root");
739 static PyObject
*mpmeth_leastcongruent(PyObject
*me
, PyObject
*arg
)
744 if (!PyArg_ParseTuple(arg
, "O&O&:leastcongruent", convmp
, &b
, convmp
, &m
))
746 z
= mp_leastcongruent(MP_NEW
, b
, MP_X(me
), m
);
752 #define STOREOP(name, c) \
753 static PyObject *mpmeth_##name(PyObject *me, \
754 PyObject *arg, PyObject *kw) \
757 static const char *const kwlist[] = { "len", 0 }; \
760 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
764 len = mp_octets##c(MP_X(me)); \
767 rc = bytestring_pywrap(0, len); \
768 mp_##name(MP_X(me), BIN_PTR(rc), len); \
774 STOREOP(storel2c
, 2c
)
775 STOREOP(storeb2c
, 2c
)
779 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
786 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
787 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
788 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
789 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
790 bytestring_pywrapbuf(&b)); \
798 static PyObject
*mpmeth_tobuf(PyObject
*me
)
806 n
= mp_octets(x
) + 3;
807 rc
= bytestring_pywrap(0, n
);
808 buf_init(&b
, BIN_PTR(rc
), n
);
811 BIN_SETLEN(rc
, BLEN(&b
));
815 static PyObject
*mpmeth_primep(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
817 grand
*r
= &rand_global
;
818 static const char *const kwlist
[] = { "rng", 0 };
821 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|O&", KWLIST
, convgrand
, &r
))
823 rc
= getbool(pgen_primep(MP_X(me
), r
));
828 static PyObject
*mpmeth_fromstring(PyObject
*me
,
829 PyObject
*arg
, PyObject
*kw
)
837 static const char *const kwlist
[] = { "x", "radix", 0 };
839 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
842 if (!good_radix_p(r
, 1)) VALERR("bad radix");
843 sc
.buf
= p
; sc
.lim
= p
+ len
;
844 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0)
845 VALERR("bad integer");
846 z
= Py_BuildValue("(Ns#)", mp_pywrap(zz
),
847 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
852 static PyObject
*mpmeth_factorial(PyObject
*me
, PyObject
*arg
)
856 if (!PyArg_ParseTuple(arg
, "O&:factorial", convulong
, &i
)) return (0);
861 static PyObject
*mpmeth_fibonacci(PyObject
*me
, PyObject
*arg
)
865 if (!PyArg_ParseTuple(arg
, "l:fibonacci", &i
)) return (0);
870 #define LOADOP(pre, name) \
871 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
874 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
875 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
885 static PyObject
*mpget_nbits(PyObject
*me
, void *hunoz
)
886 { return (PyInt_FromLong(mp_bits(MP_X(me
)))); }
888 static PyObject
*mpget_noctets(PyObject
*me
, void *hunoz
)
889 { return (PyInt_FromLong(mp_octets(MP_X(me
)))); }
891 static PyObject
*mpget_noctets2c(PyObject
*me
, void *hunoz
)
892 { return (PyInt_FromLong(mp_octets2c(MP_X(me
)))); }
894 static const PyGetSetDef mp_pygetset
[] = {
895 #define GETSETNAME(op, func) mp##op##_##func
896 GET (nbits
, "X.nbits -> bit length of X")
897 GET (noctets
, "X.noctets -> octet length of X")
898 GET (noctets2c
, "X.noctets2c -> two's complement octet length of X")
903 static const PyMethodDef mp_pymethods
[] = {
904 #define METHNAME(func) mpmeth_##func
905 METH (jacobi
, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
906 METH (setbit
, "X.setbit(N) -> X with bit N set")
907 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
908 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
909 NAMETH(odd
, "X.odd() -> S, T where X = 2^S T with T odd")
910 NAMETH(sqr
, "X.sqr() -> X^2")
911 NAMETH(sqrt
, "X.sqrt() -> largest integer <= sqrt(X)")
912 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
913 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
914 "with X U + Y V = gcd(X, Y)")
915 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
916 METH (modsqrt
, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
917 METH (leastcongruent
, "X.leastcongruent(B, M) -> "
918 "smallest Z >= B with Z == X (mod M)")
919 KWMETH(primep
, "X.primep([rng = rand]) -> X is prime?")
920 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
921 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
922 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
923 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
924 "little-endian bytes, two's complement")
925 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
926 "big-endian bytes, two's complement")
927 NAMETH(tobuf
, "X.tobuf() -> buffer format")
928 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
929 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
930 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
931 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
932 SMTH (factorial
, "factorial(I) -> I!: compute factorial")
933 SMTH (fibonacci
, "fibonacci(I) -> F(I): compute Fibonacci number")
934 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
935 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
936 SMTH (loadl2c
, "loadl2c(STR) -> X: "
937 "read little-endian bytes, two's complement")
938 SMTH (loadb2c
, "loadb2c(STR) -> X: "
939 "read big-endian bytes, two's complement")
940 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
945 static const PyNumberMethods mp_pynumber
= {
946 mp_pyadd
, /* @nb_add@ */
947 mp_pysub
, /* @nb_subtract@ */
948 mp_pymul
, /* @nb_multiply@ */
952 mp_pymod
, /* @nb_remainder@ */
953 mp_pydivmod
, /* @nb_divmod@ */
954 mp_pyexp
, /* @nb_power@ */
955 mp_pyneg
, /* @nb_negative@ */
956 mp_pyid
, /* @nb_positive@ */
957 mp_pyabs
, /* @nb_absolute@ */
958 mp_pynonzerop
, /* @nb_nonzero@ */
959 mp_pynot2c
, /* @nb_invert@ */
960 mp_pylsl2c
, /* @nb_lshift@ */
961 mp_pylsr2c
, /* @nb_rshift@ */
962 mp_pyand2c
, /* @nb_and@ */
963 mp_pyxor2c
, /* @nb_xor@ */
964 mp_pyor2c
, /* @nb_or@ */
966 mp_pycoerce
, /* @nb_coerce@ */
968 mp_pyint
, /* @nb_int@ */
969 PY23(mp_pylong
, 0), /* @nb_long@ */
970 mp_pyfloat
, /* @nb_float@ */
972 mp_pyoct
, /* @nb_oct@ */
973 mp_pyhex
, /* @nb_hex@ */
976 0, /* @nb_inplace_add@ */
977 0, /* @nb_inplace_subtract@ */
978 0, /* @nb_inplace_multiply@ */
980 0, /* @nb_inplace_divide@ */
982 0, /* @nb_inplace_remainder@ */
983 0, /* @nb_inplace_power@ */
984 0, /* @nb_inplace_lshift@ */
985 0, /* @nb_inplace_rshift@ */
986 0, /* @nb_inplace_and@ */
987 0, /* @nb_inplace_xor@ */
988 0, /* @nb_inplace_or@ */
990 mp_pydiv
, /* @nb_floor_divide@ */
991 0, /* @nb_true_divide@ */
992 0, /* @nb_inplace_floor_divide@ */
993 0, /* @nb_inplace_true_divide@ */
995 mp_pyint
, /* @nb_index@ */
998 static const PyTypeObject mp_pytype_skel
= {
999 PyVarObject_HEAD_INIT(0, 0) /* Header */
1000 "MP", /* @tp_name@ */
1001 sizeof(mp_pyobj
), /* @tp_basicsize@ */
1002 0, /* @tp_itemsize@ */
1004 mp_pydealloc
, /* @tp_dealloc@ */
1006 0, /* @tp_getattr@ */
1007 0, /* @tp_setattr@ */
1008 PY23(mp_pycompare
, 0), /* @tp_compare@/@tp_as_async@ */
1009 mp_pyrepr
, /* @tp_repr@ */
1010 PYNUMBER(mp
), /* @tp_as_number@ */
1011 0, /* @tp_as_sequence@ */
1012 0, /* @tp_as_mapping@ */
1013 mp_pyhash
, /* @tp_hash@ */
1015 mp_pystr
, /* @tp_str@ */
1016 0, /* @tp_getattro@ */
1017 0, /* @tp_setattro@ */
1018 0, /* @tp_as_buffer@ */
1019 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1020 Py_TPFLAGS_CHECKTYPES
|
1021 Py_TPFLAGS_BASETYPE
,
1024 "Multiprecision integers, similar to `long' but more efficient and\n"
1025 "versatile. Support all the standard arithmetic operations, with\n"
1026 "implicit conversions from `PrimeFilter', and other objects which\n"
1027 "convert to `" PY23("long", "int") "'.\n"
1029 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1030 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1031 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1033 "points, group elements, Python `int' and `long' objects, and anything\n"
1034 "with an integer conversion.\n",
1035 "points, group elements, Python `int' objects, and anything with an\n"
1036 "integer conversion.\n")
1040 " * Use `//' for integer division: `/' gives exact rational division.",
1042 0, /* @tp_traverse@ */
1044 mp_pyrichcompare
, /* @tp_richcompare@ */
1045 0, /* @tp_weaklistoffset@ */
1047 0, /* @tp_iternext@ */
1048 PYMETHODS(mp
), /* @tp_methods@ */
1049 0, /* @tp_members@ */
1050 PYGETSET(mp
), /* @tp_getset@ */
1053 0, /* @tp_descr_get@ */
1054 0, /* @tp_descr_set@ */
1055 0, /* @tp_dictoffset@ */
1057 PyType_GenericAlloc
, /* @tp_alloc@ */
1058 mp_pynew
, /* @tp_new@ */
1063 /*----- Products of small integers ----------------------------------------*/
1065 static PyTypeObject
*mpmul_pytype
;
1067 typedef struct mpmul_pyobj
{
1073 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1074 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1076 static void mpmul_pydealloc(PyObject
*me
)
1078 if (MPMUL_LIVEP(me
))
1079 mp_drop(mpmul_done(MPMUL_PY(me
)));
1083 static PyObject
*mmmeth_factor(PyObject
*me
, PyObject
*arg
)
1088 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1089 if (PyTuple_GET_SIZE(arg
) != 1)
1090 i
= PyObject_GetIter(arg
);
1092 if ((q
= PyTuple_GET_ITEM(arg
, 0)) == 0) goto end
;
1093 if ((i
= PyObject_GetIter(q
)) == 0) {
1094 PyErr_Clear(); /* that's ok */
1095 i
= PyObject_GetIter(arg
);
1099 while ((q
= PyIter_Next(i
)) != 0) {
1100 x
= getmp(q
); Py_DECREF(q
); if (!x
) {
1104 mpmul_add(MPMUL_PY(me
), x
);
1113 static PyObject
*mmmeth_done(PyObject
*me
)
1117 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1118 x
= mpmul_done(MPMUL_PY(me
));
1119 MPMUL_LIVEP(me
) = 0;
1120 return (mp_pywrap(x
));
1125 static PyObject
*mpmul_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1129 if (kw
) TYERR("keyword arguments not allowed here");
1130 mm
= (mpmul_pyobj
*)ty
->tp_alloc(ty
, 0);
1131 mpmul_init(&mm
->mm
);
1133 if (mmmeth_factor((PyObject
*)mm
, arg
) == 0) {
1137 return ((PyObject
*)mm
);
1142 static PyObject
*mmget_livep(PyObject
*me
, void *hunoz
)
1143 { return (getbool(MPMUL_LIVEP(me
))); }
1145 static const PyGetSetDef mpmul_pygetset
[] = {
1146 #define GETSETNAME(op, name) mm##op##_##name
1147 GET (livep
, "MM.livep -> flag: object still valid?")
1152 static const PyMethodDef mpmul_pymethods
[] = {
1153 #define METHNAME(name) mmmeth_##name
1154 METH (factor
, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1155 NAMETH(done
, "MM.done() -> PRODUCT")
1160 static const PyTypeObject mpmul_pytype_skel
= {
1161 PyVarObject_HEAD_INIT(0, 0) /* Header */
1162 "MPMul", /* @tp_name@ */
1163 sizeof(mpmul_pyobj
), /* @tp_basicsize@ */
1164 0, /* @tp_itemsize@ */
1166 mpmul_pydealloc
, /* @tp_dealloc@ */
1168 0, /* @tp_getattr@ */
1169 0, /* @tp_setattr@ */
1170 0, /* @tp_compare@ */
1172 0, /* @tp_as_number@ */
1173 0, /* @tp_as_sequence@ */
1174 0, /* @tp_as_mapping@ */
1178 0, /* @tp_getattro@ */
1179 0, /* @tp_setattro@ */
1180 0, /* @tp_as_buffer@ */
1181 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1182 Py_TPFLAGS_BASETYPE
,
1185 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1187 0, /* @tp_traverse@ */
1189 0, /* @tp_richcompare@ */
1190 0, /* @tp_weaklistoffset@ */
1192 0, /* @tp_iternext@ */
1193 PYMETHODS(mpmul
), /* @tp_methods@ */
1194 0, /* @tp_members@ */
1195 PYGETSET(mpmul
), /* @tp_getset@ */
1198 0, /* @tp_descr_get@ */
1199 0, /* @tp_descr_set@ */
1200 0, /* @tp_dictoffset@ */
1202 PyType_GenericAlloc
, /* @tp_alloc@ */
1203 mpmul_pynew
, /* @tp_new@ */
1208 /*----- Montgomery reduction ----------------------------------------------*/
1210 static PyTypeObject
*mpmont_pytype
;
1212 typedef struct mpmont_pyobj
{
1217 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1219 static PyObject
*mmmeth_int(PyObject
*me
, PyObject
*arg
)
1223 mpmont
*mm
= MPMONT_PY(me
);
1225 if (!PyArg_ParseTuple(arg
, "O&:in", convmp
, &yy
))
1227 mp_div(0, &yy
, yy
, mm
->m
);
1228 z
= mp_pywrap(mpmont_mul(mm
, MP_NEW
, yy
, mm
->r2
));
1230 if (yy
) MP_DROP(yy
);
1234 static PyObject
*mmmeth_mul(PyObject
*me
, PyObject
*arg
)
1237 mp
*yy
= 0, *zz
= 0;
1239 if (!PyArg_ParseTuple(arg
, "O&O&:mul", convmp
, &yy
, convmp
, &zz
))
1241 rc
= mp_pywrap(mpmont_mul(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1243 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1247 static PyObject
*mmmeth_exp(PyObject
*me
, PyObject
*arg
)
1250 mp
*yy
= 0, *zz
= 0;
1252 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1255 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1256 zz
= mp_neg(zz
, zz
);
1258 rc
= mp_pywrap(mpmont_exp(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1260 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1264 static PyObject
*mmmeth_expr(PyObject
*me
, PyObject
*arg
)
1267 mp
*yy
= 0, *zz
= 0;
1269 if (!PyArg_ParseTuple(arg
, "O&O&:expr", convmp
, &yy
, convmp
, &zz
))
1272 yy
= mpmont_reduce(MPMONT_PY(me
), yy
, yy
);
1273 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1274 yy
= mpmont_mul(MPMONT_PY(me
), yy
, yy
, MPMONT_PY(me
)->r2
);
1275 zz
= mp_neg(zz
, zz
);
1277 rc
= mp_pywrap(mpmont_expr(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1279 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1283 static PyObject
*mm_mexpr_id(PyObject
*me
)
1284 { return mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
)); }
1286 static int mm_mexpr_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1288 mp
*xx
= 0, *yy
= 0;
1289 mp_expfactor
*f
= p
;
1290 mpmont
*mm
= MPMONT_PY(me
);
1292 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1295 xx
= mpmont_reduce(mm
, xx
, xx
);
1296 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1298 xx
= mpmont_mul(mm
, xx
, xx
, mm
->r2
);
1299 yy
= mp_neg(yy
, yy
);
1306 mp_drop(xx
); mp_drop(yy
);
1310 static PyObject
*mm_mexpr(PyObject
*me
, void *v
, int n
)
1311 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1313 static void mp_mexp_drop(void *p
)
1315 mp_expfactor
*f
= p
;
1320 static PyObject
*mmmeth_mexpr(PyObject
*me
, PyObject
*arg
)
1322 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1323 mm_mexpr_id
, mm_mexpr_fill
, mm_mexpr
, mp_mexp_drop
);
1326 static PyObject
*mp_mexp_id(PyObject
*me
)
1327 { return mp_pywrap(MP_ONE
); }
1329 static int mp_mexp_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1331 mp
*xx
= 0, *yy
= 0;
1332 mp_expfactor
*f
= p
;
1334 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1337 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1339 yy
= mp_neg(yy
, yy
);
1346 mp_drop(xx
); mp_drop(yy
);
1350 static PyObject
*mm_mexp(PyObject
*me
, void *v
, int n
)
1351 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1353 static PyObject
*mmmeth_mexp(PyObject
*me
, PyObject
*arg
)
1355 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1356 mp_mexp_id
, mp_mexp_fill
, mm_mexp
, mp_mexp_drop
);
1359 #define mmmeth_ext mmmeth_reduce
1360 static PyObject
*mmmeth_reduce(PyObject
*me
, PyObject
*arg
)
1365 if (!PyArg_ParseTuple(arg
, "O&", convmp
, &yy
)) goto end
;
1366 z
= mp_pywrap(mpmont_reduce(MPMONT_PY(me
), MP_NEW
, yy
));
1371 static void mpmont_pydealloc(PyObject
*me
)
1373 mpmont_destroy(MPMONT_PY(me
));
1377 static PyObject
*mpmont_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1379 mpmont_pyobj
*mm
= 0;
1380 static const char *const kwlist
[] = { "m", 0 };
1383 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1385 if (!MP_POSP(xx
) || !MP_ODDP(xx
)) VALERR("m must be positive and odd");
1386 mm
= (mpmont_pyobj
*)ty
->tp_alloc(ty
, 0);
1387 mpmont_create(&mm
->mm
, xx
);
1389 if (xx
) MP_DROP(xx
);
1390 return ((PyObject
*)mm
);
1393 static PyObject
*mmget_m(PyObject
*me
, void *hunoz
)
1394 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->m
))); }
1396 static PyObject
*mmget_r(PyObject
*me
, void *hunoz
)
1397 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
))); }
1399 static PyObject
*mmget_r2(PyObject
*me
, void *hunoz
)
1400 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r2
))); }
1402 static const PyGetSetDef mpmont_pygetset
[] = {
1403 #define GETSETNAME(op, name) mm##op##_##name
1404 GET (m
, "M.m -> modulus for reduction")
1405 GET (r
, "M.r -> multiplicative identity")
1406 GET (r2
, "M.r2 -> M.r^2, Montgomerization factor")
1411 static const PyMethodDef mpmont_pymethods
[] = {
1412 #define METHNAME(name) mmmeth_##name
1413 METH (int, "M.int(X) -> XR")
1414 METH (mul
, "M.mul(XR, YR) -> ZR where Z = X Y")
1415 METH (expr
, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1416 METH (mexpr
, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1417 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1418 "\t(the list may be flattened if this more convenient.)")
1419 METH (reduce
, "M.reduce(XR) -> X")
1420 METH (ext
, "M.ext(XR) -> X")
1421 METH (exp
, "M.exp(X, N) -> X^N mod M.m")
1422 METH (mexp
, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1423 "X0^N0 X1^N1 ... mod M.m\n"
1424 "\t(the list may be flattened if this more convenient.)")
1429 static const PyTypeObject mpmont_pytype_skel
= {
1430 PyVarObject_HEAD_INIT(0, 0) /* Header */
1431 "MPMont", /* @tp_name@ */
1432 sizeof(mpmont_pyobj
), /* @tp_basicsize@ */
1433 0, /* @tp_itemsize@ */
1435 mpmont_pydealloc
, /* @tp_dealloc@ */
1437 0, /* @tp_getattr@ */
1438 0, /* @tp_setattr@ */
1439 0, /* @tp_compare@ */
1441 0, /* @tp_as_number@ */
1442 0, /* @tp_as_sequence@ */
1443 0, /* @tp_as_mapping@ */
1447 0, /* @tp_getattro@ */
1448 0, /* @tp_setattro@ */
1449 0, /* @tp_as_buffer@ */
1450 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1451 Py_TPFLAGS_BASETYPE
,
1454 "MPMont(N): a Montgomery reduction context.",
1456 0, /* @tp_traverse@ */
1458 0, /* @tp_richcompare@ */
1459 0, /* @tp_weaklistoffset@ */
1461 0, /* @tp_iternext@ */
1462 PYMETHODS(mpmont
), /* @tp_methods@ */
1463 0, /* @tp_members@ */
1464 PYGETSET(mpmont
), /* @tp_getset@ */
1467 0, /* @tp_descr_get@ */
1468 0, /* @tp_descr_set@ */
1469 0, /* @tp_dictoffset@ */
1471 PyType_GenericAlloc
, /* @tp_alloc@ */
1472 mpmont_pynew
, /* @tp_new@ */
1477 /*----- Barrett reduction -------------------------------------------------*/
1479 static PyTypeObject
*mpbarrett_pytype
;
1481 typedef struct mpbarrett_pyobj
{
1486 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1488 static PyObject
*mbmeth_exp(PyObject
*me
, PyObject
*arg
)
1491 mp
*yy
= 0, *zz
= 0;
1493 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1496 if ((yy
= mp_modinv_checked(yy
, yy
, MPBARRETT_PY(me
)->m
)) == 0) goto end
;
1497 zz
= mp_neg(zz
, zz
);
1499 rc
= mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me
), MP_NEW
, yy
, zz
));
1501 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1505 static PyObject
*mb_mexp(PyObject
*me
, void *v
, int n
)
1506 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me
), MP_NEW
, v
, n
)); }
1508 static PyObject
*mbmeth_mexp(PyObject
*me
, PyObject
*arg
)
1510 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1511 mp_mexp_id
, mp_mexp_fill
, mb_mexp
, mp_mexp_drop
);
1514 static PyObject
*mbmeth_reduce(PyObject
*me
, PyObject
*arg
)
1519 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
))
1521 z
= mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me
), MP_NEW
, yy
));
1526 static void mpbarrett_pydealloc(PyObject
*me
)
1528 mpbarrett_destroy(MPBARRETT_PY(me
));
1532 static PyObject
*mpbarrett_pynew(PyTypeObject
*ty
,
1533 PyObject
*arg
, PyObject
*kw
)
1535 mpbarrett_pyobj
*mb
= 0;
1536 static const char *const kwlist
[] = { "m", 0 };
1539 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1541 if (!MP_POSP(xx
)) VALERR("m must be positive");
1542 mb
= (mpbarrett_pyobj
*)ty
->tp_alloc(ty
, 0);
1543 mpbarrett_create(&mb
->mb
, xx
);
1545 if (xx
) MP_DROP(xx
);
1546 return ((PyObject
*)mb
);
1549 static PyObject
*mbget_m(PyObject
*me
, void *hunoz
)
1550 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me
)->m
))); }
1552 static const PyGetSetDef mpbarrett_pygetset
[] = {
1553 #define GETSETNAME(op, name) mb##op##_##name
1554 GET (m
, "B.m -> modulus for reduction")
1559 static const PyMethodDef mpbarrett_pymethods
[] = {
1560 #define METHNAME(name) mbmeth_##name
1561 METH (reduce
, "B.reduce(X) -> X mod B.m")
1562 METH (exp
, "B.exp(X, N) -> X^N mod B.m")
1563 METH (mexp
, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1564 "X0^N0 X1^N1 ... mod B.m\n"
1565 "\t(the list may be flattened if this more convenient.)")
1570 static const PyTypeObject mpbarrett_pytype_skel
= {
1571 PyVarObject_HEAD_INIT(0, 0) /* Header */
1572 "MPBarrett", /* @tp_name@ */
1573 sizeof(mpbarrett_pyobj
), /* @tp_basicsize@ */
1574 0, /* @tp_itemsize@ */
1576 mpbarrett_pydealloc
, /* @tp_dealloc@ */
1578 0, /* @tp_getattr@ */
1579 0, /* @tp_setattr@ */
1580 0, /* @tp_compare@ */
1582 0, /* @tp_as_number@ */
1583 0, /* @tp_as_sequence@ */
1584 0, /* @tp_as_mapping@ */
1588 0, /* @tp_getattro@ */
1589 0, /* @tp_setattro@ */
1590 0, /* @tp_as_buffer@ */
1591 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1592 Py_TPFLAGS_BASETYPE
,
1595 "MPBarrett(N): a Barrett reduction context.",
1597 0, /* @tp_traverse@ */
1599 0, /* @tp_richcompare@ */
1600 0, /* @tp_weaklistoffset@ */
1602 0, /* @tp_iternext@ */
1603 PYMETHODS(mpbarrett
), /* @tp_methods@ */
1604 0, /* @tp_members@ */
1605 PYGETSET(mpbarrett
), /* @tp_getset@ */
1608 0, /* @tp_descr_get@ */
1609 0, /* @tp_descr_set@ */
1610 0, /* @tp_dictoffset@ */
1612 PyType_GenericAlloc
, /* @tp_alloc@ */
1613 mpbarrett_pynew
, /* @tp_new@ */
1618 /*----- Nice prime reduction ----------------------------------------------*/
1620 static PyTypeObject
*mpreduce_pytype
;
1622 typedef struct mpreduce_pyobj
{
1627 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1629 static PyObject
*mrmeth_exp(PyObject
*me
, PyObject
*arg
)
1632 mp
*yy
= 0, *zz
= 0;
1634 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1637 if ((yy
= mp_modinv_checked(yy
, yy
, MPREDUCE_PY(me
)->p
)) == 0) goto end
;
1638 zz
= mp_neg(zz
, zz
);
1640 rc
= mp_pywrap(mpreduce_exp(MPREDUCE_PY(me
), MP_NEW
, yy
, zz
));
1642 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1646 static PyObject
*mrmeth_reduce(PyObject
*me
, PyObject
*arg
)
1651 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
)) goto end
;
1652 z
= mp_pywrap(mpreduce_do(MPREDUCE_PY(me
), MP_NEW
, yy
));
1657 static void mpreduce_pydealloc(PyObject
*me
)
1659 mpreduce_destroy(MPREDUCE_PY(me
));
1663 static PyObject
*mpreduce_pynew(PyTypeObject
*ty
,
1664 PyObject
*arg
, PyObject
*kw
)
1666 mpreduce_pyobj
*mr
= 0;
1668 static const char *const kwlist
[] = { "m", 0 };
1671 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1673 if (!MP_POSP(xx
)) VALERR("m must be positive");
1674 if (mpreduce_create(&r
, xx
)) VALERR("bad modulus (must be 2^k - ...)");
1675 mr
= (mpreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
1678 if (xx
) MP_DROP(xx
);
1679 return ((PyObject
*)mr
);
1682 static PyObject
*mrget_m(PyObject
*me
, void *hunoz
)
1683 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me
)->p
))); }
1685 static const PyGetSetDef mpreduce_pygetset
[] = {
1686 #define GETSETNAME(op, name) mr##op##_##name
1687 GET (m
, "R.m -> modulus for reduction")
1692 static const const PyMethodDef mpreduce_pymethods
[] = {
1693 #define METHNAME(name) mrmeth_##name
1694 METH (reduce
, "R.reduce(X) -> X mod B.m")
1695 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
1700 static const PyTypeObject mpreduce_pytype_skel
= {
1701 PyVarObject_HEAD_INIT(0, 0) /* Header */
1702 "MPReduce", /* @tp_name@ */
1703 sizeof(mpreduce_pyobj
), /* @tp_basicsize@ */
1704 0, /* @tp_itemsize@ */
1706 mpreduce_pydealloc
, /* @tp_dealloc@ */
1708 0, /* @tp_getattr@ */
1709 0, /* @tp_setattr@ */
1710 0, /* @tp_compare@ */
1712 0, /* @tp_as_number@ */
1713 0, /* @tp_as_sequence@ */
1714 0, /* @tp_as_mapping@ */
1718 0, /* @tp_getattro@ */
1719 0, /* @tp_setattro@ */
1720 0, /* @tp_as_buffer@ */
1721 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1722 Py_TPFLAGS_BASETYPE
,
1725 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1727 0, /* @tp_traverse@ */
1729 0, /* @tp_richcompare@ */
1730 0, /* @tp_weaklistoffset@ */
1732 0, /* @tp_iternext@ */
1733 PYMETHODS(mpreduce
), /* @tp_methods@ */
1734 0, /* @tp_members@ */
1735 PYGETSET(mpreduce
), /* @tp_getset@ */
1738 0, /* @tp_descr_get@ */
1739 0, /* @tp_descr_set@ */
1740 0, /* @tp_dictoffset@ */
1742 PyType_GenericAlloc
, /* @tp_alloc@ */
1743 mpreduce_pynew
, /* @tp_new@ */
1748 /*----- Chinese Remainder Theorem solution --------------------------------*/
1750 static PyTypeObject
*mpcrt_pytype
;
1752 typedef struct mpcrt_pyobj
{
1757 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1759 static PyObject
*mcmeth_solve(PyObject
*me
, PyObject
*arg
)
1761 mpcrt
*c
= MPCRT_PY(me
);
1762 PyObject
*q
= 0, *x
, *z
= 0;
1765 Py_ssize_t i
= 0, n
= c
->k
;
1768 if (PyTuple_GET_SIZE(arg
) == n
)
1770 else if (!PyArg_ParseTuple(arg
, "O:solve", &q
))
1773 if (!PySequence_Check(q
)) TYERR("want a sequence of residues");
1774 i
= PySequence_Size(q
); if (i
< 0) goto end
;
1775 if (i
!= n
) VALERR("residue count mismatch");
1776 v
= xmalloc(n
* sizeof(*v
));
1777 for (i
= 0; i
< n
; i
++) {
1778 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1779 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1782 z
= mp_pywrap(mpcrt_solve(c
, MP_NEW
, v
));
1786 for (i
= 0; i
< n
; i
++)
1795 static void mpcrt_pydealloc(PyObject
*me
)
1797 mpcrt
*c
= MPCRT_PY(me
);
1802 static PyObject
*mpcrt_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1805 Py_ssize_t n
, i
= 0, j
;
1806 static const char *const kwlist
[] = { "mv", 0 };
1807 PyObject
*q
= 0, *x
;
1808 mp
*xx
= MP_NEW
, *y
= MP_NEW
, *g
= MP_NEW
;
1812 if (PyTuple_GET_SIZE(arg
) > 1)
1814 else if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O:new", KWLIST
, &q
))
1817 if (!PySequence_Check(q
)) TYERR("want a sequence of moduli");
1818 n
= PySequence_Size(q
); if (n
< 0) goto end
;
1819 if (!n
) VALERR("want at least one modulus");
1820 v
= xmalloc(n
* sizeof(*v
));
1821 for (i
= 0; i
< n
; i
++) {
1822 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1823 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1824 if (MP_CMP(xx
, <=, MP_ZERO
)) VALERR("moduli must be positive");
1825 v
[i
].m
= xx
; v
[i
].n
= 0; v
[i
].ni
= 0; v
[i
].nni
= 0; xx
= MP_NEW
;
1828 for (j
= 0; j
< i
; j
++) mpmul_add(&mm
, v
[j
].m
);
1829 xx
= mpmul_done(&mm
);
1830 for (j
= 0; j
< i
; j
++) {
1831 mp_div(&y
, 0, xx
, v
[j
].m
);
1832 mp_gcd(&g
, 0, 0, y
, v
[j
].m
);
1833 if (!MP_EQ(g
, MP_ONE
)) VALERR("moduli must be pairwise coprime");
1836 c
= (mpcrt_pyobj
*)ty
->tp_alloc(ty
, 0);
1837 mpcrt_create(&c
->c
, v
, n
, 0);
1839 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1840 return ((PyObject
*)c
);
1845 for (i
= 0; i
< n
; i
++)
1850 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1854 static PyObject
*mcget_product(PyObject
*me
, void *hunoz
)
1855 { return (mp_pywrap(MP_COPY(MPCRT_PY(me
)->mb
.m
))); }
1857 static PyObject
*mcget_moduli(PyObject
*me
, void *hunoz
)
1861 mpcrt
*c
= MPCRT_PY(me
);
1863 if ((q
= PyList_New(c
->k
)) == 0) return (0);
1864 for (i
= 0; i
< c
->k
; i
++)
1865 PyList_SET_ITEM(q
, i
, mp_pywrap(c
->v
[i
].m
));
1869 static const PyGetSetDef mpcrt_pygetset
[] = {
1870 #define GETSETNAME(op, name) mc##op##_##name
1871 GET (product
, "C.product -> product of moduli")
1872 GET (moduli
, "C.moduli -> list of individual moduli")
1877 static const PyMethodDef mpcrt_pymethods
[] = {
1878 #define METHNAME(name) mcmeth_##name
1879 METH (solve
, "C.solve([R0, R1]) -> X mod C.product")
1884 static const PyTypeObject mpcrt_pytype_skel
= {
1885 PyVarObject_HEAD_INIT(0, 0) /* Header */
1886 "MPCRT", /* @tp_name@ */
1887 sizeof(mpcrt_pyobj
), /* @tp_basicsize@ */
1888 0, /* @tp_itemsize@ */
1890 mpcrt_pydealloc
, /* @tp_dealloc@ */
1892 0, /* @tp_getattr@ */
1893 0, /* @tp_setattr@ */
1894 0, /* @tp_compare@ */
1896 0, /* @tp_as_number@ */
1897 0, /* @tp_as_sequence@ */
1898 0, /* @tp_as_mapping@ */
1902 0, /* @tp_getattro@ */
1903 0, /* @tp_setattro@ */
1904 0, /* @tp_as_buffer@ */
1905 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1906 Py_TPFLAGS_BASETYPE
,
1909 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1911 0, /* @tp_traverse@ */
1913 0, /* @tp_richcompare@ */
1914 0, /* @tp_weaklistoffset@ */
1916 0, /* @tp_iternext@ */
1917 PYMETHODS(mpcrt
), /* @tp_methods@ */
1918 0, /* @tp_members@ */
1919 PYGETSET(mpcrt
), /* @tp_getset@ */
1922 0, /* @tp_descr_get@ */
1923 0, /* @tp_descr_set@ */
1924 0, /* @tp_dictoffset@ */
1926 PyType_GenericAlloc
, /* @tp_alloc@ */
1927 mpcrt_pynew
, /* @tp_new@ */
1932 /*----- Binary polynomials ------------------------------------------------*/
1934 static PyObject
*gf_pyrepr(PyObject
*o
)
1935 { return mp_topystring(MP_X(o
), 16, "GF(", "0x", ")"); }
1937 static PyObject
*gf_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
1943 if (gfbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
1945 case Py_EQ
: b
= MP_EQ(xx
, yy
); break;
1946 case Py_NE
: b
= !MP_EQ(xx
, yy
); break;
1951 case Py_LT
: b
= xl
< yl
; break;
1952 case Py_LE
: b
= xl
<= yl
; break;
1953 case Py_GT
: b
= xl
> yl
; break;
1954 case Py_GE
: b
= xl
>= yl
; break;
1959 MP_DROP(xx
); MP_DROP(yy
);
1960 return (getbool(b
));
1963 static PyObject
*gf_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1969 static const char *const kwlist
[] = { "x", "radix", 0 };
1971 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:gf", KWLIST
, &x
, &radix
))
1973 if (GF_PYCHECK(x
)) RETURN_OBJ(x
);
1974 if (!good_radix_p(radix
, 1)) VALERR("radix out of range");
1975 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
1976 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
1977 Py_TYPE(x
)->tp_name
);
1982 VALERR("gf cannot be negative");
1984 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
1987 return ((PyObject
*)zz
);
1990 static PyObject
*gf_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
1992 mp
*xx
= 0, *yy
= 0, *zz
= 0;
1996 if ((xx
= tomp(x
)) == 0 || (yy
= tomp(y
)) == 0 ||
1997 (z
&& z
!= Py_None
&& (zz
= tomp(z
)) == 0)) {
1998 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2001 if (!z
|| z
== Py_None
) {
2002 if (MP_NEGP(yy
)) VALERR("negative exponent");
2003 r
= gf_exp(MP_NEW
, xx
, yy
);
2006 if (MP_ZEROP(zz
)) ZDIVERR("zero modulus");
2008 if ((xx
= gf_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
2009 yy
= mp_neg(yy
, yy
);
2011 gfreduce_create(&gr
, zz
);
2012 r
= gfreduce_exp(&gr
, MP_NEW
, xx
, yy
);
2013 gfreduce_destroy(&gr
);
2017 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2021 static PyObject
*gfmeth_sqr(PyObject
*me
)
2022 { return (gf_pywrap(gf_sqr(MP_NEW
, MP_X(me
)))); }
2024 static PyObject
*gfmeth_gcd(PyObject
*me
, PyObject
*arg
)
2027 mp
*yy
= 0, *zz
= MP_NEW
;
2029 if (!PyArg_ParseTuple(arg
, "O&:gcd", convgf
, &yy
)) goto end
;
2030 gf_gcd(&zz
, 0, 0, MP_X(me
), yy
);
2033 if (yy
) MP_DROP(yy
);
2037 static PyObject
*gfmeth_gcdx(PyObject
*me
, PyObject
*arg
)
2040 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
2042 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convgf
, &yy
))
2044 gf_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
2045 z
= Py_BuildValue("(NNN)",
2046 gf_pywrap(zz
), gf_pywrap(uu
), gf_pywrap(vv
));
2048 if (yy
) MP_DROP(yy
);
2052 static PyObject
*gfmeth_modinv(PyObject
*me
, PyObject
*arg
)
2055 mp
*yy
= 0, *zz
= MP_NEW
;
2057 if (!PyArg_ParseTuple(arg
, "O&:modinv", convgf
, &yy
) ||
2058 (zz
= gf_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
2062 if (yy
) MP_DROP(yy
);
2066 static PyObject
*gfmeth_fromstring(PyObject
*me
,
2067 PyObject
*arg
, PyObject
*kw
)
2074 mptext_stringctx sc
;
2075 static const char *const kwlist
[] = { "x", "radix", 0 };
2077 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
2080 if (!good_radix_p(r
, 1)) VALERR("bad radix");
2081 sc
.buf
= p
; sc
.lim
= p
+ len
;
2082 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0 ||
2084 if (zz
) MP_DROP(zz
);
2085 VALERR("bad binary polynomial");
2087 z
= Py_BuildValue("(Ns#)", gf_pywrap(zz
),
2088 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
2093 static PyObject
*gfmeth_irreduciblep(PyObject
*me
)
2094 { return getbool(gf_irreduciblep(MP_X(me
))); }
2096 static PyObject
*gfget_degree(PyObject
*me
, void *hunoz
)
2097 { return (PyInt_FromLong(mp_bits(MP_X(me
)) - 1)); }
2099 static const PyGetSetDef gf_pygetset
[] = {
2100 #define GETSETNAME(op, name) gf##op##_##name
2101 GET (degree
, "X.degree -> polynomial degree of X")
2103 #define GETSETNAME(op, name) mp##op##_##name
2104 GET (nbits
, "X.nbits -> bit length of X")
2105 GET (noctets
, "X.noctets -> octet length of X")
2110 static const PyMethodDef gf_pymethods
[] = {
2111 #define METHNAME(func) gfmeth_##func
2112 METH (setbit
, "X.setbit(N) -> X with bit N set")
2113 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
2114 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
2115 NAMETH(sqr
, "X.sqr() -> X^2")
2116 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
2117 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2118 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2119 NAMETH(irreduciblep
, "X.irreduciblep() -> true/false")
2120 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2121 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2122 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2123 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2124 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
2125 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
2126 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
2128 #define METHNAME(func) mpmeth_##func
2129 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
2130 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
2131 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
2132 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
2133 "little-endian bytes, two's complement")
2134 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
2135 "big-endian bytes, two's complement")
2136 NAMETH(tobuf
, "X.tobuf() -> buffer format")
2141 static const PyNumberMethods gf_pynumber
= {
2142 gf_pyadd
, /* @nb_add@ */
2143 gf_pysub
, /* @nb_subtract@ */
2144 gf_pymul
, /* @nb_multiply@ */
2146 0, /* @nb_divide@ */
2148 gf_pymod
, /* @nb_remainder@ */
2149 gf_pydivmod
, /* @nb_divmod@ */
2150 gf_pyexp
, /* @nb_power@ */
2151 mp_pyid
, /* @nb_negative@ */
2152 mp_pyid
, /* @nb_positive@ */
2153 mp_pyid
, /* @nb_absolute@ */
2154 mp_pynonzerop
, /* @nb_nonzero@ */
2155 0 /* doesn't make any sense */, /* @nb_invert@ */
2156 gf_pylsl
, /* @nb_lshift@ */
2157 gf_pylsr
, /* @nb_rshift@ */
2158 gf_pyand
, /* @nb_and@ */
2159 gf_pyxor
, /* @nb_xor@ */
2160 gf_pyor
, /* @nb_or@ */
2162 gf_pycoerce
, /* @nb_coerce@ */
2164 mp_pyint
, /* @nb_int@ */
2165 PY23(mp_pylong
, 0), /* @nb_long@ */
2166 0 /* doesn't make any sense */, /* @nb_float@ */
2168 mp_pyoct
, /* @nb_oct@ */
2169 mp_pyhex
, /* @nb_hex@ */
2172 0, /* @nb_inplace_add@ */
2173 0, /* @nb_inplace_subtract@ */
2174 0, /* @nb_inplace_multiply@ */
2176 0, /* @nb_inplace_divide@ */
2178 0, /* @nb_inplace_remainder@ */
2179 0, /* @nb_inplace_power@ */
2180 0, /* @nb_inplace_lshift@ */
2181 0, /* @nb_inplace_rshift@ */
2182 0, /* @nb_inplace_and@ */
2183 0, /* @nb_inplace_xor@ */
2184 0, /* @nb_inplace_or@ */
2186 gf_pydiv
, /* @nb_floor_divide@ */
2187 0, /* @nb_true_divide@ */
2188 0, /* @nb_inplace_floor_divide@ */
2189 0, /* @nb_inplace_true_divide@ */
2191 mp_pyint
, /* @nb_index@ */
2194 static const PyTypeObject gf_pytype_skel
= {
2195 PyVarObject_HEAD_INIT(0, 0) /* Header */
2196 "GF", /* @tp_name@ */
2197 sizeof(mp_pyobj
), /* @tp_basicsize@ */
2198 0, /* @tp_itemsize@ */
2200 mp_pydealloc
, /* @tp_dealloc@ */
2202 0, /* @tp_getattr@ */
2203 0, /* @tp_setattr@ */
2204 0, /* @tp_compare@ */
2205 gf_pyrepr
, /* @tp_repr@ */
2206 PYNUMBER(gf
), /* @tp_as_number@ */
2207 0, /* @tp_as_sequence@ */
2208 0, /* @tp_as_mapping@ */
2209 mp_pyhash
, /* @tp_hash@ */
2211 mp_pyhex
, /* @tp_str@ */
2212 0, /* @tp_getattro@ */
2213 0, /* @tp_setattro@ */
2214 0, /* @tp_as_buffer@ */
2215 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2216 Py_TPFLAGS_CHECKTYPES
|
2217 Py_TPFLAGS_BASETYPE
,
2220 "Binary polynomials. Support almost all the standard arithmetic\n"
2223 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2224 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2225 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2227 "points, group elements, Python `int' and `long' objects, and anything\n"
2228 "with an integer conversion.\n",
2229 "points, group elements, Python `int' objects, and anything with an\n"
2230 "integer conversion.\n")
2232 "The name is hopelessly wrong from a technical point of view, but\n"
2233 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2237 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2239 0, /* @tp_traverse@ */
2241 gf_pyrichcompare
, /* @tp_richcompare@ */
2242 0, /* @tp_weaklistoffset@ */
2244 0, /* @tp_iternext@ */
2245 PYMETHODS(gf
), /* @tp_methods@ */
2246 0, /* @tp_members@ */
2247 PYGETSET(gf
), /* @tp_getset@ */
2250 0, /* @tp_descr_get@ */
2251 0, /* @tp_descr_set@ */
2252 0, /* @tp_dictoffset@ */
2254 PyType_GenericAlloc
, /* @tp_alloc@ */
2255 gf_pynew
, /* @tp_new@ */
2260 /*----- Sparse poly reduction ---------------------------------------------*/
2262 static PyTypeObject
*gfreduce_pytype
;
2264 typedef struct gfreduce_pyobj
{
2269 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2271 static PyObject
*grmeth_exp(PyObject
*me
, PyObject
*arg
)
2274 mp
*yy
= 0, *zz
= 0;
2276 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convgf
, &yy
, convgf
, &zz
))
2279 if ((yy
= gf_modinv_checked(yy
, yy
, GFREDUCE_PY(me
)->p
)) == 0) goto end
;
2280 zz
= mp_neg(zz
, zz
);
2282 rc
= gf_pywrap(gfreduce_exp(GFREDUCE_PY(me
), MP_NEW
, yy
, zz
));
2284 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
2288 static PyObject
*grmeth_trace(PyObject
*me
, PyObject
*arg
)
2293 if (!PyArg_ParseTuple(arg
, "O&:trace", convgf
, &xx
)) goto end
;
2294 rc
= PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me
), xx
));
2296 if (xx
) MP_DROP(xx
);
2300 static PyObject
*grmeth_halftrace(PyObject
*me
, PyObject
*arg
)
2305 if (!PyArg_ParseTuple(arg
, "O&:halftrace", convgf
, &xx
)) goto end
;
2306 rc
= gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me
), MP_NEW
, xx
));
2308 if (xx
) MP_DROP(xx
);
2312 static PyObject
*grmeth_sqrt(PyObject
*me
, PyObject
*arg
)
2317 if (!PyArg_ParseTuple(arg
, "O&:sqrt", convgf
, &xx
)) goto end
;
2318 if ((yy
= gfreduce_sqrt(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2319 VALERR("no modular square root");
2322 if (xx
) MP_DROP(xx
);
2326 static PyObject
*grmeth_quadsolve(PyObject
*me
, PyObject
*arg
)
2331 if (!PyArg_ParseTuple(arg
, "O&:quadsolve", convgf
, &xx
)) goto end
;
2332 if ((yy
= gfreduce_quadsolve(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2333 VALERR("no solution found");
2336 if (xx
) MP_DROP(xx
);
2340 static PyObject
*grmeth_reduce(PyObject
*me
, PyObject
*arg
)
2345 if (!PyArg_ParseTuple(arg
, "O&:reduce", convgf
, &yy
)) goto end
;
2346 z
= gf_pywrap(gfreduce_do(GFREDUCE_PY(me
), MP_NEW
, yy
));
2351 static void gfreduce_pydealloc(PyObject
*me
)
2353 gfreduce_destroy(GFREDUCE_PY(me
));
2357 static PyObject
*gfreduce_pynew(PyTypeObject
*ty
,
2358 PyObject
*arg
, PyObject
*kw
)
2360 gfreduce_pyobj
*mr
= 0;
2362 static const char *const kwlist
[] = { "m", 0 };
2365 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convgf
, &xx
))
2367 if (MP_ZEROP(xx
)) ZDIVERR("modulus is zero!");
2368 gfreduce_create(&r
, xx
);
2369 mr
= (gfreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
2372 if (xx
) MP_DROP(xx
);
2373 return ((PyObject
*)mr
);
2376 static PyObject
*grget_m(PyObject
*me
, void *hunoz
)
2377 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me
)->p
))); }
2379 static const PyGetSetDef gfreduce_pygetset
[] = {
2380 #define GETSETNAME(op, name) gr##op##_##name
2381 GET (m
, "R.m -> reduction polynomial")
2386 static const PyMethodDef gfreduce_pymethods
[] = {
2387 #define METHNAME(name) grmeth_##name
2388 METH (reduce
, "R.reduce(X) -> X mod B.m")
2389 METH (trace
, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2390 METH (halftrace
, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2391 METH (sqrt
, "R.sqrt(X) -> Y where Y^2 = X mod R")
2392 METH (quadsolve
, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2393 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
2398 static const PyTypeObject gfreduce_pytype_skel
= {
2399 PyVarObject_HEAD_INIT(0, 0) /* Header */
2400 "GFReduce", /* @tp_name@ */
2401 sizeof(gfreduce_pyobj
), /* @tp_basicsize@ */
2402 0, /* @tp_itemsize@ */
2404 gfreduce_pydealloc
, /* @tp_dealloc@ */
2406 0, /* @tp_getattr@ */
2407 0, /* @tp_setattr@ */
2408 0, /* @tp_compare@ */
2410 0, /* @tp_as_number@ */
2411 0, /* @tp_as_sequence@ */
2412 0, /* @tp_as_mapping@ */
2416 0, /* @tp_getattro@ */
2417 0, /* @tp_setattro@ */
2418 0, /* @tp_as_buffer@ */
2419 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2420 Py_TPFLAGS_BASETYPE
,
2423 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2425 0, /* @tp_traverse@ */
2427 0, /* @tp_richcompare@ */
2428 0, /* @tp_weaklistoffset@ */
2430 0, /* @tp_iternext@ */
2431 PYMETHODS(gfreduce
), /* @tp_methods@ */
2432 0, /* @tp_members@ */
2433 PYGETSET(gfreduce
), /* @tp_getset@ */
2436 0, /* @tp_descr_get@ */
2437 0, /* @tp_descr_set@ */
2438 0, /* @tp_dictoffset@ */
2440 PyType_GenericAlloc
, /* @tp_alloc@ */
2441 gfreduce_pynew
, /* @tp_new@ */
2446 /*----- Normal/poly transformation ----------------------------------------*/
2448 static PyTypeObject
*gfn_pytype
;
2450 typedef struct gfn_pyobj
{
2456 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2457 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2458 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2460 static PyObject
*gfn_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
2462 mp
*p
= 0, *beta
= 0;
2464 static const char *const kwlist
[] = { "p", "beta", 0 };
2466 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&O&:new", KWLIST
,
2467 convgf
, &p
, convgf
, &beta
))
2469 gg
= PyObject_New(gfn_pyobj
, ty
);
2471 if (gfn_create(p
, beta
, &gg
->ntop
, &gg
->pton
)) {
2474 VALERR("can't invert transformation matrix");
2480 return ((PyObject
*)gg
);
2483 static PyObject
*gfnget_p(PyObject
*me
, void *hunoz
)
2484 { return (gf_pywrap(MP_COPY(GFN_P(me
)))); }
2486 static PyObject
*gfnget_beta(PyObject
*me
, void *hunoz
)
2488 gfn
*n
= GFN_NTOP(me
);
2489 mp
*x
= n
->r
[n
->n
- 1];
2490 return (gf_pywrap(MP_COPY(x
)));
2493 #define XFORMOP(name, NAME) \
2494 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2499 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2500 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2503 if (!z) return (0); \
2504 return (gf_pywrap(z)); \
2510 static void gfn_pydealloc(PyObject
*me
)
2514 gfn_destroy(GFN_PTON(me
));
2515 gfn_destroy(GFN_NTOP(me
));
2520 static const PyGetSetDef gfn_pygetset
[] = {
2521 #define GETSETNAME(op, name) gfn##op##_##name
2522 GET (p
, "X.p -> polynomial basis, as polynomial")
2523 GET (beta
, "X.beta -> normal basis element, in poly form")
2528 static const PyMethodDef gfn_pymethods
[] = {
2529 #define METHNAME(name) gfnmeth_##name
2530 METH (pton
, "X.pton(A) -> normal-basis representation of A")
2531 METH (ntop
, "X.ntop(A) -> polynomial-basis representation of A")
2536 static const PyTypeObject gfn_pytype_skel
= {
2537 PyVarObject_HEAD_INIT(0, 0) /* Header */
2538 "GFN", /* @tp_name@ */
2539 sizeof(gfn_pyobj
), /* @tp_basicsize@ */
2540 0, /* @tp_itemsize@ */
2542 gfn_pydealloc
, /* @tp_dealloc@ */
2544 0, /* @tp_getattr@ */
2545 0, /* @tp_setattr@ */
2546 0, /* @tp_compare@ */
2548 0, /* @tp_as_number@ */
2549 0, /* @tp_as_sequence@ */
2550 0, /* @tp_as_mapping@ */
2554 0, /* @tp_getattro@ */
2555 0, /* @tp_setattro@ */
2556 0, /* @tp_as_buffer@ */
2557 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2558 Py_TPFLAGS_BASETYPE
,
2561 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2562 " between polynomial and normal basis representations.",
2564 0, /* @tp_traverse@ */
2566 0, /* @tp_richcompare@ */
2567 0, /* @tp_weaklistoffset@ */
2569 0, /* @tp_iternext@ */
2570 PYMETHODS(gfn
), /* @tp_methods@ */
2571 0, /* @tp_members@ */
2572 PYGETSET(gfn
), /* @tp_getset@ */
2575 0, /* @tp_descr_get@ */
2576 0, /* @tp_descr_set@ */
2577 0, /* @tp_dictoffset@ */
2579 PyType_GenericAlloc
, /* @tp_alloc@ */
2580 gfn_pynew
, /* @tp_new@ */
2585 /*----- Glue --------------------------------------------------------------*/
2587 static const struct nameval consts
[] = {
2592 void mp_pyinit(void)
2596 INITTYPE(mpmul
, root
);
2597 INITTYPE(mpmont
, root
);
2598 INITTYPE(mpbarrett
, root
);
2599 INITTYPE(mpreduce
, root
);
2600 INITTYPE(mpcrt
, root
);
2601 INITTYPE(gfreduce
, root
);
2602 INITTYPE(gfn
, root
);
2605 void mp_pyinsert(PyObject
*mod
)
2607 INSERT("MP", mp_pytype
);
2608 INSERT("MPMul", mpmul_pytype
);
2609 INSERT("MPMont", mpmont_pytype
);
2610 INSERT("MPBarrett", mpbarrett_pytype
);
2611 INSERT("MPReduce", mpreduce_pytype
);
2612 INSERT("MPCRT", mpcrt_pytype
);
2613 INSERT("GF", gf_pytype
);
2614 INSERT("GFReduce", gfreduce_pytype
);
2615 INSERT("GFN", gfn_pytype
);
2616 setconstants(mod
, consts
);
2619 /*----- That's all, folks -------------------------------------------------*/