mp.c: Accept `0x', `0o' and `0b' prefixes on strings with explicit base.
authorMark Wooding <mdw@distorted.org.uk>
Mon, 25 Nov 2019 12:49:34 +0000 (12:49 +0000)
committerMark Wooding <mdw@distorted.org.uk>
Mon, 25 Nov 2019 17:51:33 +0000 (17:51 +0000)
Python itself does this, so it seems like a good idea.

mp.c
t/t-mp.py

diff --git a/mp.c b/mp.c
index 59fce83..3093c83 100644 (file)
--- a/mp.c
+++ b/mp.c
@@ -122,6 +122,12 @@ mp *mp_frompyobject(PyObject *o, int radix)
     mp *x;
     size_t sz;
     TEXT_PTRLEN(o, sc.buf, sz); sc.lim = sc.buf + sz;
+    if (sc.buf + 2 < sc.lim && sc.buf[0] == '0' &&
+       (radix == 16 ? (sc.buf[1] == 'x' || sc.buf[1] == 'X') :
+        radix ==  8 ? (sc.buf[1] == 'o' || sc.buf[1] == 'O') :
+        radix ==  2 ? (sc.buf[1] == 'b' || sc.buf[1] == 'B') :
+        0))
+      sc.buf += 2;
     x = mp_read(MP_NEW, radix, &mptext_stringops, &sc);
     if (!x) return (0);
     if (sc.buf < sc.lim) { MP_DROP(x); return (0); }
index 2cba8ec..9927c12 100644 (file)
--- a/t/t-mp.py
+++ b/t/t-mp.py
@@ -56,14 +56,17 @@ class TestMP (U.TestCase):
     me.assertEqual(C.MP(str(big)), big)
     me.assertEqual(C.MP('0x4eeb684a0954ec4ceb255e3e9778d41'), big)
     me.assertEqual(C.MP('4eeb684a0954ec4ceb255e3e9778d41', 16), big)
+    me.assertEqual(C.MP('0x4eeb684a0954ec4ceb255e3e9778d41', 16), big)
     me.assertEqual(C.MP('0b0', 16), 176) # not 0
 
     me.assertEqual(C.MP('047353320450112516611472622536175135706501'), big)
     me.assertEqual(C.MP('0o47353320450112516611472622536175135706501'), big)
     me.assertEqual(C.MP('047353320450112516611472622536175135706501', 8), big)
+    me.assertEqual(C.MP('0o47353320450112516611472622536175135706501', 8), big)
     me.assertEqual(C.MP('47353320450112516611472622536175135706501', 8), big)
 
     me.assertEqual(C.MP('0b100111011011001100000010001011'), 661438603)
+    me.assertEqual(C.MP('0b100111011011001100000010001011', 2), 661438603)
     me.assertEqual(C.MP('100111011011001100000010001011', 2), 661438603)
 
   def test_string(me):
@@ -411,15 +414,18 @@ class TestGF (U.TestCase):
 
     me.assertEqual(C.GF('0x4eeb684a0954ec4ceb255e3e9778d41'), y)
     me.assertEqual(C.GF('4eeb684a0954ec4ceb255e3e9778d41', 16), y)
+    me.assertEqual(C.GF('0x4eeb684a0954ec4ceb255e3e9778d41', 16), y)
     me.assertEqual(C.GF('0b0', 16), C.GF(176)) # not 0
 
     me.assertEqual(C.GF('047353320450112516611472622536175135706501'), y)
     me.assertEqual(C.GF('0o47353320450112516611472622536175135706501'), y)
     me.assertEqual(C.GF('047353320450112516611472622536175135706501', 8), y)
+    me.assertEqual(C.GF('0o47353320450112516611472622536175135706501', 8), y)
     me.assertEqual(C.GF('47353320450112516611472622536175135706501', 8), y)
 
     t = C.GF(661438603)
     me.assertEqual(C.GF('0b100111011011001100000010001011'), t)
+    me.assertEqual(C.GF('0b100111011011001100000010001011', 2), t)
     me.assertEqual(C.GF('100111011011001100000010001011', 2), t)
 
   def test_string(me):