field.c: Replace `tofe' by `implicitfe', calling `implicit{mp,gf}'.
authorMark Wooding <mdw@distorted.org.uk>
Sat, 23 Nov 2019 23:48:52 +0000 (23:48 +0000)
committerMark Wooding <mdw@distorted.org.uk>
Sat, 11 Apr 2020 11:49:31 +0000 (12:49 +0100)
If something converts to an integer, we allow converting it to a
prime-field element too; similarly, things that convert to polynomials
can convert to binary-field elements.  (Obviously, these conversions use
the canonical homomorphisms.)

field.c
t/t-convert.py

diff --git a/field.c b/field.c
index b29d8a9..9380678 100644 (file)
--- a/field.c
+++ b/field.c
@@ -107,23 +107,18 @@ PyObject *fe_pywrap(PyObject *fobj, mp *x)
   return ((PyObject *)z);
 }
 
-static mp *tofe(field *f, PyObject *o)
+static mp *implicitfe(field *f, PyObject *o)
 {
-  mp *x = 0, *y = 0;
-
-  if (FE_PYCHECK(o)) {
-    if (FE_F(o) != f && !field_samep(FE_F(o), f)) return (0);
-    y = MP_COPY(FE_X(o));
-  } else if ((x = tomp(o)) != 0) {
-    if (MP_ZEROP(x))
-      y = MP_COPY(f->zero);
-    else if (MP_EQ(x, MP_ONE))
-      y = MP_COPY(f->one);
-    else
-      y = F_IN(f, MP_NEW, x);
-    MP_DROP(x);
+  mp *x;
+
+  if (FE_PYCHECK(o) && FE_F(o) == f) return (MP_COPY(FE_X(o)));
+  switch (f->ops->ty) {
+    case FTY_PRIME: x = implicitmp(o); break;
+    case FTY_BINARY: x = implicitgf(o); break;
+    default: assert(!"huh?");
   }
-  return (y);
+  if (!x) return (0);
+  return (F_IN(f, MP_NEW, x));
 }
 
 /*----- Field elements ----------------------------------------------------*/
@@ -135,9 +130,9 @@ static int febinop(PyObject *x, PyObject *y,
   else if (FE_PYCHECK(y)) *fobj = FE_FOBJ(y);
   else return (-1);
   *f = FIELD_F(*fobj);
-  if ((*xx = tofe(*f, x)) == 0)
+  if ((*xx = implicitfe(*f, x)) == 0)
     return (-1);
-  if ((*yy = tofe(*f, y)) == 0) {
+  if ((*yy = implicitfe(*f, y)) == 0) {
     MP_DROP(*xx);
     return (-1);
   }
@@ -232,7 +227,7 @@ static int fe_pycoerce(PyObject **x, PyObject **y)
     Py_INCREF(*x); Py_INCREF(*y);
     return (0);
   }
-  if ((z = tofe(FE_F(*x), *y)) != 0) {
+  if ((z = implicitfe(FE_F(*x), *y)) != 0) {
     Py_INCREF(*x);
     *y = fe_pywrap(FE_FOBJ(*x), z);
     return (0);
index cadf7b5..dcf9d91 100644 (file)
@@ -106,8 +106,14 @@ class TestConvert (U.TestCase):
     me.assertEqual(C.GF(7) + kk(3), C.GF(4))
     me.assertEqual(kk(3) + C.GF(7), C.GF(4))
 
+    me.assertRaises(TypeError, T.add, k(3), 3.0)
     me.assertRaises(TypeError, T.add, k(3), kk(3))
     me.assertRaises(TypeError, T.add, kk(3), k(3))
+    me.assertRaises(TypeError, T.add, k(3), C.GF(7))
+    me.assertRaises(TypeError, T.add, C.GF(7), k(3))
+    me.assertRaises(TypeError, T.add, kk(3), 7.0)
+    me.assertRaises(TypeError, T.add, kk(3), C.MP(7))
+    me.assertRaises(TypeError, T.add, C.MP(7), kk(3))
 
 ###----- That's all, folks --------------------------------------------------