ba71ee0e70162948bd4dd74dc673b669aa6d7067
[dragonfly.git] / contrib / mpfr / src / get_uj.c
1 /* mpfr_get_uj -- convert a MPFR number to a huge machine unsigned integer
2
3 Copyright 2004, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4 Contributed by the Arenaire and Caramel projects, INRIA.
5
6 This file is part of the GNU MPFR Library.
7
8 The GNU MPFR Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
12
13 The GNU MPFR Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16 License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MPFR Library; see the file COPYING.LESSER.  If not, see
20 http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
21 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
22
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"       /* for a build within gmp */
25 #endif
26
27 #include "mpfr-intmax.h"
28 #include "mpfr-impl.h"
29
30 #ifdef _MPFR_H_HAVE_INTMAX_T
31
32 uintmax_t
33 mpfr_get_uj (mpfr_srcptr f, mpfr_rnd_t rnd)
34 {
35   uintmax_t r;
36   mpfr_prec_t prec;
37   mpfr_t x;
38
39   if (MPFR_UNLIKELY (!mpfr_fits_uintmax_p (f, rnd)))
40     {
41       MPFR_SET_ERANGE ();
42       return MPFR_IS_NAN (f) || MPFR_IS_NEG (f) ?
43         (uintmax_t) 0 : MPFR_UINTMAX_MAX;
44     }
45
46   if (MPFR_IS_ZERO (f))
47     return (uintmax_t) 0;
48
49   /* determine the precision of uintmax_t */
50   for (r = MPFR_UINTMAX_MAX, prec = 0; r != 0; r /= 2, prec++)
51     { }
52
53   /* Now, r = 0. */
54
55   mpfr_init2 (x, prec);
56   mpfr_rint (x, f, rnd);
57   MPFR_ASSERTN (MPFR_IS_FP (x));
58
59   if (MPFR_NOTZERO (x))
60     {
61       mp_limb_t *xp;
62       int sh, n;  /* An int should be sufficient in this context. */
63
64       MPFR_ASSERTN (MPFR_IS_POS (x));
65       xp = MPFR_MANT (x);
66       sh = MPFR_GET_EXP (x);
67       MPFR_ASSERTN ((mpfr_prec_t) sh <= prec);
68       for (n = MPFR_LIMB_SIZE(x) - 1; n >= 0; n--)
69         {
70           sh -= GMP_NUMB_BITS;
71           r += (sh >= 0
72                 ? (uintmax_t) xp[n] << sh
73                 : (uintmax_t) xp[n] >> (- sh));
74         }
75     }
76
77   mpfr_clear (x);
78
79   return r;
80 }
81
82 #endif