mini-gmp "bug" missing mpz_fits_sint_p / mpz_fits_uint_p
Vincent Lefevre
vincent at vinc17.net
Mon Apr 20 13:44:35 UTC 2020
On 2020-04-20 15:25:54 +0200, Marco Bodrato wrote:
> Ciao,
>
> Il 2020-04-20 11:08 Vincent Lefevre ha scritto:
> > I think that in general, you should not write code that depends on
> > whether INT_MAX + INT_MIN == 0 or not (the constant INT_MAX + INT_MIN
> > might be useful in some rare cases, but I think that testing whether
> > this constant is 0 or not should be forbidden). This can mean that
>
> Forbidden? Really! :-D
>
> Anyway, using the numerical constant INT_MAX + INT_MIN is a good idea.
>
> What about the following version of the function? :-D
>
> int
> mpz_fits_sint_p (const mpz_t u)
> {
> return mpz_cmpabs_ui (u, (unsigned long) INT_MAX + (unsigned long)
> (u->_mp_size < 0 ? -(INT_MAX + INT_MIN) : 0)) <= 0;
> }
Here you do not test whether INT_MAX + INT_MIN is 0 or not, so this
is OK. However, after fixing the typo (i -> u),
int
mpz_fits_sint_p (const mpz_t u)
{
return mpz_cmp_si (u, INT_MAX) <= 0 && mpz_cmp_si (u, INT_MIN) >= 0;
}
is much more readable. And if you don't want 2 function calls,
int
mpz_fits_sint_p (const mpz_t u)
{
return u->_mp_size < 0 ? mpz_cmp_si (u, INT_MIN) >= 0
: mpz_cmp_si (u, INT_MAX) <= 0;
}
--
Vincent Lefèvre <vincent at vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)
More information about the gmp-devel
mailing list