mptext.c: Fix hopeless incorrectness in raw base conversions.
authorMark Wooding <mdw@distorted.org.uk>
Thu, 1 Sep 2011 23:49:10 +0000 (00:49 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Thu, 1 Sep 2011 23:52:30 +0000 (00:52 +0100)
Both mp_write and mp_read are broken.  The former would write a digit
`0' for a zero input, and attempt to prefix its output with a `-' sign
on negative input, both of which are impossible to decode unambiguously.
The latter would skip leading whitespace characters, which makes
encodings beginning with certain bytes decode incorrectly.

Include tests for these cases, and fix the bugs.

mptext.c
tests/mptext

index ee73fed..8c00e34 100644 (file)
--- a/mptext.c
+++ b/mptext.c
@@ -136,8 +136,10 @@ mp *mp_read(mp *m, int radix, const mptext_ops *ops, void *p)
   /* --- Read an initial character --- */
 
   ch = ops->get(p);
   /* --- Read an initial character --- */
 
   ch = ops->get(p);
-  while (isspace(ch))
-    ch = ops->get(p);
+  if (radix >= 0) {
+    while (isspace(ch))
+      ch = ops->get(p);
+  }
 
   /* --- Handle an initial sign --- */
 
 
   /* --- Handle an initial sign --- */
 
@@ -657,7 +659,7 @@ int mp_write(mp *m, int radix, const mptext_ops *ops, void *p)
   int rc;
 
   if (MP_EQ(m, MP_ZERO))
   int rc;
 
   if (MP_EQ(m, MP_ZERO))
-    return (ops->put("0", 1, p));
+    return (ops->put(radix > 0 ? "0" : "\0", 1, p));
 
   /* --- Set various things up --- */
 
 
   /* --- Set various things up --- */
 
@@ -676,6 +678,7 @@ int mp_write(mp *m, int radix, const mptext_ops *ops, void *p)
   /* --- If the number is negative, sort that out --- */
 
   if (MP_NEGP(m)) {
   /* --- If the number is negative, sort that out --- */
 
   if (MP_NEGP(m)) {
+    assert(radix > 0);
     if (ops->put("-", 1, p))
       return (EOF);
     m->f &= ~MP_NEG;
     if (ops->put("-", 1, p))
       return (EOF);
     m->f &= ~MP_NEG;
index 952f7e0..ed9fb6a 100644 (file)
@@ -79,9 +79,12 @@ mptext-ascii {
 mptext-bin-in {
   -10 010203040506070809 10 123456789 "";
   -100 01172d4359 10 123456789 "";
 mptext-bin-in {
   -10 010203040506070809 10 123456789 "";
   -100 01172d4359 10 123456789 "";
+  -90 09124709 10 6713199 "";
 }
 
 mptext-bin-out {
   10 123456789 -10 010203040506070809 "";
   10 123456789 -100 01172d4359 "";
 }
 
 mptext-bin-out {
   10 123456789 -10 010203040506070809 "";
   10 123456789 -100 01172d4359 "";
+  10 6713199 -90 09124709 "";
+  10 0 -10 00 "";
 }
 }