1 /* mpf_set_prec(x) -- Change the precision of x.
2 
3 Copyright 1993-1995, 2000, 2001 Free Software Foundation, Inc.
4 
5 This file is part of the GNU MP Library.
6 
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it 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 
14 or
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 
20 or both in parallel, as here.
21 
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
25 for more details.
26 
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library.  If not,
29 see https://www.gnu.org/licenses/.  */
30 
31 #include "gmp-impl.h"
32 
33 
34 /* A full new_prec+1 limbs are always retained, even though just new_prec
35    would satisfy the requested precision.  If size==new_prec+1 then
36    certainly new_prec+1 should be kept since no copying is needed in that
37    case.  If just new_prec was kept for size>new_prec+1 it'd be a bit
38    inconsistent.  */
39 
40 void
mpf_set_prec(mpf_ptr x,mp_bitcnt_t new_prec_in_bits)41 mpf_set_prec (mpf_ptr x, mp_bitcnt_t new_prec_in_bits)
42 {
43   mp_size_t  old_prec, new_prec, new_prec_plus1;
44   mp_size_t  size, sign;
45   mp_ptr     xp;
46 
47   new_prec = __GMPF_BITS_TO_PREC (new_prec_in_bits);
48   old_prec = PREC(x);
49 
50   /* do nothing if already the right precision */
51   if (new_prec == old_prec)
52     return;
53 
54   PREC(x) = new_prec;
55   new_prec_plus1 = new_prec + 1;
56 
57   /* retain most significant limbs */
58   sign = SIZ(x);
59   size = ABS (sign);
60   xp = PTR(x);
61   if (size > new_prec_plus1)
62     {
63       SIZ(x) = (sign >= 0 ? new_prec_plus1 : -new_prec_plus1);
64       MPN_COPY_INCR (xp, xp + size - new_prec_plus1, new_prec_plus1);
65     }
66 
67   PTR(x) = __GMP_REALLOCATE_FUNC_LIMBS (xp, old_prec+1, new_prec_plus1);
68 }
69