From 1323f0d030187f1838c533cf7043c310e6aa9298 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Niels=20M=C3=B6ller?= <nisse@lysator.liu.se>
Date: Wed, 11 Feb 1998 06:23:45 +0100
Subject: [PATCH] * modules/Gmp/mpz_glue.c (low_get_digits): Yet another bug...
 The number zero is special, it is represented with no mpz limbs at all, but
 should still produce one digit. In fact, this is the only number for which
 low_get_digits will produce a leading zero.

Rev: src/modules/Gmp/mpz_glue.c:1.29
Rev: src/modules/Gmp/testsuite.in:1.9
---
 src/modules/Gmp/mpz_glue.c   | 28 +++++++++++++++++-----------
 src/modules/Gmp/testsuite.in |  1 +
 2 files changed, 18 insertions(+), 11 deletions(-)

diff --git a/src/modules/Gmp/mpz_glue.c b/src/modules/Gmp/mpz_glue.c
index d23225f9c9..9fb66bf7ed 100644
--- a/src/modules/Gmp/mpz_glue.c
+++ b/src/modules/Gmp/mpz_glue.c
@@ -4,7 +4,7 @@
 ||| See the files COPYING and DISCLAIMER for more information.
 \*/
 #include "global.h"
-RCSID("$Id: mpz_glue.c,v 1.28 1998/02/11 03:32:44 nisse Exp $");
+RCSID("$Id: mpz_glue.c,v 1.29 1998/02/11 05:23:44 nisse Exp $");
 #include "gmp_machine.h"
 
 #if !defined(HAVE_LIBGMP)
@@ -169,10 +169,7 @@ static struct pike_string *low_get_digits(MP_INT *mpz, int base)
 #if 0
     mpz_t tmp;
 #endif
-    mp_limb_t *src;
-    unsigned char *dst;
 
-    
     if (mpz_sgn(mpz) < 0)
       error("only non-negative numbers can be converted to base 256.\n");
 #if 0
@@ -195,16 +192,25 @@ static struct pike_string *low_get_digits(MP_INT *mpz, int base)
     len = (mpz_sizeinbase(mpz, 2) + 7) / 8;
     s = begin_shared_string(len);
 
-    src=mpz->_mp_d;
-    dst=s->str+s->len;
-    while (len > 0)
+    if (!mpz->_mp_size)
     {
-       mp_limb_t x=*(src++);
-       for (i=0; i<sizeof(mp_limb_t); i++)
+      /* Zero is a special case. There are no limbs at all, but
+       * the size is still 1 bit, and one digit should be produced. */
+      if (len != 1)
+	fatal("mpz->low_get_digits: strange mpz state!\n");
+      s->str[0] = 0;
+    } else {
+      mp_limb_t *src = mpz->_mp_d;
+      unsigned char *dst = s->str+s->len;
+
+      while (len > 0)
+      {
+	mp_limb_t x=*(src++);
+	for (i=0; i<sizeof(mp_limb_t); i++)
 	  *(--dst)=x&0xff,x>>=8;
-       len-=sizeof(mp_limb_t);
+	len-=sizeof(mp_limb_t);
+      }
     }
-
     s = end_shared_string(s);
   }
   else
diff --git a/src/modules/Gmp/testsuite.in b/src/modules/Gmp/testsuite.in
index 267273f335..fcbf9cedfd 100644
--- a/src/modules/Gmp/testsuite.in
+++ b/src/modules/Gmp/testsuite.in
@@ -67,6 +67,7 @@ cond( [[ master()->resolv("Gmp")->mpz ]],
 
   test_true(catch(Gmp.mpz("abcd", 47)))
   test_true(catch(Gmp.mpz(-17)->digits(256)))
+  test_eq(Gmp.mpz(0)->digits(256), "\0");
   test_eq(Gmp.mpz(17)->digits(256), "\021");
   test_eq(Gmp.mpz(4711)->size(2), 13)
   test_true(catch(Gmp.mpz(17) + 18 + "19"))
-- 
GitLab