Skip to content

Commit 58056b0

Browse files
committed
py: Fix handling of "0" mpz in some functions.
1 parent f5465b9 commit 58056b0

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

py/mpz.c

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,11 @@ void mpz_set(mpz_t *dest, const mpz_t *src) {
653653
}
654654

655655
void mpz_set_from_int(mpz_t *z, mp_int_t val) {
656+
if (val == 0) {
657+
z->len = 0;
658+
return;
659+
}
660+
656661
mpz_need_dig(z, MPZ_NUM_DIG_FOR_INT);
657662

658663
mp_uint_t uval;
@@ -709,19 +714,19 @@ typedef uint32_t mp_float_int_t;
709714
z->neg = u.p.sgn;
710715
if (u.p.exp == 0) {
711716
// value == 0 || value < 1
712-
mpz_init_zero(z);
717+
mpz_set_from_int(z, 0);
713718
} else if (u.p.exp == ((1 << EXP_SZ) - 1)) {
714719
// u.p.frc == 0 indicates inf, else NaN
715720
// should be handled by caller
716-
mpz_init_zero(z);
721+
mpz_set_from_int(z, 0);
717722
} else {
718723
const int adj_exp = (int)u.p.exp - ((1 << (EXP_SZ - 1)) - 1);
719724
if (adj_exp < 0) {
720725
// value < 1 , truncates to 0
721-
mpz_init_zero(z);
726+
mpz_set_from_int(z, 0);
722727
} else if (adj_exp == 0) {
723728
// 1 <= value < 2 , so truncates to 1
724-
mpz_init_from_int(z, 1);
729+
mpz_set_from_int(z, 1);
725730
} else {
726731
// 2 <= value
727732
const int dig_cnt = (adj_exp + 1 + (DIG_SIZE - 1)) / DIG_SIZE;
@@ -1353,7 +1358,7 @@ mp_int_t mpz_hash(const mpz_t *z) {
13531358
mp_int_t val = 0;
13541359
mpz_dig_t *d = z->dig + z->len;
13551360

1356-
while (--d >= z->dig) {
1361+
while (d-- > z->dig) {
13571362
val = (val << DIG_SIZE) | *d;
13581363
}
13591364

@@ -1368,7 +1373,7 @@ bool mpz_as_int_checked(const mpz_t *i, mp_int_t *value) {
13681373
mp_int_t val = 0;
13691374
mpz_dig_t *d = i->dig + i->len;
13701375

1371-
while (--d >= i->dig) {
1376+
while (d-- > i->dig) {
13721377
if (val > (~(WORD_MSBIT_HIGH) >> DIG_SIZE)) {
13731378
// will overflow
13741379
return false;
@@ -1393,7 +1398,7 @@ bool mpz_as_uint_checked(const mpz_t *i, mp_uint_t *value) {
13931398
mp_uint_t val = 0;
13941399
mpz_dig_t *d = i->dig + i->len;
13951400

1396-
while (--d >= i->dig) {
1401+
while (d-- > i->dig) {
13971402
if (val > (~(WORD_MSBIT_HIGH) >> (DIG_SIZE - 1))) {
13981403
// will overflow
13991404
return false;
@@ -1410,7 +1415,7 @@ mp_float_t mpz_as_float(const mpz_t *i) {
14101415
mp_float_t val = 0;
14111416
mpz_dig_t *d = i->dig + i->len;
14121417

1413-
while (--d >= i->dig) {
1418+
while (d-- > i->dig) {
14141419
val = val * DIG_BASE + *d;
14151420
}
14161421

0 commit comments

Comments
 (0)