Merge branch 'vendor/MDOCML'
[dragonfly.git] / contrib / mpfr / set_si_2exp.c
1 /* mpfr_set_si_2exp -- set a MPFR number from a machine signed integer with
2    a shift
3
4 Copyright 2004, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5 Contributed by the Arenaire and Cacao projects, INRIA.
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 #define MPFR_NEED_LONGLONG_H
25 #include "mpfr-impl.h"
26
27 int
28 mpfr_set_si_2exp (mpfr_ptr x, long i, mp_exp_t e, mp_rnd_t rnd_mode)
29 {
30   if (i == 0)
31     {
32       MPFR_SET_ZERO (x);
33       MPFR_SET_POS (x);
34       MPFR_RET (0);
35     }
36   else
37     {
38       mp_size_t xn;
39       unsigned int cnt, nbits;
40       mp_limb_t ai, *xp;
41       int inex = 0;
42
43       /* FIXME: support int limbs (e.g. 16-bit limbs on 16-bit proc) */
44       ai = SAFE_ABS (unsigned long, i);
45       MPFR_ASSERTN (SAFE_ABS (unsigned long, i) == ai);
46
47       /* Position of the highest limb */
48       xn = (MPFR_PREC (x) - 1) / BITS_PER_MP_LIMB;
49       count_leading_zeros (cnt, ai);
50       MPFR_ASSERTD (cnt < BITS_PER_MP_LIMB);  /* OK since i != 0 */
51
52       xp = MPFR_MANT(x);
53       xp[xn] = ai << cnt;
54       /* Zero the xn lower limbs. */
55       MPN_ZERO(xp, xn);
56       MPFR_SET_SIGN (x, i < 0 ? MPFR_SIGN_NEG : MPFR_SIGN_POS);
57
58       nbits = BITS_PER_MP_LIMB - cnt;
59       e += nbits;  /* exponent _before_ the rounding */
60
61       /* round if MPFR_PREC(x) smaller than length of i */
62       if (MPFR_UNLIKELY (MPFR_PREC (x) < nbits) &&
63           MPFR_UNLIKELY (mpfr_round_raw (xp + xn, xp + xn, nbits, i < 0,
64                                          MPFR_PREC (x), rnd_mode, &inex)))
65         {
66           e++;
67           xp[xn] = MPFR_LIMB_HIGHBIT;
68         }
69
70       MPFR_CLEAR_FLAGS (x);
71       MPFR_EXP (x) = e;
72       return mpfr_check_range (x, inex, rnd_mode);
73     }
74 }