beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpq / md_2exp.c
bloba2a7e1e2fb723b5381d31c3a35c064149db3074d
1 /* mpq_mul_2exp, mpq_div_2exp - multiply or divide by 2^N */
3 /*
4 Copyright 2000, 2002, 2012 Free Software Foundation, Inc.
6 This file is part of the GNU MP Library.
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of either:
11 * the GNU Lesser General Public License as published by the Free
12 Software Foundation; either version 3 of the License, or (at your
13 option) any later version.
17 * the GNU General Public License as published by the Free Software
18 Foundation; either version 2 of the License, or (at your option) any
19 later version.
21 or both in parallel, as here.
23 The GNU MP Library is distributed in the hope that it will be useful, but
24 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
26 for more details.
28 You should have received copies of the GNU General Public License and the
29 GNU Lesser General Public License along with the GNU MP Library. If not,
30 see https://www.gnu.org/licenses/. */
32 #include "gmp.h"
33 #include "gmp-impl.h"
34 #include "longlong.h"
37 /* The multiplier/divisor "n", representing 2^n, is applied by right shifting
38 "r" until it's odd (if it isn't already), and left shifting "l" for the
39 rest. */
41 static void
42 mord_2exp (mpz_ptr ldst, mpz_ptr rdst, mpz_srcptr lsrc, mpz_srcptr rsrc,
43 mp_bitcnt_t n)
45 mp_size_t rsrc_size = SIZ(rsrc);
46 mp_size_t len = ABS (rsrc_size);
47 mp_ptr rsrc_ptr = PTR(rsrc);
48 mp_ptr p, rdst_ptr;
49 mp_limb_t plow;
51 p = rsrc_ptr;
52 plow = *p;
53 while (n >= GMP_NUMB_BITS && plow == 0)
55 n -= GMP_NUMB_BITS;
56 p++;
57 plow = *p;
60 /* no realloc here if rsrc==rdst, so p and rsrc_ptr remain valid */
61 len -= (p - rsrc_ptr);
62 rdst_ptr = MPZ_REALLOC (rdst, len);
64 if ((plow & 1) || n == 0)
66 /* need INCR when src==dst */
67 if (p != rdst_ptr)
68 MPN_COPY_INCR (rdst_ptr, p, len);
70 else
72 unsigned long shift;
73 if (plow == 0)
74 shift = n;
75 else
77 count_trailing_zeros (shift, plow);
78 shift = MIN (shift, n);
80 mpn_rshift (rdst_ptr, p, len, shift);
81 len -= (rdst_ptr[len-1] == 0);
82 n -= shift;
84 SIZ(rdst) = (rsrc_size >= 0) ? len : -len;
86 if (n)
87 mpz_mul_2exp (ldst, lsrc, n);
88 else if (ldst != lsrc)
89 mpz_set (ldst, lsrc);
93 void
94 mpq_mul_2exp (mpq_ptr dst, mpq_srcptr src, mp_bitcnt_t n)
96 mord_2exp (NUM(dst), DEN(dst), NUM(src), DEN(src), n);
99 void
100 mpq_div_2exp (mpq_ptr dst, mpq_srcptr src, mp_bitcnt_t n)
102 if (SIZ(NUM(src)) == 0)
104 SIZ(NUM(dst)) = 0;
105 SIZ(DEN(dst)) = 1;
106 PTR(DEN(dst))[0] = 1;
107 return;
110 mord_2exp (DEN(dst), NUM(dst), DEN(src), NUM(src), n);