mini-gmp "bug" missing mpz_fits_sint_p / mpz_fits_uint_p

Marco Bodrato bodrato at mail.dm.unipi.it
Sun Apr 19 07:53:04 UTC 2020


Ciao,

On the gmp-discuss list,

Il 2020-04-11 21:41 Simon Sobisch ha scritto:
> mini-gmp provides mpz_fits_slong_p ad  mpz_fits_uslingt_p, but it does
> not provide the same for smaller integer types.

We can easily add the requested functions. I suggest the following code:

diff -r 805304ca965a mini-gmp/mini-gmp.c
--- a/mini-gmp/mini-gmp.c       Tue Mar 24 23:13:28 2020 +0100
+++ b/mini-gmp/mini-gmp.c       Sun Apr 19 09:47:39 2020 +0200
@@ -1565,6 +1565,32 @@
    return us >= 0 && mpn_absfits_ulong_p (u->_mp_d, us);
  }

+int
+mpz_fits_sint_p (const mpz_t u)
+{
+  return (INT_MAX + INT_MIN == 0 || mpz_cmp_ui (u, INT_MAX) <= 0) &&
+    mpz_cmpabs_ui (u, GMP_NEG_CAST (unsigned long int, INT_MIN)) <= 0;
+}
+
+int
+mpz_fits_uint_p (const mpz_t u)
+{
+  return u->_mp_size >= 0 && mpz_cmpabs_ui (u, UINT_MAX) <= 0;
+}
+
+int
+mpz_fits_sshort_p (const mpz_t u)
+{
+  return (SHRT_MAX + SHRT_MIN == 0 || mpz_cmp_ui (u, SHRT_MAX) <= 0) &&
+    mpz_cmpabs_ui (u, GMP_NEG_CAST (unsigned long int, SHRT_MIN)) <= 0;
+}
+
+int
+mpz_fits_ushort_p (const mpz_t u)
+{
+  return u->_mp_size >= 0 && mpz_cmpabs_ui (u, USHRT_MAX) <= 0;
+}
+
  long int
  mpz_get_si (const mpz_t u)
  {
diff -r 805304ca965a mini-gmp/mini-gmp.h
--- a/mini-gmp/mini-gmp.h       Tue Mar 24 23:13:28 2020 +0100
+++ b/mini-gmp/mini-gmp.h       Sun Apr 19 09:47:39 2020 +0200
@@ -244,6 +244,10 @@

  int mpz_fits_slong_p (const mpz_t);
  int mpz_fits_ulong_p (const mpz_t);
+int mpz_fits_sint_p (const mpz_t);
+int mpz_fits_uint_p (const mpz_t);
+int mpz_fits_sshort_p (const mpz_t);
+int mpz_fits_ushort_p (const mpz_t);
  long int mpz_get_si (const mpz_t);
  unsigned long int mpz_get_ui (const mpz_t);
  double mpz_get_d (const mpz_t);


I attach a patch with also the tests (somehow redundant).

Ĝis,
m
-------------- next part --------------
A non-text attachment was scrubbed...
Name: mini-fits.patch
Type: text/x-diff
Size: 4960 bytes
Desc: not available
URL: <https://gmplib.org/list-archives/gmp-devel/attachments/20200419/2b35533e/attachment.bin>


More information about the gmp-devel mailing list