Merge branch 'vendor/BINUTILS220' into bu220
[dragonfly.git] / contrib / mpfr / fits_s.h
1 /* mpfr_fits_*_p -- test whether an mpfr fits a C signed type.
2
3 Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4 Contributed by the Arenaire and Cacao projects, INRIA.
5 Copied from mpf/fits_s.h.
6
7 This file is part of the GNU MPFR Library.
8
9 The GNU MPFR Library is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1 of the License, or (at your
12 option) any later version.
13
14 The GNU MPFR Library is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17 License for more details.
18
19 You should have received a copy of the GNU Lesser General Public License
20 along with the GNU MPFR Library; see the file COPYING.LIB.  If not, write to
21 the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
22 MA 02110-1301, USA. */
23
24 #include "mpfr-impl.h"
25
26 int
27 FUNCTION (mpfr_srcptr f, mp_rnd_t rnd)
28 {
29   mp_exp_t exp;
30   mp_prec_t prec;
31   TYPE s;
32   mpfr_t x;
33   int neg;
34   int res;
35
36   if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (f)))
37     /* Zero always fit */
38     return MPFR_IS_ZERO (f) ? 1 : 0;
39
40   /* now it fits if either
41      (a) MINIMUM <= f <= MAXIMUM
42      (b) or MINIMUM <= round(f, prec(slong), rnd) <= MAXIMUM */
43
44   exp = MPFR_GET_EXP (f);
45   if (exp < 1)
46     return 1; /* |f| < 1: always fits */
47
48   neg = MPFR_IS_NEG (f);
49
50   /* let EXTREMUM be MAXIMUM if f > 0, and MINIMUM if f < 0 */
51
52   /* first compute prec(EXTREMUM), this could be done at configure time */
53   s = (neg) ? MINIMUM : MAXIMUM;
54   for (prec = 0; s != 0; s /= 2, prec ++);
55
56   /* EXTREMUM needs prec bits, i.e. 2^(prec-1) <= |EXTREMUM| < 2^prec */
57
58    /* if exp < prec - 1, then f < 2^(prec-1) < |EXTREMUM| */
59   if ((mpfr_prec_t) exp < prec - 1)
60     return 1;
61
62   /* if exp > prec + 1, then f >= 2^prec > EXTREMUM */
63   if ((mpfr_prec_t) exp > prec + 1)
64     return 0;
65
66   /* remains cases exp = prec-1 to prec+1 */
67
68   /* hard case: first round to prec bits, then check */
69   mpfr_init2 (x, prec);
70   mpfr_set (x, f, rnd);
71   res = (neg) ? (mpfr_cmp_si (x, MINIMUM) >= 0)
72     : (mpfr_cmp_si (x, MAXIMUM) <= 0);
73   mpfr_clear (x);
74
75   return res;
76 }
77