blob: bd7ca782dd4f722c2e677a1402440c1cb97f2274 [file] [log] [blame]
Austin Schuhbb1338c2024-06-15 19:31:16 -07001/* mpf_fits_u*_p -- test whether an mpf fits a C unsigned type.
2
3Copyright 2001, 2002, 2013, 2014 Free Software Foundation, Inc.
4
5This file is part of the GNU MP Library.
6
7The GNU MP Library is free software; you can redistribute it and/or modify
8it under the terms of either:
9
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
13
14or
15
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
19
20or both in parallel, as here.
21
22The GNU MP Library is distributed in the hope that it will be useful, but
23WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25for more details.
26
27You should have received copies of the GNU General Public License and the
28GNU Lesser General Public License along with the GNU MP Library. If not,
29see https://www.gnu.org/licenses/. */
30
31#include "gmp-impl.h"
32
33
34/* Notice this is equivalent to mpz_set_f + mpz_fits_u*_p. */
35
36int
37FUNCTION (mpf_srcptr f) __GMP_NOTHROW
38{
39 mp_size_t fn;
40 mp_srcptr fp;
41 mp_exp_t exp;
42 mp_limb_t fl;
43
44 exp = EXP(f);
45 if (exp < 1)
46 return 1; /* -1 < f < 1 truncates to zero, so fits */
47
48 fn = SIZ(f);
49 if (fn < 0) /* zero catched by exp == 0 */
50 return 0; /* negatives don't fit */
51
52 fp = PTR(f);
53
54 if (exp == 1)
55 {
56 fl = fp[fn-1];
57 }
58#if GMP_NAIL_BITS != 0
59 else if (exp == 2 && MAXIMUM > GMP_NUMB_MAX)
60 {
61 fl = fp[fn-1];
62 if ((fl >> GMP_NAIL_BITS) != 0)
63 return 0;
64 fl = (fl << GMP_NUMB_BITS);
65 if (fn >= 2)
66 fl |= fp[fn-2];
67 }
68#endif
69 else
70 return 0;
71
72 return fl <= MAXIMUM;
73}