New mini-gmp macro GMP_CMP?
Niels Möller
nisse at lysator.liu.se
Tue Nov 22 08:32:11 UTC 2016
I was looking at how to simplify mini-gmp's mpz_cmp_si. I considered
using mpz_cmpabs_ui to handle the case of both inputs negative, which
made it more consice but perhaps not clearer. Then I came up with the
following.
The pattern (un == 0) ? 0 : u->_mp_d[0] and variants are replaced by
calls to mpz_get_ui which does the same thing, and the pattern (a > b) -
(a < b) is replaced by a GMP_CMP macro.
Resulting context patch below, reducing the code size by a dozen of
lines. Do you think this is also an improvement in clarity?
/Niels
*** /tmp/extdiff.RPnb3V/gmp.afda1bbf3ee3/mini-gmp/mini-gmp.c 2016-11-22 09:18:29.455237339 +0100
--- /home/nisse/hack/gmp/mini-gmp/mini-gmp.c 2016-11-22 08:54:54.290548487 +0100
*************** see https://www.gnu.org/licenses/. */
*** 70,73 ****
--- 70,75 ----
#define GMP_MAX(a, b) ((a) > (b) ? (a) : (b))
+ #define GMP_CMP(a,b) (((a) > (b)) - ((a) < (b)))
+
#define gmp_assert_nocarry(x) do { \
mp_limb_t __cy = (x); \
*************** int
*** 1778,1784 ****
mpz_sgn (const mpz_t u)
{
! mp_size_t usize = u->_mp_size;
!
! return (usize > 0) - (usize < 0);
}
--- 1780,1784 ----
mpz_sgn (const mpz_t u)
{
! return GMP_CMP (u->_mp_size, 0);
}
*************** mpz_cmp_si (const mpz_t u, long v)
*** 1795,1805 ****
return 1;
else /* usize == -1 */
! {
! mp_limb_t ul = u->_mp_d[0];
! if ((mp_limb_t)GMP_NEG_CAST (unsigned long int, v) < ul)
! return -1;
! else
! return (mp_limb_t)GMP_NEG_CAST (unsigned long int, v) > ul;
! }
}
--- 1795,1799 ----
return 1;
else /* usize == -1 */
! return GMP_CMP (GMP_NEG_CAST (mp_limb_t, v), u->_mp_d[0]);
}
*************** mpz_cmp_ui (const mpz_t u, unsigned long
*** 1814,1821 ****
return -1;
else
! {
! mp_limb_t ul = (usize > 0) ? u->_mp_d[0] : 0;
! return (ul > v) - (ul < v);
! }
}
--- 1808,1812 ----
return -1;
else
! return GMP_CMP (mpz_get_ui (u), v);
}
*************** int
*** 1837,1849 ****
mpz_cmpabs_ui (const mpz_t u, unsigned long v)
{
! mp_size_t un = GMP_ABS (u->_mp_size);
! mp_limb_t ul;
!
! if (un > 1)
return 1;
!
! ul = (un == 1) ? u->_mp_d[0] : 0;
!
! return (ul > v) - (ul < v);
}
--- 1828,1835 ----
mpz_cmpabs_ui (const mpz_t u, unsigned long v)
{
! if (GMP_ABS (u->_mp_size) > 1)
return 1;
! else
! return GMP_CMP (mpz_get_ui (u), v);
}
--
Niels Möller. PGP-encrypted email is preferred. Keyid 368C6677.
Internet email is subject to wholesale government surveillance.
More information about the gmp-devel
mailing list