112437Speter/* mpz_realloc2 -- change allocated data size.
212437Speter
312437SpeterCopyright 2001, 2002, 2008, 2015 Free Software Foundation, Inc.
412437Speter
512437SpeterThis file is part of the GNU MP Library.
612437Speter
712437SpeterThe GNU MP Library is free software; you can redistribute it and/or modify
812437Speterit under the terms of either:
912437Speter
1012437Speter  * the GNU Lesser General Public License as published by the Free
1112437Speter    Software Foundation; either version 3 of the License, or (at your
1212437Speter    option) any later version.
1312437Speter
1412437Speteror
1512437Speter
1612437Speter  * the GNU General Public License as published by the Free Software
1712437Speter    Foundation; either version 2 of the License, or (at your option) any
1812437Speter    later version.
1912437Speter
2012437Speteror both in parallel, as here.
2112437Speter
2212437SpeterThe GNU MP Library is distributed in the hope that it will be useful, but
2312437SpeterWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
2412437Speteror FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
2512437Speterfor more details.
2612437Speter
2712437SpeterYou should have received copies of the GNU General Public License and the
2812437SpeterGNU Lesser General Public License along with the GNU MP Library.  If not,
2912437Spetersee https://www.gnu.org/licenses/.  */
3012437Speter
3112437Speter#include <stdlib.h>
3219235Sjhay#include <stdio.h>
3312437Speter#include "gmp-impl.h"
3412437Speter
3512437Spetervoid
3612437Spetermpz_realloc2 (mpz_ptr m, mp_bitcnt_t bits)
3712437Speter{
3812437Speter  mp_size_t new_alloc;
3912437Speter
4012437Speter  bits -= (bits != 0);		/* Round down, except if 0 */
4112437Speter  new_alloc = 1 + bits / GMP_NUMB_BITS;
4212437Speter
4312437Speter  if (sizeof (unsigned long) > sizeof (int)) /* param vs _mp_size field */
4412437Speter    {
4512437Speter      if (UNLIKELY (new_alloc > INT_MAX))
4612437Speter	{
4712437Speter	  fprintf (stderr, "gmp: overflow in mpz type\n");
4812437Speter	  abort ();
4912437Speter	}
5012437Speter    }
5112437Speter
5212437Speter  if (ALLOC (m) == 0)
5312437Speter    {
5412437Speter      PTR (m) = __GMP_ALLOCATE_FUNC_LIMBS (new_alloc);
5512437Speter    }
5612437Speter  else
5712437Speter    {
5812437Speter      PTR (m) = __GMP_REALLOCATE_FUNC_LIMBS (PTR(m), ALLOC(m), new_alloc);
5912437Speter
6012437Speter      /* Don't create an invalid number; if the current value doesn't fit after
6112437Speter	 reallocation, clear it to 0.  */
6212437Speter      if (ABSIZ(m) > new_alloc)
6312437Speter	SIZ(m) = 0;
6412437Speter    }
6512437Speter
6612437Speter  ALLOC(m) = new_alloc;
6712437Speter}
6812437Speter