Skip to content

Commit bd3bc55

Browse files
committed
objint_mpz: Narrow result of 3-arg pow if possible.
Signed-off-by: Jeff Epler <[email protected]>
1 parent 18dcf04 commit bd3bc55

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

py/objint_mpz.c

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,18 @@ const mp_obj_int_t mp_sys_maxsize_obj = {
7474
#undef NUM_DIG
7575
#endif
7676

77+
static mp_obj_t mp_int_maybe_narrow(mp_obj_int_t *res) {
78+
// Check if the result fits in a small-int, and if so just return that.
79+
mp_int_t res_small;
80+
if (mpz_as_int_checked(&res->mpz, &res_small)) {
81+
if (MP_SMALL_INT_FITS(res_small)) {
82+
return MP_OBJ_NEW_SMALL_INT(res_small);
83+
}
84+
}
85+
86+
return MP_OBJ_FROM_PTR(res);
87+
}
88+
7789
mp_obj_int_t *mp_obj_int_new_mpz(void) {
7890
mp_obj_int_t *o = mp_obj_malloc(mp_obj_int_t, &mp_type_int);
7991
mpz_init_zero(&o->mpz);
@@ -312,16 +324,7 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i
312324
return MP_OBJ_NULL; // op not supported
313325
}
314326

315-
// Check if the result fits in a small-int, and if so just return that.
316-
mp_int_t res_small;
317-
if (mpz_as_int_checked(&res->mpz, &res_small)) {
318-
if (MP_SMALL_INT_FITS(res_small)) {
319-
return MP_OBJ_NEW_SMALL_INT(res_small);
320-
}
321-
}
322-
323-
return MP_OBJ_FROM_PTR(res);
324-
327+
return mp_int_maybe_narrow(res);
325328
} else {
326329
int cmp = mpz_cmp(zlhs, zrhs);
327330
switch (op) {
@@ -377,7 +380,8 @@ mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) {
377380
if (mod == &m_temp) {
378381
mpz_deinit(mod);
379382
}
380-
return MP_OBJ_FROM_PTR(res_p);
383+
384+
return mp_int_maybe_narrow(res_p);
381385
}
382386
}
383387
#endif

0 commit comments

Comments
 (0)