From 572b324afecc0a7cb2654caf1967e18c8bd813ec Mon Sep 17 00:00:00 2001 From: Mark Wooding Date: Fri, 2 Sep 2011 00:49:10 +0100 Subject: [PATCH] mptext.c: Fix hopeless incorrectness in raw base conversions. 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 | 9 ++++++--- tests/mptext | 3 +++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/mptext.c b/mptext.c index ee73fed..8c00e34 100644 --- 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); - while (isspace(ch)) - ch = ops->get(p); + if (radix >= 0) { + while (isspace(ch)) + ch = ops->get(p); + } /* --- 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)) - return (ops->put("0", 1, p)); + return (ops->put(radix > 0 ? "0" : "\0", 1, p)); /* --- 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)) { + assert(radix > 0); if (ops->put("-", 1, p)) return (EOF); m->f &= ~MP_NEG; diff --git a/tests/mptext b/tests/mptext index 952f7e0..ed9fb6a 100644 --- a/tests/mptext +++ b/tests/mptext @@ -79,9 +79,12 @@ mptext-ascii { 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 ""; + 10 6713199 -90 09124709 ""; + 10 0 -10 00 ""; } -- 2.11.0