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 if (sc
.buf
+ 2 < sc
.lim
&& sc
.buf
[0] == '0' &&
126 (radix
== 16 ?
(sc
.buf
[1] == 'x' || sc
.buf
[1] == 'X') :
127 radix
== 8 ?
(sc
.buf
[1] == 'o' || sc
.buf
[1] == 'O') :
128 radix
== 2 ?
(sc
.buf
[1] == 'b' || sc
.buf
[1] == 'B') :
131 x
= mp_read(MP_NEW
, radix
, &mptext_stringops
, &sc
);
133 if (sc
.buf
< sc
.lim
) { MP_DROP(x
); return (0); }
136 if ((x
= tomp(o
)) != 0)
141 PyObject
*mp_topystring(mp
*x
, int radix
, const char *xpre
,
142 const char *pre
, const char *post
)
144 int len
= mptext_len(x
, radix
) + 1;
147 size_t xprelen
= xpre ?
strlen(xpre
) : 0;
148 size_t prelen
= pre ?
strlen(pre
) : 0;
149 size_t postlen
= post ?
strlen(post
) : 0;
152 TEXT_PREPAREWRITE(o
, p
, len
+ 1 + xprelen
+ prelen
+ postlen
);
154 if (xpre
) { memcpy(sc
.buf
, xpre
, xprelen
); sc
.buf
+= xprelen
; }
155 if (MP_NEGP(x
)) { *sc
.buf
++ = '-'; x
= mp_neg(x
, x
); }
156 if (pre
) { memcpy(sc
.buf
, pre
, prelen
); sc
.buf
+= prelen
; }
157 sc
.lim
= sc
.buf
+ len
;
158 mp_write(x
, radix
, &mptext_stringops
, &sc
);
159 if (post
) { memcpy(sc
.buf
, post
, postlen
); sc
.buf
+= postlen
; }
161 TEXT_DONEWRITE(o
, sc
.buf
- p
);
165 static int good_radix_p(int r
, int readp
)
167 return ((r
>= -255 && r
<= -2) ||
169 (r
>= 2 && r
<= 62));
172 PyObject
*mp_pywrap(mp
*x
)
174 mp_pyobj
*z
= PyObject_New(mp_pyobj
, mp_pytype
);
176 return ((PyObject
*)z
);
179 PyObject
*gf_pywrap(mp
*x
)
181 mp_pyobj
*z
= PyObject_New(mp_pyobj
, gf_pytype
);
183 return ((PyObject
*)z
);
186 int mp_tolong_checked(mp
*x
, long *l
, int must
)
188 static mp
*longmin
= 0, *longmax
= 0;
192 longmin
= mp_fromlong(MP_NEW
, LONG_MIN
);
193 longmax
= mp_fromlong(MP_NEW
, LONG_MAX
);
195 if (MP_CMP(x
, <, longmin
) || MP_CMP(x
, >, longmax
)) {
196 if (must
) VALERR("mp out of range for int");
205 /*----- Arbitrary-precision integers --------------------------------------*/
207 static void mp_pydealloc(PyObject
*o
)
213 static PyObject
*mp_pyrepr(PyObject
*o
)
214 { return mp_topystring(MP_X(o
), 10, "MP(", 0, ")"); }
216 static PyObject
*mp_pystr(PyObject
*o
)
217 { return mp_topystring(MP_X(o
), 10, 0, 0, 0); }
219 mp
*tomp(PyObject
*o
)
224 if (!o
|| PyFloat_Check(o
))
226 else if (MP_PYCHECK(o
) || GF_PYCHECK(o
))
227 return (MP_COPY(MP_X(o
)));
228 else if (FE_PYCHECK(o
))
229 return (F_OUT(FE_F(o
), MP_NEW
, FE_X(o
)));
230 else if (PFILT_PYCHECK(o
))
231 return (MP_COPY(PFILT_F(o
)->m
));
232 else if (ECPT_PYCHECK(o
)) {
234 if (EC_ATINF(ECPT_P(o
))) return (0);
239 } else if (GE_PYCHECK(o
)) {
240 if ((x
= G_TOINT(GE_G(o
), MP_NEW
, GE_X(o
))) == 0)
245 else if (PyInt_Check(o
))
246 return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
248 else if ((l
= PyNumber_Long(o
)) != 0) {
249 x
= mp_frompylong(l
);
258 mp
*getmp(PyObject
*o
)
262 if ((x
= tomp(o
)) == 0) {
263 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
264 Py_TYPE(o
)->tp_name
);
269 int convmp(PyObject
*o
, void *p
)
272 if ((x
= getmp(o
)) == 0) return (0);
277 mp
*getgf(PyObject
*o
)
281 if ((x
= tomp(o
)) == 0) {
282 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
283 Py_TYPE(o
)->tp_name
);
288 int convgf(PyObject
*o
, void *p
)
291 if ((x
= getgf(o
)) == 0) return (0);
296 mp
*implicitmp(PyObject
*o
)
300 if (!o
|| GF_PYCHECK(o
) || FE_PYCHECK(o
)) return (0);
301 else if (MP_PYCHECK(o
)) return (MP_COPY(MP_X(o
)));
302 else if (PFILT_PYCHECK(o
)) return (MP_COPY(PFILT_F(o
)->m
));
304 else if (PyInt_Check(o
)) return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
306 else if ((l
= PyNumber_Index(o
)) != 0) {
308 if (PyInt_Check(o
)) return (mp_fromlong(MP_NEW
, PyInt_AS_LONG(o
)));
310 if (PyLong_Check(o
)) return (mp_frompylong(o
));
312 PyErr_Clear(); return (0);
315 mp
*implicitgf(PyObject
*o
)
317 if (GF_PYCHECK(o
)) return (MP_COPY(MP_X(o
)));
321 static int mpbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
323 if ((*xx
= implicitmp(x
)) == 0)
325 if ((*yy
= implicitmp(y
)) == 0) {
332 static int gfbinop(PyObject
*x
, PyObject
*y
, mp
**xx
, mp
**yy
)
334 if ((*xx
= implicitgf(x
)) == 0)
336 if ((*yy
= implicitgf(y
)) == 0) {
343 #define FPBINOP(name, pyop) \
344 static PyObject *mp_py##name(PyObject *x, PyObject *y) { \
347 if (PyFloat_Check(x)) { \
348 l = mp_topylong(MP_X(y)); rc = PyNumber_##pyop(x, l); \
349 Py_DECREF(l); return (rc); \
350 } else if (PyFloat_Check(y)) { \
351 l = mp_topylong(MP_X(x)); rc = PyNumber_##pyop(l, y); \
352 Py_DECREF(l); return (rc); \
354 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
355 zz = mp_##name(MP_NEW, xx, yy); \
356 MP_DROP(xx); MP_DROP(yy); \
357 return (mp_pywrap(zz)); \
360 FPBINOP(sub
, Subtract
)
361 FPBINOP(mul
, Multiply
)
363 #define gf_and mp_and
365 #define gf_xor mp_xor
366 #define BINOP(pre, name) \
367 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
369 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
370 zz = pre##_##name(MP_NEW, xx, yy); \
371 MP_DROP(xx); MP_DROP(yy); \
372 return (pre##_pywrap(zz)); \
385 static mp
*mp_abs(mp
*d
, mp
*x
)
388 return (mp_neg(d
, x
));
394 #define UNOP(pre, name) \
395 static PyObject *pre##_py##name(PyObject *x) \
396 { return mp_pywrap(pre##_##name(MP_NEW, MP_X(x))); }
402 static PyObject
*mp_pyid(PyObject
*x
) { RETURN_OBJ(x
); }
404 #define gf_lsr mp_lsr
405 #define SHIFTOP(pre, PRE, name, rname) \
406 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
410 if (!PRE##_PYCHECK(x)) RETURN_NOTIMPL; \
411 if (GF_PYCHECK(y) || FE_PYCHECK(y)) RETURN_NOTIMPL; \
412 yix = PyNumber_Index(y); if (!yix) { PyErr_Clear(); RETURN_NOTIMPL; } \
413 n = PyInt_AsLong(yix); Py_DECREF(yix); \
414 if (n == -1 && PyErr_Occurred()) { PyErr_Clear(); RETURN_NOTIMPL; } \
415 if (n < 0) z = pre##_pywrap(mp_##rname(MP_NEW, MP_X(x), -n)); \
416 else z = pre##_pywrap(mp_##name(MP_NEW, MP_X(x), n)); \
419 SHIFTOP(mp
, MP
, lsl2c
, lsr2c
)
420 SHIFTOP(mp
, MP
, lsr2c
, lsl2c
)
421 SHIFTOP(gf
, GF
, lsl
, lsr
)
422 SHIFTOP(gf
, GF
, lsr
, lsl
)
425 #define DIVOP(pre, name, qq, rr, gather) \
426 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
429 INIT_##qq(q) INIT_##rr(r) \
430 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
432 ZDIVERR("division by zero"); \
433 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
436 MP_DROP(xx); MP_DROP(yy); \
439 #define INIT_YES(p) mp *p = MP_NEW;
441 #define ARG_YES(p) &p
443 DIVOP(mp
, divmod
, YES
, YES
,
444 Py_BuildValue("(NN)", mp_pywrap(q
), mp_pywrap(r
)))
445 DIVOP(mp
, div
, YES
, NO
, mp_pywrap(q
))
446 DIVOP(mp
, mod
, NO
, YES
, mp_pywrap(r
))
447 DIVOP(gf
, divmod
, YES
, YES
,
448 Py_BuildValue("(NN)", gf_pywrap(q
), gf_pywrap(r
)))
449 DIVOP(gf
, div
, YES
, NO
, gf_pywrap(q
))
450 DIVOP(gf
, mod
, NO
, YES
, gf_pywrap(r
))
457 static mp
*mp_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
460 mp_gcd(&g
, 0, &d
, p
, x
);
461 if (!MP_EQ(g
, MP_ONE
)) {
462 MP_DROP(g
); MP_DROP(d
);
463 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
466 MP_DROP(g
); return (d
);
469 static PyObject
*mp_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
471 mp
*xx
= 0, *yy
= 0, *zz
= 0;
475 if ((xx
= implicitmp(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
476 (z
&& z
!= Py_None
&& (zz
= implicitmp(z
)) == 0)) {
477 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
480 if (!z
|| z
== Py_None
) {
481 if (MP_NEGP(yy
)) VALERR("negative exponent");
482 r
= mp_exp(MP_NEW
, xx
, yy
);
484 if (!MP_POSP(zz
)) VALERR("modulus must be positive");
486 if ((xx
= mp_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
491 mpmont_create(&mm
, zz
);
492 r
= mpmont_exp(&mm
, MP_NEW
, xx
, yy
);
496 mpbarrett_create(&mb
, zz
);
497 r
= mpbarrett_exp(&mb
, MP_NEW
, xx
, yy
);
498 mpbarrett_destroy(&mb
);
503 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
507 static mp
*gf_modinv_checked(mp
*d
, mp
*x
, mp
*p
)
510 gf_gcd(&g
, 0, &d
, p
, x
);
511 if (!MP_EQ(g
, MP_ONE
)) {
512 MP_DROP(g
); MP_DROP(d
);
513 PyErr_SetString(PyExc_ZeroDivisionError
, "no modular inverse");
516 MP_DROP(g
); return (d
);
519 #define BASEOP(name, radix, pre) \
520 static PyObject *mp_py##name(PyObject *x) \
521 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
525 BASEOP(hex
, 16, "0x");
528 static int mp_pynonzerop(PyObject
*x
) { return !MP_ZEROP(MP_X(x
)); }
530 static PyObject
*mp_pyint(PyObject
*x
)
533 if (!mp_tolong_checked(MP_X(x
), &l
, 0)) return (PyInt_FromLong(l
));
534 else return mp_topylong(MP_X(x
));
537 static PyObject
*mp_pylong(PyObject
*x
)
538 { return (mp_topylong(MP_X(x
))); }
540 static PyObject
*mp_pyfloat(PyObject
*x
)
542 PyObject
*l
= mp_topylong(MP_X(x
));
543 double f
= PyLong_AsDouble(l
);
545 return (PyFloat_FromDouble(f
));
549 #define COERCE(pre, PRE) \
550 static int pre##_pycoerce(PyObject **x, PyObject **y) \
554 if (PRE##_PYCHECK(*y)) { \
555 Py_INCREF(*x); Py_INCREF(*y); \
558 if ((z = implicit##pre(*y)) != 0) { \
560 *y = pre##_pywrap(z); \
570 static PyObject
*mp_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
574 if (PyFloat_Check(y
)) {
575 l
= mp_topylong(MP_X(x
)); rc
= PyObject_RichCompare(l
, y
, op
);
576 Py_DECREF(l
); return (rc
);
578 if (mpbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
579 rc
= enrich_compare(op
, mp_cmp(xx
, yy
));
580 MP_DROP(xx
); MP_DROP(yy
);
585 static int mp_pycompare(PyObject
*x
, PyObject
*y
)
586 { return mp_cmp(MP_X(x
), MP_X(y
)); }
589 static PyObject
*mp_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
595 static const char *const kwlist
[] = { "x", "radix", 0 };
597 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:new", KWLIST
, &x
, &radix
))
599 if (MP_PYCHECK(x
)) RETURN_OBJ(x
);
600 if (!good_radix_p(radix
, 1)) VALERR("bad radix");
601 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
602 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to mp",
603 Py_TYPE(x
)->tp_name
);
606 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
609 return ((PyObject
*)zz
);
612 #define IMPLICIT(pre) \
613 static PyObject *pre##meth__implicit(PyObject *me, PyObject *arg) \
615 PyObject *x, *rc = 0; \
617 if (!PyArg_ParseTuple(arg, "O:_implicit", &x)) goto end; \
618 y = implicit##pre(x); \
619 if (!y) TYERR("can't convert implicitly to " #pre); \
620 rc = pre##_pywrap(y); \
628 Py_hash_t
mphash(mp
*x
)
630 PyObject
*l
= mp_topylong(x
);
631 Py_hash_t h
= PyObject_Hash(l
);
632 Py_DECREF(l
); return (h
);
635 static Py_hash_t
mp_pyhash(PyObject
*me
) { return (mphash(MP_X(me
))); }
637 static PyObject
*mpmeth_jacobi(PyObject
*me
, PyObject
*arg
)
642 if (!PyArg_ParseTuple(arg
, "O&:jacobi", convmp
, &y
)) goto end
;
643 z
= PyInt_FromLong(mp_jacobi(y
, MP_X(me
)));
649 #define BITOP(pre, name, c) \
650 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
653 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
654 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
656 BITOP(mp
, setbit
, 2c
);
657 BITOP(mp
, clearbit
, 2c
);
659 BITOP(gf
, clearbit
, );
662 static PyObject
*mpmeth_testbit(PyObject
*me
, PyObject
*arg
)
665 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
666 return (getbool(mp_testbit2c(MP_X(me
), i
)));
669 static PyObject
*gfmeth_testbit(PyObject
*me
, PyObject
*arg
)
672 if (!PyArg_ParseTuple(arg
, "O&:testbit", convulong
, &i
)) return (0);
673 return (getbool(mp_testbit(MP_X(me
), i
)));
676 static PyObject
*mpmeth_odd(PyObject
*me
)
681 t
= mp_odd(MP_NEW
, MP_X(me
), &s
);
682 return (Py_BuildValue("(lN)", (long)s
, mp_pywrap(t
)));
685 static PyObject
*mpmeth_sqr(PyObject
*me
)
686 { return (mp_pywrap(mp_sqr(MP_NEW
, MP_X(me
)))); }
688 static PyObject
*mpmeth_sqrt(PyObject
*me
)
690 if (MP_NEGP(MP_X(me
))) VALERR("negative root");
691 return (mp_pywrap(mp_sqrt(MP_NEW
, MP_X(me
))));
696 static PyObject
*mpmeth_gcd(PyObject
*me
, PyObject
*arg
)
698 mp
*y
= 0, *zz
= MP_NEW
;
701 if (!PyArg_ParseTuple(arg
, "O&:gcd", convmp
, &y
)) goto end
;
702 mp_gcd(&zz
, 0, 0, MP_X(me
), y
);
709 static PyObject
*mpmeth_gcdx(PyObject
*me
, PyObject
*arg
)
712 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
714 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convmp
, &yy
)) goto end
;
715 mp_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
716 z
= Py_BuildValue("(NNN)",
717 mp_pywrap(zz
), mp_pywrap(uu
), mp_pywrap(vv
));
723 static PyObject
*mpmeth_modinv(PyObject
*me
, PyObject
*arg
)
726 mp
*yy
= 0, *zz
= MP_NEW
;
728 if (!PyArg_ParseTuple(arg
, "O&:modinv", convmp
, &yy
) ||
729 (zz
= mp_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
737 static PyObject
*mpmeth_tostring(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
740 static const char *const kwlist
[] = { "radix", 0 };
741 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|i:tostring", KWLIST
, &radix
))
743 if (!good_radix_p(radix
, 0)) VALERR("bad radix");
744 return (mp_topystring(MP_X(me
), radix
, 0, 0, 0));
749 static PyObject
*mpmeth_modsqrt(PyObject
*me
, PyObject
*arg
)
752 mp
*yy
= 0, *zz
= MP_NEW
;
754 if (!PyArg_ParseTuple(arg
, "O&:modsqrt", convmp
, &yy
)) goto end
;
755 if ((zz
= mp_modsqrt(MP_NEW
, yy
, MP_X(me
))) == 0)
756 VALERR("no modular square root");
763 static PyObject
*mpmeth_leastcongruent(PyObject
*me
, PyObject
*arg
)
768 if (!PyArg_ParseTuple(arg
, "O&O&:leastcongruent", convmp
, &b
, convmp
, &m
))
770 z
= mp_leastcongruent(MP_NEW
, b
, MP_X(me
), m
);
776 #define STOREOP(name, c) \
777 static PyObject *mpmeth_##name(PyObject *me, \
778 PyObject *arg, PyObject *kw) \
781 static const char *const kwlist[] = { "len", 0 }; \
784 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
788 len = mp_octets##c(MP_X(me)); \
791 rc = bytestring_pywrap(0, len); \
792 mp_##name(MP_X(me), BIN_PTR(rc), len); \
798 STOREOP(storel2c
, 2c
)
799 STOREOP(storeb2c
, 2c
)
803 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
810 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
811 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
812 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
813 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
814 bytestring_pywrapbuf(&b)); \
822 static PyObject
*mpmeth_tobuf(PyObject
*me
)
830 n
= mp_octets(x
) + 3;
831 rc
= bytestring_pywrap(0, n
);
832 buf_init(&b
, BIN_PTR(rc
), n
);
835 BIN_SETLEN(rc
, BLEN(&b
));
839 static PyObject
*mpmeth_primep(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
841 grand
*r
= &rand_global
;
842 static const char *const kwlist
[] = { "rng", 0 };
845 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "|O&", KWLIST
, convgrand
, &r
))
847 rc
= getbool(pgen_primep(MP_X(me
), r
));
852 static PyObject
*mpmeth_fromstring(PyObject
*me
,
853 PyObject
*arg
, PyObject
*kw
)
861 static const char *const kwlist
[] = { "x", "radix", 0 };
863 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
866 if (!good_radix_p(r
, 1)) VALERR("bad radix");
867 sc
.buf
= p
; sc
.lim
= p
+ len
;
868 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0)
869 VALERR("bad integer");
870 z
= Py_BuildValue("(Ns#)", mp_pywrap(zz
),
871 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
876 static PyObject
*mpmeth_factorial(PyObject
*me
, PyObject
*arg
)
880 if (!PyArg_ParseTuple(arg
, "O&:factorial", convulong
, &i
)) return (0);
885 static PyObject
*mpmeth_fibonacci(PyObject
*me
, PyObject
*arg
)
889 if (!PyArg_ParseTuple(arg
, "l:fibonacci", &i
)) return (0);
894 #define LOADOP(pre, name) \
895 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
898 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
899 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
909 static PyObject
*mpget_nbits(PyObject
*me
, void *hunoz
)
910 { return (PyInt_FromLong(mp_bits(MP_X(me
)))); }
912 static PyObject
*mpget_noctets(PyObject
*me
, void *hunoz
)
913 { return (PyInt_FromLong(mp_octets(MP_X(me
)))); }
915 static PyObject
*mpget_noctets2c(PyObject
*me
, void *hunoz
)
916 { return (PyInt_FromLong(mp_octets2c(MP_X(me
)))); }
918 static const PyGetSetDef mp_pygetset
[] = {
919 #define GETSETNAME(op, func) mp##op##_##func
920 GET (nbits
, "X.nbits -> bit length of X")
921 GET (noctets
, "X.noctets -> octet length of X")
922 GET (noctets2c
, "X.noctets2c -> two's complement octet length of X")
927 static const PyMethodDef mp_pymethods
[] = {
928 #define METHNAME(func) mpmeth_##func
929 METH (jacobi
, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
930 METH (setbit
, "X.setbit(N) -> X with bit N set")
931 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
932 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
933 NAMETH(odd
, "X.odd() -> S, T where X = 2^S T with T odd")
934 NAMETH(sqr
, "X.sqr() -> X^2")
935 NAMETH(sqrt
, "X.sqrt() -> largest integer <= sqrt(X)")
936 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
937 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
938 "with X U + Y V = gcd(X, Y)")
939 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
940 METH (modsqrt
, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
941 METH (leastcongruent
, "X.leastcongruent(B, M) -> "
942 "smallest Z >= B with Z == X (mod M)")
943 KWMETH(primep
, "X.primep([rng = rand]) -> X is prime?")
944 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
945 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
946 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
947 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
948 "little-endian bytes, two's complement")
949 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
950 "big-endian bytes, two's complement")
951 NAMETH(tobuf
, "X.tobuf() -> buffer format")
952 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
953 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
954 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
955 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
957 SMTH (factorial
, "factorial(I) -> I!: compute factorial")
958 SMTH (fibonacci
, "fibonacci(I) -> F(I): compute Fibonacci number")
959 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
960 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
961 SMTH (loadl2c
, "loadl2c(STR) -> X: "
962 "read little-endian bytes, two's complement")
963 SMTH (loadb2c
, "loadb2c(STR) -> X: "
964 "read big-endian bytes, two's complement")
965 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
970 static const PyNumberMethods mp_pynumber
= {
971 mp_pyadd
, /* @nb_add@ */
972 mp_pysub
, /* @nb_subtract@ */
973 mp_pymul
, /* @nb_multiply@ */
977 mp_pymod
, /* @nb_remainder@ */
978 mp_pydivmod
, /* @nb_divmod@ */
979 mp_pyexp
, /* @nb_power@ */
980 mp_pyneg
, /* @nb_negative@ */
981 mp_pyid
, /* @nb_positive@ */
982 mp_pyabs
, /* @nb_absolute@ */
983 mp_pynonzerop
, /* @nb_nonzero@ */
984 mp_pynot2c
, /* @nb_invert@ */
985 mp_pylsl2c
, /* @nb_lshift@ */
986 mp_pylsr2c
, /* @nb_rshift@ */
987 mp_pyand2c
, /* @nb_and@ */
988 mp_pyxor2c
, /* @nb_xor@ */
989 mp_pyor2c
, /* @nb_or@ */
991 mp_pycoerce
, /* @nb_coerce@ */
993 mp_pyint
, /* @nb_int@ */
994 PY23(mp_pylong
, 0), /* @nb_long@ */
995 mp_pyfloat
, /* @nb_float@ */
997 mp_pyoct
, /* @nb_oct@ */
998 mp_pyhex
, /* @nb_hex@ */
1001 0, /* @nb_inplace_add@ */
1002 0, /* @nb_inplace_subtract@ */
1003 0, /* @nb_inplace_multiply@ */
1005 0, /* @nb_inplace_divide@ */
1007 0, /* @nb_inplace_remainder@ */
1008 0, /* @nb_inplace_power@ */
1009 0, /* @nb_inplace_lshift@ */
1010 0, /* @nb_inplace_rshift@ */
1011 0, /* @nb_inplace_and@ */
1012 0, /* @nb_inplace_xor@ */
1013 0, /* @nb_inplace_or@ */
1015 mp_pydiv
, /* @nb_floor_divide@ */
1016 0, /* @nb_true_divide@ */
1017 0, /* @nb_inplace_floor_divide@ */
1018 0, /* @nb_inplace_true_divide@ */
1020 mp_pyint
, /* @nb_index@ */
1023 static const PyTypeObject mp_pytype_skel
= {
1024 PyVarObject_HEAD_INIT(0, 0) /* Header */
1025 "MP", /* @tp_name@ */
1026 sizeof(mp_pyobj
), /* @tp_basicsize@ */
1027 0, /* @tp_itemsize@ */
1029 mp_pydealloc
, /* @tp_dealloc@ */
1031 0, /* @tp_getattr@ */
1032 0, /* @tp_setattr@ */
1033 PY23(mp_pycompare
, 0), /* @tp_compare@/@tp_as_async@ */
1034 mp_pyrepr
, /* @tp_repr@ */
1035 PYNUMBER(mp
), /* @tp_as_number@ */
1036 0, /* @tp_as_sequence@ */
1037 0, /* @tp_as_mapping@ */
1038 mp_pyhash
, /* @tp_hash@ */
1040 mp_pystr
, /* @tp_str@ */
1041 0, /* @tp_getattro@ */
1042 0, /* @tp_setattro@ */
1043 0, /* @tp_as_buffer@ */
1044 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1045 Py_TPFLAGS_CHECKTYPES
|
1046 Py_TPFLAGS_BASETYPE
,
1049 "Multiprecision integers, similar to `long' but more efficient and\n"
1050 "versatile. Support all the standard arithmetic operations, with\n"
1051 "implicit conversions from `PrimeFilter', and other objects which\n"
1052 "convert to `" PY23("long", "int") "'.\n"
1054 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1055 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1056 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1058 "points, group elements, Python `int' and `long' objects, and anything\n"
1059 "with an integer conversion.\n",
1060 "points, group elements, Python `int' objects, and anything with an\n"
1061 "integer conversion.\n")
1065 " * Use `//' for integer division: `/' gives exact rational division.",
1067 0, /* @tp_traverse@ */
1069 mp_pyrichcompare
, /* @tp_richcompare@ */
1070 0, /* @tp_weaklistoffset@ */
1072 0, /* @tp_iternext@ */
1073 PYMETHODS(mp
), /* @tp_methods@ */
1074 0, /* @tp_members@ */
1075 PYGETSET(mp
), /* @tp_getset@ */
1078 0, /* @tp_descr_get@ */
1079 0, /* @tp_descr_set@ */
1080 0, /* @tp_dictoffset@ */
1082 PyType_GenericAlloc
, /* @tp_alloc@ */
1083 mp_pynew
, /* @tp_new@ */
1088 /*----- Products of small integers ----------------------------------------*/
1090 static PyTypeObject
*mpmul_pytype
;
1092 typedef struct mpmul_pyobj
{
1098 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1099 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1101 static void mpmul_pydealloc(PyObject
*me
)
1103 if (MPMUL_LIVEP(me
))
1104 mp_drop(mpmul_done(MPMUL_PY(me
)));
1108 static PyObject
*mmmeth_factor(PyObject
*me
, PyObject
*arg
)
1113 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1114 if (PyTuple_GET_SIZE(arg
) != 1)
1115 i
= PyObject_GetIter(arg
);
1117 if ((q
= PyTuple_GET_ITEM(arg
, 0)) == 0) goto end
;
1118 if ((i
= PyObject_GetIter(q
)) == 0) {
1119 PyErr_Clear(); /* that's ok */
1120 i
= PyObject_GetIter(arg
);
1124 while ((q
= PyIter_Next(i
)) != 0) {
1125 x
= getmp(q
); Py_DECREF(q
); if (!x
) {
1129 mpmul_add(MPMUL_PY(me
), x
);
1138 static PyObject
*mmmeth_done(PyObject
*me
)
1142 if (!MPMUL_LIVEP(me
)) VALERR("MPMul object invalid");
1143 x
= mpmul_done(MPMUL_PY(me
));
1144 MPMUL_LIVEP(me
) = 0;
1145 return (mp_pywrap(x
));
1150 static PyObject
*mpmul_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1154 if (kw
) TYERR("keyword arguments not allowed here");
1155 mm
= (mpmul_pyobj
*)ty
->tp_alloc(ty
, 0);
1156 mpmul_init(&mm
->mm
);
1158 if (mmmeth_factor((PyObject
*)mm
, arg
) == 0) {
1162 return ((PyObject
*)mm
);
1167 static PyObject
*mmget_livep(PyObject
*me
, void *hunoz
)
1168 { return (getbool(MPMUL_LIVEP(me
))); }
1170 static const PyGetSetDef mpmul_pygetset
[] = {
1171 #define GETSETNAME(op, name) mm##op##_##name
1172 GET (livep
, "MM.livep -> flag: object still valid?")
1177 static const PyMethodDef mpmul_pymethods
[] = {
1178 #define METHNAME(name) mmmeth_##name
1179 METH (factor
, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1180 NAMETH(done
, "MM.done() -> PRODUCT")
1185 static const PyTypeObject mpmul_pytype_skel
= {
1186 PyVarObject_HEAD_INIT(0, 0) /* Header */
1187 "MPMul", /* @tp_name@ */
1188 sizeof(mpmul_pyobj
), /* @tp_basicsize@ */
1189 0, /* @tp_itemsize@ */
1191 mpmul_pydealloc
, /* @tp_dealloc@ */
1193 0, /* @tp_getattr@ */
1194 0, /* @tp_setattr@ */
1195 0, /* @tp_compare@ */
1197 0, /* @tp_as_number@ */
1198 0, /* @tp_as_sequence@ */
1199 0, /* @tp_as_mapping@ */
1203 0, /* @tp_getattro@ */
1204 0, /* @tp_setattro@ */
1205 0, /* @tp_as_buffer@ */
1206 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1207 Py_TPFLAGS_BASETYPE
,
1210 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1212 0, /* @tp_traverse@ */
1214 0, /* @tp_richcompare@ */
1215 0, /* @tp_weaklistoffset@ */
1217 0, /* @tp_iternext@ */
1218 PYMETHODS(mpmul
), /* @tp_methods@ */
1219 0, /* @tp_members@ */
1220 PYGETSET(mpmul
), /* @tp_getset@ */
1223 0, /* @tp_descr_get@ */
1224 0, /* @tp_descr_set@ */
1225 0, /* @tp_dictoffset@ */
1227 PyType_GenericAlloc
, /* @tp_alloc@ */
1228 mpmul_pynew
, /* @tp_new@ */
1233 /*----- Montgomery reduction ----------------------------------------------*/
1235 static PyTypeObject
*mpmont_pytype
;
1237 typedef struct mpmont_pyobj
{
1242 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1244 static PyObject
*mmmeth_int(PyObject
*me
, PyObject
*arg
)
1248 mpmont
*mm
= MPMONT_PY(me
);
1250 if (!PyArg_ParseTuple(arg
, "O&:in", convmp
, &yy
))
1252 mp_div(0, &yy
, yy
, mm
->m
);
1253 z
= mp_pywrap(mpmont_mul(mm
, MP_NEW
, yy
, mm
->r2
));
1255 if (yy
) MP_DROP(yy
);
1259 static PyObject
*mmmeth_mul(PyObject
*me
, PyObject
*arg
)
1262 mp
*yy
= 0, *zz
= 0;
1264 if (!PyArg_ParseTuple(arg
, "O&O&:mul", convmp
, &yy
, convmp
, &zz
))
1266 rc
= mp_pywrap(mpmont_mul(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1268 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1272 static PyObject
*mmmeth_exp(PyObject
*me
, PyObject
*arg
)
1275 mp
*yy
= 0, *zz
= 0;
1277 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1280 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1281 zz
= mp_neg(zz
, zz
);
1283 rc
= mp_pywrap(mpmont_exp(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1285 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1289 static PyObject
*mmmeth_expr(PyObject
*me
, PyObject
*arg
)
1292 mp
*yy
= 0, *zz
= 0;
1294 if (!PyArg_ParseTuple(arg
, "O&O&:expr", convmp
, &yy
, convmp
, &zz
))
1297 yy
= mpmont_reduce(MPMONT_PY(me
), yy
, yy
);
1298 if ((yy
= mp_modinv_checked(yy
, yy
, MPMONT_PY(me
)->m
)) == 0) goto end
;
1299 yy
= mpmont_mul(MPMONT_PY(me
), yy
, yy
, MPMONT_PY(me
)->r2
);
1300 zz
= mp_neg(zz
, zz
);
1302 rc
= mp_pywrap(mpmont_expr(MPMONT_PY(me
), MP_NEW
, yy
, zz
));
1304 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1308 static PyObject
*mm_mexpr_id(PyObject
*me
)
1309 { return mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
)); }
1311 static int mm_mexpr_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1313 mp
*xx
= 0, *yy
= 0;
1314 mp_expfactor
*f
= p
;
1315 mpmont
*mm
= MPMONT_PY(me
);
1317 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1320 xx
= mpmont_reduce(mm
, xx
, xx
);
1321 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1323 xx
= mpmont_mul(mm
, xx
, xx
, mm
->r2
);
1324 yy
= mp_neg(yy
, yy
);
1331 mp_drop(xx
); mp_drop(yy
);
1335 static PyObject
*mm_mexpr(PyObject
*me
, void *v
, size_t n
)
1336 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1338 static void mp_mexp_drop(void *p
)
1340 mp_expfactor
*f
= p
;
1345 static PyObject
*mmmeth_mexpr(PyObject
*me
, PyObject
*arg
)
1347 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1348 mm_mexpr_id
, mm_mexpr_fill
, mm_mexpr
, mp_mexp_drop
);
1351 static PyObject
*mp_mexp_id(PyObject
*me
)
1352 { return mp_pywrap(MP_ONE
); }
1354 static int mp_mexp_fill(void *p
, PyObject
*me
, PyObject
*x
, PyObject
*y
)
1356 mp
*xx
= 0, *yy
= 0;
1357 mp_expfactor
*f
= p
;
1359 if ((xx
= getmp(x
)) == 0 || (yy
= getmp(y
)) == 0)
1362 if ((xx
= mp_modinv_checked(xx
, xx
, yy
)) == 0)
1364 yy
= mp_neg(yy
, yy
);
1371 mp_drop(xx
); mp_drop(yy
);
1375 static PyObject
*mm_mexp(PyObject
*me
, void *v
, size_t n
)
1376 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me
), MP_NEW
, v
, n
)); }
1378 static PyObject
*mmmeth_mexp(PyObject
*me
, PyObject
*arg
)
1380 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1381 mp_mexp_id
, mp_mexp_fill
, mm_mexp
, mp_mexp_drop
);
1384 #define mmmeth_ext mmmeth_reduce
1385 static PyObject
*mmmeth_reduce(PyObject
*me
, PyObject
*arg
)
1390 if (!PyArg_ParseTuple(arg
, "O&", convmp
, &yy
)) goto end
;
1391 z
= mp_pywrap(mpmont_reduce(MPMONT_PY(me
), MP_NEW
, yy
));
1396 static void mpmont_pydealloc(PyObject
*me
)
1398 mpmont_destroy(MPMONT_PY(me
));
1402 static PyObject
*mpmont_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1404 mpmont_pyobj
*mm
= 0;
1405 static const char *const kwlist
[] = { "m", 0 };
1408 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1410 if (!MP_POSP(xx
) || !MP_ODDP(xx
)) VALERR("m must be positive and odd");
1411 mm
= (mpmont_pyobj
*)ty
->tp_alloc(ty
, 0);
1412 mpmont_create(&mm
->mm
, xx
);
1414 if (xx
) MP_DROP(xx
);
1415 return ((PyObject
*)mm
);
1418 static PyObject
*mmget_m(PyObject
*me
, void *hunoz
)
1419 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->m
))); }
1421 static PyObject
*mmget_r(PyObject
*me
, void *hunoz
)
1422 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r
))); }
1424 static PyObject
*mmget_r2(PyObject
*me
, void *hunoz
)
1425 { return (mp_pywrap(MP_COPY(MPMONT_PY(me
)->r2
))); }
1427 static const PyGetSetDef mpmont_pygetset
[] = {
1428 #define GETSETNAME(op, name) mm##op##_##name
1429 GET (m
, "M.m -> modulus for reduction")
1430 GET (r
, "M.r -> multiplicative identity")
1431 GET (r2
, "M.r2 -> M.r^2, Montgomerization factor")
1436 static const PyMethodDef mpmont_pymethods
[] = {
1437 #define METHNAME(name) mmmeth_##name
1438 METH (int, "M.int(X) -> XR")
1439 METH (mul
, "M.mul(XR, YR) -> ZR where Z = X Y")
1440 METH (expr
, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1441 METH (mexpr
, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1442 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1443 "\t(the list may be flattened if this more convenient.)")
1444 METH (reduce
, "M.reduce(XR) -> X")
1445 METH (ext
, "M.ext(XR) -> X")
1446 METH (exp
, "M.exp(X, N) -> X^N mod M.m")
1447 METH (mexp
, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1448 "X0^N0 X1^N1 ... mod M.m\n"
1449 "\t(the list may be flattened if this more convenient.)")
1454 static const PyTypeObject mpmont_pytype_skel
= {
1455 PyVarObject_HEAD_INIT(0, 0) /* Header */
1456 "MPMont", /* @tp_name@ */
1457 sizeof(mpmont_pyobj
), /* @tp_basicsize@ */
1458 0, /* @tp_itemsize@ */
1460 mpmont_pydealloc
, /* @tp_dealloc@ */
1462 0, /* @tp_getattr@ */
1463 0, /* @tp_setattr@ */
1464 0, /* @tp_compare@ */
1466 0, /* @tp_as_number@ */
1467 0, /* @tp_as_sequence@ */
1468 0, /* @tp_as_mapping@ */
1472 0, /* @tp_getattro@ */
1473 0, /* @tp_setattro@ */
1474 0, /* @tp_as_buffer@ */
1475 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1476 Py_TPFLAGS_BASETYPE
,
1479 "MPMont(N): a Montgomery reduction context.",
1481 0, /* @tp_traverse@ */
1483 0, /* @tp_richcompare@ */
1484 0, /* @tp_weaklistoffset@ */
1486 0, /* @tp_iternext@ */
1487 PYMETHODS(mpmont
), /* @tp_methods@ */
1488 0, /* @tp_members@ */
1489 PYGETSET(mpmont
), /* @tp_getset@ */
1492 0, /* @tp_descr_get@ */
1493 0, /* @tp_descr_set@ */
1494 0, /* @tp_dictoffset@ */
1496 PyType_GenericAlloc
, /* @tp_alloc@ */
1497 mpmont_pynew
, /* @tp_new@ */
1502 /*----- Barrett reduction -------------------------------------------------*/
1504 static PyTypeObject
*mpbarrett_pytype
;
1506 typedef struct mpbarrett_pyobj
{
1511 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1513 static PyObject
*mbmeth_exp(PyObject
*me
, PyObject
*arg
)
1516 mp
*yy
= 0, *zz
= 0;
1518 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1521 if ((yy
= mp_modinv_checked(yy
, yy
, MPBARRETT_PY(me
)->m
)) == 0) goto end
;
1522 zz
= mp_neg(zz
, zz
);
1524 rc
= mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me
), MP_NEW
, yy
, zz
));
1526 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1530 static PyObject
*mb_mexp(PyObject
*me
, void *v
, size_t n
)
1531 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me
), MP_NEW
, v
, n
)); }
1533 static PyObject
*mbmeth_mexp(PyObject
*me
, PyObject
*arg
)
1535 return mexp_common(me
, arg
, sizeof(mp_expfactor
),
1536 mp_mexp_id
, mp_mexp_fill
, mb_mexp
, mp_mexp_drop
);
1539 static PyObject
*mbmeth_reduce(PyObject
*me
, PyObject
*arg
)
1544 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
))
1546 z
= mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me
), MP_NEW
, yy
));
1551 static void mpbarrett_pydealloc(PyObject
*me
)
1553 mpbarrett_destroy(MPBARRETT_PY(me
));
1557 static PyObject
*mpbarrett_pynew(PyTypeObject
*ty
,
1558 PyObject
*arg
, PyObject
*kw
)
1560 mpbarrett_pyobj
*mb
= 0;
1561 static const char *const kwlist
[] = { "m", 0 };
1564 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1566 if (!MP_POSP(xx
)) VALERR("m must be positive");
1567 mb
= (mpbarrett_pyobj
*)ty
->tp_alloc(ty
, 0);
1568 mpbarrett_create(&mb
->mb
, xx
);
1570 if (xx
) MP_DROP(xx
);
1571 return ((PyObject
*)mb
);
1574 static PyObject
*mbget_m(PyObject
*me
, void *hunoz
)
1575 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me
)->m
))); }
1577 static const PyGetSetDef mpbarrett_pygetset
[] = {
1578 #define GETSETNAME(op, name) mb##op##_##name
1579 GET (m
, "B.m -> modulus for reduction")
1584 static const PyMethodDef mpbarrett_pymethods
[] = {
1585 #define METHNAME(name) mbmeth_##name
1586 METH (reduce
, "B.reduce(X) -> X mod B.m")
1587 METH (exp
, "B.exp(X, N) -> X^N mod B.m")
1588 METH (mexp
, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1589 "X0^N0 X1^N1 ... mod B.m\n"
1590 "\t(the list may be flattened if this more convenient.)")
1595 static const PyTypeObject mpbarrett_pytype_skel
= {
1596 PyVarObject_HEAD_INIT(0, 0) /* Header */
1597 "MPBarrett", /* @tp_name@ */
1598 sizeof(mpbarrett_pyobj
), /* @tp_basicsize@ */
1599 0, /* @tp_itemsize@ */
1601 mpbarrett_pydealloc
, /* @tp_dealloc@ */
1603 0, /* @tp_getattr@ */
1604 0, /* @tp_setattr@ */
1605 0, /* @tp_compare@ */
1607 0, /* @tp_as_number@ */
1608 0, /* @tp_as_sequence@ */
1609 0, /* @tp_as_mapping@ */
1613 0, /* @tp_getattro@ */
1614 0, /* @tp_setattro@ */
1615 0, /* @tp_as_buffer@ */
1616 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1617 Py_TPFLAGS_BASETYPE
,
1620 "MPBarrett(N): a Barrett reduction context.",
1622 0, /* @tp_traverse@ */
1624 0, /* @tp_richcompare@ */
1625 0, /* @tp_weaklistoffset@ */
1627 0, /* @tp_iternext@ */
1628 PYMETHODS(mpbarrett
), /* @tp_methods@ */
1629 0, /* @tp_members@ */
1630 PYGETSET(mpbarrett
), /* @tp_getset@ */
1633 0, /* @tp_descr_get@ */
1634 0, /* @tp_descr_set@ */
1635 0, /* @tp_dictoffset@ */
1637 PyType_GenericAlloc
, /* @tp_alloc@ */
1638 mpbarrett_pynew
, /* @tp_new@ */
1643 /*----- Nice prime reduction ----------------------------------------------*/
1645 static PyTypeObject
*mpreduce_pytype
;
1647 typedef struct mpreduce_pyobj
{
1652 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1654 static PyObject
*mrmeth_exp(PyObject
*me
, PyObject
*arg
)
1657 mp
*yy
= 0, *zz
= 0;
1659 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convmp
, &yy
, convmp
, &zz
))
1662 if ((yy
= mp_modinv_checked(yy
, yy
, MPREDUCE_PY(me
)->p
)) == 0) goto end
;
1663 zz
= mp_neg(zz
, zz
);
1665 rc
= mp_pywrap(mpreduce_exp(MPREDUCE_PY(me
), MP_NEW
, yy
, zz
));
1667 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
1671 static PyObject
*mrmeth_reduce(PyObject
*me
, PyObject
*arg
)
1676 if (!PyArg_ParseTuple(arg
, "O&:reduce", convmp
, &yy
)) goto end
;
1677 z
= mp_pywrap(mpreduce_do(MPREDUCE_PY(me
), MP_NEW
, yy
));
1682 static void mpreduce_pydealloc(PyObject
*me
)
1684 mpreduce_destroy(MPREDUCE_PY(me
));
1688 static PyObject
*mpreduce_pynew(PyTypeObject
*ty
,
1689 PyObject
*arg
, PyObject
*kw
)
1691 mpreduce_pyobj
*mr
= 0;
1693 static const char *const kwlist
[] = { "m", 0 };
1696 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convmp
, &xx
))
1698 if (!MP_POSP(xx
)) VALERR("m must be positive");
1699 if (mpreduce_create(&r
, xx
)) VALERR("bad modulus (must be 2^k - ...)");
1700 mr
= (mpreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
1703 if (xx
) MP_DROP(xx
);
1704 return ((PyObject
*)mr
);
1707 static PyObject
*mrget_m(PyObject
*me
, void *hunoz
)
1708 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me
)->p
))); }
1710 static const PyGetSetDef mpreduce_pygetset
[] = {
1711 #define GETSETNAME(op, name) mr##op##_##name
1712 GET (m
, "R.m -> modulus for reduction")
1717 static const const PyMethodDef mpreduce_pymethods
[] = {
1718 #define METHNAME(name) mrmeth_##name
1719 METH (reduce
, "R.reduce(X) -> X mod B.m")
1720 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
1725 static const PyTypeObject mpreduce_pytype_skel
= {
1726 PyVarObject_HEAD_INIT(0, 0) /* Header */
1727 "MPReduce", /* @tp_name@ */
1728 sizeof(mpreduce_pyobj
), /* @tp_basicsize@ */
1729 0, /* @tp_itemsize@ */
1731 mpreduce_pydealloc
, /* @tp_dealloc@ */
1733 0, /* @tp_getattr@ */
1734 0, /* @tp_setattr@ */
1735 0, /* @tp_compare@ */
1737 0, /* @tp_as_number@ */
1738 0, /* @tp_as_sequence@ */
1739 0, /* @tp_as_mapping@ */
1743 0, /* @tp_getattro@ */
1744 0, /* @tp_setattro@ */
1745 0, /* @tp_as_buffer@ */
1746 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1747 Py_TPFLAGS_BASETYPE
,
1750 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1752 0, /* @tp_traverse@ */
1754 0, /* @tp_richcompare@ */
1755 0, /* @tp_weaklistoffset@ */
1757 0, /* @tp_iternext@ */
1758 PYMETHODS(mpreduce
), /* @tp_methods@ */
1759 0, /* @tp_members@ */
1760 PYGETSET(mpreduce
), /* @tp_getset@ */
1763 0, /* @tp_descr_get@ */
1764 0, /* @tp_descr_set@ */
1765 0, /* @tp_dictoffset@ */
1767 PyType_GenericAlloc
, /* @tp_alloc@ */
1768 mpreduce_pynew
, /* @tp_new@ */
1773 /*----- Chinese Remainder Theorem solution --------------------------------*/
1775 static PyTypeObject
*mpcrt_pytype
;
1777 typedef struct mpcrt_pyobj
{
1782 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1784 static PyObject
*mcmeth_solve(PyObject
*me
, PyObject
*arg
)
1786 mpcrt
*c
= MPCRT_PY(me
);
1787 PyObject
*q
= 0, *x
, *z
= 0;
1790 Py_ssize_t i
= 0, n
= c
->k
;
1792 if (PyTuple_GET_SIZE(arg
) == n
)
1794 else if (!PyArg_ParseTuple(arg
, "O:solve", &q
))
1796 if (!PySequence_Check(q
)) TYERR("want a sequence of residues");
1797 i
= PySequence_Size(q
); if (i
< 0) goto end
;
1798 if (i
!= n
) VALERR("residue count mismatch");
1799 v
= xmalloc(n
* sizeof(*v
));
1800 for (i
= 0; i
< n
; i
++) {
1801 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1802 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1805 z
= mp_pywrap(mpcrt_solve(c
, MP_NEW
, v
));
1808 while (i
--) MP_DROP(v
[i
]);
1814 static void mpcrt_pydealloc(PyObject
*me
)
1816 mpcrt
*c
= MPCRT_PY(me
);
1821 static PyObject
*mpcrt_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1824 Py_ssize_t n
, i
= 0, j
;
1825 static const char *const kwlist
[] = { "mv", 0 };
1826 PyObject
*q
= 0, *x
;
1827 mp
*xx
= MP_NEW
, *y
= MP_NEW
, *g
= MP_NEW
;
1831 if (PyTuple_GET_SIZE(arg
) > 1)
1833 else if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O:new", KWLIST
, &q
))
1835 if (!PySequence_Check(q
)) TYERR("want a sequence of moduli");
1836 n
= PySequence_Size(q
); if (n
< 0) goto end
;
1837 if (!n
) VALERR("want at least one modulus");
1838 v
= xmalloc(n
* sizeof(*v
));
1839 for (i
= 0; i
< n
; i
++) {
1840 if ((x
= PySequence_GetItem(q
, i
)) == 0) goto end
;
1841 xx
= getmp(x
); Py_DECREF(x
); if (!xx
) goto end
;
1842 if (MP_CMP(xx
, <=, MP_ZERO
)) VALERR("moduli must be positive");
1843 v
[i
].m
= xx
; v
[i
].n
= 0; v
[i
].ni
= 0; v
[i
].nni
= 0; xx
= MP_NEW
;
1846 for (j
= 0; j
< i
; j
++) mpmul_add(&mm
, v
[j
].m
);
1847 xx
= mpmul_done(&mm
);
1848 for (j
= 0; j
< i
; j
++) {
1849 mp_div(&y
, 0, xx
, v
[j
].m
);
1850 mp_gcd(&g
, 0, 0, y
, v
[j
].m
);
1851 if (!MP_EQ(g
, MP_ONE
)) VALERR("moduli must be pairwise coprime");
1854 c
= (mpcrt_pyobj
*)ty
->tp_alloc(ty
, 0);
1855 mpcrt_create(&c
->c
, v
, n
, 0);
1856 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1857 return ((PyObject
*)c
);
1861 while (i
--) MP_DROP(v
[i
].m
);
1864 mp_drop(xx
); mp_drop(y
); mp_drop(g
);
1868 static PyObject
*mcget_product(PyObject
*me
, void *hunoz
)
1869 { return (mp_pywrap(MP_COPY(MPCRT_PY(me
)->mb
.m
))); }
1871 static PyObject
*mcget_moduli(PyObject
*me
, void *hunoz
)
1875 mpcrt
*c
= MPCRT_PY(me
);
1877 if ((q
= PyList_New(c
->k
)) == 0) return (0);
1878 for (i
= 0; i
< c
->k
; i
++)
1879 PyList_SET_ITEM(q
, i
, mp_pywrap(c
->v
[i
].m
));
1883 static const PyGetSetDef mpcrt_pygetset
[] = {
1884 #define GETSETNAME(op, name) mc##op##_##name
1885 GET (product
, "C.product -> product of moduli")
1886 GET (moduli
, "C.moduli -> list of individual moduli")
1891 static const PyMethodDef mpcrt_pymethods
[] = {
1892 #define METHNAME(name) mcmeth_##name
1893 METH (solve
, "C.solve([R0, R1]) -> X mod C.product")
1898 static const PyTypeObject mpcrt_pytype_skel
= {
1899 PyVarObject_HEAD_INIT(0, 0) /* Header */
1900 "MPCRT", /* @tp_name@ */
1901 sizeof(mpcrt_pyobj
), /* @tp_basicsize@ */
1902 0, /* @tp_itemsize@ */
1904 mpcrt_pydealloc
, /* @tp_dealloc@ */
1906 0, /* @tp_getattr@ */
1907 0, /* @tp_setattr@ */
1908 0, /* @tp_compare@ */
1910 0, /* @tp_as_number@ */
1911 0, /* @tp_as_sequence@ */
1912 0, /* @tp_as_mapping@ */
1916 0, /* @tp_getattro@ */
1917 0, /* @tp_setattro@ */
1918 0, /* @tp_as_buffer@ */
1919 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
1920 Py_TPFLAGS_BASETYPE
,
1923 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1925 0, /* @tp_traverse@ */
1927 0, /* @tp_richcompare@ */
1928 0, /* @tp_weaklistoffset@ */
1930 0, /* @tp_iternext@ */
1931 PYMETHODS(mpcrt
), /* @tp_methods@ */
1932 0, /* @tp_members@ */
1933 PYGETSET(mpcrt
), /* @tp_getset@ */
1936 0, /* @tp_descr_get@ */
1937 0, /* @tp_descr_set@ */
1938 0, /* @tp_dictoffset@ */
1940 PyType_GenericAlloc
, /* @tp_alloc@ */
1941 mpcrt_pynew
, /* @tp_new@ */
1946 /*----- Binary polynomials ------------------------------------------------*/
1948 static PyObject
*gf_pyrepr(PyObject
*o
)
1949 { return mp_topystring(MP_X(o
), 16, "GF(", "0x", ")"); }
1951 static PyObject
*gf_pyrichcompare(PyObject
*x
, PyObject
*y
, int op
)
1957 if (gfbinop(x
, y
, &xx
, &yy
)) RETURN_NOTIMPL
;
1959 case Py_EQ
: b
= MP_EQ(xx
, yy
); break;
1960 case Py_NE
: b
= !MP_EQ(xx
, yy
); break;
1965 case Py_LT
: b
= xl
< yl
; break;
1966 case Py_LE
: b
= xl
<= yl
; break;
1967 case Py_GT
: b
= xl
> yl
; break;
1968 case Py_GE
: b
= xl
>= yl
; break;
1973 MP_DROP(xx
); MP_DROP(yy
);
1974 return (getbool(b
));
1977 static PyObject
*gf_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
1983 static const char *const kwlist
[] = { "x", "radix", 0 };
1985 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|i:gf", KWLIST
, &x
, &radix
))
1987 if (GF_PYCHECK(x
)) RETURN_OBJ(x
);
1988 if (!good_radix_p(radix
, 1)) VALERR("radix out of range");
1989 if ((z
= mp_frompyobject(x
, radix
)) == 0) {
1990 PyErr_Format(PyExc_TypeError
, "can't convert %.100s to gf",
1991 Py_TYPE(x
)->tp_name
);
1996 VALERR("gf cannot be negative");
1998 zz
= (mp_pyobj
*)ty
->tp_alloc(ty
, 0);
2001 return ((PyObject
*)zz
);
2004 static PyObject
*gf_pyexp(PyObject
*x
, PyObject
*y
, PyObject
*z
)
2006 mp
*xx
= 0, *yy
= 0, *zz
= 0;
2010 if ((xx
= implicitgf(x
)) == 0 || (yy
= implicitmp(y
)) == 0 ||
2011 (z
&& z
!= Py_None
&& (zz
= implicitgf(z
)) == 0)) {
2012 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2015 if (!z
|| z
== Py_None
) {
2016 if (MP_NEGP(yy
)) VALERR("negative exponent");
2017 r
= gf_exp(MP_NEW
, xx
, yy
);
2020 if (MP_ZEROP(zz
)) ZDIVERR("zero modulus");
2022 if ((xx
= gf_modinv_checked(xx
, xx
, zz
)) == 0) goto end
;
2023 yy
= mp_neg(yy
, yy
);
2025 gfreduce_create(&gr
, zz
);
2026 r
= gfreduce_exp(&gr
, MP_NEW
, xx
, yy
);
2027 gfreduce_destroy(&gr
);
2031 mp_drop(xx
); mp_drop(yy
); mp_drop(zz
);
2035 static PyObject
*gfmeth_sqr(PyObject
*me
)
2036 { return (gf_pywrap(gf_sqr(MP_NEW
, MP_X(me
)))); }
2038 static PyObject
*gfmeth_gcd(PyObject
*me
, PyObject
*arg
)
2041 mp
*yy
= 0, *zz
= MP_NEW
;
2043 if (!PyArg_ParseTuple(arg
, "O&:gcd", convgf
, &yy
)) goto end
;
2044 gf_gcd(&zz
, 0, 0, MP_X(me
), yy
);
2047 if (yy
) MP_DROP(yy
);
2051 static PyObject
*gfmeth_gcdx(PyObject
*me
, PyObject
*arg
)
2054 mp
*yy
= 0, *zz
= MP_NEW
, *uu
= MP_NEW
, *vv
= MP_NEW
;
2056 if (!PyArg_ParseTuple(arg
, "O&:gcdx", convgf
, &yy
))
2058 gf_gcd(&zz
, &uu
, &vv
, MP_X(me
), yy
);
2059 z
= Py_BuildValue("(NNN)",
2060 gf_pywrap(zz
), gf_pywrap(uu
), gf_pywrap(vv
));
2062 if (yy
) MP_DROP(yy
);
2066 static PyObject
*gfmeth_modinv(PyObject
*me
, PyObject
*arg
)
2069 mp
*yy
= 0, *zz
= MP_NEW
;
2071 if (!PyArg_ParseTuple(arg
, "O&:modinv", convgf
, &yy
) ||
2072 (zz
= gf_modinv_checked(MP_NEW
, yy
, MP_X(me
))) == 0)
2076 if (yy
) MP_DROP(yy
);
2080 static PyObject
*gfmeth_fromstring(PyObject
*me
,
2081 PyObject
*arg
, PyObject
*kw
)
2088 mptext_stringctx sc
;
2089 static const char *const kwlist
[] = { "x", "radix", 0 };
2091 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "s#|i:fromstring", KWLIST
,
2094 if (!good_radix_p(r
, 1)) VALERR("bad radix");
2095 sc
.buf
= p
; sc
.lim
= p
+ len
;
2096 if ((zz
= mp_read(MP_NEW
, r
, &mptext_stringops
, &sc
)) == 0 ||
2098 if (zz
) MP_DROP(zz
);
2099 VALERR("bad binary polynomial");
2101 z
= Py_BuildValue("(Ns#)", gf_pywrap(zz
),
2102 sc
.buf
, (Py_ssize_t
)(sc
.lim
- sc
.buf
));
2107 static PyObject
*gfmeth_irreduciblep(PyObject
*me
)
2108 { return getbool(gf_irreduciblep(MP_X(me
))); }
2110 static PyObject
*gfget_degree(PyObject
*me
, void *hunoz
)
2111 { return (PyInt_FromLong(mp_bits(MP_X(me
)) - 1)); }
2113 static const PyGetSetDef gf_pygetset
[] = {
2114 #define GETSETNAME(op, name) gf##op##_##name
2115 GET (degree
, "X.degree -> polynomial degree of X")
2117 #define GETSETNAME(op, name) mp##op##_##name
2118 GET (nbits
, "X.nbits -> bit length of X")
2119 GET (noctets
, "X.noctets -> octet length of X")
2124 static const PyMethodDef gf_pymethods
[] = {
2125 #define METHNAME(func) gfmeth_##func
2126 METH (setbit
, "X.setbit(N) -> X with bit N set")
2127 METH (clearbit
, "X.clearbit(N) -> X with bit N clear")
2128 METH (testbit
, "X.testbit(N) -> true/false if bit N set/clear in X")
2129 NAMETH(sqr
, "X.sqr() -> X^2")
2130 METH (gcd
, "X.gcd(Y) -> gcd(X, Y)")
2131 METH (gcdx
, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2132 METH (modinv
, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2133 NAMETH(irreduciblep
, "X.irreduciblep() -> true/false")
2134 KWSMTH(fromstring
, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2135 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2136 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2137 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2139 SMTH (loadl
, "loadl(STR) -> X: read little-endian bytes")
2140 SMTH (loadb
, "loadb(STR) -> X: read big-endian bytes")
2141 SMTH (frombuf
, "frombuf(STR) -> (X, REST): read buffer format")
2143 #define METHNAME(func) mpmeth_##func
2144 KWMETH(tostring
, "X.tostring([radix = 10]) -> STR")
2145 KWMETH(storel
, "X.storel([len = -1]) -> little-endian bytes")
2146 KWMETH(storeb
, "X.storeb([len = -1]) -> big-endian bytes")
2147 KWMETH(storel2c
, "X.storel2c([len = -1]) -> "
2148 "little-endian bytes, two's complement")
2149 KWMETH(storeb2c
, "X.storeb2c([len = -1]) -> "
2150 "big-endian bytes, two's complement")
2151 NAMETH(tobuf
, "X.tobuf() -> buffer format")
2156 static const PyNumberMethods gf_pynumber
= {
2157 gf_pyadd
, /* @nb_add@ */
2158 gf_pysub
, /* @nb_subtract@ */
2159 gf_pymul
, /* @nb_multiply@ */
2161 0, /* @nb_divide@ */
2163 gf_pymod
, /* @nb_remainder@ */
2164 gf_pydivmod
, /* @nb_divmod@ */
2165 gf_pyexp
, /* @nb_power@ */
2166 mp_pyid
, /* @nb_negative@ */
2167 mp_pyid
, /* @nb_positive@ */
2168 mp_pyid
, /* @nb_absolute@ */
2169 mp_pynonzerop
, /* @nb_nonzero@ */
2170 0 /* doesn't make any sense */, /* @nb_invert@ */
2171 gf_pylsl
, /* @nb_lshift@ */
2172 gf_pylsr
, /* @nb_rshift@ */
2173 gf_pyand
, /* @nb_and@ */
2174 gf_pyxor
, /* @nb_xor@ */
2175 gf_pyor
, /* @nb_or@ */
2177 gf_pycoerce
, /* @nb_coerce@ */
2179 mp_pyint
, /* @nb_int@ */
2180 PY23(mp_pylong
, 0), /* @nb_long@ */
2181 0 /* doesn't make any sense */, /* @nb_float@ */
2183 mp_pyoct
, /* @nb_oct@ */
2184 mp_pyhex
, /* @nb_hex@ */
2187 0, /* @nb_inplace_add@ */
2188 0, /* @nb_inplace_subtract@ */
2189 0, /* @nb_inplace_multiply@ */
2191 0, /* @nb_inplace_divide@ */
2193 0, /* @nb_inplace_remainder@ */
2194 0, /* @nb_inplace_power@ */
2195 0, /* @nb_inplace_lshift@ */
2196 0, /* @nb_inplace_rshift@ */
2197 0, /* @nb_inplace_and@ */
2198 0, /* @nb_inplace_xor@ */
2199 0, /* @nb_inplace_or@ */
2201 gf_pydiv
, /* @nb_floor_divide@ */
2202 0, /* @nb_true_divide@ */
2203 0, /* @nb_inplace_floor_divide@ */
2204 0, /* @nb_inplace_true_divide@ */
2206 mp_pyint
, /* @nb_index@ */
2209 static const PyTypeObject gf_pytype_skel
= {
2210 PyVarObject_HEAD_INIT(0, 0) /* Header */
2211 "GF", /* @tp_name@ */
2212 sizeof(mp_pyobj
), /* @tp_basicsize@ */
2213 0, /* @tp_itemsize@ */
2215 mp_pydealloc
, /* @tp_dealloc@ */
2217 0, /* @tp_getattr@ */
2218 0, /* @tp_setattr@ */
2219 0, /* @tp_compare@ */
2220 gf_pyrepr
, /* @tp_repr@ */
2221 PYNUMBER(gf
), /* @tp_as_number@ */
2222 0, /* @tp_as_sequence@ */
2223 0, /* @tp_as_mapping@ */
2224 mp_pyhash
, /* @tp_hash@ */
2226 mp_pyhex
, /* @tp_str@ */
2227 0, /* @tp_getattro@ */
2228 0, /* @tp_setattro@ */
2229 0, /* @tp_as_buffer@ */
2230 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2231 Py_TPFLAGS_CHECKTYPES
|
2232 Py_TPFLAGS_BASETYPE
,
2235 "Binary polynomials. Support almost all the standard arithmetic\n"
2238 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2239 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2240 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2242 "points, group elements, Python `int' and `long' objects, and anything\n"
2243 "with an integer conversion.\n",
2244 "points, group elements, Python `int' objects, and anything with an\n"
2245 "integer conversion.\n")
2247 "The name is hopelessly wrong from a technical point of view, but\n"
2248 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2252 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2254 0, /* @tp_traverse@ */
2256 gf_pyrichcompare
, /* @tp_richcompare@ */
2257 0, /* @tp_weaklistoffset@ */
2259 0, /* @tp_iternext@ */
2260 PYMETHODS(gf
), /* @tp_methods@ */
2261 0, /* @tp_members@ */
2262 PYGETSET(gf
), /* @tp_getset@ */
2265 0, /* @tp_descr_get@ */
2266 0, /* @tp_descr_set@ */
2267 0, /* @tp_dictoffset@ */
2269 PyType_GenericAlloc
, /* @tp_alloc@ */
2270 gf_pynew
, /* @tp_new@ */
2275 /*----- Sparse poly reduction ---------------------------------------------*/
2277 static PyTypeObject
*gfreduce_pytype
;
2279 typedef struct gfreduce_pyobj
{
2284 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2286 static PyObject
*grmeth_exp(PyObject
*me
, PyObject
*arg
)
2289 mp
*yy
= 0, *zz
= 0;
2291 if (!PyArg_ParseTuple(arg
, "O&O&:exp", convgf
, &yy
, convgf
, &zz
))
2294 if ((yy
= gf_modinv_checked(yy
, yy
, GFREDUCE_PY(me
)->p
)) == 0) goto end
;
2295 zz
= mp_neg(zz
, zz
);
2297 rc
= gf_pywrap(gfreduce_exp(GFREDUCE_PY(me
), MP_NEW
, yy
, zz
));
2299 if (yy
) MP_DROP(yy
); if (zz
) MP_DROP(zz
);
2303 static PyObject
*grmeth_trace(PyObject
*me
, PyObject
*arg
)
2308 if (!PyArg_ParseTuple(arg
, "O&:trace", convgf
, &xx
)) goto end
;
2309 rc
= PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me
), xx
));
2311 if (xx
) MP_DROP(xx
);
2315 static PyObject
*grmeth_halftrace(PyObject
*me
, PyObject
*arg
)
2320 if (!PyArg_ParseTuple(arg
, "O&:halftrace", convgf
, &xx
)) goto end
;
2321 rc
= gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me
), MP_NEW
, xx
));
2323 if (xx
) MP_DROP(xx
);
2327 static PyObject
*grmeth_sqrt(PyObject
*me
, PyObject
*arg
)
2332 if (!PyArg_ParseTuple(arg
, "O&:sqrt", convgf
, &xx
)) goto end
;
2333 if ((yy
= gfreduce_sqrt(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2334 VALERR("no modular square root");
2337 if (xx
) MP_DROP(xx
);
2341 static PyObject
*grmeth_quadsolve(PyObject
*me
, PyObject
*arg
)
2346 if (!PyArg_ParseTuple(arg
, "O&:quadsolve", convgf
, &xx
)) goto end
;
2347 if ((yy
= gfreduce_quadsolve(GFREDUCE_PY(me
), MP_NEW
, xx
)) == 0)
2348 VALERR("no solution found");
2351 if (xx
) MP_DROP(xx
);
2355 static PyObject
*grmeth_reduce(PyObject
*me
, PyObject
*arg
)
2360 if (!PyArg_ParseTuple(arg
, "O&:reduce", convgf
, &yy
)) goto end
;
2361 z
= gf_pywrap(gfreduce_do(GFREDUCE_PY(me
), MP_NEW
, yy
));
2366 static void gfreduce_pydealloc(PyObject
*me
)
2368 gfreduce_destroy(GFREDUCE_PY(me
));
2372 static PyObject
*gfreduce_pynew(PyTypeObject
*ty
,
2373 PyObject
*arg
, PyObject
*kw
)
2375 gfreduce_pyobj
*mr
= 0;
2377 static const char *const kwlist
[] = { "m", 0 };
2380 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&:new", KWLIST
, convgf
, &xx
))
2382 if (MP_ZEROP(xx
)) ZDIVERR("modulus is zero!");
2383 gfreduce_create(&r
, xx
);
2384 mr
= (gfreduce_pyobj
*)ty
->tp_alloc(ty
, 0);
2387 if (xx
) MP_DROP(xx
);
2388 return ((PyObject
*)mr
);
2391 static PyObject
*grget_m(PyObject
*me
, void *hunoz
)
2392 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me
)->p
))); }
2394 static const PyGetSetDef gfreduce_pygetset
[] = {
2395 #define GETSETNAME(op, name) gr##op##_##name
2396 GET (m
, "R.m -> reduction polynomial")
2401 static const PyMethodDef gfreduce_pymethods
[] = {
2402 #define METHNAME(name) grmeth_##name
2403 METH (reduce
, "R.reduce(X) -> X mod B.m")
2404 METH (trace
, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2405 METH (halftrace
, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2406 METH (sqrt
, "R.sqrt(X) -> Y where Y^2 = X mod R")
2407 METH (quadsolve
, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2408 METH (exp
, "R.exp(X, N) -> X^N mod B.m")
2413 static const PyTypeObject gfreduce_pytype_skel
= {
2414 PyVarObject_HEAD_INIT(0, 0) /* Header */
2415 "GFReduce", /* @tp_name@ */
2416 sizeof(gfreduce_pyobj
), /* @tp_basicsize@ */
2417 0, /* @tp_itemsize@ */
2419 gfreduce_pydealloc
, /* @tp_dealloc@ */
2421 0, /* @tp_getattr@ */
2422 0, /* @tp_setattr@ */
2423 0, /* @tp_compare@ */
2425 0, /* @tp_as_number@ */
2426 0, /* @tp_as_sequence@ */
2427 0, /* @tp_as_mapping@ */
2431 0, /* @tp_getattro@ */
2432 0, /* @tp_setattro@ */
2433 0, /* @tp_as_buffer@ */
2434 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2435 Py_TPFLAGS_BASETYPE
,
2438 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2440 0, /* @tp_traverse@ */
2442 0, /* @tp_richcompare@ */
2443 0, /* @tp_weaklistoffset@ */
2445 0, /* @tp_iternext@ */
2446 PYMETHODS(gfreduce
), /* @tp_methods@ */
2447 0, /* @tp_members@ */
2448 PYGETSET(gfreduce
), /* @tp_getset@ */
2451 0, /* @tp_descr_get@ */
2452 0, /* @tp_descr_set@ */
2453 0, /* @tp_dictoffset@ */
2455 PyType_GenericAlloc
, /* @tp_alloc@ */
2456 gfreduce_pynew
, /* @tp_new@ */
2461 /*----- Normal/poly transformation ----------------------------------------*/
2463 static PyTypeObject
*gfn_pytype
;
2465 typedef struct gfn_pyobj
{
2471 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2472 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2473 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2475 static PyObject
*gfn_pynew(PyTypeObject
*ty
, PyObject
*arg
, PyObject
*kw
)
2477 mp
*p
= 0, *beta
= 0;
2479 static const char *const kwlist
[] = { "p", "beta", 0 };
2481 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O&O&:new", KWLIST
,
2482 convgf
, &p
, convgf
, &beta
))
2484 gg
= PyObject_New(gfn_pyobj
, ty
);
2486 if (gfn_create(p
, beta
, &gg
->ntop
, &gg
->pton
)) {
2489 VALERR("can't invert transformation matrix");
2495 return ((PyObject
*)gg
);
2498 static PyObject
*gfnget_p(PyObject
*me
, void *hunoz
)
2499 { return (gf_pywrap(MP_COPY(GFN_P(me
)))); }
2501 static PyObject
*gfnget_beta(PyObject
*me
, void *hunoz
)
2503 gfn
*n
= GFN_NTOP(me
);
2504 mp
*x
= n
->r
[n
->n
- 1];
2505 return (gf_pywrap(MP_COPY(x
)));
2508 #define XFORMOP(name, NAME) \
2509 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2514 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2515 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2518 if (!z) return (0); \
2519 return (gf_pywrap(z)); \
2525 static void gfn_pydealloc(PyObject
*me
)
2529 gfn_destroy(GFN_PTON(me
));
2530 gfn_destroy(GFN_NTOP(me
));
2535 static const PyGetSetDef gfn_pygetset
[] = {
2536 #define GETSETNAME(op, name) gfn##op##_##name
2537 GET (p
, "X.p -> polynomial basis, as polynomial")
2538 GET (beta
, "X.beta -> normal basis element, in poly form")
2543 static const PyMethodDef gfn_pymethods
[] = {
2544 #define METHNAME(name) gfnmeth_##name
2545 METH (pton
, "X.pton(A) -> normal-basis representation of A")
2546 METH (ntop
, "X.ntop(A) -> polynomial-basis representation of A")
2551 static const PyTypeObject gfn_pytype_skel
= {
2552 PyVarObject_HEAD_INIT(0, 0) /* Header */
2553 "GFN", /* @tp_name@ */
2554 sizeof(gfn_pyobj
), /* @tp_basicsize@ */
2555 0, /* @tp_itemsize@ */
2557 gfn_pydealloc
, /* @tp_dealloc@ */
2559 0, /* @tp_getattr@ */
2560 0, /* @tp_setattr@ */
2561 0, /* @tp_compare@ */
2563 0, /* @tp_as_number@ */
2564 0, /* @tp_as_sequence@ */
2565 0, /* @tp_as_mapping@ */
2569 0, /* @tp_getattro@ */
2570 0, /* @tp_setattro@ */
2571 0, /* @tp_as_buffer@ */
2572 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
2573 Py_TPFLAGS_BASETYPE
,
2576 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2577 " between polynomial and normal basis representations.",
2579 0, /* @tp_traverse@ */
2581 0, /* @tp_richcompare@ */
2582 0, /* @tp_weaklistoffset@ */
2584 0, /* @tp_iternext@ */
2585 PYMETHODS(gfn
), /* @tp_methods@ */
2586 0, /* @tp_members@ */
2587 PYGETSET(gfn
), /* @tp_getset@ */
2590 0, /* @tp_descr_get@ */
2591 0, /* @tp_descr_set@ */
2592 0, /* @tp_dictoffset@ */
2594 PyType_GenericAlloc
, /* @tp_alloc@ */
2595 gfn_pynew
, /* @tp_new@ */
2600 /*----- Glue --------------------------------------------------------------*/
2602 static const struct nameval consts
[] = {
2607 void mp_pyinit(void)
2611 INITTYPE(mpmul
, root
);
2612 INITTYPE(mpmont
, root
);
2613 INITTYPE(mpbarrett
, root
);
2614 INITTYPE(mpreduce
, root
);
2615 INITTYPE(mpcrt
, root
);
2616 INITTYPE(gfreduce
, root
);
2617 INITTYPE(gfn
, root
);
2620 void mp_pyinsert(PyObject
*mod
)
2622 INSERT("MP", mp_pytype
);
2623 INSERT("MPMul", mpmul_pytype
);
2624 INSERT("MPMont", mpmont_pytype
);
2625 INSERT("MPBarrett", mpbarrett_pytype
);
2626 INSERT("MPReduce", mpreduce_pytype
);
2627 INSERT("MPCRT", mpcrt_pytype
);
2628 INSERT("GF", gf_pytype
);
2629 INSERT("GFReduce", gfreduce_pytype
);
2630 INSERT("GFN", gfn_pytype
);
2631 setconstants(mod
, consts
);
2634 /*----- That's all, folks -------------------------------------------------*/